diff_refiner.go 6.5 KB

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