burndown.go 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  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. // HibernationThreshold sets the hibernation threshold for the underlying
  45. // RBTree allocator. It is useful to trade CPU time for reduced peak memory consumption
  46. // if there are many branches.
  47. HibernationThreshold int
  48. // HibernationToDisk specifies whether the hibernated RBTree allocator must be saved on disk
  49. // rather than kept in memory.
  50. HibernationToDisk bool
  51. // HibernationDirectory is the name of the temporary directory to use for saving hibernated
  52. // RBTree allocators.
  53. HibernationDirectory string
  54. // Debug activates the debugging mode. Analyse() runs slower in this mode
  55. // but it accurately checks all the intermediate states for invariant
  56. // violations.
  57. Debug bool
  58. // Repository points to the analysed Git repository struct from go-git.
  59. repository *git.Repository
  60. // globalHistory is the daily deltas of daily line counts.
  61. // E.g. tick 0: tick 0 +50 lines
  62. // tick 10: tick 0 -10 lines; tick 10 +20 lines
  63. // tick 12: tick 0 -5 lines; tick 10 -3 lines; tick 12 +10 lines
  64. // map [0] [0] = 50
  65. // map[10] [0] = -10
  66. // map[10][10] = 20
  67. // map[12] [0] = -5
  68. // map[12][10] = -3
  69. // map[12][12] = 10
  70. globalHistory sparseHistory
  71. // fileHistories is the daily deltas of each file's daily line counts.
  72. fileHistories map[string]sparseHistory
  73. // peopleHistories is the daily deltas of each person's daily line counts.
  74. peopleHistories []sparseHistory
  75. // files is the mapping <file path> -> *File.
  76. files map[string]*burndown.File
  77. // fileAllocator is the allocator for RBTree-s in `files`.
  78. fileAllocator *rbtree.Allocator
  79. // hibernatedFileName is the path to the serialized `fileAllocator`.
  80. hibernatedFileName string
  81. // mergedFiles is used during merges to record the real file hashes
  82. mergedFiles map[string]bool
  83. // mergedAuthor of the processed merge commit
  84. mergedAuthor int
  85. // renames is a quick and dirty solution for the "future branch renames" problem.
  86. renames map[string]string
  87. // deletions is a quick and dirty solution for the "real merge removals" problem.
  88. deletions map[string]bool
  89. // matrix is the mutual deletions and self insertions.
  90. matrix []map[int]int64
  91. // tick is the most recent tick index processed.
  92. tick int
  93. // previousTick is the tick from the previous sample period -
  94. // different from TicksSinceStart.previousTick.
  95. previousTick int
  96. // tickSize indicates the size of each tick.
  97. tickSize time.Duration
  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. }