renames.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package plumbing
  2. import (
  3. "log"
  4. "sort"
  5. "unicode/utf8"
  6. "github.com/sergi/go-diff/diffmatchpatch"
  7. "gopkg.in/src-d/go-git.v4"
  8. "gopkg.in/src-d/go-git.v4/plumbing"
  9. "gopkg.in/src-d/go-git.v4/plumbing/object"
  10. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  11. "gopkg.in/src-d/hercules.v4/internal"
  12. "gopkg.in/src-d/hercules.v4/internal/core"
  13. )
  14. // RenameAnalysis improves TreeDiff's results by searching for changed blobs under different
  15. // paths which are likely to be the result of a rename with subsequent edits.
  16. // RenameAnalysis is a PipelineItem.
  17. type RenameAnalysis struct {
  18. core.NoopMerger
  19. // SimilarityThreshold adjusts the heuristic to determine file renames.
  20. // It has the same units as cgit's -X rename-threshold or -M. Better to
  21. // set it to the default value of 90 (90%).
  22. SimilarityThreshold int
  23. repository *git.Repository
  24. }
  25. const (
  26. // RenameAnalysisDefaultThreshold specifies the default percentage of common lines in a pair
  27. // of files to consider them linked. The exact code of the decision is sizesAreClose().
  28. RenameAnalysisDefaultThreshold = 90
  29. // ConfigRenameAnalysisSimilarityThreshold is the name of the configuration option
  30. // (RenameAnalysis.Configure()) which sets the similarity threshold.
  31. ConfigRenameAnalysisSimilarityThreshold = "RenameAnalysis.SimilarityThreshold"
  32. )
  33. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  34. func (ra *RenameAnalysis) Name() string {
  35. return "RenameAnalysis"
  36. }
  37. // Provides returns the list of names of entities which are produced by this PipelineItem.
  38. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  39. // to this list. Also used by core.Registry to build the global map of providers.
  40. func (ra *RenameAnalysis) Provides() []string {
  41. arr := [...]string{DependencyTreeChanges}
  42. return arr[:]
  43. }
  44. // Requires returns the list of names of entities which are needed by this PipelineItem.
  45. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  46. // entities are Provides() upstream.
  47. func (ra *RenameAnalysis) Requires() []string {
  48. arr := [...]string{DependencyBlobCache, DependencyTreeChanges}
  49. return arr[:]
  50. }
  51. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  52. func (ra *RenameAnalysis) ListConfigurationOptions() []core.ConfigurationOption {
  53. options := [...]core.ConfigurationOption{{
  54. Name: ConfigRenameAnalysisSimilarityThreshold,
  55. Description: "The threshold on the similarity index used to detect renames.",
  56. Flag: "M",
  57. Type: core.IntConfigurationOption,
  58. Default: RenameAnalysisDefaultThreshold},
  59. }
  60. return options[:]
  61. }
  62. // Configure sets the properties previously published by ListConfigurationOptions().
  63. func (ra *RenameAnalysis) Configure(facts map[string]interface{}) {
  64. if val, exists := facts[ConfigRenameAnalysisSimilarityThreshold].(int); exists {
  65. ra.SimilarityThreshold = val
  66. }
  67. }
  68. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  69. // calls. The repository which is going to be analysed is supplied as an argument.
  70. func (ra *RenameAnalysis) Initialize(repository *git.Repository) {
  71. if ra.SimilarityThreshold < 0 || ra.SimilarityThreshold > 100 {
  72. log.Printf("Warning: adjusted the similarity threshold to %d\n",
  73. RenameAnalysisDefaultThreshold)
  74. ra.SimilarityThreshold = RenameAnalysisDefaultThreshold
  75. }
  76. ra.repository = repository
  77. }
  78. // Consume runs this PipelineItem on the next commit data.
  79. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  80. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  81. // This function returns the mapping with analysis results. The keys must be the same as
  82. // in Provides(). If there was an error, nil is returned.
  83. func (ra *RenameAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  84. changes := deps[DependencyTreeChanges].(object.Changes)
  85. cache := deps[DependencyBlobCache].(map[plumbing.Hash]*object.Blob)
  86. reducedChanges := make(object.Changes, 0, changes.Len())
  87. // Stage 1 - find renames by matching the hashes
  88. // n log(n)
  89. // We sort additions and deletions by hash and then do the single scan along
  90. // both slices.
  91. deleted := make(sortableChanges, 0, changes.Len())
  92. added := make(sortableChanges, 0, changes.Len())
  93. for _, change := range changes {
  94. action, err := change.Action()
  95. if err != nil {
  96. return nil, err
  97. }
  98. switch action {
  99. case merkletrie.Insert:
  100. added = append(added, sortableChange{change, change.To.TreeEntry.Hash})
  101. case merkletrie.Delete:
  102. deleted = append(deleted, sortableChange{change, change.From.TreeEntry.Hash})
  103. case merkletrie.Modify:
  104. reducedChanges = append(reducedChanges, change)
  105. }
  106. }
  107. sort.Sort(deleted)
  108. sort.Sort(added)
  109. a := 0
  110. d := 0
  111. stillDeleted := make(object.Changes, 0, deleted.Len())
  112. stillAdded := make(object.Changes, 0, added.Len())
  113. for a < added.Len() && d < deleted.Len() {
  114. if added[a].hash == deleted[d].hash {
  115. reducedChanges = append(
  116. reducedChanges,
  117. &object.Change{From: deleted[d].change.From, To: added[a].change.To})
  118. a++
  119. d++
  120. } else if added[a].Less(&deleted[d]) {
  121. stillAdded = append(stillAdded, added[a].change)
  122. a++
  123. } else {
  124. stillDeleted = append(stillDeleted, deleted[d].change)
  125. d++
  126. }
  127. }
  128. for ; a < added.Len(); a++ {
  129. stillAdded = append(stillAdded, added[a].change)
  130. }
  131. for ; d < deleted.Len(); d++ {
  132. stillDeleted = append(stillDeleted, deleted[d].change)
  133. }
  134. // Stage 2 - apply the similarity threshold
  135. // n^2 but actually linear
  136. // We sort the blobs by size and do the single linear scan.
  137. addedBlobs := make(sortableBlobs, 0, stillAdded.Len())
  138. deletedBlobs := make(sortableBlobs, 0, stillDeleted.Len())
  139. for _, change := range stillAdded {
  140. blob := cache[change.To.TreeEntry.Hash]
  141. addedBlobs = append(
  142. addedBlobs, sortableBlob{change: change, size: blob.Size})
  143. }
  144. for _, change := range stillDeleted {
  145. blob := cache[change.From.TreeEntry.Hash]
  146. deletedBlobs = append(
  147. deletedBlobs, sortableBlob{change: change, size: blob.Size})
  148. }
  149. sort.Sort(addedBlobs)
  150. sort.Sort(deletedBlobs)
  151. dStart := 0
  152. for a = 0; a < addedBlobs.Len(); a++ {
  153. myBlob := cache[addedBlobs[a].change.To.TreeEntry.Hash]
  154. mySize := addedBlobs[a].size
  155. for d = dStart; d < deletedBlobs.Len() && !ra.sizesAreClose(mySize, deletedBlobs[d].size); d++ {
  156. }
  157. dStart = d
  158. foundMatch := false
  159. for d = dStart; d < deletedBlobs.Len() && ra.sizesAreClose(mySize, deletedBlobs[d].size); d++ {
  160. blobsAreClose, err := ra.blobsAreClose(
  161. myBlob, cache[deletedBlobs[d].change.From.TreeEntry.Hash])
  162. if err != nil {
  163. return nil, err
  164. }
  165. if blobsAreClose {
  166. foundMatch = true
  167. reducedChanges = append(
  168. reducedChanges,
  169. &object.Change{From: deletedBlobs[d].change.From,
  170. To: addedBlobs[a].change.To})
  171. break
  172. }
  173. }
  174. if foundMatch {
  175. addedBlobs = append(addedBlobs[:a], addedBlobs[a+1:]...)
  176. a--
  177. deletedBlobs = append(deletedBlobs[:d], deletedBlobs[d+1:]...)
  178. }
  179. }
  180. // Stage 3 - we give up, everything left are independent additions and deletions
  181. for _, blob := range addedBlobs {
  182. reducedChanges = append(reducedChanges, blob.change)
  183. }
  184. for _, blob := range deletedBlobs {
  185. reducedChanges = append(reducedChanges, blob.change)
  186. }
  187. return map[string]interface{}{DependencyTreeChanges: reducedChanges}, nil
  188. }
  189. // Fork clones this PipelineItem.
  190. func (ra *RenameAnalysis) Fork(n int) []core.PipelineItem {
  191. return core.ForkSamePipelineItem(ra, n)
  192. }
  193. func (ra *RenameAnalysis) sizesAreClose(size1 int64, size2 int64) bool {
  194. return internal.Abs64(size1-size2)*100/internal.Max64(1, internal.Min64(size1, size2)) <=
  195. int64(100-ra.SimilarityThreshold)
  196. }
  197. func (ra *RenameAnalysis) blobsAreClose(
  198. blob1 *object.Blob, blob2 *object.Blob) (bool, error) {
  199. strFrom, err := BlobToString(blob1)
  200. if err != nil {
  201. return false, err
  202. }
  203. strTo, err := BlobToString(blob2)
  204. if err != nil {
  205. return false, err
  206. }
  207. dmp := diffmatchpatch.New()
  208. src, dst, _ := dmp.DiffLinesToRunes(strFrom, strTo)
  209. diffs := dmp.DiffMainRunes(src, dst, false)
  210. common := 0
  211. for _, edit := range diffs {
  212. if edit.Type == diffmatchpatch.DiffEqual {
  213. common += utf8.RuneCountInString(edit.Text)
  214. }
  215. }
  216. similarity := common * 100 / internal.Max(1, internal.Min(len(src), len(dst)))
  217. return similarity >= ra.SimilarityThreshold, nil
  218. }
  219. type sortableChange struct {
  220. change *object.Change
  221. hash plumbing.Hash
  222. }
  223. type sortableChanges []sortableChange
  224. func (change *sortableChange) Less(other *sortableChange) bool {
  225. for x := 0; x < 20; x++ {
  226. if change.hash[x] < other.hash[x] {
  227. return true
  228. }
  229. }
  230. return false
  231. }
  232. func (slice sortableChanges) Len() int {
  233. return len(slice)
  234. }
  235. func (slice sortableChanges) Less(i, j int) bool {
  236. return slice[i].Less(&slice[j])
  237. }
  238. func (slice sortableChanges) Swap(i, j int) {
  239. slice[i], slice[j] = slice[j], slice[i]
  240. }
  241. type sortableBlob struct {
  242. change *object.Change
  243. size int64
  244. }
  245. type sortableBlobs []sortableBlob
  246. func (change *sortableBlob) Less(other *sortableBlob) bool {
  247. return change.size < other.size
  248. }
  249. func (slice sortableBlobs) Len() int {
  250. return len(slice)
  251. }
  252. func (slice sortableBlobs) Less(i, j int) bool {
  253. return slice[i].Less(&slice[j])
  254. }
  255. func (slice sortableBlobs) Swap(i, j int) {
  256. slice[i], slice[j] = slice[j], slice[i]
  257. }
  258. func init() {
  259. core.Registry.Register(&RenameAnalysis{})
  260. }