burndown.go 34 KB

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