burndown.go 51 KB

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