burndown.go 43 KB

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