burndown.go 50 KB

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