burndown.go 34 KB

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