renames.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. type RenameAnalysis struct {
  14. // SimilarityThreshold adjusts the heuristic to determine file renames.
  15. // It has the same units as cgit's -X rename-threshold or -M. Better to
  16. // set it to the default value of 90 (90%).
  17. SimilarityThreshold int
  18. repository *git.Repository
  19. }
  20. const (
  21. ConfigRenameAnalysisSimilarityThreshold = "RenameAnalysis.SimilarityThreshold"
  22. )
  23. func (ra *RenameAnalysis) Name() string {
  24. return "RenameAnalysis"
  25. }
  26. func (ra *RenameAnalysis) Provides() []string {
  27. arr := [...]string{"changes"}
  28. return arr[:]
  29. }
  30. func (ra *RenameAnalysis) Requires() []string {
  31. arr := [...]string{"blob_cache", "changes"}
  32. return arr[:]
  33. }
  34. func (ra *RenameAnalysis) ListConfigurationOptions() []ConfigurationOption {
  35. options := [...]ConfigurationOption{{
  36. Name: ConfigBurndownGranularity,
  37. Description: "How many days there are in a single band.",
  38. Flag: "M",
  39. Type: IntConfigurationOption,
  40. Default: 90},
  41. }
  42. return options[:]
  43. }
  44. func (ra *RenameAnalysis) Configure(facts map[string]interface{}) {
  45. if val, exists := facts[ConfigRenameAnalysisSimilarityThreshold].(int); exists {
  46. ra.SimilarityThreshold = val
  47. }
  48. }
  49. func (ra *RenameAnalysis) Initialize(repository *git.Repository) {
  50. if ra.SimilarityThreshold < 0 || ra.SimilarityThreshold > 100 {
  51. fmt.Fprintln(os.Stderr, "Warning: adjusted the similarity threshold to 90")
  52. ra.SimilarityThreshold = 90
  53. }
  54. ra.repository = repository
  55. }
  56. func (ra *RenameAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  57. changes := deps["changes"].(object.Changes)
  58. cache := deps["blob_cache"].(map[plumbing.Hash]*object.Blob)
  59. reduced_changes := make(object.Changes, 0, changes.Len())
  60. // Stage 1 - find renames by matching the hashes
  61. // n log(n)
  62. // We sort additions and deletions by hash and then do the single scan along
  63. // both slices.
  64. deleted := make(sortableChanges, 0, changes.Len())
  65. added := make(sortableChanges, 0, changes.Len())
  66. for _, change := range changes {
  67. action, err := change.Action()
  68. if err != nil {
  69. return nil, err
  70. }
  71. switch action {
  72. case merkletrie.Insert:
  73. added = append(added, sortableChange{change, change.To.TreeEntry.Hash})
  74. case merkletrie.Delete:
  75. deleted = append(deleted, sortableChange{change, change.From.TreeEntry.Hash})
  76. case merkletrie.Modify:
  77. reduced_changes = append(reduced_changes, change)
  78. }
  79. }
  80. sort.Sort(deleted)
  81. sort.Sort(added)
  82. a := 0
  83. d := 0
  84. still_deleted := make(object.Changes, 0, deleted.Len())
  85. still_added := make(object.Changes, 0, added.Len())
  86. for a < added.Len() && d < deleted.Len() {
  87. if added[a].hash == deleted[d].hash {
  88. reduced_changes = append(
  89. reduced_changes,
  90. &object.Change{From: deleted[d].change.From, To: added[a].change.To})
  91. a++
  92. d++
  93. } else if added[a].Less(&deleted[d]) {
  94. still_added = append(still_added, added[a].change)
  95. a++
  96. } else {
  97. still_deleted = append(still_deleted, deleted[d].change)
  98. d++
  99. }
  100. }
  101. for ; a < added.Len(); a++ {
  102. still_added = append(still_added, added[a].change)
  103. }
  104. for ; d < deleted.Len(); d++ {
  105. still_deleted = append(still_deleted, deleted[d].change)
  106. }
  107. // Stage 2 - apply the similarity threshold
  108. // n^2 but actually linear
  109. // We sort the blobs by size and do the single linear scan.
  110. added_blobs := make(sortableBlobs, 0, still_added.Len())
  111. deleted_blobs := make(sortableBlobs, 0, still_deleted.Len())
  112. for _, change := range still_added {
  113. blob := cache[change.To.TreeEntry.Hash]
  114. added_blobs = append(
  115. added_blobs, sortableBlob{change: change, size: blob.Size})
  116. }
  117. for _, change := range still_deleted {
  118. blob := cache[change.From.TreeEntry.Hash]
  119. deleted_blobs = append(
  120. deleted_blobs, sortableBlob{change: change, size: blob.Size})
  121. }
  122. sort.Sort(added_blobs)
  123. sort.Sort(deleted_blobs)
  124. d_start := 0
  125. for a = 0; a < added_blobs.Len(); a++ {
  126. my_blob := cache[added_blobs[a].change.To.TreeEntry.Hash]
  127. my_size := added_blobs[a].size
  128. for d = d_start; d < deleted_blobs.Len() && !ra.sizesAreClose(my_size, deleted_blobs[d].size); d++ {
  129. }
  130. d_start = d
  131. found_match := false
  132. for d = d_start; d < deleted_blobs.Len() && ra.sizesAreClose(my_size, deleted_blobs[d].size); d++ {
  133. blobsAreClose, err := ra.blobsAreClose(
  134. my_blob, cache[deleted_blobs[d].change.From.TreeEntry.Hash])
  135. if err != nil {
  136. return nil, err
  137. }
  138. if blobsAreClose {
  139. found_match = true
  140. reduced_changes = append(
  141. reduced_changes,
  142. &object.Change{From: deleted_blobs[d].change.From,
  143. To: added_blobs[a].change.To})
  144. break
  145. }
  146. }
  147. if found_match {
  148. added_blobs = append(added_blobs[:a], added_blobs[a+1:]...)
  149. a--
  150. deleted_blobs = append(deleted_blobs[:d], deleted_blobs[d+1:]...)
  151. }
  152. }
  153. // Stage 3 - we give up, everything left are independent additions and deletions
  154. for _, blob := range added_blobs {
  155. reduced_changes = append(reduced_changes, blob.change)
  156. }
  157. for _, blob := range deleted_blobs {
  158. reduced_changes = append(reduced_changes, blob.change)
  159. }
  160. return map[string]interface{}{"changes": reduced_changes}, nil
  161. }
  162. func (ra *RenameAnalysis) sizesAreClose(size1 int64, size2 int64) bool {
  163. return abs64(size1-size2)*100/max64(1, min64(size1, size2)) <=
  164. int64(100-ra.SimilarityThreshold)
  165. }
  166. func (ra *RenameAnalysis) blobsAreClose(
  167. blob1 *object.Blob, blob2 *object.Blob) (bool, error) {
  168. str_from, err := blobToString(blob1)
  169. if err != nil {
  170. return false, err
  171. }
  172. str_to, err := blobToString(blob2)
  173. if err != nil {
  174. return false, err
  175. }
  176. dmp := diffmatchpatch.New()
  177. src, dst, _ := dmp.DiffLinesToRunes(str_from, str_to)
  178. diffs := dmp.DiffMainRunes(src, dst, false)
  179. common := 0
  180. for _, edit := range diffs {
  181. if edit.Type == diffmatchpatch.DiffEqual {
  182. common += utf8.RuneCountInString(edit.Text)
  183. }
  184. }
  185. return common*100/max(1, min(len(src), len(dst))) >= ra.SimilarityThreshold, nil
  186. }
  187. type sortableChange struct {
  188. change *object.Change
  189. hash plumbing.Hash
  190. }
  191. type sortableChanges []sortableChange
  192. func (change *sortableChange) Less(other *sortableChange) bool {
  193. for x := 0; x < 20; x++ {
  194. if change.hash[x] < other.hash[x] {
  195. return true
  196. }
  197. }
  198. return false
  199. }
  200. func (slice sortableChanges) Len() int {
  201. return len(slice)
  202. }
  203. func (slice sortableChanges) Less(i, j int) bool {
  204. return slice[i].Less(&slice[j])
  205. }
  206. func (slice sortableChanges) Swap(i, j int) {
  207. slice[i], slice[j] = slice[j], slice[i]
  208. }
  209. type sortableBlob struct {
  210. change *object.Change
  211. size int64
  212. }
  213. type sortableBlobs []sortableBlob
  214. func (change *sortableBlob) Less(other *sortableBlob) bool {
  215. return change.size < other.size
  216. }
  217. func (slice sortableBlobs) Len() int {
  218. return len(slice)
  219. }
  220. func (slice sortableBlobs) Less(i, j int) bool {
  221. return slice[i].Less(&slice[j])
  222. }
  223. func (slice sortableBlobs) Swap(i, j int) {
  224. slice[i], slice[j] = slice[j], slice[i]
  225. }
  226. func init() {
  227. Registry.Register(&RenameAnalysis{})
  228. }