burndown.go 48 KB

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