burndown.go 32 KB

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