diff_refiner.go 6.6 KB

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