burndown.go 50 KB

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