burndown.go 45 KB

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