burndown.go 41 KB

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