blob_cache.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package plumbing
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "github.com/pkg/errors"
  9. "gopkg.in/src-d/go-git.v4"
  10. "gopkg.in/src-d/go-git.v4/config"
  11. "gopkg.in/src-d/go-git.v4/plumbing"
  12. "gopkg.in/src-d/go-git.v4/plumbing/object"
  13. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  14. "gopkg.in/src-d/hercules.v5/internal"
  15. "gopkg.in/src-d/hercules.v5/internal/core"
  16. )
  17. // ErrorBinary is raised in CachedBlob.CountLines() if the file is binary.
  18. var ErrorBinary = errors.New("binary")
  19. // CachedBlob allows to explicitly cache the binary data associated with the Blob object.
  20. type CachedBlob struct {
  21. object.Blob
  22. // Data is the read contents of the blob object.
  23. Data []byte
  24. }
  25. // Reader returns a reader allow the access to the content of the blob
  26. func (b *CachedBlob) Reader() (io.ReadCloser, error) {
  27. return ioutil.NopCloser(bytes.NewReader(b.Data)), nil
  28. }
  29. // Cache reads the underlying blob object and sets CachedBlob.Data.
  30. func (b *CachedBlob) Cache() error {
  31. reader, err := b.Blob.Reader()
  32. if err != nil {
  33. return err
  34. }
  35. defer reader.Close()
  36. buf := new(bytes.Buffer)
  37. buf.Grow(int(b.Size))
  38. size, err := buf.ReadFrom(reader)
  39. if err != nil {
  40. return err
  41. }
  42. if size != b.Size {
  43. return fmt.Errorf("incomplete read of %s: %d while the declared size is %d",
  44. b.Hash.String(), size, b.Size)
  45. }
  46. b.Data = buf.Bytes()
  47. return nil
  48. }
  49. // CountLines returns the number of lines in the blob or (0, ErrorBinary) if it is binary.
  50. func (b *CachedBlob) CountLines() (int, error) {
  51. if len(b.Data) == 0 {
  52. return 0, nil
  53. }
  54. // 8000 was taken from go-git's utils/binary.IsBinary()
  55. sniffLen := 8000
  56. sniff := b.Data
  57. if len(sniff) > sniffLen {
  58. sniff = sniff[:sniffLen]
  59. }
  60. if bytes.IndexByte(sniff, 0) >= 0 {
  61. return 0, ErrorBinary
  62. }
  63. lines := bytes.Count(b.Data, []byte{'\n'})
  64. if b.Data[len(b.Data)-1] != '\n' {
  65. lines++
  66. }
  67. return lines, nil
  68. }
  69. // BlobCache loads the blobs which correspond to the changed files in a commit.
  70. // It is a PipelineItem.
  71. // It must provide the old and the new objects; "blobCache" rotates and allows to not load
  72. // the same blobs twice. Outdated objects are removed so "blobCache" never grows big.
  73. type BlobCache struct {
  74. core.NoopMerger
  75. // Specifies how to handle the situation when we encounter a git submodule - an object
  76. // without the blob. If true, we look inside .gitmodules and if we don't find it,
  77. // raise an error. If false, we do not look inside .gitmodules and always succeed.
  78. FailOnMissingSubmodules bool
  79. repository *git.Repository
  80. cache map[plumbing.Hash]*CachedBlob
  81. }
  82. const (
  83. // ConfigBlobCacheFailOnMissingSubmodules is the name of the configuration option for
  84. // BlobCache.Configure() to check if the referenced submodules are registered in .gitignore.
  85. ConfigBlobCacheFailOnMissingSubmodules = "BlobCache.FailOnMissingSubmodules"
  86. // DependencyBlobCache identifies the dependency provided by BlobCache.
  87. DependencyBlobCache = "blob_cache"
  88. )
  89. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  90. func (blobCache *BlobCache) Name() string {
  91. return "BlobCache"
  92. }
  93. // Provides returns the list of names of entities which are produced by this PipelineItem.
  94. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  95. // to this list. Also used by core.Registry to build the global map of providers.
  96. func (blobCache *BlobCache) Provides() []string {
  97. arr := [...]string{DependencyBlobCache}
  98. return arr[:]
  99. }
  100. // Requires returns the list of names of entities which are needed by this PipelineItem.
  101. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  102. // entities are Provides() upstream.
  103. func (blobCache *BlobCache) Requires() []string {
  104. arr := [...]string{DependencyTreeChanges}
  105. return arr[:]
  106. }
  107. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  108. func (blobCache *BlobCache) ListConfigurationOptions() []core.ConfigurationOption {
  109. options := [...]core.ConfigurationOption{{
  110. Name: ConfigBlobCacheFailOnMissingSubmodules,
  111. Description: "Specifies whether to panic if any referenced submodule does " +
  112. "not exist in .gitmodules and thus the corresponding Git object cannot be loaded. " +
  113. "Override this if you want to ensure that your repository is integral. ",
  114. Flag: "fail-on-missing-submodules",
  115. Type: core.BoolConfigurationOption,
  116. Default: false}}
  117. return options[:]
  118. }
  119. // Configure sets the properties previously published by ListConfigurationOptions().
  120. func (blobCache *BlobCache) Configure(facts map[string]interface{}) {
  121. if val, exists := facts[ConfigBlobCacheFailOnMissingSubmodules].(bool); exists {
  122. blobCache.FailOnMissingSubmodules = val
  123. }
  124. }
  125. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  126. // calls. The repository which is going to be analysed is supplied as an argument.
  127. func (blobCache *BlobCache) Initialize(repository *git.Repository) {
  128. blobCache.repository = repository
  129. blobCache.cache = map[plumbing.Hash]*CachedBlob{}
  130. }
  131. // Consume runs this PipelineItem on the next commit data.
  132. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  133. // Additionally, DependencyCommit is always present there and represents
  134. // the analysed *object.Commit. This function returns the mapping with analysis
  135. // results. The keys must be the same as in Provides(). If there was an error,
  136. // nil is returned.
  137. func (blobCache *BlobCache) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  138. commit := deps[core.DependencyCommit].(*object.Commit)
  139. changes := deps[DependencyTreeChanges].(object.Changes)
  140. cache := map[plumbing.Hash]*CachedBlob{}
  141. newCache := map[plumbing.Hash]*CachedBlob{}
  142. for _, change := range changes {
  143. action, err := change.Action()
  144. if err != nil {
  145. log.Printf("no action in %s\n", change.To.TreeEntry.Hash)
  146. return nil, err
  147. }
  148. var exists bool
  149. var blob *object.Blob
  150. switch action {
  151. case merkletrie.Insert:
  152. cache[change.To.TreeEntry.Hash] = &CachedBlob{}
  153. newCache[change.To.TreeEntry.Hash] = &CachedBlob{}
  154. blob, err = blobCache.getBlob(&change.To, commit.File)
  155. if err != nil {
  156. log.Printf("file to %s %s: %v\n", change.To.Name, change.To.TreeEntry.Hash, err)
  157. } else {
  158. cb := &CachedBlob{Blob: *blob}
  159. err = cb.Cache()
  160. if err == nil {
  161. cache[change.To.TreeEntry.Hash] = cb
  162. newCache[change.To.TreeEntry.Hash] = cb
  163. } else {
  164. log.Printf("file to %s %s: %v\n", change.To.Name, change.To.TreeEntry.Hash, err)
  165. }
  166. }
  167. case merkletrie.Delete:
  168. cache[change.From.TreeEntry.Hash], exists =
  169. blobCache.cache[change.From.TreeEntry.Hash]
  170. if !exists {
  171. cache[change.From.TreeEntry.Hash] = &CachedBlob{}
  172. blob, err = blobCache.getBlob(&change.From, commit.File)
  173. if err != nil {
  174. if err.Error() != plumbing.ErrObjectNotFound.Error() {
  175. log.Printf("file from %s %s: %v\n", change.From.Name,
  176. change.From.TreeEntry.Hash, err)
  177. } else {
  178. blob, err = internal.CreateDummyBlob(change.From.TreeEntry.Hash)
  179. cache[change.From.TreeEntry.Hash] = &CachedBlob{Blob: *blob}
  180. }
  181. } else {
  182. cb := &CachedBlob{Blob: *blob}
  183. err = cb.Cache()
  184. if err == nil {
  185. cache[change.From.TreeEntry.Hash] = cb
  186. } else {
  187. log.Printf("file from %s %s: %v\n", change.From.Name,
  188. change.From.TreeEntry.Hash, err)
  189. }
  190. }
  191. }
  192. case merkletrie.Modify:
  193. blob, err = blobCache.getBlob(&change.To, commit.File)
  194. cache[change.To.TreeEntry.Hash] = &CachedBlob{}
  195. newCache[change.To.TreeEntry.Hash] = &CachedBlob{}
  196. if err != nil {
  197. log.Printf("file to %s: %v\n", change.To.Name, err)
  198. } else {
  199. cb := &CachedBlob{Blob: *blob}
  200. err = cb.Cache()
  201. if err == nil {
  202. cache[change.To.TreeEntry.Hash] = cb
  203. newCache[change.To.TreeEntry.Hash] = cb
  204. } else {
  205. log.Printf("file to %s: %v\n", change.To.Name, err)
  206. }
  207. }
  208. cache[change.From.TreeEntry.Hash], exists =
  209. blobCache.cache[change.From.TreeEntry.Hash]
  210. if !exists {
  211. cache[change.From.TreeEntry.Hash] = &CachedBlob{}
  212. blob, err = blobCache.getBlob(&change.From, commit.File)
  213. if err != nil {
  214. log.Printf("file from %s: %v\n", change.From.Name, err)
  215. } else {
  216. cb := &CachedBlob{Blob: *blob}
  217. err = cb.Cache()
  218. if err == nil {
  219. cache[change.From.TreeEntry.Hash] = cb
  220. } else {
  221. log.Printf("file from %s: %v\n", change.From.Name, err)
  222. }
  223. }
  224. }
  225. }
  226. if err != nil {
  227. return nil, err
  228. }
  229. }
  230. blobCache.cache = newCache
  231. return map[string]interface{}{DependencyBlobCache: cache}, nil
  232. }
  233. // Fork clones this PipelineItem.
  234. func (blobCache *BlobCache) Fork(n int) []core.PipelineItem {
  235. caches := make([]core.PipelineItem, n)
  236. for i := 0; i < n; i++ {
  237. cache := map[plumbing.Hash]*CachedBlob{}
  238. for k, v := range blobCache.cache {
  239. cache[k] = v
  240. }
  241. caches[i] = &BlobCache{
  242. FailOnMissingSubmodules: blobCache.FailOnMissingSubmodules,
  243. repository: blobCache.repository,
  244. cache: cache,
  245. }
  246. }
  247. return caches
  248. }
  249. // FileGetter defines a function which loads the Git file by
  250. // the specified path. The state can be arbitrary though here it always
  251. // corresponds to the currently processed commit.
  252. type FileGetter func(path string) (*object.File, error)
  253. // Returns the blob which corresponds to the specified ChangeEntry.
  254. func (blobCache *BlobCache) getBlob(entry *object.ChangeEntry, fileGetter FileGetter) (
  255. *object.Blob, error) {
  256. blob, err := blobCache.repository.BlobObject(entry.TreeEntry.Hash)
  257. if err != nil {
  258. if err.Error() != plumbing.ErrObjectNotFound.Error() {
  259. log.Printf("getBlob(%s)\n", entry.TreeEntry.Hash.String())
  260. return nil, err
  261. }
  262. if entry.TreeEntry.Mode != 0160000 {
  263. // this is not a submodule
  264. return nil, err
  265. } else if !blobCache.FailOnMissingSubmodules {
  266. return internal.CreateDummyBlob(entry.TreeEntry.Hash)
  267. }
  268. file, errModules := fileGetter(".gitmodules")
  269. if errModules != nil {
  270. return nil, errModules
  271. }
  272. contents, errModules := file.Contents()
  273. if errModules != nil {
  274. return nil, errModules
  275. }
  276. modules := config.NewModules()
  277. errModules = modules.Unmarshal([]byte(contents))
  278. if errModules != nil {
  279. return nil, errModules
  280. }
  281. _, exists := modules.Submodules[entry.Name]
  282. if exists {
  283. // we found that this is a submodule
  284. return internal.CreateDummyBlob(entry.TreeEntry.Hash)
  285. }
  286. return nil, err
  287. }
  288. return blob, nil
  289. }
  290. func init() {
  291. core.Registry.Register(&BlobCache{})
  292. }