diff_refiner.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package hercules
  2. import (
  3. "unicode/utf8"
  4. "github.com/sergi/go-diff/diffmatchpatch"
  5. "gopkg.in/bblfsh/sdk.v1/uast"
  6. "gopkg.in/src-d/go-git.v4"
  7. )
  8. // FileDiffRefiner uses UASTs to improve the human interpretability of diffs.
  9. // It is a PipelineItem.
  10. // The idea behind this algorithm is simple: in case of multiple choices which are equally
  11. // optimal, choose the one which touches less AST nodes.
  12. type FileDiffRefiner struct {
  13. }
  14. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  15. func (ref *FileDiffRefiner) Name() string {
  16. return "FileDiffRefiner"
  17. }
  18. // Provides returns the list of names of entities which are produced by this PipelineItem.
  19. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  20. // to this list. Also used by hercules.Registry to build the global map of providers.
  21. func (ref *FileDiffRefiner) Provides() []string {
  22. arr := [...]string{DependencyFileDiff}
  23. return arr[:]
  24. }
  25. // Requires returns the list of names of entities which are needed by this PipelineItem.
  26. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  27. // entities are Provides() upstream.
  28. func (ref *FileDiffRefiner) Requires() []string {
  29. arr := [...]string{DependencyFileDiff, DependencyUastChanges}
  30. return arr[:]
  31. }
  32. // Features which must be enabled for this PipelineItem to be automatically inserted into the DAG.
  33. func (ref *FileDiffRefiner) Features() []string {
  34. arr := [...]string{FeatureUast}
  35. return arr[:]
  36. }
  37. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  38. func (ref *FileDiffRefiner) ListConfigurationOptions() []ConfigurationOption {
  39. return []ConfigurationOption{}
  40. }
  41. // Configure sets the properties previously published by ListConfigurationOptions().
  42. func (ref *FileDiffRefiner) Configure(facts map[string]interface{}) {}
  43. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  44. // calls. The repository which is going to be analysed is supplied as an argument.
  45. func (ref *FileDiffRefiner) Initialize(repository *git.Repository) {
  46. }
  47. // Consume runs this PipelineItem on the next commit data.
  48. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  49. // Additionally, "commit" is always present there and represents the analysed *object.Commit.
  50. // This function returns the mapping with analysis results. The keys must be the same as
  51. // in Provides(). If there was an error, nil is returned.
  52. func (ref *FileDiffRefiner) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  53. changesList := deps[DependencyUastChanges].([]UASTChange)
  54. changes := map[string]UASTChange{}
  55. for _, change := range changesList {
  56. if change.Before != nil && change.After != nil {
  57. changes[change.Change.To.Name] = change
  58. }
  59. }
  60. diffs := deps[DependencyFileDiff].(map[string]FileDiffData)
  61. result := map[string]FileDiffData{}
  62. for fileName, oldDiff := range diffs {
  63. uastChange, exists := changes[fileName]
  64. if !exists {
  65. result[fileName] = oldDiff
  66. continue
  67. }
  68. suspicious := map[int][2]int{}
  69. line := 0
  70. for i, diff := range oldDiff.Diffs {
  71. if i == len(oldDiff.Diffs)-1 {
  72. break
  73. }
  74. if diff.Type == diffmatchpatch.DiffInsert &&
  75. oldDiff.Diffs[i+1].Type == diffmatchpatch.DiffEqual {
  76. matched := 0
  77. runesAdded := []rune(diff.Text)
  78. runesEqual := []rune(oldDiff.Diffs[i+1].Text)
  79. for ; matched < len(runesAdded) && matched < len(runesEqual) &&
  80. runesAdded[matched] == runesEqual[matched]; matched++ {
  81. }
  82. if matched > 0 {
  83. suspicious[i] = [2]int{line, matched}
  84. }
  85. }
  86. if diff.Type != diffmatchpatch.DiffDelete {
  87. line += utf8.RuneCountInString(diff.Text)
  88. }
  89. }
  90. if len(suspicious) == 0 {
  91. result[fileName] = oldDiff
  92. continue
  93. }
  94. line2node := make([][]*uast.Node, oldDiff.NewLinesOfCode)
  95. VisitEachNode(uastChange.After, func(node *uast.Node) {
  96. if node.StartPosition != nil && node.EndPosition != nil {
  97. for l := node.StartPosition.Line; l <= node.EndPosition.Line; l++ {
  98. nodes := line2node[l-1] // line starts with 1
  99. if nodes == nil {
  100. nodes = []*uast.Node{}
  101. }
  102. line2node[l-1] = append(nodes, node)
  103. }
  104. }
  105. })
  106. newDiff := FileDiffData{
  107. OldLinesOfCode: oldDiff.OldLinesOfCode,
  108. NewLinesOfCode: oldDiff.NewLinesOfCode,
  109. Diffs: []diffmatchpatch.Diff{},
  110. }
  111. skipNext := false
  112. for i, diff := range oldDiff.Diffs {
  113. if skipNext {
  114. skipNext = false
  115. continue
  116. }
  117. info, exists := suspicious[i]
  118. if !exists {
  119. newDiff.Diffs = append(newDiff.Diffs, diff)
  120. continue
  121. }
  122. line := info[0]
  123. matched := info[1]
  124. size := utf8.RuneCountInString(diff.Text)
  125. n1 := countNodesInInterval(line2node, line, line+size)
  126. n2 := countNodesInInterval(line2node, line+matched, line+size+matched)
  127. if n1 <= n2 {
  128. newDiff.Diffs = append(newDiff.Diffs, diff)
  129. continue
  130. }
  131. skipNext = true
  132. runes := []rune(diff.Text)
  133. newDiff.Diffs = append(newDiff.Diffs, diffmatchpatch.Diff{
  134. Type: diffmatchpatch.DiffEqual, Text: string(runes[:matched]),
  135. })
  136. newDiff.Diffs = append(newDiff.Diffs, diffmatchpatch.Diff{
  137. Type: diffmatchpatch.DiffInsert, Text: string(runes[matched:]) + string(runes[:matched]),
  138. })
  139. runes = []rune(oldDiff.Diffs[i+1].Text)
  140. if len(runes) > matched {
  141. newDiff.Diffs = append(newDiff.Diffs, diffmatchpatch.Diff{
  142. Type: diffmatchpatch.DiffEqual, Text: string(runes[matched:]),
  143. })
  144. }
  145. }
  146. result[fileName] = newDiff
  147. }
  148. return map[string]interface{}{DependencyFileDiff: result}, nil
  149. }
  150. // VisitEachNode is a handy routine to execute a callback on every node in the subtree,
  151. // including the root itself. Depth first tree traversal.
  152. func VisitEachNode(root *uast.Node, payload func(*uast.Node)) {
  153. queue := []*uast.Node{}
  154. queue = append(queue, root)
  155. for len(queue) > 0 {
  156. node := queue[len(queue)-1]
  157. queue = queue[:len(queue)-1]
  158. payload(node)
  159. for _, child := range node.Children {
  160. queue = append(queue, child)
  161. }
  162. }
  163. }
  164. func countNodesInInterval(occupiedMap [][]*uast.Node, start, end int) int {
  165. nodes := map[*uast.Node]bool{}
  166. for i := start; i < end; i++ {
  167. for _, node := range occupiedMap[i] {
  168. nodes[node] = true
  169. }
  170. }
  171. return len(nodes)
  172. }
  173. func init() {
  174. Registry.Register(&FileDiffRefiner{})
  175. }