tree_diff.go 9.7 KB

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