burndown.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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.v9/internal/burndown"
  20. "gopkg.in/src-d/hercules.v9/internal/core"
  21. "gopkg.in/src-d/hercules.v9/internal/pb"
  22. items "gopkg.in/src-d/hercules.v9/internal/plumbing"
  23. "gopkg.in/src-d/hercules.v9/internal/plumbing/identity"
  24. "gopkg.in/src-d/hercules.v9/internal/rbtree"
  25. "gopkg.in/src-d/hercules.v9/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 ticks it spans.
  32. // Smaller values provide better resolution but require more work and eat more
  33. // memory. 30 ticks is usually enough.
  34. Granularity int
  35. // Sampling sets how detailed is the statistic - the size of the interval in
  36. // ticks 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. tick 0: tick 0 +50 lines
  61. // tick 10: tick 0 -10 lines; tick 10 +20 lines
  62. // tick 12: tick 0 -5 lines; tick 10 -3 lines; tick 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. // tick is the most recent tick index processed.
  89. tick int
  90. // previousTick is the tick from the previous sample period -
  91. // different from TicksSinceStart.previousTick.
  92. previousTick 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 ticks 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.DependencyTick, 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 time ticks 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 time ticks.",
  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 ticks\n",
  278. DefaultBurndownGranularity)
  279. analyser.Granularity = DefaultBurndownGranularity
  280. }
  281. if analyser.Sampling <= 0 {
  282. log.Printf("Warning: adjusted the sampling to %d ticks\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.tick = 0
  306. analyser.previousTick = 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. tick := deps[items.DependencyTick].(int)
  320. if !deps[core.DependencyIsMerge].(bool) {
  321. analyser.tick = tick
  322. analyser.onNewTick()
  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.tick = 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.tick equals to TreeMergeMark
  349. analyser.tick = tick
  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(
  408. analyser.packPersonWithTick(analyser.mergedAuthor, analyser.tick),
  409. files[1:]...)
  410. for _, burn := range all {
  411. if burn.files[key] != files[0] {
  412. if burn.files[key] != nil {
  413. burn.files[key].Delete()
  414. }
  415. burn.files[key] = files[0].CloneDeep(burn.fileAllocator)
  416. }
  417. }
  418. }
  419. analyser.onNewTick()
  420. }
  421. // Hibernate compresses the bound RBTree memory with the files.
  422. func (analyser *BurndownAnalysis) Hibernate() error {
  423. analyser.fileAllocator.Hibernate()
  424. if analyser.HibernationToDisk {
  425. file, err := ioutil.TempFile(analyser.HibernationDirectory, "*-hercules.bin")
  426. if err != nil {
  427. return err
  428. }
  429. analyser.hibernatedFileName = file.Name()
  430. err = file.Close()
  431. if err != nil {
  432. analyser.hibernatedFileName = ""
  433. return err
  434. }
  435. err = analyser.fileAllocator.Serialize(analyser.hibernatedFileName)
  436. if err != nil {
  437. analyser.hibernatedFileName = ""
  438. return err
  439. }
  440. }
  441. return nil
  442. }
  443. // Boot decompresses the bound RBTree memory with the files.
  444. func (analyser *BurndownAnalysis) Boot() error {
  445. if analyser.hibernatedFileName != "" {
  446. err := analyser.fileAllocator.Deserialize(analyser.hibernatedFileName)
  447. if err != nil {
  448. return err
  449. }
  450. err = os.Remove(analyser.hibernatedFileName)
  451. if err != nil {
  452. return err
  453. }
  454. analyser.hibernatedFileName = ""
  455. }
  456. analyser.fileAllocator.Boot()
  457. return nil
  458. }
  459. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  460. func (analyser *BurndownAnalysis) Finalize() interface{} {
  461. globalHistory, lastTick := analyser.groupSparseHistory(analyser.globalHistory, -1)
  462. fileHistories := map[string]DenseHistory{}
  463. fileOwnership := map[string]map[int]int{}
  464. for key, history := range analyser.fileHistories {
  465. if len(history) == 0 {
  466. continue
  467. }
  468. fileHistories[key], _ = analyser.groupSparseHistory(history, lastTick)
  469. file := analyser.files[key]
  470. previousLine := 0
  471. previousAuthor := identity.AuthorMissing
  472. ownership := map[int]int{}
  473. fileOwnership[key] = ownership
  474. file.ForEach(func(line, value int) {
  475. length := line - previousLine
  476. if length > 0 {
  477. ownership[previousAuthor] += length
  478. }
  479. previousLine = line
  480. previousAuthor, _ = analyser.unpackPersonWithTick(int(value))
  481. if previousAuthor == identity.AuthorMissing {
  482. previousAuthor = -1
  483. }
  484. })
  485. }
  486. peopleHistories := make([]DenseHistory, analyser.PeopleNumber)
  487. for i, history := range analyser.peopleHistories {
  488. if len(history) > 0 {
  489. // there can be people with only trivial merge commits and without own lines
  490. peopleHistories[i], _ = analyser.groupSparseHistory(history, lastTick)
  491. } else {
  492. peopleHistories[i] = make(DenseHistory, len(globalHistory))
  493. for j, gh := range globalHistory {
  494. peopleHistories[i][j] = make([]int64, len(gh))
  495. }
  496. }
  497. }
  498. var peopleMatrix DenseHistory
  499. if len(analyser.matrix) > 0 {
  500. peopleMatrix = make(DenseHistory, analyser.PeopleNumber)
  501. for i, row := range analyser.matrix {
  502. mrow := make([]int64, analyser.PeopleNumber+2)
  503. peopleMatrix[i] = mrow
  504. for key, val := range row {
  505. if key == identity.AuthorMissing {
  506. key = -1
  507. } else if key == authorSelf {
  508. key = -2
  509. }
  510. mrow[key+2] = val
  511. }
  512. }
  513. }
  514. return BurndownResult{
  515. GlobalHistory: globalHistory,
  516. FileHistories: fileHistories,
  517. FileOwnership: fileOwnership,
  518. PeopleHistories: peopleHistories,
  519. PeopleMatrix: peopleMatrix,
  520. reversedPeopleDict: analyser.reversedPeopleDict,
  521. sampling: analyser.Sampling,
  522. granularity: analyser.Granularity,
  523. }
  524. }
  525. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  526. // The text format is YAML and the bytes format is Protocol Buffers.
  527. func (analyser *BurndownAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  528. burndownResult := result.(BurndownResult)
  529. if binary {
  530. return analyser.serializeBinary(&burndownResult, writer)
  531. }
  532. analyser.serializeText(&burndownResult, writer)
  533. return nil
  534. }
  535. // Deserialize converts the specified protobuf bytes to BurndownResult.
  536. func (analyser *BurndownAnalysis) Deserialize(pbmessage []byte) (interface{}, error) {
  537. msg := pb.BurndownAnalysisResults{}
  538. err := proto.Unmarshal(pbmessage, &msg)
  539. if err != nil {
  540. return nil, err
  541. }
  542. result := BurndownResult{}
  543. convertCSR := func(mat *pb.BurndownSparseMatrix) DenseHistory {
  544. res := make(DenseHistory, mat.NumberOfRows)
  545. for i := 0; i < int(mat.NumberOfRows); i++ {
  546. res[i] = make([]int64, mat.NumberOfColumns)
  547. for j := 0; j < len(mat.Rows[i].Columns); j++ {
  548. res[i][j] = int64(mat.Rows[i].Columns[j])
  549. }
  550. }
  551. return res
  552. }
  553. result.GlobalHistory = convertCSR(msg.Project)
  554. result.FileHistories = map[string]DenseHistory{}
  555. result.FileOwnership = map[string]map[int]int{}
  556. for i, mat := range msg.Files {
  557. result.FileHistories[mat.Name] = convertCSR(mat)
  558. ownership := map[int]int{}
  559. result.FileOwnership[mat.Name] = ownership
  560. for key, val := range msg.FilesOwnership[i].Value {
  561. ownership[int(key)] = int(val)
  562. }
  563. }
  564. result.reversedPeopleDict = make([]string, len(msg.People))
  565. result.PeopleHistories = make([]DenseHistory, len(msg.People))
  566. for i, mat := range msg.People {
  567. result.PeopleHistories[i] = convertCSR(mat)
  568. result.reversedPeopleDict[i] = mat.Name
  569. }
  570. if msg.PeopleInteraction != nil {
  571. result.PeopleMatrix = make(DenseHistory, msg.PeopleInteraction.NumberOfRows)
  572. }
  573. for i := 0; i < len(result.PeopleMatrix); i++ {
  574. result.PeopleMatrix[i] = make([]int64, msg.PeopleInteraction.NumberOfColumns)
  575. for j := int(msg.PeopleInteraction.Indptr[i]); j < int(msg.PeopleInteraction.Indptr[i+1]); j++ {
  576. result.PeopleMatrix[i][msg.PeopleInteraction.Indices[j]] = msg.PeopleInteraction.Data[j]
  577. }
  578. }
  579. result.sampling = int(msg.Sampling)
  580. result.granularity = int(msg.Granularity)
  581. return result, nil
  582. }
  583. // MergeResults combines two BurndownResult-s together.
  584. func (analyser *BurndownAnalysis) MergeResults(
  585. r1, r2 interface{}, c1, c2 *core.CommonAnalysisResult) interface{} {
  586. bar1 := r1.(BurndownResult)
  587. bar2 := r2.(BurndownResult)
  588. merged := BurndownResult{}
  589. if bar1.sampling < bar2.sampling {
  590. merged.sampling = bar1.sampling
  591. } else {
  592. merged.sampling = bar2.sampling
  593. }
  594. if bar1.granularity < bar2.granularity {
  595. merged.granularity = bar1.granularity
  596. } else {
  597. merged.granularity = bar2.granularity
  598. }
  599. var people map[string][3]int
  600. people, merged.reversedPeopleDict = identity.Detector{}.MergeReversedDicts(
  601. bar1.reversedPeopleDict, bar2.reversedPeopleDict)
  602. var wg sync.WaitGroup
  603. if len(bar1.GlobalHistory) > 0 || len(bar2.GlobalHistory) > 0 {
  604. wg.Add(1)
  605. go func() {
  606. defer wg.Done()
  607. merged.GlobalHistory = mergeMatrices(
  608. bar1.GlobalHistory, bar2.GlobalHistory,
  609. bar1.granularity, bar1.sampling,
  610. bar2.granularity, bar2.sampling,
  611. c1, c2)
  612. }()
  613. }
  614. // we don't merge files
  615. if len(merged.reversedPeopleDict) > 0 {
  616. if len(bar1.PeopleHistories) > 0 || len(bar2.PeopleHistories) > 0 {
  617. merged.PeopleHistories = make([]DenseHistory, len(merged.reversedPeopleDict))
  618. for i, key := range merged.reversedPeopleDict {
  619. ptrs := people[key]
  620. wg.Add(1)
  621. go func(i int) {
  622. defer wg.Done()
  623. var m1, m2 DenseHistory
  624. if ptrs[1] >= 0 {
  625. m1 = bar1.PeopleHistories[ptrs[1]]
  626. }
  627. if ptrs[2] >= 0 {
  628. m2 = bar2.PeopleHistories[ptrs[2]]
  629. }
  630. merged.PeopleHistories[i] = mergeMatrices(
  631. m1, m2,
  632. bar1.granularity, bar1.sampling,
  633. bar2.granularity, bar2.sampling,
  634. c1, c2,
  635. )
  636. }(i)
  637. }
  638. }
  639. wg.Add(1)
  640. go func() {
  641. defer wg.Done()
  642. if len(bar2.PeopleMatrix) == 0 {
  643. merged.PeopleMatrix = bar1.PeopleMatrix
  644. // extend the matrix in both directions
  645. for i := 0; i < len(merged.PeopleMatrix); i++ {
  646. for j := len(bar1.reversedPeopleDict); j < len(merged.reversedPeopleDict); j++ {
  647. merged.PeopleMatrix[i] = append(merged.PeopleMatrix[i], 0)
  648. }
  649. }
  650. if len(bar1.PeopleMatrix) > 0 {
  651. for i := len(bar1.reversedPeopleDict); i < len(merged.reversedPeopleDict); i++ {
  652. merged.PeopleMatrix = append(
  653. merged.PeopleMatrix, make([]int64, len(merged.reversedPeopleDict)+2))
  654. }
  655. }
  656. } else {
  657. merged.PeopleMatrix = make(DenseHistory, len(merged.reversedPeopleDict))
  658. for i := range merged.PeopleMatrix {
  659. merged.PeopleMatrix[i] = make([]int64, len(merged.reversedPeopleDict)+2)
  660. }
  661. for i, key := range bar1.reversedPeopleDict {
  662. mi := people[key][0] // index in merged.reversedPeopleDict
  663. copy(merged.PeopleMatrix[mi][:2], bar1.PeopleMatrix[i][:2])
  664. for j, val := range bar1.PeopleMatrix[i][2:] {
  665. merged.PeopleMatrix[mi][2+people[bar1.reversedPeopleDict[j]][0]] = val
  666. }
  667. }
  668. for i, key := range bar2.reversedPeopleDict {
  669. mi := people[key][0] // index in merged.reversedPeopleDict
  670. merged.PeopleMatrix[mi][0] += bar2.PeopleMatrix[i][0]
  671. merged.PeopleMatrix[mi][1] += bar2.PeopleMatrix[i][1]
  672. for j, val := range bar2.PeopleMatrix[i][2:] {
  673. merged.PeopleMatrix[mi][2+people[bar2.reversedPeopleDict[j]][0]] += val
  674. }
  675. }
  676. }
  677. }()
  678. }
  679. wg.Wait()
  680. return merged
  681. }
  682. func roundTime(unix int64, dir bool) int {
  683. ticks := float64(unix) / (3600 * 24)
  684. if dir {
  685. return int(math.Ceil(ticks))
  686. }
  687. return int(math.Floor(ticks))
  688. }
  689. // mergeMatrices takes two [number of samples][number of bands] matrices,
  690. // resamples them to ticks so that they become square, sums and resamples back to the
  691. // least of (sampling1, sampling2) and (granularity1, granularity2).
  692. func mergeMatrices(m1, m2 DenseHistory, granularity1, sampling1, granularity2, sampling2 int,
  693. c1, c2 *core.CommonAnalysisResult) DenseHistory {
  694. commonMerged := c1.Copy()
  695. commonMerged.Merge(c2)
  696. var granularity, sampling int
  697. if sampling1 < sampling2 {
  698. sampling = sampling1
  699. } else {
  700. sampling = sampling2
  701. }
  702. if granularity1 < granularity2 {
  703. granularity = granularity1
  704. } else {
  705. granularity = granularity2
  706. }
  707. size := roundTime(commonMerged.EndTime, true) - roundTime(commonMerged.BeginTime, false)
  708. daily := make([][]float32, size+granularity)
  709. for i := range daily {
  710. daily[i] = make([]float32, size+sampling)
  711. }
  712. if len(m1) > 0 {
  713. addBurndownMatrix(m1, granularity1, sampling1, daily,
  714. roundTime(c1.BeginTime, false)-roundTime(commonMerged.BeginTime, false))
  715. }
  716. if len(m2) > 0 {
  717. addBurndownMatrix(m2, granularity2, sampling2, daily,
  718. roundTime(c2.BeginTime, false)-roundTime(commonMerged.BeginTime, false))
  719. }
  720. // convert daily to [][]int64
  721. result := make(DenseHistory, (size+sampling-1)/sampling)
  722. for i := range result {
  723. result[i] = make([]int64, (size+granularity-1)/granularity)
  724. sampledIndex := (i+1)*sampling - 1
  725. for j := 0; j < len(result[i]); j++ {
  726. accum := float32(0)
  727. for k := j * granularity; k < (j+1)*granularity; k++ {
  728. accum += daily[sampledIndex][k]
  729. }
  730. result[i][j] = int64(accum)
  731. }
  732. }
  733. return result
  734. }
  735. // Explode `matrix` so that it is daily sampled and has daily bands, shift by `offset` ticks
  736. // and add to the accumulator. `daily` size is square and is guaranteed to fit `matrix` by
  737. // the caller.
  738. // Rows: *at least* len(matrix) * sampling + offset
  739. // Columns: *at least* len(matrix[...]) * granularity + offset
  740. // `matrix` can be sparse, so that the last columns which are equal to 0 are truncated.
  741. func addBurndownMatrix(matrix DenseHistory, granularity, sampling int, accdaily [][]float32, offset int) {
  742. // Determine the maximum number of bands; the actual one may be larger but we do not care
  743. maxCols := 0
  744. for _, row := range matrix {
  745. if maxCols < len(row) {
  746. maxCols = len(row)
  747. }
  748. }
  749. neededRows := len(matrix)*sampling + offset
  750. if len(accdaily) < neededRows {
  751. log.Panicf("merge bug: too few daily rows: required %d, have %d",
  752. neededRows, len(accdaily))
  753. }
  754. if len(accdaily[0]) < maxCols {
  755. log.Panicf("merge bug: too few daily cols: required %d, have %d",
  756. maxCols, len(accdaily[0]))
  757. }
  758. daily := make([][]float32, len(accdaily))
  759. for i, row := range accdaily {
  760. daily[i] = make([]float32, len(row))
  761. }
  762. for x := 0; x < maxCols; x++ {
  763. for y := 0; y < len(matrix); y++ {
  764. if x*granularity > (y+1)*sampling {
  765. // the future is zeros
  766. continue
  767. }
  768. decay := func(startIndex int, startVal float32) {
  769. if startVal == 0 {
  770. return
  771. }
  772. k := float32(matrix[y][x]) / startVal // <= 1
  773. scale := float32((y+1)*sampling - startIndex)
  774. for i := x * granularity; i < (x+1)*granularity; i++ {
  775. initial := daily[startIndex-1+offset][i+offset]
  776. for j := startIndex; j < (y+1)*sampling; j++ {
  777. daily[j+offset][i+offset] = initial * (1 + (k-1)*float32(j-startIndex+1)/scale)
  778. }
  779. }
  780. }
  781. raise := func(finishIndex int, finishVal float32) {
  782. var initial float32
  783. if y > 0 {
  784. initial = float32(matrix[y-1][x])
  785. }
  786. startIndex := y * sampling
  787. if startIndex < x*granularity {
  788. startIndex = x * granularity
  789. }
  790. if startIndex == finishIndex {
  791. return
  792. }
  793. avg := (finishVal - initial) / float32(finishIndex-startIndex)
  794. for j := y * sampling; j < finishIndex; j++ {
  795. for i := startIndex; i <= j; i++ {
  796. daily[j+offset][i+offset] = avg
  797. }
  798. }
  799. // copy [x*g..y*s)
  800. for j := y * sampling; j < finishIndex; j++ {
  801. for i := x * granularity; i < y*sampling; i++ {
  802. daily[j+offset][i+offset] = daily[j-1+offset][i+offset]
  803. }
  804. }
  805. }
  806. if (x+1)*granularity >= (y+1)*sampling {
  807. // x*granularity <= (y+1)*sampling
  808. // 1. x*granularity <= y*sampling
  809. // y*sampling..(y+1)sampling
  810. //
  811. // x+1
  812. // /
  813. // /
  814. // / y+1 -|
  815. // / |
  816. // / y -|
  817. // /
  818. // / x
  819. //
  820. // 2. x*granularity > y*sampling
  821. // x*granularity..(y+1)sampling
  822. //
  823. // x+1
  824. // /
  825. // /
  826. // / y+1 -|
  827. // / |
  828. // / x -|
  829. // /
  830. // / y
  831. if x*granularity <= y*sampling {
  832. raise((y+1)*sampling, float32(matrix[y][x]))
  833. } else if (y+1)*sampling > x*granularity {
  834. raise((y+1)*sampling, float32(matrix[y][x]))
  835. avg := float32(matrix[y][x]) / float32((y+1)*sampling-x*granularity)
  836. for j := x * granularity; j < (y+1)*sampling; j++ {
  837. for i := x * granularity; i <= j; i++ {
  838. daily[j+offset][i+offset] = avg
  839. }
  840. }
  841. }
  842. } else if (x+1)*granularity >= y*sampling {
  843. // y*sampling <= (x+1)*granularity < (y+1)sampling
  844. // y*sampling..(x+1)*granularity
  845. // (x+1)*granularity..(y+1)sampling
  846. // x+1
  847. // /\
  848. // / \
  849. // / \
  850. // / y+1
  851. // /
  852. // y
  853. v1 := float32(matrix[y-1][x])
  854. v2 := float32(matrix[y][x])
  855. var peak float32
  856. delta := float32((x+1)*granularity - y*sampling)
  857. var scale float32
  858. var previous float32
  859. if y > 0 && (y-1)*sampling >= x*granularity {
  860. // x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  861. // |________|.......^
  862. if y > 1 {
  863. previous = float32(matrix[y-2][x])
  864. }
  865. scale = float32(sampling)
  866. } else {
  867. // (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  868. // |______|.......^
  869. if y == 0 {
  870. scale = float32(sampling)
  871. } else {
  872. scale = float32(y*sampling - x*granularity)
  873. }
  874. }
  875. peak = v1 + (v1-previous)/scale*delta
  876. if v2 > peak {
  877. // we need to adjust the peak, it may not be less than the decayed value
  878. if y < len(matrix)-1 {
  879. // y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  880. // ^.........|_________|
  881. k := (v2 - float32(matrix[y+1][x])) / float32(sampling) // > 0
  882. peak = float32(matrix[y][x]) + k*float32((y+1)*sampling-(x+1)*granularity)
  883. // peak > v2 > v1
  884. } else {
  885. peak = v2
  886. // not enough data to interpolate; this is at least not restricted
  887. }
  888. }
  889. raise((x+1)*granularity, peak)
  890. decay((x+1)*granularity, peak)
  891. } else {
  892. // (x+1)*granularity < y*sampling
  893. // y*sampling..(y+1)sampling
  894. decay(y*sampling, float32(matrix[y-1][x]))
  895. }
  896. }
  897. }
  898. for y := len(matrix) * sampling; y+offset < len(daily); y++ {
  899. copy(daily[y+offset], daily[len(matrix)*sampling-1+offset])
  900. }
  901. // the original matrix has been resampled by tick
  902. // add it to the accumulator
  903. for y, row := range daily {
  904. for x, val := range row {
  905. accdaily[y][x] += val
  906. }
  907. }
  908. }
  909. func (analyser *BurndownAnalysis) serializeText(result *BurndownResult, writer io.Writer) {
  910. fmt.Fprintln(writer, " granularity:", result.granularity)
  911. fmt.Fprintln(writer, " sampling:", result.sampling)
  912. yaml.PrintMatrix(writer, result.GlobalHistory, 2, "project", true)
  913. if len(result.FileHistories) > 0 {
  914. fmt.Fprintln(writer, " files:")
  915. keys := sortedKeys(result.FileHistories)
  916. for _, key := range keys {
  917. yaml.PrintMatrix(writer, result.FileHistories[key], 4, key, true)
  918. }
  919. fmt.Fprintln(writer, " files_ownership:")
  920. okeys := make([]string, 0, len(result.FileOwnership))
  921. for key := range result.FileOwnership {
  922. okeys = append(okeys, key)
  923. }
  924. sort.Strings(okeys)
  925. for _, key := range okeys {
  926. owned := result.FileOwnership[key]
  927. devs := make([]int, 0, len(owned))
  928. for devi := range owned {
  929. devs = append(devs, devi)
  930. }
  931. sort.Slice(devs, func(i, j int) bool {
  932. return owned[devs[i]] > owned[devs[j]] // descending order
  933. })
  934. for x, devi := range devs {
  935. var indent string
  936. if x == 0 {
  937. indent = "- "
  938. } else {
  939. indent = " "
  940. }
  941. fmt.Fprintf(writer, " %s%d: %d\n", indent, devi, owned[devi])
  942. }
  943. }
  944. }
  945. if len(result.PeopleHistories) > 0 {
  946. fmt.Fprintln(writer, " people_sequence:")
  947. for key := range result.PeopleHistories {
  948. fmt.Fprintln(writer, " - "+yaml.SafeString(result.reversedPeopleDict[key]))
  949. }
  950. fmt.Fprintln(writer, " people:")
  951. for key, val := range result.PeopleHistories {
  952. yaml.PrintMatrix(writer, val, 4, result.reversedPeopleDict[key], true)
  953. }
  954. fmt.Fprintln(writer, " people_interaction: |-")
  955. yaml.PrintMatrix(writer, result.PeopleMatrix, 4, "", false)
  956. }
  957. }
  958. func (analyser *BurndownAnalysis) serializeBinary(result *BurndownResult, writer io.Writer) error {
  959. message := pb.BurndownAnalysisResults{
  960. Granularity: int32(result.granularity),
  961. Sampling: int32(result.sampling),
  962. }
  963. if len(result.GlobalHistory) > 0 {
  964. message.Project = pb.ToBurndownSparseMatrix(result.GlobalHistory, "project")
  965. }
  966. if len(result.FileHistories) > 0 {
  967. message.Files = make([]*pb.BurndownSparseMatrix, len(result.FileHistories))
  968. message.FilesOwnership = make([]*pb.FilesOwnership, len(result.FileHistories))
  969. keys := sortedKeys(result.FileHistories)
  970. i := 0
  971. for _, key := range keys {
  972. message.Files[i] = pb.ToBurndownSparseMatrix(result.FileHistories[key], key)
  973. ownership := map[int32]int32{}
  974. message.FilesOwnership[i] = &pb.FilesOwnership{Value: ownership}
  975. for key, val := range result.FileOwnership[key] {
  976. ownership[int32(key)] = int32(val)
  977. }
  978. i++
  979. }
  980. }
  981. if len(result.PeopleHistories) > 0 {
  982. message.People = make(
  983. []*pb.BurndownSparseMatrix, len(result.PeopleHistories))
  984. for key, val := range result.PeopleHistories {
  985. if len(val) > 0 {
  986. message.People[key] = pb.ToBurndownSparseMatrix(val, result.reversedPeopleDict[key])
  987. }
  988. }
  989. }
  990. if result.PeopleMatrix != nil {
  991. message.PeopleInteraction = pb.DenseToCompressedSparseRowMatrix(result.PeopleMatrix)
  992. }
  993. serialized, err := proto.Marshal(&message)
  994. if err != nil {
  995. return err
  996. }
  997. _, err = writer.Write(serialized)
  998. return err
  999. }
  1000. func sortedKeys(m map[string]DenseHistory) []string {
  1001. keys := make([]string, 0, len(m))
  1002. for k := range m {
  1003. keys = append(keys, k)
  1004. }
  1005. sort.Strings(keys)
  1006. return keys
  1007. }
  1008. func checkClose(c io.Closer) {
  1009. if err := c.Close(); err != nil {
  1010. panic(err)
  1011. }
  1012. }
  1013. // We do a hack and store the tick in the first 14 bits and the author index in the last 18.
  1014. // Strictly speaking, int can be 64-bit and then the author index occupies 32+18 bits.
  1015. // This hack is needed to simplify the values storage inside File-s. We can compare
  1016. // different values together and they are compared as ticks for the same author.
  1017. func (analyser *BurndownAnalysis) packPersonWithTick(person int, tick int) int {
  1018. if analyser.PeopleNumber == 0 {
  1019. return tick
  1020. }
  1021. result := tick & burndown.TreeMergeMark
  1022. result |= person << burndown.TreeMaxBinPower
  1023. // This effectively means max (16383 - 1) ticks (>44 years) and (262143 - 3) devs.
  1024. // One tick less because burndown.TreeMergeMark = ((1 << 14) - 1) is a special tick.
  1025. // Three devs less because:
  1026. // - math.MaxUint32 is the special rbtree value with tick == TreeMergeMark (-1)
  1027. // - identity.AuthorMissing (-2)
  1028. // - authorSelf (-3)
  1029. return result
  1030. }
  1031. func (analyser *BurndownAnalysis) unpackPersonWithTick(value int) (int, int) {
  1032. if analyser.PeopleNumber == 0 {
  1033. return identity.AuthorMissing, value
  1034. }
  1035. return value >> burndown.TreeMaxBinPower, value & burndown.TreeMergeMark
  1036. }
  1037. func (analyser *BurndownAnalysis) onNewTick() {
  1038. if analyser.tick > analyser.previousTick {
  1039. analyser.previousTick = analyser.tick
  1040. }
  1041. analyser.mergedAuthor = identity.AuthorMissing
  1042. }
  1043. func (analyser *BurndownAnalysis) updateGlobal(currentTime, previousTime, delta int) {
  1044. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1045. _, prevTick := analyser.unpackPersonWithTick(previousTime)
  1046. currentHistory := analyser.globalHistory[curTick]
  1047. if currentHistory == nil {
  1048. currentHistory = map[int]int64{}
  1049. analyser.globalHistory[curTick] = currentHistory
  1050. }
  1051. currentHistory[prevTick] += int64(delta)
  1052. }
  1053. // updateFile is bound to the specific `history` in the closure.
  1054. func (analyser *BurndownAnalysis) updateFile(
  1055. history sparseHistory, currentTime, previousTime, delta int) {
  1056. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1057. _, prevTick := analyser.unpackPersonWithTick(previousTime)
  1058. currentHistory := history[curTick]
  1059. if currentHistory == nil {
  1060. currentHistory = map[int]int64{}
  1061. history[curTick] = currentHistory
  1062. }
  1063. currentHistory[prevTick] += int64(delta)
  1064. }
  1065. func (analyser *BurndownAnalysis) updateAuthor(currentTime, previousTime, delta int) {
  1066. previousAuthor, prevTick := analyser.unpackPersonWithTick(previousTime)
  1067. if previousAuthor == identity.AuthorMissing {
  1068. return
  1069. }
  1070. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1071. history := analyser.peopleHistories[previousAuthor]
  1072. if history == nil {
  1073. history = sparseHistory{}
  1074. analyser.peopleHistories[previousAuthor] = history
  1075. }
  1076. currentHistory := history[curTick]
  1077. if currentHistory == nil {
  1078. currentHistory = map[int]int64{}
  1079. history[curTick] = currentHistory
  1080. }
  1081. currentHistory[prevTick] += int64(delta)
  1082. }
  1083. func (analyser *BurndownAnalysis) updateMatrix(currentTime, previousTime, delta int) {
  1084. newAuthor, _ := analyser.unpackPersonWithTick(currentTime)
  1085. oldAuthor, _ := analyser.unpackPersonWithTick(previousTime)
  1086. if oldAuthor == identity.AuthorMissing {
  1087. return
  1088. }
  1089. if newAuthor == oldAuthor && delta > 0 {
  1090. newAuthor = authorSelf
  1091. }
  1092. row := analyser.matrix[oldAuthor]
  1093. if row == nil {
  1094. row = map[int]int64{}
  1095. analyser.matrix[oldAuthor] = row
  1096. }
  1097. cell, exists := row[newAuthor]
  1098. if !exists {
  1099. row[newAuthor] = 0
  1100. cell = 0
  1101. }
  1102. row[newAuthor] = cell + int64(delta)
  1103. }
  1104. func (analyser *BurndownAnalysis) newFile(
  1105. hash plumbing.Hash, name string, author int, tick int, size int) (*burndown.File, error) {
  1106. updaters := make([]burndown.Updater, 1)
  1107. updaters[0] = analyser.updateGlobal
  1108. if analyser.TrackFiles {
  1109. history := analyser.fileHistories[name]
  1110. if history == nil {
  1111. // can be not nil if the file was created in a future branch
  1112. history = sparseHistory{}
  1113. }
  1114. analyser.fileHistories[name] = history
  1115. updaters = append(updaters, func(currentTime, previousTime, delta int) {
  1116. analyser.updateFile(history, currentTime, previousTime, delta)
  1117. })
  1118. }
  1119. if analyser.PeopleNumber > 0 {
  1120. updaters = append(updaters, analyser.updateAuthor)
  1121. updaters = append(updaters, analyser.updateMatrix)
  1122. tick = analyser.packPersonWithTick(author, tick)
  1123. }
  1124. return burndown.NewFile(tick, size, analyser.fileAllocator, updaters...), nil
  1125. }
  1126. func (analyser *BurndownAnalysis) handleInsertion(
  1127. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  1128. blob := cache[change.To.TreeEntry.Hash]
  1129. lines, err := blob.CountLines()
  1130. if err != nil {
  1131. // binary
  1132. return nil
  1133. }
  1134. name := change.To.Name
  1135. file, exists := analyser.files[name]
  1136. if exists {
  1137. return fmt.Errorf("file %s already exists", name)
  1138. }
  1139. var hash plumbing.Hash
  1140. if analyser.tick != burndown.TreeMergeMark {
  1141. hash = blob.Hash
  1142. }
  1143. file, err = analyser.newFile(hash, name, author, analyser.tick, lines)
  1144. analyser.files[name] = file
  1145. if analyser.tick == burndown.TreeMergeMark {
  1146. analyser.mergedFiles[name] = true
  1147. }
  1148. return err
  1149. }
  1150. func (analyser *BurndownAnalysis) handleDeletion(
  1151. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  1152. var name string
  1153. if change.To.TreeEntry.Hash != plumbing.ZeroHash {
  1154. // became binary
  1155. name = change.To.Name
  1156. } else {
  1157. name = change.From.Name
  1158. }
  1159. file, exists := analyser.files[name]
  1160. blob := cache[change.From.TreeEntry.Hash]
  1161. lines, err := blob.CountLines()
  1162. if exists && err != nil {
  1163. return fmt.Errorf("previous version of %s unexpectedly became binary", name)
  1164. }
  1165. if !exists {
  1166. return nil
  1167. }
  1168. file.Update(analyser.packPersonWithTick(author, analyser.tick), 0, 0, lines)
  1169. file.Delete()
  1170. delete(analyser.files, name)
  1171. delete(analyser.fileHistories, name)
  1172. stack := []string{name}
  1173. for len(stack) > 0 {
  1174. head := stack[len(stack)-1]
  1175. stack = stack[:len(stack)-1]
  1176. analyser.renames[head] = ""
  1177. for key, val := range analyser.renames {
  1178. if val == head {
  1179. stack = append(stack, key)
  1180. }
  1181. }
  1182. }
  1183. if analyser.tick == burndown.TreeMergeMark {
  1184. analyser.mergedFiles[name] = false
  1185. }
  1186. return nil
  1187. }
  1188. func (analyser *BurndownAnalysis) handleModification(
  1189. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob,
  1190. diffs map[string]items.FileDiffData) error {
  1191. if analyser.tick == burndown.TreeMergeMark {
  1192. analyser.mergedFiles[change.To.Name] = true
  1193. }
  1194. file, exists := analyser.files[change.From.Name]
  1195. if !exists {
  1196. // this indeed may happen
  1197. return analyser.handleInsertion(change, author, cache)
  1198. }
  1199. // possible rename
  1200. if change.To.Name != change.From.Name {
  1201. err := analyser.handleRename(change.From.Name, change.To.Name)
  1202. if err != nil {
  1203. return err
  1204. }
  1205. }
  1206. // Check for binary changes
  1207. blobFrom := cache[change.From.TreeEntry.Hash]
  1208. _, errFrom := blobFrom.CountLines()
  1209. blobTo := cache[change.To.TreeEntry.Hash]
  1210. _, errTo := blobTo.CountLines()
  1211. if errFrom != errTo {
  1212. if errFrom != nil {
  1213. // the file is no longer binary
  1214. return analyser.handleInsertion(change, author, cache)
  1215. }
  1216. // the file became binary
  1217. return analyser.handleDeletion(change, author, cache)
  1218. } else if errFrom != nil {
  1219. // what are we doing here?!
  1220. return nil
  1221. }
  1222. thisDiffs := diffs[change.To.Name]
  1223. if file.Len() != thisDiffs.OldLinesOfCode {
  1224. log.Printf("====TREE====\n%s", file.Dump())
  1225. return fmt.Errorf("%s: internal integrity error src %d != %d %s -> %s",
  1226. change.To.Name, thisDiffs.OldLinesOfCode, file.Len(),
  1227. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1228. }
  1229. // we do not call RunesToDiffLines so the number of lines equals
  1230. // to the rune count
  1231. position := 0
  1232. pending := diffmatchpatch.Diff{Text: ""}
  1233. apply := func(edit diffmatchpatch.Diff) {
  1234. length := utf8.RuneCountInString(edit.Text)
  1235. if edit.Type == diffmatchpatch.DiffInsert {
  1236. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, length, 0)
  1237. position += length
  1238. } else {
  1239. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, 0, length)
  1240. }
  1241. if analyser.Debug {
  1242. file.Validate()
  1243. }
  1244. }
  1245. for _, edit := range thisDiffs.Diffs {
  1246. dumpBefore := ""
  1247. if analyser.Debug {
  1248. dumpBefore = file.Dump()
  1249. }
  1250. length := utf8.RuneCountInString(edit.Text)
  1251. debugError := func() {
  1252. log.Printf("%s: internal diff error\n", change.To.Name)
  1253. log.Printf("Update(%d, %d, %d (0), %d (0))\n", analyser.tick, position,
  1254. length, utf8.RuneCountInString(pending.Text))
  1255. if dumpBefore != "" {
  1256. log.Printf("====TREE BEFORE====\n%s====END====\n", dumpBefore)
  1257. }
  1258. log.Printf("====TREE AFTER====\n%s====END====\n", file.Dump())
  1259. }
  1260. switch edit.Type {
  1261. case diffmatchpatch.DiffEqual:
  1262. if pending.Text != "" {
  1263. apply(pending)
  1264. pending.Text = ""
  1265. }
  1266. position += length
  1267. case diffmatchpatch.DiffInsert:
  1268. if pending.Text != "" {
  1269. if pending.Type == diffmatchpatch.DiffInsert {
  1270. debugError()
  1271. return errors.New("DiffInsert may not appear after DiffInsert")
  1272. }
  1273. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, length,
  1274. utf8.RuneCountInString(pending.Text))
  1275. if analyser.Debug {
  1276. file.Validate()
  1277. }
  1278. position += length
  1279. pending.Text = ""
  1280. } else {
  1281. pending = edit
  1282. }
  1283. case diffmatchpatch.DiffDelete:
  1284. if pending.Text != "" {
  1285. debugError()
  1286. return errors.New("DiffDelete may not appear after DiffInsert/DiffDelete")
  1287. }
  1288. pending = edit
  1289. default:
  1290. debugError()
  1291. return fmt.Errorf("diff operation is not supported: %d", edit.Type)
  1292. }
  1293. }
  1294. if pending.Text != "" {
  1295. apply(pending)
  1296. pending.Text = ""
  1297. }
  1298. if file.Len() != thisDiffs.NewLinesOfCode {
  1299. return fmt.Errorf("%s: internal integrity error dst %d != %d %s -> %s",
  1300. change.To.Name, thisDiffs.NewLinesOfCode, file.Len(),
  1301. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1302. }
  1303. return nil
  1304. }
  1305. func (analyser *BurndownAnalysis) handleRename(from, to string) error {
  1306. if from == to {
  1307. return nil
  1308. }
  1309. file, exists := analyser.files[from]
  1310. if !exists {
  1311. return fmt.Errorf("file %s > %s does not exist (files)", from, to)
  1312. }
  1313. delete(analyser.files, from)
  1314. analyser.files[to] = file
  1315. if analyser.tick == burndown.TreeMergeMark {
  1316. analyser.mergedFiles[from] = false
  1317. }
  1318. if analyser.TrackFiles {
  1319. history := analyser.fileHistories[from]
  1320. if history == nil {
  1321. var futureRename string
  1322. if _, exists := analyser.renames[""]; exists {
  1323. panic("burndown renames tracking corruption")
  1324. }
  1325. known := map[string]bool{}
  1326. newRename, exists := analyser.renames[from]
  1327. known[from] = true
  1328. for exists {
  1329. futureRename = newRename
  1330. newRename, exists = analyser.renames[futureRename]
  1331. if known[newRename] {
  1332. // infinite cycle
  1333. futureRename = ""
  1334. for key := range known {
  1335. if analyser.fileHistories[key] != nil {
  1336. futureRename = key
  1337. break
  1338. }
  1339. }
  1340. break
  1341. }
  1342. known[futureRename] = true
  1343. }
  1344. // a future branch could have already renamed it and we are retarded
  1345. if futureRename == "" {
  1346. // the file will be deleted in the future, whatever
  1347. history = sparseHistory{}
  1348. } else {
  1349. history = analyser.fileHistories[futureRename]
  1350. if history == nil {
  1351. return fmt.Errorf("file %s > %s (%s) does not exist (histories)",
  1352. from, to, futureRename)
  1353. }
  1354. }
  1355. }
  1356. delete(analyser.fileHistories, from)
  1357. analyser.fileHistories[to] = history
  1358. }
  1359. analyser.renames[from] = to
  1360. return nil
  1361. }
  1362. func (analyser *BurndownAnalysis) groupSparseHistory(
  1363. history sparseHistory, lastTick int) (DenseHistory, int) {
  1364. if len(history) == 0 {
  1365. panic("empty history")
  1366. }
  1367. var ticks []int
  1368. for tick := range history {
  1369. ticks = append(ticks, tick)
  1370. }
  1371. sort.Ints(ticks)
  1372. if lastTick >= 0 {
  1373. if ticks[len(ticks)-1] < lastTick {
  1374. ticks = append(ticks, lastTick)
  1375. } else if ticks[len(ticks)-1] > lastTick {
  1376. panic("ticks corruption")
  1377. }
  1378. } else {
  1379. lastTick = ticks[len(ticks)-1]
  1380. }
  1381. // [y][x]
  1382. // y - sampling
  1383. // x - granularity
  1384. samples := lastTick/analyser.Sampling + 1
  1385. bands := lastTick/analyser.Granularity + 1
  1386. result := make(DenseHistory, samples)
  1387. for i := 0; i < bands; i++ {
  1388. result[i] = make([]int64, bands)
  1389. }
  1390. prevsi := 0
  1391. for _, tick := range ticks {
  1392. si := tick / analyser.Sampling
  1393. if si > prevsi {
  1394. state := result[prevsi]
  1395. for i := prevsi + 1; i <= si; i++ {
  1396. copy(result[i], state)
  1397. }
  1398. prevsi = si
  1399. }
  1400. sample := result[si]
  1401. for t, value := range history[tick] {
  1402. sample[t/analyser.Granularity] += value
  1403. }
  1404. }
  1405. return result, lastTick
  1406. }
  1407. func init() {
  1408. core.Registry.Register(&BurndownAnalysis{})
  1409. }