tree_diff.go 9.4 KB

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