tree_diff.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package plumbing
  2. import (
  3. "fmt"
  4. "regexp"
  5. "gopkg.in/src-d/enry.v1"
  6. "io"
  7. "log"
  8. "strings"
  9. "gopkg.in/src-d/go-git.v4"
  10. "gopkg.in/src-d/go-git.v4/plumbing/object"
  11. "gopkg.in/src-d/hercules.v5/internal/core"
  12. "gopkg.in/src-d/go-git.v4/plumbing"
  13. )
  14. // TreeDiff generates the list of changes for a commit. A change can be either one or two blobs
  15. // under the same path: "before" and "after". If "before" is nil, the change is an addition.
  16. // If "after" is nil, the change is a removal. Otherwise, it is a modification.
  17. // TreeDiff is a PipelineItem.
  18. type TreeDiff struct {
  19. core.NoopMerger
  20. SkipDirs []string
  21. Filter string
  22. Languages map[string]bool
  23. previousTree *object.Tree
  24. previousCommit plumbing.Hash
  25. repository *git.Repository
  26. }
  27. const (
  28. // DependencyTreeChanges is the name of the dependency provided by TreeDiff.
  29. DependencyTreeChanges = "changes"
  30. // ConfigTreeDiffEnableBlacklist is the name of the configuration option
  31. // (TreeDiff.Configure()) which allows to skip blacklisted directories.
  32. ConfigTreeDiffEnableBlacklist = "TreeDiff.EnableBlacklist"
  33. // ConfigTreeDiffBlacklistedPrefixes s the name of the configuration option
  34. // (TreeDiff.Configure()) which allows to set blacklisted path prefixes -
  35. // directories or complete file names.
  36. ConfigTreeDiffBlacklistedPrefixes = "TreeDiff.BlacklistedPrefixes"
  37. // ConfigTreeDiffLanguages is the name of the configuration option (TreeDiff.Configure())
  38. // which sets the list of programming languages to analyze. Language names are at
  39. // https://doc.bblf.sh/languages.html Names are joined with a comma ",".
  40. // "all" is the special name which disables this filter.
  41. ConfigTreeDiffLanguages = "TreeDiff.Languages"
  42. // allLanguages denotes passing all files in.
  43. allLanguages = "all"
  44. // ConfigTreeDiffFilteredRegexes is the name of the configuration option
  45. // (TreeDiff.Configure()) which allows to set whitelisted path prefixes -
  46. // directories or complete file names.
  47. ConfigTreeDiffFilterRegex = "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: ConfigTreeDiffFilterRegex,
  97. Description: "Will filter which files to analyze based on this Regex",
  98. Flag: "filter",
  99. Type: core.StringsConfigurationOption,
  100. },
  101. }
  102. return options[:]
  103. }
  104. // Configure sets the properties previously published by ListConfigurationOptions().
  105. func (treediff *TreeDiff) Configure(facts map[string]interface{}) {
  106. if val, exist := facts[ConfigTreeDiffEnableBlacklist]; exist && val.(bool) {
  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 strings.Split(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[ConfigTreeDiffFilterRegex].(string); exists {
  119. treediff.Filter = val
  120. }
  121. }
  122. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  123. // calls. The repository which is going to be analysed is supplied as an argument.
  124. func (treediff *TreeDiff) Initialize(repository *git.Repository) {
  125. treediff.previousTree = nil
  126. treediff.repository = repository
  127. if treediff.Languages == nil {
  128. treediff.Languages = map[string]bool{}
  129. treediff.Languages[allLanguages] = true
  130. }
  131. }
  132. // Consume runs this PipelineItem on the next commit data.
  133. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  134. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  135. // This function returns the mapping with analysis results. The keys must be the same as
  136. // in Provides(). If there was an error, nil is returned.
  137. func (treediff *TreeDiff) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  138. commit := deps[core.DependencyCommit].(*object.Commit)
  139. pass := false
  140. for _, hash := range commit.ParentHashes {
  141. if hash == treediff.previousCommit {
  142. pass = true
  143. }
  144. }
  145. if !pass && treediff.previousCommit != plumbing.ZeroHash {
  146. log.Panicf("%s > %s", treediff.previousCommit.String(), commit.Hash.String())
  147. }
  148. tree, err := commit.Tree()
  149. if err != nil {
  150. return nil, err
  151. }
  152. var diff object.Changes
  153. if treediff.previousTree != nil {
  154. diff, err = object.DiffTree(treediff.previousTree, tree)
  155. if err != nil {
  156. return nil, err
  157. }
  158. } else {
  159. diff = []*object.Change{}
  160. err = func() error {
  161. fileIter := tree.Files()
  162. defer fileIter.Close()
  163. for {
  164. file, err := fileIter.Next()
  165. if err != nil {
  166. if err == io.EOF {
  167. break
  168. }
  169. return err
  170. }
  171. pass, err := treediff.checkLanguage(file.Name, file.Hash)
  172. if err != nil {
  173. return err
  174. }
  175. if !pass {
  176. continue
  177. }
  178. diff = append(diff, &object.Change{
  179. To: object.ChangeEntry{Name: file.Name, Tree: tree, TreeEntry: object.TreeEntry{
  180. Name: file.Name, Mode: file.Mode, Hash: file.Hash}}})
  181. }
  182. return nil
  183. }()
  184. if err != nil {
  185. return nil, err
  186. }
  187. }
  188. treediff.previousTree = tree
  189. treediff.previousCommit = commit.Hash
  190. // filter without allocation
  191. filteredDiff := make([]*object.Change, 0, len(diff))
  192. OUTER:
  193. for _, change := range diff {
  194. for _, dir := range treediff.SkipDirs {
  195. if strings.HasPrefix(change.To.Name, dir) || strings.HasPrefix(change.From.Name, dir) {
  196. continue OUTER
  197. }
  198. }
  199. if treediff.Filter != "" {
  200. matchedTo, err := regexp.MatchString(treediff.Filter, change.To.Name)
  201. matchedFrom, _ := regexp.MatchString(treediff.Filter, change.From.Name)
  202. if err != nil {
  203. panic(err)
  204. }
  205. if !matchedTo && !matchedFrom {
  206. continue OUTER
  207. }
  208. }
  209. var changeEntry object.ChangeEntry
  210. if change.To.Tree == nil {
  211. changeEntry = change.From
  212. } else {
  213. changeEntry = change.To
  214. }
  215. pass, _ := treediff.checkLanguage(changeEntry.Name, changeEntry.TreeEntry.Hash)
  216. if !pass {
  217. continue
  218. }
  219. filteredDiff = append(filteredDiff, change)
  220. }
  221. diff = filteredDiff
  222. return map[string]interface{}{DependencyTreeChanges: diff}, nil
  223. }
  224. // Fork clones this PipelineItem.
  225. func (treediff *TreeDiff) Fork(n int) []core.PipelineItem {
  226. return core.ForkCopyPipelineItem(treediff, n)
  227. }
  228. // checkLanguage returns whether the blob corresponds to the list of required languages.
  229. func (treediff *TreeDiff) checkLanguage(name string, blobHash plumbing.Hash) (bool, error) {
  230. if treediff.Languages[allLanguages] {
  231. return true, nil
  232. }
  233. blob, err := treediff.repository.BlobObject(blobHash)
  234. if err != nil {
  235. return false, err
  236. }
  237. reader, err := blob.Reader()
  238. if err != nil {
  239. return false, err
  240. }
  241. buffer := make([]byte, 1024)
  242. _, err = reader.Read(buffer)
  243. if err != nil {
  244. return false, err
  245. }
  246. lang := enry.GetLanguage(name, buffer)
  247. return treediff.Languages[lang], nil
  248. }
  249. func init() {
  250. core.Registry.Register(&TreeDiff{})
  251. }