Files
beads/internal/importer/sort.go
Steve Yegge d6e2ff6151 Phase 1: Add topological sorting to fix import ordering
- Add sort.go with depth-based utilities (GetHierarchyDepth, SortByDepth, GroupByDepth)
- Sort issues by hierarchy depth before batch creation
- Create in depth-order batches (0→1→2→3)
- Fixes latent bug: parent-child pairs in same batch could fail if wrong order
- Comprehensive tests for all sorting functions
- Closes bd-37dd, bd-3433, bd-8b65

Part of bd-d19a (Fix import failure on missing parent issues)

Amp-Thread-ID: https://ampcode.com/threads/T-44a36985-b59c-426f-834c-60a0faa0f9fb
Co-authored-by: Amp <amp@ampcode.com>
2025-11-04 22:25:26 -08:00

45 lines
1.4 KiB
Go

package importer
import (
"sort"
"strings"
"github.com/steveyegge/beads/internal/types"
)
// GetHierarchyDepth returns the depth of a hierarchical issue ID.
// Depth is determined by the number of dots in the ID.
// Examples:
// - "bd-abc123" → 0 (top-level)
// - "bd-abc123.1" → 1 (one level deep)
// - "bd-abc123.1.2" → 2 (two levels deep)
func GetHierarchyDepth(id string) int {
return strings.Count(id, ".")
}
// SortByDepth sorts issues by hierarchy depth (shallow to deep) with stable sorting.
// Issues at the same depth are sorted by ID for deterministic ordering.
// This ensures parent issues are processed before their children.
func SortByDepth(issues []*types.Issue) {
sort.SliceStable(issues, func(i, j int) bool {
depthI := GetHierarchyDepth(issues[i].ID)
depthJ := GetHierarchyDepth(issues[j].ID)
if depthI != depthJ {
return depthI < depthJ
}
return issues[i].ID < issues[j].ID
})
}
// GroupByDepth groups issues into buckets by hierarchy depth.
// Returns a map where keys are depth levels and values are slices of issues at that depth.
// Maximum supported depth is 3 (as per beads spec).
func GroupByDepth(issues []*types.Issue) map[int][]*types.Issue {
groups := make(map[int][]*types.Issue)
for _, issue := range issues {
depth := GetHierarchyDepth(issue.ID)
groups[depth] = append(groups[depth], issue)
}
return groups
}