tree_diff.go 9.0 KB

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