diff.go 5.8 KB

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