burndown.go 32 KB

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