burndown.go 51 KB

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