couples.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. package hercules
  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.v3/pb"
  11. "gopkg.in/src-d/hercules.v3/yaml"
  12. )
  13. // CouplesAnalysis calculates the number of common commits for files and authors.
  14. // The results are matrices, where cell at row X and column Y is the number of commits which
  15. // changed X and Y together. In case with people, the numbers are summed for every common file.
  16. type CouplesAnalysis struct {
  17. // PeopleNumber is the number of developers for which to build the matrix. 0 disables this analysis.
  18. PeopleNumber int
  19. // people store how many times every developer committed to every file.
  20. people []map[string]int
  21. // peopleCommits is the number of commits each author made.
  22. peopleCommits []int
  23. // files store every file occurred in the same commit with every other file.
  24. files map[string]map[string]int
  25. // reversedPeopleDict references IdentityDetector.ReversedPeopleDict
  26. reversedPeopleDict []string
  27. }
  28. // CouplesResult is returned by CouplesAnalysis.Finalize() and carries couples matrices from
  29. // authors and files.
  30. type CouplesResult struct {
  31. PeopleMatrix []map[int]int64
  32. PeopleFiles [][]int
  33. FilesMatrix []map[int]int64
  34. Files []string
  35. // reversedPeopleDict references IdentityDetector.ReversedPeopleDict
  36. reversedPeopleDict []string
  37. }
  38. func (couples *CouplesAnalysis) Name() string {
  39. return "Couples"
  40. }
  41. func (couples *CouplesAnalysis) Provides() []string {
  42. return []string{}
  43. }
  44. func (couples *CouplesAnalysis) Requires() []string {
  45. arr := [...]string{DependencyAuthor, DependencyTreeChanges}
  46. return arr[:]
  47. }
  48. func (couples *CouplesAnalysis) ListConfigurationOptions() []ConfigurationOption {
  49. return []ConfigurationOption{}
  50. }
  51. func (couples *CouplesAnalysis) Configure(facts map[string]interface{}) {
  52. if val, exists := facts[FactIdentityDetectorPeopleCount].(int); exists {
  53. couples.PeopleNumber = val
  54. couples.reversedPeopleDict = facts[FactIdentityDetectorReversedPeopleDict].([]string)
  55. }
  56. }
  57. func (couples *CouplesAnalysis) Flag() string {
  58. return "couples"
  59. }
  60. func (couples *CouplesAnalysis) Initialize(repository *git.Repository) {
  61. couples.people = make([]map[string]int, couples.PeopleNumber+1)
  62. for i := range couples.people {
  63. couples.people[i] = map[string]int{}
  64. }
  65. couples.peopleCommits = make([]int, couples.PeopleNumber+1)
  66. couples.files = map[string]map[string]int{}
  67. }
  68. func (couples *CouplesAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  69. author := deps[DependencyAuthor].(int)
  70. if author == AuthorMissing {
  71. author = couples.PeopleNumber
  72. }
  73. couples.peopleCommits[author]++
  74. treeDiff := deps[DependencyTreeChanges].(object.Changes)
  75. context := make([]string, 0)
  76. deleteFile := func(name string) {
  77. // we do not remove the file from people - the context does not expire
  78. delete(couples.files, name)
  79. for _, otherFiles := range couples.files {
  80. delete(otherFiles, name)
  81. }
  82. }
  83. for _, change := range treeDiff {
  84. action, err := change.Action()
  85. if err != nil {
  86. return nil, err
  87. }
  88. toName := change.To.Name
  89. fromName := change.From.Name
  90. switch action {
  91. case merkletrie.Insert:
  92. context = append(context, toName)
  93. couples.people[author][toName]++
  94. case merkletrie.Delete:
  95. deleteFile(fromName)
  96. couples.people[author][fromName]++
  97. case merkletrie.Modify:
  98. if fromName != toName {
  99. // renamed
  100. couples.files[toName] = couples.files[fromName]
  101. for _, otherFiles := range couples.files {
  102. val, exists := otherFiles[fromName]
  103. if exists {
  104. otherFiles[toName] = val
  105. }
  106. }
  107. deleteFile(fromName)
  108. for _, authorFiles := range couples.people {
  109. val, exists := authorFiles[fromName]
  110. if exists {
  111. authorFiles[toName] = val
  112. delete(authorFiles, fromName)
  113. }
  114. }
  115. }
  116. context = append(context, toName)
  117. couples.people[author][toName]++
  118. }
  119. }
  120. for _, file := range context {
  121. for _, otherFile := range context {
  122. lane, exists := couples.files[file]
  123. if !exists {
  124. lane = map[string]int{}
  125. couples.files[file] = lane
  126. }
  127. lane[otherFile]++
  128. }
  129. }
  130. return nil, nil
  131. }
  132. func (couples *CouplesAnalysis) Finalize() interface{} {
  133. filesSequence := make([]string, len(couples.files))
  134. i := 0
  135. for file := range couples.files {
  136. filesSequence[i] = file
  137. i++
  138. }
  139. sort.Strings(filesSequence)
  140. filesIndex := map[string]int{}
  141. for i, file := range filesSequence {
  142. filesIndex[file] = i
  143. }
  144. peopleMatrix := make([]map[int]int64, couples.PeopleNumber+1)
  145. peopleFiles := make([][]int, couples.PeopleNumber+1)
  146. for i := range peopleMatrix {
  147. peopleMatrix[i] = map[int]int64{}
  148. for file, commits := range couples.people[i] {
  149. fi, exists := filesIndex[file]
  150. if exists {
  151. peopleFiles[i] = append(peopleFiles[i], fi)
  152. }
  153. for j, otherFiles := range couples.people {
  154. otherCommits := otherFiles[file]
  155. delta := otherCommits
  156. if otherCommits > commits {
  157. delta = commits
  158. }
  159. if delta > 0 {
  160. peopleMatrix[i][j] += int64(delta)
  161. }
  162. }
  163. }
  164. sort.Ints(peopleFiles[i])
  165. }
  166. filesMatrix := make([]map[int]int64, len(filesIndex))
  167. for i := range filesMatrix {
  168. filesMatrix[i] = map[int]int64{}
  169. for otherFile, cooccs := range couples.files[filesSequence[i]] {
  170. filesMatrix[i][filesIndex[otherFile]] = int64(cooccs)
  171. }
  172. }
  173. return CouplesResult{
  174. PeopleMatrix: peopleMatrix,
  175. PeopleFiles: peopleFiles,
  176. Files: filesSequence,
  177. FilesMatrix: filesMatrix,
  178. reversedPeopleDict: couples.reversedPeopleDict,
  179. }
  180. }
  181. func (couples *CouplesAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  182. couplesResult := result.(CouplesResult)
  183. if binary {
  184. return couples.serializeBinary(&couplesResult, writer)
  185. }
  186. couples.serializeText(&couplesResult, writer)
  187. return nil
  188. }
  189. func (couples *CouplesAnalysis) Deserialize(pbmessage []byte) (interface{}, error) {
  190. message := pb.CouplesAnalysisResults{}
  191. err := proto.Unmarshal(pbmessage, &message)
  192. if err != nil {
  193. return nil, err
  194. }
  195. result := CouplesResult{
  196. Files: message.FileCouples.Index,
  197. FilesMatrix: make([]map[int]int64, message.FileCouples.Matrix.NumberOfRows),
  198. PeopleFiles: make([][]int, len(message.PeopleCouples.Index)),
  199. PeopleMatrix: make([]map[int]int64, message.PeopleCouples.Matrix.NumberOfRows),
  200. reversedPeopleDict: message.PeopleCouples.Index,
  201. }
  202. for i, files := range message.PeopleFiles {
  203. result.PeopleFiles[i] = make([]int, len(files.Files))
  204. for j, val := range files.Files {
  205. result.PeopleFiles[i][j] = int(val)
  206. }
  207. }
  208. convertCSR := func(dest []map[int]int64, src *pb.CompressedSparseRowMatrix) {
  209. for indptr := range src.Indptr {
  210. if indptr == 0 {
  211. continue
  212. }
  213. dest[indptr-1] = map[int]int64{}
  214. for j := src.Indptr[indptr-1]; j < src.Indptr[indptr]; j++ {
  215. dest[indptr-1][int(src.Indices[j])] = src.Data[j]
  216. }
  217. }
  218. }
  219. convertCSR(result.FilesMatrix, message.FileCouples.Matrix)
  220. convertCSR(result.PeopleMatrix, message.PeopleCouples.Matrix)
  221. return result, nil
  222. }
  223. func (couples *CouplesAnalysis) MergeResults(r1, r2 interface{}, c1, c2 *CommonAnalysisResult) interface{} {
  224. cr1 := r1.(CouplesResult)
  225. cr2 := r2.(CouplesResult)
  226. merged := CouplesResult{}
  227. var people, files map[string][3]int
  228. people, merged.reversedPeopleDict = IdentityDetector{}.MergeReversedDicts(
  229. cr1.reversedPeopleDict, cr2.reversedPeopleDict)
  230. files, merged.Files = IdentityDetector{}.MergeReversedDicts(cr1.Files, cr2.Files)
  231. merged.PeopleFiles = make([][]int, len(merged.reversedPeopleDict))
  232. peopleFilesDicts := make([]map[int]bool, len(merged.reversedPeopleDict))
  233. addPeopleFiles := func(peopleFiles [][]int, reversedPeopleDict []string,
  234. reversedFilesDict []string) {
  235. for pi, fs := range peopleFiles {
  236. idx := people[reversedPeopleDict[pi]][0]
  237. m := peopleFilesDicts[idx]
  238. if m == nil {
  239. m = map[int]bool{}
  240. peopleFilesDicts[idx] = m
  241. }
  242. for _, f := range fs {
  243. m[files[reversedFilesDict[f]][0]] = true
  244. }
  245. }
  246. }
  247. addPeopleFiles(cr1.PeopleFiles, cr1.reversedPeopleDict, cr1.Files)
  248. addPeopleFiles(cr2.PeopleFiles, cr2.reversedPeopleDict, cr2.Files)
  249. for i, m := range peopleFilesDicts {
  250. merged.PeopleFiles[i] = make([]int, len(m))
  251. j := 0
  252. for f := range m {
  253. merged.PeopleFiles[i][j] = f
  254. j++
  255. }
  256. sort.Ints(merged.PeopleFiles[i])
  257. }
  258. merged.PeopleMatrix = make([]map[int]int64, len(merged.reversedPeopleDict)+1)
  259. addPeople := func(peopleMatrix []map[int]int64, reversedPeopleDict []string,
  260. reversedFilesDict []string) {
  261. for pi, pc := range peopleMatrix {
  262. var idx int
  263. if pi < len(reversedPeopleDict) {
  264. idx = people[reversedPeopleDict[pi]][0]
  265. } else {
  266. idx = len(merged.reversedPeopleDict)
  267. }
  268. m := merged.PeopleMatrix[idx]
  269. if m == nil {
  270. m = map[int]int64{}
  271. merged.PeopleMatrix[idx] = m
  272. }
  273. for file, val := range pc {
  274. m[files[reversedFilesDict[file]][0]] += val
  275. }
  276. }
  277. }
  278. addPeople(cr1.PeopleMatrix, cr1.reversedPeopleDict, cr1.Files)
  279. addPeople(cr2.PeopleMatrix, cr2.reversedPeopleDict, cr2.Files)
  280. merged.FilesMatrix = make([]map[int]int64, len(merged.Files))
  281. addFiles := func(filesMatrix []map[int]int64, reversedFilesDict []string) {
  282. for fi, fc := range filesMatrix {
  283. idx := people[reversedFilesDict[fi]][0]
  284. m := merged.FilesMatrix[idx]
  285. if m == nil {
  286. m = map[int]int64{}
  287. merged.FilesMatrix[idx] = m
  288. }
  289. for file, val := range fc {
  290. m[files[reversedFilesDict[file]][0]] += val
  291. }
  292. }
  293. }
  294. addFiles(cr1.FilesMatrix, cr1.Files)
  295. addFiles(cr2.FilesMatrix, cr2.Files)
  296. return merged
  297. }
  298. func (couples *CouplesAnalysis) serializeText(result *CouplesResult, writer io.Writer) {
  299. fmt.Fprintln(writer, " files_coocc:")
  300. fmt.Fprintln(writer, " index:")
  301. for _, file := range result.Files {
  302. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(file))
  303. }
  304. fmt.Fprintln(writer, " matrix:")
  305. for _, files := range result.FilesMatrix {
  306. fmt.Fprint(writer, " - {")
  307. indices := []int{}
  308. for file := range files {
  309. indices = append(indices, file)
  310. }
  311. sort.Ints(indices)
  312. for i, file := range indices {
  313. fmt.Fprintf(writer, "%d: %d", file, files[file])
  314. if i < len(indices)-1 {
  315. fmt.Fprint(writer, ", ")
  316. }
  317. }
  318. fmt.Fprintln(writer, "}")
  319. }
  320. fmt.Fprintln(writer, " people_coocc:")
  321. fmt.Fprintln(writer, " index:")
  322. for _, person := range couples.reversedPeopleDict {
  323. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(person))
  324. }
  325. fmt.Fprintln(writer, " matrix:")
  326. for _, people := range result.PeopleMatrix {
  327. fmt.Fprint(writer, " - {")
  328. indices := []int{}
  329. for file := range people {
  330. indices = append(indices, file)
  331. }
  332. sort.Ints(indices)
  333. for i, person := range indices {
  334. fmt.Fprintf(writer, "%d: %d", person, people[person])
  335. if i < len(indices)-1 {
  336. fmt.Fprint(writer, ", ")
  337. }
  338. }
  339. fmt.Fprintln(writer, "}")
  340. }
  341. fmt.Fprintln(writer, " author_files:") // sorted by number of files each author changed
  342. peopleFiles := sortByNumberOfFiles(result.PeopleFiles, couples.reversedPeopleDict, result.Files)
  343. for _, authorFiles := range peopleFiles {
  344. fmt.Fprintf(writer, " - %s:\n", yaml.SafeString(authorFiles.Author))
  345. sort.Strings(authorFiles.Files)
  346. for _, file := range authorFiles.Files {
  347. fmt.Fprintf(writer, " - %s\n", yaml.SafeString(file)) // sorted by path
  348. }
  349. }
  350. }
  351. func sortByNumberOfFiles(
  352. peopleFiles [][]int, peopleDict []string, filesDict []string) authorFilesList {
  353. var pfl authorFilesList
  354. for peopleIdx, files := range peopleFiles {
  355. if peopleIdx < len(peopleDict) {
  356. fileNames := make([]string, len(files))
  357. for i, fi := range files {
  358. fileNames[i] = filesDict[fi]
  359. }
  360. pfl = append(pfl, authorFiles{peopleDict[peopleIdx], fileNames})
  361. }
  362. }
  363. sort.Sort(pfl)
  364. return pfl
  365. }
  366. type authorFiles struct {
  367. Author string
  368. Files []string
  369. }
  370. type authorFilesList []authorFiles
  371. func (s authorFilesList) Len() int {
  372. return len(s)
  373. }
  374. func (s authorFilesList) Swap(i, j int) {
  375. s[i], s[j] = s[j], s[i]
  376. }
  377. func (s authorFilesList) Less(i, j int) bool {
  378. return len(s[i].Files) < len(s[j].Files)
  379. }
  380. func (couples *CouplesAnalysis) serializeBinary(result *CouplesResult, writer io.Writer) error {
  381. message := pb.CouplesAnalysisResults{}
  382. message.FileCouples = &pb.Couples{
  383. Index: result.Files,
  384. Matrix: pb.MapToCompressedSparseRowMatrix(result.FilesMatrix),
  385. }
  386. message.PeopleCouples = &pb.Couples{
  387. Index: result.reversedPeopleDict,
  388. Matrix: pb.MapToCompressedSparseRowMatrix(result.PeopleMatrix),
  389. }
  390. message.PeopleFiles = make([]*pb.TouchedFiles, len(result.reversedPeopleDict))
  391. for key := range result.reversedPeopleDict {
  392. files := result.PeopleFiles[key]
  393. int32Files := make([]int32, len(files))
  394. for i, f := range files {
  395. int32Files[i] = int32(f)
  396. }
  397. message.PeopleFiles[key] = &pb.TouchedFiles{
  398. Files: int32Files,
  399. }
  400. }
  401. serialized, err := proto.Marshal(&message)
  402. if err != nil {
  403. return err
  404. }
  405. writer.Write(serialized)
  406. return nil
  407. }
  408. func init() {
  409. Registry.Register(&CouplesAnalysis{})
  410. }