analyser.go 21 KB

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