diff.go 5.5 KB

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