burndown.go 32 KB

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