burndown.go 49 KB

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