burndown.go 50 KB

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