forks.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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. firstItem := p.Items[0]
  147. switch p.Action {
  148. case runActionCommit:
  149. planPrintFunc("C", firstItem, p.Commit.Hash.String())
  150. case runActionFork:
  151. planPrintFunc("F", p.Items)
  152. case runActionMerge:
  153. planPrintFunc("M", p.Items)
  154. case runActionEmerge:
  155. planPrintFunc("E", p.Items)
  156. case runActionDelete:
  157. planPrintFunc("D", p.Items)
  158. case runActionHibernate:
  159. planPrintFunc("H", firstItem)
  160. case runActionBoot:
  161. planPrintFunc("B", firstItem)
  162. }
  163. }
  164. }
  165. return plan
  166. }
  167. // buildDag generates the raw commit DAG and the commit hash map.
  168. func buildDag(commits []*object.Commit) (
  169. map[string]*object.Commit, map[plumbing.Hash][]*object.Commit) {
  170. hashes := map[string]*object.Commit{}
  171. for _, commit := range commits {
  172. hashes[commit.Hash.String()] = commit
  173. }
  174. dag := map[plumbing.Hash][]*object.Commit{}
  175. for _, commit := range commits {
  176. if _, exists := dag[commit.Hash]; !exists {
  177. dag[commit.Hash] = make([]*object.Commit, 0, 1)
  178. }
  179. for _, parent := range commit.ParentHashes {
  180. if _, exists := hashes[parent.String()]; !exists {
  181. continue
  182. }
  183. children := dag[parent]
  184. if children == nil {
  185. children = make([]*object.Commit, 0, 1)
  186. }
  187. dag[parent] = append(children, commit)
  188. }
  189. }
  190. return hashes, dag
  191. }
  192. // leaveRootComponent runs connected components analysis and throws away everything
  193. // but the part which grows from the root.
  194. func leaveRootComponent(
  195. hashes map[string]*object.Commit,
  196. dag map[plumbing.Hash][]*object.Commit) {
  197. visited := map[plumbing.Hash]bool{}
  198. var sets [][]plumbing.Hash
  199. for key := range dag {
  200. if visited[key] {
  201. continue
  202. }
  203. var set []plumbing.Hash
  204. for queue := []plumbing.Hash{key}; len(queue) > 0; {
  205. head := queue[len(queue)-1]
  206. queue = queue[:len(queue)-1]
  207. if visited[head] {
  208. continue
  209. }
  210. set = append(set, head)
  211. visited[head] = true
  212. for _, c := range dag[head] {
  213. if !visited[c.Hash] {
  214. queue = append(queue, c.Hash)
  215. }
  216. }
  217. if commit, exists := hashes[head.String()]; exists {
  218. for _, p := range commit.ParentHashes {
  219. if !visited[p] {
  220. if _, exists := hashes[p.String()]; exists {
  221. queue = append(queue, p)
  222. }
  223. }
  224. }
  225. }
  226. }
  227. sets = append(sets, set)
  228. }
  229. if len(sets) > 1 {
  230. maxlen := 0
  231. maxind := -1
  232. for i, set := range sets {
  233. if len(set) > maxlen {
  234. maxlen = len(set)
  235. maxind = i
  236. }
  237. }
  238. for i, set := range sets {
  239. if i == maxind {
  240. continue
  241. }
  242. for _, h := range set {
  243. log.Printf("warning: dropped %s from the analysis - disjoint", h.String())
  244. delete(dag, h)
  245. delete(hashes, h.String())
  246. }
  247. }
  248. }
  249. }
  250. // bindOrderNodes returns curried "orderNodes" function.
  251. func bindOrderNodes(mergedDag map[plumbing.Hash][]*object.Commit) orderer {
  252. return func(reverse, direction bool) []string {
  253. graph := toposort.NewGraph()
  254. keys := make([]plumbing.Hash, 0, len(mergedDag))
  255. for key := range mergedDag {
  256. keys = append(keys, key)
  257. }
  258. sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
  259. for _, key := range keys {
  260. graph.AddNode(key.String())
  261. }
  262. for _, key := range keys {
  263. children := mergedDag[key]
  264. sort.Slice(children, func(i, j int) bool {
  265. return children[i].Hash.String() < children[j].Hash.String()
  266. })
  267. for _, c := range children {
  268. if !direction {
  269. graph.AddEdge(key.String(), c.Hash.String())
  270. } else {
  271. graph.AddEdge(c.Hash.String(), key.String())
  272. }
  273. }
  274. }
  275. order, ok := graph.Toposort()
  276. if !ok {
  277. // should never happen
  278. panic("Could not topologically sort the DAG of commits")
  279. }
  280. if reverse != direction {
  281. // one day this must appear in the standard library...
  282. for i, j := 0, len(order)-1; i < len(order)/2; i, j = i+1, j-1 {
  283. order[i], order[j] = order[j], order[i]
  284. }
  285. }
  286. return order
  287. }
  288. }
  289. // inverts `dag`
  290. func buildParents(dag map[plumbing.Hash][]*object.Commit) map[plumbing.Hash]map[plumbing.Hash]bool {
  291. parents := map[plumbing.Hash]map[plumbing.Hash]bool{}
  292. for key, vals := range dag {
  293. for _, val := range vals {
  294. myps := parents[val.Hash]
  295. if myps == nil {
  296. myps = map[plumbing.Hash]bool{}
  297. parents[val.Hash] = myps
  298. }
  299. myps[key] = true
  300. }
  301. }
  302. return parents
  303. }
  304. // mergeDag turns sequences of consecutive commits into single nodes.
  305. func mergeDag(
  306. hashes map[string]*object.Commit,
  307. dag map[plumbing.Hash][]*object.Commit) (
  308. mergedDag, mergedSeq map[plumbing.Hash][]*object.Commit) {
  309. parents := buildParents(dag)
  310. mergedDag = map[plumbing.Hash][]*object.Commit{}
  311. mergedSeq = map[plumbing.Hash][]*object.Commit{}
  312. visited := map[plumbing.Hash]bool{}
  313. for head := range dag {
  314. if visited[head] {
  315. continue
  316. }
  317. c := head
  318. for true {
  319. nextParents := parents[c]
  320. var next plumbing.Hash
  321. for p := range nextParents {
  322. next = p
  323. break
  324. }
  325. if len(nextParents) != 1 || len(dag[next]) != 1 {
  326. break
  327. }
  328. c = next
  329. }
  330. head = c
  331. var seq []*object.Commit
  332. for true {
  333. visited[c] = true
  334. seq = append(seq, hashes[c.String()])
  335. if len(dag[c]) != 1 {
  336. break
  337. }
  338. c = dag[c][0].Hash
  339. if len(parents[c]) != 1 {
  340. break
  341. }
  342. }
  343. mergedSeq[head] = seq
  344. mergedDag[head] = dag[seq[len(seq)-1].Hash]
  345. }
  346. return
  347. }
  348. // collapseFastForwards removes the fast forward merges.
  349. func collapseFastForwards(
  350. orderNodes orderer, hashes map[string]*object.Commit,
  351. mergedDag, dag, mergedSeq map[plumbing.Hash][]*object.Commit) {
  352. parents := buildParents(mergedDag)
  353. processed := map[plumbing.Hash]bool{}
  354. for _, strkey := range orderNodes(false, true) {
  355. key := hashes[strkey].Hash
  356. processed[key] = true
  357. repeat:
  358. vals, exists := mergedDag[key]
  359. if !exists {
  360. continue
  361. }
  362. if len(vals) < 2 {
  363. continue
  364. }
  365. toRemove := map[plumbing.Hash]bool{}
  366. sort.Slice(vals, func(i, j int) bool { return vals[i].Hash.String() < vals[j].Hash.String() })
  367. for _, child := range vals {
  368. var queue []plumbing.Hash
  369. visited := map[plumbing.Hash]bool{child.Hash: true}
  370. childParents := parents[child.Hash]
  371. childNumOtherParents := 0
  372. for parent := range childParents {
  373. if parent != key {
  374. visited[parent] = true
  375. childNumOtherParents++
  376. queue = append(queue, parent)
  377. }
  378. }
  379. var immediateParent plumbing.Hash
  380. if childNumOtherParents == 1 {
  381. immediateParent = queue[0]
  382. }
  383. for len(queue) > 0 {
  384. head := queue[len(queue)-1]
  385. queue = queue[:len(queue)-1]
  386. if processed[head] {
  387. if head == key {
  388. toRemove[child.Hash] = true
  389. if childNumOtherParents == 1 && len(mergedDag[immediateParent]) == 1 {
  390. mergedSeq[immediateParent] = append(
  391. mergedSeq[immediateParent], mergedSeq[child.Hash]...)
  392. delete(mergedSeq, child.Hash)
  393. mergedDag[immediateParent] = mergedDag[child.Hash]
  394. delete(mergedDag, child.Hash)
  395. parents[child.Hash] = parents[immediateParent]
  396. for _, vals := range parents {
  397. for v := range vals {
  398. if v == child.Hash {
  399. delete(vals, v)
  400. vals[immediateParent] = true
  401. break
  402. }
  403. }
  404. }
  405. }
  406. break
  407. }
  408. } else {
  409. for parent := range parents[head] {
  410. if !visited[parent] {
  411. visited[head] = true
  412. queue = append(queue, parent)
  413. }
  414. }
  415. }
  416. }
  417. }
  418. if len(toRemove) == 0 {
  419. continue
  420. }
  421. // update dag
  422. var newVals []*object.Commit
  423. node := mergedSeq[key][len(mergedSeq[key])-1].Hash
  424. for _, child := range dag[node] {
  425. if !toRemove[child.Hash] {
  426. newVals = append(newVals, child)
  427. }
  428. }
  429. dag[node] = newVals
  430. // update mergedDag
  431. newVals = []*object.Commit{}
  432. for _, child := range vals {
  433. if !toRemove[child.Hash] {
  434. newVals = append(newVals, child)
  435. }
  436. }
  437. merged := false
  438. if len(newVals) == 1 {
  439. onlyChild := newVals[0].Hash
  440. if len(parents[onlyChild]) == 1 {
  441. merged = true
  442. mergedSeq[key] = append(mergedSeq[key], mergedSeq[onlyChild]...)
  443. delete(mergedSeq, onlyChild)
  444. mergedDag[key] = mergedDag[onlyChild]
  445. delete(mergedDag, onlyChild)
  446. parents[onlyChild] = parents[key]
  447. for _, vals := range parents {
  448. for v := range vals {
  449. if v == onlyChild {
  450. delete(vals, v)
  451. vals[key] = true
  452. break
  453. }
  454. }
  455. }
  456. }
  457. }
  458. // update parents
  459. for rm := range toRemove {
  460. delete(parents[rm], key)
  461. }
  462. if !merged {
  463. mergedDag[key] = newVals
  464. } else {
  465. goto repeat
  466. }
  467. }
  468. }
  469. // generatePlan creates the list of actions from the commit DAG.
  470. func generatePlan(
  471. orderNodes orderer, hashes map[string]*object.Commit,
  472. mergedDag, dag, mergedSeq map[plumbing.Hash][]*object.Commit) []runAction {
  473. parents := buildParents(dag)
  474. var plan []runAction
  475. branches := map[plumbing.Hash]int{}
  476. branchers := map[plumbing.Hash]map[plumbing.Hash]int{}
  477. counter := rootBranchIndex
  478. for _, name := range orderNodes(false, true) {
  479. commit := hashes[name]
  480. if len(parents[commit.Hash]) == 0 {
  481. branches[commit.Hash] = counter
  482. plan = append(plan, runAction{
  483. Action: runActionEmerge,
  484. Commit: commit,
  485. Items: []int{counter},
  486. })
  487. counter++
  488. }
  489. var branch int
  490. {
  491. var exists bool
  492. branch, exists = branches[commit.Hash]
  493. if !exists {
  494. branch = -1
  495. }
  496. }
  497. branchExists := func() bool { return branch >= rootBranchIndex }
  498. appendCommit := func(c *object.Commit, branch int) {
  499. if branch == 0 {
  500. log.Panicf("setting a zero branch for %s", c.Hash.String())
  501. }
  502. plan = append(plan, runAction{
  503. Action: runActionCommit,
  504. Commit: c,
  505. Items: []int{branch},
  506. })
  507. }
  508. appendMergeIfNeeded := func() bool {
  509. if len(parents[commit.Hash]) < 2 {
  510. return false
  511. }
  512. // merge after the merge commit (the first in the sequence)
  513. var items []int
  514. minBranch := 1 << 31
  515. for parent := range parents[commit.Hash] {
  516. parentBranch := -1
  517. if parents, exists := branchers[commit.Hash]; exists {
  518. if inheritedBranch, exists := parents[parent]; exists {
  519. parentBranch = inheritedBranch
  520. }
  521. }
  522. if parentBranch == -1 {
  523. parentBranch = branches[parent]
  524. if parentBranch < rootBranchIndex {
  525. log.Panicf("parent %s > %s does not have a branch assigned",
  526. parent.String(), commit.Hash.String())
  527. }
  528. }
  529. if len(dag[parent]) == 1 && minBranch > parentBranch {
  530. minBranch = parentBranch
  531. }
  532. items = append(items, parentBranch)
  533. if parentBranch != branch {
  534. appendCommit(commit, parentBranch)
  535. }
  536. }
  537. // there should be no duplicates in items
  538. if minBranch < 1<<31 {
  539. branch = minBranch
  540. branches[commit.Hash] = minBranch
  541. } else if !branchExists() {
  542. log.Panicf("failed to assign the branch to merge %s", commit.Hash.String())
  543. }
  544. plan = append(plan, runAction{
  545. Action: runActionMerge,
  546. Commit: nil,
  547. Items: items,
  548. })
  549. return true
  550. }
  551. var head plumbing.Hash
  552. if subseq, exists := mergedSeq[commit.Hash]; exists {
  553. for subseqIndex, offspring := range subseq {
  554. if branchExists() {
  555. appendCommit(offspring, branch)
  556. }
  557. if subseqIndex == 0 {
  558. if !appendMergeIfNeeded() && !branchExists() {
  559. log.Panicf("head of the sequence does not have an assigned branch: %s",
  560. commit.Hash.String())
  561. }
  562. }
  563. }
  564. head = subseq[len(subseq)-1].Hash
  565. branches[head] = branch
  566. } else {
  567. head = commit.Hash
  568. }
  569. if len(mergedDag[commit.Hash]) > 1 {
  570. children := []int{branch}
  571. for i, child := range mergedDag[commit.Hash] {
  572. if i == 0 {
  573. branches[child.Hash] = branch
  574. continue
  575. }
  576. if _, exists := branches[child.Hash]; !exists {
  577. branches[child.Hash] = counter
  578. }
  579. parents := branchers[child.Hash]
  580. if parents == nil {
  581. parents = map[plumbing.Hash]int{}
  582. branchers[child.Hash] = parents
  583. }
  584. parents[head] = counter
  585. children = append(children, counter)
  586. counter++
  587. }
  588. plan = append(plan, runAction{
  589. Action: runActionFork,
  590. Commit: hashes[head.String()],
  591. Items: children,
  592. })
  593. }
  594. }
  595. return plan
  596. }
  597. // collectGarbage inserts `runActionDelete` disposal steps.
  598. func collectGarbage(plan []runAction) []runAction {
  599. // lastMentioned maps branch index to the index inside `plan` when that branch was last used
  600. lastMentioned := map[int]int{}
  601. for i, p := range plan {
  602. firstItem := p.Items[0]
  603. switch p.Action {
  604. case runActionCommit:
  605. lastMentioned[firstItem] = i
  606. if firstItem < rootBranchIndex {
  607. log.Panicf("commit %s does not have an assigned branch",
  608. p.Commit.Hash.String())
  609. }
  610. case runActionFork:
  611. lastMentioned[firstItem] = i
  612. case runActionMerge:
  613. for _, item := range p.Items {
  614. lastMentioned[item] = i
  615. }
  616. case runActionEmerge:
  617. lastMentioned[firstItem] = i
  618. }
  619. }
  620. var garbageCollectedPlan []runAction
  621. lastMentionedArr := make([][2]int, 0, len(lastMentioned)+1)
  622. for key, val := range lastMentioned {
  623. if val != len(plan)-1 {
  624. lastMentionedArr = append(lastMentionedArr, [2]int{val, key})
  625. }
  626. }
  627. if len(lastMentionedArr) == 0 {
  628. // early return - we have nothing to collect
  629. return plan
  630. }
  631. sort.Slice(lastMentionedArr, func(i, j int) bool {
  632. return lastMentionedArr[i][0] < lastMentionedArr[j][0]
  633. })
  634. lastMentionedArr = append(lastMentionedArr, [2]int{len(plan) - 1, -1})
  635. prevpi := -1
  636. for _, pair := range lastMentionedArr {
  637. for pi := prevpi + 1; pi <= pair[0]; pi++ {
  638. garbageCollectedPlan = append(garbageCollectedPlan, plan[pi])
  639. }
  640. if pair[1] >= 0 {
  641. prevpi = pair[0]
  642. garbageCollectedPlan = append(garbageCollectedPlan, runAction{
  643. Action: runActionDelete,
  644. Commit: nil,
  645. Items: []int{pair[1]},
  646. })
  647. }
  648. }
  649. return garbageCollectedPlan
  650. }
  651. type hbAction struct {
  652. Branch int
  653. Hibernate bool
  654. }
  655. func insertHibernateBoot(plan []runAction, hibernationDistance int) []runAction {
  656. addons := map[int][]hbAction{}
  657. lastUsed := map[int]int{}
  658. addonsCount := 0
  659. for x, action := range plan {
  660. if action.Action == runActionDelete {
  661. continue
  662. }
  663. for _, item := range action.Items {
  664. if i, exists := lastUsed[item]; exists && (x-i-1) > hibernationDistance {
  665. if addons[x] == nil {
  666. addons[x] = make([]hbAction, 0, 1)
  667. }
  668. addons[x] = append(addons[x], hbAction{item, false})
  669. if addons[i] == nil {
  670. addons[i] = make([]hbAction, 0, 1)
  671. }
  672. addons[i] = append(addons[i], hbAction{item, true})
  673. addonsCount += 2
  674. }
  675. lastUsed[item] = x
  676. }
  677. }
  678. newPlan := make([]runAction, 0, len(plan)+addonsCount)
  679. for x, action := range plan {
  680. xaddons := addons[x]
  681. var boots []int
  682. var hibernates []int
  683. if len(xaddons) > 0 {
  684. boots = make([]int, 0, len(xaddons))
  685. hibernates = make([]int, 0, len(xaddons))
  686. for _, addon := range xaddons {
  687. if !addon.Hibernate {
  688. boots = append(boots, addon.Branch)
  689. } else {
  690. hibernates = append(hibernates, addon.Branch)
  691. }
  692. }
  693. }
  694. if len(boots) > 0 {
  695. newPlan = append(newPlan, runAction{
  696. Action: runActionBoot,
  697. Commit: action.Commit,
  698. Items: boots,
  699. })
  700. }
  701. newPlan = append(newPlan, action)
  702. if len(hibernates) > 0 {
  703. newPlan = append(newPlan, runAction{
  704. Action: runActionHibernate,
  705. Commit: action.Commit,
  706. Items: hibernates,
  707. })
  708. }
  709. }
  710. return newPlan
  711. }