diff_refiner.go 6.6 KB

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