tree_diff.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package plumbing
  2. import (
  3. "fmt"
  4. "io"
  5. "path"
  6. "regexp"
  7. "strings"
  8. "gopkg.in/src-d/enry.v1"
  9. "gopkg.in/src-d/go-git.v4"
  10. "gopkg.in/src-d/go-git.v4/plumbing"
  11. "gopkg.in/src-d/go-git.v4/plumbing/object"
  12. "gopkg.in/src-d/hercules.v10/internal/core"
  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. SkipFiles []string
  21. NameFilter *regexp.Regexp
  22. Languages map[string]bool
  23. previousTree *object.Tree
  24. previousCommit plumbing.Hash
  25. repository *git.Repository
  26. l core.Logger
  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 l, exists := facts[core.ConfigLogger].(core.Logger); exists {
  108. treediff.l = l
  109. }
  110. if val, exists := facts[ConfigTreeDiffEnableBlacklist].(bool); exists && val {
  111. treediff.SkipFiles = facts[ConfigTreeDiffBlacklistedPrefixes].([]string)
  112. }
  113. if val, exists := facts[ConfigTreeDiffLanguages].([]string); exists {
  114. treediff.Languages = map[string]bool{}
  115. for _, lang := range val {
  116. treediff.Languages[strings.TrimSpace(lang)] = true
  117. }
  118. } else if treediff.Languages == nil {
  119. treediff.Languages = map[string]bool{}
  120. treediff.Languages[allLanguages] = true
  121. }
  122. if val, exists := facts[ConfigTreeDiffFilterRegexp].(string); exists {
  123. treediff.NameFilter = regexp.MustCompile(val)
  124. }
  125. return nil
  126. }
  127. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  128. // calls. The repository which is going to be analysed is supplied as an argument.
  129. func (treediff *TreeDiff) Initialize(repository *git.Repository) error {
  130. treediff.l = core.NewLogger()
  131. treediff.previousTree = nil
  132. treediff.repository = repository
  133. if treediff.Languages == nil {
  134. treediff.Languages = map[string]bool{}
  135. treediff.Languages[allLanguages] = true
  136. }
  137. return nil
  138. }
  139. // Consume runs this PipelineItem on the next commit data.
  140. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  141. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  142. // This function returns the mapping with analysis results. The keys must be the same as
  143. // in Provides(). If there was an error, nil is returned.
  144. func (treediff *TreeDiff) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  145. commit := deps[core.DependencyCommit].(*object.Commit)
  146. pass := false
  147. for _, hash := range commit.ParentHashes {
  148. if hash == treediff.previousCommit {
  149. pass = true
  150. }
  151. }
  152. if !pass && treediff.previousCommit != plumbing.ZeroHash {
  153. err := fmt.Errorf("%s > %s", treediff.previousCommit.String(), commit.Hash.String())
  154. treediff.l.Error(err)
  155. return nil, err
  156. }
  157. tree, err := commit.Tree()
  158. if err != nil {
  159. return nil, err
  160. }
  161. var diffs object.Changes
  162. if treediff.previousTree != nil {
  163. diffs, err = object.DiffTree(treediff.previousTree, tree)
  164. if err != nil {
  165. return nil, err
  166. }
  167. } else {
  168. diffs = []*object.Change{}
  169. err = func() error {
  170. fileIter := tree.Files()
  171. defer fileIter.Close()
  172. for {
  173. file, err := fileIter.Next()
  174. if err != nil {
  175. if err == io.EOF {
  176. break
  177. }
  178. return err
  179. }
  180. pass, err := treediff.checkLanguage(file.Name, file.Hash)
  181. if err != nil {
  182. return err
  183. }
  184. if !pass {
  185. continue
  186. }
  187. diffs = append(diffs, &object.Change{
  188. To: object.ChangeEntry{Name: file.Name, Tree: tree, TreeEntry: object.TreeEntry{
  189. Name: file.Name, Mode: file.Mode, Hash: file.Hash}}})
  190. }
  191. return nil
  192. }()
  193. if err != nil {
  194. return nil, err
  195. }
  196. }
  197. treediff.previousTree = tree
  198. treediff.previousCommit = commit.Hash
  199. diffs = treediff.filterDiffs(diffs)
  200. return map[string]interface{}{DependencyTreeChanges: diffs}, nil
  201. }
  202. func (treediff *TreeDiff) filterDiffs(diffs object.Changes) object.Changes {
  203. // filter without allocation
  204. filteredDiffs := make(object.Changes, 0, len(diffs))
  205. OUTER:
  206. for _, change := range diffs {
  207. if len(treediff.SkipFiles) > 0 && (enry.IsVendor(change.To.Name) || enry.IsVendor(change.From.Name)) {
  208. continue
  209. }
  210. for _, dir := range treediff.SkipFiles {
  211. if strings.HasPrefix(change.To.Name, dir) || strings.HasPrefix(change.From.Name, dir) {
  212. continue OUTER
  213. }
  214. }
  215. if treediff.NameFilter != nil {
  216. matchedTo := treediff.NameFilter.MatchString(change.To.Name)
  217. matchedFrom := treediff.NameFilter.MatchString(change.From.Name)
  218. if !matchedTo && !matchedFrom {
  219. continue
  220. }
  221. }
  222. var changeEntry object.ChangeEntry
  223. if change.To.Tree == nil {
  224. changeEntry = change.From
  225. } else {
  226. changeEntry = change.To
  227. }
  228. if pass, _ := treediff.checkLanguage(changeEntry.Name, changeEntry.TreeEntry.Hash); !pass {
  229. continue
  230. }
  231. filteredDiffs = append(filteredDiffs, change)
  232. }
  233. return filteredDiffs
  234. }
  235. // Fork clones this PipelineItem.
  236. func (treediff *TreeDiff) Fork(n int) []core.PipelineItem {
  237. return core.ForkCopyPipelineItem(treediff, n)
  238. }
  239. // checkLanguage returns whether the blob corresponds to the list of required languages.
  240. func (treediff *TreeDiff) checkLanguage(name string, blobHash plumbing.Hash) (bool, error) {
  241. if treediff.Languages[allLanguages] {
  242. return true, nil
  243. }
  244. blob, err := treediff.repository.BlobObject(blobHash)
  245. if err != nil {
  246. return false, err
  247. }
  248. reader, err := blob.Reader()
  249. if err != nil {
  250. return false, err
  251. }
  252. buffer := make([]byte, 1024)
  253. n, err := reader.Read(buffer)
  254. if err != nil {
  255. return false, err
  256. }
  257. if n < len(buffer) {
  258. buffer = buffer[:n]
  259. }
  260. lang := enry.GetLanguage(path.Base(name), buffer)
  261. return treediff.Languages[lang], nil
  262. }
  263. func init() {
  264. core.Registry.Register(&TreeDiff{})
  265. }