burndown.go 46 KB

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