burndown.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. people := map[string][3]int{}
  312. for i, pid := range bar1.reversedPeopleDict {
  313. ptrs := people[pid]
  314. ptrs[0] = len(people)
  315. ptrs[1] = i
  316. ptrs[2] = -1
  317. people[pid] = ptrs
  318. }
  319. for i, pid := range bar2.reversedPeopleDict {
  320. ptrs, exists := people[pid]
  321. if !exists {
  322. ptrs[0] = len(people)
  323. ptrs[1] = -1
  324. }
  325. ptrs[2] = i
  326. people[pid] = ptrs
  327. }
  328. merged.reversedPeopleDict = make([]string, len(people))
  329. for name, ptrs := range people {
  330. merged.reversedPeopleDict[ptrs[0]] = name
  331. }
  332. var wg sync.WaitGroup
  333. if len(bar1.GlobalHistory) > 0 || len(bar2.GlobalHistory) > 0 {
  334. wg.Add(1)
  335. go func() {
  336. defer wg.Done()
  337. merged.GlobalHistory = mergeMatrices(
  338. bar1.GlobalHistory, bar2.GlobalHistory,
  339. bar1.granularity, bar1.sampling,
  340. bar2.granularity, bar2.sampling,
  341. c1, c2)
  342. }()
  343. }
  344. if len(bar1.FileHistories) > 0 || len(bar2.FileHistories) > 0 {
  345. merged.FileHistories = map[string][][]int64{}
  346. historyMutex := sync.Mutex{}
  347. for key, fh1 := range bar1.FileHistories {
  348. if fh2, exists := bar2.FileHistories[key]; exists {
  349. wg.Add(1)
  350. go func(fh1, fh2 [][]int64, key string) {
  351. defer wg.Done()
  352. historyMutex.Lock()
  353. defer historyMutex.Unlock()
  354. merged.FileHistories[key] = mergeMatrices(
  355. fh1, fh2, bar1.granularity, bar1.sampling, bar2.granularity, bar2.sampling, c1, c2)
  356. }(fh1, fh2, key)
  357. } else {
  358. historyMutex.Lock()
  359. merged.FileHistories[key] = fh1
  360. historyMutex.Unlock()
  361. }
  362. }
  363. for key, fh2 := range bar2.FileHistories {
  364. if _, exists := bar1.FileHistories[key]; !exists {
  365. historyMutex.Lock()
  366. merged.FileHistories[key] = fh2
  367. historyMutex.Unlock()
  368. }
  369. }
  370. }
  371. if len(merged.reversedPeopleDict) > 0 {
  372. merged.PeopleHistories = make([][][]int64, len(merged.reversedPeopleDict))
  373. for i, key := range merged.reversedPeopleDict {
  374. ptrs := people[key]
  375. if ptrs[1] < 0 {
  376. if len(bar2.PeopleHistories) > 0 {
  377. merged.PeopleHistories[i] = bar2.PeopleHistories[ptrs[2]]
  378. }
  379. } else if ptrs[2] < 0 {
  380. if len(bar1.PeopleHistories) > 0 {
  381. merged.PeopleHistories[i] = bar1.PeopleHistories[ptrs[1]]
  382. }
  383. } else {
  384. wg.Add(1)
  385. go func(i int) {
  386. defer wg.Done()
  387. var m1, m2 [][]int64
  388. if len(bar1.PeopleHistories) > 0 {
  389. m1 = bar1.PeopleHistories[ptrs[1]]
  390. }
  391. if len(bar2.PeopleHistories) > 0 {
  392. m2 = bar2.PeopleHistories[ptrs[2]]
  393. }
  394. merged.PeopleHistories[i] = mergeMatrices(
  395. m1, m2,
  396. bar1.granularity, bar1.sampling,
  397. bar2.granularity, bar2.sampling,
  398. c1, c2,
  399. )
  400. }(i)
  401. }
  402. }
  403. wg.Add(1)
  404. go func() {
  405. defer wg.Done()
  406. if len(bar2.PeopleMatrix) == 0 {
  407. merged.PeopleMatrix = bar1.PeopleMatrix
  408. // extend the matrix in both directions
  409. for i := 0; i < len(merged.PeopleMatrix); i++ {
  410. for j := len(bar1.reversedPeopleDict); j < len(merged.reversedPeopleDict); j++ {
  411. merged.PeopleMatrix[i] = append(merged.PeopleMatrix[i], 0)
  412. }
  413. }
  414. for i := len(bar1.reversedPeopleDict); i < len(merged.reversedPeopleDict); i++ {
  415. merged.PeopleMatrix = append(
  416. merged.PeopleMatrix, make([]int64, len(merged.reversedPeopleDict)+2))
  417. }
  418. } else {
  419. merged.PeopleMatrix = make([][]int64, len(merged.reversedPeopleDict))
  420. for i := range merged.PeopleMatrix {
  421. merged.PeopleMatrix[i] = make([]int64, len(merged.reversedPeopleDict)+2)
  422. }
  423. for i, key := range bar1.reversedPeopleDict {
  424. mi := people[key][0] // index in merged.reversedPeopleDict
  425. copy(merged.PeopleMatrix[mi][:2], bar1.PeopleMatrix[i][:2])
  426. for j, val := range bar1.PeopleMatrix[i][2:] {
  427. merged.PeopleMatrix[mi][2+people[bar1.reversedPeopleDict[j]][0]] = val
  428. }
  429. }
  430. for i, key := range bar2.reversedPeopleDict {
  431. mi := people[key][0] // index in merged.reversedPeopleDict
  432. merged.PeopleMatrix[mi][0] += bar2.PeopleMatrix[i][0]
  433. merged.PeopleMatrix[mi][1] += bar2.PeopleMatrix[i][1]
  434. for j, val := range bar2.PeopleMatrix[i][2:] {
  435. merged.PeopleMatrix[mi][2+people[bar2.reversedPeopleDict[j]][0]] += val
  436. }
  437. }
  438. }
  439. }()
  440. }
  441. wg.Wait()
  442. return merged
  443. }
  444. func mergeMatrices(m1, m2 [][]int64, granularity1, sampling1, granularity2, sampling2 int,
  445. c1, c2 *CommonAnalysisResult) [][]int64 {
  446. commonMerged := *c1
  447. commonMerged.Merge(c2)
  448. var granularity, sampling int
  449. if sampling1 < sampling2 {
  450. sampling = sampling1
  451. } else {
  452. sampling = sampling2
  453. }
  454. if granularity1 < granularity2 {
  455. granularity = granularity1
  456. } else {
  457. granularity = granularity2
  458. }
  459. size := int((commonMerged.EndTime - commonMerged.BeginTime) / (3600 * 24))
  460. daily := make([][]float32, size+granularity)
  461. for i := range daily {
  462. daily[i] = make([]float32, size+sampling)
  463. }
  464. if len(m1) > 0 {
  465. addBurndownMatrix(m1, granularity1, sampling1, daily,
  466. int(c1.BeginTime-commonMerged.BeginTime)/(3600*24))
  467. }
  468. if len(m2) > 0 {
  469. addBurndownMatrix(m2, granularity2, sampling2, daily,
  470. int(c2.BeginTime-commonMerged.BeginTime)/(3600*24))
  471. }
  472. // convert daily to [][]in(t64
  473. result := make([][]int64, (size+sampling-1)/sampling)
  474. for i := range result {
  475. result[i] = make([]int64, (size+granularity-1)/granularity)
  476. sampledIndex := i * sampling
  477. if i == len(result)-1 {
  478. sampledIndex = size - 1
  479. }
  480. for j := 0; j < len(result[i]); j++ {
  481. accum := float32(0)
  482. for k := j * granularity; k < (j+1)*granularity && k < size; k++ {
  483. accum += daily[sampledIndex][k]
  484. }
  485. result[i][j] = int64(accum)
  486. }
  487. }
  488. return result
  489. }
  490. // Explode `matrix` so that it is daily sampled and has daily bands, shift by `offset` days
  491. // and add to the accumulator. `daily` size is square and is guaranteed to fit `matrix` by
  492. // the caller.
  493. // Rows: *at least* len(matrix) * sampling + offset
  494. // Columns: *at least* len(matrix[...]) * granularity + offset
  495. // `matrix` can be sparse, so that the last columns which are equal to 0 are truncated.
  496. func addBurndownMatrix(matrix [][]int64, granularity, sampling int, daily [][]float32, offset int) {
  497. // Determine the maximum number of bands; the actual one may be larger but we do not care
  498. maxCols := 0
  499. for _, row := range matrix {
  500. if maxCols < len(row) {
  501. maxCols = len(row)
  502. }
  503. }
  504. neededRows := len(matrix)*sampling + offset
  505. if len(daily) < neededRows {
  506. panic(fmt.Sprintf("merge bug: too few daily rows: required %d, have %d",
  507. neededRows, len(daily)))
  508. }
  509. if len(daily[0]) < maxCols {
  510. panic(fmt.Sprintf("merge bug: too few daily cols: required %d, have %d",
  511. maxCols, len(daily[0])))
  512. }
  513. for x := 0; x < maxCols; x++ {
  514. for y := 0; y < len(matrix); y++ {
  515. if x*granularity > (y+1)*sampling {
  516. // the future is zeros
  517. continue
  518. }
  519. decay := func(startIndex int, startVal float32) {
  520. k := float32(matrix[y][x]) / startVal // <= 1
  521. scale := float32((y+1)*sampling - startIndex)
  522. for i := x * granularity; i < (x+1)*granularity; i++ {
  523. initial := daily[startIndex-1+offset][i+offset]
  524. for j := startIndex; j < (y+1)*sampling; j++ {
  525. daily[j+offset][i+offset] = initial * (1 + (k-1)*float32(j-startIndex+1)/scale)
  526. }
  527. }
  528. }
  529. raise := func(finishIndex int, finishVal float32) {
  530. var initial float32
  531. if y > 0 {
  532. initial = float32(matrix[y-1][x])
  533. }
  534. startIndex := y * sampling
  535. if startIndex < x*granularity {
  536. startIndex = x * granularity
  537. }
  538. avg := (finishVal - initial) / float32(finishIndex-startIndex)
  539. for j := y * sampling; j < finishIndex; j++ {
  540. for i := startIndex; i <= j; i++ {
  541. daily[j+offset][i+offset] = avg
  542. }
  543. }
  544. // copy [x*g..y*s)
  545. for j := y * sampling; j < finishIndex; j++ {
  546. for i := x * granularity; i < y*sampling; i++ {
  547. daily[j+offset][i+offset] = daily[j-1+offset][i+offset]
  548. }
  549. }
  550. }
  551. if (x+1)*granularity >= (y+1)*sampling {
  552. // x*granularity <= (y+1)*sampling
  553. // 1. x*granularity <= y*sampling
  554. // y*sampling..(y+1)sampling
  555. //
  556. // x+1
  557. // /
  558. // /
  559. // / y+1 -|
  560. // / |
  561. // / y -|
  562. // /
  563. // / x
  564. //
  565. // 2. x*granularity > y*sampling
  566. // x*granularity..(y+1)sampling
  567. //
  568. // x+1
  569. // /
  570. // /
  571. // / y+1 -|
  572. // / |
  573. // / x -|
  574. // /
  575. // / y
  576. if x*granularity <= y*sampling {
  577. raise((y+1)*sampling, float32(matrix[y][x]))
  578. } else {
  579. raise((y+1)*sampling, float32(matrix[y][x]))
  580. avg := float32(matrix[y][x]) / float32((y+1)*sampling-x*granularity)
  581. for j := x * granularity; j < (y+1)*sampling; j++ {
  582. for i := x * granularity; i <= j; i++ {
  583. daily[j+offset][i+offset] = avg
  584. }
  585. }
  586. }
  587. } else if (x+1)*granularity >= y*sampling {
  588. // y*sampling <= (x+1)*granularity < (y+1)sampling
  589. // y*sampling..(x+1)*granularity
  590. // (x+1)*granularity..(y+1)sampling
  591. // x+1
  592. // /\
  593. // / \
  594. // / \
  595. // / y+1
  596. // /
  597. // y
  598. v1 := float32(matrix[y-1][x])
  599. v2 := float32(matrix[y][x])
  600. var peak float32
  601. delta := float32((x+1)*granularity - y*sampling)
  602. var scale float32
  603. var previous float32
  604. if y > 0 && (y-1)*sampling >= x*granularity {
  605. // x*g <= (y-1)*s <= y*s <= (x+1)*g <= (y+1)*s
  606. // |________|.......^
  607. if y > 1 {
  608. previous = float32(matrix[y-2][x])
  609. }
  610. scale = float32(sampling)
  611. } else {
  612. // (y-1)*s < x*g <= y*s <= (x+1)*g <= (y+1)*s
  613. // |______|.......^
  614. if y == 0 {
  615. scale = float32(sampling)
  616. } else {
  617. scale = float32(y*sampling - x*granularity)
  618. }
  619. }
  620. peak = v1 + (v1-previous)/scale*delta
  621. if v2 > peak {
  622. // we need to adjust the peak, it may not be less than the decayed value
  623. if y < len(matrix)-1 {
  624. // y*s <= (x+1)*g <= (y+1)*s < (y+2)*s
  625. // ^.........|_________|
  626. k := (v2 - float32(matrix[y+1][x])) / float32(sampling) // > 0
  627. peak = float32(matrix[y][x]) + k*float32((y+1)*sampling-(x+1)*granularity)
  628. // peak > v2 > v1
  629. } else {
  630. peak = v2
  631. // not enough data to interpolate; this is at least not restricted
  632. }
  633. }
  634. raise((x+1)*granularity, peak)
  635. decay((x+1)*granularity, peak)
  636. } else {
  637. // (x+1)*granularity < y*sampling
  638. // y*sampling..(y+1)sampling
  639. decay(y*sampling, float32(matrix[y-1][x]))
  640. }
  641. }
  642. }
  643. }
  644. func (analyser *BurndownAnalysis) serializeText(result *BurndownResult, writer io.Writer) {
  645. fmt.Fprintln(writer, " granularity:", analyser.Granularity)
  646. fmt.Fprintln(writer, " sampling:", analyser.Sampling)
  647. yaml.PrintMatrix(writer, result.GlobalHistory, 2, "project", true)
  648. if len(result.FileHistories) > 0 {
  649. fmt.Fprintln(writer, " files:")
  650. keys := sortedKeys(result.FileHistories)
  651. for _, key := range keys {
  652. yaml.PrintMatrix(writer, result.FileHistories[key], 4, key, true)
  653. }
  654. }
  655. if len(result.PeopleHistories) > 0 {
  656. fmt.Fprintln(writer, " people_sequence:")
  657. for key := range result.PeopleHistories {
  658. fmt.Fprintln(writer, " - "+yaml.SafeString(result.reversedPeopleDict[key]))
  659. }
  660. fmt.Fprintln(writer, " people:")
  661. for key, val := range result.PeopleHistories {
  662. yaml.PrintMatrix(writer, val, 4, result.reversedPeopleDict[key], true)
  663. }
  664. fmt.Fprintln(writer, " people_interaction: |-")
  665. yaml.PrintMatrix(writer, result.PeopleMatrix, 4, "", false)
  666. }
  667. }
  668. func (analyser *BurndownAnalysis) serializeBinary(result *BurndownResult, writer io.Writer) error {
  669. message := pb.BurndownAnalysisResults{
  670. Granularity: int32(analyser.Granularity),
  671. Sampling: int32(analyser.Sampling),
  672. }
  673. if len(result.GlobalHistory) > 0 {
  674. message.Project = pb.ToBurndownSparseMatrix(result.GlobalHistory, "project")
  675. }
  676. if len(result.FileHistories) > 0 {
  677. message.Files = make([]*pb.BurndownSparseMatrix, len(result.FileHistories))
  678. keys := sortedKeys(result.FileHistories)
  679. i := 0
  680. for _, key := range keys {
  681. message.Files[i] = pb.ToBurndownSparseMatrix(
  682. result.FileHistories[key], key)
  683. i++
  684. }
  685. }
  686. if len(result.PeopleHistories) > 0 {
  687. message.People = make(
  688. []*pb.BurndownSparseMatrix, len(result.PeopleHistories))
  689. for key, val := range result.PeopleHistories {
  690. if len(val) > 0 {
  691. message.People[key] = pb.ToBurndownSparseMatrix(val, result.reversedPeopleDict[key])
  692. }
  693. }
  694. message.PeopleInteraction = pb.DenseToCompressedSparseRowMatrix(result.PeopleMatrix)
  695. }
  696. serialized, err := proto.Marshal(&message)
  697. if err != nil {
  698. return err
  699. }
  700. writer.Write(serialized)
  701. return nil
  702. }
  703. func sortedKeys(m map[string][][]int64) []string {
  704. keys := make([]string, 0, len(m))
  705. for k := range m {
  706. keys = append(keys, k)
  707. }
  708. sort.Strings(keys)
  709. return keys
  710. }
  711. func checkClose(c io.Closer) {
  712. if err := c.Close(); err != nil {
  713. panic(err)
  714. }
  715. }
  716. func (analyser *BurndownAnalysis) packPersonWithDay(person int, day int) int {
  717. if analyser.PeopleNumber == 0 {
  718. return day
  719. }
  720. result := day
  721. result |= person << 14
  722. // This effectively means max 16384 days (>44 years) and (131072 - 2) devs
  723. return result
  724. }
  725. func (analyser *BurndownAnalysis) unpackPersonWithDay(value int) (int, int) {
  726. if analyser.PeopleNumber == 0 {
  727. return MISSING_AUTHOR, value
  728. }
  729. return value >> 14, value & 0x3FFF
  730. }
  731. func (analyser *BurndownAnalysis) updateStatus(
  732. status interface{}, _ int, previous_time_ int, delta int) {
  733. _, previous_time := analyser.unpackPersonWithDay(previous_time_)
  734. status.(map[int]int64)[previous_time] += int64(delta)
  735. }
  736. func (analyser *BurndownAnalysis) updatePeople(people interface{}, _ int, previous_time_ int, delta int) {
  737. old_author, previous_time := analyser.unpackPersonWithDay(previous_time_)
  738. if old_author == MISSING_AUTHOR {
  739. return
  740. }
  741. casted := people.([]map[int]int64)
  742. stats := casted[old_author]
  743. if stats == nil {
  744. stats = map[int]int64{}
  745. casted[old_author] = stats
  746. }
  747. stats[previous_time] += int64(delta)
  748. }
  749. func (analyser *BurndownAnalysis) updateMatrix(
  750. matrix_ interface{}, current_time int, previous_time int, delta int) {
  751. matrix := matrix_.([]map[int]int64)
  752. new_author, _ := analyser.unpackPersonWithDay(current_time)
  753. old_author, _ := analyser.unpackPersonWithDay(previous_time)
  754. if old_author == MISSING_AUTHOR {
  755. return
  756. }
  757. if new_author == old_author && delta > 0 {
  758. new_author = SELF_AUTHOR
  759. }
  760. row := matrix[old_author]
  761. if row == nil {
  762. row = map[int]int64{}
  763. matrix[old_author] = row
  764. }
  765. cell, exists := row[new_author]
  766. if !exists {
  767. row[new_author] = 0
  768. cell = 0
  769. }
  770. row[new_author] = cell + int64(delta)
  771. }
  772. func (analyser *BurndownAnalysis) newFile(
  773. author int, day int, size int, global map[int]int64, people []map[int]int64,
  774. matrix []map[int]int64) *File {
  775. statuses := make([]Status, 1)
  776. statuses[0] = NewStatus(global, analyser.updateStatus)
  777. if analyser.TrackFiles {
  778. statuses = append(statuses, NewStatus(map[int]int64{}, analyser.updateStatus))
  779. }
  780. if analyser.PeopleNumber > 0 {
  781. statuses = append(statuses, NewStatus(people, analyser.updatePeople))
  782. statuses = append(statuses, NewStatus(matrix, analyser.updateMatrix))
  783. day = analyser.packPersonWithDay(author, day)
  784. }
  785. return NewFile(day, size, statuses...)
  786. }
  787. func (analyser *BurndownAnalysis) handleInsertion(
  788. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob) error {
  789. blob := cache[change.To.TreeEntry.Hash]
  790. lines, err := CountLines(blob)
  791. if err != nil {
  792. if err.Error() == "binary" {
  793. return nil
  794. }
  795. return err
  796. }
  797. name := change.To.Name
  798. file, exists := analyser.files[name]
  799. if exists {
  800. return errors.New(fmt.Sprintf("file %s already exists", name))
  801. }
  802. file = analyser.newFile(
  803. author, analyser.day, lines, analyser.globalStatus, analyser.people, analyser.matrix)
  804. analyser.files[name] = file
  805. return nil
  806. }
  807. func (analyser *BurndownAnalysis) handleDeletion(
  808. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob) error {
  809. blob := cache[change.From.TreeEntry.Hash]
  810. lines, err := CountLines(blob)
  811. if err != nil {
  812. if err.Error() == "binary" {
  813. return nil
  814. }
  815. return err
  816. }
  817. name := change.From.Name
  818. file := analyser.files[name]
  819. file.Update(analyser.packPersonWithDay(author, analyser.day), 0, 0, lines)
  820. delete(analyser.files, name)
  821. return nil
  822. }
  823. func (analyser *BurndownAnalysis) handleModification(
  824. change *object.Change, author int, cache map[plumbing.Hash]*object.Blob,
  825. diffs map[string]FileDiffData) error {
  826. file, exists := analyser.files[change.From.Name]
  827. if !exists {
  828. // this indeed may happen
  829. return analyser.handleInsertion(change, author, cache)
  830. }
  831. // possible rename
  832. if change.To.Name != change.From.Name {
  833. err := analyser.handleRename(change.From.Name, change.To.Name)
  834. if err != nil {
  835. return err
  836. }
  837. }
  838. thisDiffs := diffs[change.To.Name]
  839. if file.Len() != thisDiffs.OldLinesOfCode {
  840. fmt.Fprintf(os.Stderr, "====TREE====\n%s", file.Dump())
  841. return errors.New(fmt.Sprintf("%s: internal integrity error src %d != %d %s -> %s",
  842. change.To.Name, thisDiffs.OldLinesOfCode, file.Len(),
  843. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String()))
  844. }
  845. // we do not call RunesToDiffLines so the number of lines equals
  846. // to the rune count
  847. position := 0
  848. pending := diffmatchpatch.Diff{Text: ""}
  849. apply := func(edit diffmatchpatch.Diff) {
  850. length := utf8.RuneCountInString(edit.Text)
  851. if edit.Type == diffmatchpatch.DiffInsert {
  852. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length, 0)
  853. position += length
  854. } else {
  855. file.Update(analyser.packPersonWithDay(author, analyser.day), position, 0, length)
  856. }
  857. if analyser.Debug {
  858. file.Validate()
  859. }
  860. }
  861. for _, edit := range thisDiffs.Diffs {
  862. dump_before := ""
  863. if analyser.Debug {
  864. dump_before = file.Dump()
  865. }
  866. length := utf8.RuneCountInString(edit.Text)
  867. debug_error := func() {
  868. fmt.Fprintf(os.Stderr, "%s: internal diff error\n", change.To.Name)
  869. fmt.Fprintf(os.Stderr, "Update(%d, %d, %d (0), %d (0))\n", analyser.day, position,
  870. length, utf8.RuneCountInString(pending.Text))
  871. if dump_before != "" {
  872. fmt.Fprintf(os.Stderr, "====TREE BEFORE====\n%s====END====\n", dump_before)
  873. }
  874. fmt.Fprintf(os.Stderr, "====TREE AFTER====\n%s====END====\n", file.Dump())
  875. }
  876. switch edit.Type {
  877. case diffmatchpatch.DiffEqual:
  878. if pending.Text != "" {
  879. apply(pending)
  880. pending.Text = ""
  881. }
  882. position += length
  883. case diffmatchpatch.DiffInsert:
  884. if pending.Text != "" {
  885. if pending.Type == diffmatchpatch.DiffInsert {
  886. debug_error()
  887. return errors.New("DiffInsert may not appear after DiffInsert")
  888. }
  889. file.Update(analyser.packPersonWithDay(author, analyser.day), position, length,
  890. utf8.RuneCountInString(pending.Text))
  891. if analyser.Debug {
  892. file.Validate()
  893. }
  894. position += length
  895. pending.Text = ""
  896. } else {
  897. pending = edit
  898. }
  899. case diffmatchpatch.DiffDelete:
  900. if pending.Text != "" {
  901. debug_error()
  902. return errors.New("DiffDelete may not appear after DiffInsert/DiffDelete")
  903. }
  904. pending = edit
  905. default:
  906. debug_error()
  907. return errors.New(fmt.Sprintf("diff operation is not supported: %d", edit.Type))
  908. }
  909. }
  910. if pending.Text != "" {
  911. apply(pending)
  912. pending.Text = ""
  913. }
  914. if file.Len() != thisDiffs.NewLinesOfCode {
  915. return errors.New(fmt.Sprintf("%s: internal integrity error dst %d != %d",
  916. change.To.Name, thisDiffs.NewLinesOfCode, file.Len()))
  917. }
  918. return nil
  919. }
  920. func (analyser *BurndownAnalysis) handleRename(from, to string) error {
  921. file, exists := analyser.files[from]
  922. if !exists {
  923. return errors.New(fmt.Sprintf("file %s does not exist", from))
  924. }
  925. analyser.files[to] = file
  926. delete(analyser.files, from)
  927. return nil
  928. }
  929. func (analyser *BurndownAnalysis) groupStatus() ([]int64, map[string][]int64, [][]int64) {
  930. granularity := analyser.Granularity
  931. if granularity == 0 {
  932. granularity = 1
  933. }
  934. day := analyser.day
  935. day++
  936. adjust := 0
  937. if day%granularity != 0 {
  938. adjust = 1
  939. }
  940. global := make([]int64, day/granularity+adjust)
  941. var group int64
  942. for i := 0; i < day; i++ {
  943. group += analyser.globalStatus[i]
  944. if (i % granularity) == (granularity - 1) {
  945. global[i/granularity] = group
  946. group = 0
  947. }
  948. }
  949. if day%granularity != 0 {
  950. global[len(global)-1] = group
  951. }
  952. locals := make(map[string][]int64)
  953. if analyser.TrackFiles {
  954. for key, file := range analyser.files {
  955. status := make([]int64, day/granularity+adjust)
  956. var group int64
  957. for i := 0; i < day; i++ {
  958. group += file.Status(1).(map[int]int64)[i]
  959. if (i % granularity) == (granularity - 1) {
  960. status[i/granularity] = group
  961. group = 0
  962. }
  963. }
  964. if day%granularity != 0 {
  965. status[len(status)-1] = group
  966. }
  967. locals[key] = status
  968. }
  969. }
  970. peoples := make([][]int64, len(analyser.people))
  971. for key, person := range analyser.people {
  972. status := make([]int64, day/granularity+adjust)
  973. var group int64
  974. for i := 0; i < day; i++ {
  975. group += person[i]
  976. if (i % granularity) == (granularity - 1) {
  977. status[i/granularity] = group
  978. group = 0
  979. }
  980. }
  981. if day%granularity != 0 {
  982. status[len(status)-1] = group
  983. }
  984. peoples[key] = status
  985. }
  986. return global, locals, peoples
  987. }
  988. func (analyser *BurndownAnalysis) updateHistories(
  989. globalStatus []int64, file_statuses map[string][]int64, people_statuses [][]int64, delta int) {
  990. for i := 0; i < delta; i++ {
  991. analyser.globalHistory = append(analyser.globalHistory, globalStatus)
  992. }
  993. to_delete := make([]string, 0)
  994. for key, fh := range analyser.fileHistories {
  995. ls, exists := file_statuses[key]
  996. if !exists {
  997. to_delete = append(to_delete, key)
  998. } else {
  999. for i := 0; i < delta; i++ {
  1000. fh = append(fh, ls)
  1001. }
  1002. analyser.fileHistories[key] = fh
  1003. }
  1004. }
  1005. for _, key := range to_delete {
  1006. delete(analyser.fileHistories, key)
  1007. }
  1008. for key, ls := range file_statuses {
  1009. fh, exists := analyser.fileHistories[key]
  1010. if exists {
  1011. continue
  1012. }
  1013. for i := 0; i < delta; i++ {
  1014. fh = append(fh, ls)
  1015. }
  1016. analyser.fileHistories[key] = fh
  1017. }
  1018. for key, ph := range analyser.peopleHistories {
  1019. ls := people_statuses[key]
  1020. for i := 0; i < delta; i++ {
  1021. ph = append(ph, ls)
  1022. }
  1023. analyser.peopleHistories[key] = ph
  1024. }
  1025. }
  1026. func init() {
  1027. Registry.Register(&BurndownAnalysis{})
  1028. }