burndown.go 38 KB

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