burndown.go 36 KB

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