couples.go 18 KB

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