renames.go 8.9 KB

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