@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,256 @@
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
+ const defaultShell = {
7
+ runResult: (command, args, cwd) => runResult(command, args, cwd),
8
+ run: (command, args, cwd) => run(command, args, cwd),
9
+ };
10
+ /**
11
+ * Agent-first conflict resolution for a GitHub PR.
12
+ *
13
+ * First run (pointed at a PR): reports the conflict markers and, if any, checks
14
+ * out the PR branch and instructs the next step. Second run (on that branch,
15
+ * after the human/agent has resolved + committed): verifies no markers remain,
16
+ * pushes, and returns to the original branch. Idempotent via a state file under
17
+ * the git dir.
18
+ */
19
+ export async function resolvePrConflicts(root, prArg, options, shell = defaultShell) {
20
+ const statePath = join(await absoluteGitDir(shell, root), 'smoo', 'pr-resolve.json');
21
+ const state = readState(statePath);
22
+ if (options.abort === true) {
23
+ return abortResolve(shell, root, statePath, state);
24
+ }
25
+ if (state) {
26
+ return finishResolve(shell, root, statePath, state, prArg);
27
+ }
28
+ return startResolve(shell, root, statePath, prArg, options.remote);
29
+ }
30
+ async function startResolve(shell, root, statePath, prArg, remoteOption) {
31
+ if (!prArg) {
32
+ console.error('Point smoo at a PR: smoo pr resolve <number|url|branch> [--remote <name>]');
33
+ return 1;
34
+ }
35
+ if (!(await isWorkingTreeClean(shell, root))) {
36
+ console.error('Working tree is dirty. Commit or stash your changes before resolving a PR.');
37
+ return 1;
38
+ }
39
+ const meta = await prMeta(shell, root, prArg);
40
+ const remote = remoteOption ?? (await inferRemote(shell, root, meta.nameWithOwner));
41
+ await fetchBranches(shell, root, remote, [meta.baseBranch, meta.headBranch]);
42
+ const baseRef = `${remote}/${meta.baseBranch}`;
43
+ const headRef = `${remote}/${meta.headBranch}`;
44
+ const hits = await scanRefChangedForMarkers(shell, root, baseRef, headRef);
45
+ if (hits.length === 0) {
46
+ console.log(`✅ PR #${meta.number} (${meta.headBranch} → ${meta.baseBranch}) has no conflict markers — nothing to resolve.`);
47
+ console.log('Next: it is safe to Rebase-and-merge.');
48
+ return 0;
49
+ }
50
+ const originalBranch = await currentBranch(shell, root);
51
+ const originalSha = (await mustRun(shell, root, ['rev-parse', 'HEAD'])).trim();
52
+ await checkoutPrBranch(shell, root, remote, meta);
53
+ writeState(statePath, {
54
+ pr: meta.number,
55
+ url: meta.url,
56
+ headBranch: meta.headBranch,
57
+ baseBranch: meta.baseBranch,
58
+ remote,
59
+ crossRepo: meta.crossRepo,
60
+ originalBranch,
61
+ originalSha,
62
+ startedAt: new Date().toISOString(),
63
+ });
64
+ const fileCount = hits.length;
65
+ console.log(`⚠️ PR #${meta.number} has conflict markers in ${fileCount} file${fileCount === 1 ? '' : 's'}:`);
66
+ console.log(formatMarkerHits(hits));
67
+ console.log('');
68
+ console.log(`Checked out '${meta.headBranch}' (was on '${originalBranch || originalSha.slice(0, 8)}').`);
69
+ console.log('Next:');
70
+ console.log(' 1. Resolve each <<<<<<< / ======= / >>>>>>> block (keep the right content, delete the markers).');
71
+ console.log(' 2. Commit the resolution: git add -A && git commit');
72
+ console.log(' 3. Run the SAME command again to verify, push, and return: smoo pr resolve');
73
+ return 2;
74
+ }
75
+ async function finishResolve(shell, root, statePath, state, prArg) {
76
+ if (prArg && !prArgMatchesState(prArg, state)) {
77
+ console.error(`A resolution for PR #${state.pr} (${state.headBranch}) is already in progress.\n` +
78
+ 'Finish it with `smoo pr resolve` (no argument), or discard it with `smoo pr resolve --abort`.');
79
+ return 1;
80
+ }
81
+ const branch = await currentBranch(shell, root);
82
+ if (branch !== state.headBranch) {
83
+ console.error(`Expected to be on '${state.headBranch}' to finish resolving PR #${state.pr}, but HEAD is '${branch || 'detached'}'.\n` +
84
+ `Check out the branch (git checkout ${state.headBranch}) or discard with \`smoo pr resolve --abort\`.`);
85
+ return 1;
86
+ }
87
+ if (!(await isWorkingTreeClean(shell, root))) {
88
+ console.error('Your resolution is not committed yet.');
89
+ console.error('Next: git add -A && git commit — then run `smoo pr resolve` again.');
90
+ return 2;
91
+ }
92
+ await fetchBranches(shell, root, state.remote, [state.baseBranch]);
93
+ const hits = await scanRefChangedForMarkers(shell, root, `${state.remote}/${state.baseBranch}`, 'HEAD');
94
+ if (hits.length > 0) {
95
+ console.error(`Conflict markers still present in ${hits.length} file(s):`);
96
+ console.error(formatMarkerHits(hits));
97
+ console.error('Next: resolve the remaining markers, commit, then run `smoo pr resolve` again.');
98
+ return 2;
99
+ }
100
+ await pushResolvedBranch(shell, root, state);
101
+ await restoreOriginalBranch(shell, root, state);
102
+ clearState(statePath);
103
+ const back = state.originalBranch || state.originalSha.slice(0, 8);
104
+ console.log(`✅ Resolved PR #${state.pr}: pushed '${state.headBranch}' to '${state.remote}' and returned to '${back}'.`);
105
+ console.log(`Next: PR #${state.pr} is clean now — mark it Ready / Rebase-and-merge.`);
106
+ return 0;
107
+ }
108
+ async function abortResolve(shell, root, statePath, state) {
109
+ if (!state) {
110
+ console.log('No conflict resolution in progress.');
111
+ return 0;
112
+ }
113
+ await restoreOriginalBranch(shell, root, state);
114
+ clearState(statePath);
115
+ const back = state.originalBranch || state.originalSha.slice(0, 8);
116
+ console.log(`Aborted resolution of PR #${state.pr}; returned to '${back}'. The PR branch is unchanged.`);
117
+ return 0;
118
+ }
119
+ async function prMeta(shell, root, prArg) {
120
+ const fields = 'number,url,headRefName,baseRefName,isCrossRepository';
121
+ const result = await shell.runResult('gh', ['pr', 'view', prArg, '--json', fields], root);
122
+ if (result.exitCode !== 0) {
123
+ throw new Error(`Could not resolve PR '${prArg}' via gh: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
124
+ }
125
+ const raw = JSON.parse(result.stdout);
126
+ if (!isRecord(raw)) {
127
+ throw new Error(`gh pr view returned unexpected JSON for '${prArg}'.`);
128
+ }
129
+ const { number, url, headRefName, baseRefName } = raw;
130
+ if (typeof number !== 'number' ||
131
+ typeof url !== 'string' ||
132
+ typeof headRefName !== 'string' ||
133
+ typeof baseRefName !== 'string') {
134
+ throw new Error(`gh pr view JSON for '${prArg}' is missing expected fields.`);
135
+ }
136
+ const match = /github\.com\/([^/]+\/[^/]+)\/pull\//.exec(url);
137
+ return {
138
+ number,
139
+ url,
140
+ headBranch: headRefName,
141
+ baseBranch: baseRefName,
142
+ crossRepo: raw.isCrossRepository === true,
143
+ nameWithOwner: match ? match[1] : '',
144
+ };
145
+ }
146
+ /** Pick the git remote whose URL points at `nameWithOwner`; fall back to origin. */
147
+ async function inferRemote(shell, root, nameWithOwner) {
148
+ if (nameWithOwner.length === 0) {
149
+ return 'origin';
150
+ }
151
+ const result = await shell.runResult('git', ['remote', '-v'], root);
152
+ const needle = nameWithOwner.toLowerCase();
153
+ for (const line of result.stdout.split('\n')) {
154
+ const [name, url] = line.split(/\s+/);
155
+ if (name && url?.toLowerCase().includes(needle)) {
156
+ return name;
157
+ }
158
+ }
159
+ return 'origin';
160
+ }
161
+ async function checkoutPrBranch(shell, root, remote, meta) {
162
+ if (meta.crossRepo) {
163
+ // Fork PR: let gh set up the fork remote + tracking branch correctly.
164
+ await shell.run('gh', ['pr', 'checkout', String(meta.number)], root);
165
+ return;
166
+ }
167
+ await shell.run('git', ['checkout', '-B', meta.headBranch, `${remote}/${meta.headBranch}`], root);
168
+ }
169
+ async function pushResolvedBranch(shell, root, state) {
170
+ const refspec = `HEAD:refs/heads/${state.headBranch}`;
171
+ const ff = await shell.runResult('git', ['push', state.remote, refspec], root);
172
+ if (ff.exitCode === 0) {
173
+ return;
174
+ }
175
+ // The resolution may have been rebased/amended onto a moved head; the branch is
176
+ // the review branch we own, so force-with-lease is the safe way to update it.
177
+ console.log('Fast-forward push rejected; retrying with --force-with-lease (review branch).');
178
+ const forced = await shell.runResult('git', ['push', '--force-with-lease', state.remote, refspec], root);
179
+ if (forced.exitCode !== 0) {
180
+ throw new Error(`Failed to push '${state.headBranch}' to '${state.remote}': ${forced.stderr.trim() || ff.stderr.trim()}`);
181
+ }
182
+ }
183
+ async function restoreOriginalBranch(shell, root, state) {
184
+ const target = state.originalBranch.length > 0 ? state.originalBranch : state.originalSha;
185
+ await shell.run('git', ['checkout', target], root);
186
+ }
187
+ async function fetchBranches(shell, root, remote, branches) {
188
+ const refspecs = branches.map((branch) => `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`);
189
+ await shell.run('git', ['fetch', remote, ...refspecs], root);
190
+ }
191
+ async function currentBranch(shell, root) {
192
+ const result = await shell.runResult('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], root);
193
+ return result.exitCode === 0 ? result.stdout.trim() : '';
194
+ }
195
+ async function isWorkingTreeClean(shell, root) {
196
+ const result = await shell.runResult('git', ['status', '--porcelain'], root);
197
+ return result.exitCode === 0 && result.stdout.trim().length === 0;
198
+ }
199
+ async function absoluteGitDir(shell, root) {
200
+ const result = await shell.runResult('git', ['rev-parse', '--absolute-git-dir'], root);
201
+ if (result.exitCode !== 0) {
202
+ throw new Error(`Not a git repository at ${root}: ${result.stderr.trim()}`);
203
+ }
204
+ return result.stdout.trim();
205
+ }
206
+ async function mustRun(shell, root, args) {
207
+ const result = await shell.runResult('git', args, root);
208
+ if (result.exitCode !== 0) {
209
+ throw new Error(`git ${args.join(' ')} failed: ${result.stderr.trim() || `exit ${result.exitCode}`}`);
210
+ }
211
+ return result.stdout;
212
+ }
213
+ function prArgMatchesState(prArg, state) {
214
+ if (prArg === state.headBranch || prArg === state.url) {
215
+ return true;
216
+ }
217
+ const numeric = prArg.startsWith('#') ? prArg.slice(1) : prArg;
218
+ return numeric === String(state.pr);
219
+ }
220
+ function readState(statePath) {
221
+ let raw;
222
+ try {
223
+ raw = readJson(statePath);
224
+ }
225
+ catch {
226
+ return null;
227
+ }
228
+ if (!isRecord(raw)) {
229
+ return null;
230
+ }
231
+ const { pr, url, headBranch, baseBranch, remote, crossRepo, originalBranch, originalSha, startedAt } = raw;
232
+ if (typeof pr !== 'number' ||
233
+ typeof headBranch !== 'string' ||
234
+ typeof baseBranch !== 'string' ||
235
+ typeof remote !== 'string') {
236
+ return null;
237
+ }
238
+ return {
239
+ pr,
240
+ url: typeof url === 'string' ? url : '',
241
+ headBranch,
242
+ baseBranch,
243
+ remote,
244
+ crossRepo: crossRepo === true,
245
+ originalBranch: typeof originalBranch === 'string' ? originalBranch : '',
246
+ originalSha: typeof originalSha === 'string' ? originalSha : '',
247
+ startedAt: typeof startedAt === 'string' ? startedAt : '',
248
+ };
249
+ }
250
+ function writeState(statePath, state) {
251
+ mkdirSync(dirname(statePath), { recursive: true });
252
+ writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`);
253
+ }
254
+ function clearState(statePath) {
255
+ rmSync(statePath, { force: true });
256
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/release/index.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,KAAK,2BAA2B,EAIjC,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAML,KAAK,kBAAkB,EAGxB,MAAM,WAAW,CAAC;AAkBnB,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,2BAA2B;IAC1C,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,4BAA4B;IAC3C,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,OAA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AE,MAAM,CAAC;CACrB;AAED,wBAAsB,0BAA0B,CAAC,OAAO,SAAS,kBAAkB,EACjF,KAAK,EAAE,mBAAmB,CAAC,OAAO,CAAC,EACnC,OAAO,EAAE,4BAA4B,GACpC,OAAO,CAAC,IAAI,CAAC,CAuEf;AAuCD,wBAAsB,2BAA2B,CAC/C,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,kCAAkC,GAC1C,OAAO,CAAC,IAAI,CAAC,CAiBf;AAED,wBAAsB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,8BAA8B,GAAG,OAAO,CAAC,IAAI,CAAC,CAelH;AAED,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEnE;AAkkCD,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAe9F"}
@@ -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';
@@ -39,6 +40,10 @@ export async function releaseVersion(root, options) {
39
40
  await writeReleaseGithubOutput(options.githubOutput, result.packages, result.mode);
40
41
  }
41
42
  export async function releasePublish(root, options) {
43
+ // Never publish a tree carrying unresolved conflict markers (e.g. a merged
44
+ // review branch that still had markers). Enforced here so every smoo-managed
45
+ // repo's template publish step inherits it. See `smoo pr resolve`.
46
+ await assertNoConflictMarkers({ runResult }, root, 'publish');
42
47
  const bump = releaseBumpArg(options.bump);
43
48
  const packages = await releasePackagesAtHead(root, releasePackages(root));
44
49
  if (packages.length === 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smoothbricks/cli",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "SmoothBricks monorepo automation CLI",
6
6
  "bin": {
@@ -44,7 +44,7 @@
44
44
  "!**/*.tsbuildinfo"
45
45
  ],
46
46
  "dependencies": {
47
- "@arethetypeswrong/cli": "^0.18.2",
47
+ "@arethetypeswrong/core": "^0.18.2",
48
48
  "@smoothbricks/nx-plugin": "0.2.5",
49
49
  "@smoothbricks/validation": "0.1.1",
50
50
  "commander": "^14.0.3",
package/src/cli.ts CHANGED
@@ -2,6 +2,7 @@ import { Command, CommanderError } from 'commander';
2
2
  import { variants } from './generate/index.js';
3
3
  import { cliPackageVersion } from './lib/cli-package.js';
4
4
  import { findRepoRoot } from './lib/run.js';
5
+ import { resolvePrConflicts } from './pr/index.js';
5
6
 
6
7
  export async function runCli(argv = process.argv.slice(2)): Promise<void> {
7
8
  const program = buildProgram();
@@ -341,6 +342,18 @@ function buildProgram(): Command {
341
342
  },
342
343
  );
343
344
 
345
+ const pr = program.command('pr').description('Work with GitHub pull requests');
346
+ pr.command('resolve [pr]')
347
+ .description('Resolve conflict markers in a PR (agent-first, two-phase)')
348
+ .option('--remote <name>', 'git remote hosting the PR branch (auto-inferred when omitted)')
349
+ .option('--abort', 'discard an in-progress resolution and return to the original branch')
350
+ .action(async (prArg: string | undefined, options: { remote?: string; abort?: boolean }) => {
351
+ const exitCode = await resolvePrConflicts(await findRepoRoot(), prArg, options);
352
+ if (exitCode !== 0) {
353
+ process.exitCode = exitCode;
354
+ }
355
+ });
356
+
344
357
  return program;
345
358
  }
346
359
 
@@ -0,0 +1,165 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import {
3
+ assertNoConflictMarkers,
4
+ type ConflictMarkerHit,
5
+ ConflictMarkersError,
6
+ findMarkerLines,
7
+ formatMarkerHits,
8
+ type MarkerScanShell,
9
+ parseGitGrep,
10
+ scanRefChangedForMarkers,
11
+ scanTrackedForMarkers,
12
+ } from './conflict-markers.js';
13
+
14
+ describe('findMarkerLines', () => {
15
+ it('detects ours/base/theirs markers with their 1-based line numbers', () => {
16
+ const text = [
17
+ '{',
18
+ '<<<<<<< HEAD',
19
+ ' "a": 1',
20
+ '||||||| base',
21
+ ' "a": 0',
22
+ '=======',
23
+ ' "a": 2',
24
+ '>>>>>>> feat',
25
+ '}',
26
+ ].join('\n');
27
+ expect(findMarkerLines(text)).toEqual([2, 4, 8]);
28
+ });
29
+
30
+ it('does not flag a bare ======= separator (Markdown h1 / diff fill)', () => {
31
+ expect(findMarkerLines('Title\n=======\nbody')).toEqual([]);
32
+ });
33
+
34
+ it('does not flag quoted/indented marker strings in source', () => {
35
+ const source = ["const OPEN = '<<<<<<< ';", " const CLOSE = '>>>>>>> ';", 'const P = /^<<<<<<< /;'].join('\n');
36
+ expect(findMarkerLines(source)).toEqual([]);
37
+ });
38
+
39
+ it('returns empty for clean text', () => {
40
+ expect(findMarkerLines('{\n "a": 1\n}\n')).toEqual([]);
41
+ });
42
+ });
43
+
44
+ describe('parseGitGrep', () => {
45
+ it('groups path:line:content rows by file', () => {
46
+ const stdout = ['pkg/a.json:12:<<<<<<< HEAD', 'pkg/a.json:16:>>>>>>> x', 'b.toml:36:<<<<<<< HEAD', ''].join('\n');
47
+ expect(parseGitGrep(stdout)).toEqual([
48
+ { file: 'pkg/a.json', lines: [12, 16] },
49
+ { file: 'b.toml', lines: [36] },
50
+ ]);
51
+ });
52
+
53
+ it('tolerates paths containing colons in content and skips malformed rows', () => {
54
+ const stdout = ['a.ts:3:foo: bar', 'garbage-without-colon', 'a.ts:9:>>>>>>> y'].join('\n');
55
+ expect(parseGitGrep(stdout)).toEqual([{ file: 'a.ts', lines: [3, 9] }]);
56
+ });
57
+
58
+ it('returns empty for empty output', () => {
59
+ expect(parseGitGrep('')).toEqual([]);
60
+ });
61
+ });
62
+
63
+ describe('scanTrackedForMarkers', () => {
64
+ it('returns hits when git grep finds markers (exit 0)', async () => {
65
+ const shell = scriptedShell([{ exitCode: 0, stdout: 'x.json:2:<<<<<<< HEAD\n', stderr: '' }]);
66
+ const hits = await scanTrackedForMarkers(shell.shell, '/repo');
67
+ expect(hits).toEqual([{ file: 'x.json', lines: [2] }]);
68
+ expect(shell.calls[0].args).toEqual(['grep', '-nI', '-E', '^(<<<<<<< |\\|\\|\\|\\|\\|\\|\\| |>>>>>>> )']);
69
+ });
70
+
71
+ it('passes pathspecs through after --', async () => {
72
+ const shell = scriptedShell([{ exitCode: 1, stdout: '', stderr: '' }]);
73
+ await scanTrackedForMarkers(shell.shell, '/repo', ['packages/a', 'packages/b']);
74
+ expect(shell.calls[0].args.slice(-3)).toEqual(['--', 'packages/a', 'packages/b']);
75
+ });
76
+
77
+ it('treats exit 1 as no matches', async () => {
78
+ const shell = scriptedShell([{ exitCode: 1, stdout: '', stderr: '' }]);
79
+ expect(await scanTrackedForMarkers(shell.shell, '/repo')).toEqual([]);
80
+ });
81
+
82
+ it('throws on git grep error (exit > 1)', async () => {
83
+ const shell = scriptedShell([{ exitCode: 128, stdout: '', stderr: 'not a git repo' }]);
84
+ await expect(scanTrackedForMarkers(shell.shell, '/repo')).rejects.toThrow('not a git repo');
85
+ });
86
+ });
87
+
88
+ describe('scanRefChangedForMarkers', () => {
89
+ it('reads changed-file blobs at head and reports only markered files', async () => {
90
+ const shell = scriptedShell([
91
+ { exitCode: 0, stdout: 'pkg/a.json\npkg/clean.ts\n', stderr: '' }, // git diff --name-only
92
+ { exitCode: 0, stdout: '{\n<<<<<<< HEAD\n=======\n>>>>>>> feat\n}\n', stderr: '' }, // show a.json
93
+ { exitCode: 0, stdout: 'export const ok = 1;\n', stderr: '' }, // show clean.ts
94
+ ]);
95
+ const hits = await scanRefChangedForMarkers(shell.shell, '/repo', 'base', 'head');
96
+ expect(hits).toEqual([{ file: 'pkg/a.json', lines: [2, 4] }]);
97
+ expect(shell.calls[0].args).toEqual(['diff', '--name-only', 'base...head']);
98
+ expect(shell.calls[1].args).toEqual(['show', 'head:pkg/a.json', '--textconv']);
99
+ });
100
+
101
+ it('skips files deleted/unreadable at head', async () => {
102
+ const shell = scriptedShell([
103
+ { exitCode: 0, stdout: 'gone.txt\n', stderr: '' },
104
+ { exitCode: 128, stdout: '', stderr: 'exists on disk, but not in head' },
105
+ ]);
106
+ expect(await scanRefChangedForMarkers(shell.shell, '/repo', 'base', 'head')).toEqual([]);
107
+ });
108
+ });
109
+
110
+ describe('formatMarkerHits', () => {
111
+ it('formats file + line list per hit', () => {
112
+ const hits: ConflictMarkerHit[] = [
113
+ { file: 'a.json', lines: [12, 16] },
114
+ { file: 'b.toml', lines: [3] },
115
+ ];
116
+ expect(formatMarkerHits(hits)).toBe(' a.json (lines 12, 16)\n b.toml (lines 3)');
117
+ });
118
+ });
119
+
120
+ interface ScriptedCall {
121
+ command: string;
122
+ args: string[];
123
+ cwd: string;
124
+ }
125
+
126
+ function scriptedShell(responses: { exitCode: number; stdout: string; stderr: string }[]): {
127
+ shell: MarkerScanShell;
128
+ calls: ScriptedCall[];
129
+ } {
130
+ const calls: ScriptedCall[] = [];
131
+ let index = 0;
132
+ const shell: MarkerScanShell = {
133
+ async runResult(command, args, cwd) {
134
+ calls.push({ command, args, cwd });
135
+ const response = responses[index++];
136
+ if (!response) {
137
+ throw new Error(`unexpected shell call: ${command} ${args.join(' ')}`);
138
+ }
139
+ return response;
140
+ },
141
+ };
142
+ return { shell, calls };
143
+ }
144
+
145
+ describe('assertNoConflictMarkers', () => {
146
+ it('throws ConflictMarkersError listing hits when markers exist', async () => {
147
+ const shell = scriptedShell([{ exitCode: 0, stdout: 'a.json:2:<<<<<<< HEAD\n', stderr: '' }]);
148
+ let caught: unknown;
149
+ try {
150
+ await assertNoConflictMarkers(shell.shell, '/repo', 'publish');
151
+ } catch (error) {
152
+ caught = error;
153
+ }
154
+ expect(caught).toBeInstanceOf(ConflictMarkersError);
155
+ if (caught instanceof ConflictMarkersError) {
156
+ expect(caught.hits).toEqual([{ file: 'a.json', lines: [2] }]);
157
+ expect(caught.message).toContain('Refusing to publish');
158
+ }
159
+ });
160
+
161
+ it('resolves when the tree is clean', async () => {
162
+ const shell = scriptedShell([{ exitCode: 1, stdout: '', stderr: '' }]);
163
+ await expect(assertNoConflictMarkers(shell.shell, '/repo', 'publish')).resolves.toBeUndefined();
164
+ });
165
+ });
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Shared detection of Git merge-conflict markers.
3
+ *
4
+ * Real conflict markers always sit at column 0 and are a 7-character run of
5
+ * `<`, `|`, or `>` followed by a space (the diff3 base marker `|||||||` and the
6
+ * ours/theirs markers `<<<<<<< ` / `>>>>>>> `). We deliberately do NOT match a
7
+ * bare `=======` separator: it is ambiguous with Markdown h1 underlines and adds
8
+ * no signal (a real conflict always carries the angle/pipe markers too). The
9
+ * column-0 anchor also means quoted marker strings inside source (which are
10
+ * indented) never false-positive.
11
+ */
12
+ export const CONFLICT_MARKER_PATTERN = '^(<<<<<<< |\\|\\|\\|\\|\\|\\|\\| |>>>>>>> )';
13
+
14
+ const conflictMarkerRe = new RegExp(CONFLICT_MARKER_PATTERN);
15
+
16
+ export interface ConflictMarkerHit {
17
+ /** Repo-relative path of the offending file. */
18
+ readonly file: string;
19
+ /** 1-based line numbers carrying a conflict marker. */
20
+ readonly lines: number[];
21
+ }
22
+
23
+ /** 1-based line numbers of every conflict-marker line in `text`. */
24
+ export function findMarkerLines(text: string): number[] {
25
+ const hits: number[] = [];
26
+ const lines = text.split('\n');
27
+ for (let i = 0; i < lines.length; i++) {
28
+ if (conflictMarkerRe.test(lines[i])) {
29
+ hits.push(i + 1);
30
+ }
31
+ }
32
+ return hits;
33
+ }
34
+
35
+ export interface MarkerScanShell {
36
+ runResult(
37
+ command: string,
38
+ args: string[],
39
+ cwd: string,
40
+ ): Promise<{ exitCode: number; stdout: string; stderr: string }>;
41
+ }
42
+
43
+ /**
44
+ * Scan tracked files in the working tree for conflict markers via `git grep`.
45
+ * `pathspecs` optionally restricts the scan (e.g. release package roots).
46
+ */
47
+ export async function scanTrackedForMarkers(
48
+ shell: MarkerScanShell,
49
+ root: string,
50
+ pathspecs: string[] = [],
51
+ ): Promise<ConflictMarkerHit[]> {
52
+ const args = ['grep', '-nI', '-E', CONFLICT_MARKER_PATTERN];
53
+ if (pathspecs.length > 0) {
54
+ args.push('--', ...pathspecs);
55
+ }
56
+ const { exitCode, stdout, stderr } = await shell.runResult('git', args, root);
57
+ // git grep: 0 = matches found, 1 = no matches, >1 = error.
58
+ if (exitCode > 1) {
59
+ throw new Error(`git grep for conflict markers failed: ${stderr.trim() || `exit ${exitCode}`}`);
60
+ }
61
+ return parseGitGrep(stdout);
62
+ }
63
+
64
+ /** Thrown by {@link assertNoConflictMarkers} so callers/tests can inspect the hits. */
65
+ export class ConflictMarkersError extends Error {
66
+ constructor(
67
+ readonly hits: ConflictMarkerHit[],
68
+ context: string,
69
+ ) {
70
+ super(`Refusing to ${context}: conflict markers found in ${hits.length} file(s):\n${formatMarkerHits(hits)}`);
71
+ this.name = 'ConflictMarkersError';
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Reusable publish/merge guard: throw {@link ConflictMarkersError} when any
77
+ * tracked file carries conflict markers. `context` names the blocked operation
78
+ * (e.g. `'publish'`) for the message.
79
+ */
80
+ export async function assertNoConflictMarkers(shell: MarkerScanShell, root: string, context: string): Promise<void> {
81
+ const hits = await scanTrackedForMarkers(shell, root);
82
+ if (hits.length > 0) {
83
+ throw new ConflictMarkersError(hits, context);
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Scan the files changed between `baseRef` and `headRef` (three-dot, i.e. since
89
+ * their merge base) for conflict markers, reading blobs at `headRef` — no
90
+ * checkout or working-tree mutation required.
91
+ */
92
+ export async function scanRefChangedForMarkers(
93
+ shell: MarkerScanShell,
94
+ root: string,
95
+ baseRef: string,
96
+ headRef: string,
97
+ ): Promise<ConflictMarkerHit[]> {
98
+ const diff = await shell.runResult('git', ['diff', '--name-only', `${baseRef}...${headRef}`], root);
99
+ if (diff.exitCode !== 0) {
100
+ throw new Error(`git diff ${baseRef}...${headRef} failed: ${diff.stderr.trim() || `exit ${diff.exitCode}`}`);
101
+ }
102
+ const files = diff.stdout.split('\n').filter((line) => line.length > 0);
103
+ const hits: ConflictMarkerHit[] = [];
104
+ for (const file of files) {
105
+ const show = await shell.runResult('git', ['show', `${headRef}:${file}`, '--textconv'], root);
106
+ if (show.exitCode !== 0) {
107
+ continue; // deleted at head / binary / unreadable — not a marker source
108
+ }
109
+ const lines = findMarkerLines(show.stdout);
110
+ if (lines.length > 0) {
111
+ hits.push({ file, lines });
112
+ }
113
+ }
114
+ return hits;
115
+ }
116
+
117
+ /** Parse `path:line:content` rows from `git grep -n` into per-file hits. */
118
+ export function parseGitGrep(stdout: string): ConflictMarkerHit[] {
119
+ const byFile = new Map<string, number[]>();
120
+ for (const row of stdout.split('\n')) {
121
+ if (row.length === 0) {
122
+ continue;
123
+ }
124
+ const firstColon = row.indexOf(':');
125
+ if (firstColon < 0) {
126
+ continue;
127
+ }
128
+ const secondColon = row.indexOf(':', firstColon + 1);
129
+ if (secondColon < 0) {
130
+ continue;
131
+ }
132
+ const file = row.slice(0, firstColon);
133
+ const line = Number.parseInt(row.slice(firstColon + 1, secondColon), 10);
134
+ if (!Number.isFinite(line)) {
135
+ continue;
136
+ }
137
+ const existing = byFile.get(file);
138
+ if (existing) {
139
+ existing.push(line);
140
+ } else {
141
+ byFile.set(file, [line]);
142
+ }
143
+ }
144
+ return [...byFile.entries()].map(([file, lines]) => ({ file, lines }));
145
+ }
146
+
147
+ /** Human-readable one-liner summary of marker hits, e.g. for CLI output. */
148
+ export function formatMarkerHits(hits: ConflictMarkerHit[]): string {
149
+ return hits.map((hit) => ` ${hit.file} (lines ${hit.lines.join(', ')})`).join('\n');
150
+ }
package/src/lib/run.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { existsSync } from 'node:fs';
3
- import { dirname, join } from 'node:path';
3
+ import { join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { $ } from 'bun';
6
6
 
@@ -106,10 +106,6 @@ function resolveBundledCommand(command: string): string | null {
106
106
  if (command === 'sherif') {
107
107
  return fileURLToPath(import.meta.resolve('sherif'));
108
108
  }
109
- if (command === 'attw') {
110
- const packageJson = fileURLToPath(import.meta.resolve('@arethetypeswrong/cli/package.json'));
111
- return join(dirname(packageJson), 'dist', 'index.js');
112
- }
113
109
  } catch {
114
110
  return null;
115
111
  }