burndown.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. package leaves
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "math"
  9. "os"
  10. "sort"
  11. "sync"
  12. "time"
  13. "unicode/utf8"
  14. "github.com/gogo/protobuf/proto"
  15. "github.com/sergi/go-diff/diffmatchpatch"
  16. "gopkg.in/src-d/go-git.v4"
  17. "gopkg.in/src-d/go-git.v4/plumbing"
  18. "gopkg.in/src-d/go-git.v4/plumbing/object"
  19. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  20. "gopkg.in/src-d/hercules.v10/internal/burndown"
  21. "gopkg.in/src-d/hercules.v10/internal/core"
  22. "gopkg.in/src-d/hercules.v10/internal/pb"
  23. items "gopkg.in/src-d/hercules.v10/internal/plumbing"
  24. "gopkg.in/src-d/hercules.v10/internal/plumbing/identity"
  25. "gopkg.in/src-d/hercules.v10/internal/rbtree"
  26. "gopkg.in/src-d/hercules.v10/internal/yaml"
  27. )
  28. // BurndownAnalysis allows to gather the line burndown statistics for a Git repository.
  29. // It is a LeafPipelineItem.
  30. // Reference: https://erikbern.com/2016/12/05/the-half-life-of-code.html
  31. type BurndownAnalysis struct {
  32. // Granularity sets the size of each band - the number of ticks it spans.
  33. // Smaller values provide better resolution but require more work and eat more
  34. // memory. 30 ticks is usually enough.
  35. Granularity int
  36. // Sampling sets how detailed is the statistic - the size of the interval in
  37. // ticks between consecutive measurements. It may not be greater than Granularity. Try 15 or 30.
  38. Sampling int
  39. // TrackFiles enables or disables the fine-grained per-file burndown analysis.
  40. // It does not change the project level burndown results.
  41. TrackFiles bool
  42. // PeopleNumber is the number of developers for which to collect the burndown stats. 0 disables it.
  43. PeopleNumber int
  44. // TickSize indicates the size of each time granule: day, hour, week, etc.
  45. TickSize time.Duration
  46. // HibernationThreshold sets the hibernation threshold for the underlying
  47. // RBTree allocator. It is useful to trade CPU time for reduced peak memory consumption
  48. // if there are many branches.
  49. HibernationThreshold int
  50. // HibernationToDisk specifies whether the hibernated RBTree allocator must be saved on disk
  51. // rather than kept in memory.
  52. HibernationToDisk bool
  53. // HibernationDirectory is the name of the temporary directory to use for saving hibernated
  54. // RBTree allocators.
  55. HibernationDirectory string
  56. // Debug activates the debugging mode. Analyse() runs slower in this mode
  57. // but it accurately checks all the intermediate states for invariant
  58. // violations.
  59. Debug bool
  60. // Repository points to the analysed Git repository struct from go-git.
  61. repository *git.Repository
  62. // globalHistory is the daily deltas of daily line counts.
  63. // E.g. tick 0: tick 0 +50 lines
  64. // tick 10: tick 0 -10 lines; tick 10 +20 lines
  65. // tick 12: tick 0 -5 lines; tick 10 -3 lines; tick 12 +10 lines
  66. // map [0] [0] = 50
  67. // map[10] [0] = -10
  68. // map[10][10] = 20
  69. // map[12] [0] = -5
  70. // map[12][10] = -3
  71. // map[12][12] = 10
  72. globalHistory sparseHistory
  73. // fileHistories is the daily deltas of each file's daily line counts.
  74. fileHistories map[string]sparseHistory
  75. // peopleHistories is the daily deltas of each person's daily line counts.
  76. peopleHistories []sparseHistory
  77. // files is the mapping <file path> -> *File.
  78. files map[string]*burndown.File
  79. // fileAllocator is the allocator for RBTree-s in `files`.
  80. fileAllocator *rbtree.Allocator
  81. // hibernatedFileName is the path to the serialized `fileAllocator`.
  82. hibernatedFileName string
  83. // mergedFiles is used during merges to record the real file hashes
  84. mergedFiles map[string]bool
  85. // mergedAuthor of the processed merge commit
  86. mergedAuthor int
  87. // renames is a quick and dirty solution for the "future branch renames" problem.
  88. renames map[string]string
  89. // deletions is a quick and dirty solution for the "real merge removals" problem.
  90. deletions map[string]bool
  91. // matrix is the mutual deletions and self insertions.
  92. matrix []map[int]int64
  93. // tick is the most recent tick index processed.
  94. tick int
  95. // previousTick is the tick from the previous sample period -
  96. // different from TicksSinceStart.previousTick.
  97. previousTick int
  98. // references IdentityDetector.ReversedPeopleDict
  99. reversedPeopleDict []string
  100. l core.Logger
  101. }
  102. // BurndownResult carries the result of running BurndownAnalysis - it is returned by
  103. // BurndownAnalysis.Finalize().
  104. type BurndownResult struct {
  105. // [number of samples][number of bands]
  106. // The number of samples depends on Sampling: the less Sampling, the bigger the number.
  107. // The number of bands depends on Granularity: the less Granularity, the bigger the number.
  108. GlobalHistory DenseHistory
  109. // The key is a path inside the Git repository. The value's dimensions are the same as
  110. // in GlobalHistory.
  111. FileHistories map[string]DenseHistory
  112. // The key is a path inside the Git repository. The value is a mapping from developer indexes
  113. // (see reversedPeopleDict) and the owned line numbers. Their sum equals to the total number of
  114. // lines in the file.
  115. FileOwnership map[string]map[int]int
  116. // [number of people][number of samples][number of bands]
  117. PeopleHistories []DenseHistory
  118. // [number of people][number of people + 2]
  119. // The first element is the total number of lines added by the author.
  120. // The second element is the number of removals by unidentified authors (outside reversedPeopleDict).
  121. // The rest of the elements are equal the number of line removals by the corresponding
  122. // authors in reversedPeopleDict: 2 -> 0, 3 -> 1, etc.
  123. PeopleMatrix DenseHistory
  124. // The following members are private.
  125. // reversedPeopleDict is borrowed from IdentityDetector and becomes available after
  126. // Pipeline.Initialize(facts map[string]interface{}). Thus it can be obtained via
  127. // facts[FactIdentityDetectorReversedPeopleDict].
  128. reversedPeopleDict []string
  129. // TickSize references TicksSinceStart.TickSize
  130. tickSize time.Duration
  131. // sampling and granularity are copied from BurndownAnalysis and stored for service purposes
  132. // such as merging several results together.
  133. sampling int
  134. granularity int
  135. }
  136. const (
  137. // ConfigBurndownGranularity is the name of the option to set BurndownAnalysis.Granularity.
  138. ConfigBurndownGranularity = "Burndown.Granularity"
  139. // ConfigBurndownSampling is the name of the option to set BurndownAnalysis.Sampling.
  140. ConfigBurndownSampling = "Burndown.Sampling"
  141. // ConfigBurndownTrackFiles enables burndown collection for files.
  142. ConfigBurndownTrackFiles = "Burndown.TrackFiles"
  143. // ConfigBurndownTrackPeople enables burndown collection for authors.
  144. ConfigBurndownTrackPeople = "Burndown.TrackPeople"
  145. // ConfigBurndownHibernationThreshold sets the hibernation threshold for the underlying
  146. // RBTree allocator. It is useful to trade CPU time for reduced peak memory consumption
  147. // if there are many branches.
  148. ConfigBurndownHibernationThreshold = "Burndown.HibernationThreshold"
  149. // ConfigBurndownHibernationToDisk sets whether the hibernated RBTree allocator must be saved
  150. // on disk rather than kept in memory.
  151. ConfigBurndownHibernationToDisk = "Burndown.HibernationOnDisk"
  152. // ConfigBurndownHibernationDirectory sets the name of the temporary directory to use for
  153. // saving hibernated RBTree allocators.
  154. ConfigBurndownHibernationDirectory = "Burndown.HibernationDirectory"
  155. // ConfigBurndownDebug enables some extra debug assertions.
  156. ConfigBurndownDebug = "Burndown.Debug"
  157. // DefaultBurndownGranularity is the default number of ticks for BurndownAnalysis.Granularity
  158. // and BurndownAnalysis.Sampling.
  159. DefaultBurndownGranularity = 30
  160. // authorSelf is the internal author index which is used in BurndownAnalysis.Finalize() to
  161. // format the author overwrites matrix.
  162. authorSelf = identity.AuthorMissing - 1
  163. )
  164. type sparseHistory = map[int]map[int]int64
  165. // DenseHistory is the matrix [number of samples][number of bands] -> number of lines.
  166. // y x
  167. type DenseHistory = [][]int64
  168. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  169. func (analyser *BurndownAnalysis) Name() string {
  170. return "Burndown"
  171. }
  172. // Provides returns the list of names of entities which are produced by this PipelineItem.
  173. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  174. // to this list. Also used by core.Registry to build the global map of providers.
  175. func (analyser *BurndownAnalysis) Provides() []string {
  176. return []string{}
  177. }
  178. // Requires returns the list of names of entities which are needed by this PipelineItem.
  179. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  180. // entities are Provides() upstream.
  181. func (analyser *BurndownAnalysis) Requires() []string {
  182. return []string{
  183. items.DependencyFileDiff, items.DependencyTreeChanges, items.DependencyBlobCache,
  184. items.DependencyTick, identity.DependencyAuthor}
  185. }
  186. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  187. func (analyser *BurndownAnalysis) ListConfigurationOptions() []core.ConfigurationOption {
  188. options := [...]core.ConfigurationOption{{
  189. Name: ConfigBurndownGranularity,
  190. Description: "How many time ticks there are in a single band.",
  191. Flag: "granularity",
  192. Type: core.IntConfigurationOption,
  193. Default: DefaultBurndownGranularity}, {
  194. Name: ConfigBurndownSampling,
  195. Description: "How frequently to record the state in time ticks.",
  196. Flag: "sampling",
  197. Type: core.IntConfigurationOption,
  198. Default: DefaultBurndownGranularity}, {
  199. Name: ConfigBurndownTrackFiles,
  200. Description: "Record detailed statistics per each file.",
  201. Flag: "burndown-files",
  202. Type: core.BoolConfigurationOption,
  203. Default: false}, {
  204. Name: ConfigBurndownTrackPeople,
  205. Description: "Record detailed statistics per each developer.",
  206. Flag: "burndown-people",
  207. Type: core.BoolConfigurationOption,
  208. Default: false}, {
  209. Name: ConfigBurndownHibernationThreshold,
  210. Description: "The minimum size for the allocated memory in each branch to be compressed." +
  211. "0 disables this optimization. Lower values trade CPU time more. Sane examples: Nx1000.",
  212. Flag: "burndown-hibernation-threshold",
  213. Type: core.IntConfigurationOption,
  214. Default: 0}, {
  215. Name: ConfigBurndownHibernationToDisk,
  216. Description: "Save hibernated RBTree allocators to disk rather than keep it in memory; " +
  217. "requires --burndown-hibernation-threshold to be greater than zero.",
  218. Flag: "burndown-hibernation-disk",
  219. Type: core.BoolConfigurationOption,
  220. Default: false}, {
  221. Name: ConfigBurndownHibernationDirectory,
  222. Description: "Temporary directory where to save the hibernated RBTree allocators; " +
  223. "requires --burndown-hibernation-disk.",
  224. Flag: "burndown-hibernation-dir",
  225. Type: core.PathConfigurationOption,
  226. Default: ""}, {
  227. Name: ConfigBurndownDebug,
  228. Description: "Validate the trees at each step.",
  229. Flag: "burndown-debug",
  230. Type: core.BoolConfigurationOption,
  231. Default: false},
  232. }
  233. return options[:]
  234. }
  235. // Configure sets the properties previously published by ListConfigurationOptions().
  236. func (analyser *BurndownAnalysis) Configure(facts map[string]interface{}) error {
  237. if l, exists := facts[core.ConfigLogger].(core.Logger); exists {
  238. analyser.l = l
  239. } else {
  240. analyser.l = core.NewLogger()
  241. }
  242. if val, exists := facts[ConfigBurndownGranularity].(int); exists {
  243. analyser.Granularity = val
  244. }
  245. if val, exists := facts[ConfigBurndownSampling].(int); exists {
  246. analyser.Sampling = val
  247. }
  248. if val, exists := facts[ConfigBurndownTrackFiles].(bool); exists {
  249. analyser.TrackFiles = val
  250. }
  251. if people, exists := facts[ConfigBurndownTrackPeople].(bool); people {
  252. if val, exists := facts[identity.FactIdentityDetectorPeopleCount].(int); exists {
  253. if val < 0 {
  254. return fmt.Errorf("PeopleNumber is negative: %d", val)
  255. }
  256. analyser.PeopleNumber = val
  257. analyser.reversedPeopleDict = facts[identity.FactIdentityDetectorReversedPeopleDict].([]string)
  258. }
  259. } else if exists {
  260. analyser.PeopleNumber = 0
  261. }
  262. if val, exists := facts[ConfigBurndownHibernationThreshold].(int); exists {
  263. analyser.HibernationThreshold = val
  264. }
  265. if val, exists := facts[ConfigBurndownHibernationToDisk].(bool); exists {
  266. analyser.HibernationToDisk = val
  267. }
  268. if val, exists := facts[ConfigBurndownHibernationDirectory].(string); exists {
  269. analyser.HibernationDirectory = val
  270. }
  271. if val, exists := facts[ConfigBurndownDebug].(bool); exists {
  272. analyser.Debug = val
  273. }
  274. if val, exists := facts[items.FactTickSize].(time.Duration); exists {
  275. analyser.TickSize = val
  276. }
  277. return nil
  278. }
  279. // Flag for the command line switch which enables this analysis.
  280. func (analyser *BurndownAnalysis) Flag() string {
  281. return "burndown"
  282. }
  283. // Description returns the text which explains what the analysis is doing.
  284. func (analyser *BurndownAnalysis) Description() string {
  285. return "Line burndown stats indicate the numbers of lines which were last edited within " +
  286. "specific time intervals through time. Search for \"git-of-theseus\" in the internet."
  287. }
  288. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  289. // calls. The repository which is going to be analysed is supplied as an argument.
  290. func (analyser *BurndownAnalysis) Initialize(repository *git.Repository) error {
  291. analyser.l = core.NewLogger()
  292. if analyser.Granularity <= 0 {
  293. analyser.l.Warnf("adjusted the granularity to %d ticks\n",
  294. DefaultBurndownGranularity)
  295. analyser.Granularity = DefaultBurndownGranularity
  296. }
  297. if analyser.Sampling <= 0 {
  298. analyser.l.Warnf("adjusted the sampling to %d ticks\n",
  299. DefaultBurndownGranularity)
  300. analyser.Sampling = DefaultBurndownGranularity
  301. }
  302. if analyser.Sampling > analyser.Granularity {
  303. analyser.l.Warnf("granularity may not be less than sampling, adjusted to %d\n",
  304. analyser.Granularity)
  305. analyser.Sampling = analyser.Granularity
  306. }
  307. if analyser.TickSize == 0 {
  308. def := items.DefaultTicksSinceStartTickSize * time.Hour
  309. analyser.l.Warnf("tick size was not set, adjusted to %v\n", def)
  310. analyser.TickSize = items.DefaultTicksSinceStartTickSize * time.Hour
  311. }
  312. analyser.repository = repository
  313. analyser.globalHistory = sparseHistory{}
  314. analyser.fileHistories = map[string]sparseHistory{}
  315. if analyser.PeopleNumber < 0 {
  316. return fmt.Errorf("PeopleNumber is negative: %d", analyser.PeopleNumber)
  317. }
  318. analyser.peopleHistories = make([]sparseHistory, analyser.PeopleNumber)
  319. analyser.files = map[string]*burndown.File{}
  320. analyser.fileAllocator = rbtree.NewAllocator()
  321. analyser.fileAllocator.HibernationThreshold = analyser.HibernationThreshold
  322. analyser.mergedFiles = map[string]bool{}
  323. analyser.mergedAuthor = identity.AuthorMissing
  324. analyser.renames = map[string]string{}
  325. analyser.deletions = map[string]bool{}
  326. analyser.matrix = make([]map[int]int64, analyser.PeopleNumber)
  327. analyser.tick = 0
  328. analyser.previousTick = 0
  329. return nil
  330. }
  331. // Consume runs this PipelineItem on the next commit's data.
  332. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  333. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  334. // This function returns the mapping with analysis results. The keys must be the same as
  335. // in Provides(). If there was an error, nil is returned.
  336. func (analyser *BurndownAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  337. if analyser.fileAllocator.Size() == 0 && len(analyser.files) > 0 {
  338. panic("BurndownAnalysis.Consume() was called on a hibernated instance")
  339. }
  340. author := deps[identity.DependencyAuthor].(int)
  341. tick := deps[items.DependencyTick].(int)
  342. if !deps[core.DependencyIsMerge].(bool) {
  343. analyser.tick = tick
  344. analyser.onNewTick()
  345. } else {
  346. // effectively disables the status updates if the commit is a merge
  347. // we will analyse the conflicts resolution in Merge()
  348. analyser.tick = burndown.TreeMergeMark
  349. analyser.mergedFiles = map[string]bool{}
  350. analyser.mergedAuthor = author
  351. }
  352. cache := deps[items.DependencyBlobCache].(map[plumbing.Hash]*items.CachedBlob)
  353. treeDiffs := deps[items.DependencyTreeChanges].(object.Changes)
  354. fileDiffs := deps[items.DependencyFileDiff].(map[string]items.FileDiffData)
  355. for _, change := range treeDiffs {
  356. action, _ := change.Action()
  357. var err error
  358. switch action {
  359. case merkletrie.Insert:
  360. err = analyser.handleInsertion(change, author, cache)
  361. case merkletrie.Delete:
  362. err = analyser.handleDeletion(change, author, cache)
  363. case merkletrie.Modify:
  364. err = analyser.handleModification(change, author, cache, fileDiffs)
  365. }
  366. if err != nil {
  367. return nil, err
  368. }
  369. }
  370. // in case there is a merge analyser.tick equals to TreeMergeMark
  371. analyser.tick = tick
  372. return nil, nil
  373. }
  374. // Fork clones this item. Everything is copied by reference except the files
  375. // which are copied by value.
  376. func (analyser *BurndownAnalysis) Fork(n int) []core.PipelineItem {
  377. result := make([]core.PipelineItem, n)
  378. for i := range result {
  379. clone := *analyser
  380. clone.files = map[string]*burndown.File{}
  381. clone.fileAllocator = clone.fileAllocator.Clone()
  382. for key, file := range analyser.files {
  383. clone.files[key] = file.CloneShallow(clone.fileAllocator)
  384. }
  385. result[i] = &clone
  386. }
  387. return result
  388. }
  389. // Merge combines several items together. We apply the special file merging logic here.
  390. func (analyser *BurndownAnalysis) Merge(branches []core.PipelineItem) {
  391. all := make([]*BurndownAnalysis, len(branches)+1)
  392. all[0] = analyser
  393. for i, branch := range branches {
  394. all[i+1] = branch.(*BurndownAnalysis)
  395. }
  396. keys := map[string]bool{}
  397. for _, burn := range all {
  398. for key, val := range burn.mergedFiles {
  399. // (*)
  400. // there can be contradicting flags,
  401. // e.g. item was renamed and a new item written on its place
  402. // this may be not exactly accurate
  403. keys[key] = keys[key] || val
  404. }
  405. }
  406. for key, val := range keys {
  407. if !val {
  408. for _, burn := range all {
  409. if f, exists := burn.files[key]; exists {
  410. f.Delete()
  411. }
  412. delete(burn.files, key)
  413. }
  414. continue
  415. }
  416. files := make([]*burndown.File, 0, len(all))
  417. for _, burn := range all {
  418. file := burn.files[key]
  419. if file != nil {
  420. // file can be nil if it is considered binary in this branch
  421. files = append(files, file)
  422. }
  423. }
  424. if len(files) == 0 {
  425. // so we could be wrong in (*) and there is no such file eventually
  426. // it could be also removed in the merge commit itself
  427. continue
  428. }
  429. files[0].Merge(
  430. analyser.packPersonWithTick(analyser.mergedAuthor, analyser.tick),
  431. files[1:]...)
  432. for _, burn := range all {
  433. if burn.files[key] != files[0] {
  434. if burn.files[key] != nil {
  435. burn.files[key].Delete()
  436. }
  437. burn.files[key] = files[0].CloneDeep(burn.fileAllocator)
  438. }
  439. }
  440. }
  441. analyser.onNewTick()
  442. }
  443. // Hibernate compresses the bound RBTree memory with the files.
  444. func (analyser *BurndownAnalysis) Hibernate() error {
  445. analyser.fileAllocator.Hibernate()
  446. if analyser.HibernationToDisk {
  447. file, err := ioutil.TempFile(analyser.HibernationDirectory, "*-hercules.bin")
  448. if err != nil {
  449. return err
  450. }
  451. analyser.hibernatedFileName = file.Name()
  452. err = file.Close()
  453. if err != nil {
  454. analyser.hibernatedFileName = ""
  455. return err
  456. }
  457. err = analyser.fileAllocator.Serialize(analyser.hibernatedFileName)
  458. if err != nil {
  459. analyser.hibernatedFileName = ""
  460. return err
  461. }
  462. }
  463. return nil
  464. }
  465. // Boot decompresses the bound RBTree memory with the files.
  466. func (analyser *BurndownAnalysis) Boot() error {
  467. if analyser.hibernatedFileName != "" {
  468. err := analyser.fileAllocator.Deserialize(analyser.hibernatedFileName)
  469. if err != nil {
  470. return err
  471. }
  472. err = os.Remove(analyser.hibernatedFileName)
  473. if err != nil {
  474. return err
  475. }
  476. analyser.hibernatedFileName = ""
  477. }
  478. analyser.fileAllocator.Boot()
  479. return nil
  480. }
  481. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  482. func (analyser *BurndownAnalysis) Finalize() interface{} {
  483. globalHistory, lastTick := analyser.groupSparseHistory(analyser.globalHistory, -1)
  484. fileHistories := map[string]DenseHistory{}
  485. fileOwnership := map[string]map[int]int{}
  486. for key, history := range analyser.fileHistories {
  487. if len(history) == 0 {
  488. continue
  489. }
  490. fileHistories[key], _ = analyser.groupSparseHistory(history, lastTick)
  491. file := analyser.files[key]
  492. previousLine := 0
  493. previousAuthor := identity.AuthorMissing
  494. ownership := map[int]int{}
  495. fileOwnership[key] = ownership
  496. file.ForEach(func(line, value int) {
  497. length := line - previousLine
  498. if length > 0 {
  499. ownership[previousAuthor] += length
  500. }
  501. previousLine = line
  502. previousAuthor, _ = analyser.unpackPersonWithTick(int(value))
  503. if previousAuthor == identity.AuthorMissing {
  504. previousAuthor = -1
  505. }
  506. })
  507. }
  508. peopleHistories := make([]DenseHistory, analyser.PeopleNumber)
  509. for i, history := range analyser.peopleHistories {
  510. if len(history) > 0 {
  511. // there can be people with only trivial merge commits and without own lines
  512. peopleHistories[i], _ = analyser.groupSparseHistory(history, lastTick)
  513. } else {
  514. peopleHistories[i] = make(DenseHistory, len(globalHistory))
  515. for j, gh := range globalHistory {
  516. peopleHistories[i][j] = make([]int64, len(gh))
  517. }
  518. }
  519. }
  520. var peopleMatrix DenseHistory
  521. if len(analyser.matrix) > 0 {
  522. peopleMatrix = make(DenseHistory, analyser.PeopleNumber)
  523. for i, row := range analyser.matrix {
  524. mrow := make([]int64, analyser.PeopleNumber+2)
  525. peopleMatrix[i] = mrow
  526. for key, val := range row {
  527. if key == identity.AuthorMissing {
  528. key = -1
  529. } else if key == authorSelf {
  530. key = -2
  531. }
  532. mrow[key+2] = val
  533. }
  534. }
  535. }
  536. return BurndownResult{
  537. GlobalHistory: globalHistory,
  538. FileHistories: fileHistories,
  539. FileOwnership: fileOwnership,
  540. PeopleHistories: peopleHistories,
  541. PeopleMatrix: peopleMatrix,
  542. tickSize: analyser.TickSize,
  543. reversedPeopleDict: analyser.reversedPeopleDict,
  544. sampling: analyser.Sampling,
  545. granularity: analyser.Granularity,
  546. }
  547. }
  548. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  549. // The text format is YAML and the bytes format is Protocol Buffers.
  550. func (analyser *BurndownAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  551. burndownResult, ok := result.(BurndownResult)
  552. if !ok {
  553. return fmt.Errorf("result is not a burndown result: '%v'", result)
  554. }
  555. if binary {
  556. return analyser.serializeBinary(&burndownResult, writer)
  557. }
  558. analyser.serializeText(&burndownResult, writer)
  559. return nil
  560. }
  561. // Deserialize converts the specified protobuf bytes to BurndownResult.
  562. func (analyser *BurndownAnalysis) Deserialize(pbmessage []byte) (interface{}, error) {
  563. msg := pb.BurndownAnalysisResults{}
  564. err := proto.Unmarshal(pbmessage, &msg)
  565. if err != nil {
  566. return nil, err
  567. }
  568. convertCSR := func(mat *pb.BurndownSparseMatrix) DenseHistory {
  569. res := make(DenseHistory, mat.NumberOfRows)
  570. for i := 0; i < int(mat.NumberOfRows); i++ {
  571. res[i] = make([]int64, mat.NumberOfColumns)
  572. for j := 0; j < len(mat.Rows[i].Columns); j++ {
  573. res[i][j] = int64(mat.Rows[i].Columns[j])
  574. }
  575. }
  576. return res
  577. }
  578. result := BurndownResult{
  579. GlobalHistory: convertCSR(msg.Project),
  580. FileHistories: map[string]DenseHistory{},
  581. FileOwnership: map[string]map[int]int{},
  582. tickSize: time.Duration(msg.TickSize),
  583. granularity: int(msg.Granularity),
  584. sampling: int(msg.Sampling),
  585. }
  586. for i, mat := range msg.Files {
  587. result.FileHistories[mat.Name] = convertCSR(mat)
  588. ownership := map[int]int{}
  589. result.FileOwnership[mat.Name] = ownership
  590. for key, val := range msg.FilesOwnership[i].Value {
  591. ownership[int(key)] = int(val)
  592. }
  593. }
  594. result.reversedPeopleDict = make([]string, len(msg.People))
  595. result.PeopleHistories = make([]DenseHistory, len(msg.People))
  596. for i, mat := range msg.People {
  597. result.PeopleHistories[i] = convertCSR(mat)
  598. result.reversedPeopleDict[i] = mat.Name
  599. }
  600. if msg.PeopleInteraction != nil {
  601. result.PeopleMatrix = make(DenseHistory, msg.PeopleInteraction.NumberOfRows)
  602. }
  603. for i := 0; i < len(result.PeopleMatrix); i++ {
  604. result.PeopleMatrix[i] = make([]int64, msg.PeopleInteraction.NumberOfColumns)
  605. for j := int(msg.PeopleInteraction.Indptr[i]); j < int(msg.PeopleInteraction.Indptr[i+1]); j++ {
  606. result.PeopleMatrix[i][msg.PeopleInteraction.Indices[j]] = msg.PeopleInteraction.Data[j]
  607. }
  608. }
  609. return result, nil
  610. }
  611. // MergeResults combines two BurndownResult-s together.
  612. func (analyser *BurndownAnalysis) MergeResults(
  613. r1, r2 interface{}, c1, c2 *core.CommonAnalysisResult) interface{} {
  614. bar1 := r1.(BurndownResult)
  615. bar2 := r2.(BurndownResult)
  616. if bar1.tickSize != bar2.tickSize {
  617. return fmt.Errorf("mismatching tick sizes (r1: %d, r2: %d) received",
  618. bar1.tickSize, bar2.tickSize)
  619. }
  620. // for backwards-compatibility, if no tick size is present set to default
  621. analyser.TickSize = bar1.tickSize
  622. if analyser.TickSize == 0 {
  623. analyser.TickSize = items.DefaultTicksSinceStartTickSize * time.Hour
  624. }
  625. merged := BurndownResult{
  626. tickSize: analyser.TickSize,
  627. }
  628. if bar1.sampling < bar2.sampling {
  629. merged.sampling = bar1.sampling
  630. } else {
  631. merged.sampling = bar2.sampling
  632. }
  633. if bar1.granularity < bar2.granularity {
  634. merged.granularity = bar1.granularity
  635. } else {
  636. merged.granularity = bar2.granularity
  637. }
  638. var people map[string]identity.MergedIndex
  639. people, merged.reversedPeopleDict = identity.MergeReversedDictsIdentities(
  640. bar1.reversedPeopleDict, bar2.reversedPeopleDict)
  641. var wg sync.WaitGroup
  642. if len(bar1.GlobalHistory) > 0 || len(bar2.GlobalHistory) > 0 {
  643. wg.Add(1)
  644. go func() {
  645. defer wg.Done()
  646. merged.GlobalHistory = analyser.mergeMatrices(
  647. bar1.GlobalHistory, bar2.GlobalHistory,
  648. bar1.granularity, bar1.sampling,
  649. bar2.granularity, bar2.sampling,
  650. bar1.tickSize,
  651. c1, c2)
  652. }()
  653. }
  654. // we don't merge files
  655. if len(merged.reversedPeopleDict) > 0 {
  656. if len(bar1.PeopleHistories) > 0 || len(bar2.PeopleHistories) > 0 {
  657. merged.PeopleHistories = make([]DenseHistory, len(merged.reversedPeopleDict))
  658. for i, key := range merged.reversedPeopleDict {
  659. ptrs := people[key]
  660. wg.Add(1)
  661. go func(i int) {
  662. defer wg.Done()
  663. var m1, m2 DenseHistory
  664. if ptrs.First >= 0 {
  665. m1 = bar1.PeopleHistories[ptrs.First]
  666. }
  667. if ptrs.Second >= 0 {
  668. m2 = bar2.PeopleHistories[ptrs.Second]
  669. }
  670. merged.PeopleHistories[i] = analyser.mergeMatrices(
  671. m1, m2,
  672. bar1.granularity, bar1.sampling,
  673. bar2.granularity, bar2.sampling,
  674. bar1.tickSize,
  675. c1, c2,
  676. )
  677. }(i)
  678. }
  679. }
  680. wg.Add(1)
  681. go func() {
  682. defer wg.Done()
  683. if len(bar2.PeopleMatrix) == 0 {
  684. merged.PeopleMatrix = bar1.PeopleMatrix
  685. // extend the matrix in both directions
  686. for i := 0; i < len(merged.PeopleMatrix); i++ {
  687. for j := len(bar1.reversedPeopleDict); j < len(merged.reversedPeopleDict); j++ {
  688. merged.PeopleMatrix[i] = append(merged.PeopleMatrix[i], 0)
  689. }
  690. }
  691. if len(bar1.PeopleMatrix) > 0 {
  692. for i := len(bar1.reversedPeopleDict); i < len(merged.reversedPeopleDict); i++ {
  693. merged.PeopleMatrix = append(
  694. merged.PeopleMatrix, make([]int64, len(merged.reversedPeopleDict)+2))
  695. }
  696. }
  697. } else {
  698. merged.PeopleMatrix = make(DenseHistory, len(merged.reversedPeopleDict))
  699. for i := range merged.PeopleMatrix {
  700. merged.PeopleMatrix[i] = make([]int64, len(merged.reversedPeopleDict)+2)
  701. }
  702. for i, key := range bar1.reversedPeopleDict {
  703. mi := people[key].Final // index in merged.reversedPeopleDict
  704. copy(merged.PeopleMatrix[mi][:2], bar1.PeopleMatrix[i][:2])
  705. for j, val := range bar1.PeopleMatrix[i][2:] {
  706. merged.PeopleMatrix[mi][2+people[bar1.reversedPeopleDict[j]].Final] = val
  707. }
  708. }
  709. for i, key := range bar2.reversedPeopleDict {
  710. mi := people[key].Final // index in merged.reversedPeopleDict
  711. merged.PeopleMatrix[mi][0] += bar2.PeopleMatrix[i][0]
  712. merged.PeopleMatrix[mi][1] += bar2.PeopleMatrix[i][1]
  713. for j, val := range bar2.PeopleMatrix[i][2:] {
  714. merged.PeopleMatrix[mi][2+people[bar2.reversedPeopleDict[j]].Final] += val
  715. }
  716. }
  717. }
  718. }()
  719. }
  720. wg.Wait()
  721. return merged
  722. }
  723. func roundTime(t time.Time, d time.Duration, dir bool) int {
  724. if !dir {
  725. t = items.FloorTime(t, d)
  726. }
  727. ticks := float64(t.Unix()) / d.Seconds()
  728. if dir {
  729. return int(math.Ceil(ticks))
  730. }
  731. return int(math.Floor(ticks))
  732. }
  733. // mergeMatrices takes two [number of samples][number of bands] matrices,
  734. // resamples them to ticks so that they become square, sums and resamples back to the
  735. // least of (sampling1, sampling2) and (granularity1, granularity2).
  736. func (analyser *BurndownAnalysis) mergeMatrices(
  737. m1, m2 DenseHistory, granularity1, sampling1, granularity2, sampling2 int, tickSize time.Duration,
  738. c1, c2 *core.CommonAnalysisResult) DenseHistory {
  739. commonMerged := c1.Copy()
  740. commonMerged.Merge(c2)
  741. var granularity, sampling int
  742. if sampling1 < sampling2 {
  743. sampling = sampling1
  744. } else {
  745. sampling = sampling2
  746. }
  747. if granularity1 < granularity2 {
  748. granularity = granularity1
  749. } else {
  750. granularity = granularity2
  751. }
  752. size := roundTime(commonMerged.EndTimeAsTime(), tickSize, true) -
  753. roundTime(commonMerged.BeginTimeAsTime(), tickSize, false)
  754. perTick := make([][]float32, size+granularity)
  755. for i := range perTick {
  756. perTick[i] = make([]float32, size+sampling)
  757. }
  758. if len(m1) > 0 {
  759. addBurndownMatrix(m1, granularity1, sampling1, perTick,
  760. roundTime(c1.BeginTimeAsTime(), tickSize, false)-roundTime(commonMerged.BeginTimeAsTime(), tickSize, false))
  761. }
  762. if len(m2) > 0 {
  763. addBurndownMatrix(m2, granularity2, sampling2, perTick,
  764. roundTime(c2.BeginTimeAsTime(), tickSize, false)-roundTime(commonMerged.BeginTimeAsTime(), tickSize, false))
  765. }
  766. // convert daily to [][]int64
  767. result := make(DenseHistory, (size+sampling-1)/sampling)
  768. for i := range result {
  769. result[i] = make([]int64, (size+granularity-1)/granularity)
  770. sampledIndex := (i+1)*sampling - 1
  771. for j := 0; j < len(result[i]); j++ {
  772. accum := float32(0)
  773. for k := j * granularity; k < (j+1)*granularity; k++ {
  774. accum += perTick[sampledIndex][k]
  775. }
  776. result[i][j] = int64(accum)
  777. }
  778. }
  779. return result
  780. }
  781. // Explode `matrix` so that it is daily sampled and has daily bands, shift by `offset` ticks
  782. // and add to the accumulator. `daily` size is square and is guaranteed to fit `matrix` by
  783. // the caller.
  784. // Rows: *at least* len(matrix) * sampling + offset
  785. // Columns: *at least* len(matrix[...]) * granularity + offset
  786. // `matrix` can be sparse, so that the last columns which are equal to 0 are truncated.
  787. func addBurndownMatrix(matrix DenseHistory, granularity, sampling int, accPerTick [][]float32, offset int) {
  788. // Determine the maximum number of bands; the actual one may be larger but we do not care
  789. maxCols := 0
  790. for _, row := range matrix {
  791. if maxCols < len(row) {
  792. maxCols = len(row)
  793. }
  794. }
  795. neededRows := len(matrix)*sampling + offset
  796. if len(accPerTick) < neededRows {
  797. log.Panicf("merge bug: too few per-tick rows: required %d, have %d",
  798. neededRows, len(accPerTick))
  799. }
  800. if len(accPerTick[0]) < maxCols {
  801. log.Panicf("merge bug: too few per-tick cols: required %d, have %d",
  802. maxCols, len(accPerTick[0]))
  803. }
  804. perTick := make([][]float32, len(accPerTick))
  805. for i, row := range accPerTick {
  806. perTick[i] = make([]float32, len(row))
  807. }
  808. for x := 0; x < maxCols; x++ {
  809. for y := 0; y < len(matrix); y++ {
  810. if x*granularity > (y+1)*sampling {
  811. // the future is zeros
  812. continue
  813. }
  814. decay := func(startIndex int, startVal float32) {
  815. if startVal == 0 {
  816. return
  817. }
  818. k := float32(matrix[y][x]) / startVal // <= 1
  819. scale := float32((y+1)*sampling - startIndex)
  820. for i := x * granularity; i < (x+1)*granularity; i++ {
  821. initial := perTick[startIndex-1+offset][i+offset]
  822. for j := startIndex; j < (y+1)*sampling; j++ {
  823. perTick[j+offset][i+offset] = initial * (1 + (k-1)*float32(j-startIndex+1)/scale)
  824. }
  825. }
  826. }
  827. raise := func(finishIndex int, finishVal float32) {
  828. var initial float32
  829. if y > 0 {
  830. initial = float32(matrix[y-1][x])
  831. }
  832. startIndex := y * sampling
  833. if startIndex < x*granularity {
  834. startIndex = x * granularity
  835. }
  836. if startIndex == finishIndex {
  837. return
  838. }
  839. avg := (finishVal - initial) / float32(finishIndex-startIndex)
  840. for j := y * sampling; j < finishIndex; j++ {
  841. for i := startIndex; i <= j; i++ {
  842. perTick[j+offset][i+offset] = avg
  843. }
  844. }
  845. // copy [x*g..y*s)
  846. for j := y * sampling; j < finishIndex; j++ {
  847. for i := x * granularity; i < y*sampling; i++ {
  848. perTick[j+offset][i+offset] = perTick[j-1+offset][i+offset]
  849. }
  850. }
  851. }
  852. if (x+1)*granularity >= (y+1)*sampling {
  853. // x*granularity <= (y+1)*sampling
  854. // 1. x*granularity <= y*sampling
  855. // y*sampling..(y+1)sampling
  856. //
  857. // x+1
  858. // /
  859. // /
  860. // / y+1 -|
  861. // / |
  862. // / y -|
  863. // /
  864. // / x
  865. //
  866. // 2. x*granularity > y*sampling
  867. // x*granularity..(y+1)sampling
  868. //
  869. // x+1
  870. // /
  871. // /
  872. // / y+1 -|
  873. // / |
  874. // / x -|
  875. // /
  876. // / y
  877. if x*granularity <= y*sampling {
  878. raise((y+1)*sampling, float32(matrix[y][x]))
  879. } else if (y+1)*sampling > x*granularity {
  880. raise((y+1)*sampling, float32(matrix[y][x]))
  881. avg := float32(matrix[y][x]) / float32((y+1)*sampling-x*granularity)
  882. for j := x * granularity; j < (y+1)*sampling; j++ {
  883. for i := x * granularity; i <= j; i++ {
  884. perTick[j+offset][i+offset] = avg
  885. }
  886. }
  887. }
  888. } else if (x+1)*granularity >= y*sampling {
  889. // y*sampling <= (x+1)*granularity < (y+1)sampling
  890. // y*sampling..(x+1)*granularity
  891. // (x+1)*granularity..(y+1)sampling
  892. // x+1
  893. // /\
  894. // / \
  895. // / \
  896. // / y+1
  897. // /
  898. // y
  899. v1 := float32(matrix[y-1][x])
  900. v2 := float32(matrix[y][x])
  901. var peak float32
  902. delta := float32((x+1)*granularity - y*sampling)
  903. var scale float32
  904. var previous float32
  905. if y > 0 && (y-1)*sampling >= x*granularity {
  906. // x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  907. // |________|.......^
  908. if y > 1 {
  909. previous = float32(matrix[y-2][x])
  910. }
  911. scale = float32(sampling)
  912. } else {
  913. // (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  914. // |______|.......^
  915. if y == 0 {
  916. scale = float32(sampling)
  917. } else {
  918. scale = float32(y*sampling - x*granularity)
  919. }
  920. }
  921. peak = v1 + (v1-previous)/scale*delta
  922. if v2 > peak {
  923. // we need to adjust the peak, it may not be less than the decayed value
  924. if y < len(matrix)-1 {
  925. // y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  926. // ^.........|_________|
  927. k := (v2 - float32(matrix[y+1][x])) / float32(sampling) // > 0
  928. peak = float32(matrix[y][x]) + k*float32((y+1)*sampling-(x+1)*granularity)
  929. // peak > v2 > v1
  930. } else {
  931. peak = v2
  932. // not enough data to interpolate; this is at least not restricted
  933. }
  934. }
  935. raise((x+1)*granularity, peak)
  936. decay((x+1)*granularity, peak)
  937. } else {
  938. // (x+1)*granularity < y*sampling
  939. // y*sampling..(y+1)sampling
  940. decay(y*sampling, float32(matrix[y-1][x]))
  941. }
  942. }
  943. }
  944. for y := len(matrix) * sampling; y+offset < len(perTick); y++ {
  945. copy(perTick[y+offset], perTick[len(matrix)*sampling-1+offset])
  946. }
  947. // the original matrix has been resampled by tick
  948. // add it to the accumulator
  949. for y, row := range perTick {
  950. for x, val := range row {
  951. accPerTick[y][x] += val
  952. }
  953. }
  954. }
  955. func (analyser *BurndownAnalysis) serializeText(result *BurndownResult, writer io.Writer) {
  956. fmt.Fprintln(writer, " granularity:", result.granularity)
  957. fmt.Fprintln(writer, " sampling:", result.sampling)
  958. fmt.Fprintln(writer, " tick_size:", int(result.tickSize.Seconds()))
  959. yaml.PrintMatrix(writer, result.GlobalHistory, 2, "project", true)
  960. if len(result.FileHistories) > 0 {
  961. fmt.Fprintln(writer, " files:")
  962. keys := sortedKeys(result.FileHistories)
  963. for _, key := range keys {
  964. yaml.PrintMatrix(writer, result.FileHistories[key], 4, key, true)
  965. }
  966. fmt.Fprintln(writer, " files_ownership:")
  967. okeys := make([]string, 0, len(result.FileOwnership))
  968. for key := range result.FileOwnership {
  969. okeys = append(okeys, key)
  970. }
  971. sort.Strings(okeys)
  972. for _, key := range okeys {
  973. owned := result.FileOwnership[key]
  974. devs := make([]int, 0, len(owned))
  975. for devi := range owned {
  976. devs = append(devs, devi)
  977. }
  978. sort.Slice(devs, func(i, j int) bool {
  979. return owned[devs[i]] > owned[devs[j]] // descending order
  980. })
  981. for x, devi := range devs {
  982. var indent string
  983. if x == 0 {
  984. indent = "- "
  985. } else {
  986. indent = " "
  987. }
  988. fmt.Fprintf(writer, " %s%d: %d\n", indent, devi, owned[devi])
  989. }
  990. }
  991. }
  992. if len(result.PeopleHistories) > 0 {
  993. fmt.Fprintln(writer, " people_sequence:")
  994. for key := range result.PeopleHistories {
  995. fmt.Fprintln(writer, " - "+yaml.SafeString(result.reversedPeopleDict[key]))
  996. }
  997. fmt.Fprintln(writer, " people:")
  998. for key, val := range result.PeopleHistories {
  999. yaml.PrintMatrix(writer, val, 4, result.reversedPeopleDict[key], true)
  1000. }
  1001. fmt.Fprintln(writer, " people_interaction: |-")
  1002. yaml.PrintMatrix(writer, result.PeopleMatrix, 4, "", false)
  1003. }
  1004. }
  1005. func (analyser *BurndownAnalysis) serializeBinary(result *BurndownResult, writer io.Writer) error {
  1006. message := pb.BurndownAnalysisResults{
  1007. Granularity: int32(result.granularity),
  1008. Sampling: int32(result.sampling),
  1009. TickSize: int64(result.tickSize),
  1010. }
  1011. if len(result.GlobalHistory) > 0 {
  1012. message.Project = pb.ToBurndownSparseMatrix(result.GlobalHistory, "project")
  1013. }
  1014. if len(result.FileHistories) > 0 {
  1015. message.Files = make([]*pb.BurndownSparseMatrix, len(result.FileHistories))
  1016. message.FilesOwnership = make([]*pb.FilesOwnership, len(result.FileHistories))
  1017. keys := sortedKeys(result.FileHistories)
  1018. i := 0
  1019. for _, key := range keys {
  1020. message.Files[i] = pb.ToBurndownSparseMatrix(result.FileHistories[key], key)
  1021. ownership := map[int32]int32{}
  1022. message.FilesOwnership[i] = &pb.FilesOwnership{Value: ownership}
  1023. for key, val := range result.FileOwnership[key] {
  1024. ownership[int32(key)] = int32(val)
  1025. }
  1026. i++
  1027. }
  1028. }
  1029. if len(result.PeopleHistories) > 0 {
  1030. message.People = make(
  1031. []*pb.BurndownSparseMatrix, len(result.PeopleHistories))
  1032. for key, val := range result.PeopleHistories {
  1033. if len(val) > 0 {
  1034. message.People[key] = pb.ToBurndownSparseMatrix(val, result.reversedPeopleDict[key])
  1035. }
  1036. }
  1037. }
  1038. if result.PeopleMatrix != nil {
  1039. message.PeopleInteraction = pb.DenseToCompressedSparseRowMatrix(result.PeopleMatrix)
  1040. }
  1041. serialized, err := proto.Marshal(&message)
  1042. if err != nil {
  1043. return err
  1044. }
  1045. _, err = writer.Write(serialized)
  1046. return err
  1047. }
  1048. func sortedKeys(m map[string]DenseHistory) []string {
  1049. keys := make([]string, 0, len(m))
  1050. for k := range m {
  1051. keys = append(keys, k)
  1052. }
  1053. sort.Strings(keys)
  1054. return keys
  1055. }
  1056. func checkClose(c io.Closer) {
  1057. if err := c.Close(); err != nil {
  1058. panic(err)
  1059. }
  1060. }
  1061. // We do a hack and store the tick in the first 14 bits and the author index in the last 18.
  1062. // Strictly speaking, int can be 64-bit and then the author index occupies 32+18 bits.
  1063. // This hack is needed to simplify the values storage inside File-s. We can compare
  1064. // different values together and they are compared as ticks for the same author.
  1065. func (analyser *BurndownAnalysis) packPersonWithTick(person int, tick int) int {
  1066. if analyser.PeopleNumber == 0 {
  1067. return tick
  1068. }
  1069. result := tick & burndown.TreeMergeMark
  1070. result |= person << burndown.TreeMaxBinPower
  1071. // This effectively means max (16383 - 1) ticks (>44 years) and (262143 - 3) devs.
  1072. // One tick less because burndown.TreeMergeMark = ((1 << 14) - 1) is a special tick.
  1073. // Three devs less because:
  1074. // - math.MaxUint32 is the special rbtree value with tick == TreeMergeMark (-1)
  1075. // - identity.AuthorMissing (-2)
  1076. // - authorSelf (-3)
  1077. return result
  1078. }
  1079. func (analyser *BurndownAnalysis) unpackPersonWithTick(value int) (int, int) {
  1080. if analyser.PeopleNumber == 0 {
  1081. return identity.AuthorMissing, value
  1082. }
  1083. return value >> burndown.TreeMaxBinPower, value & burndown.TreeMergeMark
  1084. }
  1085. func (analyser *BurndownAnalysis) onNewTick() {
  1086. if analyser.tick > analyser.previousTick {
  1087. analyser.previousTick = analyser.tick
  1088. }
  1089. analyser.mergedAuthor = identity.AuthorMissing
  1090. }
  1091. func (analyser *BurndownAnalysis) updateGlobal(currentTime, previousTime, delta int) {
  1092. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1093. _, prevTick := analyser.unpackPersonWithTick(previousTime)
  1094. currentHistory := analyser.globalHistory[curTick]
  1095. if currentHistory == nil {
  1096. currentHistory = map[int]int64{}
  1097. analyser.globalHistory[curTick] = currentHistory
  1098. }
  1099. currentHistory[prevTick] += int64(delta)
  1100. }
  1101. // updateFile is bound to the specific `history` in the closure.
  1102. func (analyser *BurndownAnalysis) updateFile(
  1103. history sparseHistory, currentTime, previousTime, delta int) {
  1104. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1105. _, prevTick := analyser.unpackPersonWithTick(previousTime)
  1106. currentHistory := history[curTick]
  1107. if currentHistory == nil {
  1108. currentHistory = map[int]int64{}
  1109. history[curTick] = currentHistory
  1110. }
  1111. currentHistory[prevTick] += int64(delta)
  1112. }
  1113. func (analyser *BurndownAnalysis) updateAuthor(currentTime, previousTime, delta int) {
  1114. previousAuthor, prevTick := analyser.unpackPersonWithTick(previousTime)
  1115. if previousAuthor == identity.AuthorMissing {
  1116. return
  1117. }
  1118. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1119. history := analyser.peopleHistories[previousAuthor]
  1120. if history == nil {
  1121. history = sparseHistory{}
  1122. analyser.peopleHistories[previousAuthor] = history
  1123. }
  1124. currentHistory := history[curTick]
  1125. if currentHistory == nil {
  1126. currentHistory = map[int]int64{}
  1127. history[curTick] = currentHistory
  1128. }
  1129. currentHistory[prevTick] += int64(delta)
  1130. }
  1131. func (analyser *BurndownAnalysis) updateMatrix(currentTime, previousTime, delta int) {
  1132. newAuthor, _ := analyser.unpackPersonWithTick(currentTime)
  1133. oldAuthor, _ := analyser.unpackPersonWithTick(previousTime)
  1134. if oldAuthor == identity.AuthorMissing {
  1135. return
  1136. }
  1137. if newAuthor == oldAuthor && delta > 0 {
  1138. newAuthor = authorSelf
  1139. }
  1140. row := analyser.matrix[oldAuthor]
  1141. if row == nil {
  1142. row = map[int]int64{}
  1143. analyser.matrix[oldAuthor] = row
  1144. }
  1145. cell, exists := row[newAuthor]
  1146. if !exists {
  1147. row[newAuthor] = 0
  1148. cell = 0
  1149. }
  1150. row[newAuthor] = cell + int64(delta)
  1151. }
  1152. func (analyser *BurndownAnalysis) newFile(
  1153. hash plumbing.Hash, name string, author int, tick int, size int) (*burndown.File, error) {
  1154. updaters := make([]burndown.Updater, 1)
  1155. updaters[0] = analyser.updateGlobal
  1156. if analyser.TrackFiles {
  1157. history := analyser.fileHistories[name]
  1158. if history == nil {
  1159. // can be not nil if the file was created in a future branch
  1160. history = sparseHistory{}
  1161. }
  1162. analyser.fileHistories[name] = history
  1163. updaters = append(updaters, func(currentTime, previousTime, delta int) {
  1164. analyser.updateFile(history, currentTime, previousTime, delta)
  1165. })
  1166. }
  1167. if analyser.PeopleNumber > 0 {
  1168. updaters = append(updaters, analyser.updateAuthor)
  1169. updaters = append(updaters, analyser.updateMatrix)
  1170. tick = analyser.packPersonWithTick(author, tick)
  1171. }
  1172. return burndown.NewFile(tick, size, analyser.fileAllocator, updaters...), nil
  1173. }
  1174. func (analyser *BurndownAnalysis) handleInsertion(
  1175. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  1176. blob := cache[change.To.TreeEntry.Hash]
  1177. lines, err := blob.CountLines()
  1178. if err != nil {
  1179. // binary
  1180. return nil
  1181. }
  1182. name := change.To.Name
  1183. file, exists := analyser.files[name]
  1184. if exists {
  1185. return fmt.Errorf("file %s already exists", name)
  1186. }
  1187. var hash plumbing.Hash
  1188. if analyser.tick != burndown.TreeMergeMark {
  1189. hash = blob.Hash
  1190. }
  1191. file, err = analyser.newFile(hash, name, author, analyser.tick, lines)
  1192. analyser.files[name] = file
  1193. delete(analyser.deletions, name)
  1194. if analyser.tick == burndown.TreeMergeMark {
  1195. analyser.mergedFiles[name] = true
  1196. }
  1197. return err
  1198. }
  1199. func (analyser *BurndownAnalysis) handleDeletion(
  1200. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  1201. var name string
  1202. if change.To.TreeEntry.Hash != plumbing.ZeroHash {
  1203. // became binary
  1204. name = change.To.Name
  1205. } else {
  1206. name = change.From.Name
  1207. }
  1208. file, exists := analyser.files[name]
  1209. blob := cache[change.From.TreeEntry.Hash]
  1210. lines, err := blob.CountLines()
  1211. if exists && err != nil {
  1212. return fmt.Errorf("previous version of %s unexpectedly became binary", name)
  1213. }
  1214. if !exists {
  1215. return nil
  1216. }
  1217. // Parallel independent file removals are incorrectly handled. The solution seems to be quite
  1218. // complex, but feel free to suggest your ideas.
  1219. // These edge cases happen *very* rarely, so we don't bother for now.
  1220. tick := analyser.tick
  1221. // Are we merging and this file has never been actually deleted in any branch?
  1222. if analyser.tick == burndown.TreeMergeMark && !analyser.deletions[name] {
  1223. tick = 0
  1224. // Early removal in one branch with pre-merge changes in another is not handled correctly.
  1225. }
  1226. analyser.deletions[name] = true
  1227. file.Update(analyser.packPersonWithTick(author, tick), 0, 0, lines)
  1228. file.Delete()
  1229. delete(analyser.files, name)
  1230. delete(analyser.fileHistories, name)
  1231. stack := []string{name}
  1232. for len(stack) > 0 {
  1233. head := stack[len(stack)-1]
  1234. stack = stack[:len(stack)-1]
  1235. analyser.renames[head] = ""
  1236. for key, val := range analyser.renames {
  1237. if val == head {
  1238. stack = append(stack, key)
  1239. }
  1240. }
  1241. }
  1242. if analyser.tick == burndown.TreeMergeMark {
  1243. analyser.mergedFiles[name] = false
  1244. }
  1245. return nil
  1246. }
  1247. func (analyser *BurndownAnalysis) handleModification(
  1248. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob,
  1249. diffs map[string]items.FileDiffData) error {
  1250. if analyser.tick == burndown.TreeMergeMark {
  1251. analyser.mergedFiles[change.To.Name] = true
  1252. }
  1253. file, exists := analyser.files[change.From.Name]
  1254. if !exists {
  1255. // this indeed may happen
  1256. return analyser.handleInsertion(change, author, cache)
  1257. }
  1258. // possible rename
  1259. if change.To.Name != change.From.Name {
  1260. err := analyser.handleRename(change.From.Name, change.To.Name)
  1261. if err != nil {
  1262. return err
  1263. }
  1264. }
  1265. // Check for binary changes
  1266. blobFrom := cache[change.From.TreeEntry.Hash]
  1267. _, errFrom := blobFrom.CountLines()
  1268. blobTo := cache[change.To.TreeEntry.Hash]
  1269. _, errTo := blobTo.CountLines()
  1270. if errFrom != errTo {
  1271. if errFrom != nil {
  1272. // the file is no longer binary
  1273. return analyser.handleInsertion(change, author, cache)
  1274. }
  1275. // the file became binary
  1276. return analyser.handleDeletion(change, author, cache)
  1277. } else if errFrom != nil {
  1278. // what are we doing here?!
  1279. return nil
  1280. }
  1281. thisDiffs := diffs[change.To.Name]
  1282. if file.Len() != thisDiffs.OldLinesOfCode {
  1283. analyser.l.Infof("====TREE====\n%s", file.Dump())
  1284. return fmt.Errorf("%s: internal integrity error src %d != %d %s -> %s",
  1285. change.To.Name, thisDiffs.OldLinesOfCode, file.Len(),
  1286. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1287. }
  1288. // we do not call RunesToDiffLines so the number of lines equals
  1289. // to the rune count
  1290. position := 0
  1291. pending := diffmatchpatch.Diff{Text: ""}
  1292. apply := func(edit diffmatchpatch.Diff) {
  1293. length := utf8.RuneCountInString(edit.Text)
  1294. if edit.Type == diffmatchpatch.DiffInsert {
  1295. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, length, 0)
  1296. position += length
  1297. } else {
  1298. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, 0, length)
  1299. }
  1300. if analyser.Debug {
  1301. file.Validate()
  1302. }
  1303. }
  1304. for _, edit := range thisDiffs.Diffs {
  1305. dumpBefore := ""
  1306. if analyser.Debug {
  1307. dumpBefore = file.Dump()
  1308. }
  1309. length := utf8.RuneCountInString(edit.Text)
  1310. debugError := func() {
  1311. analyser.l.Errorf("%s: internal diff error\n", change.To.Name)
  1312. analyser.l.Errorf("Update(%d, %d, %d (0), %d (0))\n", analyser.tick, position,
  1313. length, utf8.RuneCountInString(pending.Text))
  1314. if dumpBefore != "" {
  1315. analyser.l.Errorf("====TREE BEFORE====\n%s====END====\n", dumpBefore)
  1316. }
  1317. analyser.l.Errorf("====TREE AFTER====\n%s====END====\n", file.Dump())
  1318. }
  1319. switch edit.Type {
  1320. case diffmatchpatch.DiffEqual:
  1321. if pending.Text != "" {
  1322. apply(pending)
  1323. pending.Text = ""
  1324. }
  1325. position += length
  1326. case diffmatchpatch.DiffInsert:
  1327. if pending.Text != "" {
  1328. if pending.Type == diffmatchpatch.DiffInsert {
  1329. debugError()
  1330. return errors.New("DiffInsert may not appear after DiffInsert")
  1331. }
  1332. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, length,
  1333. utf8.RuneCountInString(pending.Text))
  1334. if analyser.Debug {
  1335. file.Validate()
  1336. }
  1337. position += length
  1338. pending.Text = ""
  1339. } else {
  1340. pending = edit
  1341. }
  1342. case diffmatchpatch.DiffDelete:
  1343. if pending.Text != "" {
  1344. debugError()
  1345. return errors.New("DiffDelete may not appear after DiffInsert/DiffDelete")
  1346. }
  1347. pending = edit
  1348. default:
  1349. debugError()
  1350. return fmt.Errorf("diff operation is not supported: %d", edit.Type)
  1351. }
  1352. }
  1353. if pending.Text != "" {
  1354. apply(pending)
  1355. pending.Text = ""
  1356. }
  1357. if file.Len() != thisDiffs.NewLinesOfCode {
  1358. return fmt.Errorf("%s: internal integrity error dst %d != %d %s -> %s",
  1359. change.To.Name, thisDiffs.NewLinesOfCode, file.Len(),
  1360. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1361. }
  1362. return nil
  1363. }
  1364. func (analyser *BurndownAnalysis) handleRename(from, to string) error {
  1365. if from == to {
  1366. return nil
  1367. }
  1368. file, exists := analyser.files[from]
  1369. if !exists {
  1370. return fmt.Errorf("file %s > %s does not exist (files)", from, to)
  1371. }
  1372. delete(analyser.files, from)
  1373. analyser.files[to] = file
  1374. delete(analyser.deletions, to)
  1375. if analyser.tick == burndown.TreeMergeMark {
  1376. analyser.mergedFiles[from] = false
  1377. }
  1378. if analyser.TrackFiles {
  1379. history := analyser.fileHistories[from]
  1380. if history == nil {
  1381. var futureRename string
  1382. if _, exists := analyser.renames[""]; exists {
  1383. panic("burndown renames tracking corruption")
  1384. }
  1385. known := map[string]bool{}
  1386. newRename, exists := analyser.renames[from]
  1387. known[from] = true
  1388. for exists {
  1389. futureRename = newRename
  1390. newRename, exists = analyser.renames[futureRename]
  1391. if known[newRename] {
  1392. // infinite cycle
  1393. futureRename = ""
  1394. for key := range known {
  1395. if analyser.fileHistories[key] != nil {
  1396. futureRename = key
  1397. break
  1398. }
  1399. }
  1400. break
  1401. }
  1402. known[futureRename] = true
  1403. }
  1404. // a future branch could have already renamed it and we are retarded
  1405. if futureRename == "" {
  1406. // the file will be deleted in the future, whatever
  1407. history = sparseHistory{}
  1408. } else {
  1409. history = analyser.fileHistories[futureRename]
  1410. if history == nil {
  1411. return fmt.Errorf("file %s > %s (%s) does not exist (histories)",
  1412. from, to, futureRename)
  1413. }
  1414. }
  1415. }
  1416. delete(analyser.fileHistories, from)
  1417. analyser.fileHistories[to] = history
  1418. }
  1419. analyser.renames[from] = to
  1420. return nil
  1421. }
  1422. func (analyser *BurndownAnalysis) groupSparseHistory(
  1423. history sparseHistory, lastTick int) (DenseHistory, int) {
  1424. if len(history) == 0 {
  1425. panic("empty history")
  1426. }
  1427. var ticks []int
  1428. for tick := range history {
  1429. ticks = append(ticks, tick)
  1430. }
  1431. sort.Ints(ticks)
  1432. if lastTick >= 0 {
  1433. if ticks[len(ticks)-1] < lastTick {
  1434. ticks = append(ticks, lastTick)
  1435. } else if ticks[len(ticks)-1] > lastTick {
  1436. panic("ticks corruption")
  1437. }
  1438. } else {
  1439. lastTick = ticks[len(ticks)-1]
  1440. }
  1441. // [y][x]
  1442. // y - sampling
  1443. // x - granularity
  1444. samples := lastTick/analyser.Sampling + 1
  1445. bands := lastTick/analyser.Granularity + 1
  1446. result := make(DenseHistory, samples)
  1447. for i := 0; i < bands; i++ {
  1448. result[i] = make([]int64, bands)
  1449. }
  1450. prevsi := 0
  1451. for _, tick := range ticks {
  1452. si := tick / analyser.Sampling
  1453. if si > prevsi {
  1454. state := result[prevsi]
  1455. for i := prevsi + 1; i <= si; i++ {
  1456. copy(result[i], state)
  1457. }
  1458. prevsi = si
  1459. }
  1460. sample := result[si]
  1461. for t, value := range history[tick] {
  1462. sample[t/analyser.Granularity] += value
  1463. }
  1464. }
  1465. return result, lastTick
  1466. }
  1467. // GetTickSize returns the tick size used to generate this burndown analysis result.
  1468. func (br BurndownResult) GetTickSize() time.Duration {
  1469. return br.tickSize
  1470. }
  1471. // GetIdentities returns the list of developer identities used to generate this burndown analysis result.
  1472. // The format is |-joined keys, see internals/plumbing/identity for details.
  1473. func (br BurndownResult) GetIdentities() []string {
  1474. return br.reversedPeopleDict
  1475. }
  1476. func init() {
  1477. core.Registry.Register(&BurndownAnalysis{})
  1478. }