burndown.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  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 = (1 << (32 - burndown.TreeMaxBinPower)) - 2
  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 (131072 - 2) devs.
  962. // One day less because burndown.TreeMergeMark = ((1 << 14) - 1) is a special day.
  963. return result
  964. }
  965. func (analyser *BurndownAnalysis) unpackPersonWithDay(value int) (int, int) {
  966. if analyser.PeopleNumber == 0 {
  967. return identity.AuthorMissing, value
  968. }
  969. return value >> burndown.TreeMaxBinPower, value & burndown.TreeMergeMark
  970. }
  971. func (analyser *BurndownAnalysis) onNewDay() {
  972. if analyser.day > analyser.previousDay {
  973. analyser.previousDay = analyser.day
  974. }
  975. analyser.mergedAuthor = identity.AuthorMissing
  976. }
  977. func (analyser *BurndownAnalysis) updateGlobal(currentTime, previousTime, delta int) {
  978. _, currentDay := analyser.unpackPersonWithDay(currentTime)
  979. _, previousDay := analyser.unpackPersonWithDay(previousTime)
  980. currentHistory := analyser.globalHistory[currentDay]
  981. if currentHistory == nil {
  982. currentHistory = map[int]int64{}
  983. analyser.globalHistory[currentDay] = currentHistory
  984. }
  985. currentHistory[previousDay] += int64(delta)
  986. }
  987. // updateFile is bound to the specific `history` in the closure.
  988. func (analyser *BurndownAnalysis) updateFile(
  989. history sparseHistory, currentTime, previousTime, delta int) {
  990. _, currentDay := analyser.unpackPersonWithDay(currentTime)
  991. _, previousDay := analyser.unpackPersonWithDay(previousTime)
  992. currentHistory := history[currentDay]
  993. if currentHistory == nil {
  994. currentHistory = map[int]int64{}
  995. history[currentDay] = currentHistory
  996. }
  997. currentHistory[previousDay] += int64(delta)
  998. }
  999. func (analyser *BurndownAnalysis) updateAuthor(currentTime, previousTime, delta int) {
  1000. previousAuthor, previousDay := analyser.unpackPersonWithDay(previousTime)
  1001. if previousAuthor == identity.AuthorMissing {
  1002. return
  1003. }
  1004. _, currentDay := analyser.unpackPersonWithDay(currentTime)
  1005. history := analyser.peopleHistories[previousAuthor]
  1006. if history == nil {
  1007. history = sparseHistory{}
  1008. analyser.peopleHistories[previousAuthor] = history
  1009. }
  1010. currentHistory := history[currentDay]
  1011. if currentHistory == nil {
  1012. currentHistory = map[int]int64{}
  1013. history[currentDay] = currentHistory
  1014. }
  1015. currentHistory[previousDay] += int64(delta)
  1016. }
  1017. func (analyser *BurndownAnalysis) updateMatrix(currentTime, previousTime, delta int) {
  1018. newAuthor, _ := analyser.unpackPersonWithDay(currentTime)
  1019. oldAuthor, _ := analyser.unpackPersonWithDay(previousTime)
  1020. if oldAuthor == identity.AuthorMissing {
  1021. return
  1022. }
  1023. if newAuthor == oldAuthor && delta > 0 {
  1024. newAuthor = authorSelf
  1025. }
  1026. row := analyser.matrix[oldAuthor]
  1027. if row == nil {
  1028. row = map[int]int64{}
  1029. analyser.matrix[oldAuthor] = row
  1030. }
  1031. cell, exists := row[newAuthor]
  1032. if !exists {
  1033. row[newAuthor] = 0
  1034. cell = 0
  1035. }
  1036. row[newAuthor] = cell + int64(delta)
  1037. }
  1038. func (analyser *BurndownAnalysis) newFile(
  1039. hash plumbing.Hash, name string, author int, day int, size int) (*burndown.File, error) {
  1040. updaters := make([]burndown.Updater, 1)
  1041. updaters[0] = analyser.updateGlobal
  1042. if analyser.TrackFiles {
  1043. history := analyser.fileHistories[name]
  1044. if history == nil {
  1045. // can be not nil if the file was created in a future branch
  1046. history = sparseHistory{}
  1047. }
  1048. analyser.fileHistories[name] = history
  1049. updaters = append(updaters, func(currentTime, previousTime, delta int) {
  1050. analyser.updateFile(history, currentTime, previousTime, delta)
  1051. })
  1052. }
  1053. if analyser.PeopleNumber > 0 {
  1054. updaters = append(updaters, analyser.updateAuthor)
  1055. updaters = append(updaters, analyser.updateMatrix)
  1056. day = analyser.packPersonWithDay(author, day)
  1057. }
  1058. return burndown.NewFile(day, size, analyser.fileAllocator, updaters...), nil
  1059. }
  1060. func (analyser *BurndownAnalysis) handleInsertion(
  1061. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  1062. blob := cache[change.To.TreeEntry.Hash]
  1063. lines, err := blob.CountLines()
  1064. if err != nil {
  1065. // binary
  1066. return nil
  1067. }
  1068. name := change.To.Name
  1069. file, exists := analyser.files[name]
  1070. if exists {
  1071. return fmt.Errorf("file %s already exists", name)
  1072. }
  1073. var hash plumbing.Hash
  1074. if analyser.day != burndown.TreeMergeMark {
  1075. hash = blob.Hash
  1076. }
  1077. file, err = analyser.newFile(hash, name, author, analyser.day, lines)
  1078. analyser.files[name] = file
  1079. if analyser.day == burndown.TreeMergeMark {
  1080. analyser.mergedFiles[name] = true
  1081. }
  1082. return err
  1083. }
  1084. func (analyser *BurndownAnalysis) handleDeletion(
  1085. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  1086. var name string
  1087. if change.To.TreeEntry.Hash != plumbing.ZeroHash {
  1088. // became binary
  1089. name = change.To.Name
  1090. } else {
  1091. name = change.From.Name
  1092. }
  1093. file, exists := analyser.files[name]
  1094. blob := cache[change.From.TreeEntry.Hash]
  1095. lines, err := blob.CountLines()
  1096. if exists && err != nil {
  1097. return fmt.Errorf("previous version of %s unexpectedly became binary", name)
  1098. }
  1099. if !exists {
  1100. return nil
  1101. }
  1102. file.Update(analyser.packPersonWithDay(author, analyser.day), 0, 0, lines)
  1103. file.Delete()
  1104. delete(analyser.files, name)
  1105. delete(analyser.fileHistories, name)
  1106. stack := []string{name}
  1107. for len(stack) > 0 {
  1108. head := stack[len(stack)-1]
  1109. stack = stack[:len(stack)-1]
  1110. analyser.renames[head] = ""
  1111. for key, val := range analyser.renames {
  1112. if val == head {
  1113. stack = append(stack, key)
  1114. }
  1115. }
  1116. }
  1117. if analyser.day == burndown.TreeMergeMark {
  1118. analyser.mergedFiles[name] = false
  1119. }
  1120. return nil
  1121. }
  1122. func (analyser *BurndownAnalysis) handleModification(
  1123. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob,
  1124. diffs map[string]items.FileDiffData) error {
  1125. if analyser.day == burndown.TreeMergeMark {
  1126. analyser.mergedFiles[change.To.Name] = true
  1127. }
  1128. file, exists := analyser.files[change.From.Name]
  1129. if !exists {
  1130. // this indeed may happen
  1131. return analyser.handleInsertion(change, author, cache)
  1132. }
  1133. // possible rename
  1134. if change.To.Name != change.From.Name {
  1135. err := analyser.handleRename(change.From.Name, change.To.Name)
  1136. if err != nil {
  1137. return err
  1138. }
  1139. }
  1140. // Check for binary changes
  1141. blobFrom := cache[change.From.TreeEntry.Hash]
  1142. _, errFrom := blobFrom.CountLines()
  1143. blobTo := cache[change.To.TreeEntry.Hash]
  1144. _, errTo := blobTo.CountLines()
  1145. if errFrom != errTo {
  1146. if errFrom != nil {
  1147. // the file is no longer binary
  1148. return analyser.handleInsertion(change, author, cache)
  1149. }
  1150. // the file became binary
  1151. return analyser.handleDeletion(change, author, cache)
  1152. } else if errFrom != nil {
  1153. // what are we doing here?!
  1154. return nil
  1155. }
  1156. thisDiffs := diffs[change.To.Name]
  1157. if file.Len() != thisDiffs.OldLinesOfCode {
  1158. log.Printf("====TREE====\n%s", file.Dump())
  1159. return fmt.Errorf("%s: internal integrity error src %d != %d %s -> %s",
  1160. change.To.Name, thisDiffs.OldLinesOfCode, file.Len(),
  1161. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1162. }
  1163. // we do not call RunesToDiffLines so the number of lines equals
  1164. // to the rune count
  1165. position := 0
  1166. pending := diffmatchpatch.Diff{Text: ""}
  1167. apply := func(edit diffmatchpatch.Diff) {
  1168. length := utf8.RuneCountInString(edit.Text)
  1169. if edit.Type == diffmatchpatch.DiffInsert {
  1170. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length, 0)
  1171. position += length
  1172. } else {
  1173. file.Update(analyser.packPersonWithDay(author, analyser.day), position, 0, length)
  1174. }
  1175. if analyser.Debug {
  1176. file.Validate()
  1177. }
  1178. }
  1179. for _, edit := range thisDiffs.Diffs {
  1180. dumpBefore := ""
  1181. if analyser.Debug {
  1182. dumpBefore = file.Dump()
  1183. }
  1184. length := utf8.RuneCountInString(edit.Text)
  1185. debugError := func() {
  1186. log.Printf("%s: internal diff error\n", change.To.Name)
  1187. log.Printf("Update(%d, %d, %d (0), %d (0))\n", analyser.day, position,
  1188. length, utf8.RuneCountInString(pending.Text))
  1189. if dumpBefore != "" {
  1190. log.Printf("====TREE BEFORE====\n%s====END====\n", dumpBefore)
  1191. }
  1192. log.Printf("====TREE AFTER====\n%s====END====\n", file.Dump())
  1193. }
  1194. switch edit.Type {
  1195. case diffmatchpatch.DiffEqual:
  1196. if pending.Text != "" {
  1197. apply(pending)
  1198. pending.Text = ""
  1199. }
  1200. position += length
  1201. case diffmatchpatch.DiffInsert:
  1202. if pending.Text != "" {
  1203. if pending.Type == diffmatchpatch.DiffInsert {
  1204. debugError()
  1205. return errors.New("DiffInsert may not appear after DiffInsert")
  1206. }
  1207. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length,
  1208. utf8.RuneCountInString(pending.Text))
  1209. if analyser.Debug {
  1210. file.Validate()
  1211. }
  1212. position += length
  1213. pending.Text = ""
  1214. } else {
  1215. pending = edit
  1216. }
  1217. case diffmatchpatch.DiffDelete:
  1218. if pending.Text != "" {
  1219. debugError()
  1220. return errors.New("DiffDelete may not appear after DiffInsert/DiffDelete")
  1221. }
  1222. pending = edit
  1223. default:
  1224. debugError()
  1225. return fmt.Errorf("diff operation is not supported: %d", edit.Type)
  1226. }
  1227. }
  1228. if pending.Text != "" {
  1229. apply(pending)
  1230. pending.Text = ""
  1231. }
  1232. if file.Len() != thisDiffs.NewLinesOfCode {
  1233. return fmt.Errorf("%s: internal integrity error dst %d != %d %s -> %s",
  1234. change.To.Name, thisDiffs.NewLinesOfCode, file.Len(),
  1235. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1236. }
  1237. return nil
  1238. }
  1239. func (analyser *BurndownAnalysis) handleRename(from, to string) error {
  1240. if from == to {
  1241. return nil
  1242. }
  1243. file, exists := analyser.files[from]
  1244. if !exists {
  1245. return fmt.Errorf("file %s > %s does not exist (files)", from, to)
  1246. }
  1247. delete(analyser.files, from)
  1248. analyser.files[to] = file
  1249. if analyser.day == burndown.TreeMergeMark {
  1250. analyser.mergedFiles[from] = false
  1251. }
  1252. if analyser.TrackFiles {
  1253. history := analyser.fileHistories[from]
  1254. if history == nil {
  1255. var futureRename string
  1256. if _, exists := analyser.renames[""]; exists {
  1257. panic("burndown renames tracking corruption")
  1258. }
  1259. known := map[string]bool{}
  1260. newRename, exists := analyser.renames[from]
  1261. known[from] = true
  1262. for exists {
  1263. futureRename = newRename
  1264. newRename, exists = analyser.renames[futureRename]
  1265. if known[newRename] {
  1266. // infinite cycle
  1267. futureRename = ""
  1268. for key := range known {
  1269. if analyser.fileHistories[key] != nil {
  1270. futureRename = key
  1271. break
  1272. }
  1273. }
  1274. break
  1275. }
  1276. known[futureRename] = true
  1277. }
  1278. // a future branch could have already renamed it and we are retarded
  1279. if futureRename == "" {
  1280. // the file will be deleted in the future, whatever
  1281. history = sparseHistory{}
  1282. } else {
  1283. history = analyser.fileHistories[futureRename]
  1284. if history == nil {
  1285. return fmt.Errorf("file %s > %s (%s) does not exist (histories)",
  1286. from, to, futureRename)
  1287. }
  1288. }
  1289. }
  1290. delete(analyser.fileHistories, from)
  1291. analyser.fileHistories[to] = history
  1292. }
  1293. analyser.renames[from] = to
  1294. return nil
  1295. }
  1296. func (analyser *BurndownAnalysis) groupSparseHistory(
  1297. history sparseHistory, lastDay int) (DenseHistory, int) {
  1298. if len(history) == 0 {
  1299. panic("empty history")
  1300. }
  1301. var days []int
  1302. for day := range history {
  1303. days = append(days, day)
  1304. }
  1305. sort.Ints(days)
  1306. if lastDay >= 0 {
  1307. if days[len(days)-1] < lastDay {
  1308. days = append(days, lastDay)
  1309. } else if days[len(days)-1] > lastDay {
  1310. panic("days corruption")
  1311. }
  1312. } else {
  1313. lastDay = days[len(days)-1]
  1314. }
  1315. // [y][x]
  1316. // y - sampling
  1317. // x - granularity
  1318. samples := lastDay/analyser.Sampling + 1
  1319. bands := lastDay/analyser.Granularity + 1
  1320. result := make(DenseHistory, samples)
  1321. for i := 0; i < bands; i++ {
  1322. result[i] = make([]int64, bands)
  1323. }
  1324. prevsi := 0
  1325. for _, day := range days {
  1326. si := day / analyser.Sampling
  1327. if si > prevsi {
  1328. state := result[prevsi]
  1329. for i := prevsi + 1; i <= si; i++ {
  1330. copy(result[i], state)
  1331. }
  1332. prevsi = si
  1333. }
  1334. sample := result[si]
  1335. for bday, value := range history[day] {
  1336. sample[bday/analyser.Granularity] += value
  1337. }
  1338. }
  1339. return result, lastDay
  1340. }
  1341. func init() {
  1342. core.Registry.Register(&BurndownAnalysis{})
  1343. }