burndown.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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.v5/internal/burndown"
  17. "gopkg.in/src-d/hercules.v5/internal/core"
  18. "gopkg.in/src-d/hercules.v5/internal/pb"
  19. items "gopkg.in/src-d/hercules.v5/internal/plumbing"
  20. "gopkg.in/src-d/hercules.v5/internal/plumbing/identity"
  21. "gopkg.in/src-d/hercules.v5/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]*items.CachedBlob)
  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]*items.CachedBlob) error {
  958. blob := cache[change.To.TreeEntry.Hash]
  959. lines, err := blob.CountLines()
  960. if err != nil {
  961. // binary
  962. return nil
  963. }
  964. name := change.To.Name
  965. file, exists := analyser.files[name]
  966. if exists {
  967. println("\n", analyser, "error")
  968. return fmt.Errorf("file %s already exists", name)
  969. }
  970. var hash plumbing.Hash
  971. if analyser.day != burndown.TreeMergeMark {
  972. hash = blob.Hash
  973. }
  974. file, err = analyser.newFile(hash, name, author, analyser.day, lines)
  975. analyser.files[name] = file
  976. if analyser.day == burndown.TreeMergeMark {
  977. analyser.mergedFiles[name] = true
  978. }
  979. return err
  980. }
  981. func (analyser *BurndownAnalysis) handleDeletion(
  982. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob) error {
  983. name := change.From.Name
  984. file, exists := analyser.files[name]
  985. blob := cache[change.From.TreeEntry.Hash]
  986. lines, err := blob.CountLines()
  987. if exists && err != nil {
  988. return fmt.Errorf("file %s unexpectedly became binary", name)
  989. }
  990. if !exists {
  991. return nil
  992. }
  993. file.Update(analyser.packPersonWithDay(author, analyser.day), 0, 0, lines)
  994. delete(analyser.files, name)
  995. delete(analyser.fileHistories, name)
  996. analyser.renames[name] = ""
  997. if analyser.day == burndown.TreeMergeMark {
  998. analyser.mergedFiles[name] = false
  999. }
  1000. return nil
  1001. }
  1002. func (analyser *BurndownAnalysis) handleModification(
  1003. change *object.Change, author int, cache map[plumbing.Hash]*items.CachedBlob,
  1004. diffs map[string]items.FileDiffData) error {
  1005. if analyser.day == burndown.TreeMergeMark {
  1006. analyser.mergedFiles[change.To.Name] = true
  1007. }
  1008. file, exists := analyser.files[change.From.Name]
  1009. if !exists {
  1010. // this indeed may happen
  1011. return analyser.handleInsertion(change, author, cache)
  1012. }
  1013. // possible rename
  1014. if change.To.Name != change.From.Name {
  1015. err := analyser.handleRename(change.From.Name, change.To.Name)
  1016. if err != nil {
  1017. return err
  1018. }
  1019. }
  1020. // Check for binary changes
  1021. blobFrom := cache[change.From.TreeEntry.Hash]
  1022. _, errFrom := blobFrom.CountLines()
  1023. blobTo := cache[change.To.TreeEntry.Hash]
  1024. _, errTo := blobTo.CountLines()
  1025. if errFrom != errTo {
  1026. if errFrom != nil {
  1027. // the file is no longer binary
  1028. return analyser.handleInsertion(change, author, cache)
  1029. }
  1030. // the file became binary
  1031. return analyser.handleDeletion(change, author, cache)
  1032. } else if errFrom != nil {
  1033. // what are we doing here?!
  1034. return nil
  1035. }
  1036. thisDiffs := diffs[change.To.Name]
  1037. if file.Len() != thisDiffs.OldLinesOfCode {
  1038. log.Printf("====TREE====\n%s", file.Dump())
  1039. return fmt.Errorf("%s: internal integrity error src %d != %d %s -> %s",
  1040. change.To.Name, thisDiffs.OldLinesOfCode, file.Len(),
  1041. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1042. }
  1043. // we do not call RunesToDiffLines so the number of lines equals
  1044. // to the rune count
  1045. position := 0
  1046. pending := diffmatchpatch.Diff{Text: ""}
  1047. apply := func(edit diffmatchpatch.Diff) {
  1048. length := utf8.RuneCountInString(edit.Text)
  1049. if edit.Type == diffmatchpatch.DiffInsert {
  1050. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length, 0)
  1051. position += length
  1052. } else {
  1053. file.Update(analyser.packPersonWithDay(author, analyser.day), position, 0, length)
  1054. }
  1055. if analyser.Debug {
  1056. file.Validate()
  1057. }
  1058. }
  1059. for _, edit := range thisDiffs.Diffs {
  1060. dumpBefore := ""
  1061. if analyser.Debug {
  1062. dumpBefore = file.Dump()
  1063. }
  1064. length := utf8.RuneCountInString(edit.Text)
  1065. debugError := func() {
  1066. log.Printf("%s: internal diff error\n", change.To.Name)
  1067. log.Printf("Update(%d, %d, %d (0), %d (0))\n", analyser.day, position,
  1068. length, utf8.RuneCountInString(pending.Text))
  1069. if dumpBefore != "" {
  1070. log.Printf("====TREE BEFORE====\n%s====END====\n", dumpBefore)
  1071. }
  1072. log.Printf("====TREE AFTER====\n%s====END====\n", file.Dump())
  1073. }
  1074. switch edit.Type {
  1075. case diffmatchpatch.DiffEqual:
  1076. if pending.Text != "" {
  1077. apply(pending)
  1078. pending.Text = ""
  1079. }
  1080. position += length
  1081. case diffmatchpatch.DiffInsert:
  1082. if pending.Text != "" {
  1083. if pending.Type == diffmatchpatch.DiffInsert {
  1084. debugError()
  1085. return errors.New("DiffInsert may not appear after DiffInsert")
  1086. }
  1087. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length,
  1088. utf8.RuneCountInString(pending.Text))
  1089. if analyser.Debug {
  1090. file.Validate()
  1091. }
  1092. position += length
  1093. pending.Text = ""
  1094. } else {
  1095. pending = edit
  1096. }
  1097. case diffmatchpatch.DiffDelete:
  1098. if pending.Text != "" {
  1099. debugError()
  1100. return errors.New("DiffDelete may not appear after DiffInsert/DiffDelete")
  1101. }
  1102. pending = edit
  1103. default:
  1104. debugError()
  1105. return fmt.Errorf("diff operation is not supported: %d", edit.Type)
  1106. }
  1107. }
  1108. if pending.Text != "" {
  1109. apply(pending)
  1110. pending.Text = ""
  1111. }
  1112. if file.Len() != thisDiffs.NewLinesOfCode {
  1113. return fmt.Errorf("%s: internal integrity error dst %d != %d %s -> %s",
  1114. change.To.Name, thisDiffs.NewLinesOfCode, file.Len(),
  1115. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String())
  1116. }
  1117. return nil
  1118. }
  1119. func (analyser *BurndownAnalysis) handleRename(from, to string) error {
  1120. if from == to {
  1121. return nil
  1122. }
  1123. file, exists := analyser.files[from]
  1124. if !exists {
  1125. return fmt.Errorf("file %s > %s does not exist (files)", from, to)
  1126. }
  1127. analyser.files[to] = file
  1128. delete(analyser.files, from)
  1129. if analyser.day == burndown.TreeMergeMark {
  1130. analyser.mergedFiles[from] = false
  1131. }
  1132. if analyser.TrackFiles {
  1133. history := analyser.fileHistories[from]
  1134. if history == nil {
  1135. // a future branch could have already renamed it and we are retarded
  1136. futureRename, exists := analyser.renames[from]
  1137. if futureRename == "" && exists {
  1138. // the file will be deleted in the future, whatever
  1139. history = sparseHistory{}
  1140. } else {
  1141. history = analyser.fileHistories[futureRename]
  1142. if history == nil {
  1143. return fmt.Errorf("file %s > %s does not exist (histories)", from, to)
  1144. }
  1145. }
  1146. }
  1147. analyser.fileHistories[to] = history
  1148. delete(analyser.fileHistories, from)
  1149. }
  1150. analyser.renames[from] = to
  1151. return nil
  1152. }
  1153. func (analyser *BurndownAnalysis) groupSparseHistory(
  1154. history sparseHistory, lastDay int) (DenseHistory, int) {
  1155. if len(history) == 0 {
  1156. panic("empty history")
  1157. }
  1158. var days []int
  1159. for day := range history {
  1160. days = append(days, day)
  1161. }
  1162. sort.Ints(days)
  1163. if lastDay >= 0 {
  1164. if days[len(days)-1] < lastDay {
  1165. days = append(days, lastDay)
  1166. } else if days[len(days)-1] > lastDay {
  1167. panic("days corruption")
  1168. }
  1169. } else {
  1170. lastDay = days[len(days)-1]
  1171. }
  1172. // [y][x]
  1173. // y - sampling
  1174. // x - granularity
  1175. samples := lastDay/analyser.Sampling + 1
  1176. bands := lastDay/analyser.Granularity + 1
  1177. result := make(DenseHistory, samples)
  1178. for i := 0; i < bands; i++ {
  1179. result[i] = make([]int64, bands)
  1180. }
  1181. prevsi := 0
  1182. for _, day := range days {
  1183. si := day / analyser.Sampling
  1184. if si > prevsi {
  1185. state := result[prevsi]
  1186. for i := prevsi + 1; i <= si; i++ {
  1187. copy(result[i], state)
  1188. }
  1189. prevsi = si
  1190. }
  1191. sample := result[si]
  1192. for bday, value := range history[day] {
  1193. sample[bday/analyser.Granularity] += value
  1194. }
  1195. }
  1196. return result, lastDay
  1197. }
  1198. func init() {
  1199. core.Registry.Register(&BurndownAnalysis{})
  1200. }