couples.go 18 KB

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