blob_cache.go 9.9 KB

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