couples.go 18 KB

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