compactBindingContexts mimics the logic from shell-operator's CombineBindingContextForHook. It removes intermediate states for the same group, keeping only the most recent one.
(combinedContext []bindingcontext.BindingContext)
| 571 | // compactBindingContexts mimics the logic from shell-operator's CombineBindingContextForHook. |
| 572 | // It removes intermediate states for the same group, keeping only the most recent one. |
| 573 | func compactBindingContexts(combinedContext []bindingcontext.BindingContext) []bindingcontext.BindingContext { |
| 574 | if len(combinedContext) < 2 { |
| 575 | return combinedContext |
| 576 | } |
| 577 | |
| 578 | // Count ungrouped contexts and estimate result size |
| 579 | ungroupedCount := 0 |
| 580 | groupCount := 0 |
| 581 | for _, bc := range combinedContext { |
| 582 | if bc.Metadata.Group == "" { |
| 583 | ungroupedCount++ |
| 584 | } else { |
| 585 | groupCount++ |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | // If no grouped contexts, return as is |
| 590 | if groupCount == 0 { |
| 591 | return combinedContext |
| 592 | } |
| 593 | |
| 594 | // Use a single pass approach with a map to track the last occurrence of each group |
| 595 | lastIndexForGroup := make(map[string]int, groupCount) |
| 596 | ungroupedIndices := make([]int, 0, ungroupedCount) |
| 597 | |
| 598 | for i, bc := range combinedContext { |
| 599 | group := bc.Metadata.Group |
| 600 | if group == "" { |
| 601 | ungroupedIndices = append(ungroupedIndices, i) |
| 602 | } else { |
| 603 | lastIndexForGroup[group] = i |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | // Pre-allocate result slice with exact capacity |
| 608 | resultSize := len(ungroupedIndices) + len(lastIndexForGroup) |
| 609 | result := make([]bindingcontext.BindingContext, 0, resultSize) |
| 610 | |
| 611 | // Add ungrouped contexts first (preserving their order) |
| 612 | for _, idx := range ungroupedIndices { |
| 613 | result = append(result, combinedContext[idx]) |
| 614 | } |
| 615 | |
| 616 | // Add the last occurrence of each group |
| 617 | for _, idx := range lastIndexForGroup { |
| 618 | result = append(result, combinedContext[idx]) |
| 619 | } |
| 620 | |
| 621 | return result |
| 622 | } |
| 623 | |
| 624 | // RemoveLast deletes a tail element, so tail is moved. |
| 625 | func (q *TaskQueue) RemoveLast() task.Task { |