Open History to see the last commit
1/**
2 * Sanitize an arbitrary string into a valid, lowercase git branch fragment.
3 * Strips quotes, collapses separators, limits to 64 chars.
4 */
5export function sanitizeBranchFragment(raw: string): string {
6 const normalized = raw
7 .trim()
8 .toLowerCase()
9 .replace(/['"`]/g, "")
10 .replace(/^[./\s_-]+|[./\s_-]+$/g, "");
11
12 const branchFragment = normalized
13 .replace(/[^a-z0-9/_-]+/g, "-")
14 .replace(/\/+/g, "/")
15 .replace(/-+/g, "-")
16 .replace(/^[./_-]+|[./_-]+$/g, "")
17 .slice(0, 64)
18 .replace(/[./_-]+$/g, "");
19
20 return branchFragment.length > 0 ? branchFragment : "update";
21}
22
23/**
24 * Sanitize a string into a `feature/…` branch name.
25 * Preserves an existing `feature/` prefix or slash-separated namespace.
26 */
27export function sanitizeFeatureBranchName(raw: string): string {
28 const sanitized = sanitizeBranchFragment(raw);
29 if (sanitized.includes("/")) {
30 return sanitized.startsWith("feature/") ? sanitized : `feature/${sanitized}`;
31 }
32 return `feature/${sanitized}`;
33}
34
35const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update";
36
37/**
38 * Resolve a unique `feature/…` branch name that doesn't collide with
39 * any existing branch. Appends a numeric suffix when needed.
40 */
41export function resolveAutoFeatureBranchName(
42 existingBranchNames: readonly string[],
43 preferredBranch?: string,
44): string {
45 const preferred = preferredBranch?.trim();
46 const resolvedBase = sanitizeFeatureBranchName(
47 preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,
48 );
49 const existingNames = new Set(existingBranchNames.map((branch) => branch.toLowerCase()));
50
51 if (!existingNames.has(resolvedBase)) {
52 return resolvedBase;
53 }
54
55 let suffix = 2;
56 while (existingNames.has(`${resolvedBase}-${suffix}`)) {
57 suffix += 1;
58 }
59
60 return `${resolvedBase}-${suffix}`;
61}