burndown.go 40 KB

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