@bluenyang/reins 0.3.3 → 0.3.4-rc.1

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,74 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ const INSTALL = /^(?:(?:pnpm|yarn|bun|npm) (?:install|i|ci)\b|corepack enable\b|go mod download\b)/;
5
+ const onPullRequest = (on) => on === 'pull_request' ||
6
+ (Array.isArray(on) && on.includes('pull_request')) ||
7
+ (!!on && typeof on === 'object' && !Array.isArray(on) && 'pull_request' in on);
8
+ /** `cmd` run in `dir`, from the root, for the tools that take a directory option; null otherwise. */
9
+ export function fromDir(cmd, dir) {
10
+ if (!dir || dir === '.')
11
+ return cmd;
12
+ const [tool, ...rest] = cmd.split(' ');
13
+ const r = rest.join(' ');
14
+ switch (tool) {
15
+ case 'pnpm':
16
+ return `pnpm --dir ${dir} ${r}`;
17
+ case 'yarn':
18
+ return `yarn --cwd ${dir} ${r}`;
19
+ case 'npm':
20
+ return `npm --prefix ${dir} ${r}`;
21
+ case 'go':
22
+ return `go -C ${dir} ${r}`;
23
+ case 'make':
24
+ return `make -C ${dir} ${r}`;
25
+ default:
26
+ return null;
27
+ }
28
+ }
29
+ /**
30
+ * The one-line `run:` commands of the workflows that run on `pull_request` (024 S-8): no `${{`, one
31
+ * command (`compound` false), not an install step and not `skip(cmd)`; a multi-line `run: |` is unclear
32
+ * and left out, and so is a `working-directory` step whose tool takes no directory option.
33
+ */
34
+ export function ciRuns(root, compound, skip) {
35
+ const dir = join(root, '.github/workflows');
36
+ if (!existsSync(dir))
37
+ return [];
38
+ const out = [];
39
+ for (const f of readdirSync(dir).toSorted()) {
40
+ if (!/\.ya?ml$/.test(f))
41
+ continue;
42
+ let doc;
43
+ try {
44
+ doc = parse(readFileSync(join(dir, f), 'utf8'));
45
+ }
46
+ catch {
47
+ continue;
48
+ }
49
+ if (!doc || !onPullRequest(doc.on))
50
+ continue;
51
+ for (const job of Object.values(doc.jobs ?? {}))
52
+ for (const step of job?.steps ?? []) {
53
+ const s = step;
54
+ if (typeof s?.run !== 'string')
55
+ continue;
56
+ const raw = s.run.trim().replace(/\s+/g, ' ');
57
+ // a block scalar (`run: |`) keeps its newline even with one line in it
58
+ if (s.run.includes('\n') || raw.includes('${{') || compound(raw))
59
+ continue;
60
+ if (INSTALL.test(raw) || skip(raw))
61
+ continue;
62
+ const wd = typeof s['working-directory'] === 'string'
63
+ ? s['working-directory'].replace(/^\.\//, '').replace(/\/$/, '')
64
+ : '';
65
+ // a directory with a space, an expression or other characters would not read back as one word
66
+ if (wd && !/^[\w@.+/-]+$/.test(wd))
67
+ continue;
68
+ const cmd = fromDir(raw, wd);
69
+ if (cmd)
70
+ out.push({ file: `.github/workflows/${f}`, cmd, dir: wd === '.' ? '' : wd, raw });
71
+ }
72
+ }
73
+ return out;
74
+ }
@@ -0,0 +1,266 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ const LOCKS = ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json', 'bun.lockb', 'bun.lock'];
5
+ const SKIP = new Set(['node_modules', '.git', 'dist', 'build', 'vendor', '.loctx', '.agents']);
6
+ const readJson = (p) => {
7
+ try {
8
+ return JSON.parse(readFileSync(p, 'utf8'));
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ };
14
+ /** A file that makes `dir` a project of its own, outside the root workspace (croffle `apps/server/web`). */
15
+ export function ownProjectFile(root, dir) {
16
+ if (!dir)
17
+ return null;
18
+ for (const f of [...LOCKS, 'pnpm-workspace.yaml'])
19
+ if (existsSync(join(root, dir, f)))
20
+ return `${dir}/${f}`;
21
+ return null;
22
+ }
23
+ /** The workspace globs of the root: `pnpm-workspace.yaml` `packages`, else package.json `workspaces`. */
24
+ export function workspaceGlobs(root) {
25
+ const pnpm = join(root, 'pnpm-workspace.yaml');
26
+ if (existsSync(pnpm)) {
27
+ try {
28
+ const doc = parse(readFileSync(pnpm, 'utf8'));
29
+ if (Array.isArray(doc?.packages))
30
+ return { globs: doc.packages.map(String), file: 'pnpm-workspace.yaml' };
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ const pkg = readJson(join(root, 'package.json'));
37
+ const ws = pkg?.['workspaces'];
38
+ const list = Array.isArray(ws)
39
+ ? ws
40
+ : ws && typeof ws === 'object' && Array.isArray(ws.packages)
41
+ ? ws.packages
42
+ : null;
43
+ return list ? { globs: list.map(String), file: 'package.json' } : null;
44
+ }
45
+ /** One path segment of a glob as a regular expression: `*` is any run of characters but `/`. */
46
+ const segment = (s) => new RegExp(`^${s.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')}$`);
47
+ /** Directories (with a package.json) a workspace glob names: literal, `a/*`, `a/*-x`, `a/**`. */
48
+ function expand(root, glob) {
49
+ const parts = glob.replace(/^\.\//, '').replace(/\/$/, '').split('/');
50
+ const out = [];
51
+ const walk = (dir, i, depth) => {
52
+ if (i === parts.length) {
53
+ if (existsSync(join(root, dir, 'package.json')))
54
+ out.push(dir);
55
+ return;
56
+ }
57
+ const p = parts[i];
58
+ if (p === '**') {
59
+ walk(dir, i + 1, depth); // zero directories
60
+ if (depth > 4)
61
+ return;
62
+ for (const e of children(root, dir))
63
+ walk(dir ? `${dir}/${e}` : e, i, depth + 1);
64
+ return;
65
+ }
66
+ if (!p.includes('*')) {
67
+ walk(dir ? `${dir}/${p}` : p, i + 1, depth);
68
+ return;
69
+ }
70
+ const re = segment(p);
71
+ for (const e of children(root, dir))
72
+ if (re.test(e))
73
+ walk(dir ? `${dir}/${e}` : e, i + 1, depth);
74
+ };
75
+ walk('', 0, 0);
76
+ return out;
77
+ }
78
+ function children(root, dir) {
79
+ try {
80
+ return readdirSync(join(root, dir), { withFileTypes: true })
81
+ .filter((e) => e.isDirectory() && !SKIP.has(e.name))
82
+ .map((e) => e.name)
83
+ .toSorted();
84
+ }
85
+ catch {
86
+ return [];
87
+ }
88
+ }
89
+ /**
90
+ * The packages of the root workspace (024 S-7): the globs expanded to directories with a package.json,
91
+ * `!` globs taken out, and a directory with a lock or workspace file of its own left out.
92
+ */
93
+ export function workspacePackages(root) {
94
+ const ws = workspaceGlobs(root);
95
+ if (!ws)
96
+ return [];
97
+ const take = new Set();
98
+ for (const g of ws.globs.filter((x) => !x.startsWith('!')))
99
+ for (const d of expand(root, g))
100
+ take.add(d);
101
+ for (const g of ws.globs.filter((x) => x.startsWith('!')))
102
+ for (const d of expand(root, g.slice(1)))
103
+ take.delete(d);
104
+ return [...take]
105
+ .filter((d) => d !== '' && !ownProjectFile(root, d))
106
+ .toSorted()
107
+ .map((dir) => {
108
+ const name = readJson(join(root, dir, 'package.json'))?.['name'];
109
+ return typeof name === 'string' ? { dir, name } : { dir };
110
+ });
111
+ }
112
+ const nameGlob = (p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`);
113
+ /** The packages a pnpm `--filter`/npm `-w` value selects: a name as written, or `./dir`/`dir`. */
114
+ function select(pkgs, v) {
115
+ if (/[*{}[\]^!]|\.\.\./.test(v))
116
+ return null;
117
+ const path = v.replace(/^\.\//, '').replace(/\/$/, '');
118
+ const byName = pkgs.filter((p) => p.name === v);
119
+ if (byName.length)
120
+ return byName;
121
+ const byDir = pkgs.filter((p) => p.dir === path);
122
+ return byDir.length ? byDir : [];
123
+ }
124
+ /** The script after an optional `run`, with nothing after it; null when that is not the shape. */
125
+ function scriptAt(rest) {
126
+ const r = rest[0] === 'run' ? rest.slice(1) : rest;
127
+ return r.length === 1 && /^[\w:.-]+$/.test(r[0]) ? r[0] : null;
128
+ }
129
+ const HARMLESS = new Set(['--parallel', '--stream', '--if-present']);
130
+ /**
131
+ * Whether one command (already split into words) runs a script in workspace packages, in one of the
132
+ * forms of 024 S-7. A form with any other flag is unclear, so nothing is filtered by it.
133
+ */
134
+ export function forwards(words, pkgs) {
135
+ const [tool, ...a] = words;
136
+ if (tool === 'pnpm') {
137
+ let all = false;
138
+ let picked = null;
139
+ const rest = [];
140
+ for (let i = 0; i < a.length; i++) {
141
+ const w = a[i];
142
+ if (w === '-r' || w === '--recursive')
143
+ all = true;
144
+ else if (w === '--filter' || w === '-F' || w.startsWith('--filter=') || /^-F./.test(w)) {
145
+ const v = w.includes('=')
146
+ ? w.slice(w.indexOf('=') + 1)
147
+ : w.length > 2 && w.startsWith('-F')
148
+ ? w.slice(2)
149
+ : a[++i];
150
+ const s = v === undefined ? null : select(pkgs, v);
151
+ if (s === null)
152
+ return { unclear: `pnpm filter ${v ?? ''}` };
153
+ picked = [...(picked ?? []), ...s];
154
+ }
155
+ else if (HARMLESS.has(w))
156
+ continue;
157
+ else if (w.startsWith('-'))
158
+ return all || picked ? { unclear: `pnpm ${w}` } : null;
159
+ else
160
+ rest.push(w);
161
+ }
162
+ if (!all && !picked)
163
+ return null;
164
+ const s = scriptAt(rest);
165
+ if (!s)
166
+ return { unclear: 'pnpm: not one script' };
167
+ // a filter narrows -r: pnpm runs the filtered packages only (review 1)
168
+ return { scripts: [s], pkgs: picked ?? pkgs };
169
+ }
170
+ if (tool === 'npm') {
171
+ let all = false;
172
+ let picked = null;
173
+ const rest = [];
174
+ for (let i = 0; i < a.length; i++) {
175
+ const w = a[i];
176
+ if (w === '--workspaces' || w === '-ws')
177
+ all = true;
178
+ else if (w === '-w' || w === '--workspace' || w.startsWith('--workspace=')) {
179
+ const v = w.includes('=') ? w.slice(w.indexOf('=') + 1) : a[++i];
180
+ const s = v === undefined ? null : select(pkgs, v);
181
+ if (s === null)
182
+ return { unclear: `npm workspace ${v ?? ''}` };
183
+ picked = [...(picked ?? []), ...s];
184
+ }
185
+ else if (HARMLESS.has(w))
186
+ continue;
187
+ else if (w.startsWith('-'))
188
+ return all || picked ? { unclear: `npm ${w}` } : null;
189
+ else
190
+ rest.push(w);
191
+ }
192
+ if (!all && !picked)
193
+ return null;
194
+ if (rest[0] !== 'run' && rest[0] !== 'run-script')
195
+ return { unclear: 'npm: not run' };
196
+ const s = scriptAt(rest.slice(1));
197
+ if (!s)
198
+ return { unclear: 'npm: not one script' };
199
+ return { scripts: [s], pkgs: picked ?? pkgs };
200
+ }
201
+ if (tool === 'yarn') {
202
+ if (a[0] === 'workspaces' && a[1] === 'run') {
203
+ const s = scriptAt(a.slice(2));
204
+ return s ? { scripts: [s], pkgs } : { unclear: 'yarn workspaces run' };
205
+ }
206
+ if (a[0] === 'workspace' && a[1]) {
207
+ const s = scriptAt(a.slice(2));
208
+ const p = select(pkgs, a[1]);
209
+ return s && p ? { scripts: [s], pkgs: p } : { unclear: 'yarn workspace' };
210
+ }
211
+ if (a[0] === 'workspaces' && a[1] === 'foreach') {
212
+ const ok = new Set([
213
+ '-A',
214
+ '--all',
215
+ '-p',
216
+ '--parallel',
217
+ '-v',
218
+ '--verbose',
219
+ '-i',
220
+ '--interlaced',
221
+ '-t',
222
+ '--topological',
223
+ '-R',
224
+ '--recursive',
225
+ ]);
226
+ const rest = a.slice(2);
227
+ const i = rest.indexOf('run');
228
+ if (i < 0 || rest.slice(0, i).some((w) => !ok.has(w)))
229
+ return { unclear: 'yarn workspaces foreach' };
230
+ const s = scriptAt(rest.slice(i));
231
+ return s ? { scripts: [s], pkgs } : { unclear: 'yarn workspaces foreach' };
232
+ }
233
+ return null;
234
+ }
235
+ if (tool === 'bun') {
236
+ if (a[0] !== '--filter' || a[1] === undefined)
237
+ return null;
238
+ if (/[^\w@/.*-]/.test(a[1]))
239
+ return { unclear: `bun filter ${a[1]}` };
240
+ const re = nameGlob(a[1]);
241
+ const s = scriptAt(a.slice(2));
242
+ return s
243
+ ? { scripts: [s], pkgs: pkgs.filter((p) => p.name !== undefined && re.test(p.name)) }
244
+ : { unclear: 'bun --filter' };
245
+ }
246
+ if (tool === 'turbo' || tool === 'lerna') {
247
+ if (a[0] !== 'run')
248
+ return null;
249
+ const s = a.slice(1);
250
+ if (s.length === 0 || s.some((w) => !/^[\w:.-]+$/.test(w)))
251
+ return { unclear: `${tool} run` };
252
+ return { scripts: tool === 'lerna' ? s.slice(0, 1) : s, pkgs };
253
+ }
254
+ if (tool === 'nx') {
255
+ if (a[0] !== 'run-many')
256
+ return null;
257
+ const s = a.slice(1);
258
+ if ((s[0] !== '-t' && s[0] !== '--target' && s[0] !== '--targets') || s.length < 2)
259
+ return { unclear: 'nx run-many' };
260
+ const names = s.slice(1);
261
+ if (names.some((w) => !/^[\w:.-]+$/.test(w)))
262
+ return { unclear: 'nx run-many' };
263
+ return { scripts: names, pkgs };
264
+ }
265
+ return null;
266
+ }