diff.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package plumbing
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "io"
  7. "unicode/utf8"
  8. "github.com/sergi/go-diff/diffmatchpatch"
  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/go-git.v4/utils/merkletrie"
  13. "gopkg.in/src-d/hercules.v4/internal/core"
  14. )
  15. // FileDiff calculates the difference of files which were modified.
  16. // It is a PipelineItem.
  17. type FileDiff struct {
  18. CleanupDisabled bool
  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. )
  28. // FileDiffData is the type of the dependency provided by FileDiff.
  29. type FileDiffData struct {
  30. OldLinesOfCode int
  31. NewLinesOfCode int
  32. Diffs []diffmatchpatch.Diff
  33. }
  34. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  35. func (diff *FileDiff) Name() string {
  36. return "FileDiff"
  37. }
  38. // Provides returns the list of names of entities which are produced by this PipelineItem.
  39. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  40. // to this list. Also used by core.Registry to build the global map of providers.
  41. func (diff *FileDiff) Provides() []string {
  42. arr := [...]string{DependencyFileDiff}
  43. return arr[:]
  44. }
  45. // Requires returns the list of names of entities which are needed by this PipelineItem.
  46. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  47. // entities are Provides() upstream.
  48. func (diff *FileDiff) Requires() []string {
  49. arr := [...]string{DependencyTreeChanges, DependencyBlobCache}
  50. return arr[:]
  51. }
  52. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  53. func (diff *FileDiff) ListConfigurationOptions() []core.ConfigurationOption {
  54. options := [...]core.ConfigurationOption{{
  55. Name: ConfigFileDiffDisableCleanup,
  56. Description: "Do not apply additional heuristics to improve diffs.",
  57. Flag: "no-diff-cleanup",
  58. Type: core.BoolConfigurationOption,
  59. Default: false},
  60. }
  61. return options[:]
  62. }
  63. // Configure sets the properties previously published by ListConfigurationOptions().
  64. func (diff *FileDiff) Configure(facts map[string]interface{}) {
  65. if val, exists := facts[ConfigFileDiffDisableCleanup].(bool); exists {
  66. diff.CleanupDisabled = val
  67. }
  68. }
  69. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  70. // calls. The repository which is going to be analysed is supplied as an argument.
  71. func (diff *FileDiff) Initialize(repository *git.Repository) {}
  72. // Consume runs this PipelineItem on the next commit data.
  73. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  74. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  75. // This function returns the mapping with analysis results. The keys must be the same as
  76. // in Provides(). If there was an error, nil is returned.
  77. func (diff *FileDiff) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  78. result := map[string]FileDiffData{}
  79. cache := deps[DependencyBlobCache].(map[plumbing.Hash]*object.Blob)
  80. treeDiff := deps[DependencyTreeChanges].(object.Changes)
  81. for _, change := range treeDiff {
  82. action, err := change.Action()
  83. if err != nil {
  84. return nil, err
  85. }
  86. switch action {
  87. case merkletrie.Modify:
  88. blobFrom := cache[change.From.TreeEntry.Hash]
  89. blobTo := cache[change.To.TreeEntry.Hash]
  90. // we are not validating UTF-8 here because for example
  91. // git/git 4f7770c87ce3c302e1639a7737a6d2531fe4b160 fetch-pack.c is invalid UTF-8
  92. strFrom, err := BlobToString(blobFrom)
  93. if err != nil {
  94. return nil, err
  95. }
  96. strTo, err := BlobToString(blobTo)
  97. if err != nil {
  98. return nil, err
  99. }
  100. dmp := diffmatchpatch.New()
  101. src, dst, _ := dmp.DiffLinesToRunes(strFrom, strTo)
  102. diffs := dmp.DiffMainRunes(src, dst, false)
  103. if !diff.CleanupDisabled {
  104. diffs = dmp.DiffCleanupMerge(dmp.DiffCleanupSemanticLossless(diffs))
  105. }
  106. result[change.To.Name] = FileDiffData{
  107. OldLinesOfCode: len(src),
  108. NewLinesOfCode: len(dst),
  109. Diffs: diffs,
  110. }
  111. default:
  112. continue
  113. }
  114. }
  115. return map[string]interface{}{DependencyFileDiff: result}, nil
  116. }
  117. func (diff *FileDiff) Fork(n int) []core.PipelineItem {
  118. diffs := make([]core.PipelineItem, n)
  119. for i := 0; i < n; i++ {
  120. diffs[i] = diff
  121. }
  122. return diffs
  123. }
  124. func (diff *FileDiff) Merge(branches []core.PipelineItem) {
  125. // no-op
  126. }
  127. // CountLines returns the number of lines in a *object.Blob.
  128. func CountLines(file *object.Blob) (int, error) {
  129. if file == nil {
  130. return -1, errors.New("blob is nil: probably not cached")
  131. }
  132. reader, err := file.Reader()
  133. if err != nil {
  134. return -1, err
  135. }
  136. defer checkClose(reader)
  137. var scanner *bufio.Scanner
  138. buffer := make([]byte, bufio.MaxScanTokenSize)
  139. counter := 0
  140. for scanner == nil || scanner.Err() == bufio.ErrTooLong {
  141. if scanner != nil && !utf8.Valid(scanner.Bytes()) {
  142. return -1, errors.New("binary")
  143. }
  144. scanner = bufio.NewScanner(reader)
  145. scanner.Buffer(buffer, 0)
  146. for scanner.Scan() {
  147. if !utf8.Valid(scanner.Bytes()) {
  148. return -1, errors.New("binary")
  149. }
  150. counter++
  151. }
  152. }
  153. return counter, nil
  154. }
  155. // BlobToString reads *object.Blob and returns its contents as a string.
  156. func BlobToString(file *object.Blob) (string, error) {
  157. if file == nil {
  158. return "", errors.New("blob is nil: probably not cached")
  159. }
  160. reader, err := file.Reader()
  161. if err != nil {
  162. return "", err
  163. }
  164. defer checkClose(reader)
  165. buf := new(bytes.Buffer)
  166. buf.ReadFrom(reader)
  167. return buf.String(), nil
  168. }
  169. func checkClose(c io.Closer) {
  170. if err := c.Close(); err != nil {
  171. panic(err)
  172. }
  173. }
  174. func init() {
  175. core.Registry.Register(&FileDiff{})
  176. }