couples.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. package leaves
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "sort"
  7. "github.com/gogo/protobuf/proto"
  8. "gopkg.in/src-d/go-git.v4"
  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.v10/internal/core"
  12. "gopkg.in/src-d/hercules.v10/internal/pb"
  13. items "gopkg.in/src-d/hercules.v10/internal/plumbing"
  14. "gopkg.in/src-d/hercules.v10/internal/plumbing/identity"
  15. "gopkg.in/src-d/hercules.v10/internal/yaml"
  16. )
  17. // CouplesAnalysis calculates the number of common commits for files and authors.
  18. // The results are matrices, where cell at row X and column Y is the number of commits which
  19. // changed X and Y together. In case with people, the numbers are summed for every common file.
  20. type CouplesAnalysis struct {
  21. core.NoopMerger
  22. core.OneShotMergeProcessor
  23. // PeopleNumber is the number of developers for which to build the matrix. 0 disables this analysis.
  24. PeopleNumber int
  25. // people store how many times every developer committed to every file.
  26. people []map[string]int
  27. // peopleCommits is the number of commits each author made.
  28. peopleCommits []int
  29. // files store every file occurred in the same commit with every other file.
  30. files map[string]map[string]int
  31. // renames point from new file name to old file name.
  32. renames *[]rename
  33. // lastCommit is the last commit which was consumed.
  34. lastCommit *object.Commit
  35. // reversedPeopleDict references IdentityDetector.ReversedPeopleDict
  36. reversedPeopleDict []string
  37. l core.Logger
  38. }
  39. // CouplesResult is returned by CouplesAnalysis.Finalize() and carries couples matrices from
  40. // authors and files.
  41. type CouplesResult struct {
  42. // PeopleMatrix is how many times developers changed files which were also changed by other developers.
  43. // The mapping's key is the other developer, and the value is the sum over all the files both developers changed.
  44. // Each element of that sum is min(C1, C2) where Ci is the number of commits developer i made which touched the file.
  45. PeopleMatrix []map[int]int64
  46. // PeopleFiles is how many times developers changed files. The first dimension (left []) is developers,
  47. // and the second dimension (right []) is file indexes.
  48. PeopleFiles [][]int
  49. // FilesMatrix is how many times file pairs occurred in the same commit.
  50. FilesMatrix []map[int]int64
  51. // FilesLines is the number of lines contained in each file from the last analyzed commit.
  52. FilesLines []int
  53. // Files is the names of the files. The order matches PeopleFiles' indexes and FilesMatrix.
  54. Files []string
  55. // reversedPeopleDict references IdentityDetector.ReversedPeopleDict
  56. reversedPeopleDict []string
  57. }
  58. const (
  59. // CouplesMaximumMeaningfulContextSize is the threshold on the number of files in a commit to
  60. // consider them as grouped together.
  61. CouplesMaximumMeaningfulContextSize = 1000
  62. )
  63. type rename struct {
  64. FromName string
  65. ToName string
  66. }
  67. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  68. func (couples *CouplesAnalysis) Name() string {
  69. return "Couples"
  70. }
  71. // Provides returns the list of names of entities which are produced by this PipelineItem.
  72. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  73. // to this list. Also used by core.Registry to build the global map of providers.
  74. func (couples *CouplesAnalysis) Provides() []string {
  75. return []string{}
  76. }
  77. // Requires returns the list of names of entities which are needed by this PipelineItem.
  78. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  79. // entities are Provides() upstream.
  80. func (couples *CouplesAnalysis) Requires() []string {
  81. arr := [...]string{identity.DependencyAuthor, items.DependencyTreeChanges}
  82. return arr[:]
  83. }
  84. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  85. func (couples *CouplesAnalysis) ListConfigurationOptions() []core.ConfigurationOption {
  86. return []core.ConfigurationOption{}
  87. }
  88. // Configure sets the properties previously published by ListConfigurationOptions().
  89. func (couples *CouplesAnalysis) Configure(facts map[string]interface{}) error {
  90. if l, exists := facts[core.ConfigLogger].(core.Logger); exists {
  91. couples.l = l
  92. }
  93. if val, exists := facts[identity.FactIdentityDetectorPeopleCount].(int); exists {
  94. couples.PeopleNumber = val
  95. couples.reversedPeopleDict = facts[identity.FactIdentityDetectorReversedPeopleDict].([]string)
  96. }
  97. return nil
  98. }
  99. // Flag for the command line switch which enables this analysis.
  100. func (couples *CouplesAnalysis) Flag() string {
  101. return "couples"
  102. }
  103. // Description returns the text which explains what the analysis is doing.
  104. func (couples *CouplesAnalysis) Description() string {
  105. return "The result is a square matrix, the value in each cell corresponds to the number " +
  106. "of times the pair of files appeared in the same commit or pair of developers " +
  107. "committed to the same file."
  108. }
  109. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  110. // calls. The repository which is going to be analysed is supplied as an argument.
  111. func (couples *CouplesAnalysis) Initialize(repository *git.Repository) error {
  112. couples.l = core.NewLogger()
  113. couples.people = make([]map[string]int, couples.PeopleNumber+1)
  114. for i := range couples.people {
  115. couples.people[i] = map[string]int{}
  116. }
  117. couples.peopleCommits = make([]int, couples.PeopleNumber+1)
  118. couples.files = map[string]map[string]int{}
  119. couples.renames = &[]rename{}
  120. couples.OneShotMergeProcessor.Initialize()
  121. return nil
  122. }
  123. // Consume runs this PipelineItem on the next commit data.
  124. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  125. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  126. // This function returns the mapping with analysis results. The keys must be the same as
  127. // in Provides(). If there was an error, nil is returned.
  128. func (couples *CouplesAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  129. firstMerge := couples.ShouldConsumeCommit(deps)
  130. mergeMode := deps[core.DependencyIsMerge].(bool)
  131. couples.lastCommit = deps[core.DependencyCommit].(*object.Commit)
  132. author := deps[identity.DependencyAuthor].(int)
  133. if author == identity.AuthorMissing {
  134. author = couples.PeopleNumber
  135. }
  136. if firstMerge {
  137. couples.peopleCommits[author]++
  138. }
  139. treeDiff := deps[items.DependencyTreeChanges].(object.Changes)
  140. context := make([]string, 0, len(treeDiff))
  141. for _, change := range treeDiff {
  142. action, err := change.Action()
  143. if err != nil {
  144. return nil, err
  145. }
  146. toName := change.To.Name
  147. fromName := change.From.Name
  148. switch action {
  149. case merkletrie.Insert:
  150. if !mergeMode || couples.files[toName] == nil {
  151. context = append(context, toName)
  152. couples.people[author][toName]++
  153. }
  154. case merkletrie.Delete:
  155. if !mergeMode {
  156. couples.people[author][fromName]++
  157. }
  158. case merkletrie.Modify:
  159. if fromName != toName {
  160. // renamed
  161. *couples.renames = append(
  162. *couples.renames, rename{ToName: toName, FromName: fromName})
  163. }
  164. if !mergeMode || couples.files[toName] == nil {
  165. context = append(context, toName)
  166. couples.people[author][toName]++
  167. }
  168. }
  169. }
  170. if len(context) <= CouplesMaximumMeaningfulContextSize {
  171. for _, file := range context {
  172. for _, otherFile := range context {
  173. lane, exists := couples.files[file]
  174. if !exists {
  175. lane = map[string]int{}
  176. couples.files[file] = lane
  177. }
  178. lane[otherFile]++
  179. }
  180. }
  181. }
  182. return nil, nil
  183. }
  184. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  185. func (couples *CouplesAnalysis) Finalize() interface{} {
  186. files, people := couples.propagateRenames(couples.currentFiles())
  187. filesSequence := make([]string, len(files))
  188. i := 0
  189. for file := range files {
  190. filesSequence[i] = file
  191. i++
  192. }
  193. sort.Strings(filesSequence)
  194. filesIndex := map[string]int{}
  195. for i, file := range filesSequence {
  196. filesIndex[file] = i
  197. }
  198. filesLines := make([]int, len(filesSequence))
  199. for i, name := range filesSequence {
  200. file, err := couples.lastCommit.File(name)
  201. if err != nil {
  202. log.Panicf("cannot find file %s in commit %s: %v",
  203. name, couples.lastCommit.Hash.String(), err)
  204. }
  205. blob := items.CachedBlob{Blob: file.Blob}
  206. err = blob.Cache()
  207. if err != nil {
  208. log.Panicf("cannot read blob %s of file %s: %v",
  209. blob.Hash.String(), name, err)
  210. }
  211. filesLines[i], _ = blob.CountLines()
  212. }
  213. peopleMatrix := make([]map[int]int64, couples.PeopleNumber+1)
  214. peopleFiles := make([][]int, couples.PeopleNumber+1)
  215. for i := range peopleMatrix {
  216. peopleMatrix[i] = map[int]int64{}
  217. for file, commits := range people[i] {
  218. if fi, exists := filesIndex[file]; exists {
  219. peopleFiles[i] = append(peopleFiles[i], fi)
  220. }
  221. for j, otherFiles := range people {
  222. otherCommits := otherFiles[file]
  223. delta := otherCommits
  224. if otherCommits > commits {
  225. delta = commits
  226. }
  227. if delta > 0 {
  228. peopleMatrix[i][j] += int64(delta)
  229. }
  230. }
  231. }
  232. sort.Ints(peopleFiles[i])
  233. }
  234. filesMatrix := make([]map[int]int64, len(filesIndex))
  235. for i := range filesMatrix {
  236. filesMatrix[i] = map[int]int64{}
  237. for otherFile, cooccs := range files[filesSequence[i]] {
  238. filesMatrix[i][filesIndex[otherFile]] = int64(cooccs)
  239. }
  240. }
  241. return CouplesResult{
  242. PeopleMatrix: peopleMatrix,
  243. PeopleFiles: peopleFiles,
  244. Files: filesSequence,
  245. FilesLines: filesLines,
  246. FilesMatrix: filesMatrix,
  247. reversedPeopleDict: couples.reversedPeopleDict,
  248. }
  249. }
  250. // Fork clones this pipeline item.
  251. func (couples *CouplesAnalysis) Fork(n int) []core.PipelineItem {
  252. return core.ForkCopyPipelineItem(couples, n)
  253. }
  254. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  255. // The text format is YAML and the bytes format is Protocol Buffers.
  256. func (couples *CouplesAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  257. couplesResult := result.(CouplesResult)
  258. if binary {
  259. return couples.serializeBinary(&couplesResult, writer)
  260. }
  261. couples.serializeText(&couplesResult, writer)
  262. return nil
  263. }
  264. // Deserialize converts the specified protobuf bytes to CouplesResult.
  265. func (couples *CouplesAnalysis) Deserialize(pbmessage []byte) (interface{}, error) {
  266. message := pb.CouplesAnalysisResults{}
  267. err := proto.Unmarshal(pbmessage, &message)
  268. if err != nil {
  269. return nil, err
  270. }
  271. result := CouplesResult{
  272. Files: message.FileCouples.Index,
  273. FilesLines: make([]int, len(message.FileCouples.Index)),
  274. FilesMatrix: make([]map[int]int64, message.FileCouples.Matrix.NumberOfRows),
  275. PeopleFiles: make([][]int, len(message.PeopleCouples.Index)),
  276. PeopleMatrix: make([]map[int]int64, message.PeopleCouples.Matrix.NumberOfRows),
  277. reversedPeopleDict: message.PeopleCouples.Index,
  278. }
  279. for i, files := range message.PeopleFiles {
  280. result.PeopleFiles[i] = make([]int, len(files.Files))
  281. for j, val := range files.Files {
  282. result.PeopleFiles[i][j] = int(val)
  283. }
  284. }
  285. if len(message.FileCouples.Index) != len(message.FilesLines) {
  286. log.Panicf("Couples PB message integrity violation: file_couples (%d) != file_lines (%d)",
  287. len(message.FileCouples.Index), len(message.FilesLines))
  288. }
  289. for i, v := range message.FilesLines {
  290. result.FilesLines[i] = int(v)
  291. }
  292. convertCSR := func(dest []map[int]int64, src *pb.CompressedSparseRowMatrix) {
  293. for indptr := range src.Indptr {
  294. if indptr == 0 {
  295. continue
  296. }
  297. dest[indptr-1] = map[int]int64{}
  298. for j := src.Indptr[indptr-1]; j < src.Indptr[indptr]; j++ {
  299. dest[indptr-1][int(src.Indices[j])] = src.Data[j]
  300. }
  301. }
  302. }
  303. convertCSR(result.FilesMatrix, message.FileCouples.Matrix)
  304. convertCSR(result.PeopleMatrix, message.PeopleCouples.Matrix)
  305. return result, nil
  306. }
  307. // MergeResults combines two CouplesAnalysis-s together.
  308. func (couples *CouplesAnalysis) MergeResults(r1, r2 interface{}, c1, c2 *core.CommonAnalysisResult) interface{} {
  309. cr1 := r1.(CouplesResult)
  310. cr2 := r2.(CouplesResult)
  311. merged := CouplesResult{}
  312. var people, files map[string][3]int
  313. id := identity.Detector{}
  314. people, merged.reversedPeopleDict = id.MergeReversedDicts(cr1.reversedPeopleDict, cr2.reversedPeopleDict)
  315. files, merged.Files = id.MergeReversedDicts(cr1.Files, cr2.Files)
  316. merged.FilesLines = make([]int, len(merged.Files))
  317. for i, name := range merged.Files {
  318. idxs := files[name]
  319. if idxs[1] >= 0 {
  320. merged.FilesLines[i] += cr1.FilesLines[idxs[1]]
  321. }
  322. if idxs[2] >= 0 {
  323. merged.FilesLines[i] += cr2.FilesLines[idxs[2]]
  324. }
  325. }
  326. merged.PeopleFiles = make([][]int, len(merged.reversedPeopleDict))
  327. peopleFilesDicts := make([]map[int]bool, len(merged.reversedPeopleDict))
  328. addPeopleFiles := func(peopleFiles [][]int, reversedPeopleDict []string,
  329. reversedFilesDict []string) {
  330. for pi, fs := range peopleFiles {
  331. idx := people[reversedPeopleDict[pi]][0]
  332. m := peopleFilesDicts[idx]
  333. if m == nil {
  334. m = map[int]bool{}
  335. peopleFilesDicts[idx] = m
  336. }
  337. for _, f := range fs {
  338. m[files[reversedFilesDict[f]][0]] = true
  339. }
  340. }
  341. }
  342. addPeopleFiles(cr1.PeopleFiles, cr1.reversedPeopleDict, cr1.Files)
  343. addPeopleFiles(cr2.PeopleFiles, cr2.reversedPeopleDict, cr2.Files)
  344. for i, m := range peopleFilesDicts {
  345. merged.PeopleFiles[i] = make([]int, len(m))
  346. j := 0
  347. for f := range m {
  348. merged.PeopleFiles[i][j] = f
  349. j++
  350. }
  351. sort.Ints(merged.PeopleFiles[i])
  352. }
  353. merged.PeopleMatrix = make([]map[int]int64, len(merged.reversedPeopleDict)+1)
  354. addPeople := func(peopleMatrix []map[int]int64, reversedPeopleDict []string) {
  355. for pi, pc := range peopleMatrix {
  356. var idx int
  357. if pi < len(reversedPeopleDict) {
  358. idx = people[reversedPeopleDict[pi]][0]
  359. } else {
  360. idx = len(merged.reversedPeopleDict)
  361. }
  362. m := merged.PeopleMatrix[idx]
  363. if m == nil {
  364. m = map[int]int64{}
  365. merged.PeopleMatrix[idx] = m
  366. }
  367. for otherDev, val := range pc {
  368. var otherIdx int
  369. if otherDev < len(reversedPeopleDict) {
  370. otherIdx = people[reversedPeopleDict[otherDev]][0]
  371. } else {
  372. otherIdx = len(merged.reversedPeopleDict)
  373. }
  374. m[otherIdx] += val
  375. }
  376. }
  377. }
  378. addPeople(cr1.PeopleMatrix, cr1.reversedPeopleDict)
  379. addPeople(cr2.PeopleMatrix, cr2.reversedPeopleDict)
  380. merged.FilesMatrix = make([]map[int]int64, len(merged.Files))
  381. addFiles := func(filesMatrix []map[int]int64, reversedFilesDict []string) {
  382. for fi, fc := range filesMatrix {
  383. idx := people[reversedFilesDict[fi]][0]
  384. m := merged.FilesMatrix[idx]
  385. if m == nil {
  386. m = map[int]int64{}
  387. merged.FilesMatrix[idx] = m
  388. }
  389. for file, val := range fc {
  390. m[files[reversedFilesDict[file]][0]] += val
  391. }
  392. }
  393. }
  394. addFiles(cr1.FilesMatrix, cr1.Files)
  395. addFiles(cr2.FilesMatrix, cr2.Files)
  396. return merged
  397. }
  398. func (couples *CouplesAnalysis) serializeText(result *CouplesResult, writer io.Writer) {
  399. fmt.Fprintln(writer, " files_coocc:")
  400. fmt.Fprintln(writer, " index:")
  401. for _, file := range result.Files {
  402. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(file))
  403. }
  404. fmt.Fprintln(writer, " lines:")
  405. for _, l := range result.FilesLines {
  406. fmt.Fprintf(writer, " - %d\n", l)
  407. }
  408. fmt.Fprintln(writer, " matrix:")
  409. for _, files := range result.FilesMatrix {
  410. fmt.Fprint(writer, " - {")
  411. var indices []int
  412. for file := range files {
  413. indices = append(indices, file)
  414. }
  415. sort.Ints(indices)
  416. for i, file := range indices {
  417. fmt.Fprintf(writer, "%d: %d", file, files[file])
  418. if i < len(indices)-1 {
  419. fmt.Fprint(writer, ", ")
  420. }
  421. }
  422. fmt.Fprintln(writer, "}")
  423. }
  424. fmt.Fprintln(writer, " people_coocc:")
  425. fmt.Fprintln(writer, " index:")
  426. for _, person := range result.reversedPeopleDict {
  427. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(person))
  428. }
  429. fmt.Fprintln(writer, " matrix:")
  430. for _, people := range result.PeopleMatrix {
  431. fmt.Fprint(writer, " - {")
  432. var indices []int
  433. for file := range people {
  434. indices = append(indices, file)
  435. }
  436. sort.Ints(indices)
  437. for i, person := range indices {
  438. fmt.Fprintf(writer, "%d: %d", person, people[person])
  439. if i < len(indices)-1 {
  440. fmt.Fprint(writer, ", ")
  441. }
  442. }
  443. fmt.Fprintln(writer, "}")
  444. }
  445. fmt.Fprintln(writer, " author_files:") // sorted by number of files each author changed
  446. peopleFiles := sortByNumberOfFiles(result.PeopleFiles, result.reversedPeopleDict, result.Files)
  447. for _, authorFiles := range peopleFiles {
  448. fmt.Fprintf(writer, " - %s:\n", yaml.SafeString(authorFiles.Author))
  449. sort.Strings(authorFiles.Files)
  450. for _, file := range authorFiles.Files {
  451. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(file)) // sorted by path
  452. }
  453. }
  454. }
  455. func sortByNumberOfFiles(
  456. peopleFiles [][]int, peopleDict []string, filesDict []string) authorFilesList {
  457. var pfl authorFilesList
  458. for peopleIdx, files := range peopleFiles {
  459. if peopleIdx < len(peopleDict) {
  460. fileNames := make([]string, len(files))
  461. for i, fi := range files {
  462. fileNames[i] = filesDict[fi]
  463. }
  464. pfl = append(pfl, authorFiles{peopleDict[peopleIdx], fileNames})
  465. }
  466. }
  467. sort.Sort(pfl)
  468. return pfl
  469. }
  470. type authorFiles struct {
  471. Author string
  472. Files []string
  473. }
  474. type authorFilesList []authorFiles
  475. func (s authorFilesList) Len() int {
  476. return len(s)
  477. }
  478. func (s authorFilesList) Swap(i, j int) {
  479. s[i], s[j] = s[j], s[i]
  480. }
  481. func (s authorFilesList) Less(i, j int) bool {
  482. return len(s[i].Files) < len(s[j].Files)
  483. }
  484. func (couples *CouplesAnalysis) serializeBinary(result *CouplesResult, writer io.Writer) error {
  485. message := pb.CouplesAnalysisResults{}
  486. message.FileCouples = &pb.Couples{
  487. Index: result.Files,
  488. Matrix: pb.MapToCompressedSparseRowMatrix(result.FilesMatrix),
  489. }
  490. message.PeopleCouples = &pb.Couples{
  491. Index: result.reversedPeopleDict,
  492. Matrix: pb.MapToCompressedSparseRowMatrix(result.PeopleMatrix),
  493. }
  494. message.PeopleFiles = make([]*pb.TouchedFiles, len(result.reversedPeopleDict))
  495. for key := range result.reversedPeopleDict {
  496. files := result.PeopleFiles[key]
  497. int32Files := make([]int32, len(files))
  498. for i, f := range files {
  499. int32Files[i] = int32(f)
  500. }
  501. message.PeopleFiles[key] = &pb.TouchedFiles{
  502. Files: int32Files,
  503. }
  504. }
  505. message.FilesLines = make([]int32, len(result.FilesLines))
  506. for i, l := range result.FilesLines {
  507. message.FilesLines[i] = int32(l)
  508. }
  509. serialized, err := proto.Marshal(&message)
  510. if err != nil {
  511. return err
  512. }
  513. _, err = writer.Write(serialized)
  514. return err
  515. }
  516. // currentFiles return the list of files in the last consumed commit.
  517. func (couples *CouplesAnalysis) currentFiles() map[string]bool {
  518. files := map[string]bool{}
  519. if couples.lastCommit == nil {
  520. for key := range couples.files {
  521. files[key] = true
  522. }
  523. }
  524. tree, _ := couples.lastCommit.Tree()
  525. fileIter := tree.Files()
  526. fileIter.ForEach(func(fobj *object.File) error {
  527. files[fobj.Name] = true
  528. return nil
  529. })
  530. return files
  531. }
  532. // propagateRenames applies `renames` over the files from `lastCommit`.
  533. func (couples *CouplesAnalysis) propagateRenames(files map[string]bool) (
  534. map[string]map[string]int, []map[string]int) {
  535. renames := *couples.renames
  536. reducedFiles := map[string]map[string]int{}
  537. for file := range files {
  538. fmap := map[string]int{}
  539. refmap := couples.files[file]
  540. for other := range files {
  541. refval := refmap[other]
  542. if refval > 0 {
  543. fmap[other] = refval
  544. }
  545. }
  546. if len(fmap) > 0 {
  547. reducedFiles[file] = fmap
  548. }
  549. }
  550. // propagate renames
  551. aliases := map[string]map[string]bool{}
  552. pointers := map[string]string{}
  553. for i := range renames {
  554. rename := renames[len(renames)-i-1]
  555. toName := rename.ToName
  556. if newTo, exists := pointers[toName]; exists {
  557. toName = newTo
  558. }
  559. if _, exists := reducedFiles[toName]; exists {
  560. if rename.FromName != toName {
  561. var set map[string]bool
  562. if set, exists = aliases[toName]; !exists {
  563. set = map[string]bool{}
  564. aliases[toName] = set
  565. }
  566. set[rename.FromName] = true
  567. pointers[rename.FromName] = toName
  568. }
  569. continue
  570. }
  571. }
  572. adjustments := map[string]map[string]int{}
  573. for final, set := range aliases {
  574. adjustment := map[string]int{}
  575. for alias := range set {
  576. for k, v := range couples.files[alias] {
  577. adjustment[k] += v
  578. }
  579. }
  580. adjustments[final] = adjustment
  581. }
  582. for _, adjustment := range adjustments {
  583. for final, set := range aliases {
  584. for alias := range set {
  585. adjustment[final] += adjustment[alias]
  586. delete(adjustment, alias)
  587. }
  588. }
  589. }
  590. for final, adjustment := range adjustments {
  591. for key, val := range adjustment {
  592. if coocc, exists := reducedFiles[final][key]; exists {
  593. reducedFiles[final][key] = coocc + val
  594. reducedFiles[key][final] = coocc + val
  595. }
  596. }
  597. }
  598. people := make([]map[string]int, len(couples.people))
  599. for i, counts := range couples.people {
  600. reducedCounts := map[string]int{}
  601. people[i] = reducedCounts
  602. for file := range files {
  603. count := counts[file]
  604. for alias := range aliases[file] {
  605. count += counts[alias]
  606. }
  607. if count > 0 {
  608. reducedCounts[file] = count
  609. }
  610. }
  611. for key, val := range counts {
  612. if _, exists := files[key]; !exists {
  613. if _, exists = pointers[key]; !exists {
  614. reducedCounts[key] = val
  615. }
  616. }
  617. }
  618. }
  619. return reducedFiles, people
  620. }
  621. func init() {
  622. core.Registry.Register(&CouplesAnalysis{})
  623. }