burndown.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  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. merged := BurndownResult{}
  605. if bar1.sampling < bar2.sampling {
  606. merged.sampling = bar1.sampling
  607. } else {
  608. merged.sampling = bar2.sampling
  609. }
  610. if bar1.granularity < bar2.granularity {
  611. merged.granularity = bar1.granularity
  612. } else {
  613. merged.granularity = bar2.granularity
  614. }
  615. if bar1.TickSize < bar2.TickSize {
  616. merged.TickSize = bar1.TickSize
  617. } else {
  618. merged.TickSize = bar2.TickSize
  619. }
  620. var people map[string][3]int
  621. people, merged.reversedPeopleDict = identity.Detector{}.MergeReversedDicts(
  622. bar1.reversedPeopleDict, bar2.reversedPeopleDict)
  623. var wg sync.WaitGroup
  624. if len(bar1.GlobalHistory) > 0 || len(bar2.GlobalHistory) > 0 {
  625. wg.Add(1)
  626. go func() {
  627. defer wg.Done()
  628. merged.GlobalHistory = analyser.mergeMatrices(
  629. bar1.GlobalHistory, bar2.GlobalHistory,
  630. bar1.granularity, bar1.sampling,
  631. bar2.granularity, bar2.sampling,
  632. c1, c2)
  633. }()
  634. }
  635. // we don't merge files
  636. if len(merged.reversedPeopleDict) > 0 {
  637. if len(bar1.PeopleHistories) > 0 || len(bar2.PeopleHistories) > 0 {
  638. merged.PeopleHistories = make([]DenseHistory, len(merged.reversedPeopleDict))
  639. for i, key := range merged.reversedPeopleDict {
  640. ptrs := people[key]
  641. wg.Add(1)
  642. go func(i int) {
  643. defer wg.Done()
  644. var m1, m2 DenseHistory
  645. if ptrs[1] >= 0 {
  646. m1 = bar1.PeopleHistories[ptrs[1]]
  647. }
  648. if ptrs[2] >= 0 {
  649. m2 = bar2.PeopleHistories[ptrs[2]]
  650. }
  651. merged.PeopleHistories[i] = analyser.mergeMatrices(
  652. m1, m2,
  653. bar1.granularity, bar1.sampling,
  654. bar2.granularity, bar2.sampling,
  655. c1, c2,
  656. )
  657. }(i)
  658. }
  659. }
  660. wg.Add(1)
  661. go func() {
  662. defer wg.Done()
  663. if len(bar2.PeopleMatrix) == 0 {
  664. merged.PeopleMatrix = bar1.PeopleMatrix
  665. // extend the matrix in both directions
  666. for i := 0; i < len(merged.PeopleMatrix); i++ {
  667. for j := len(bar1.reversedPeopleDict); j < len(merged.reversedPeopleDict); j++ {
  668. merged.PeopleMatrix[i] = append(merged.PeopleMatrix[i], 0)
  669. }
  670. }
  671. if len(bar1.PeopleMatrix) > 0 {
  672. for i := len(bar1.reversedPeopleDict); i < len(merged.reversedPeopleDict); i++ {
  673. merged.PeopleMatrix = append(
  674. merged.PeopleMatrix, make([]int64, len(merged.reversedPeopleDict)+2))
  675. }
  676. }
  677. } else {
  678. merged.PeopleMatrix = make(DenseHistory, len(merged.reversedPeopleDict))
  679. for i := range merged.PeopleMatrix {
  680. merged.PeopleMatrix[i] = make([]int64, len(merged.reversedPeopleDict)+2)
  681. }
  682. for i, key := range bar1.reversedPeopleDict {
  683. mi := people[key][0] // index in merged.reversedPeopleDict
  684. copy(merged.PeopleMatrix[mi][:2], bar1.PeopleMatrix[i][:2])
  685. for j, val := range bar1.PeopleMatrix[i][2:] {
  686. merged.PeopleMatrix[mi][2+people[bar1.reversedPeopleDict[j]][0]] = val
  687. }
  688. }
  689. for i, key := range bar2.reversedPeopleDict {
  690. mi := people[key][0] // index in merged.reversedPeopleDict
  691. merged.PeopleMatrix[mi][0] += bar2.PeopleMatrix[i][0]
  692. merged.PeopleMatrix[mi][1] += bar2.PeopleMatrix[i][1]
  693. for j, val := range bar2.PeopleMatrix[i][2:] {
  694. merged.PeopleMatrix[mi][2+people[bar2.reversedPeopleDict[j]][0]] += val
  695. }
  696. }
  697. }
  698. }()
  699. }
  700. wg.Wait()
  701. return merged
  702. }
  703. func (analyser *BurndownAnalysis) roundTime(unix int64, dir bool) int {
  704. ticks := float64(unix) / analyser.tickSize.Seconds()
  705. if dir {
  706. return int(math.Ceil(ticks))
  707. }
  708. return int(math.Floor(ticks))
  709. }
  710. // mergeMatrices takes two [number of samples][number of bands] matrices,
  711. // resamples them to ticks so that they become square, sums and resamples back to the
  712. // least of (sampling1, sampling2) and (granularity1, granularity2).
  713. func (analyser *BurndownAnalysis) mergeMatrices(m1, m2 DenseHistory, granularity1, sampling1, granularity2, sampling2 int,
  714. c1, c2 *core.CommonAnalysisResult) DenseHistory {
  715. commonMerged := c1.Copy()
  716. commonMerged.Merge(c2)
  717. var granularity, sampling int
  718. if sampling1 < sampling2 {
  719. sampling = sampling1
  720. } else {
  721. sampling = sampling2
  722. }
  723. if granularity1 < granularity2 {
  724. granularity = granularity1
  725. } else {
  726. granularity = granularity2
  727. }
  728. size := analyser.roundTime(commonMerged.EndTime, true) -
  729. analyser.roundTime(commonMerged.BeginTime, false)
  730. perTick := make([][]float32, size+granularity)
  731. for i := range perTick {
  732. perTick[i] = make([]float32, size+sampling)
  733. }
  734. if len(m1) > 0 {
  735. addBurndownMatrix(m1, granularity1, sampling1, perTick,
  736. analyser.roundTime(c1.BeginTime, false)-analyser.roundTime(commonMerged.BeginTime, false))
  737. }
  738. if len(m2) > 0 {
  739. addBurndownMatrix(m2, granularity2, sampling2, perTick,
  740. analyser.roundTime(c2.BeginTime, false)-analyser.roundTime(commonMerged.BeginTime, false))
  741. }
  742. // convert daily to [][]int64
  743. result := make(DenseHistory, (size+sampling-1)/sampling)
  744. for i := range result {
  745. result[i] = make([]int64, (size+granularity-1)/granularity)
  746. sampledIndex := (i+1)*sampling - 1
  747. for j := 0; j < len(result[i]); j++ {
  748. accum := float32(0)
  749. for k := j * granularity; k < (j+1)*granularity; k++ {
  750. accum += perTick[sampledIndex][k]
  751. }
  752. result[i][j] = int64(accum)
  753. }
  754. }
  755. return result
  756. }
  757. // Explode `matrix` so that it is daily sampled and has daily bands, shift by `offset` ticks
  758. // and add to the accumulator. `daily` size is square and is guaranteed to fit `matrix` by
  759. // the caller.
  760. // Rows: *at least* len(matrix) * sampling + offset
  761. // Columns: *at least* len(matrix[...]) * granularity + offset
  762. // `matrix` can be sparse, so that the last columns which are equal to 0 are truncated.
  763. func addBurndownMatrix(matrix DenseHistory, granularity, sampling int, accPerTick [][]float32, offset int) {
  764. // Determine the maximum number of bands; the actual one may be larger but we do not care
  765. maxCols := 0
  766. for _, row := range matrix {
  767. if maxCols < len(row) {
  768. maxCols = len(row)
  769. }
  770. }
  771. neededRows := len(matrix)*sampling + offset
  772. if len(accPerTick) < neededRows {
  773. log.Panicf("merge bug: too few per-tick rows: required %d, have %d",
  774. neededRows, len(accPerTick))
  775. }
  776. if len(accPerTick[0]) < maxCols {
  777. log.Panicf("merge bug: too few per-tick cols: required %d, have %d",
  778. maxCols, len(accPerTick[0]))
  779. }
  780. perTick := make([][]float32, len(accPerTick))
  781. for i, row := range accPerTick {
  782. perTick[i] = make([]float32, len(row))
  783. }
  784. for x := 0; x < maxCols; x++ {
  785. for y := 0; y < len(matrix); y++ {
  786. if x*granularity > (y+1)*sampling {
  787. // the future is zeros
  788. continue
  789. }
  790. decay := func(startIndex int, startVal float32) {
  791. if startVal == 0 {
  792. return
  793. }
  794. k := float32(matrix[y][x]) / startVal // <= 1
  795. scale := float32((y+1)*sampling - startIndex)
  796. for i := x * granularity; i < (x+1)*granularity; i++ {
  797. initial := perTick[startIndex-1+offset][i+offset]
  798. for j := startIndex; j < (y+1)*sampling; j++ {
  799. perTick[j+offset][i+offset] = initial * (1 + (k-1)*float32(j-startIndex+1)/scale)
  800. }
  801. }
  802. }
  803. raise := func(finishIndex int, finishVal float32) {
  804. var initial float32
  805. if y > 0 {
  806. initial = float32(matrix[y-1][x])
  807. }
  808. startIndex := y * sampling
  809. if startIndex < x*granularity {
  810. startIndex = x * granularity
  811. }
  812. if startIndex == finishIndex {
  813. return
  814. }
  815. avg := (finishVal - initial) / float32(finishIndex-startIndex)
  816. for j := y * sampling; j < finishIndex; j++ {
  817. for i := startIndex; i <= j; i++ {
  818. perTick[j+offset][i+offset] = avg
  819. }
  820. }
  821. // copy [x*g..y*s)
  822. for j := y * sampling; j < finishIndex; j++ {
  823. for i := x * granularity; i < y*sampling; i++ {
  824. perTick[j+offset][i+offset] = perTick[j-1+offset][i+offset]
  825. }
  826. }
  827. }
  828. if (x+1)*granularity >= (y+1)*sampling {
  829. // x*granularity <= (y+1)*sampling
  830. // 1. x*granularity <= y*sampling
  831. // y*sampling..(y+1)sampling
  832. //
  833. // x+1
  834. // /
  835. // /
  836. // / y+1 -|
  837. // / |
  838. // / y -|
  839. // /
  840. // / x
  841. //
  842. // 2. x*granularity > y*sampling
  843. // x*granularity..(y+1)sampling
  844. //
  845. // x+1
  846. // /
  847. // /
  848. // / y+1 -|
  849. // / |
  850. // / x -|
  851. // /
  852. // / y
  853. if x*granularity <= y*sampling {
  854. raise((y+1)*sampling, float32(matrix[y][x]))
  855. } else if (y+1)*sampling > x*granularity {
  856. raise((y+1)*sampling, float32(matrix[y][x]))
  857. avg := float32(matrix[y][x]) / float32((y+1)*sampling-x*granularity)
  858. for j := x * granularity; j < (y+1)*sampling; j++ {
  859. for i := x * granularity; i <= j; i++ {
  860. perTick[j+offset][i+offset] = avg
  861. }
  862. }
  863. }
  864. } else if (x+1)*granularity >= y*sampling {
  865. // y*sampling <= (x+1)*granularity < (y+1)sampling
  866. // y*sampling..(x+1)*granularity
  867. // (x+1)*granularity..(y+1)sampling
  868. // x+1
  869. // /\
  870. // / \
  871. // / \
  872. // / y+1
  873. // /
  874. // y
  875. v1 := float32(matrix[y-1][x])
  876. v2 := float32(matrix[y][x])
  877. var peak float32
  878. delta := float32((x+1)*granularity - y*sampling)
  879. var scale float32
  880. var previous float32
  881. if y > 0 && (y-1)*sampling >= x*granularity {
  882. // x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  883. // |________|.......^
  884. if y > 1 {
  885. previous = float32(matrix[y-2][x])
  886. }
  887. scale = float32(sampling)
  888. } else {
  889. // (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  890. // |______|.......^
  891. if y == 0 {
  892. scale = float32(sampling)
  893. } else {
  894. scale = float32(y*sampling - x*granularity)
  895. }
  896. }
  897. peak = v1 + (v1-previous)/scale*delta
  898. if v2 > peak {
  899. // we need to adjust the peak, it may not be less than the decayed value
  900. if y < len(matrix)-1 {
  901. // y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  902. // ^.........|_________|
  903. k := (v2 - float32(matrix[y+1][x])) / float32(sampling) // > 0
  904. peak = float32(matrix[y][x]) + k*float32((y+1)*sampling-(x+1)*granularity)
  905. // peak > v2 > v1
  906. } else {
  907. peak = v2
  908. // not enough data to interpolate; this is at least not restricted
  909. }
  910. }
  911. raise((x+1)*granularity, peak)
  912. decay((x+1)*granularity, peak)
  913. } else {
  914. // (x+1)*granularity < y*sampling
  915. // y*sampling..(y+1)sampling
  916. decay(y*sampling, float32(matrix[y-1][x]))
  917. }
  918. }
  919. }
  920. for y := len(matrix) * sampling; y+offset < len(perTick); y++ {
  921. copy(perTick[y+offset], perTick[len(matrix)*sampling-1+offset])
  922. }
  923. // the original matrix has been resampled by tick
  924. // add it to the accumulator
  925. for y, row := range perTick {
  926. for x, val := range row {
  927. accPerTick[y][x] += val
  928. }
  929. }
  930. }
  931. func (analyser *BurndownAnalysis) serializeText(result *BurndownResult, writer io.Writer) {
  932. fmt.Fprintln(writer, " granularity:", result.granularity)
  933. fmt.Fprintln(writer, " sampling:", result.sampling)
  934. yaml.PrintMatrix(writer, result.GlobalHistory, 2, "project", true)
  935. if len(result.FileHistories) > 0 {
  936. fmt.Fprintln(writer, " files:")
  937. keys := sortedKeys(result.FileHistories)
  938. for _, key := range keys {
  939. yaml.PrintMatrix(writer, result.FileHistories[key], 4, key, true)
  940. }
  941. fmt.Fprintln(writer, " files_ownership:")
  942. okeys := make([]string, 0, len(result.FileOwnership))
  943. for key := range result.FileOwnership {
  944. okeys = append(okeys, key)
  945. }
  946. sort.Strings(okeys)
  947. for _, key := range okeys {
  948. owned := result.FileOwnership[key]
  949. devs := make([]int, 0, len(owned))
  950. for devi := range owned {
  951. devs = append(devs, devi)
  952. }
  953. sort.Slice(devs, func(i, j int) bool {
  954. return owned[devs[i]] > owned[devs[j]] // descending order
  955. })
  956. for x, devi := range devs {
  957. var indent string
  958. if x == 0 {
  959. indent = "- "
  960. } else {
  961. indent = " "
  962. }
  963. fmt.Fprintf(writer, " %s%d: %d\n", indent, devi, owned[devi])
  964. }
  965. }
  966. }
  967. if len(result.PeopleHistories) > 0 {
  968. fmt.Fprintln(writer, " people_sequence:")
  969. for key := range result.PeopleHistories {
  970. fmt.Fprintln(writer, " - "+yaml.SafeString(result.reversedPeopleDict[key]))
  971. }
  972. fmt.Fprintln(writer, " people:")
  973. for key, val := range result.PeopleHistories {
  974. yaml.PrintMatrix(writer, val, 4, result.reversedPeopleDict[key], true)
  975. }
  976. fmt.Fprintln(writer, " people_interaction: |-")
  977. yaml.PrintMatrix(writer, result.PeopleMatrix, 4, "", false)
  978. }
  979. }
  980. func (analyser *BurndownAnalysis) serializeBinary(result *BurndownResult, writer io.Writer) error {
  981. message := pb.BurndownAnalysisResults{
  982. Granularity: int32(result.granularity),
  983. Sampling: int32(result.sampling),
  984. TickSize: int64(result.TickSize),
  985. }
  986. if len(result.GlobalHistory) > 0 {
  987. message.Project = pb.ToBurndownSparseMatrix(result.GlobalHistory, "project")
  988. }
  989. if len(result.FileHistories) > 0 {
  990. message.Files = make([]*pb.BurndownSparseMatrix, len(result.FileHistories))
  991. message.FilesOwnership = make([]*pb.FilesOwnership, len(result.FileHistories))
  992. keys := sortedKeys(result.FileHistories)
  993. i := 0
  994. for _, key := range keys {
  995. message.Files[i] = pb.ToBurndownSparseMatrix(result.FileHistories[key], key)
  996. ownership := map[int32]int32{}
  997. message.FilesOwnership[i] = &pb.FilesOwnership{Value: ownership}
  998. for key, val := range result.FileOwnership[key] {
  999. ownership[int32(key)] = int32(val)
  1000. }
  1001. i++
  1002. }
  1003. }
  1004. if len(result.PeopleHistories) > 0 {
  1005. message.People = make(
  1006. []*pb.BurndownSparseMatrix, len(result.PeopleHistories))
  1007. for key, val := range result.PeopleHistories {
  1008. if len(val) > 0 {
  1009. message.People[key] = pb.ToBurndownSparseMatrix(val, result.reversedPeopleDict[key])
  1010. }
  1011. }
  1012. }
  1013. if result.PeopleMatrix != nil {
  1014. message.PeopleInteraction = pb.DenseToCompressedSparseRowMatrix(result.PeopleMatrix)
  1015. }
  1016. serialized, err := proto.Marshal(&message)
  1017. if err != nil {
  1018. return err
  1019. }
  1020. _, err = writer.Write(serialized)
  1021. return err
  1022. }
  1023. func sortedKeys(m map[string]DenseHistory) []string {
  1024. keys := make([]string, 0, len(m))
  1025. for k := range m {
  1026. keys = append(keys, k)
  1027. }
  1028. sort.Strings(keys)
  1029. return keys
  1030. }
  1031. func checkClose(c io.Closer) {
  1032. if err := c.Close(); err != nil {
  1033. panic(err)
  1034. }
  1035. }
  1036. // We do a hack and store the tick in the first 14 bits and the author index in the last 18.
  1037. // Strictly speaking, int can be 64-bit and then the author index occupies 32+18 bits.
  1038. // This hack is needed to simplify the values storage inside File-s. We can compare
  1039. // different values together and they are compared as ticks for the same author.
  1040. func (analyser *BurndownAnalysis) packPersonWithTick(person int, tick int) int {
  1041. if analyser.PeopleNumber == 0 {
  1042. return tick
  1043. }
  1044. result := tick & burndown.TreeMergeMark
  1045. result |= person << burndown.TreeMaxBinPower
  1046. // This effectively means max (16383 - 1) ticks (>44 years) and (262143 - 3) devs.
  1047. // One tick less because burndown.TreeMergeMark = ((1 << 14) - 1) is a special tick.
  1048. // Three devs less because:
  1049. // - math.MaxUint32 is the special rbtree value with tick == TreeMergeMark (-1)
  1050. // - identity.AuthorMissing (-2)
  1051. // - authorSelf (-3)
  1052. return result
  1053. }
  1054. func (analyser *BurndownAnalysis) unpackPersonWithTick(value int) (int, int) {
  1055. if analyser.PeopleNumber == 0 {
  1056. return identity.AuthorMissing, value
  1057. }
  1058. return value >> burndown.TreeMaxBinPower, value & burndown.TreeMergeMark
  1059. }
  1060. func (analyser *BurndownAnalysis) onNewTick() {
  1061. if analyser.tick > analyser.previousTick {
  1062. analyser.previousTick = analyser.tick
  1063. }
  1064. analyser.mergedAuthor = identity.AuthorMissing
  1065. }
  1066. func (analyser *BurndownAnalysis) updateGlobal(currentTime, previousTime, delta int) {
  1067. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1068. _, prevTick := analyser.unpackPersonWithTick(previousTime)
  1069. currentHistory := analyser.globalHistory[curTick]
  1070. if currentHistory == nil {
  1071. currentHistory = map[int]int64{}
  1072. analyser.globalHistory[curTick] = currentHistory
  1073. }
  1074. currentHistory[prevTick] += int64(delta)
  1075. }
  1076. // updateFile is bound to the specific `history` in the closure.
  1077. func (analyser *BurndownAnalysis) updateFile(
  1078. history sparseHistory, currentTime, previousTime, delta int) {
  1079. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1080. _, prevTick := analyser.unpackPersonWithTick(previousTime)
  1081. currentHistory := history[curTick]
  1082. if currentHistory == nil {
  1083. currentHistory = map[int]int64{}
  1084. history[curTick] = currentHistory
  1085. }
  1086. currentHistory[prevTick] += int64(delta)
  1087. }
  1088. func (analyser *BurndownAnalysis) updateAuthor(currentTime, previousTime, delta int) {
  1089. previousAuthor, prevTick := analyser.unpackPersonWithTick(previousTime)
  1090. if previousAuthor == identity.AuthorMissing {
  1091. return
  1092. }
  1093. _, curTick := analyser.unpackPersonWithTick(currentTime)
  1094. history := analyser.peopleHistories[previousAuthor]
  1095. if history == nil {
  1096. history = sparseHistory{}
  1097. analyser.peopleHistories[previousAuthor] = history
  1098. }
  1099. currentHistory := history[curTick]
  1100. if currentHistory == nil {
  1101. currentHistory = map[int]int64{}
  1102. history[curTick] = currentHistory
  1103. }
  1104. currentHistory[prevTick] += int64(delta)
  1105. }
  1106. func (analyser *BurndownAnalysis) updateMatrix(currentTime, previousTime, delta int) {
  1107. newAuthor, _ := analyser.unpackPersonWithTick(currentTime)
  1108. oldAuthor, _ := analyser.unpackPersonWithTick(previousTime)
  1109. if oldAuthor == identity.AuthorMissing {
  1110. return
  1111. }
  1112. if newAuthor == oldAuthor && delta > 0 {
  1113. newAuthor = authorSelf
  1114. }
  1115. row := analyser.matrix[oldAuthor]
  1116. if row == nil {
  1117. row = map[int]int64{}
  1118. analyser.matrix[oldAuthor] = row
  1119. }
  1120. cell, exists := row[newAuthor]
  1121. if !exists {
  1122. row[newAuthor] = 0
  1123. cell = 0
  1124. }
  1125. row[newAuthor] = cell + int64(delta)
  1126. }
  1127. func (analyser *BurndownAnalysis) newFile(
  1128. hash plumbing.Hash, name string, author int, tick int, size int) (*burndown.File, error) {
  1129. updaters := make([]burndown.Updater, 1)
  1130. updaters[0] = analyser.updateGlobal
  1131. if analyser.TrackFiles {
  1132. history := analyser.fileHistories[name]
  1133. if history == nil {
  1134. // can be not nil if the file was created in a future branch
  1135. history = sparseHistory{}
  1136. }
  1137. analyser.fileHistories[name] = history
  1138. updaters = append(updaters, func(currentTime, previousTime, delta int) {
  1139. analyser.updateFile(history, currentTime, previousTime, delta)
  1140. })
  1141. }
  1142. if analyser.PeopleNumber > 0 {
  1143. updaters = append(updaters, analyser.updateAuthor)
  1144. updaters = append(updaters, analyser.updateMatrix)
  1145. tick = analyser.packPersonWithTick(author, tick)
  1146. }
  1147. return burndown.NewFile(tick, size, analyser.fileAllocator, updaters...), nil
  1148. }
  1149. func (analyser *BurndownAnalysis) handleInsertion(
  1150. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  1151. blob := cache[change.To.TreeEntry.Hash]
  1152. lines, err := blob.CountLines()
  1153. if err != nil {
  1154. // binary
  1155. return nil
  1156. }
  1157. name := change.To.Name
  1158. file, exists := analyser.files[name]
  1159. if exists {
  1160. return fmt.Errorf("file %s already exists", name)
  1161. }
  1162. var hash plumbing.Hash
  1163. if analyser.tick != burndown.TreeMergeMark {
  1164. hash = blob.Hash
  1165. }
  1166. file, err = analyser.newFile(hash, name, author, analyser.tick, lines)
  1167. analyser.files[name] = file
  1168. if analyser.tick == burndown.TreeMergeMark {
  1169. analyser.mergedFiles[name] = true
  1170. }
  1171. return err
  1172. }
  1173. func (analyser *BurndownAnalysis) handleDeletion(
  1174. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  1175. var name string
  1176. if change.To.TreeEntry.Hash != plumbing.ZeroHash {
  1177. // became binary
  1178. name = change.To.Name
  1179. } else {
  1180. name = change.From.Name
  1181. }
  1182. file, exists := analyser.files[name]
  1183. blob := cache[change.From.TreeEntry.Hash]
  1184. lines, err := blob.CountLines()
  1185. if exists && err != nil {
  1186. return fmt.Errorf("previous version of %s unexpectedly became binary", name)
  1187. }
  1188. if !exists {
  1189. return nil
  1190. }
  1191. file.Update(analyser.packPersonWithTick(author, analyser.tick), 0, 0, lines)
  1192. file.Delete()
  1193. delete(analyser.files, name)
  1194. delete(analyser.fileHistories, name)
  1195. stack := []string{name}
  1196. for len(stack) > 0 {
  1197. head := stack[len(stack)-1]
  1198. stack = stack[:len(stack)-1]
  1199. analyser.renames[head] = ""
  1200. for key, val := range analyser.renames {
  1201. if val == head {
  1202. stack = append(stack, key)
  1203. }
  1204. }
  1205. }
  1206. if analyser.tick == burndown.TreeMergeMark {
  1207. analyser.mergedFiles[name] = false
  1208. }
  1209. return nil
  1210. }
  1211. func (analyser *BurndownAnalysis) handleModification(
  1212. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob,
  1213. diffs map[string]items.FileDiffData) error {
  1214. if analyser.tick == burndown.TreeMergeMark {
  1215. analyser.mergedFiles[change.To.Name] = true
  1216. }
  1217. file, exists := analyser.files[change.From.Name]
  1218. if !exists {
  1219. // this indeed may happen
  1220. return analyser.handleInsertion(change, author, cache)
  1221. }
  1222. // possible rename
  1223. if change.To.Name != change.From.Name {
  1224. err := analyser.handleRename(change.From.Name, change.To.Name)
  1225. if err != nil {
  1226. return err
  1227. }
  1228. }
  1229. // Check for binary changes
  1230. blobFrom := cache[change.From.TreeEntry.Hash]
  1231. _, errFrom := blobFrom.CountLines()
  1232. blobTo := cache[change.To.TreeEntry.Hash]
  1233. _, errTo := blobTo.CountLines()
  1234. if errFrom != errTo {
  1235. if errFrom != nil {
  1236. // the file is no longer binary
  1237. return analyser.handleInsertion(change, author, cache)
  1238. }
  1239. // the file became binary
  1240. return analyser.handleDeletion(change, author, cache)
  1241. } else if errFrom != nil {
  1242. // what are we doing here?!
  1243. return nil
  1244. }
  1245. thisDiffs := diffs[change.To.Name]
  1246. if file.Len() != thisDiffs.OldLinesOfCode {
  1247. log.Printf("====TREE====\n%s", file.Dump())
  1248. return fmt.Errorf("%s: internal integrity error src %d != %d %s -> %s",
  1249. change.To.Name, thisDiffs.OldLinesOfCode, file.Len(),
  1250. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1251. }
  1252. // we do not call RunesToDiffLines so the number of lines equals
  1253. // to the rune count
  1254. position := 0
  1255. pending := diffmatchpatch.Diff{Text: ""}
  1256. apply := func(edit diffmatchpatch.Diff) {
  1257. length := utf8.RuneCountInString(edit.Text)
  1258. if edit.Type == diffmatchpatch.DiffInsert {
  1259. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, length, 0)
  1260. position += length
  1261. } else {
  1262. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, 0, length)
  1263. }
  1264. if analyser.Debug {
  1265. file.Validate()
  1266. }
  1267. }
  1268. for _, edit := range thisDiffs.Diffs {
  1269. dumpBefore := ""
  1270. if analyser.Debug {
  1271. dumpBefore = file.Dump()
  1272. }
  1273. length := utf8.RuneCountInString(edit.Text)
  1274. debugError := func() {
  1275. log.Printf("%s: internal diff error\n", change.To.Name)
  1276. log.Printf("Update(%d, %d, %d (0), %d (0))\n", analyser.tick, position,
  1277. length, utf8.RuneCountInString(pending.Text))
  1278. if dumpBefore != "" {
  1279. log.Printf("====TREE BEFORE====\n%s====END====\n", dumpBefore)
  1280. }
  1281. log.Printf("====TREE AFTER====\n%s====END====\n", file.Dump())
  1282. }
  1283. switch edit.Type {
  1284. case diffmatchpatch.DiffEqual:
  1285. if pending.Text != "" {
  1286. apply(pending)
  1287. pending.Text = ""
  1288. }
  1289. position += length
  1290. case diffmatchpatch.DiffInsert:
  1291. if pending.Text != "" {
  1292. if pending.Type == diffmatchpatch.DiffInsert {
  1293. debugError()
  1294. return errors.New("DiffInsert may not appear after DiffInsert")
  1295. }
  1296. file.Update(analyser.packPersonWithTick(author, analyser.tick), position, length,
  1297. utf8.RuneCountInString(pending.Text))
  1298. if analyser.Debug {
  1299. file.Validate()
  1300. }
  1301. position += length
  1302. pending.Text = ""
  1303. } else {
  1304. pending = edit
  1305. }
  1306. case diffmatchpatch.DiffDelete:
  1307. if pending.Text != "" {
  1308. debugError()
  1309. return errors.New("DiffDelete may not appear after DiffInsert/DiffDelete")
  1310. }
  1311. pending = edit
  1312. default:
  1313. debugError()
  1314. return fmt.Errorf("diff operation is not supported: %d", edit.Type)
  1315. }
  1316. }
  1317. if pending.Text != "" {
  1318. apply(pending)
  1319. pending.Text = ""
  1320. }
  1321. if file.Len() != thisDiffs.NewLinesOfCode {
  1322. return fmt.Errorf("%s: internal integrity error dst %d != %d %s -> %s",
  1323. change.To.Name, thisDiffs.NewLinesOfCode, file.Len(),
  1324. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1325. }
  1326. return nil
  1327. }
  1328. func (analyser *BurndownAnalysis) handleRename(from, to string) error {
  1329. if from == to {
  1330. return nil
  1331. }
  1332. file, exists := analyser.files[from]
  1333. if !exists {
  1334. return fmt.Errorf("file %s > %s does not exist (files)", from, to)
  1335. }
  1336. delete(analyser.files, from)
  1337. analyser.files[to] = file
  1338. if analyser.tick == burndown.TreeMergeMark {
  1339. analyser.mergedFiles[from] = false
  1340. }
  1341. if analyser.TrackFiles {
  1342. history := analyser.fileHistories[from]
  1343. if history == nil {
  1344. var futureRename string
  1345. if _, exists := analyser.renames[""]; exists {
  1346. panic("burndown renames tracking corruption")
  1347. }
  1348. known := map[string]bool{}
  1349. newRename, exists := analyser.renames[from]
  1350. known[from] = true
  1351. for exists {
  1352. futureRename = newRename
  1353. newRename, exists = analyser.renames[futureRename]
  1354. if known[newRename] {
  1355. // infinite cycle
  1356. futureRename = ""
  1357. for key := range known {
  1358. if analyser.fileHistories[key] != nil {
  1359. futureRename = key
  1360. break
  1361. }
  1362. }
  1363. break
  1364. }
  1365. known[futureRename] = true
  1366. }
  1367. // a future branch could have already renamed it and we are retarded
  1368. if futureRename == "" {
  1369. // the file will be deleted in the future, whatever
  1370. history = sparseHistory{}
  1371. } else {
  1372. history = analyser.fileHistories[futureRename]
  1373. if history == nil {
  1374. return fmt.Errorf("file %s > %s (%s) does not exist (histories)",
  1375. from, to, futureRename)
  1376. }
  1377. }
  1378. }
  1379. delete(analyser.fileHistories, from)
  1380. analyser.fileHistories[to] = history
  1381. }
  1382. analyser.renames[from] = to
  1383. return nil
  1384. }
  1385. func (analyser *BurndownAnalysis) groupSparseHistory(
  1386. history sparseHistory, lastTick int) (DenseHistory, int) {
  1387. if len(history) == 0 {
  1388. panic("empty history")
  1389. }
  1390. var ticks []int
  1391. for tick := range history {
  1392. ticks = append(ticks, tick)
  1393. }
  1394. sort.Ints(ticks)
  1395. if lastTick >= 0 {
  1396. if ticks[len(ticks)-1] < lastTick {
  1397. ticks = append(ticks, lastTick)
  1398. } else if ticks[len(ticks)-1] > lastTick {
  1399. panic("ticks corruption")
  1400. }
  1401. } else {
  1402. lastTick = ticks[len(ticks)-1]
  1403. }
  1404. // [y][x]
  1405. // y - sampling
  1406. // x - granularity
  1407. samples := lastTick/analyser.Sampling + 1
  1408. bands := lastTick/analyser.Granularity + 1
  1409. result := make(DenseHistory, samples)
  1410. for i := 0; i < bands; i++ {
  1411. result[i] = make([]int64, bands)
  1412. }
  1413. prevsi := 0
  1414. for _, tick := range ticks {
  1415. si := tick / analyser.Sampling
  1416. if si > prevsi {
  1417. state := result[prevsi]
  1418. for i := prevsi + 1; i <= si; i++ {
  1419. copy(result[i], state)
  1420. }
  1421. prevsi = si
  1422. }
  1423. sample := result[si]
  1424. for t, value := range history[tick] {
  1425. sample[t/analyser.Granularity] += value
  1426. }
  1427. }
  1428. return result, lastTick
  1429. }
  1430. func init() {
  1431. core.Registry.Register(&BurndownAnalysis{})
  1432. }