burndown.go 42 KB

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