burndown.go 32 KB

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