diff.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package plumbing
  2. import (
  3. "strings"
  4. "time"
  5. "github.com/sergi/go-diff/diffmatchpatch"
  6. "gopkg.in/src-d/go-git.v4"
  7. "gopkg.in/src-d/go-git.v4/plumbing"
  8. "gopkg.in/src-d/go-git.v4/plumbing/object"
  9. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  10. "gopkg.in/src-d/hercules.v10/internal/core"
  11. )
  12. // FileDiff calculates the difference of files which were modified.
  13. // It is a PipelineItem.
  14. type FileDiff struct {
  15. core.NoopMerger
  16. CleanupDisabled bool
  17. WhitespaceIgnore bool
  18. Timeout time.Duration
  19. l core.Logger
  20. }
  21. const (
  22. // ConfigFileDiffDisableCleanup is the name of the configuration option (FileDiff.Configure())
  23. // to suppress diffmatchpatch.DiffCleanupSemanticLossless() which is supposed to improve
  24. // the human interpretability of diffs.
  25. ConfigFileDiffDisableCleanup = "FileDiff.NoCleanup"
  26. // DependencyFileDiff is the name of the dependency provided by FileDiff.
  27. DependencyFileDiff = "file_diff"
  28. // ConfigFileWhitespaceIgnore is the name of the configuration option (FileDiff.Configure())
  29. // to suppress whitespace changes which can pollute the core diff of the files
  30. ConfigFileWhitespaceIgnore = "FileDiff.WhitespaceIgnore"
  31. // ConfigFileDiffTimeout is the number of milliseconds a single diff calculation may elapse.
  32. // We need this timeout to avoid spending too much time comparing big or "bad" files.
  33. ConfigFileDiffTimeout = "FileDiff.Timeout"
  34. )
  35. // FileDiffData is the type of the dependency provided by FileDiff.
  36. type FileDiffData struct {
  37. OldLinesOfCode int
  38. NewLinesOfCode int
  39. Diffs []diffmatchpatch.Diff
  40. }
  41. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  42. func (diff *FileDiff) Name() string {
  43. return "FileDiff"
  44. }
  45. // Provides returns the list of names of entities which are produced by this PipelineItem.
  46. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  47. // to this list. Also used by core.Registry to build the global map of providers.
  48. func (diff *FileDiff) Provides() []string {
  49. return []string{DependencyFileDiff}
  50. }
  51. // Requires returns the list of names of entities which are needed by this PipelineItem.
  52. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  53. // entities are Provides() upstream.
  54. func (diff *FileDiff) Requires() []string {
  55. return []string{DependencyTreeChanges, DependencyBlobCache}
  56. }
  57. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  58. func (diff *FileDiff) ListConfigurationOptions() []core.ConfigurationOption {
  59. options := [...]core.ConfigurationOption{
  60. {
  61. Name: ConfigFileDiffDisableCleanup,
  62. Description: "Do not apply additional heuristics to improve diffs.",
  63. Flag: "no-diff-cleanup",
  64. Type: core.BoolConfigurationOption,
  65. Default: false},
  66. {
  67. Name: ConfigFileWhitespaceIgnore,
  68. Description: "Ignore whitespace when computing diffs.",
  69. Flag: "no-diff-whitespace",
  70. Type: core.BoolConfigurationOption,
  71. Default: false},
  72. {
  73. Name: ConfigFileDiffTimeout,
  74. Description: "Maximum time in milliseconds a single diff calculation may elapse.",
  75. Flag: "diff-timeout",
  76. Type: core.IntConfigurationOption,
  77. Default: 1000},
  78. }
  79. return options[:]
  80. }
  81. // Configure sets the properties previously published by ListConfigurationOptions().
  82. func (diff *FileDiff) Configure(facts map[string]interface{}) error {
  83. if l, exists := facts[core.ConfigLogger].(core.Logger); exists {
  84. diff.l = l
  85. }
  86. if val, exists := facts[ConfigFileDiffDisableCleanup].(bool); exists {
  87. diff.CleanupDisabled = val
  88. }
  89. if val, exists := facts[ConfigFileWhitespaceIgnore].(bool); exists {
  90. diff.WhitespaceIgnore = val
  91. }
  92. if val, exists := facts[ConfigFileDiffTimeout].(int); exists {
  93. if val <= 0 {
  94. diff.l.Warnf("invalid timeout value: %d", val)
  95. }
  96. diff.Timeout = time.Duration(val) * time.Millisecond
  97. }
  98. return nil
  99. }
  100. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  101. // calls. The repository which is going to be analysed is supplied as an argument.
  102. func (diff *FileDiff) Initialize(repository *git.Repository) error {
  103. diff.l = core.NewLogger()
  104. return nil
  105. }
  106. func stripWhitespace(str string, ignoreWhitespace bool) string {
  107. if ignoreWhitespace {
  108. response := strings.Replace(str, " ", "", -1)
  109. return response
  110. }
  111. return str
  112. }
  113. // Consume runs this PipelineItem on the next commit data.
  114. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  115. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  116. // This function returns the mapping with analysis results. The keys must be the same as
  117. // in Provides(). If there was an error, nil is returned.
  118. func (diff *FileDiff) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  119. result := map[string]FileDiffData{}
  120. cache := deps[DependencyBlobCache].(map[plumbing.Hash]*CachedBlob)
  121. treeDiff := deps[DependencyTreeChanges].(object.Changes)
  122. for _, change := range treeDiff {
  123. action, err := change.Action()
  124. if err != nil {
  125. return nil, err
  126. }
  127. switch action {
  128. case merkletrie.Modify:
  129. blobFrom := cache[change.From.TreeEntry.Hash]
  130. blobTo := cache[change.To.TreeEntry.Hash]
  131. // we are not validating UTF-8 here because for example
  132. // git/git 4f7770c87ce3c302e1639a7737a6d2531fe4b160 fetch-pack.c is invalid UTF-8
  133. strFrom, strTo := string(blobFrom.Data), string(blobTo.Data)
  134. dmp := diffmatchpatch.New()
  135. dmp.DiffTimeout = diff.Timeout
  136. src, dst, _ := dmp.DiffLinesToRunes(stripWhitespace(strFrom, diff.WhitespaceIgnore), stripWhitespace(strTo, diff.WhitespaceIgnore))
  137. diffs := dmp.DiffMainRunes(src, dst, false)
  138. if !diff.CleanupDisabled {
  139. diffs = dmp.DiffCleanupMerge(dmp.DiffCleanupSemanticLossless(diffs))
  140. }
  141. result[change.To.Name] = FileDiffData{
  142. OldLinesOfCode: len(src),
  143. NewLinesOfCode: len(dst),
  144. Diffs: diffs,
  145. }
  146. default:
  147. continue
  148. }
  149. }
  150. return map[string]interface{}{DependencyFileDiff: result}, nil
  151. }
  152. // Fork clones this PipelineItem.
  153. func (diff *FileDiff) Fork(n int) []core.PipelineItem {
  154. return core.ForkSamePipelineItem(diff, n)
  155. }
  156. func init() {
  157. core.Registry.Register(&FileDiff{})
  158. }