diff_refiner.go 6.5 KB

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