burndown.go 34 KB

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