forks.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. package core
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "reflect"
  7. "sort"
  8. "gopkg.in/src-d/go-git.v4/plumbing"
  9. "gopkg.in/src-d/go-git.v4/plumbing/object"
  10. "gopkg.in/src-d/hercules.v7/internal/toposort"
  11. )
  12. // OneShotMergeProcessor provides the convenience method to consume merges only once.
  13. type OneShotMergeProcessor struct {
  14. merges map[plumbing.Hash]bool
  15. }
  16. // Initialize resets OneShotMergeProcessor.
  17. func (proc *OneShotMergeProcessor) Initialize() {
  18. proc.merges = map[plumbing.Hash]bool{}
  19. }
  20. // ShouldConsumeCommit returns true on regular commits. It also returns true upon
  21. // the first occurrence of a particular merge commit.
  22. func (proc *OneShotMergeProcessor) ShouldConsumeCommit(deps map[string]interface{}) bool {
  23. commit := deps[DependencyCommit].(*object.Commit)
  24. if commit.NumParents() <= 1 {
  25. return true
  26. }
  27. if !proc.merges[commit.Hash] {
  28. proc.merges[commit.Hash] = true
  29. return true
  30. }
  31. return false
  32. }
  33. // NoopMerger provides an empty Merge() method suitable for PipelineItem.
  34. type NoopMerger struct {
  35. }
  36. // Merge does nothing.
  37. func (merger *NoopMerger) Merge(branches []PipelineItem) {
  38. // no-op
  39. }
  40. // ForkSamePipelineItem clones items by referencing the same origin.
  41. func ForkSamePipelineItem(origin PipelineItem, n int) []PipelineItem {
  42. clones := make([]PipelineItem, n)
  43. for i := 0; i < n; i++ {
  44. clones[i] = origin
  45. }
  46. return clones
  47. }
  48. // ForkCopyPipelineItem clones items by copying them by value from the origin.
  49. func ForkCopyPipelineItem(origin PipelineItem, n int) []PipelineItem {
  50. originValue := reflect.Indirect(reflect.ValueOf(origin))
  51. originType := originValue.Type()
  52. clones := make([]PipelineItem, n)
  53. for i := 0; i < n; i++ {
  54. cloneValue := reflect.New(originType).Elem()
  55. cloneValue.Set(originValue)
  56. clones[i] = cloneValue.Addr().Interface().(PipelineItem)
  57. }
  58. return clones
  59. }
  60. const (
  61. // runActionCommit corresponds to a regular commit
  62. runActionCommit = 0
  63. // runActionFork splits a branch into several parts
  64. runActionFork = iota
  65. // runActionMerge merges several branches together
  66. runActionMerge = iota
  67. // runActionEmerge starts a root branch
  68. runActionEmerge = iota
  69. // runActionDelete removes the branch as it is no longer needed
  70. runActionDelete = iota
  71. // runActionHibernate preserves the items in the branch
  72. runActionHibernate = iota
  73. // runActionBoot does the opposite to runActionHibernate - recovers the original memory
  74. runActionBoot = iota
  75. // rootBranchIndex is the minimum branch index in the plan
  76. rootBranchIndex = 1
  77. )
  78. // planPrintFunc is used to print the execution plan in prepareRunPlan().
  79. var planPrintFunc = func(args ...interface{}) {
  80. fmt.Fprintln(os.Stderr, args...)
  81. }
  82. type runAction struct {
  83. Action int
  84. Commit *object.Commit
  85. Items []int
  86. }
  87. type orderer = func(reverse, direction bool) []string
  88. func cloneItems(origin []PipelineItem, n int) [][]PipelineItem {
  89. clones := make([][]PipelineItem, n)
  90. for j := 0; j < n; j++ {
  91. clones[j] = make([]PipelineItem, len(origin))
  92. }
  93. for i, item := range origin {
  94. itemClones := item.Fork(n)
  95. for j := 0; j < n; j++ {
  96. clones[j][i] = itemClones[j]
  97. }
  98. }
  99. return clones
  100. }
  101. func mergeItems(branches [][]PipelineItem) {
  102. buffer := make([]PipelineItem, len(branches)-1)
  103. for i, item := range branches[0] {
  104. for j := 0; j < len(branches)-1; j++ {
  105. buffer[j] = branches[j+1][i]
  106. }
  107. item.Merge(buffer)
  108. }
  109. }
  110. // getMasterBranch returns the branch with the smallest index.
  111. func getMasterBranch(branches map[int][]PipelineItem) []PipelineItem {
  112. minKey := 1 << 31
  113. var minVal []PipelineItem
  114. for key, val := range branches {
  115. if key < minKey {
  116. minKey = key
  117. minVal = val
  118. }
  119. }
  120. return minVal
  121. }
  122. // prepareRunPlan schedules the actions for Pipeline.Run().
  123. func prepareRunPlan(commits []*object.Commit, hibernationDistance int,
  124. printResult bool) []runAction {
  125. hashes, dag := buildDag(commits)
  126. leaveRootComponent(hashes, dag)
  127. mergedDag, mergedSeq := mergeDag(hashes, dag)
  128. orderNodes := bindOrderNodes(mergedDag)
  129. collapseFastForwards(orderNodes, hashes, mergedDag, dag, mergedSeq)
  130. /*fmt.Printf("digraph Hercules {\n")
  131. for i, c := range orderNodes(false, false) {
  132. commit := hashes[c]
  133. fmt.Printf(" \"%s\"[label=\"[%d] %s\"]\n", commit.Hash.String(), i, commit.Hash.String()[:6])
  134. for _, child := range mergedDag[commit.Hash] {
  135. fmt.Printf(" \"%s\" -> \"%s\"\n", commit.Hash.String(), child.Hash.String())
  136. }
  137. }
  138. fmt.Printf("}\n")*/
  139. plan := generatePlan(orderNodes, hashes, mergedDag, dag, mergedSeq)
  140. plan = collectGarbage(plan)
  141. if hibernationDistance > 0 {
  142. plan = insertHibernateBoot(plan, hibernationDistance)
  143. }
  144. if printResult {
  145. for _, p := range plan {
  146. printAction(p)
  147. }
  148. }
  149. return plan
  150. }
  151. // printAction prints the specified action to stderr.
  152. func printAction(p runAction) {
  153. firstItem := p.Items[0]
  154. switch p.Action {
  155. case runActionCommit:
  156. planPrintFunc("C", firstItem, p.Commit.Hash.String())
  157. case runActionFork:
  158. planPrintFunc("F", p.Items)
  159. case runActionMerge:
  160. planPrintFunc("M", p.Items)
  161. case runActionEmerge:
  162. planPrintFunc("E", p.Items)
  163. case runActionDelete:
  164. planPrintFunc("D", p.Items)
  165. case runActionHibernate:
  166. planPrintFunc("H", firstItem)
  167. case runActionBoot:
  168. planPrintFunc("B", firstItem)
  169. }
  170. }
  171. // getCommitParents returns the list of *unique* commit parents.
  172. // Yes, it *is* possible to have several identical parents, and Hercules used to crash because of that.
  173. func getCommitParents(commit *object.Commit) []plumbing.Hash {
  174. result := make([]plumbing.Hash, 0, len(commit.ParentHashes))
  175. var parents map[plumbing.Hash]bool
  176. if len(commit.ParentHashes) > 1 {
  177. parents = map[plumbing.Hash]bool{}
  178. }
  179. for _, parent := range commit.ParentHashes {
  180. if _, exists := parents[parent]; !exists {
  181. if parents != nil {
  182. parents[parent] = true
  183. }
  184. result = append(result, parent)
  185. }
  186. }
  187. return result
  188. }
  189. // buildDag generates the raw commit DAG and the commit hash map.
  190. func buildDag(commits []*object.Commit) (
  191. map[string]*object.Commit, map[plumbing.Hash][]*object.Commit) {
  192. hashes := map[string]*object.Commit{}
  193. for _, commit := range commits {
  194. hashes[commit.Hash.String()] = commit
  195. }
  196. dag := map[plumbing.Hash][]*object.Commit{}
  197. for _, commit := range commits {
  198. if _, exists := dag[commit.Hash]; !exists {
  199. dag[commit.Hash] = make([]*object.Commit, 0, 1)
  200. }
  201. for _, parent := range getCommitParents(commit) {
  202. if _, exists := hashes[parent.String()]; !exists {
  203. continue
  204. }
  205. children := dag[parent]
  206. if children == nil {
  207. children = make([]*object.Commit, 0, 1)
  208. }
  209. dag[parent] = append(children, commit)
  210. }
  211. }
  212. return hashes, dag
  213. }
  214. // leaveRootComponent runs connected components analysis and throws away everything
  215. // but the part which grows from the root.
  216. func leaveRootComponent(
  217. hashes map[string]*object.Commit,
  218. dag map[plumbing.Hash][]*object.Commit) {
  219. visited := map[plumbing.Hash]bool{}
  220. var sets [][]plumbing.Hash
  221. for key := range dag {
  222. if visited[key] {
  223. continue
  224. }
  225. var set []plumbing.Hash
  226. for queue := []plumbing.Hash{key}; len(queue) > 0; {
  227. head := queue[len(queue)-1]
  228. queue = queue[:len(queue)-1]
  229. if visited[head] {
  230. continue
  231. }
  232. set = append(set, head)
  233. visited[head] = true
  234. for _, c := range dag[head] {
  235. if !visited[c.Hash] {
  236. queue = append(queue, c.Hash)
  237. }
  238. }
  239. if commit, exists := hashes[head.String()]; exists {
  240. for _, p := range getCommitParents(commit) {
  241. if !visited[p] {
  242. if _, exists := hashes[p.String()]; exists {
  243. queue = append(queue, p)
  244. }
  245. }
  246. }
  247. }
  248. }
  249. sets = append(sets, set)
  250. }
  251. if len(sets) > 1 {
  252. maxlen := 0
  253. maxind := -1
  254. for i, set := range sets {
  255. if len(set) > maxlen {
  256. maxlen = len(set)
  257. maxind = i
  258. }
  259. }
  260. for i, set := range sets {
  261. if i == maxind {
  262. continue
  263. }
  264. for _, h := range set {
  265. log.Printf("warning: dropped %s from the analysis - disjoint", h.String())
  266. delete(dag, h)
  267. delete(hashes, h.String())
  268. }
  269. }
  270. }
  271. }
  272. // bindOrderNodes returns curried "orderNodes" function.
  273. func bindOrderNodes(mergedDag map[plumbing.Hash][]*object.Commit) orderer {
  274. return func(reverse, direction bool) []string {
  275. graph := toposort.NewGraph()
  276. keys := make([]plumbing.Hash, 0, len(mergedDag))
  277. for key := range mergedDag {
  278. keys = append(keys, key)
  279. }
  280. sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
  281. for _, key := range keys {
  282. graph.AddNode(key.String())
  283. }
  284. for _, key := range keys {
  285. children := mergedDag[key]
  286. sort.Slice(children, func(i, j int) bool {
  287. return children[i].Hash.String() < children[j].Hash.String()
  288. })
  289. for _, c := range children {
  290. if !direction {
  291. graph.AddEdge(key.String(), c.Hash.String())
  292. } else {
  293. graph.AddEdge(c.Hash.String(), key.String())
  294. }
  295. }
  296. }
  297. order, ok := graph.Toposort()
  298. if !ok {
  299. // should never happen
  300. panic("Could not topologically sort the DAG of commits")
  301. }
  302. if reverse != direction {
  303. // one day this must appear in the standard library...
  304. for i, j := 0, len(order)-1; i < len(order)/2; i, j = i+1, j-1 {
  305. order[i], order[j] = order[j], order[i]
  306. }
  307. }
  308. return order
  309. }
  310. }
  311. // inverts `dag`
  312. func buildParents(dag map[plumbing.Hash][]*object.Commit) map[plumbing.Hash]map[plumbing.Hash]bool {
  313. parents := map[plumbing.Hash]map[plumbing.Hash]bool{}
  314. for key, vals := range dag {
  315. for _, val := range vals {
  316. myps := parents[val.Hash]
  317. if myps == nil {
  318. myps = map[plumbing.Hash]bool{}
  319. parents[val.Hash] = myps
  320. }
  321. myps[key] = true
  322. }
  323. }
  324. return parents
  325. }
  326. // mergeDag turns sequences of consecutive commits into single nodes.
  327. func mergeDag(
  328. hashes map[string]*object.Commit,
  329. dag map[plumbing.Hash][]*object.Commit) (
  330. mergedDag, mergedSeq map[plumbing.Hash][]*object.Commit) {
  331. parents := buildParents(dag)
  332. mergedDag = map[plumbing.Hash][]*object.Commit{}
  333. mergedSeq = map[plumbing.Hash][]*object.Commit{}
  334. visited := map[plumbing.Hash]bool{}
  335. for head := range dag {
  336. if visited[head] {
  337. continue
  338. }
  339. c := head
  340. for true {
  341. nextParents := parents[c]
  342. var next plumbing.Hash
  343. for p := range nextParents {
  344. next = p
  345. break
  346. }
  347. if len(nextParents) != 1 || len(dag[next]) != 1 {
  348. break
  349. }
  350. c = next
  351. }
  352. head = c
  353. var seq []*object.Commit
  354. for true {
  355. visited[c] = true
  356. seq = append(seq, hashes[c.String()])
  357. if len(dag[c]) != 1 {
  358. break
  359. }
  360. c = dag[c][0].Hash
  361. if len(parents[c]) != 1 {
  362. break
  363. }
  364. }
  365. mergedSeq[head] = seq
  366. mergedDag[head] = dag[seq[len(seq)-1].Hash]
  367. }
  368. return
  369. }
  370. // collapseFastForwards removes the fast forward merges.
  371. func collapseFastForwards(
  372. orderNodes orderer, hashes map[string]*object.Commit,
  373. mergedDag, dag, mergedSeq map[plumbing.Hash][]*object.Commit) {
  374. parents := buildParents(mergedDag)
  375. processed := map[plumbing.Hash]bool{}
  376. for _, strkey := range orderNodes(false, true) {
  377. key := hashes[strkey].Hash
  378. processed[key] = true
  379. repeat:
  380. vals, exists := mergedDag[key]
  381. if !exists {
  382. continue
  383. }
  384. if len(vals) < 2 {
  385. continue
  386. }
  387. toRemove := map[plumbing.Hash]bool{}
  388. sort.Slice(vals, func(i, j int) bool { return vals[i].Hash.String() < vals[j].Hash.String() })
  389. for _, child := range vals {
  390. var queue []plumbing.Hash
  391. visited := map[plumbing.Hash]bool{child.Hash: true}
  392. childParents := parents[child.Hash]
  393. childNumOtherParents := 0
  394. for parent := range childParents {
  395. if parent != key {
  396. visited[parent] = true
  397. childNumOtherParents++
  398. queue = append(queue, parent)
  399. }
  400. }
  401. var immediateParent plumbing.Hash
  402. if childNumOtherParents == 1 {
  403. immediateParent = queue[0]
  404. }
  405. for len(queue) > 0 {
  406. head := queue[len(queue)-1]
  407. queue = queue[:len(queue)-1]
  408. if processed[head] {
  409. if head == key {
  410. toRemove[child.Hash] = true
  411. if childNumOtherParents == 1 && len(mergedDag[immediateParent]) == 1 {
  412. mergedSeq[immediateParent] = append(
  413. mergedSeq[immediateParent], mergedSeq[child.Hash]...)
  414. delete(mergedSeq, child.Hash)
  415. mergedDag[immediateParent] = mergedDag[child.Hash]
  416. delete(mergedDag, child.Hash)
  417. parents[child.Hash] = parents[immediateParent]
  418. for _, vals := range parents {
  419. for v := range vals {
  420. if v == child.Hash {
  421. delete(vals, v)
  422. vals[immediateParent] = true
  423. break
  424. }
  425. }
  426. }
  427. }
  428. break
  429. }
  430. } else {
  431. for parent := range parents[head] {
  432. if !visited[parent] {
  433. visited[head] = true
  434. queue = append(queue, parent)
  435. }
  436. }
  437. }
  438. }
  439. }
  440. if len(toRemove) == 0 {
  441. continue
  442. }
  443. // update dag
  444. var newVals []*object.Commit
  445. node := mergedSeq[key][len(mergedSeq[key])-1].Hash
  446. for _, child := range dag[node] {
  447. if !toRemove[child.Hash] {
  448. newVals = append(newVals, child)
  449. }
  450. }
  451. dag[node] = newVals
  452. // update mergedDag
  453. newVals = []*object.Commit{}
  454. for _, child := range vals {
  455. if !toRemove[child.Hash] {
  456. newVals = append(newVals, child)
  457. }
  458. }
  459. merged := false
  460. if len(newVals) == 1 {
  461. onlyChild := newVals[0].Hash
  462. if len(parents[onlyChild]) == 1 {
  463. merged = true
  464. mergedSeq[key] = append(mergedSeq[key], mergedSeq[onlyChild]...)
  465. delete(mergedSeq, onlyChild)
  466. mergedDag[key] = mergedDag[onlyChild]
  467. delete(mergedDag, onlyChild)
  468. parents[onlyChild] = parents[key]
  469. for _, vals := range parents {
  470. for v := range vals {
  471. if v == onlyChild {
  472. delete(vals, v)
  473. vals[key] = true
  474. break
  475. }
  476. }
  477. }
  478. }
  479. }
  480. // update parents
  481. for rm := range toRemove {
  482. delete(parents[rm], key)
  483. }
  484. if !merged {
  485. mergedDag[key] = newVals
  486. } else {
  487. goto repeat
  488. }
  489. }
  490. }
  491. // generatePlan creates the list of actions from the commit DAG.
  492. func generatePlan(
  493. orderNodes orderer, hashes map[string]*object.Commit,
  494. mergedDag, dag, mergedSeq map[plumbing.Hash][]*object.Commit) []runAction {
  495. parents := buildParents(dag)
  496. var plan []runAction
  497. branches := map[plumbing.Hash]int{}
  498. branchers := map[plumbing.Hash]map[plumbing.Hash]int{}
  499. counter := rootBranchIndex
  500. for _, name := range orderNodes(false, true) {
  501. commit := hashes[name]
  502. if len(parents[commit.Hash]) == 0 {
  503. branches[commit.Hash] = counter
  504. plan = append(plan, runAction{
  505. Action: runActionEmerge,
  506. Commit: commit,
  507. Items: []int{counter},
  508. })
  509. counter++
  510. }
  511. var branch int
  512. {
  513. var exists bool
  514. branch, exists = branches[commit.Hash]
  515. if !exists {
  516. branch = -1
  517. }
  518. }
  519. branchExists := func() bool { return branch >= rootBranchIndex }
  520. appendCommit := func(c *object.Commit, branch int) {
  521. if branch == 0 {
  522. log.Panicf("setting a zero branch for %s", c.Hash.String())
  523. }
  524. plan = append(plan, runAction{
  525. Action: runActionCommit,
  526. Commit: c,
  527. Items: []int{branch},
  528. })
  529. }
  530. appendMergeIfNeeded := func() bool {
  531. if len(parents[commit.Hash]) < 2 {
  532. return false
  533. }
  534. // merge after the merge commit (the first in the sequence)
  535. var items []int
  536. minBranch := 1 << 31
  537. for parent := range parents[commit.Hash] {
  538. parentBranch := -1
  539. if parents, exists := branchers[commit.Hash]; exists {
  540. if inheritedBranch, exists := parents[parent]; exists {
  541. parentBranch = inheritedBranch
  542. }
  543. }
  544. if parentBranch == -1 {
  545. parentBranch = branches[parent]
  546. if parentBranch < rootBranchIndex {
  547. log.Panicf("parent %s > %s does not have a branch assigned",
  548. parent.String(), commit.Hash.String())
  549. }
  550. }
  551. if len(dag[parent]) == 1 && minBranch > parentBranch {
  552. minBranch = parentBranch
  553. }
  554. items = append(items, parentBranch)
  555. if parentBranch != branch {
  556. appendCommit(commit, parentBranch)
  557. }
  558. }
  559. // there should be no duplicates in items
  560. if minBranch < 1<<31 {
  561. branch = minBranch
  562. branches[commit.Hash] = minBranch
  563. } else if !branchExists() {
  564. log.Panicf("failed to assign the branch to merge %s", commit.Hash.String())
  565. }
  566. plan = append(plan, runAction{
  567. Action: runActionMerge,
  568. Commit: nil,
  569. Items: items,
  570. })
  571. return true
  572. }
  573. var head plumbing.Hash
  574. if subseq, exists := mergedSeq[commit.Hash]; exists {
  575. for subseqIndex, offspring := range subseq {
  576. if branchExists() {
  577. appendCommit(offspring, branch)
  578. }
  579. if subseqIndex == 0 {
  580. if !appendMergeIfNeeded() && !branchExists() {
  581. log.Panicf("head of the sequence does not have an assigned branch: %s",
  582. commit.Hash.String())
  583. }
  584. }
  585. }
  586. head = subseq[len(subseq)-1].Hash
  587. branches[head] = branch
  588. } else {
  589. head = commit.Hash
  590. }
  591. if len(mergedDag[commit.Hash]) > 1 {
  592. children := []int{branch}
  593. for i, child := range mergedDag[commit.Hash] {
  594. if i == 0 {
  595. branches[child.Hash] = branch
  596. continue
  597. }
  598. if _, exists := branches[child.Hash]; !exists {
  599. branches[child.Hash] = counter
  600. }
  601. parents := branchers[child.Hash]
  602. if parents == nil {
  603. parents = map[plumbing.Hash]int{}
  604. branchers[child.Hash] = parents
  605. }
  606. parents[head] = counter
  607. children = append(children, counter)
  608. counter++
  609. }
  610. plan = append(plan, runAction{
  611. Action: runActionFork,
  612. Commit: hashes[head.String()],
  613. Items: children,
  614. })
  615. }
  616. }
  617. return plan
  618. }
  619. // collectGarbage inserts `runActionDelete` disposal steps.
  620. func collectGarbage(plan []runAction) []runAction {
  621. // lastMentioned maps branch index to the index inside `plan` when that branch was last used
  622. lastMentioned := map[int]int{}
  623. for i, p := range plan {
  624. firstItem := p.Items[0]
  625. switch p.Action {
  626. case runActionCommit:
  627. lastMentioned[firstItem] = i
  628. if firstItem < rootBranchIndex {
  629. log.Panicf("commit %s does not have an assigned branch",
  630. p.Commit.Hash.String())
  631. }
  632. case runActionFork:
  633. lastMentioned[firstItem] = i
  634. case runActionMerge:
  635. for _, item := range p.Items {
  636. lastMentioned[item] = i
  637. }
  638. case runActionEmerge:
  639. lastMentioned[firstItem] = i
  640. }
  641. }
  642. var garbageCollectedPlan []runAction
  643. lastMentionedArr := make([][2]int, 0, len(lastMentioned)+1)
  644. for key, val := range lastMentioned {
  645. if val != len(plan)-1 {
  646. lastMentionedArr = append(lastMentionedArr, [2]int{val, key})
  647. }
  648. }
  649. if len(lastMentionedArr) == 0 {
  650. // early return - we have nothing to collect
  651. return plan
  652. }
  653. sort.Slice(lastMentionedArr, func(i, j int) bool {
  654. return lastMentionedArr[i][0] < lastMentionedArr[j][0]
  655. })
  656. lastMentionedArr = append(lastMentionedArr, [2]int{len(plan) - 1, -1})
  657. prevpi := -1
  658. for _, pair := range lastMentionedArr {
  659. for pi := prevpi + 1; pi <= pair[0]; pi++ {
  660. garbageCollectedPlan = append(garbageCollectedPlan, plan[pi])
  661. }
  662. if pair[1] >= 0 {
  663. prevpi = pair[0]
  664. garbageCollectedPlan = append(garbageCollectedPlan, runAction{
  665. Action: runActionDelete,
  666. Commit: nil,
  667. Items: []int{pair[1]},
  668. })
  669. }
  670. }
  671. return garbageCollectedPlan
  672. }
  673. type hbAction struct {
  674. Branch int
  675. Hibernate bool
  676. }
  677. func insertHibernateBoot(plan []runAction, hibernationDistance int) []runAction {
  678. addons := map[int][]hbAction{}
  679. lastUsed := map[int]int{}
  680. addonsCount := 0
  681. for x, action := range plan {
  682. if action.Action == runActionDelete {
  683. continue
  684. }
  685. for _, item := range action.Items {
  686. if i, exists := lastUsed[item]; exists && (x-i-1) > hibernationDistance {
  687. if addons[x] == nil {
  688. addons[x] = make([]hbAction, 0, 1)
  689. }
  690. addons[x] = append(addons[x], hbAction{item, false})
  691. if addons[i] == nil {
  692. addons[i] = make([]hbAction, 0, 1)
  693. }
  694. addons[i] = append(addons[i], hbAction{item, true})
  695. addonsCount += 2
  696. }
  697. lastUsed[item] = x
  698. }
  699. }
  700. newPlan := make([]runAction, 0, len(plan)+addonsCount)
  701. for x, action := range plan {
  702. xaddons := addons[x]
  703. var boots []int
  704. var hibernates []int
  705. if len(xaddons) > 0 {
  706. boots = make([]int, 0, len(xaddons))
  707. hibernates = make([]int, 0, len(xaddons))
  708. for _, addon := range xaddons {
  709. if !addon.Hibernate {
  710. boots = append(boots, addon.Branch)
  711. } else {
  712. hibernates = append(hibernates, addon.Branch)
  713. }
  714. }
  715. }
  716. if len(boots) > 0 {
  717. newPlan = append(newPlan, runAction{
  718. Action: runActionBoot,
  719. Commit: action.Commit,
  720. Items: boots,
  721. })
  722. }
  723. newPlan = append(newPlan, action)
  724. if len(hibernates) > 0 {
  725. newPlan = append(newPlan, runAction{
  726. Action: runActionHibernate,
  727. Commit: action.Commit,
  728. Items: hibernates,
  729. })
  730. }
  731. }
  732. return newPlan
  733. }