forks.go 20 KB

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