@alxwlw/stack 1.0.1 → 1.1.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.
- package/canon/catalogs.json +3 -3
- package/package.json +1 -1
- package/schema.json +1 -1
- package/src/canon.ts +73 -0
- package/src/catalogs.ts +25 -69
- package/src/check.ts +45 -22
- package/src/cli.ts +9 -10
- package/src/deps.ts +8 -28
- package/src/files.ts +25 -65
- package/src/findings.ts +39 -0
- package/src/package-manager.ts +41 -0
- package/src/manifest.ts +0 -33
package/canon/catalogs.json
CHANGED
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
"dependency-cruiser": "18.1.0",
|
|
11
11
|
"vitest": "4.1.10",
|
|
12
12
|
"@playwright/test": "1.62.0",
|
|
13
|
-
"@alxwlw/stack": "1.0
|
|
14
|
-
"@alxwlw/oxlint-config": "1.0
|
|
15
|
-
"@alxwlw/tsconfig": "1.0
|
|
13
|
+
"@alxwlw/stack": "1.1.0",
|
|
14
|
+
"@alxwlw/oxlint-config": "1.1.0",
|
|
15
|
+
"@alxwlw/tsconfig": "1.1.0"
|
|
16
16
|
},
|
|
17
17
|
"libs": {
|
|
18
18
|
"@nestjs/core": "12.0.1",
|
package/package.json
CHANGED
package/schema.json
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
},
|
|
20
20
|
"exceptions": {
|
|
21
21
|
"type": "array",
|
|
22
|
-
"description": "
|
|
22
|
+
"description": "An exception holds its item back in both `stack check` (the finding is suppressed and reported as allowed) and `stack sync` (the item is left untouched). Each exception addresses exactly one canon file or exactly one catalog entry.",
|
|
23
23
|
"items": {
|
|
24
24
|
"type": "object",
|
|
25
25
|
"additionalProperties": false,
|
package/src/canon.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
import type { Profile, StackConfig } from './config.ts';
|
|
6
|
+
|
|
7
|
+
export type SyncStrategy = 'verbatim' | 'create-if-absent';
|
|
8
|
+
|
|
9
|
+
export interface CanonFile {
|
|
10
|
+
src: string;
|
|
11
|
+
dest: string;
|
|
12
|
+
appliesTo: Profile[];
|
|
13
|
+
strategy?: SyncStrategy;
|
|
14
|
+
/** Группа, включаемая через `with` в .stack.jsonc. Без группы файл обязателен всем. */
|
|
15
|
+
group?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type CanonCatalogs = Record<string, Record<string, string>>;
|
|
19
|
+
|
|
20
|
+
// Канон одного прогона как значение: уже отфильтрован под профиль и группы, содержимое файлов
|
|
21
|
+
// прочитано, пины node и pnpm вычислены. Правила и план принимают его и не знают, где лежит каталог.
|
|
22
|
+
export interface Canon {
|
|
23
|
+
files: { dest: string; content: string; strategy?: SyncStrategy }[];
|
|
24
|
+
catalogs: CanonCatalogs;
|
|
25
|
+
nodePin: string;
|
|
26
|
+
pnpmPin: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function canonDir(): string {
|
|
30
|
+
return join(dirname(fileURLToPath(import.meta.url)), '..', 'canon');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function loadManifest(dir: string = canonDir()): CanonFile[] {
|
|
34
|
+
const raw = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')) as {
|
|
35
|
+
files: CanonFile[];
|
|
36
|
+
};
|
|
37
|
+
return raw.files;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function filesFor(cfg: StackConfig, dir: string = canonDir()): CanonFile[] {
|
|
41
|
+
return loadManifest(dir).filter(
|
|
42
|
+
(f) => f.appliesTo.includes(cfg.profile) && (f.group == null || cfg.with.includes(f.group)),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function loadCatalogs(dir: string = canonDir()): CanonCatalogs {
|
|
47
|
+
return JSON.parse(readFileSync(join(dir, 'catalogs.json'), 'utf8')) as CanonCatalogs;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function loadCanon(cfg: StackConfig, dir: string = canonDir()): Canon {
|
|
51
|
+
const files = filesFor(cfg, dir).map((f) => ({
|
|
52
|
+
dest: f.dest,
|
|
53
|
+
content: readFileSync(join(dir, f.src), 'utf8'),
|
|
54
|
+
strategy: f.strategy,
|
|
55
|
+
}));
|
|
56
|
+
const all = loadCatalogs(dir);
|
|
57
|
+
const groups = ['dev', ...cfg.with.filter((g) => g !== 'dev')];
|
|
58
|
+
const catalogs = Object.fromEntries(
|
|
59
|
+
groups.filter((g) => g in all).map((g) => [g, all[g] as Record<string, string>]),
|
|
60
|
+
);
|
|
61
|
+
// Единственное место, где канон-файл читается как данные, а не копируется: пин node нужен
|
|
62
|
+
// правилу engines-node и пин pnpm — правилу package-manager, они одинаковы во всех профилях.
|
|
63
|
+
const prototools = files.find((f) => f.dest === '.prototools');
|
|
64
|
+
if (!prototools) {
|
|
65
|
+
throw new Error('canon manifest has no .prototools entry for profile ' + cfg.profile);
|
|
66
|
+
}
|
|
67
|
+
const pin = /^node\s*=\s*"([^"]+)"/m.exec(prototools.content);
|
|
68
|
+
if (!pin?.[1]) throw new Error('canon .prototools has no node pin');
|
|
69
|
+
// Пин pnpm нужен правилу package-manager: поле packageManager — второй источник версии pnpm.
|
|
70
|
+
const pnpm = /^pnpm\s*=\s*"([^"]+)"/m.exec(prototools.content);
|
|
71
|
+
if (!pnpm?.[1]) throw new Error('canon .prototools has no pnpm pin');
|
|
72
|
+
return { files, catalogs, nodePin: pin[1], pnpmPin: pnpm[1] };
|
|
73
|
+
}
|
package/src/catalogs.ts
CHANGED
|
@@ -3,18 +3,8 @@ import { join } from 'node:path';
|
|
|
3
3
|
|
|
4
4
|
import { parseDocument } from 'yaml';
|
|
5
5
|
|
|
6
|
-
import type {
|
|
7
|
-
import type {
|
|
8
|
-
import { canonDir } from './manifest.ts';
|
|
9
|
-
|
|
10
|
-
export type CanonCatalogs = Record<string, Record<string, string>>;
|
|
11
|
-
|
|
12
|
-
export interface CatalogChange {
|
|
13
|
-
group: string;
|
|
14
|
-
name: string;
|
|
15
|
-
from: string | undefined;
|
|
16
|
-
to: string;
|
|
17
|
-
}
|
|
6
|
+
import type { Canon } from './canon.ts';
|
|
7
|
+
import type { Drift } from './findings.ts';
|
|
18
8
|
|
|
19
9
|
const WORKSPACE_FILE = 'pnpm-workspace.yaml';
|
|
20
10
|
|
|
@@ -28,74 +18,40 @@ function displayValue(v: unknown): string {
|
|
|
28
18
|
return JSON.stringify(v);
|
|
29
19
|
}
|
|
30
20
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function catalogsFor(cfg: StackConfig, dir: string = canonDir()): CanonCatalogs {
|
|
36
|
-
const all = loadCatalogs(dir);
|
|
37
|
-
const groups = ['dev', ...cfg.with.filter((g) => g in all && g !== 'dev')];
|
|
38
|
-
return Object.fromEntries(
|
|
39
|
-
groups.filter((g) => all[g]).map((g) => [g, all[g] as Record<string, string>]),
|
|
40
|
-
);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function syncCatalogs(
|
|
44
|
-
repoRoot: string,
|
|
45
|
-
cfg: StackConfig,
|
|
46
|
-
dir: string = canonDir(),
|
|
47
|
-
): CatalogChange[] {
|
|
21
|
+
// Один проход и один предикат для check и sync — см. planFiles.
|
|
22
|
+
export function planCatalogs(repoRoot: string, canon: Canon): Drift[] {
|
|
48
23
|
const path = join(repoRoot, WORKSPACE_FILE);
|
|
49
24
|
if (!existsSync(path)) return [];
|
|
50
25
|
const doc = parseDocument(readFileSync(path, 'utf8'));
|
|
51
|
-
const
|
|
52
|
-
for (const [group, entries] of Object.entries(
|
|
26
|
+
const plan: Drift[] = [];
|
|
27
|
+
for (const [group, entries] of Object.entries(canon.catalogs)) {
|
|
53
28
|
for (const [name, version] of Object.entries(entries)) {
|
|
54
29
|
const current = doc.getIn(['catalogs', group, name]);
|
|
55
30
|
// YAML разбирает `typescript: 7` и `26.1` как числа — сравниваем строками.
|
|
56
31
|
if (current != null && displayValue(current) === version) continue;
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
group,
|
|
61
|
-
name,
|
|
62
|
-
from: current == null ? undefined : displayValue(current),
|
|
63
|
-
to: version,
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
// singleQuote: oxfmt (canon .oxfmtrc.jsonc) formats YAML with singleQuote:true, and this
|
|
68
|
-
// file's own pre-existing catalogs already use single quotes for scoped names. New
|
|
69
|
-
// scoped-package keys (@foo/bar isn't a plain-scalar-safe start char) default to double
|
|
70
|
-
// quotes otherwise, so a freshly-synced workspace fails `oxfmt --check` on its own output.
|
|
71
|
-
if (changes.length) writeFileSync(path, doc.toString({ singleQuote: true }));
|
|
72
|
-
return changes;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export function checkCatalogs(
|
|
76
|
-
repoRoot: string,
|
|
77
|
-
cfg: StackConfig,
|
|
78
|
-
dir: string = canonDir(),
|
|
79
|
-
): Finding[] {
|
|
80
|
-
const path = join(repoRoot, WORKSPACE_FILE);
|
|
81
|
-
if (!existsSync(path)) return [];
|
|
82
|
-
const doc = parseDocument(readFileSync(path, 'utf8'));
|
|
83
|
-
const findings: Finding[] = [];
|
|
84
|
-
for (const [group, entries] of Object.entries(catalogsFor(cfg, dir))) {
|
|
85
|
-
for (const [name, version] of Object.entries(entries)) {
|
|
86
|
-
const current = doc.getIn(['catalogs', group, name]);
|
|
87
|
-
if (current != null && displayValue(current) === version) continue;
|
|
88
|
-
const exception = cfg.exceptions.find((e) => e.catalog === group && e.name === name);
|
|
89
|
-
findings.push({
|
|
90
|
-
code: current == null ? 'catalog-missing' : 'catalog-drift',
|
|
32
|
+
const from = current == null ? undefined : displayValue(current);
|
|
33
|
+
plan.push({
|
|
34
|
+
code: from == null ? 'catalog-missing' : 'catalog-drift',
|
|
91
35
|
target: `catalogs.${group}.${name}`,
|
|
92
36
|
message:
|
|
93
|
-
|
|
37
|
+
from == null
|
|
94
38
|
? `catalog entry missing: expected ${version}`
|
|
95
|
-
: `${
|
|
96
|
-
|
|
39
|
+
: `${from} instead of ${version}`,
|
|
40
|
+
address: { catalog: group, name },
|
|
41
|
+
fix: `catalog ${group}.${name}: ${from ?? '—'} → ${version}`,
|
|
42
|
+
apply() {
|
|
43
|
+
// setIn создаёт недостающие узлы и не трогает соседей и их комментарии.
|
|
44
|
+
doc.setIn(['catalogs', group, name], version);
|
|
45
|
+
// singleQuote: oxfmt (canon .oxfmtrc.jsonc) formats YAML with singleQuote:true, and
|
|
46
|
+
// this file's own pre-existing catalogs already use single quotes for scoped names.
|
|
47
|
+
// New scoped-package keys (@foo/bar isn't a plain-scalar-safe start char) default to
|
|
48
|
+
// double quotes otherwise, so a freshly-synced workspace fails `oxfmt --check`.
|
|
49
|
+
// ponytail: doc общий на весь план, файл пишется на каждую запись; один flush в
|
|
50
|
+
// конце, если ~40 записей первого sync станут заметны.
|
|
51
|
+
writeFileSync(path, doc.toString({ singleQuote: true }));
|
|
52
|
+
},
|
|
97
53
|
});
|
|
98
54
|
}
|
|
99
55
|
}
|
|
100
|
-
return
|
|
56
|
+
return plan;
|
|
101
57
|
}
|
package/src/check.ts
CHANGED
|
@@ -1,27 +1,50 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
1
|
+
import type { Canon } from './canon.ts';
|
|
2
|
+
import { planCatalogs } from './catalogs.ts';
|
|
3
|
+
import type { Exception } from './config.ts';
|
|
3
4
|
import { checkDependabotIgnore, checkEnginesNode, checkInlineVersions } from './deps.ts';
|
|
4
|
-
import {
|
|
5
|
-
import type
|
|
6
|
-
import {
|
|
5
|
+
import { planFiles } from './files.ts';
|
|
6
|
+
import { applyExceptions, covers, type Drift, type Finding } from './findings.ts';
|
|
7
|
+
import { planPackageManager } from './package-manager.ts';
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
...
|
|
12
|
-
...
|
|
13
|
-
...
|
|
14
|
-
...checkDependabotIgnore(repoRoot, cfg),
|
|
9
|
+
// План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, packageManager.
|
|
10
|
+
export function planRepo(repoRoot: string, canon: Canon): Drift[] {
|
|
11
|
+
return [
|
|
12
|
+
...planFiles(repoRoot, canon),
|
|
13
|
+
...planCatalogs(repoRoot, canon),
|
|
14
|
+
...planPackageManager(repoRoot, canon),
|
|
15
15
|
];
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SyncResult {
|
|
19
|
+
applied: Drift[];
|
|
20
|
+
held: Finding[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// sync — тот же план, но удержанное исключением не применяется: иначе исключению после sync
|
|
24
|
+
// нечего покрывать, и следующий check краснеет на stale-exception. Исключение держит и check, и sync.
|
|
25
|
+
export function syncRepo(repoRoot: string, canon: Canon, exceptions: Exception[]): SyncResult {
|
|
26
|
+
const result: SyncResult = { applied: [], held: [] };
|
|
27
|
+
for (const d of planRepo(repoRoot, canon)) {
|
|
28
|
+
const e = exceptions.find((e) => covers(e, d));
|
|
29
|
+
if (e) {
|
|
30
|
+
result.held.push({ ...d, suppressedBy: e });
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
d.apply();
|
|
34
|
+
result.applied.push(d);
|
|
25
35
|
}
|
|
26
|
-
return
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Тот же план плюс правила «только отчёт» из deps.ts, пропущенные через исключения.
|
|
40
|
+
export function checkRepo(repoRoot: string, canon: Canon, exceptions: Exception[]): Finding[] {
|
|
41
|
+
return applyExceptions(
|
|
42
|
+
[
|
|
43
|
+
...planRepo(repoRoot, canon),
|
|
44
|
+
...checkInlineVersions(repoRoot, canon),
|
|
45
|
+
...checkEnginesNode(repoRoot, canon),
|
|
46
|
+
...checkDependabotIgnore(repoRoot),
|
|
47
|
+
],
|
|
48
|
+
exceptions,
|
|
49
|
+
);
|
|
27
50
|
}
|
package/src/cli.ts
CHANGED
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
import { existsSync } from 'node:fs';
|
|
3
3
|
import { parseArgs } from 'node:util';
|
|
4
4
|
|
|
5
|
-
import {
|
|
6
|
-
import { checkRepo } from './check.ts';
|
|
5
|
+
import { loadCanon } from './canon.ts';
|
|
6
|
+
import { checkRepo, syncRepo } from './check.ts';
|
|
7
7
|
import { type Profile, PROFILES, readStackConfig, StackConfigError } from './config.ts';
|
|
8
|
-
import { syncFiles } from './files.ts';
|
|
9
8
|
import { initConfig } from './init.ts';
|
|
10
9
|
|
|
11
10
|
function fail(message: string): never {
|
|
@@ -47,15 +46,15 @@ try {
|
|
|
47
46
|
console.log(`created ${path}`);
|
|
48
47
|
} else if (command === 'sync') {
|
|
49
48
|
const cfg = readStackConfig(repoRoot);
|
|
50
|
-
const
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
console.log(`canon ${
|
|
49
|
+
const { applied, held } = syncRepo(repoRoot, loadCanon(cfg), cfg.exceptions);
|
|
50
|
+
for (const f of held) {
|
|
51
|
+
console.warn(`allowed (${f.suppressedBy?.reason}): ${f.target} — ${f.message}`);
|
|
52
|
+
}
|
|
53
|
+
for (const d of applied) console.log(d.fix);
|
|
54
|
+
console.log(`canon ${applied.length === 0 ? 'already up to date' : 'applied'}`);
|
|
56
55
|
} else if (command === 'check') {
|
|
57
56
|
const cfg = readStackConfig(repoRoot);
|
|
58
|
-
const findings = checkRepo(repoRoot, cfg);
|
|
57
|
+
const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions);
|
|
59
58
|
const blocking = findings.filter((f) => !f.suppressedBy);
|
|
60
59
|
for (const f of findings.filter((f) => f.suppressedBy)) {
|
|
61
60
|
console.warn(`allowed (${f.suppressedBy?.reason}): ${f.target} — ${f.message}`);
|
package/src/deps.ts
CHANGED
|
@@ -4,28 +4,14 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { Glob } from 'bun';
|
|
5
5
|
import { parse as parseYaml } from 'yaml';
|
|
6
6
|
|
|
7
|
-
import {
|
|
8
|
-
import type { StackConfig } from './config.ts';
|
|
7
|
+
import type { Canon } from './canon.ts';
|
|
9
8
|
import type { Finding } from './findings.ts';
|
|
10
|
-
import { canonDir, filesFor } from './manifest.ts';
|
|
11
9
|
|
|
12
10
|
const SKIP = /node_modules|\.worktrees|\.moon\/cache|(^|\/)(dist|build)\//;
|
|
13
11
|
|
|
14
|
-
export function
|
|
15
|
-
const entry = filesFor(cfg, dir).find((f) => f.dest === '.prototools');
|
|
16
|
-
if (!entry) throw new Error('canon manifest has no .prototools entry for profile ' + cfg.profile);
|
|
17
|
-
const pin = /^node\s*=\s*"([^"]+)"/m.exec(readFileSync(join(dir, entry.src), 'utf8'));
|
|
18
|
-
if (!pin?.[1]) throw new Error('canon .prototools has no node pin');
|
|
19
|
-
return pin[1];
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function checkInlineVersions(
|
|
23
|
-
repoRoot: string,
|
|
24
|
-
cfg: StackConfig,
|
|
25
|
-
dir: string = canonDir(),
|
|
26
|
-
): Finding[] {
|
|
12
|
+
export function checkInlineVersions(repoRoot: string, canon: Canon): Finding[] {
|
|
27
13
|
if (!existsSync(join(repoRoot, 'pnpm-workspace.yaml'))) return [];
|
|
28
|
-
const canonNames = new Set(Object.values(
|
|
14
|
+
const canonNames = new Set(Object.values(canon.catalogs).flatMap((e) => Object.keys(e)));
|
|
29
15
|
const findings: Finding[] = [];
|
|
30
16
|
for (const file of new Glob('**/package.json').scanSync({ cwd: repoRoot })) {
|
|
31
17
|
if (SKIP.test(file)) continue;
|
|
@@ -45,12 +31,11 @@ export function checkInlineVersions(
|
|
|
45
31
|
if (!canonNames.has(name) || spec.startsWith('catalog:') || spec.startsWith('workspace:')) {
|
|
46
32
|
continue;
|
|
47
33
|
}
|
|
48
|
-
const exception = cfg.exceptions.find((e) => e.name === name);
|
|
49
34
|
findings.push({
|
|
50
35
|
code: 'inline-version',
|
|
51
36
|
target: `${file}:${name}`,
|
|
52
37
|
message: `${name} is declared as "${spec}" instead of catalog:`,
|
|
53
|
-
|
|
38
|
+
address: { name },
|
|
54
39
|
});
|
|
55
40
|
}
|
|
56
41
|
}
|
|
@@ -58,11 +43,7 @@ export function checkInlineVersions(
|
|
|
58
43
|
return findings;
|
|
59
44
|
}
|
|
60
45
|
|
|
61
|
-
export function checkEnginesNode(
|
|
62
|
-
repoRoot: string,
|
|
63
|
-
cfg: StackConfig,
|
|
64
|
-
dir: string = canonDir(),
|
|
65
|
-
): Finding[] {
|
|
46
|
+
export function checkEnginesNode(repoRoot: string, canon: Canon): Finding[] {
|
|
66
47
|
const path = join(repoRoot, 'package.json');
|
|
67
48
|
if (!existsSync(path)) return [];
|
|
68
49
|
let pkg: { engines?: { node?: string } };
|
|
@@ -79,13 +60,12 @@ export function checkEnginesNode(
|
|
|
79
60
|
}
|
|
80
61
|
const range = pkg.engines?.node;
|
|
81
62
|
if (!range) return [];
|
|
82
|
-
|
|
83
|
-
if (Bun.semver.satisfies(pin, range)) return [];
|
|
63
|
+
if (Bun.semver.satisfies(canon.nodePin, range)) return [];
|
|
84
64
|
return [
|
|
85
65
|
{
|
|
86
66
|
code: 'engines-node',
|
|
87
67
|
target: 'package.json:engines.node',
|
|
88
|
-
message: `"${range}" doesn't cover the canon pin ${
|
|
68
|
+
message: `"${range}" doesn't cover the canon pin ${canon.nodePin} — proto will rewrite .prototools from engines`,
|
|
89
69
|
},
|
|
90
70
|
];
|
|
91
71
|
}
|
|
@@ -109,7 +89,7 @@ function ignoresAlxwlw(doc: unknown): boolean {
|
|
|
109
89
|
});
|
|
110
90
|
}
|
|
111
91
|
|
|
112
|
-
export function checkDependabotIgnore(repoRoot: string
|
|
92
|
+
export function checkDependabotIgnore(repoRoot: string): Finding[] {
|
|
113
93
|
if (!existsSync(join(repoRoot, 'pnpm-workspace.yaml'))) return [];
|
|
114
94
|
const path = join(repoRoot, '.github/dependabot.yml');
|
|
115
95
|
if (!existsSync(path)) return [];
|
package/src/files.ts
CHANGED
|
@@ -1,75 +1,35 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { dirname, join } from 'node:path';
|
|
3
3
|
|
|
4
|
-
import type {
|
|
5
|
-
import type {
|
|
6
|
-
import { canonDir, filesFor } from './manifest.ts';
|
|
4
|
+
import type { Canon } from './canon.ts';
|
|
5
|
+
import type { Drift } from './findings.ts';
|
|
7
6
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
export function syncFiles(
|
|
14
|
-
repoRoot: string,
|
|
15
|
-
cfg: StackConfig,
|
|
16
|
-
dir: string = canonDir(),
|
|
17
|
-
): FileChange[] {
|
|
18
|
-
const changes: FileChange[] = [];
|
|
19
|
-
for (const f of filesFor(cfg, dir)) {
|
|
7
|
+
// Один проход и один предикат дрейфа для check и sync: check печатает план, sync его применяет,
|
|
8
|
+
// поэтому «после sync — check зелёный» для файлов выполняется по построению.
|
|
9
|
+
export function planFiles(repoRoot: string, canon: Canon): Drift[] {
|
|
10
|
+
const plan: Drift[] = [];
|
|
11
|
+
for (const f of canon.files) {
|
|
20
12
|
const target = join(repoRoot, f.dest);
|
|
21
|
-
const want = readFileSync(join(dir, f.src), 'utf8');
|
|
22
13
|
const exists = existsSync(target);
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
mkdirSync(dirname(target), { recursive: true });
|
|
30
|
-
writeFileSync(target, want);
|
|
31
|
-
changes.push({ dest: f.dest, action: 'seeded' });
|
|
32
|
-
continue;
|
|
33
|
-
}
|
|
34
|
-
if (exists && readFileSync(target, 'utf8') === want) {
|
|
35
|
-
changes.push({ dest: f.dest, action: 'unchanged' });
|
|
14
|
+
// create-if-absent принадлежит репозиторию после первого засева: расхождением считается
|
|
15
|
+
// только отсутствие, содержимое не трогаем.
|
|
16
|
+
if (
|
|
17
|
+
exists &&
|
|
18
|
+
(f.strategy === 'create-if-absent' || readFileSync(target, 'utf8') === f.content)
|
|
19
|
+
) {
|
|
36
20
|
continue;
|
|
37
21
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
): Finding[] {
|
|
50
|
-
const findings: Finding[] = [];
|
|
51
|
-
for (const f of filesFor(cfg, dir)) {
|
|
52
|
-
const target = join(repoRoot, f.dest);
|
|
53
|
-
const exception = cfg.exceptions.find((e) => e.file === f.dest);
|
|
54
|
-
if (!existsSync(target)) {
|
|
55
|
-
findings.push({
|
|
56
|
-
code: 'file-missing',
|
|
57
|
-
target: f.dest,
|
|
58
|
-
message: `canon file missing: ${f.dest}`,
|
|
59
|
-
...(exception ? { suppressedBy: exception } : {}),
|
|
60
|
-
});
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
// create-if-absent принадлежит репозиторию: расхождением считается только отсутствие.
|
|
64
|
-
if (f.strategy === 'create-if-absent') continue;
|
|
65
|
-
if (readFileSync(target, 'utf8') !== readFileSync(join(dir, f.src), 'utf8')) {
|
|
66
|
-
findings.push({
|
|
67
|
-
code: 'file-drift',
|
|
68
|
-
target: f.dest,
|
|
69
|
-
message: `${f.dest} differs from canon`,
|
|
70
|
-
...(exception ? { suppressedBy: exception } : {}),
|
|
71
|
-
});
|
|
72
|
-
}
|
|
22
|
+
plan.push({
|
|
23
|
+
code: exists ? 'file-drift' : 'file-missing',
|
|
24
|
+
target: f.dest,
|
|
25
|
+
message: exists ? `${f.dest} differs from canon` : `canon file missing: ${f.dest}`,
|
|
26
|
+
address: { file: f.dest },
|
|
27
|
+
fix: `${f.strategy === 'create-if-absent' ? 'seeded' : 'updated'} ${f.dest}`,
|
|
28
|
+
apply() {
|
|
29
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
30
|
+
writeFileSync(target, f.content);
|
|
31
|
+
},
|
|
32
|
+
});
|
|
73
33
|
}
|
|
74
|
-
return
|
|
34
|
+
return plan;
|
|
75
35
|
}
|
package/src/findings.ts
CHANGED
|
@@ -7,6 +7,7 @@ export type FindingCode =
|
|
|
7
7
|
| 'catalog-missing'
|
|
8
8
|
| 'inline-version'
|
|
9
9
|
| 'engines-node'
|
|
10
|
+
| 'package-manager'
|
|
10
11
|
| 'dependabot-ignore'
|
|
11
12
|
| 'unreadable-file'
|
|
12
13
|
| 'stale-exception';
|
|
@@ -15,5 +16,43 @@ export interface Finding {
|
|
|
15
16
|
code: FindingCode;
|
|
16
17
|
target: string;
|
|
17
18
|
message: string;
|
|
19
|
+
// Что в этой находке может адресовать исключение из .stack.jsonc: файл — его dest, запись
|
|
20
|
+
// каталога — catalog+name, inline-version — name. Находка без адреса не подавляется никогда.
|
|
21
|
+
address?: Omit<Exception, 'reason'>;
|
|
18
22
|
suppressedBy?: Exception;
|
|
19
23
|
}
|
|
24
|
+
|
|
25
|
+
// Расхождение, которое sync умеет закрыть: находка плюс действие. check печатает message,
|
|
26
|
+
// sync — fix после apply(). Правила из deps.ts дают Finding без действия — только отчёт.
|
|
27
|
+
export interface Drift extends Finding {
|
|
28
|
+
fix: string;
|
|
29
|
+
apply(): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function covers(e: Exception, f: Finding): boolean {
|
|
33
|
+
const a = f.address;
|
|
34
|
+
if (!a) return false;
|
|
35
|
+
if (e.file != null) return a.file === e.file;
|
|
36
|
+
// Исключение catalog+name гасит не только свою запись каталога, но и inline-version того же
|
|
37
|
+
// пакета в любом package.json: пакет, который держат на своей версии, объявляют напрямую, а не
|
|
38
|
+
// через catalog:, и одно оправдание покрывает оба симптома одной причины (fixtures/node: knip).
|
|
39
|
+
return a.name === e.name && (a.catalog == null || a.catalog === e.catalog);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Правила отдают сырые находки; здесь — единственное место, где исключение сопоставляется с
|
|
43
|
+
// находкой, и здесь же исключение без находки становится stale-exception.
|
|
44
|
+
export function applyExceptions(findings: Finding[], exceptions: Exception[]): Finding[] {
|
|
45
|
+
const suppressed = findings.map((f) => {
|
|
46
|
+
const e = exceptions.find((e) => covers(e, f));
|
|
47
|
+
return e ? { ...f, suppressedBy: e } : f;
|
|
48
|
+
});
|
|
49
|
+
// Исключение без находки — мёртвая запись: канон уже изменился, а оправдание осталось.
|
|
50
|
+
const stale = exceptions
|
|
51
|
+
.filter((e) => !findings.some((f) => covers(e, f)))
|
|
52
|
+
.map<Finding>((e) => ({
|
|
53
|
+
code: 'stale-exception',
|
|
54
|
+
target: e.file ?? `catalogs.${e.catalog}.${e.name}`,
|
|
55
|
+
message: `exception no longer covers anything: ${e.reason}`,
|
|
56
|
+
}));
|
|
57
|
+
return [...suppressed, ...stale];
|
|
58
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { applyEdits, modify } from 'jsonc-parser';
|
|
5
|
+
|
|
6
|
+
import type { Canon } from './canon.ts';
|
|
7
|
+
import type { Drift } from './findings.ts';
|
|
8
|
+
|
|
9
|
+
// package.json#packageManager — второй источник версии pnpm рядом с .prototools: pnpm сам
|
|
10
|
+
// переключается на версию из поля, и пин канона молча перестаёт действовать. Держим поле на пине
|
|
11
|
+
// канона. Адрес — .prototools: одно исключение удерживает оба симптома одного решения.
|
|
12
|
+
export function planPackageManager(repoRoot: string, canon: Canon): Drift[] {
|
|
13
|
+
const path = join(repoRoot, 'package.json');
|
|
14
|
+
if (!existsSync(path)) return [];
|
|
15
|
+
const text = readFileSync(path, 'utf8');
|
|
16
|
+
let current: unknown;
|
|
17
|
+
try {
|
|
18
|
+
current = (JSON.parse(text) as { packageManager?: unknown }).packageManager;
|
|
19
|
+
} catch {
|
|
20
|
+
// Нечитаемый package.json — находка unreadable-file у checkEnginesNode, не здесь.
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
if (typeof current !== 'string' || !current.startsWith('pnpm@')) return [];
|
|
24
|
+
// `pnpm@11.15.0+sha512.…` — хэш относится к той же версии, сравниваем только её.
|
|
25
|
+
if (current.slice('pnpm@'.length).split('+')[0] === canon.pnpmPin) return [];
|
|
26
|
+
const want = `pnpm@${canon.pnpmPin}`;
|
|
27
|
+
return [
|
|
28
|
+
{
|
|
29
|
+
code: 'package-manager',
|
|
30
|
+
target: 'package.json:packageManager',
|
|
31
|
+
message: `"${current}" instead of "${want}" — pnpm would switch to it and bypass .prototools`,
|
|
32
|
+
address: { file: '.prototools' },
|
|
33
|
+
fix: `package.json packageManager: ${current} → ${want}`,
|
|
34
|
+
apply() {
|
|
35
|
+
// modify+applyEdits меняет только значение поля: отступы и порядок ключей остаются.
|
|
36
|
+
const now = readFileSync(path, 'utf8');
|
|
37
|
+
writeFileSync(path, applyEdits(now, modify(now, ['packageManager'], want, {})));
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
];
|
|
41
|
+
}
|
package/src/manifest.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs';
|
|
2
|
-
import { dirname, join } from 'node:path';
|
|
3
|
-
import { fileURLToPath } from 'node:url';
|
|
4
|
-
|
|
5
|
-
import type { Profile, StackConfig } from './config.ts';
|
|
6
|
-
|
|
7
|
-
export type SyncStrategy = 'verbatim' | 'create-if-absent';
|
|
8
|
-
|
|
9
|
-
export interface CanonFile {
|
|
10
|
-
src: string;
|
|
11
|
-
dest: string;
|
|
12
|
-
appliesTo: Profile[];
|
|
13
|
-
strategy?: SyncStrategy;
|
|
14
|
-
/** Группа, включаемая через `with` в .stack.jsonc. Без группы файл обязателен всем. */
|
|
15
|
-
group?: string;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function canonDir(): string {
|
|
19
|
-
return join(dirname(fileURLToPath(import.meta.url)), '..', 'canon');
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function loadManifest(dir: string = canonDir()): CanonFile[] {
|
|
23
|
-
const raw = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')) as {
|
|
24
|
-
files: CanonFile[];
|
|
25
|
-
};
|
|
26
|
-
return raw.files;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export function filesFor(cfg: StackConfig, dir: string = canonDir()): CanonFile[] {
|
|
30
|
-
return loadManifest(dir).filter(
|
|
31
|
-
(f) => f.appliesTo.includes(cfg.profile) && (f.group == null || cfg.with.includes(f.group)),
|
|
32
|
-
);
|
|
33
|
-
}
|