tree_diff.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. package plumbing
  2. import (
  3. "fmt"
  4. "gopkg.in/src-d/enry.v1"
  5. "io"
  6. "log"
  7. "strings"
  8. "gopkg.in/src-d/go-git.v4"
  9. "gopkg.in/src-d/go-git.v4/plumbing/object"
  10. "gopkg.in/src-d/hercules.v4/internal/core"
  11. "gopkg.in/src-d/go-git.v4/plumbing"
  12. )
  13. // TreeDiff generates the list of changes for a commit. A change can be either one or two blobs
  14. // under the same path: "before" and "after". If "before" is nil, the change is an addition.
  15. // If "after" is nil, the change is a removal. Otherwise, it is a modification.
  16. // TreeDiff is a PipelineItem.
  17. type TreeDiff struct {
  18. core.NoopMerger
  19. SkipDirs []string
  20. Languages map[string]bool
  21. previousTree *object.Tree
  22. previousCommit plumbing.Hash
  23. repository *git.Repository
  24. }
  25. const (
  26. // DependencyTreeChanges is the name of the dependency provided by TreeDiff.
  27. DependencyTreeChanges = "changes"
  28. // ConfigTreeDiffEnableBlacklist is the name of the configuration option
  29. // (TreeDiff.Configure()) which allows to skip blacklisted directories.
  30. ConfigTreeDiffEnableBlacklist = "TreeDiff.EnableBlacklist"
  31. // ConfigTreeDiffBlacklistedPrefixes s the name of the configuration option
  32. // (TreeDiff.Configure()) which allows to set blacklisted path prefixes -
  33. // directories or complete file names.
  34. ConfigTreeDiffBlacklistedPrefixes = "TreeDiff.BlacklistedPrefixes"
  35. // ConfigTreeDiffLanguages is the name of the configuration option (TreeDiff.Configure())
  36. // which sets the list of programming languages to analyze. Language names are at
  37. // https://doc.bblf.sh/languages.html Names are joined with a comma ",".
  38. // "all" is the special name which disables this filter.
  39. ConfigTreeDiffLanguages = "TreeDiff.Languages"
  40. // allLanguages denotes passing all files in.
  41. allLanguages = "all"
  42. )
  43. // defaultBlacklistedPrefixes is the list of file path prefixes which should be skipped by default.
  44. var defaultBlacklistedPrefixes = []string{
  45. "vendor/",
  46. "vendors/",
  47. "node_modules/",
  48. "package-lock.json",
  49. }
  50. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  51. func (treediff *TreeDiff) Name() string {
  52. return "TreeDiff"
  53. }
  54. // Provides returns the list of names of entities which are produced by this PipelineItem.
  55. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  56. // to this list. Also used by core.Registry to build the global map of providers.
  57. func (treediff *TreeDiff) Provides() []string {
  58. arr := [...]string{DependencyTreeChanges}
  59. return arr[:]
  60. }
  61. // Requires returns the list of names of entities which are needed by this PipelineItem.
  62. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  63. // entities are Provides() upstream.
  64. func (treediff *TreeDiff) Requires() []string {
  65. return []string{}
  66. }
  67. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  68. func (treediff *TreeDiff) ListConfigurationOptions() []core.ConfigurationOption {
  69. options := [...]core.ConfigurationOption{{
  70. Name: ConfigTreeDiffEnableBlacklist,
  71. Description: "Skip blacklisted directories.",
  72. Flag: "skip-blacklist",
  73. Type: core.BoolConfigurationOption,
  74. Default: false}, {
  75. Name: ConfigTreeDiffBlacklistedPrefixes,
  76. Description: "List of blacklisted path prefixes (e.g. directories or specific files). " +
  77. "Values are in the UNIX format (\"path/to/x\"). Values should *not* start with \"/\". " +
  78. "Separated with commas \",\".",
  79. Flag: "blacklisted-prefixes",
  80. Type: core.StringsConfigurationOption,
  81. Default: defaultBlacklistedPrefixes}, {
  82. Name: ConfigTreeDiffLanguages,
  83. Description: fmt.Sprintf(
  84. "List of programming languages to analyze. Separated by comma \",\". " +
  85. "Names are at https://doc.bblf.sh/languages.html \"%s\" is the special name " +
  86. "which disables this filter and lets all the files through.", allLanguages),
  87. Flag: "languages",
  88. Type: core.StringsConfigurationOption,
  89. Default: []string{allLanguages}},
  90. }
  91. return options[:]
  92. }
  93. // Configure sets the properties previously published by ListConfigurationOptions().
  94. func (treediff *TreeDiff) Configure(facts map[string]interface{}) {
  95. if val, exist := facts[ConfigTreeDiffEnableBlacklist]; exist && val.(bool) {
  96. treediff.SkipDirs = facts[ConfigTreeDiffBlacklistedPrefixes].([]string)
  97. }
  98. if val, exists := facts[ConfigTreeDiffLanguages].(string); exists {
  99. treediff.Languages = map[string]bool{}
  100. for _, lang := range strings.Split(val, ",") {
  101. treediff.Languages[strings.TrimSpace(lang)] = true
  102. }
  103. } else if treediff.Languages == nil {
  104. treediff.Languages = map[string]bool{}
  105. treediff.Languages[allLanguages] = true
  106. }
  107. }
  108. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  109. // calls. The repository which is going to be analysed is supplied as an argument.
  110. func (treediff *TreeDiff) Initialize(repository *git.Repository) {
  111. treediff.previousTree = nil
  112. treediff.repository = repository
  113. if treediff.Languages == nil {
  114. treediff.Languages = map[string]bool{}
  115. treediff.Languages[allLanguages] = true
  116. }
  117. }
  118. // Consume runs this PipelineItem on the next commit data.
  119. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  120. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  121. // This function returns the mapping with analysis results. The keys must be the same as
  122. // in Provides(). If there was an error, nil is returned.
  123. func (treediff *TreeDiff) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  124. commit := deps[core.DependencyCommit].(*object.Commit)
  125. pass := false
  126. for _, hash := range commit.ParentHashes {
  127. if hash == treediff.previousCommit {
  128. pass = true
  129. }
  130. }
  131. if !pass && treediff.previousCommit != plumbing.ZeroHash {
  132. log.Panicf("%s > %s", treediff.previousCommit.String(), commit.Hash.String())
  133. }
  134. tree, err := commit.Tree()
  135. if err != nil {
  136. return nil, err
  137. }
  138. var diff object.Changes
  139. if treediff.previousTree != nil {
  140. diff, err = object.DiffTree(treediff.previousTree, tree)
  141. if err != nil {
  142. return nil, err
  143. }
  144. } else {
  145. diff = []*object.Change{}
  146. err = func() error {
  147. fileIter := tree.Files()
  148. defer fileIter.Close()
  149. for {
  150. file, err := fileIter.Next()
  151. if err != nil {
  152. if err == io.EOF {
  153. break
  154. }
  155. return err
  156. }
  157. pass, err := treediff.checkLanguage(file.Name, file.Hash)
  158. if err != nil {
  159. return err
  160. }
  161. if !pass {
  162. continue
  163. }
  164. diff = append(diff, &object.Change{
  165. To: object.ChangeEntry{Name: file.Name, Tree: tree, TreeEntry: object.TreeEntry{
  166. Name: file.Name, Mode: file.Mode, Hash: file.Hash}}})
  167. }
  168. return nil
  169. }()
  170. if err != nil {
  171. return nil, err
  172. }
  173. }
  174. treediff.previousTree = tree
  175. treediff.previousCommit = commit.Hash
  176. // filter without allocation
  177. filteredDiff := make([]*object.Change, 0, len(diff))
  178. OUTER:
  179. for _, change := range diff {
  180. for _, dir := range treediff.SkipDirs {
  181. if strings.HasPrefix(change.To.Name, dir) || strings.HasPrefix(change.From.Name, dir) {
  182. continue OUTER
  183. }
  184. }
  185. var changeEntry object.ChangeEntry
  186. if change.To.Tree == nil {
  187. changeEntry = change.From
  188. } else {
  189. changeEntry = change.To
  190. }
  191. pass, _ := treediff.checkLanguage(changeEntry.Name, changeEntry.TreeEntry.Hash)
  192. if !pass {
  193. continue
  194. }
  195. filteredDiff = append(filteredDiff, change)
  196. }
  197. diff = filteredDiff
  198. return map[string]interface{}{DependencyTreeChanges: diff}, nil
  199. }
  200. // Fork clones this PipelineItem.
  201. func (treediff *TreeDiff) Fork(n int) []core.PipelineItem {
  202. return core.ForkCopyPipelineItem(treediff, n)
  203. }
  204. // checkLanguage returns whether the blob corresponds to the list of required languages.
  205. func (treediff *TreeDiff) checkLanguage(name string, blobHash plumbing.Hash) (bool, error) {
  206. if treediff.Languages[allLanguages] {
  207. return true, nil
  208. }
  209. blob, err := treediff.repository.BlobObject(blobHash)
  210. if err != nil {
  211. return false, err
  212. }
  213. reader, err := blob.Reader()
  214. if err != nil {
  215. return false, err
  216. }
  217. buffer := make([]byte, 1024)
  218. _, err = reader.Read(buffer)
  219. if err != nil {
  220. return false, err
  221. }
  222. lang := enry.GetLanguage(name, buffer)
  223. return treediff.Languages[lang], nil
  224. }
  225. func init() {
  226. core.Registry.Register(&TreeDiff{})
  227. }