burndown.go 46 KB

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