burndown.go 39 KB

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