couples.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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. }
  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.PeopleFiles[i] = make([]int, len(files.Files))
  276. for j, val := range files.Files {
  277. result.PeopleFiles[i][j] = int(val)
  278. }
  279. }
  280. if len(message.FileCouples.Index) != len(message.FilesLines) {
  281. log.Panicf("Couples PB message integrity violation: file_couples (%d) != file_lines (%d)",
  282. len(message.FileCouples.Index), len(message.FilesLines))
  283. }
  284. for i, v := range message.FilesLines {
  285. result.FilesLines[i] = int(v)
  286. }
  287. convertCSR := func(dest []map[int]int64, src *pb.CompressedSparseRowMatrix) {
  288. for indptr := range src.Indptr {
  289. if indptr == 0 {
  290. continue
  291. }
  292. dest[indptr-1] = map[int]int64{}
  293. for j := src.Indptr[indptr-1]; j < src.Indptr[indptr]; j++ {
  294. dest[indptr-1][int(src.Indices[j])] = src.Data[j]
  295. }
  296. }
  297. }
  298. convertCSR(result.FilesMatrix, message.FileCouples.Matrix)
  299. convertCSR(result.PeopleMatrix, message.PeopleCouples.Matrix)
  300. return result, nil
  301. }
  302. // MergeResults combines two CouplesAnalysis-s together.
  303. func (couples *CouplesAnalysis) MergeResults(r1, r2 interface{}, c1, c2 *core.CommonAnalysisResult) interface{} {
  304. cr1 := r1.(CouplesResult)
  305. cr2 := r2.(CouplesResult)
  306. merged := CouplesResult{}
  307. var people, files map[string][3]int
  308. id := identity.Detector{}
  309. people, merged.reversedPeopleDict = id.MergeReversedDicts(cr1.reversedPeopleDict, cr2.reversedPeopleDict)
  310. files, merged.Files = id.MergeReversedDicts(cr1.Files, cr2.Files)
  311. merged.FilesLines = make([]int, len(merged.Files))
  312. for i, name := range merged.Files {
  313. idxs := files[name]
  314. if idxs[1] >= 0 {
  315. merged.FilesLines[i] += cr1.FilesLines[idxs[1]]
  316. }
  317. if idxs[2] >= 0 {
  318. merged.FilesLines[i] += cr2.FilesLines[idxs[2]]
  319. }
  320. }
  321. merged.PeopleFiles = make([][]int, len(merged.reversedPeopleDict))
  322. peopleFilesDicts := make([]map[int]bool, len(merged.reversedPeopleDict))
  323. addPeopleFiles := func(peopleFiles [][]int, reversedPeopleDict []string,
  324. reversedFilesDict []string) {
  325. for pi, fs := range peopleFiles {
  326. idx := people[reversedPeopleDict[pi]][0]
  327. m := peopleFilesDicts[idx]
  328. if m == nil {
  329. m = map[int]bool{}
  330. peopleFilesDicts[idx] = m
  331. }
  332. for _, f := range fs {
  333. m[files[reversedFilesDict[f]][0]] = true
  334. }
  335. }
  336. }
  337. addPeopleFiles(cr1.PeopleFiles, cr1.reversedPeopleDict, cr1.Files)
  338. addPeopleFiles(cr2.PeopleFiles, cr2.reversedPeopleDict, cr2.Files)
  339. for i, m := range peopleFilesDicts {
  340. merged.PeopleFiles[i] = make([]int, len(m))
  341. j := 0
  342. for f := range m {
  343. merged.PeopleFiles[i][j] = f
  344. j++
  345. }
  346. sort.Ints(merged.PeopleFiles[i])
  347. }
  348. merged.PeopleMatrix = make([]map[int]int64, len(merged.reversedPeopleDict)+1)
  349. addPeople := func(peopleMatrix []map[int]int64, reversedPeopleDict []string) {
  350. for pi, pc := range peopleMatrix {
  351. var idx int
  352. if pi < len(reversedPeopleDict) {
  353. idx = people[reversedPeopleDict[pi]][0]
  354. } else {
  355. idx = len(merged.reversedPeopleDict)
  356. }
  357. m := merged.PeopleMatrix[idx]
  358. if m == nil {
  359. m = map[int]int64{}
  360. merged.PeopleMatrix[idx] = m
  361. }
  362. for otherDev, val := range pc {
  363. var otherIdx int
  364. if otherDev < len(reversedPeopleDict) {
  365. otherIdx = people[reversedPeopleDict[otherDev]][0]
  366. } else {
  367. otherIdx = len(merged.reversedPeopleDict)
  368. }
  369. m[otherIdx] += val
  370. }
  371. }
  372. }
  373. addPeople(cr1.PeopleMatrix, cr1.reversedPeopleDict)
  374. addPeople(cr2.PeopleMatrix, cr2.reversedPeopleDict)
  375. merged.FilesMatrix = make([]map[int]int64, len(merged.Files))
  376. addFiles := func(filesMatrix []map[int]int64, reversedFilesDict []string) {
  377. for fi, fc := range filesMatrix {
  378. idx := people[reversedFilesDict[fi]][0]
  379. m := merged.FilesMatrix[idx]
  380. if m == nil {
  381. m = map[int]int64{}
  382. merged.FilesMatrix[idx] = m
  383. }
  384. for file, val := range fc {
  385. m[files[reversedFilesDict[file]][0]] += val
  386. }
  387. }
  388. }
  389. addFiles(cr1.FilesMatrix, cr1.Files)
  390. addFiles(cr2.FilesMatrix, cr2.Files)
  391. return merged
  392. }
  393. func (couples *CouplesAnalysis) serializeText(result *CouplesResult, writer io.Writer) {
  394. fmt.Fprintln(writer, " files_coocc:")
  395. fmt.Fprintln(writer, " index:")
  396. for _, file := range result.Files {
  397. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(file))
  398. }
  399. fmt.Fprintln(writer, " lines:")
  400. for _, l := range result.FilesLines {
  401. fmt.Fprintf(writer, " - %d\n", l)
  402. }
  403. fmt.Fprintln(writer, " matrix:")
  404. for _, files := range result.FilesMatrix {
  405. fmt.Fprint(writer, " - {")
  406. var indices []int
  407. for file := range files {
  408. indices = append(indices, file)
  409. }
  410. sort.Ints(indices)
  411. for i, file := range indices {
  412. fmt.Fprintf(writer, "%d: %d", file, files[file])
  413. if i < len(indices)-1 {
  414. fmt.Fprint(writer, ", ")
  415. }
  416. }
  417. fmt.Fprintln(writer, "}")
  418. }
  419. fmt.Fprintln(writer, " people_coocc:")
  420. fmt.Fprintln(writer, " index:")
  421. for _, person := range result.reversedPeopleDict {
  422. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(person))
  423. }
  424. fmt.Fprintln(writer, " matrix:")
  425. for _, people := range result.PeopleMatrix {
  426. fmt.Fprint(writer, " - {")
  427. var indices []int
  428. for file := range people {
  429. indices = append(indices, file)
  430. }
  431. sort.Ints(indices)
  432. for i, person := range indices {
  433. fmt.Fprintf(writer, "%d: %d", person, people[person])
  434. if i < len(indices)-1 {
  435. fmt.Fprint(writer, ", ")
  436. }
  437. }
  438. fmt.Fprintln(writer, "}")
  439. }
  440. fmt.Fprintln(writer, " author_files:") // sorted by number of files each author changed
  441. peopleFiles := sortByNumberOfFiles(result.PeopleFiles, result.reversedPeopleDict, result.Files)
  442. for _, authorFiles := range peopleFiles {
  443. fmt.Fprintf(writer, " - %s:\n", yaml.SafeString(authorFiles.Author))
  444. sort.Strings(authorFiles.Files)
  445. for _, file := range authorFiles.Files {
  446. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(file)) // sorted by path
  447. }
  448. }
  449. }
  450. func sortByNumberOfFiles(
  451. peopleFiles [][]int, peopleDict []string, filesDict []string) authorFilesList {
  452. var pfl authorFilesList
  453. for peopleIdx, files := range peopleFiles {
  454. if peopleIdx < len(peopleDict) {
  455. fileNames := make([]string, len(files))
  456. for i, fi := range files {
  457. fileNames[i] = filesDict[fi]
  458. }
  459. pfl = append(pfl, authorFiles{peopleDict[peopleIdx], fileNames})
  460. }
  461. }
  462. sort.Sort(pfl)
  463. return pfl
  464. }
  465. type authorFiles struct {
  466. Author string
  467. Files []string
  468. }
  469. type authorFilesList []authorFiles
  470. func (s authorFilesList) Len() int {
  471. return len(s)
  472. }
  473. func (s authorFilesList) Swap(i, j int) {
  474. s[i], s[j] = s[j], s[i]
  475. }
  476. func (s authorFilesList) Less(i, j int) bool {
  477. return len(s[i].Files) < len(s[j].Files)
  478. }
  479. func (couples *CouplesAnalysis) serializeBinary(result *CouplesResult, writer io.Writer) error {
  480. message := pb.CouplesAnalysisResults{}
  481. message.FileCouples = &pb.Couples{
  482. Index: result.Files,
  483. Matrix: pb.MapToCompressedSparseRowMatrix(result.FilesMatrix),
  484. }
  485. message.PeopleCouples = &pb.Couples{
  486. Index: result.reversedPeopleDict,
  487. Matrix: pb.MapToCompressedSparseRowMatrix(result.PeopleMatrix),
  488. }
  489. message.PeopleFiles = make([]*pb.TouchedFiles, len(result.reversedPeopleDict))
  490. for key := range result.reversedPeopleDict {
  491. files := result.PeopleFiles[key]
  492. int32Files := make([]int32, len(files))
  493. for i, f := range files {
  494. int32Files[i] = int32(f)
  495. }
  496. message.PeopleFiles[key] = &pb.TouchedFiles{
  497. Files: int32Files,
  498. }
  499. }
  500. message.FilesLines = make([]int32, len(result.FilesLines))
  501. for i, l := range result.FilesLines {
  502. message.FilesLines[i] = int32(l)
  503. }
  504. serialized, err := proto.Marshal(&message)
  505. if err != nil {
  506. return err
  507. }
  508. _, err = writer.Write(serialized)
  509. return err
  510. }
  511. // currentFiles return the list of files in the last consumed commit.
  512. func (couples *CouplesAnalysis) currentFiles() map[string]bool {
  513. files := map[string]bool{}
  514. if couples.lastCommit == nil {
  515. for key := range couples.files {
  516. files[key] = true
  517. }
  518. }
  519. tree, _ := couples.lastCommit.Tree()
  520. fileIter := tree.Files()
  521. fileIter.ForEach(func(fobj *object.File) error {
  522. files[fobj.Name] = true
  523. return nil
  524. })
  525. return files
  526. }
  527. // propagateRenames applies `renames` over the files from `lastCommit`.
  528. func (couples *CouplesAnalysis) propagateRenames(files map[string]bool) (
  529. map[string]map[string]int, []map[string]int) {
  530. renames := *couples.renames
  531. reducedFiles := map[string]map[string]int{}
  532. for file := range files {
  533. fmap := map[string]int{}
  534. refmap := couples.files[file]
  535. for other := range files {
  536. refval := refmap[other]
  537. if refval > 0 {
  538. fmap[other] = refval
  539. }
  540. }
  541. if len(fmap) > 0 {
  542. reducedFiles[file] = fmap
  543. }
  544. }
  545. // propagate renames
  546. aliases := map[string]map[string]bool{}
  547. pointers := map[string]string{}
  548. for i := range renames {
  549. rename := renames[len(renames)-i-1]
  550. toName := rename.ToName
  551. if newTo, exists := pointers[toName]; exists {
  552. toName = newTo
  553. }
  554. if _, exists := reducedFiles[toName]; exists {
  555. if rename.FromName != toName {
  556. var set map[string]bool
  557. if set, exists = aliases[toName]; !exists {
  558. set = map[string]bool{}
  559. aliases[toName] = set
  560. }
  561. set[rename.FromName] = true
  562. pointers[rename.FromName] = toName
  563. }
  564. continue
  565. }
  566. }
  567. adjustments := map[string]map[string]int{}
  568. for final, set := range aliases {
  569. adjustment := map[string]int{}
  570. for alias := range set {
  571. for k, v := range couples.files[alias] {
  572. adjustment[k] += v
  573. }
  574. }
  575. adjustments[final] = adjustment
  576. }
  577. for _, adjustment := range adjustments {
  578. for final, set := range aliases {
  579. for alias := range set {
  580. adjustment[final] += adjustment[alias]
  581. delete(adjustment, alias)
  582. }
  583. }
  584. }
  585. for final, adjustment := range adjustments {
  586. for key, val := range adjustment {
  587. if coocc, exists := reducedFiles[final][key]; exists {
  588. reducedFiles[final][key] = coocc + val
  589. reducedFiles[key][final] = coocc + val
  590. }
  591. }
  592. }
  593. people := make([]map[string]int, len(couples.people))
  594. for i, counts := range couples.people {
  595. reducedCounts := map[string]int{}
  596. people[i] = reducedCounts
  597. for file := range files {
  598. count := counts[file]
  599. for alias := range aliases[file] {
  600. count += counts[alias]
  601. }
  602. if count > 0 {
  603. reducedCounts[file] = count
  604. }
  605. }
  606. for key, val := range counts {
  607. if _, exists := files[key]; !exists {
  608. if _, exists = pointers[key]; !exists {
  609. reducedCounts[key] = val
  610. }
  611. }
  612. }
  613. }
  614. return reducedFiles, people
  615. }
  616. func init() {
  617. core.Registry.Register(&CouplesAnalysis{})
  618. }