diff.go 5.5 KB

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