-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.ts
More file actions
168 lines (156 loc) · 5.99 KB
/
start.ts
File metadata and controls
168 lines (156 loc) · 5.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import type { Command } from 'commander';
import { join, basename } from 'path';
import { configManager } from '../config/manager';
import {
getCurrentBranch,
checkout,
branchExists,
getRepoRoot,
addWorktree,
pullBranch,
fetchAndUpdateBranch,
} from '../git/index';
import { isTicketId, extractTicketId, findBranchCaseInsensitive } from '../utils/ticket';
import { handleDirtyTree } from '../utils/stash';
import { requireTrackedRepo } from '../utils/detect';
import { theme, symbols } from '../ui/theme';
import { withSpinner } from '../ui/spinner';
import { fetchTicket, promptTicketInProgress } from '../utils/providers';
import { registry } from '../services/registry';
import { signalWorktreeCd } from '../utils/shell';
export async function runStart(
input: string,
options: { base?: string; worktree?: boolean },
): Promise<void> {
const projectId = await requireTrackedRepo();
let branchName: string;
let ticketId: string | null = null;
let ticketTitle: string | null = null;
let ticketUrl: string | null = null;
if (isTicketId(input)) {
const candidateId = input.trim().toUpperCase();
// Preserve the ticket ID's original case as the branch name (e.g. MORG-28 → branch MORG-28)
branchName = candidateId;
// Enrich from tickets provider if available — non-fatal if not configured or fetch fails
// ticketId only set on successful fetch so failed lookups don't link the branch to a bad ID
const ticketsProvider = await registry.tickets().catch(() => null);
if (ticketsProvider) {
try {
const ticket = await fetchTicket(ticketsProvider, candidateId);
ticketId = ticket.key;
ticketTitle = ticket.title;
ticketUrl = ticket.url ?? null;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.log(theme.warning(` ${symbols.warning} Could not fetch ticket: ${msg}`));
}
}
} else {
branchName = input;
ticketId = extractTicketId(input);
}
const [currentBranch, globalConfig, projectConfig] = await Promise.all([
getCurrentBranch(),
configManager.getGlobalConfig(),
configManager.getProjectConfig(projectId),
]);
const base = options.base ?? projectConfig.defaultBranch;
const autoUpdateTicketStatus =
projectConfig.autoUpdateTicketStatus ?? globalConfig.autoUpdateTicketStatus;
let worktreePath: string | null = null;
const exists = await branchExists(branchName);
if (options.worktree) {
const repoRoot = await getRepoRoot();
const repoName = basename(repoRoot);
const branchSlug = branchName.replace(/\//g, '-');
worktreePath = join(repoRoot, '..', `${repoName}-worktrees`, branchSlug);
if (exists) {
await withSpinner(`Creating worktree for ${branchName}...`, () =>
addWorktree(worktreePath!, branchName),
);
} else {
// Update local base before creating the worktree from it
if (currentBranch === base) {
try {
await withSpinner(`Pulling ${base}...`, () => pullBranch(base));
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.log(theme.warning(` ${symbols.warning} Could not pull ${base}: ${msg}`));
}
} else {
const updated = await fetchAndUpdateBranch(base);
if (!updated) {
console.log(theme.warning(` ${symbols.warning} Could not update ${base} — using local`));
}
}
await withSpinner(`Creating branch ${branchName} and worktree...`, () =>
addWorktree(worktreePath!, branchName, base),
);
}
console.log(
theme.success(`\n${symbols.success} Worktree created at ${theme.primaryBold(worktreePath)}`),
);
signalWorktreeCd(worktreePath);
} else {
if (exists) {
if (currentBranch !== branchName) {
await handleDirtyTree(currentBranch, branchName);
await withSpinner(`Switching to ${branchName}...`, () => checkout(branchName));
}
} else {
if (currentBranch !== base) {
await handleDirtyTree(currentBranch, branchName);
const updated = await fetchAndUpdateBranch(base);
if (!updated) {
console.log(theme.warning(` ${symbols.warning} Could not update ${base} — using local`));
}
} else {
try {
await withSpinner(`Pulling ${base}...`, () => pullBranch(base));
} catch {
console.log(theme.warning(` ${symbols.warning} Could not pull ${base} — using local`));
}
}
await withSpinner(`Creating branch ${branchName}...`, () => checkout(branchName, true, base));
}
console.log(theme.success(`\n${symbols.success} On branch ${theme.primaryBold(branchName)}`));
}
// Transition ticket to in-progress if configured
if (ticketId) {
await promptTicketInProgress(projectId, ticketId, autoUpdateTicketStatus);
}
// Create branch entry if it doesn't exist (case-insensitive check to avoid duplicates)
const now = new Date().toISOString();
const branches = await configManager.getBranches(projectId);
const existing = findBranchCaseInsensitive(branches.branches, branchName);
if (!existing) {
branches.branches.push({
id: `branch_${Date.now()}`,
branchName,
ticketId,
ticketTitle,
ticketUrl,
status: 'active',
createdAt: now,
updatedAt: now,
prNumber: null,
prUrl: null,
prStatus: null,
worktreePath,
lastAccessedAt: now,
});
} else {
existing.lastAccessedAt = now;
if (worktreePath) existing.worktreePath = worktreePath;
}
await configManager.saveBranches(projectId, branches);
if (ticketId) console.log(theme.muted(` Ticket: ${ticketId}`));
}
export function registerStartCommand(program: Command): void {
program
.command('start <branch-or-ticket>')
.description('Start work on a branch or ticket')
.option('--base <branch>', 'Base branch to create from (default: repo default branch)')
.option('-w, --worktree', 'Create a git worktree instead of checking out')
.action(runStart);
}