blob_cache.go 11 KB

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