@smoothbricks/cli 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,361 @@
1
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { formatMarkerHits, scanRefChangedForMarkers } from '../lib/conflict-markers.js';
4
+ import { isRecord, readJson } from '../lib/json.js';
5
+ import { run, runResult } from '../lib/run.js';
6
+
7
+ /** 0 = clean/done, 2 = action required (conflicts to resolve), 1 = usage/error. */
8
+ export type PrResolveExit = 0 | 1 | 2;
9
+
10
+ export interface PrResolveOptions {
11
+ /** Git remote hosting the PR branch. Auto-inferred from the PR repo when omitted. */
12
+ remote?: string;
13
+ /** Abort an in-progress resolution: restore the original branch, drop state. */
14
+ abort?: boolean;
15
+ }
16
+
17
+ export interface PrResolveShell {
18
+ runResult(
19
+ command: string,
20
+ args: string[],
21
+ cwd: string,
22
+ ): Promise<{ exitCode: number; stdout: string; stderr: string }>;
23
+ run(command: string, args: string[], cwd: string): Promise<void>;
24
+ }
25
+
26
+ const defaultShell: PrResolveShell = {
27
+ runResult: (command, args, cwd) => runResult(command, args, cwd),
28
+ run: (command, args, cwd) => run(command, args, cwd),
29
+ };
30
+
31
+ interface PrMeta {
32
+ number: number;
33
+ url: string;
34
+ headBranch: string;
35
+ baseBranch: string;
36
+ crossRepo: boolean;
37
+ nameWithOwner: string;
38
+ }
39
+
40
+ interface PrResolveState {
41
+ pr: number;
42
+ url: string;
43
+ headBranch: string;
44
+ baseBranch: string;
45
+ remote: string;
46
+ crossRepo: boolean;
47
+ /** Branch to return to, or '' when the original HEAD was detached. */
48
+ originalBranch: string;
49
+ originalSha: string;
50
+ startedAt: string;
51
+ }
52
+
53
+ /**
54
+ * Agent-first conflict resolution for a GitHub PR.
55
+ *
56
+ * First run (pointed at a PR): reports the conflict markers and, if any, checks
57
+ * out the PR branch and instructs the next step. Second run (on that branch,
58
+ * after the human/agent has resolved + committed): verifies no markers remain,
59
+ * pushes, and returns to the original branch. Idempotent via a state file under
60
+ * the git dir.
61
+ */
62
+ export async function resolvePrConflicts(
63
+ root: string,
64
+ prArg: string | undefined,
65
+ options: PrResolveOptions,
66
+ shell: PrResolveShell = defaultShell,
67
+ ): Promise<PrResolveExit> {
68
+ const statePath = join(await absoluteGitDir(shell, root), 'smoo', 'pr-resolve.json');
69
+ const state = readState(statePath);
70
+
71
+ if (options.abort === true) {
72
+ return abortResolve(shell, root, statePath, state);
73
+ }
74
+ if (state) {
75
+ return finishResolve(shell, root, statePath, state, prArg);
76
+ }
77
+ return startResolve(shell, root, statePath, prArg, options.remote);
78
+ }
79
+
80
+ async function startResolve(
81
+ shell: PrResolveShell,
82
+ root: string,
83
+ statePath: string,
84
+ prArg: string | undefined,
85
+ remoteOption: string | undefined,
86
+ ): Promise<PrResolveExit> {
87
+ if (!prArg) {
88
+ console.error('Point smoo at a PR: smoo pr resolve <number|url|branch> [--remote <name>]');
89
+ return 1;
90
+ }
91
+ if (!(await isWorkingTreeClean(shell, root))) {
92
+ console.error('Working tree is dirty. Commit or stash your changes before resolving a PR.');
93
+ return 1;
94
+ }
95
+
96
+ const meta = await prMeta(shell, root, prArg);
97
+ const remote = remoteOption ?? (await inferRemote(shell, root, meta.nameWithOwner));
98
+ await fetchBranches(shell, root, remote, [meta.baseBranch, meta.headBranch]);
99
+
100
+ const baseRef = `${remote}/${meta.baseBranch}`;
101
+ const headRef = `${remote}/${meta.headBranch}`;
102
+ const hits = await scanRefChangedForMarkers(shell, root, baseRef, headRef);
103
+ if (hits.length === 0) {
104
+ console.log(
105
+ `✅ PR #${meta.number} (${meta.headBranch} → ${meta.baseBranch}) has no conflict markers — nothing to resolve.`,
106
+ );
107
+ console.log('Next: it is safe to Rebase-and-merge.');
108
+ return 0;
109
+ }
110
+
111
+ const originalBranch = await currentBranch(shell, root);
112
+ const originalSha = (await mustRun(shell, root, ['rev-parse', 'HEAD'])).trim();
113
+ await checkoutPrBranch(shell, root, remote, meta);
114
+
115
+ writeState(statePath, {
116
+ pr: meta.number,
117
+ url: meta.url,
118
+ headBranch: meta.headBranch,
119
+ baseBranch: meta.baseBranch,
120
+ remote,
121
+ crossRepo: meta.crossRepo,
122
+ originalBranch,
123
+ originalSha,
124
+ startedAt: new Date().toISOString(),
125
+ });
126
+
127
+ const fileCount = hits.length;
128
+ console.log(`⚠️ PR #${meta.number} has conflict markers in ${fileCount} file${fileCount === 1 ? '' : 's'}:`);
129
+ console.log(formatMarkerHits(hits));
130
+ console.log('');
131
+ console.log(`Checked out '${meta.headBranch}' (was on '${originalBranch || originalSha.slice(0, 8)}').`);
132
+ console.log('Next:');
133
+ console.log(' 1. Resolve each <<<<<<< / ======= / >>>>>>> block (keep the right content, delete the markers).');
134
+ console.log(' 2. Commit the resolution: git add -A && git commit');
135
+ console.log(' 3. Run the SAME command again to verify, push, and return: smoo pr resolve');
136
+ return 2;
137
+ }
138
+
139
+ async function finishResolve(
140
+ shell: PrResolveShell,
141
+ root: string,
142
+ statePath: string,
143
+ state: PrResolveState,
144
+ prArg: string | undefined,
145
+ ): Promise<PrResolveExit> {
146
+ if (prArg && !prArgMatchesState(prArg, state)) {
147
+ console.error(
148
+ `A resolution for PR #${state.pr} (${state.headBranch}) is already in progress.\n` +
149
+ 'Finish it with `smoo pr resolve` (no argument), or discard it with `smoo pr resolve --abort`.',
150
+ );
151
+ return 1;
152
+ }
153
+
154
+ const branch = await currentBranch(shell, root);
155
+ if (branch !== state.headBranch) {
156
+ console.error(
157
+ `Expected to be on '${state.headBranch}' to finish resolving PR #${state.pr}, but HEAD is '${branch || 'detached'}'.\n` +
158
+ `Check out the branch (git checkout ${state.headBranch}) or discard with \`smoo pr resolve --abort\`.`,
159
+ );
160
+ return 1;
161
+ }
162
+ if (!(await isWorkingTreeClean(shell, root))) {
163
+ console.error('Your resolution is not committed yet.');
164
+ console.error('Next: git add -A && git commit — then run `smoo pr resolve` again.');
165
+ return 2;
166
+ }
167
+
168
+ await fetchBranches(shell, root, state.remote, [state.baseBranch]);
169
+ const hits = await scanRefChangedForMarkers(shell, root, `${state.remote}/${state.baseBranch}`, 'HEAD');
170
+ if (hits.length > 0) {
171
+ console.error(`Conflict markers still present in ${hits.length} file(s):`);
172
+ console.error(formatMarkerHits(hits));
173
+ console.error('Next: resolve the remaining markers, commit, then run `smoo pr resolve` again.');
174
+ return 2;
175
+ }
176
+
177
+ await pushResolvedBranch(shell, root, state);
178
+ await restoreOriginalBranch(shell, root, state);
179
+ clearState(statePath);
180
+
181
+ const back = state.originalBranch || state.originalSha.slice(0, 8);
182
+ console.log(
183
+ `✅ Resolved PR #${state.pr}: pushed '${state.headBranch}' to '${state.remote}' and returned to '${back}'.`,
184
+ );
185
+ console.log(`Next: PR #${state.pr} is clean now — mark it Ready / Rebase-and-merge.`);
186
+ return 0;
187
+ }
188
+
189
+ async function abortResolve(
190
+ shell: PrResolveShell,
191
+ root: string,
192
+ statePath: string,
193
+ state: PrResolveState | null,
194
+ ): Promise<PrResolveExit> {
195
+ if (!state) {
196
+ console.log('No conflict resolution in progress.');
197
+ return 0;
198
+ }
199
+ await restoreOriginalBranch(shell, root, state);
200
+ clearState(statePath);
201
+ const back = state.originalBranch || state.originalSha.slice(0, 8);
202
+ console.log(`Aborted resolution of PR #${state.pr}; returned to '${back}'. The PR branch is unchanged.`);
203
+ return 0;
204
+ }
205
+
206
+ async function prMeta(shell: PrResolveShell, root: string, prArg: string): Promise<PrMeta> {
207
+ const fields = 'number,url,headRefName,baseRefName,isCrossRepository';
208
+ const result = await shell.runResult('gh', ['pr', 'view', prArg, '--json', fields], root);
209
+ if (result.exitCode !== 0) {
210
+ throw new Error(`Could not resolve PR '${prArg}' via gh: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
211
+ }
212
+ const raw: unknown = JSON.parse(result.stdout);
213
+ if (!isRecord(raw)) {
214
+ throw new Error(`gh pr view returned unexpected JSON for '${prArg}'.`);
215
+ }
216
+ const { number, url, headRefName, baseRefName } = raw;
217
+ if (
218
+ typeof number !== 'number' ||
219
+ typeof url !== 'string' ||
220
+ typeof headRefName !== 'string' ||
221
+ typeof baseRefName !== 'string'
222
+ ) {
223
+ throw new Error(`gh pr view JSON for '${prArg}' is missing expected fields.`);
224
+ }
225
+ const match = /github\.com\/([^/]+\/[^/]+)\/pull\//.exec(url);
226
+ return {
227
+ number,
228
+ url,
229
+ headBranch: headRefName,
230
+ baseBranch: baseRefName,
231
+ crossRepo: raw.isCrossRepository === true,
232
+ nameWithOwner: match ? match[1] : '',
233
+ };
234
+ }
235
+
236
+ /** Pick the git remote whose URL points at `nameWithOwner`; fall back to origin. */
237
+ async function inferRemote(shell: PrResolveShell, root: string, nameWithOwner: string): Promise<string> {
238
+ if (nameWithOwner.length === 0) {
239
+ return 'origin';
240
+ }
241
+ const result = await shell.runResult('git', ['remote', '-v'], root);
242
+ const needle = nameWithOwner.toLowerCase();
243
+ for (const line of result.stdout.split('\n')) {
244
+ const [name, url] = line.split(/\s+/);
245
+ if (name && url?.toLowerCase().includes(needle)) {
246
+ return name;
247
+ }
248
+ }
249
+ return 'origin';
250
+ }
251
+
252
+ async function checkoutPrBranch(shell: PrResolveShell, root: string, remote: string, meta: PrMeta): Promise<void> {
253
+ if (meta.crossRepo) {
254
+ // Fork PR: let gh set up the fork remote + tracking branch correctly.
255
+ await shell.run('gh', ['pr', 'checkout', String(meta.number)], root);
256
+ return;
257
+ }
258
+ await shell.run('git', ['checkout', '-B', meta.headBranch, `${remote}/${meta.headBranch}`], root);
259
+ }
260
+
261
+ async function pushResolvedBranch(shell: PrResolveShell, root: string, state: PrResolveState): Promise<void> {
262
+ const refspec = `HEAD:refs/heads/${state.headBranch}`;
263
+ const ff = await shell.runResult('git', ['push', state.remote, refspec], root);
264
+ if (ff.exitCode === 0) {
265
+ return;
266
+ }
267
+ // The resolution may have been rebased/amended onto a moved head; the branch is
268
+ // the review branch we own, so force-with-lease is the safe way to update it.
269
+ console.log('Fast-forward push rejected; retrying with --force-with-lease (review branch).');
270
+ const forced = await shell.runResult('git', ['push', '--force-with-lease', state.remote, refspec], root);
271
+ if (forced.exitCode !== 0) {
272
+ throw new Error(
273
+ `Failed to push '${state.headBranch}' to '${state.remote}': ${forced.stderr.trim() || ff.stderr.trim()}`,
274
+ );
275
+ }
276
+ }
277
+
278
+ async function restoreOriginalBranch(shell: PrResolveShell, root: string, state: PrResolveState): Promise<void> {
279
+ const target = state.originalBranch.length > 0 ? state.originalBranch : state.originalSha;
280
+ await shell.run('git', ['checkout', target], root);
281
+ }
282
+
283
+ async function fetchBranches(shell: PrResolveShell, root: string, remote: string, branches: string[]): Promise<void> {
284
+ const refspecs = branches.map((branch) => `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`);
285
+ await shell.run('git', ['fetch', remote, ...refspecs], root);
286
+ }
287
+
288
+ async function currentBranch(shell: PrResolveShell, root: string): Promise<string> {
289
+ const result = await shell.runResult('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], root);
290
+ return result.exitCode === 0 ? result.stdout.trim() : '';
291
+ }
292
+
293
+ async function isWorkingTreeClean(shell: PrResolveShell, root: string): Promise<boolean> {
294
+ const result = await shell.runResult('git', ['status', '--porcelain'], root);
295
+ return result.exitCode === 0 && result.stdout.trim().length === 0;
296
+ }
297
+
298
+ async function absoluteGitDir(shell: PrResolveShell, root: string): Promise<string> {
299
+ const result = await shell.runResult('git', ['rev-parse', '--absolute-git-dir'], root);
300
+ if (result.exitCode !== 0) {
301
+ throw new Error(`Not a git repository at ${root}: ${result.stderr.trim()}`);
302
+ }
303
+ return result.stdout.trim();
304
+ }
305
+
306
+ async function mustRun(shell: PrResolveShell, root: string, args: string[]): Promise<string> {
307
+ const result = await shell.runResult('git', args, root);
308
+ if (result.exitCode !== 0) {
309
+ throw new Error(`git ${args.join(' ')} failed: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
310
+ }
311
+ return result.stdout;
312
+ }
313
+
314
+ function prArgMatchesState(prArg: string, state: PrResolveState): boolean {
315
+ if (prArg === state.headBranch || prArg === state.url) {
316
+ return true;
317
+ }
318
+ const numeric = prArg.startsWith('#') ? prArg.slice(1) : prArg;
319
+ return numeric === String(state.pr);
320
+ }
321
+
322
+ function readState(statePath: string): PrResolveState | null {
323
+ let raw: unknown;
324
+ try {
325
+ raw = readJson(statePath);
326
+ } catch {
327
+ return null;
328
+ }
329
+ if (!isRecord(raw)) {
330
+ return null;
331
+ }
332
+ const { pr, url, headBranch, baseBranch, remote, crossRepo, originalBranch, originalSha, startedAt } = raw;
333
+ if (
334
+ typeof pr !== 'number' ||
335
+ typeof headBranch !== 'string' ||
336
+ typeof baseBranch !== 'string' ||
337
+ typeof remote !== 'string'
338
+ ) {
339
+ return null;
340
+ }
341
+ return {
342
+ pr,
343
+ url: typeof url === 'string' ? url : '',
344
+ headBranch,
345
+ baseBranch,
346
+ remote,
347
+ crossRepo: crossRepo === true,
348
+ originalBranch: typeof originalBranch === 'string' ? originalBranch : '',
349
+ originalSha: typeof originalSha === 'string' ? originalSha : '',
350
+ startedAt: typeof startedAt === 'string' ? startedAt : '',
351
+ };
352
+ }
353
+
354
+ function writeState(statePath: string, state: PrResolveState): void {
355
+ mkdirSync(dirname(statePath), { recursive: true });
356
+ writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`);
357
+ }
358
+
359
+ function clearState(statePath: string): void {
360
+ rmSync(statePath, { force: true });
361
+ }
@@ -4,6 +4,7 @@ import { join } from 'node:path';
4
4
  import { createInterface } from 'node:readline/promises';
5
5
  import { Writable } from 'node:stream';
6
6
  import { $ } from 'bun';
7
+ import { assertNoConflictMarkers } from '../lib/conflict-markers.js';
7
8
  import { withDevenvEnv } from '../lib/devenv.js';
8
9
  import { isRecord, readJsonObject, stringProperty } from '../lib/json.js';
9
10
  import { decode, run, runInteractiveStatus, runResult, runStatus } from '../lib/run.js';
@@ -110,6 +111,10 @@ export async function releaseVersion(root: string, options: ReleaseVersionOption
110
111
  }
111
112
 
112
113
  export async function releasePublish(root: string, options: ReleasePublishOptions): Promise<void> {
114
+ // Never publish a tree carrying unresolved conflict markers (e.g. a merged
115
+ // review branch that still had markers). Enforced here so every smoo-managed
116
+ // repo's template publish step inherits it. See `smoo pr resolve`.
117
+ await assertNoConflictMarkers({ runResult }, root, 'publish');
113
118
  const bump = releaseBumpArg(options.bump);
114
119
  const packages = await releasePackagesAtHead(root, releasePackages(root));
115
120
  if (packages.length === 0) {