tree_diff.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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.v9/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. SkipFiles []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. "package-lock.json",
  54. "Gopkg.lock",
  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 and vendored files (according to " +
  78. "src-d/enry.IsVendor).",
  79. Flag: "skip-blacklist",
  80. Type: core.BoolConfigurationOption,
  81. Default: false}, {
  82. Name: ConfigTreeDiffBlacklistedPrefixes,
  83. Description: "List of blacklisted path prefixes (e.g. directories or specific files). " +
  84. "Values are in the UNIX format (\"path/to/x\"). Values should *not* start with \"/\". " +
  85. "Separated with commas \",\".",
  86. Flag: "blacklisted-prefixes",
  87. Type: core.StringsConfigurationOption,
  88. Default: defaultBlacklistedPrefixes}, {
  89. Name: ConfigTreeDiffLanguages,
  90. Description: fmt.Sprintf(
  91. "List of programming languages to analyze. Separated by comma \",\". "+
  92. "Names are at https://doc.bblf.sh/languages.html \"%s\" is the special name "+
  93. "which disables this filter and lets all the files through.", allLanguages),
  94. Flag: "languages",
  95. Type: core.StringsConfigurationOption,
  96. Default: []string{allLanguages}}, {
  97. Name: ConfigTreeDiffFilterRegexp,
  98. Description: "Whitelist regexp to determine which files to analyze.",
  99. Flag: "whitelist",
  100. Type: core.StringConfigurationOption,
  101. Default: ""},
  102. }
  103. return options[:]
  104. }
  105. // Configure sets the properties previously published by ListConfigurationOptions().
  106. func (treediff *TreeDiff) Configure(facts map[string]interface{}) error {
  107. if val, exists := facts[ConfigTreeDiffEnableBlacklist].(bool); exists && val {
  108. treediff.SkipFiles = facts[ConfigTreeDiffBlacklistedPrefixes].([]string)
  109. }
  110. if val, exists := facts[ConfigTreeDiffLanguages].([]string); exists {
  111. treediff.Languages = map[string]bool{}
  112. for _, lang := range val {
  113. treediff.Languages[strings.TrimSpace(lang)] = true
  114. }
  115. } else if treediff.Languages == nil {
  116. treediff.Languages = map[string]bool{}
  117. treediff.Languages[allLanguages] = true
  118. }
  119. if val, exists := facts[ConfigTreeDiffFilterRegexp].(string); exists {
  120. treediff.NameFilter = regexp.MustCompile(val)
  121. }
  122. return nil
  123. }
  124. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  125. // calls. The repository which is going to be analysed is supplied as an argument.
  126. func (treediff *TreeDiff) Initialize(repository *git.Repository) error {
  127. treediff.previousTree = nil
  128. treediff.repository = repository
  129. if treediff.Languages == nil {
  130. treediff.Languages = map[string]bool{}
  131. treediff.Languages[allLanguages] = true
  132. }
  133. return nil
  134. }
  135. // Consume runs this PipelineItem on the next commit data.
  136. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  137. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  138. // This function returns the mapping with analysis results. The keys must be the same as
  139. // in Provides(). If there was an error, nil is returned.
  140. func (treediff *TreeDiff) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  141. commit := deps[core.DependencyCommit].(*object.Commit)
  142. pass := false
  143. for _, hash := range commit.ParentHashes {
  144. if hash == treediff.previousCommit {
  145. pass = true
  146. }
  147. }
  148. if !pass && treediff.previousCommit != plumbing.ZeroHash {
  149. log.Panicf("%s > %s", treediff.previousCommit.String(), commit.Hash.String())
  150. }
  151. tree, err := commit.Tree()
  152. if err != nil {
  153. return nil, err
  154. }
  155. var diffs object.Changes
  156. if treediff.previousTree != nil {
  157. diffs, err = object.DiffTree(treediff.previousTree, tree)
  158. if err != nil {
  159. return nil, err
  160. }
  161. } else {
  162. diffs = []*object.Change{}
  163. err = func() error {
  164. fileIter := tree.Files()
  165. defer fileIter.Close()
  166. for {
  167. file, err := fileIter.Next()
  168. if err != nil {
  169. if err == io.EOF {
  170. break
  171. }
  172. return err
  173. }
  174. pass, err := treediff.checkLanguage(file.Name, file.Hash)
  175. if err != nil {
  176. return err
  177. }
  178. if !pass {
  179. continue
  180. }
  181. diffs = append(diffs, &object.Change{
  182. To: object.ChangeEntry{Name: file.Name, Tree: tree, TreeEntry: object.TreeEntry{
  183. Name: file.Name, Mode: file.Mode, Hash: file.Hash}}})
  184. }
  185. return nil
  186. }()
  187. if err != nil {
  188. return nil, err
  189. }
  190. }
  191. treediff.previousTree = tree
  192. treediff.previousCommit = commit.Hash
  193. diffs = treediff.filterDiffs(diffs)
  194. return map[string]interface{}{DependencyTreeChanges: diffs}, nil
  195. }
  196. func (treediff *TreeDiff) filterDiffs(diffs object.Changes) object.Changes {
  197. // filter without allocation
  198. filteredDiffs := make(object.Changes, 0, len(diffs))
  199. OUTER:
  200. for _, change := range diffs {
  201. if len(treediff.SkipFiles) > 0 && (enry.IsVendor(change.To.Name) || enry.IsVendor(change.From.Name)) {
  202. continue
  203. }
  204. for _, dir := range treediff.SkipFiles {
  205. if strings.HasPrefix(change.To.Name, dir) || strings.HasPrefix(change.From.Name, dir) {
  206. continue OUTER
  207. }
  208. }
  209. if treediff.NameFilter != nil {
  210. matchedTo := treediff.NameFilter.MatchString(change.To.Name)
  211. matchedFrom := treediff.NameFilter.MatchString(change.From.Name)
  212. if !matchedTo && !matchedFrom {
  213. continue
  214. }
  215. }
  216. var changeEntry object.ChangeEntry
  217. if change.To.Tree == nil {
  218. changeEntry = change.From
  219. } else {
  220. changeEntry = change.To
  221. }
  222. if pass, _ := treediff.checkLanguage(changeEntry.Name, changeEntry.TreeEntry.Hash); !pass {
  223. continue
  224. }
  225. filteredDiffs = append(filteredDiffs, change)
  226. }
  227. return filteredDiffs
  228. }
  229. // Fork clones this PipelineItem.
  230. func (treediff *TreeDiff) Fork(n int) []core.PipelineItem {
  231. return core.ForkCopyPipelineItem(treediff, n)
  232. }
  233. // checkLanguage returns whether the blob corresponds to the list of required languages.
  234. func (treediff *TreeDiff) checkLanguage(name string, blobHash plumbing.Hash) (bool, error) {
  235. if treediff.Languages[allLanguages] {
  236. return true, nil
  237. }
  238. blob, err := treediff.repository.BlobObject(blobHash)
  239. if err != nil {
  240. return false, err
  241. }
  242. reader, err := blob.Reader()
  243. if err != nil {
  244. return false, err
  245. }
  246. buffer := make([]byte, 1024)
  247. n, err := reader.Read(buffer)
  248. if err != nil {
  249. return false, err
  250. }
  251. if n < len(buffer) {
  252. buffer = buffer[:n]
  253. }
  254. lang := enry.GetLanguage(path.Base(name), buffer)
  255. return treediff.Languages[lang], nil
  256. }
  257. func init() {
  258. core.Registry.Register(&TreeDiff{})
  259. }