burndown.go 40 KB

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