couples.go 21 KB

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