analyser.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. package hercules
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "sort"
  10. "time"
  11. "unicode/utf8"
  12. "github.com/sergi/go-diff/diffmatchpatch"
  13. "gopkg.in/src-d/go-git.v4"
  14. "gopkg.in/src-d/go-git.v4/config"
  15. "gopkg.in/src-d/go-git.v4/plumbing"
  16. "gopkg.in/src-d/go-git.v4/plumbing/object"
  17. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  18. )
  19. // Analyser allows to gather the line burndown statistics for a Git repository.
  20. type Analyser struct {
  21. // Repository points to the analysed Git repository struct from go-git.
  22. Repository *git.Repository
  23. // Granularity sets the size of each band - the number of days it spans.
  24. // Smaller values provide better resolution but require more work and eat more
  25. // memory. 30 days is usually enough.
  26. Granularity int
  27. // Sampling sets how detailed is the statistic - the size of the interval in
  28. // days between consecutive measurements. It is usually a good idea to set it
  29. // <= Granularity. Try 15 or 30.
  30. Sampling int
  31. // SimilarityThreshold adjusts the heuristic to determine file renames.
  32. // It has the same units as cgit's -X rename-threshold or -M. Better to
  33. // set it to the default value of 90 (90%).
  34. SimilarityThreshold int
  35. // The number of developers for which to collect the burndown stats. 0 disables it.
  36. PeopleNumber int
  37. // Maps email || name -> developer id.
  38. PeopleDict map[string]int
  39. // Debug activates the debugging mode. Analyse() runs slower in this mode
  40. // but it accurately checks all the intermediate states for invariant
  41. // violations.
  42. Debug bool
  43. // OnProgress is the callback which is invoked in Analyse() to output it's
  44. // progress. The first argument is the number of processed commits and the
  45. // second is the total number of commits.
  46. OnProgress func(int, int)
  47. }
  48. type ProtoMatrix map[int]map[int]int64
  49. func checkClose(c io.Closer) {
  50. if err := c.Close(); err != nil {
  51. panic(err)
  52. }
  53. }
  54. func loc(file *object.Blob) (int, error) {
  55. reader, err := file.Reader()
  56. if err != nil {
  57. panic(err)
  58. }
  59. defer checkClose(reader)
  60. var scanner *bufio.Scanner
  61. buffer := make([]byte, bufio.MaxScanTokenSize)
  62. counter := 0
  63. for scanner == nil || scanner.Err() == bufio.ErrTooLong {
  64. if scanner != nil && !utf8.Valid(scanner.Bytes()) {
  65. return -1, errors.New("binary")
  66. }
  67. scanner = bufio.NewScanner(reader)
  68. scanner.Buffer(buffer, 0)
  69. for scanner.Scan() {
  70. if !utf8.Valid(scanner.Bytes()) {
  71. return -1, errors.New("binary")
  72. }
  73. counter++
  74. }
  75. }
  76. return counter, nil
  77. }
  78. func str(file *object.Blob) string {
  79. reader, err := file.Reader()
  80. if err != nil {
  81. panic(err)
  82. }
  83. defer checkClose(reader)
  84. buf := new(bytes.Buffer)
  85. buf.ReadFrom(reader)
  86. return buf.String()
  87. }
  88. type dummyIO struct {
  89. }
  90. func (dummyIO) Read(p []byte) (int, error) {
  91. return 0, io.EOF
  92. }
  93. func (dummyIO) Write(p []byte) (int, error) {
  94. return len(p), nil
  95. }
  96. func (dummyIO) Close() error {
  97. return nil
  98. }
  99. type dummyEncodedObject struct {
  100. FakeHash plumbing.Hash
  101. }
  102. func (obj dummyEncodedObject) Hash() plumbing.Hash {
  103. return obj.FakeHash
  104. }
  105. func (obj dummyEncodedObject) Type() plumbing.ObjectType {
  106. return plumbing.BlobObject
  107. }
  108. func (obj dummyEncodedObject) SetType(plumbing.ObjectType) {
  109. }
  110. func (obj dummyEncodedObject) Size() int64 {
  111. return 0
  112. }
  113. func (obj dummyEncodedObject) SetSize(int64) {
  114. }
  115. func (obj dummyEncodedObject) Reader() (io.ReadCloser, error) {
  116. return dummyIO{}, nil
  117. }
  118. func (obj dummyEncodedObject) Writer() (io.WriteCloser, error) {
  119. return dummyIO{}, nil
  120. }
  121. func createDummyBlob(hash *plumbing.Hash) (*object.Blob, error) {
  122. return object.DecodeBlob(dummyEncodedObject{*hash})
  123. }
  124. const MISSING_AUTHOR = -1
  125. const SELF_AUTHOR = -2
  126. func (analyser *Analyser) packPersonWithDay(person int, day int) int {
  127. if analyser.PeopleNumber == 0 {
  128. return day
  129. }
  130. result := day
  131. result |= person << 14
  132. // This effectively means max 16384 days (>44 years) and 262144 devs
  133. return result
  134. }
  135. func (analyser *Analyser) unpackPersonWithDay(value int) (int, int) {
  136. if analyser.PeopleNumber == 0 {
  137. return MISSING_AUTHOR, value
  138. }
  139. return value >> 14, value & 0x3FFF
  140. }
  141. func (analyser *Analyser) updateStatus(
  142. status interface{}, _ int, previous_time_ int, delta int) {
  143. _, previous_time := analyser.unpackPersonWithDay(previous_time_)
  144. status.(map[int]int64)[previous_time] += int64(delta)
  145. }
  146. func (analyser *Analyser) updatePeople(people interface{}, _ int, previous_time_ int, delta int) {
  147. old_author, previous_time := analyser.unpackPersonWithDay(previous_time_)
  148. if old_author == MISSING_AUTHOR {
  149. return
  150. }
  151. casted := people.([]map[int]int64)
  152. stats := casted[old_author]
  153. if stats == nil {
  154. stats = map[int]int64{}
  155. casted[old_author] = stats
  156. }
  157. stats[previous_time] += int64(delta)
  158. }
  159. func (analyser *Analyser) updateMatrix(
  160. matrix_ interface{}, current_time int, previous_time int, delta int) {
  161. matrix := matrix_.([]map[int]int64)
  162. new_author, _ := analyser.unpackPersonWithDay(current_time)
  163. old_author, _ := analyser.unpackPersonWithDay(previous_time)
  164. if old_author == MISSING_AUTHOR {
  165. return
  166. }
  167. if new_author == old_author && delta > 0 {
  168. new_author = SELF_AUTHOR
  169. }
  170. row := matrix[old_author]
  171. if row == nil {
  172. row = map[int]int64{}
  173. matrix[old_author] = row
  174. }
  175. cell, exists := row[new_author]
  176. if !exists {
  177. row[new_author] = 0
  178. cell = 0
  179. }
  180. row[new_author] = cell + int64(delta)
  181. }
  182. func (analyser *Analyser) newFile(
  183. author int, day int, size int, global map[int]int64, people []map[int]int64,
  184. matrix []map[int]int64) *File {
  185. if analyser.PeopleNumber == 0 {
  186. return NewFile(day, size, NewStatus(global, analyser.updateStatus),
  187. NewStatus(make(map[int]int64), analyser.updateStatus))
  188. }
  189. return NewFile(analyser.packPersonWithDay(author, day), size,
  190. NewStatus(global, analyser.updateStatus),
  191. NewStatus(make(map[int]int64), analyser.updateStatus),
  192. NewStatus(people, analyser.updatePeople),
  193. NewStatus(matrix, analyser.updateMatrix))
  194. }
  195. func (analyser *Analyser) getAuthorId(signature object.Signature) int {
  196. id, exists := analyser.PeopleDict[signature.Email]
  197. if !exists {
  198. id, exists = analyser.PeopleDict[signature.Name]
  199. if !exists {
  200. id = MISSING_AUTHOR
  201. }
  202. }
  203. return id
  204. }
  205. func (analyser *Analyser) handleInsertion(
  206. change *object.Change, author int, day int, global_status map[int]int64,
  207. files map[string]*File, people []map[int]int64, matrix []map[int]int64,
  208. cache *map[plumbing.Hash]*object.Blob) {
  209. blob := (*cache)[change.To.TreeEntry.Hash]
  210. lines, err := loc(blob)
  211. if err != nil {
  212. return
  213. }
  214. name := change.To.Name
  215. file, exists := files[name]
  216. if exists {
  217. panic(fmt.Sprintf("file %s already exists", name))
  218. }
  219. file = analyser.newFile(author, day, lines, global_status, people, matrix)
  220. files[name] = file
  221. }
  222. func (analyser *Analyser) handleDeletion(
  223. change *object.Change, author int, day int, status map[int]int64, files map[string]*File,
  224. cache *map[plumbing.Hash]*object.Blob) {
  225. blob := (*cache)[change.From.TreeEntry.Hash]
  226. lines, err := loc(blob)
  227. if err != nil {
  228. return
  229. }
  230. name := change.From.Name
  231. file := files[name]
  232. file.Update(analyser.packPersonWithDay(author, day), 0, 0, lines)
  233. delete(files, name)
  234. }
  235. func (analyser *Analyser) handleModification(
  236. change *object.Change, author int, day int, status map[int]int64, files map[string]*File,
  237. people []map[int]int64, matrix []map[int]int64,
  238. cache *map[plumbing.Hash]*object.Blob) {
  239. blob_from := (*cache)[change.From.TreeEntry.Hash]
  240. blob_to := (*cache)[change.To.TreeEntry.Hash]
  241. // we are not validating UTF-8 here because for example
  242. // git/git 4f7770c87ce3c302e1639a7737a6d2531fe4b160 fetch-pack.c is invalid UTF-8
  243. str_from := str(blob_from)
  244. str_to := str(blob_to)
  245. file, exists := files[change.From.Name]
  246. if !exists {
  247. analyser.handleInsertion(change, author, day, status, files, people, matrix, cache)
  248. return
  249. }
  250. // possible rename
  251. if change.To.Name != change.From.Name {
  252. analyser.handleRename(change.From.Name, change.To.Name, files)
  253. }
  254. dmp := diffmatchpatch.New()
  255. src, dst, _ := dmp.DiffLinesToRunes(str_from, str_to)
  256. if file.Len() != len(src) {
  257. fmt.Fprintf(os.Stderr, "====TREE====\n%s", file.Dump())
  258. panic(fmt.Sprintf("%s: internal integrity error src %d != %d %s -> %s",
  259. change.To.Name, len(src), file.Len(),
  260. change.From.TreeEntry.Hash.String(), change.To.TreeEntry.Hash.String()))
  261. }
  262. diffs := dmp.DiffMainRunes(src, dst, false)
  263. // we do not call RunesToDiffLines so the number of lines equals
  264. // to the rune count
  265. position := 0
  266. pending := diffmatchpatch.Diff{Text: ""}
  267. apply := func(edit diffmatchpatch.Diff) {
  268. length := utf8.RuneCountInString(edit.Text)
  269. if edit.Type == diffmatchpatch.DiffInsert {
  270. file.Update(analyser.packPersonWithDay(author, day), position, length, 0)
  271. position += length
  272. } else {
  273. file.Update(analyser.packPersonWithDay(author, day), position, 0, length)
  274. }
  275. if analyser.Debug {
  276. file.Validate()
  277. }
  278. }
  279. for _, edit := range diffs {
  280. dump_before := ""
  281. if analyser.Debug {
  282. dump_before = file.Dump()
  283. }
  284. length := utf8.RuneCountInString(edit.Text)
  285. func() {
  286. defer func() {
  287. r := recover()
  288. if r != nil {
  289. fmt.Fprintf(os.Stderr, "%s: internal diff error\n", change.To.Name)
  290. fmt.Fprintf(os.Stderr, "Update(%d, %d, %d (0), %d (0))\n", day, position,
  291. length, utf8.RuneCountInString(pending.Text))
  292. if dump_before != "" {
  293. fmt.Fprintf(os.Stderr, "====TREE BEFORE====\n%s====END====\n", dump_before)
  294. }
  295. fmt.Fprintf(os.Stderr, "====TREE AFTER====\n%s====END====\n", file.Dump())
  296. panic(r)
  297. }
  298. }()
  299. switch edit.Type {
  300. case diffmatchpatch.DiffEqual:
  301. if pending.Text != "" {
  302. apply(pending)
  303. pending.Text = ""
  304. }
  305. position += length
  306. case diffmatchpatch.DiffInsert:
  307. if pending.Text != "" {
  308. if pending.Type == diffmatchpatch.DiffInsert {
  309. panic("DiffInsert may not appear after DiffInsert")
  310. }
  311. file.Update(analyser.packPersonWithDay(author, day), position, length,
  312. utf8.RuneCountInString(pending.Text))
  313. if analyser.Debug {
  314. file.Validate()
  315. }
  316. position += length
  317. pending.Text = ""
  318. } else {
  319. pending = edit
  320. }
  321. case diffmatchpatch.DiffDelete:
  322. if pending.Text != "" {
  323. panic("DiffDelete may not appear after DiffInsert/DiffDelete")
  324. }
  325. pending = edit
  326. default:
  327. panic(fmt.Sprintf("diff operation is not supported: %d", edit.Type))
  328. }
  329. }()
  330. }
  331. if pending.Text != "" {
  332. apply(pending)
  333. pending.Text = ""
  334. }
  335. if file.Len() != len(dst) {
  336. panic(fmt.Sprintf("%s: internal integrity error dst %d != %d",
  337. change.To.Name, len(dst), file.Len()))
  338. }
  339. }
  340. func (analyser *Analyser) handleRename(from, to string, files map[string]*File) {
  341. file, exists := files[from]
  342. if !exists {
  343. panic(fmt.Sprintf("file %s does not exist", from))
  344. }
  345. files[to] = file
  346. delete(files, from)
  347. }
  348. // Commits returns the critical path in the repository's history. It starts
  349. // from HEAD and traces commits backwards till the root. When it encounters
  350. // a merge (more than one parent), it always chooses the first parent.
  351. func (analyser *Analyser) Commits() []*object.Commit {
  352. result := []*object.Commit{}
  353. repository := analyser.Repository
  354. head, err := repository.Head()
  355. if err != nil {
  356. panic(err)
  357. }
  358. commit, err := repository.CommitObject(head.Hash())
  359. if err != nil {
  360. panic(err)
  361. }
  362. result = append(result, commit)
  363. for ; err != io.EOF; commit, err = commit.Parents().Next() {
  364. if err != nil {
  365. panic(err)
  366. }
  367. result = append(result, commit)
  368. }
  369. // reverse the order
  370. for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
  371. result[i], result[j] = result[j], result[i]
  372. }
  373. return result
  374. }
  375. func (analyser *Analyser) groupStatus(
  376. status map[int]int64,
  377. files map[string]*File,
  378. people []map[int]int64,
  379. day int) ([]int64, map[string][]int64, [][]int64) {
  380. granularity := analyser.Granularity
  381. if granularity == 0 {
  382. granularity = 1
  383. }
  384. day++
  385. adjust := 0
  386. if day%granularity != 0 {
  387. adjust = 1
  388. }
  389. global := make([]int64, day/granularity+adjust)
  390. var group int64
  391. for i := 0; i < day; i++ {
  392. group += status[i]
  393. if (i % granularity) == (granularity - 1) {
  394. global[i/granularity] = group
  395. group = 0
  396. }
  397. }
  398. if day%granularity != 0 {
  399. global[len(global)-1] = group
  400. }
  401. locals := make(map[string][]int64)
  402. for key, file := range files {
  403. status := make([]int64, day/granularity+adjust)
  404. var group int64
  405. for i := 0; i < day; i++ {
  406. group += file.Status(1).(map[int]int64)[i]
  407. if (i % granularity) == (granularity - 1) {
  408. status[i/granularity] = group
  409. group = 0
  410. }
  411. }
  412. if day%granularity != 0 {
  413. status[len(status)-1] = group
  414. }
  415. locals[key] = status
  416. }
  417. peoples := make([][]int64, len(people))
  418. for key, person := range people {
  419. status := make([]int64, day/granularity+adjust)
  420. var group int64
  421. for i := 0; i < day; i++ {
  422. group += person[i]
  423. if (i % granularity) == (granularity - 1) {
  424. status[i/granularity] = group
  425. group = 0
  426. }
  427. }
  428. if day%granularity != 0 {
  429. status[len(status)-1] = group
  430. }
  431. peoples[key] = status
  432. }
  433. return global, locals, peoples
  434. }
  435. func (analyser *Analyser) updateHistories(
  436. global_history [][]int64, global_status []int64,
  437. file_histories map[string][][]int64, file_statuses map[string][]int64,
  438. people_histories [][][]int64, people_statuses [][]int64,
  439. delta int) [][]int64 {
  440. for i := 0; i < delta; i++ {
  441. global_history = append(global_history, global_status)
  442. }
  443. to_delete := make([]string, 0)
  444. for key, fh := range file_histories {
  445. ls, exists := file_statuses[key]
  446. if !exists {
  447. to_delete = append(to_delete, key)
  448. } else {
  449. for i := 0; i < delta; i++ {
  450. fh = append(fh, ls)
  451. }
  452. file_histories[key] = fh
  453. }
  454. }
  455. for _, key := range to_delete {
  456. delete(file_histories, key)
  457. }
  458. for key, ls := range file_statuses {
  459. fh, exists := file_histories[key]
  460. if exists {
  461. continue
  462. }
  463. for i := 0; i < delta; i++ {
  464. fh = append(fh, ls)
  465. }
  466. file_histories[key] = fh
  467. }
  468. for key, ph := range people_histories {
  469. ls := people_statuses[key]
  470. for i := 0; i < delta; i++ {
  471. ph = append(ph, ls)
  472. }
  473. people_histories[key] = ph
  474. }
  475. return global_history
  476. }
  477. type sortableChange struct {
  478. change *object.Change
  479. hash plumbing.Hash
  480. }
  481. type sortableChanges []sortableChange
  482. func (change *sortableChange) Less(other *sortableChange) bool {
  483. for x := 0; x < 20; x++ {
  484. if change.hash[x] < other.hash[x] {
  485. return true
  486. }
  487. }
  488. return false
  489. }
  490. func (slice sortableChanges) Len() int {
  491. return len(slice)
  492. }
  493. func (slice sortableChanges) Less(i, j int) bool {
  494. return slice[i].Less(&slice[j])
  495. }
  496. func (slice sortableChanges) Swap(i, j int) {
  497. slice[i], slice[j] = slice[j], slice[i]
  498. }
  499. type sortableBlob struct {
  500. change *object.Change
  501. size int64
  502. }
  503. type sortableBlobs []sortableBlob
  504. func (change *sortableBlob) Less(other *sortableBlob) bool {
  505. return change.size < other.size
  506. }
  507. func (slice sortableBlobs) Len() int {
  508. return len(slice)
  509. }
  510. func (slice sortableBlobs) Less(i, j int) bool {
  511. return slice[i].Less(&slice[j])
  512. }
  513. func (slice sortableBlobs) Swap(i, j int) {
  514. slice[i], slice[j] = slice[j], slice[i]
  515. }
  516. func (analyser *Analyser) sizesAreClose(size1 int64, size2 int64) bool {
  517. return abs64(size1-size2)*100/max64(1, min64(size1, size2)) <=
  518. int64(100-analyser.SimilarityThreshold)
  519. }
  520. func (analyser *Analyser) blobsAreClose(
  521. blob1 *object.Blob, blob2 *object.Blob) bool {
  522. str_from := str(blob1)
  523. str_to := str(blob2)
  524. dmp := diffmatchpatch.New()
  525. src, dst, _ := dmp.DiffLinesToRunes(str_from, str_to)
  526. diffs := dmp.DiffMainRunes(src, dst, false)
  527. common := 0
  528. for _, edit := range diffs {
  529. if edit.Type == diffmatchpatch.DiffEqual {
  530. common += utf8.RuneCountInString(edit.Text)
  531. }
  532. }
  533. return common*100/max(1, min(len(src), len(dst))) >=
  534. analyser.SimilarityThreshold
  535. }
  536. func (analyser *Analyser) getBlob(entry *object.ChangeEntry, commit *object.Commit) (
  537. *object.Blob, error) {
  538. blob, err := analyser.Repository.BlobObject(entry.TreeEntry.Hash)
  539. if err != nil {
  540. if err.Error() != git.ErrObjectNotFound.Error() {
  541. fmt.Fprintf(os.Stderr, "getBlob(%s)\n", entry.TreeEntry.Hash.String())
  542. return nil, err
  543. }
  544. file, err_modules := commit.File(".gitmodules")
  545. if err_modules != nil {
  546. return nil, err
  547. }
  548. contents, err_modules := file.Contents()
  549. if err_modules != nil {
  550. return nil, err
  551. }
  552. modules := config.NewModules()
  553. err_modules = modules.Unmarshal([]byte(contents))
  554. if err_modules != nil {
  555. return nil, err
  556. }
  557. _, exists := modules.Submodules[entry.Name]
  558. if exists {
  559. // we found that this is a submodule
  560. return createDummyBlob(&entry.TreeEntry.Hash)
  561. }
  562. return nil, err
  563. }
  564. return blob, nil
  565. }
  566. func (analyser *Analyser) cacheBlobs(changes *object.Changes, commit *object.Commit) (
  567. *map[plumbing.Hash]*object.Blob, error) {
  568. cache := make(map[plumbing.Hash]*object.Blob)
  569. for _, change := range *changes {
  570. action, err := change.Action()
  571. if err != nil {
  572. return nil, err
  573. }
  574. switch action {
  575. case merkletrie.Insert:
  576. cache[change.To.TreeEntry.Hash], err = analyser.getBlob(&change.To, commit)
  577. if err != nil {
  578. fmt.Fprintf(os.Stderr, "file to %s\n", change.To.Name)
  579. }
  580. case merkletrie.Delete:
  581. cache[change.From.TreeEntry.Hash], err = analyser.getBlob(&change.From, commit)
  582. if err != nil {
  583. if err.Error() != git.ErrObjectNotFound.Error() {
  584. fmt.Fprintf(os.Stderr, "file from %s\n", change.From.Name)
  585. } else {
  586. cache[change.From.TreeEntry.Hash], err = createDummyBlob(
  587. &change.From.TreeEntry.Hash)
  588. }
  589. }
  590. case merkletrie.Modify:
  591. cache[change.To.TreeEntry.Hash], err = analyser.getBlob(&change.To, commit)
  592. if err != nil {
  593. fmt.Fprintf(os.Stderr, "file to %s\n", change.To.Name)
  594. }
  595. cache[change.From.TreeEntry.Hash], err = analyser.getBlob(&change.From, commit)
  596. if err != nil {
  597. fmt.Fprintf(os.Stderr, "file from %s\n", change.From.Name)
  598. }
  599. default:
  600. panic(fmt.Sprintf("unsupported action: %d", change.Action))
  601. }
  602. if err != nil {
  603. return nil, err
  604. }
  605. }
  606. return &cache, nil
  607. }
  608. func (analyser *Analyser) detectRenames(
  609. changes *object.Changes, cache *map[plumbing.Hash]*object.Blob) object.Changes {
  610. reduced_changes := make(object.Changes, 0, changes.Len())
  611. // Stage 1 - find renames by matching the hashes
  612. // n log(n)
  613. // We sort additions and deletions by hash and then do the single scan along
  614. // both slices.
  615. deleted := make(sortableChanges, 0, changes.Len())
  616. added := make(sortableChanges, 0, changes.Len())
  617. for _, change := range *changes {
  618. action, err := change.Action()
  619. if err != nil {
  620. panic(err)
  621. }
  622. switch action {
  623. case merkletrie.Insert:
  624. added = append(added, sortableChange{change, change.To.TreeEntry.Hash})
  625. case merkletrie.Delete:
  626. deleted = append(deleted, sortableChange{change, change.From.TreeEntry.Hash})
  627. case merkletrie.Modify:
  628. reduced_changes = append(reduced_changes, change)
  629. default:
  630. panic(fmt.Sprintf("unsupported action: %d", change.Action))
  631. }
  632. }
  633. sort.Sort(deleted)
  634. sort.Sort(added)
  635. a := 0
  636. d := 0
  637. still_deleted := make(object.Changes, 0, deleted.Len())
  638. still_added := make(object.Changes, 0, added.Len())
  639. for a < added.Len() && d < deleted.Len() {
  640. if added[a].hash == deleted[d].hash {
  641. reduced_changes = append(
  642. reduced_changes,
  643. &object.Change{From: deleted[d].change.From, To: added[a].change.To})
  644. a++
  645. d++
  646. } else if added[a].Less(&deleted[d]) {
  647. still_added = append(still_added, added[a].change)
  648. a++
  649. } else {
  650. still_deleted = append(still_deleted, deleted[d].change)
  651. d++
  652. }
  653. }
  654. for ; a < added.Len(); a++ {
  655. still_added = append(still_added, added[a].change)
  656. }
  657. for ; d < deleted.Len(); d++ {
  658. still_deleted = append(still_deleted, deleted[d].change)
  659. }
  660. // Stage 2 - apply the similarity threshold
  661. // n^2 but actually linear
  662. // We sort the blobs by size and do the single linear scan.
  663. added_blobs := make(sortableBlobs, 0, still_added.Len())
  664. deleted_blobs := make(sortableBlobs, 0, still_deleted.Len())
  665. for _, change := range still_added {
  666. blob := (*cache)[change.To.TreeEntry.Hash]
  667. added_blobs = append(
  668. added_blobs, sortableBlob{change: change, size: blob.Size})
  669. }
  670. for _, change := range still_deleted {
  671. blob := (*cache)[change.From.TreeEntry.Hash]
  672. deleted_blobs = append(
  673. deleted_blobs, sortableBlob{change: change, size: blob.Size})
  674. }
  675. sort.Sort(added_blobs)
  676. sort.Sort(deleted_blobs)
  677. d_start := 0
  678. for a = 0; a < added_blobs.Len(); a++ {
  679. my_blob := (*cache)[added_blobs[a].change.To.TreeEntry.Hash]
  680. my_size := added_blobs[a].size
  681. for d = d_start; d < deleted_blobs.Len() && !analyser.sizesAreClose(my_size, deleted_blobs[d].size); d++ {
  682. }
  683. d_start = d
  684. found_match := false
  685. for d = d_start; d < deleted_blobs.Len() && analyser.sizesAreClose(my_size, deleted_blobs[d].size); d++ {
  686. if analyser.blobsAreClose(
  687. my_blob, (*cache)[deleted_blobs[d].change.From.TreeEntry.Hash]) {
  688. found_match = true
  689. reduced_changes = append(
  690. reduced_changes,
  691. &object.Change{From: deleted_blobs[d].change.From,
  692. To: added_blobs[a].change.To})
  693. break
  694. }
  695. }
  696. if found_match {
  697. added_blobs = append(added_blobs[:a], added_blobs[a+1:]...)
  698. a--
  699. deleted_blobs = append(deleted_blobs[:d], deleted_blobs[d+1:]...)
  700. }
  701. }
  702. // Stage 3 - we give up, everything left are independent additions and deletions
  703. for _, blob := range added_blobs {
  704. reduced_changes = append(reduced_changes, blob.change)
  705. }
  706. for _, blob := range deleted_blobs {
  707. reduced_changes = append(reduced_changes, blob.change)
  708. }
  709. return reduced_changes
  710. }
  711. // Analyse calculates the line burndown statistics for the bound repository.
  712. //
  713. // commits is a slice with the sequential commit history. It shall start from
  714. // the root (ascending order).
  715. //
  716. // Returns the list of snapshots of the cumulative line edit times and the
  717. // similar lists for every file which is alive in HEAD.
  718. // The number of snapshots (the first dimension >[]<[]int64) depends on
  719. // Analyser.Sampling (the more Sampling, the less the value); the length of
  720. // each snapshot depends on Analyser.Granularity (the more Granularity,
  721. // the less the value).
  722. func (analyser *Analyser) Analyse(commits []*object.Commit) (
  723. [][]int64, map[string][][]int64, [][][]int64, [][]int64) {
  724. sampling := analyser.Sampling
  725. if sampling == 0 {
  726. sampling = 1
  727. }
  728. onProgress := analyser.OnProgress
  729. if onProgress == nil {
  730. onProgress = func(int, int) {}
  731. }
  732. if analyser.SimilarityThreshold < 0 || analyser.SimilarityThreshold > 100 {
  733. panic("hercules.Analyser: an invalid SimilarityThreshold was specified")
  734. }
  735. // current daily alive number of lines; key is the number of days from the
  736. // beginning of the history
  737. global_status := map[int]int64{}
  738. // weekly snapshots of status
  739. global_history := [][]int64{}
  740. // weekly snapshots of each file's status
  741. file_histories := map[string][][]int64{}
  742. // weekly snapshots of each person's status
  743. people_histories := make([][][]int64, analyser.PeopleNumber)
  744. // mapping <file path> -> hercules.File
  745. files := map[string]*File{}
  746. // Mutual deletions and self insertions
  747. matrix := make([]map[int]int64, analyser.PeopleNumber)
  748. // People's individual time stats
  749. people := make([]map[int]int64, analyser.PeopleNumber)
  750. var day0 time.Time // will be initialized in the first iteration
  751. var prev_tree *object.Tree = nil
  752. var day, prev_day int
  753. for index, commit := range commits {
  754. onProgress(index, len(commits))
  755. tree, err := commit.Tree()
  756. if err != nil {
  757. panic(err)
  758. }
  759. author := analyser.getAuthorId(commit.Author)
  760. if index == 0 {
  761. // first iteration - initialize the file objects from the tree
  762. day0 = commit.Author.When
  763. func() {
  764. file_iter := tree.Files()
  765. defer file_iter.Close()
  766. for {
  767. file, err := file_iter.Next()
  768. if err != nil {
  769. if err == io.EOF {
  770. break
  771. }
  772. panic(err)
  773. }
  774. lines, err := loc(&file.Blob)
  775. if err == nil {
  776. files[file.Name] = analyser.newFile(author, 0, lines, global_status, people, matrix)
  777. }
  778. }
  779. }()
  780. } else {
  781. day = int(commit.Author.When.Sub(day0).Hours() / 24)
  782. if day < prev_day {
  783. // rebase makes miracles
  784. day = prev_day
  785. }
  786. delta := (day / sampling) - (prev_day / sampling)
  787. if delta > 0 {
  788. prev_day = day
  789. gs, fss, pss := analyser.groupStatus(global_status, files, people, day)
  790. global_history = analyser.updateHistories(
  791. global_history, gs, file_histories, fss, people_histories, pss, delta)
  792. }
  793. tree_diff, err := object.DiffTree(prev_tree, tree)
  794. if err != nil {
  795. fmt.Fprintf(os.Stderr, "commit #%d %s\n", index, commit.Hash.String())
  796. panic(err)
  797. }
  798. cache, err := analyser.cacheBlobs(&tree_diff, commit)
  799. if err != nil {
  800. fmt.Fprintf(os.Stderr, "commit #%d %s\n", index, commit.Hash.String())
  801. panic(err)
  802. }
  803. tree_diff = analyser.detectRenames(&tree_diff, cache)
  804. for _, change := range tree_diff {
  805. action, err := change.Action()
  806. if err != nil {
  807. fmt.Fprintf(os.Stderr, "commit #%d %s\n", index, commit.Hash.String())
  808. panic(err)
  809. }
  810. switch action {
  811. case merkletrie.Insert:
  812. analyser.handleInsertion(change, author, day, global_status, files, people, matrix, cache)
  813. case merkletrie.Delete:
  814. analyser.handleDeletion(change, author, day, global_status, files, cache)
  815. case merkletrie.Modify:
  816. func() {
  817. defer func() {
  818. r := recover()
  819. if r != nil {
  820. fmt.Fprintf(os.Stderr, "#%d - %s: modification error\n",
  821. index, commit.Hash.String())
  822. panic(r)
  823. }
  824. }()
  825. analyser.handleModification(change, author, day, global_status, files, people, matrix, cache)
  826. }()
  827. }
  828. }
  829. }
  830. prev_tree = tree
  831. }
  832. gs, fss, pss := analyser.groupStatus(global_status, files, people, day)
  833. global_history = analyser.updateHistories(
  834. global_history, gs, file_histories, fss, people_histories, pss, 1)
  835. for key, statuses := range file_histories {
  836. if len(statuses) == len(global_history) {
  837. continue
  838. }
  839. padding := make([][]int64, len(global_history)-len(statuses))
  840. for i := range padding {
  841. padding[i] = make([]int64, len(global_status))
  842. }
  843. file_histories[key] = append(padding, statuses...)
  844. }
  845. people_matrix := make([][]int64, analyser.PeopleNumber)
  846. for i, row := range matrix {
  847. mrow := make([]int64, analyser.PeopleNumber+2)
  848. people_matrix[i] = mrow
  849. for key, val := range row {
  850. mrow[key+2] = val
  851. }
  852. }
  853. return global_history, file_histories, people_histories, people_matrix
  854. }