burndown.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. package hercules
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "log"
  7. "sort"
  8. "sync"
  9. "unicode/utf8"
  10. "github.com/gogo/protobuf/proto"
  11. "github.com/sergi/go-diff/diffmatchpatch"
  12. "gopkg.in/src-d/go-git.v4"
  13. "gopkg.in/src-d/go-git.v4/plumbing"
  14. "gopkg.in/src-d/go-git.v4/plumbing/object"
  15. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  16. "gopkg.in/src-d/hercules.v3/pb"
  17. "gopkg.in/src-d/hercules.v3/yaml"
  18. )
  19. // BurndownAnalysis allows to gather the line burndown statistics for a Git repository.
  20. // It is a LeafPipelineItem.
  21. // Reference: https://erikbern.com/2016/12/05/the-half-life-of-code.html
  22. type BurndownAnalysis struct {
  23. // Granularity sets the size of each band - the number of days it spans.
  24. // Smaller values provide better resolution but require more work and eat more
  25. // memory. 30 days is usually enough.
  26. Granularity int
  27. // Sampling sets how detailed is the statistic - the size of the interval in
  28. // days between consecutive measurements. It may not be greater than Granularity. Try 15 or 30.
  29. Sampling int
  30. // TrackFiles enables or disables the fine-grained per-file burndown analysis.
  31. // It does not change the project level burndown results.
  32. TrackFiles bool
  33. // The number of developers for which to collect the burndown stats. 0 disables it.
  34. PeopleNumber int
  35. // Debug activates the debugging mode. Analyse() runs slower in this mode
  36. // but it accurately checks all the intermediate states for invariant
  37. // violations.
  38. Debug bool
  39. // Repository points to the analysed Git repository struct from go-git.
  40. repository *git.Repository
  41. // globalStatus is the current daily alive number of lines; key is the number
  42. // of days from the beginning of the history.
  43. globalStatus map[int]int64
  44. // globalHistory is the periodic snapshots of globalStatus.
  45. globalHistory [][]int64
  46. // fileHistories is the periodic snapshots of each file's status.
  47. fileHistories map[string][][]int64
  48. // peopleHistories is the periodic snapshots of each person's status.
  49. peopleHistories [][][]int64
  50. // files is the mapping <file path> -> *File.
  51. files map[string]*File
  52. // matrix is the mutual deletions and self insertions.
  53. matrix []map[int]int64
  54. // people is the people's individual time stats.
  55. people []map[int]int64
  56. // day is the most recent day index processed.
  57. day int
  58. // previousDay is the day from the previous sample period -
  59. // different from DaysSinceStart.previousDay.
  60. previousDay int
  61. // references IdentityDetector.ReversedPeopleDict
  62. reversedPeopleDict []string
  63. }
  64. // BurndownResult carries the result of running BurndownAnalysis - it is returned by
  65. // BurndownAnalysis.Finalize().
  66. type BurndownResult struct {
  67. // [number of samples][number of bands]
  68. // The number of samples depends on Sampling: the less Sampling, the bigger the number.
  69. // The number of bands depends on Granularity: the less Granularity, the bigger the number.
  70. GlobalHistory [][]int64
  71. // The key is the path inside the Git repository. The value's dimensions are the same as
  72. // in GlobalHistory.
  73. FileHistories map[string][][]int64
  74. // [number of people][number of samples][number of bands]
  75. PeopleHistories [][][]int64
  76. // [number of people][number of people + 2]
  77. // The first element is the total number of lines added by the author.
  78. // The second element is the number of removals by unidentified authors (outside reversedPeopleDict).
  79. // The rest of the elements are equal the number of line removals by the corresponding
  80. // authors in reversedPeopleDict: 2 -> 0, 3 -> 1, etc.
  81. PeopleMatrix [][]int64
  82. // The following members are private.
  83. // reversedPeopleDict is borrowed from IdentityDetector and becomes available after
  84. // Pipeline.Initialize(facts map[string]interface{}). Thus it can be obtained via
  85. // facts[FactIdentityDetectorReversedPeopleDict].
  86. reversedPeopleDict []string
  87. // sampling and granularity are copied from BurndownAnalysis and stored for service purposes
  88. // such as merging several results together.
  89. sampling int
  90. granularity int
  91. }
  92. const (
  93. // ConfigBurndownGranularity is the name of the option to set BurndownAnalysis.Granularity.
  94. ConfigBurndownGranularity = "Burndown.Granularity"
  95. // ConfigBurndownSampling is the name of the option to set BurndownAnalysis.Sampling.
  96. ConfigBurndownSampling = "Burndown.Sampling"
  97. // ConfigBurndownTrackFiles enables burndown collection for files.
  98. ConfigBurndownTrackFiles = "Burndown.TrackFiles"
  99. // ConfigBurndownTrackPeople enables burndown collection for authors.
  100. ConfigBurndownTrackPeople = "Burndown.TrackPeople"
  101. // ConfigBurndownDebug enables some extra debug assertions.
  102. ConfigBurndownDebug = "Burndown.Debug"
  103. // DefaultBurndownGranularity is the default number of days for BurndownAnalysis.Granularity
  104. // and BurndownAnalysis.Sampling.
  105. DefaultBurndownGranularity = 30
  106. // authorSelf is the internal author index which is used in BurndownAnalysis.Finalize() to
  107. // format the author overwrites matrix.
  108. authorSelf = (1 << 18) - 2
  109. )
  110. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  111. func (analyser *BurndownAnalysis) Name() string {
  112. return "Burndown"
  113. }
  114. // Provides returns the list of names of entities which are produced by this PipelineItem.
  115. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  116. // to this list. Also used by hercules.Registry to build the global map of providers.
  117. func (analyser *BurndownAnalysis) Provides() []string {
  118. return []string{}
  119. }
  120. // Requires returns the list of names of entities which are needed by this PipelineItem.
  121. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  122. // entities are Provides() upstream.
  123. func (analyser *BurndownAnalysis) Requires() []string {
  124. arr := [...]string{
  125. DependencyFileDiff, DependencyTreeChanges, DependencyBlobCache, DependencyDay, DependencyAuthor}
  126. return arr[:]
  127. }
  128. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  129. func (analyser *BurndownAnalysis) ListConfigurationOptions() []ConfigurationOption {
  130. options := [...]ConfigurationOption{{
  131. Name: ConfigBurndownGranularity,
  132. Description: "How many days there are in a single band.",
  133. Flag: "granularity",
  134. Type: IntConfigurationOption,
  135. Default: DefaultBurndownGranularity}, {
  136. Name: ConfigBurndownSampling,
  137. Description: "How frequently to record the state in days.",
  138. Flag: "sampling",
  139. Type: IntConfigurationOption,
  140. Default: DefaultBurndownGranularity}, {
  141. Name: ConfigBurndownTrackFiles,
  142. Description: "Record detailed statistics per each file.",
  143. Flag: "burndown-files",
  144. Type: BoolConfigurationOption,
  145. Default: false}, {
  146. Name: ConfigBurndownTrackPeople,
  147. Description: "Record detailed statistics per each developer.",
  148. Flag: "burndown-people",
  149. Type: BoolConfigurationOption,
  150. Default: false}, {
  151. Name: ConfigBurndownDebug,
  152. Description: "Validate the trees on each step.",
  153. Flag: "burndown-debug",
  154. Type: BoolConfigurationOption,
  155. Default: false},
  156. }
  157. return options[:]
  158. }
  159. // Configure sets the properties previously published by ListConfigurationOptions().
  160. func (analyser *BurndownAnalysis) Configure(facts map[string]interface{}) {
  161. if val, exists := facts[ConfigBurndownGranularity].(int); exists {
  162. analyser.Granularity = val
  163. }
  164. if val, exists := facts[ConfigBurndownSampling].(int); exists {
  165. analyser.Sampling = val
  166. }
  167. if val, exists := facts[ConfigBurndownTrackFiles].(bool); exists {
  168. analyser.TrackFiles = val
  169. }
  170. if people, exists := facts[ConfigBurndownTrackPeople].(bool); people {
  171. if val, exists := facts[FactIdentityDetectorPeopleCount].(int); exists {
  172. analyser.PeopleNumber = val
  173. analyser.reversedPeopleDict = facts[FactIdentityDetectorReversedPeopleDict].([]string)
  174. }
  175. } else if exists {
  176. analyser.PeopleNumber = 0
  177. }
  178. if val, exists := facts[ConfigBurndownDebug].(bool); exists {
  179. analyser.Debug = val
  180. }
  181. }
  182. // Flag for the command line switch which enables this analysis.
  183. func (analyser *BurndownAnalysis) Flag() string {
  184. return "burndown"
  185. }
  186. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  187. // calls. The repository which is going to be analysed is supplied as an argument.
  188. func (analyser *BurndownAnalysis) Initialize(repository *git.Repository) {
  189. if analyser.Granularity <= 0 {
  190. log.Printf("Warning: adjusted the granularity to %d days\n",
  191. DefaultBurndownGranularity)
  192. analyser.Granularity = DefaultBurndownGranularity
  193. }
  194. if analyser.Sampling <= 0 {
  195. log.Printf("Warning: adjusted the sampling to %d days\n",
  196. DefaultBurndownGranularity)
  197. analyser.Sampling = DefaultBurndownGranularity
  198. }
  199. if analyser.Sampling > analyser.Granularity {
  200. log.Printf("Warning: granularity may not be less than sampling, adjusted to %d\n",
  201. analyser.Granularity)
  202. analyser.Sampling = analyser.Granularity
  203. }
  204. analyser.repository = repository
  205. analyser.globalStatus = map[int]int64{}
  206. analyser.globalHistory = [][]int64{}
  207. analyser.fileHistories = map[string][][]int64{}
  208. analyser.peopleHistories = make([][][]int64, analyser.PeopleNumber)
  209. analyser.files = map[string]*File{}
  210. analyser.matrix = make([]map[int]int64, analyser.PeopleNumber)
  211. analyser.people = make([]map[int]int64, analyser.PeopleNumber)
  212. analyser.day = 0
  213. analyser.previousDay = 0
  214. }
  215. // Consume runs this PipelineItem on the next commit data.
  216. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  217. // Additionally, "commit" is always present there and represents the analysed *object.Commit.
  218. // This function returns the mapping with analysis results. The keys must be the same as
  219. // in Provides(). If there was an error, nil is returned.
  220. func (analyser *BurndownAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  221. sampling := analyser.Sampling
  222. if sampling == 0 {
  223. sampling = 1
  224. }
  225. author := deps[DependencyAuthor].(int)
  226. analyser.day = deps[DependencyDay].(int)
  227. delta := (analyser.day / sampling) - (analyser.previousDay / sampling)
  228. if delta > 0 {
  229. analyser.previousDay = analyser.day
  230. gs, fss, pss := analyser.groupStatus()
  231. analyser.updateHistories(gs, fss, pss, delta)
  232. }
  233. cache := deps[DependencyBlobCache].(map[plumbing.Hash]*object.Blob)
  234. treeDiffs := deps[DependencyTreeChanges].(object.Changes)
  235. fileDiffs := deps[DependencyFileDiff].(map[string]FileDiffData)
  236. for _, change := range treeDiffs {
  237. action, _ := change.Action()
  238. var err error
  239. switch action {
  240. case merkletrie.Insert:
  241. err = analyser.handleInsertion(change, author, cache)
  242. case merkletrie.Delete:
  243. err = analyser.handleDeletion(change, author, cache)
  244. case merkletrie.Modify:
  245. err = analyser.handleModification(change, author, cache, fileDiffs)
  246. }
  247. if err != nil {
  248. return nil, err
  249. }
  250. }
  251. return nil, nil
  252. }
  253. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  254. func (analyser *BurndownAnalysis) Finalize() interface{} {
  255. gs, fss, pss := analyser.groupStatus()
  256. analyser.updateHistories(gs, fss, pss, 1)
  257. for key, statuses := range analyser.fileHistories {
  258. if len(statuses) == len(analyser.globalHistory) {
  259. continue
  260. }
  261. padding := make([][]int64, len(analyser.globalHistory)-len(statuses))
  262. for i := range padding {
  263. padding[i] = make([]int64, len(analyser.globalStatus))
  264. }
  265. analyser.fileHistories[key] = append(padding, statuses...)
  266. }
  267. peopleMatrix := make([][]int64, analyser.PeopleNumber)
  268. for i, row := range analyser.matrix {
  269. mrow := make([]int64, analyser.PeopleNumber+2)
  270. peopleMatrix[i] = mrow
  271. for key, val := range row {
  272. if key == AuthorMissing {
  273. key = -1
  274. } else if key == authorSelf {
  275. key = -2
  276. }
  277. mrow[key+2] = val
  278. }
  279. }
  280. return BurndownResult{
  281. GlobalHistory: analyser.globalHistory,
  282. FileHistories: analyser.fileHistories,
  283. PeopleHistories: analyser.peopleHistories,
  284. PeopleMatrix: peopleMatrix,
  285. reversedPeopleDict: analyser.reversedPeopleDict,
  286. sampling: analyser.Sampling,
  287. granularity: analyser.Granularity,
  288. }
  289. }
  290. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  291. // The text format is YAML and the bytes format is Protocol Buffers.
  292. func (analyser *BurndownAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  293. burndownResult := result.(BurndownResult)
  294. if binary {
  295. return analyser.serializeBinary(&burndownResult, writer)
  296. }
  297. analyser.serializeText(&burndownResult, writer)
  298. return nil
  299. }
  300. // Deserialize converts the specified protobuf bytes to BurndownResult.
  301. func (analyser *BurndownAnalysis) Deserialize(pbmessage []byte) (interface{}, error) {
  302. msg := pb.BurndownAnalysisResults{}
  303. err := proto.Unmarshal(pbmessage, &msg)
  304. if err != nil {
  305. return nil, err
  306. }
  307. result := BurndownResult{}
  308. convertCSR := func(mat *pb.BurndownSparseMatrix) [][]int64 {
  309. res := make([][]int64, mat.NumberOfRows)
  310. for i := 0; i < int(mat.NumberOfRows); i++ {
  311. res[i] = make([]int64, mat.NumberOfColumns)
  312. for j := 0; j < len(mat.Rows[i].Columns); j++ {
  313. res[i][j] = int64(mat.Rows[i].Columns[j])
  314. }
  315. }
  316. return res
  317. }
  318. result.GlobalHistory = convertCSR(msg.Project)
  319. result.FileHistories = map[string][][]int64{}
  320. for _, mat := range msg.Files {
  321. result.FileHistories[mat.Name] = convertCSR(mat)
  322. }
  323. result.reversedPeopleDict = make([]string, len(msg.People))
  324. result.PeopleHistories = make([][][]int64, len(msg.People))
  325. for i, mat := range msg.People {
  326. result.PeopleHistories[i] = convertCSR(mat)
  327. result.reversedPeopleDict[i] = mat.Name
  328. }
  329. if msg.PeopleInteraction != nil {
  330. result.PeopleMatrix = make([][]int64, msg.PeopleInteraction.NumberOfRows)
  331. }
  332. for i := 0; i < len(result.PeopleMatrix); i++ {
  333. result.PeopleMatrix[i] = make([]int64, msg.PeopleInteraction.NumberOfColumns)
  334. for j := int(msg.PeopleInteraction.Indptr[i]); j < int(msg.PeopleInteraction.Indptr[i+1]); j++ {
  335. result.PeopleMatrix[i][msg.PeopleInteraction.Indices[j]] = msg.PeopleInteraction.Data[j]
  336. }
  337. }
  338. result.sampling = int(msg.Sampling)
  339. result.granularity = int(msg.Granularity)
  340. return result, nil
  341. }
  342. // MergeResults combines two BurndownResult-s together.
  343. func (analyser *BurndownAnalysis) MergeResults(
  344. r1, r2 interface{}, c1, c2 *CommonAnalysisResult) interface{} {
  345. bar1 := r1.(BurndownResult)
  346. bar2 := r2.(BurndownResult)
  347. merged := BurndownResult{}
  348. if bar1.sampling < bar2.sampling {
  349. merged.sampling = bar1.sampling
  350. } else {
  351. merged.sampling = bar2.sampling
  352. }
  353. if bar1.granularity < bar2.granularity {
  354. merged.granularity = bar1.granularity
  355. } else {
  356. merged.granularity = bar2.granularity
  357. }
  358. var people map[string][3]int
  359. people, merged.reversedPeopleDict = IdentityDetector{}.MergeReversedDicts(
  360. bar1.reversedPeopleDict, bar2.reversedPeopleDict)
  361. var wg sync.WaitGroup
  362. if len(bar1.GlobalHistory) > 0 || len(bar2.GlobalHistory) > 0 {
  363. wg.Add(1)
  364. go func() {
  365. defer wg.Done()
  366. merged.GlobalHistory = mergeMatrices(
  367. bar1.GlobalHistory, bar2.GlobalHistory,
  368. bar1.granularity, bar1.sampling,
  369. bar2.granularity, bar2.sampling,
  370. c1, c2)
  371. }()
  372. }
  373. if len(bar1.FileHistories) > 0 || len(bar2.FileHistories) > 0 {
  374. merged.FileHistories = map[string][][]int64{}
  375. historyMutex := sync.Mutex{}
  376. for key, fh1 := range bar1.FileHistories {
  377. if fh2, exists := bar2.FileHistories[key]; exists {
  378. wg.Add(1)
  379. go func(fh1, fh2 [][]int64, key string) {
  380. defer wg.Done()
  381. historyMutex.Lock()
  382. defer historyMutex.Unlock()
  383. merged.FileHistories[key] = mergeMatrices(
  384. fh1, fh2, bar1.granularity, bar1.sampling, bar2.granularity, bar2.sampling, c1, c2)
  385. }(fh1, fh2, key)
  386. } else {
  387. historyMutex.Lock()
  388. merged.FileHistories[key] = fh1
  389. historyMutex.Unlock()
  390. }
  391. }
  392. for key, fh2 := range bar2.FileHistories {
  393. if _, exists := bar1.FileHistories[key]; !exists {
  394. historyMutex.Lock()
  395. merged.FileHistories[key] = fh2
  396. historyMutex.Unlock()
  397. }
  398. }
  399. }
  400. if len(merged.reversedPeopleDict) > 0 {
  401. merged.PeopleHistories = make([][][]int64, len(merged.reversedPeopleDict))
  402. for i, key := range merged.reversedPeopleDict {
  403. ptrs := people[key]
  404. if ptrs[1] < 0 {
  405. if len(bar2.PeopleHistories) > 0 {
  406. merged.PeopleHistories[i] = bar2.PeopleHistories[ptrs[2]]
  407. }
  408. } else if ptrs[2] < 0 {
  409. if len(bar1.PeopleHistories) > 0 {
  410. merged.PeopleHistories[i] = bar1.PeopleHistories[ptrs[1]]
  411. }
  412. } else {
  413. wg.Add(1)
  414. go func(i int) {
  415. defer wg.Done()
  416. var m1, m2 [][]int64
  417. if len(bar1.PeopleHistories) > 0 {
  418. m1 = bar1.PeopleHistories[ptrs[1]]
  419. }
  420. if len(bar2.PeopleHistories) > 0 {
  421. m2 = bar2.PeopleHistories[ptrs[2]]
  422. }
  423. merged.PeopleHistories[i] = mergeMatrices(
  424. m1, m2,
  425. bar1.granularity, bar1.sampling,
  426. bar2.granularity, bar2.sampling,
  427. c1, c2,
  428. )
  429. }(i)
  430. }
  431. }
  432. wg.Add(1)
  433. go func() {
  434. defer wg.Done()
  435. if len(bar2.PeopleMatrix) == 0 {
  436. merged.PeopleMatrix = bar1.PeopleMatrix
  437. // extend the matrix in both directions
  438. for i := 0; i < len(merged.PeopleMatrix); i++ {
  439. for j := len(bar1.reversedPeopleDict); j < len(merged.reversedPeopleDict); j++ {
  440. merged.PeopleMatrix[i] = append(merged.PeopleMatrix[i], 0)
  441. }
  442. }
  443. for i := len(bar1.reversedPeopleDict); i < len(merged.reversedPeopleDict); i++ {
  444. merged.PeopleMatrix = append(
  445. merged.PeopleMatrix, make([]int64, len(merged.reversedPeopleDict)+2))
  446. }
  447. } else {
  448. merged.PeopleMatrix = make([][]int64, len(merged.reversedPeopleDict))
  449. for i := range merged.PeopleMatrix {
  450. merged.PeopleMatrix[i] = make([]int64, len(merged.reversedPeopleDict)+2)
  451. }
  452. for i, key := range bar1.reversedPeopleDict {
  453. mi := people[key][0] // index in merged.reversedPeopleDict
  454. copy(merged.PeopleMatrix[mi][:2], bar1.PeopleMatrix[i][:2])
  455. for j, val := range bar1.PeopleMatrix[i][2:] {
  456. merged.PeopleMatrix[mi][2+people[bar1.reversedPeopleDict[j]][0]] = val
  457. }
  458. }
  459. for i, key := range bar2.reversedPeopleDict {
  460. mi := people[key][0] // index in merged.reversedPeopleDict
  461. merged.PeopleMatrix[mi][0] += bar2.PeopleMatrix[i][0]
  462. merged.PeopleMatrix[mi][1] += bar2.PeopleMatrix[i][1]
  463. for j, val := range bar2.PeopleMatrix[i][2:] {
  464. merged.PeopleMatrix[mi][2+people[bar2.reversedPeopleDict[j]][0]] += val
  465. }
  466. }
  467. }
  468. }()
  469. }
  470. wg.Wait()
  471. return merged
  472. }
  473. // mergeMatrices takes two [number of samples][number of bands] matrices,
  474. // resamples them to days so that they become square, sums and resamples back to the
  475. // least of (sampling1, sampling2) and (granularity1, granularity2).
  476. func mergeMatrices(m1, m2 [][]int64, granularity1, sampling1, granularity2, sampling2 int,
  477. c1, c2 *CommonAnalysisResult) [][]int64 {
  478. commonMerged := *c1
  479. commonMerged.Merge(c2)
  480. var granularity, sampling int
  481. if sampling1 < sampling2 {
  482. sampling = sampling1
  483. } else {
  484. sampling = sampling2
  485. }
  486. if granularity1 < granularity2 {
  487. granularity = granularity1
  488. } else {
  489. granularity = granularity2
  490. }
  491. size := int((commonMerged.EndTime - commonMerged.BeginTime) / (3600 * 24))
  492. daily := make([][]float32, size+granularity)
  493. for i := range daily {
  494. daily[i] = make([]float32, size+sampling)
  495. }
  496. if len(m1) > 0 {
  497. addBurndownMatrix(m1, granularity1, sampling1, daily,
  498. int(c1.BeginTime-commonMerged.BeginTime)/(3600*24))
  499. }
  500. if len(m2) > 0 {
  501. addBurndownMatrix(m2, granularity2, sampling2, daily,
  502. int(c2.BeginTime-commonMerged.BeginTime)/(3600*24))
  503. }
  504. // convert daily to [][]in(t64
  505. result := make([][]int64, (size+sampling-1)/sampling)
  506. for i := range result {
  507. result[i] = make([]int64, (size+granularity-1)/granularity)
  508. sampledIndex := i * sampling
  509. if i == len(result)-1 {
  510. sampledIndex = size - 1
  511. }
  512. for j := 0; j < len(result[i]); j++ {
  513. accum := float32(0)
  514. for k := j * granularity; k < (j+1)*granularity && k < size; k++ {
  515. accum += daily[sampledIndex][k]
  516. }
  517. result[i][j] = int64(accum)
  518. }
  519. }
  520. return result
  521. }
  522. // Explode `matrix` so that it is daily sampled and has daily bands, shift by `offset` days
  523. // and add to the accumulator. `daily` size is square and is guaranteed to fit `matrix` by
  524. // the caller.
  525. // Rows: *at least* len(matrix) * sampling + offset
  526. // Columns: *at least* len(matrix[...]) * granularity + offset
  527. // `matrix` can be sparse, so that the last columns which are equal to 0 are truncated.
  528. func addBurndownMatrix(matrix [][]int64, granularity, sampling int, daily [][]float32, offset int) {
  529. // Determine the maximum number of bands; the actual one may be larger but we do not care
  530. maxCols := 0
  531. for _, row := range matrix {
  532. if maxCols < len(row) {
  533. maxCols = len(row)
  534. }
  535. }
  536. neededRows := len(matrix)*sampling + offset
  537. if len(daily) < neededRows {
  538. panic(fmt.Sprintf("merge bug: too few daily rows: required %d, have %d",
  539. neededRows, len(daily)))
  540. }
  541. if len(daily[0]) < maxCols {
  542. panic(fmt.Sprintf("merge bug: too few daily cols: required %d, have %d",
  543. maxCols, len(daily[0])))
  544. }
  545. for x := 0; x < maxCols; x++ {
  546. for y := 0; y < len(matrix); y++ {
  547. if x*granularity > (y+1)*sampling {
  548. // the future is zeros
  549. continue
  550. }
  551. decay := func(startIndex int, startVal float32) {
  552. if startVal == 0 {
  553. return
  554. }
  555. k := float32(matrix[y][x]) / startVal // <= 1
  556. scale := float32((y+1)*sampling - startIndex)
  557. for i := x * granularity; i < (x+1)*granularity; i++ {
  558. initial := daily[startIndex-1+offset][i+offset]
  559. for j := startIndex; j < (y+1)*sampling; j++ {
  560. daily[j+offset][i+offset] = initial * (1 + (k-1)*float32(j-startIndex+1)/scale)
  561. }
  562. }
  563. }
  564. raise := func(finishIndex int, finishVal float32) {
  565. var initial float32
  566. if y > 0 {
  567. initial = float32(matrix[y-1][x])
  568. }
  569. startIndex := y * sampling
  570. if startIndex < x*granularity {
  571. startIndex = x * granularity
  572. }
  573. if startIndex == finishIndex {
  574. return
  575. }
  576. avg := (finishVal - initial) / float32(finishIndex-startIndex)
  577. for j := y * sampling; j < finishIndex; j++ {
  578. for i := startIndex; i <= j; i++ {
  579. daily[j+offset][i+offset] = avg
  580. }
  581. }
  582. // copy [x*g..y*s)
  583. for j := y * sampling; j < finishIndex; j++ {
  584. for i := x * granularity; i < y*sampling; i++ {
  585. daily[j+offset][i+offset] = daily[j-1+offset][i+offset]
  586. }
  587. }
  588. }
  589. if (x+1)*granularity >= (y+1)*sampling {
  590. // x*granularity <= (y+1)*sampling
  591. // 1. x*granularity <= y*sampling
  592. // y*sampling..(y+1)sampling
  593. //
  594. // x+1
  595. // /
  596. // /
  597. // / y+1 -|
  598. // / |
  599. // / y -|
  600. // /
  601. // / x
  602. //
  603. // 2. x*granularity > y*sampling
  604. // x*granularity..(y+1)sampling
  605. //
  606. // x+1
  607. // /
  608. // /
  609. // / y+1 -|
  610. // / |
  611. // / x -|
  612. // /
  613. // / y
  614. if x*granularity <= y*sampling {
  615. raise((y+1)*sampling, float32(matrix[y][x]))
  616. } else if (y+1)*sampling > x*granularity {
  617. raise((y+1)*sampling, float32(matrix[y][x]))
  618. avg := float32(matrix[y][x]) / float32((y+1)*sampling-x*granularity)
  619. for j := x * granularity; j < (y+1)*sampling; j++ {
  620. for i := x * granularity; i <= j; i++ {
  621. daily[j+offset][i+offset] = avg
  622. }
  623. }
  624. }
  625. } else if (x+1)*granularity >= y*sampling {
  626. // y*sampling <= (x+1)*granularity < (y+1)sampling
  627. // y*sampling..(x+1)*granularity
  628. // (x+1)*granularity..(y+1)sampling
  629. // x+1
  630. // /\
  631. // / \
  632. // / \
  633. // / y+1
  634. // /
  635. // y
  636. v1 := float32(matrix[y-1][x])
  637. v2 := float32(matrix[y][x])
  638. var peak float32
  639. delta := float32((x+1)*granularity - y*sampling)
  640. var scale float32
  641. var previous float32
  642. if y > 0 && (y-1)*sampling >= x*granularity {
  643. // x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  644. // |________|.......^
  645. if y > 1 {
  646. previous = float32(matrix[y-2][x])
  647. }
  648. scale = float32(sampling)
  649. } else {
  650. // (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  651. // |______|.......^
  652. if y == 0 {
  653. scale = float32(sampling)
  654. } else {
  655. scale = float32(y*sampling - x*granularity)
  656. }
  657. }
  658. peak = v1 + (v1-previous)/scale*delta
  659. if v2 > peak {
  660. // we need to adjust the peak, it may not be less than the decayed value
  661. if y < len(matrix)-1 {
  662. // y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  663. // ^.........|_________|
  664. k := (v2 - float32(matrix[y+1][x])) / float32(sampling) // > 0
  665. peak = float32(matrix[y][x]) + k*float32((y+1)*sampling-(x+1)*granularity)
  666. // peak > v2 > v1
  667. } else {
  668. peak = v2
  669. // not enough data to interpolate; this is at least not restricted
  670. }
  671. }
  672. raise((x+1)*granularity, peak)
  673. decay((x+1)*granularity, peak)
  674. } else {
  675. // (x+1)*granularity < y*sampling
  676. // y*sampling..(y+1)sampling
  677. decay(y*sampling, float32(matrix[y-1][x]))
  678. }
  679. }
  680. }
  681. }
  682. func (analyser *BurndownAnalysis) serializeText(result *BurndownResult, writer io.Writer) {
  683. fmt.Fprintln(writer, " granularity:", result.granularity)
  684. fmt.Fprintln(writer, " sampling:", result.sampling)
  685. yaml.PrintMatrix(writer, result.GlobalHistory, 2, "project", true)
  686. if len(result.FileHistories) > 0 {
  687. fmt.Fprintln(writer, " files:")
  688. keys := sortedKeys(result.FileHistories)
  689. for _, key := range keys {
  690. yaml.PrintMatrix(writer, result.FileHistories[key], 4, key, true)
  691. }
  692. }
  693. if len(result.PeopleHistories) > 0 {
  694. fmt.Fprintln(writer, " people_sequence:")
  695. for key := range result.PeopleHistories {
  696. fmt.Fprintln(writer, " - "+yaml.SafeString(result.reversedPeopleDict[key]))
  697. }
  698. fmt.Fprintln(writer, " people:")
  699. for key, val := range result.PeopleHistories {
  700. yaml.PrintMatrix(writer, val, 4, result.reversedPeopleDict[key], true)
  701. }
  702. fmt.Fprintln(writer, " people_interaction: |-")
  703. yaml.PrintMatrix(writer, result.PeopleMatrix, 4, "", false)
  704. }
  705. }
  706. func (analyser *BurndownAnalysis) serializeBinary(result *BurndownResult, writer io.Writer) error {
  707. message := pb.BurndownAnalysisResults{
  708. Granularity: int32(result.granularity),
  709. Sampling: int32(result.sampling),
  710. }
  711. if len(result.GlobalHistory) > 0 {
  712. message.Project = pb.ToBurndownSparseMatrix(result.GlobalHistory, "project")
  713. }
  714. if len(result.FileHistories) > 0 {
  715. message.Files = make([]*pb.BurndownSparseMatrix, len(result.FileHistories))
  716. keys := sortedKeys(result.FileHistories)
  717. i := 0
  718. for _, key := range keys {
  719. message.Files[i] = pb.ToBurndownSparseMatrix(
  720. result.FileHistories[key], key)
  721. i++
  722. }
  723. }
  724. if len(result.PeopleHistories) > 0 {
  725. message.People = make(
  726. []*pb.BurndownSparseMatrix, len(result.PeopleHistories))
  727. for key, val := range result.PeopleHistories {
  728. if len(val) > 0 {
  729. message.People[key] = pb.ToBurndownSparseMatrix(val, result.reversedPeopleDict[key])
  730. }
  731. }
  732. message.PeopleInteraction = pb.DenseToCompressedSparseRowMatrix(result.PeopleMatrix)
  733. }
  734. serialized, err := proto.Marshal(&message)
  735. if err != nil {
  736. return err
  737. }
  738. writer.Write(serialized)
  739. return nil
  740. }
  741. func sortedKeys(m map[string][][]int64) []string {
  742. keys := make([]string, 0, len(m))
  743. for k := range m {
  744. keys = append(keys, k)
  745. }
  746. sort.Strings(keys)
  747. return keys
  748. }
  749. func checkClose(c io.Closer) {
  750. if err := c.Close(); err != nil {
  751. panic(err)
  752. }
  753. }
  754. // We do a hack and store the day in the first 14 bits and the author index in the last 18.
  755. // Strictly speaking, int can be 64-bit and then the author index occupies 32+18 bits.
  756. // This hack is needed to simplify the values storage inside File-s. We can compare
  757. // different values together and they are compared as days for the same author.
  758. func (analyser *BurndownAnalysis) packPersonWithDay(person int, day int) int {
  759. if analyser.PeopleNumber == 0 {
  760. return day
  761. }
  762. result := day
  763. result |= person << 14
  764. // This effectively means max 16384 days (>44 years) and (131072 - 2) devs
  765. return result
  766. }
  767. func (analyser *BurndownAnalysis) unpackPersonWithDay(value int) (int, int) {
  768. if analyser.PeopleNumber == 0 {
  769. return AuthorMissing, value
  770. }
  771. return value >> 14, value & 0x3FFF
  772. }
  773. func (analyser *BurndownAnalysis) updateStatus(
  774. status interface{}, _ int, previousValue int, delta int) {
  775. _, previousTime := analyser.unpackPersonWithDay(previousValue)
  776. status.(map[int]int64)[previousTime] += int64(delta)
  777. }
  778. func (analyser *BurndownAnalysis) updatePeople(
  779. peopleUncasted interface{}, _ int, previousValue int, delta int) {
  780. previousAuthor, previousTime := analyser.unpackPersonWithDay(previousValue)
  781. if previousAuthor == AuthorMissing {
  782. return
  783. }
  784. people := peopleUncasted.([]map[int]int64)
  785. stats := people[previousAuthor]
  786. if stats == nil {
  787. stats = map[int]int64{}
  788. people[previousAuthor] = stats
  789. }
  790. stats[previousTime] += int64(delta)
  791. }
  792. func (analyser *BurndownAnalysis) updateMatrix(
  793. matrixUncasted interface{}, currentTime int, previousTime int, delta int) {
  794. matrix := matrixUncasted.([]map[int]int64)
  795. newAuthor, _ := analyser.unpackPersonWithDay(currentTime)
  796. oldAuthor, _ := analyser.unpackPersonWithDay(previousTime)
  797. if oldAuthor == AuthorMissing {
  798. return
  799. }
  800. if newAuthor == oldAuthor && delta > 0 {
  801. newAuthor = authorSelf
  802. }
  803. row := matrix[oldAuthor]
  804. if row == nil {
  805. row = map[int]int64{}
  806. matrix[oldAuthor] = row
  807. }
  808. cell, exists := row[newAuthor]
  809. if !exists {
  810. row[newAuthor] = 0
  811. cell = 0
  812. }
  813. row[newAuthor] = cell + int64(delta)
  814. }
  815. func (analyser *BurndownAnalysis) newFile(
  816. author int, day int, size int, global map[int]int64, people []map[int]int64,
  817. matrix []map[int]int64) *File {
  818. statuses := make([]Status, 1)
  819. statuses[0] = NewStatus(global, analyser.updateStatus)
  820. if analyser.TrackFiles {
  821. statuses = append(statuses, NewStatus(map[int]int64{}, analyser.updateStatus))
  822. }
  823. if analyser.PeopleNumber > 0 {
  824. statuses = append(statuses, NewStatus(people, analyser.updatePeople))
  825. statuses = append(statuses, NewStatus(matrix, analyser.updateMatrix))
  826. day = analyser.packPersonWithDay(author, day)
  827. }
  828. return NewFile(day, size, statuses...)
  829. }
  830. func (analyser *BurndownAnalysis) handleInsertion(
  831. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob) error {
  832. blob := cache[change.To.TreeEntry.Hash]
  833. lines, err := CountLines(blob)
  834. if err != nil {
  835. if err.Error() == "binary" {
  836. return nil
  837. }
  838. return err
  839. }
  840. name := change.To.Name
  841. file, exists := analyser.files[name]
  842. if exists {
  843. return fmt.Errorf("file %s already exists", name)
  844. }
  845. file = analyser.newFile(
  846. author, analyser.day, lines, analyser.globalStatus, analyser.people, analyser.matrix)
  847. analyser.files[name] = file
  848. return nil
  849. }
  850. func (analyser *BurndownAnalysis) handleDeletion(
  851. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob) error {
  852. blob := cache[change.From.TreeEntry.Hash]
  853. lines, err := CountLines(blob)
  854. if err != nil {
  855. if err.Error() == "binary" {
  856. return nil
  857. }
  858. return err
  859. }
  860. name := change.From.Name
  861. file := analyser.files[name]
  862. file.Update(analyser.packPersonWithDay(author, analyser.day), 0, 0, lines)
  863. delete(analyser.files, name)
  864. return nil
  865. }
  866. func (analyser *BurndownAnalysis) handleModification(
  867. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob,
  868. diffs map[string]FileDiffData) error {
  869. file, exists := analyser.files[change.From.Name]
  870. if !exists {
  871. // this indeed may happen
  872. return analyser.handleInsertion(change, author, cache)
  873. }
  874. // possible rename
  875. if change.To.Name != change.From.Name {
  876. err := analyser.handleRename(change.From.Name, change.To.Name)
  877. if err != nil {
  878. return err
  879. }
  880. }
  881. thisDiffs := diffs[change.To.Name]
  882. if file.Len() != thisDiffs.OldLinesOfCode {
  883. log.Printf("====TREE====\n%s", file.Dump())
  884. return fmt.Errorf("%s: internal integrity error src %d != %d %s -> %s",
  885. change.To.Name, thisDiffs.OldLinesOfCode, file.Len(),
  886. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  887. }
  888. // we do not call RunesToDiffLines so the number of lines equals
  889. // to the rune count
  890. position := 0
  891. pending := diffmatchpatch.Diff{Text: ""}
  892. apply := func(edit diffmatchpatch.Diff) {
  893. length := utf8.RuneCountInString(edit.Text)
  894. if edit.Type == diffmatchpatch.DiffInsert {
  895. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length, 0)
  896. position += length
  897. } else {
  898. file.Update(analyser.packPersonWithDay(author, analyser.day), position, 0, length)
  899. }
  900. if analyser.Debug {
  901. file.Validate()
  902. }
  903. }
  904. for _, edit := range thisDiffs.Diffs {
  905. dumpBefore := ""
  906. if analyser.Debug {
  907. dumpBefore = file.Dump()
  908. }
  909. length := utf8.RuneCountInString(edit.Text)
  910. debugError := func() {
  911. log.Printf("%s: internal diff error\n", change.To.Name)
  912. log.Printf("Update(%d, %d, %d (0), %d (0))\n", analyser.day, position,
  913. length, utf8.RuneCountInString(pending.Text))
  914. if dumpBefore != "" {
  915. log.Printf("====TREE BEFORE====\n%s====END====\n", dumpBefore)
  916. }
  917. log.Printf("====TREE AFTER====\n%s====END====\n", file.Dump())
  918. }
  919. switch edit.Type {
  920. case diffmatchpatch.DiffEqual:
  921. if pending.Text != "" {
  922. apply(pending)
  923. pending.Text = ""
  924. }
  925. position += length
  926. case diffmatchpatch.DiffInsert:
  927. if pending.Text != "" {
  928. if pending.Type == diffmatchpatch.DiffInsert {
  929. debugError()
  930. return errors.New("DiffInsert may not appear after DiffInsert")
  931. }
  932. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length,
  933. utf8.RuneCountInString(pending.Text))
  934. if analyser.Debug {
  935. file.Validate()
  936. }
  937. position += length
  938. pending.Text = ""
  939. } else {
  940. pending = edit
  941. }
  942. case diffmatchpatch.DiffDelete:
  943. if pending.Text != "" {
  944. debugError()
  945. return errors.New("DiffDelete may not appear after DiffInsert/DiffDelete")
  946. }
  947. pending = edit
  948. default:
  949. debugError()
  950. return fmt.Errorf("diff operation is not supported: %d", edit.Type)
  951. }
  952. }
  953. if pending.Text != "" {
  954. apply(pending)
  955. pending.Text = ""
  956. }
  957. if file.Len() != thisDiffs.NewLinesOfCode {
  958. return fmt.Errorf("%s: internal integrity error dst %d != %d",
  959. change.To.Name, thisDiffs.NewLinesOfCode, file.Len())
  960. }
  961. return nil
  962. }
  963. func (analyser *BurndownAnalysis) handleRename(from, to string) error {
  964. file, exists := analyser.files[from]
  965. if !exists {
  966. return fmt.Errorf("file %s does not exist", from)
  967. }
  968. analyser.files[to] = file
  969. delete(analyser.files, from)
  970. return nil
  971. }
  972. func (analyser *BurndownAnalysis) groupStatus() ([]int64, map[string][]int64, [][]int64) {
  973. granularity := analyser.Granularity
  974. if granularity == 0 {
  975. granularity = 1
  976. }
  977. day := analyser.day
  978. day++
  979. adjust := 0
  980. if day%granularity != 0 {
  981. adjust = 1
  982. }
  983. global := make([]int64, day/granularity+adjust)
  984. var group int64
  985. for i := 0; i < day; i++ {
  986. group += analyser.globalStatus[i]
  987. if (i % granularity) == (granularity - 1) {
  988. global[i/granularity] = group
  989. group = 0
  990. }
  991. }
  992. if day%granularity != 0 {
  993. global[len(global)-1] = group
  994. }
  995. locals := make(map[string][]int64)
  996. if analyser.TrackFiles {
  997. for key, file := range analyser.files {
  998. status := make([]int64, day/granularity+adjust)
  999. var group int64
  1000. for i := 0; i < day; i++ {
  1001. group += file.Status(1).(map[int]int64)[i]
  1002. if (i % granularity) == (granularity - 1) {
  1003. status[i/granularity] = group
  1004. group = 0
  1005. }
  1006. }
  1007. if day%granularity != 0 {
  1008. status[len(status)-1] = group
  1009. }
  1010. locals[key] = status
  1011. }
  1012. }
  1013. peoples := make([][]int64, len(analyser.people))
  1014. for key, person := range analyser.people {
  1015. status := make([]int64, day/granularity+adjust)
  1016. var group int64
  1017. for i := 0; i < day; i++ {
  1018. group += person[i]
  1019. if (i % granularity) == (granularity - 1) {
  1020. status[i/granularity] = group
  1021. group = 0
  1022. }
  1023. }
  1024. if day%granularity != 0 {
  1025. status[len(status)-1] = group
  1026. }
  1027. peoples[key] = status
  1028. }
  1029. return global, locals, peoples
  1030. }
  1031. func (analyser *BurndownAnalysis) updateHistories(
  1032. globalStatus []int64, fileStatuses map[string][]int64, peopleStatuses [][]int64, delta int) {
  1033. for i := 0; i < delta; i++ {
  1034. analyser.globalHistory = append(analyser.globalHistory, globalStatus)
  1035. }
  1036. toDelete := make([]string, 0)
  1037. for key, fh := range analyser.fileHistories {
  1038. ls, exists := fileStatuses[key]
  1039. if !exists {
  1040. toDelete = append(toDelete, key)
  1041. } else {
  1042. for i := 0; i < delta; i++ {
  1043. fh = append(fh, ls)
  1044. }
  1045. analyser.fileHistories[key] = fh
  1046. }
  1047. }
  1048. for _, key := range toDelete {
  1049. delete(analyser.fileHistories, key)
  1050. }
  1051. for key, ls := range fileStatuses {
  1052. fh, exists := analyser.fileHistories[key]
  1053. if exists {
  1054. continue
  1055. }
  1056. for i := 0; i < delta; i++ {
  1057. fh = append(fh, ls)
  1058. }
  1059. analyser.fileHistories[key] = fh
  1060. }
  1061. for key, ph := range analyser.peopleHistories {
  1062. ls := peopleStatuses[key]
  1063. for i := 0; i < delta; i++ {
  1064. ph = append(ph, ls)
  1065. }
  1066. analyser.peopleHistories[key] = ph
  1067. }
  1068. }
  1069. func init() {
  1070. Registry.Register(&BurndownAnalysis{})
  1071. }