utils.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package git
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "sync"
  8. )
  9. // objectCache provides thread-safe cache opeations.
  10. type objectCache struct {
  11. lock sync.RWMutex
  12. cache map[string]interface{}
  13. }
  14. func newObjectCache() *objectCache {
  15. return &objectCache{
  16. cache: make(map[string]interface{}, 10),
  17. }
  18. }
  19. func (oc *objectCache) Set(id string, obj interface{}) {
  20. oc.lock.Lock()
  21. defer oc.lock.Unlock()
  22. oc.cache[id] = obj
  23. }
  24. func (oc *objectCache) Get(id string) (interface{}, bool) {
  25. oc.lock.RLock()
  26. defer oc.lock.RUnlock()
  27. obj, has := oc.cache[id]
  28. return obj, has
  29. }
  30. // isDir returns true if given path is a directory,
  31. // or returns false when it's a file or does not exist.
  32. func isDir(dir string) bool {
  33. f, e := os.Stat(dir)
  34. if e != nil {
  35. return false
  36. }
  37. return f.IsDir()
  38. }
  39. // isFile returns true if given path is a file,
  40. // or returns false when it's a directory or does not exist.
  41. func isFile(filePath string) bool {
  42. f, e := os.Stat(filePath)
  43. if e != nil {
  44. return false
  45. }
  46. return !f.IsDir()
  47. }
  48. // isExist checks whether a file or directory exists.
  49. // It returns false when the file or directory does not exist.
  50. func isExist(path string) bool {
  51. _, err := os.Stat(path)
  52. return err == nil || os.IsExist(err)
  53. }
  54. func concatenateError(err error, stderr string) error {
  55. if len(stderr) == 0 {
  56. return err
  57. }
  58. return fmt.Errorf("%v - %s", err, stderr)
  59. }
  60. // If the object is stored in its own file (i.e not in a pack file),
  61. // this function returns the full path to the object file.
  62. // It does not test if the file exists.
  63. func filepathFromSHA1(rootdir, sha1 string) string {
  64. return filepath.Join(rootdir, "objects", sha1[:2], sha1[2:])
  65. }
  66. func RefEndName(refStr string) string {
  67. if strings.HasPrefix(refStr, BRANCH_PREFIX) {
  68. return refStr[len(BRANCH_PREFIX):]
  69. }
  70. if strings.HasPrefix(refStr, TAG_PREFIX) {
  71. return refStr[len(TAG_PREFIX):]
  72. }
  73. return refStr
  74. }