1// Copyright 2015 The Gogs Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
3
4package git
5
6import (
7 "crypto/sha1"
8 "encoding/hex"
9 "fmt"
10 "os"
11 "strconv"
12 "strings"
13 "sync"
14)
15
16// ObjectCache provides thread-safe cache operations.
17type ObjectCache struct {
18 lock sync.RWMutex
19 cache map[string]any
20}
21
22func newObjectCache() *ObjectCache {
23 return &ObjectCache{
24 cache: make(map[string]any, 10),
25 }
26}
27
28// Set add obj to cache
29func (oc *ObjectCache) Set(id string, obj any) {
30 oc.lock.Lock()
31 defer oc.lock.Unlock()
32
33 oc.cache[id] = obj
34}
35
36// Get get cached obj by id
37func (oc *ObjectCache) Get(id string) (any, bool) {
38 oc.lock.RLock()
39 defer oc.lock.RUnlock()
40
41 obj, has := oc.cache[id]
42 return obj, has
43}
44
45// isDir returns true if given path is a directory,
46// or returns false when it's a file or does not exist.
47func isDir(dir string) bool {
48 f, e := os.Stat(dir)
49 if e != nil {
50 return false
51 }
52 return f.IsDir()
53}
54
55// isFile returns true if given path is a file,
56// or returns false when it's a directory or does not exist.
57func isFile(filePath string) bool {
58 f, e := os.Stat(filePath)
59 if e != nil {
60 return false
61 }
62 return !f.IsDir()
63}
64
65// isExist checks whether a file or directory exists.
66// It returns false when the file or directory does not exist.
67func isExist(path string) bool {
68 _, err := os.Stat(path)
69 return err == nil || os.IsExist(err)
70}
71
72// ConcatenateError concatenats an error with stderr string
73func ConcatenateError(err error, stderr string) error {
74 if len(stderr) == 0 {
75 return err
76 }
77 return fmt.Errorf("%w - %s", err, stderr)
78}
79
80// ParseBool returns the boolean value represented by the string as per git's git_config_bool
81// true will be returned for the result if the string is empty, but valid will be false.
82// "true", "yes", "on" are all true, true
83// "false", "no", "off" are all false, true
84// 0 is false, true
85// Any other integer is true, true
86// Anything else will return false, false
87func ParseBool(value string) (result, valid bool) {
88 // Empty strings are true but invalid
89 if len(value) == 0 {
90 return true, false
91 }
92 // These are the git expected true and false values
93 if strings.EqualFold(value, "true") || strings.EqualFold(value, "yes") || strings.EqualFold(value, "on") {
94 return true, true
95 }
96 if strings.EqualFold(value, "false") || strings.EqualFold(value, "no") || strings.EqualFold(value, "off") {
97 return false, true
98 }
99 // Try a number
100 intValue, err := strconv.ParseInt(value, 10, 32)
101 if err != nil {
102 return false, false
103 }
104 return intValue != 0, true
105}
106
107func HashFilePathForWebUI(s string) string {
108 h := sha1.New()
109 _, _ = h.Write([]byte(s))
110 return hex.EncodeToString(h.Sum(nil))
111}