couples.go 20 KB

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