blob_cache.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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.v7/internal"
  15. "gopkg.in/src-d/hercules.v7/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{}) error {
  121. if val, exists := facts[ConfigBlobCacheFailOnMissingSubmodules].(bool); exists {
  122. blobCache.FailOnMissingSubmodules = val
  123. }
  124. return nil
  125. }
  126. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  127. // calls. The repository which is going to be analysed is supplied as an argument.
  128. func (blobCache *BlobCache) Initialize(repository *git.Repository) error {
  129. blobCache.repository = repository
  130. blobCache.cache = map[plumbing.Hash]*CachedBlob{}
  131. return nil
  132. }
  133. // Consume runs this PipelineItem on the next commit data.
  134. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  135. // Additionally, DependencyCommit is always present there and represents
  136. // the analysed *object.Commit. This function returns the mapping with analysis
  137. // results. The keys must be the same as in Provides(). If there was an error,
  138. // nil is returned.
  139. func (blobCache *BlobCache) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  140. commit := deps[core.DependencyCommit].(*object.Commit)
  141. changes := deps[DependencyTreeChanges].(object.Changes)
  142. cache := map[plumbing.Hash]*CachedBlob{}
  143. newCache := map[plumbing.Hash]*CachedBlob{}
  144. for _, change := range changes {
  145. action, err := change.Action()
  146. if err != nil {
  147. log.Printf("no action in %s\n", change.To.TreeEntry.Hash)
  148. return nil, err
  149. }
  150. var exists bool
  151. var blob *object.Blob
  152. switch action {
  153. case merkletrie.Insert:
  154. cache[change.To.TreeEntry.Hash] = &CachedBlob{}
  155. newCache[change.To.TreeEntry.Hash] = &CachedBlob{}
  156. blob, err = blobCache.getBlob(&change.To, commit.File)
  157. if err != nil {
  158. log.Printf("file to %s %s: %v\n", change.To.Name, change.To.TreeEntry.Hash, err)
  159. } else {
  160. cb := &CachedBlob{Blob: *blob}
  161. err = cb.Cache()
  162. if err == nil {
  163. cache[change.To.TreeEntry.Hash] = cb
  164. newCache[change.To.TreeEntry.Hash] = cb
  165. } else {
  166. log.Printf("file to %s %s: %v\n", change.To.Name, change.To.TreeEntry.Hash, err)
  167. }
  168. }
  169. case merkletrie.Delete:
  170. cache[change.From.TreeEntry.Hash], exists =
  171. blobCache.cache[change.From.TreeEntry.Hash]
  172. if !exists {
  173. cache[change.From.TreeEntry.Hash] = &CachedBlob{}
  174. blob, err = blobCache.getBlob(&change.From, commit.File)
  175. if err != nil {
  176. if err.Error() != plumbing.ErrObjectNotFound.Error() {
  177. log.Printf("file from %s %s: %v\n", change.From.Name,
  178. change.From.TreeEntry.Hash, err)
  179. } else {
  180. blob, err = internal.CreateDummyBlob(change.From.TreeEntry.Hash)
  181. cache[change.From.TreeEntry.Hash] = &CachedBlob{Blob: *blob}
  182. }
  183. } else {
  184. cb := &CachedBlob{Blob: *blob}
  185. err = cb.Cache()
  186. if err == nil {
  187. cache[change.From.TreeEntry.Hash] = cb
  188. } else {
  189. log.Printf("file from %s %s: %v\n", change.From.Name,
  190. change.From.TreeEntry.Hash, err)
  191. }
  192. }
  193. }
  194. case merkletrie.Modify:
  195. blob, err = blobCache.getBlob(&change.To, commit.File)
  196. cache[change.To.TreeEntry.Hash] = &CachedBlob{}
  197. newCache[change.To.TreeEntry.Hash] = &CachedBlob{}
  198. if err != nil {
  199. log.Printf("file to %s: %v\n", change.To.Name, err)
  200. } else {
  201. cb := &CachedBlob{Blob: *blob}
  202. err = cb.Cache()
  203. if err == nil {
  204. cache[change.To.TreeEntry.Hash] = cb
  205. newCache[change.To.TreeEntry.Hash] = cb
  206. } else {
  207. log.Printf("file to %s: %v\n", change.To.Name, err)
  208. }
  209. }
  210. cache[change.From.TreeEntry.Hash], exists =
  211. blobCache.cache[change.From.TreeEntry.Hash]
  212. if !exists {
  213. cache[change.From.TreeEntry.Hash] = &CachedBlob{}
  214. blob, err = blobCache.getBlob(&change.From, commit.File)
  215. if err != nil {
  216. log.Printf("file from %s: %v\n", change.From.Name, err)
  217. } else {
  218. cb := &CachedBlob{Blob: *blob}
  219. err = cb.Cache()
  220. if err == nil {
  221. cache[change.From.TreeEntry.Hash] = cb
  222. } else {
  223. log.Printf("file from %s: %v\n", change.From.Name, err)
  224. }
  225. }
  226. }
  227. }
  228. if err != nil {
  229. return nil, err
  230. }
  231. }
  232. blobCache.cache = newCache
  233. return map[string]interface{}{DependencyBlobCache: cache}, nil
  234. }
  235. // Fork clones this PipelineItem.
  236. func (blobCache *BlobCache) Fork(n int) []core.PipelineItem {
  237. caches := make([]core.PipelineItem, n)
  238. for i := 0; i < n; i++ {
  239. cache := map[plumbing.Hash]*CachedBlob{}
  240. for k, v := range blobCache.cache {
  241. cache[k] = v
  242. }
  243. caches[i] = &BlobCache{
  244. FailOnMissingSubmodules: blobCache.FailOnMissingSubmodules,
  245. repository: blobCache.repository,
  246. cache: cache,
  247. }
  248. }
  249. return caches
  250. }
  251. // FileGetter defines a function which loads the Git file by
  252. // the specified path. The state can be arbitrary though here it always
  253. // corresponds to the currently processed commit.
  254. type FileGetter func(path string) (*object.File, error)
  255. // Returns the blob which corresponds to the specified ChangeEntry.
  256. func (blobCache *BlobCache) getBlob(entry *object.ChangeEntry, fileGetter FileGetter) (
  257. *object.Blob, error) {
  258. blob, err := blobCache.repository.BlobObject(entry.TreeEntry.Hash)
  259. if err != nil {
  260. if err.Error() != plumbing.ErrObjectNotFound.Error() {
  261. log.Printf("getBlob(%s)\n", entry.TreeEntry.Hash.String())
  262. return nil, err
  263. }
  264. if entry.TreeEntry.Mode != 0160000 {
  265. // this is not a submodule
  266. return nil, err
  267. } else if !blobCache.FailOnMissingSubmodules {
  268. return internal.CreateDummyBlob(entry.TreeEntry.Hash)
  269. }
  270. file, errModules := fileGetter(".gitmodules")
  271. if errModules != nil {
  272. return nil, errModules
  273. }
  274. contents, errModules := file.Contents()
  275. if errModules != nil {
  276. return nil, errModules
  277. }
  278. modules := config.NewModules()
  279. errModules = modules.Unmarshal([]byte(contents))
  280. if errModules != nil {
  281. return nil, errModules
  282. }
  283. _, exists := modules.Submodules[entry.Name]
  284. if exists {
  285. // we found that this is a submodule
  286. return internal.CreateDummyBlob(entry.TreeEntry.Hash)
  287. }
  288. return nil, err
  289. }
  290. return blob, nil
  291. }
  292. func init() {
  293. core.Registry.Register(&BlobCache{})
  294. }