renames.go 8.9 KB

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