You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.1 KiB

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