diff_refiner.go 6.6 KB

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