analyser.go 26 KB

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