@alxwlw/stack 1.16.0 → 1.17.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/canon/files/oxfmtrc.jsonc +4 -1
- package/canon/files/prototools +1 -1
- package/package.json +2 -1
- package/schema.json +1 -1
- package/src/canon.ts +18 -5
- package/src/check.ts +53 -15
- package/src/cli.ts +61 -3
- package/src/exceptions.ts +10 -0
- package/src/findings.ts +14 -2
- package/src/moon-toolchains.ts +15 -1
- package/src/own-packages.ts +39 -0
- package/src/release-age.ts +8 -7
- package/src/repo-rules-rule.ts +51 -0
- package/src/repo-rules.ts +144 -0
- package/src/repo.ts +50 -8
- package/src/seed-extends.ts +97 -0
- package/src/sync-pr.ts +31 -17
- package/src/toolchain-pins-rule.ts +56 -0
- package/src/toolchain-pins.ts +179 -0
package/canon/catalogs.json
CHANGED
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
"dependency-cruiser": "18.8.0",
|
|
11
11
|
"vitest": "5.1.0",
|
|
12
12
|
"@playwright/test": "1.65.1",
|
|
13
|
-
"@alxwlw/stack": "1.
|
|
14
|
-
"@alxwlw/oxlint-config": "1.
|
|
15
|
-
"@alxwlw/tsconfig": "1.
|
|
13
|
+
"@alxwlw/stack": "1.17.0",
|
|
14
|
+
"@alxwlw/oxlint-config": "1.17.0",
|
|
15
|
+
"@alxwlw/tsconfig": "1.17.0"
|
|
16
16
|
},
|
|
17
17
|
"libs": {
|
|
18
18
|
"@nestjs/core": "12.5.1",
|
|
@@ -19,5 +19,8 @@
|
|
|
19
19
|
|
|
20
20
|
// TOML belongs to gitleaks and uv, not this formatter: gitleaks-canon.toml's rules are
|
|
21
21
|
// regex literals inside '''...''' blocks, and a formatter has no business rewriting them.
|
|
22
|
-
|
|
22
|
+
// The two baselines are written by the canon's own tools (repo-rules, stack peers-baseline) in
|
|
23
|
+
// their own layout: formatting them would turn every rewrite into a format failure.
|
|
24
|
+
// Lockfiles need no entry — oxfmt always skips pnpm-lock.yaml and its kin.
|
|
25
|
+
"ignorePatterns": ["**/*.toml", ".repo-rules-baseline.json", ".stack-peers-baseline.json"],
|
|
23
26
|
}
|
package/canon/files/prototools
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxwlw/stack",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.17.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
"provenance": true
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
+
"@alxwlw/repo-rules": "1.17.0",
|
|
25
26
|
"json5": "^2.2.3",
|
|
26
27
|
"jsonc-parser": "^3.3.1",
|
|
27
28
|
"yaml": "^2.9.1"
|
package/schema.json
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"description": "Opt-in canon groups. \"renovate\" is deprecated and does nothing: Renovate is the canon's dependency bot for every profile.",
|
|
15
15
|
"items": {
|
|
16
16
|
"type": "string",
|
|
17
|
-
"enum": ["depcruise", "knip", "libs", "moon-tasks", "peers", "renovate"]
|
|
17
|
+
"enum": ["depcruise", "knip", "libs", "moon-tasks", "peers", "renovate", "repo-rules"]
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
20
|
"exceptions": {
|
package/src/canon.ts
CHANGED
|
@@ -3,6 +3,8 @@ import { dirname, join } from 'node:path';
|
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
|
|
5
5
|
import { type Profile, PROFILES, type StackConfig, StackConfigError } from './config.ts';
|
|
6
|
+
import { ownManifest, ownPackages, type StackManifest } from './own-packages.ts';
|
|
7
|
+
import type { Wanted } from './registry.ts';
|
|
6
8
|
|
|
7
9
|
export const SYNC_STRATEGIES = ['verbatim', 'create-if-absent'] as const;
|
|
8
10
|
export type SyncStrategy = (typeof SYNC_STRATEGIES)[number];
|
|
@@ -122,6 +124,8 @@ export interface Canon {
|
|
|
122
124
|
pins: Pins;
|
|
123
125
|
/** Включённые через with группы правил, в порядке RULE_GROUPS. */
|
|
124
126
|
rules: RuleGroup[];
|
|
127
|
+
/** Свои пакеты: приходят потребителю с каналом, прямо или зависимостью stack. */
|
|
128
|
+
ownPackages: readonly Wanted[];
|
|
125
129
|
}
|
|
126
130
|
|
|
127
131
|
// Пины инструментов из .prototools канона: node и pnpm обязательны, прочие строки верхнего уровня допустимы.
|
|
@@ -139,7 +143,7 @@ export function canonDir(): string {
|
|
|
139
143
|
const DEPRECATED_GROUPS: readonly string[] = ['renovate'];
|
|
140
144
|
|
|
141
145
|
// Группа правила включает правило `stack check`, файлов и каталогов не даёт.
|
|
142
|
-
export const RULE_GROUPS = ['peers'] as const;
|
|
146
|
+
export const RULE_GROUPS = ['peers', 'repo-rules'] as const;
|
|
143
147
|
export type RuleGroup = (typeof RULE_GROUPS)[number];
|
|
144
148
|
|
|
145
149
|
export interface CanonGroups {
|
|
@@ -155,9 +159,12 @@ export interface CanonSource {
|
|
|
155
159
|
entries: readonly (CanonFile & { content: string })[];
|
|
156
160
|
catalogs: CanonCatalogs;
|
|
157
161
|
groups: CanonGroups;
|
|
162
|
+
/** package.json самого stack: его зависимости — свои пакеты, пришедшие транзитивно. */
|
|
163
|
+
manifest: StackManifest;
|
|
158
164
|
}
|
|
159
165
|
|
|
160
|
-
// Единственное место, где canon/
|
|
166
|
+
// Единственное место, где canon/ и package.json пакета читаются с диска: manifest.json и catalogs.json
|
|
167
|
+
// по разу, каждый src по разу, package.json пакета один раз (не зависит от dir).
|
|
161
168
|
// Имена групп: файловые — поле group манифеста, каталожные — ключи catalogs.json кроме dev, устаревшие и
|
|
162
169
|
// группы правил — константы этого модуля.
|
|
163
170
|
export function readCanonSource(dir: string = canonDir()): CanonSource {
|
|
@@ -173,7 +180,7 @@ export function readCanonSource(dir: string = canonDir()): CanonSource {
|
|
|
173
180
|
deprecated: DEPRECATED_GROUPS,
|
|
174
181
|
rules: RULE_GROUPS,
|
|
175
182
|
};
|
|
176
|
-
return { entries, catalogs, groups };
|
|
183
|
+
return { entries, catalogs, groups, manifest: ownManifest() };
|
|
177
184
|
}
|
|
178
185
|
|
|
179
186
|
// Все имена, допустимые в `with`: файловые, каталожные, устаревшие и группы правил — без повторов,
|
|
@@ -227,7 +234,13 @@ export function canonFor(source: CanonSource, cfg: StackConfig): Canon {
|
|
|
227
234
|
// Пин pnpm нужен правилу package-manager: поле packageManager — второй источник версии pnpm.
|
|
228
235
|
if (!pnpm) throw new Error('canon .prototools has no pnpm pin');
|
|
229
236
|
const rules = RULE_GROUPS.filter((g) => cfg.with.includes(g));
|
|
230
|
-
return {
|
|
237
|
+
return {
|
|
238
|
+
files,
|
|
239
|
+
catalogs,
|
|
240
|
+
pins: { ...rest, node, pnpm },
|
|
241
|
+
rules,
|
|
242
|
+
ownPackages: ownPackages(source.catalogs.dev, source.manifest),
|
|
243
|
+
};
|
|
231
244
|
}
|
|
232
245
|
|
|
233
246
|
export function loadCanon(cfg: StackConfig, dir: string = canonDir()): Canon {
|
|
@@ -235,7 +248,7 @@ export function loadCanon(cfg: StackConfig, dir: string = canonDir()): Canon {
|
|
|
235
248
|
}
|
|
236
249
|
|
|
237
250
|
// Строковые значения верхнего уровня .prototools; таблица [plugins] и нестроковые значения — не пины.
|
|
238
|
-
function parsePins(prototools: string): Record<string, string> {
|
|
251
|
+
export function parsePins(prototools: string): Record<string, string> {
|
|
239
252
|
const parsed = Bun.TOML.parse(prototools) as Record<string, unknown>;
|
|
240
253
|
return Object.fromEntries(
|
|
241
254
|
Object.entries(parsed).filter((e): e is [string, string] => typeof e[1] === 'string'),
|
package/src/check.ts
CHANGED
|
@@ -10,70 +10,108 @@ import {
|
|
|
10
10
|
import { allowedLine, type Exception, type Held, isHeld, resolve } from './exceptions.ts';
|
|
11
11
|
import { planFiles } from './files.ts';
|
|
12
12
|
import type { Drift, Finding } from './findings.ts';
|
|
13
|
-
import { checkMoonToolchains } from './moon-toolchains.ts';
|
|
13
|
+
import { checkMoonToolchains, checkMoonV1Toolchain } from './moon-toolchains.ts';
|
|
14
14
|
import { checkMoonDefaultBranch, planMoonDefaultBranch } from './moon-workspace.ts';
|
|
15
15
|
import { planPackageManager } from './package-manager.ts';
|
|
16
16
|
import { type PeersOutcome, peersOutcome, type PeersReader } from './peers.ts';
|
|
17
17
|
import { checkPeers } from './peers-rule.ts';
|
|
18
18
|
import { planReleaseAgeExcludes } from './release-age.ts';
|
|
19
19
|
import { loadRepo, LOCKFILE, type Repo } from './repo.ts';
|
|
20
|
+
import { readRepoRules, type RepoRulesOutcome, type RepoRulesPort } from './repo-rules.ts';
|
|
21
|
+
import { checkRepoRules, repoRulesNotes } from './repo-rules-rule.ts';
|
|
22
|
+
import { checkSeedExtends } from './seed-extends.ts';
|
|
23
|
+
import { planToolchainPins } from './toolchain-pins-rule.ts';
|
|
20
24
|
|
|
21
25
|
// План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, release-age,
|
|
22
|
-
// packageManager, ветка по умолчанию moon
|
|
23
|
-
|
|
26
|
+
// packageManager, ветка по умолчанию moon, копии пинов тулчейна. Правки одного файла друг от друга не
|
|
27
|
+
// зависят: sync применяет любое их подмножество. Исключения нужны правилу копий пинов: удержанный
|
|
28
|
+
// .prototools меняет, с какими пинами оно сверяется; сами находки гасит resolve.
|
|
29
|
+
export function plan(repo: Repo, canon: Canon, exceptions: readonly Exception[] = []): Drift[] {
|
|
24
30
|
return [
|
|
25
31
|
...planFiles(repo, canon),
|
|
26
32
|
...planCatalogs(repo, canon),
|
|
27
33
|
...planReleaseAgeExcludes(repo, canon),
|
|
28
34
|
...planPackageManager(repo, canon),
|
|
29
35
|
...planMoonDefaultBranch(repo),
|
|
36
|
+
...planToolchainPins(repo, canon, exceptions),
|
|
30
37
|
];
|
|
31
38
|
}
|
|
32
39
|
|
|
33
|
-
// Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts и moon,
|
|
34
|
-
//
|
|
35
|
-
// исключения. peers — исход `pnpm peers check`,
|
|
40
|
+
// Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts, засевы и moon,
|
|
41
|
+
// правила групп peers и repo-rules, если они включены (в этом порядке); затем протухшие исключения.
|
|
42
|
+
// Все они проходят через исключения. peers — исход `pnpm peers check`, repoRules — исход двух вызовов
|
|
43
|
+
// repo-rules; оба получает checkRepo.
|
|
36
44
|
export function check(
|
|
37
45
|
repo: Repo,
|
|
38
46
|
canon: Canon,
|
|
39
47
|
exceptions: Exception[],
|
|
40
48
|
peers?: PeersOutcome,
|
|
49
|
+
repoRules?: RepoRulesOutcome,
|
|
41
50
|
): Finding[] {
|
|
42
51
|
const r = resolve(
|
|
43
52
|
[
|
|
44
|
-
...plan(repo, canon),
|
|
53
|
+
...plan(repo, canon, exceptions),
|
|
45
54
|
...repo.unreadable,
|
|
46
55
|
...checkInlineVersions(repo, canon),
|
|
47
56
|
...checkEnginesNode(repo, canon),
|
|
48
57
|
...checkRenovatePreset(repo),
|
|
49
58
|
...checkDependabot(repo),
|
|
59
|
+
...checkSeedExtends(repo, canon),
|
|
50
60
|
...checkMoonToolchains(repo, canon),
|
|
61
|
+
...checkMoonV1Toolchain(repo),
|
|
51
62
|
...checkMoonDefaultBranch(repo),
|
|
52
63
|
...(canon.rules.includes('peers') ? checkPeers(repo, peers) : []),
|
|
64
|
+
...(canon.rules.includes('repo-rules') ? checkRepoRules(repoRules) : []),
|
|
53
65
|
],
|
|
54
66
|
exceptions,
|
|
55
67
|
);
|
|
56
68
|
return [...r.findings, ...r.stale];
|
|
57
69
|
}
|
|
58
70
|
|
|
59
|
-
export function planRepo(
|
|
60
|
-
|
|
71
|
+
export function planRepo(
|
|
72
|
+
repoRoot: string,
|
|
73
|
+
canon: Canon,
|
|
74
|
+
exceptions: readonly Exception[] = [],
|
|
75
|
+
): Drift[] {
|
|
76
|
+
return plan(loadRepo(repoRoot, canon), canon, exceptions);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Порты `checkRepo`: каждый нужен только своей группе. */
|
|
80
|
+
export interface CheckPorts {
|
|
81
|
+
peers?: PeersReader;
|
|
82
|
+
repoRules?: RepoRulesPort;
|
|
83
|
+
}
|
|
84
|
+
/** Итог check: находки (блокируют, если не удержаны) и пометки (выход не меняют). */
|
|
85
|
+
export interface CheckReport {
|
|
86
|
+
findings: Finding[];
|
|
87
|
+
notes: string[];
|
|
61
88
|
}
|
|
62
89
|
|
|
63
90
|
// pnpm запускается, только если группа peers включена и лок есть: без лока правило отвечает само.
|
|
91
|
+
// repo-rules — только если включена группа: два вызова через порт, пометки идут отдельно от находок.
|
|
64
92
|
export function checkRepo(
|
|
65
93
|
repoRoot: string,
|
|
66
94
|
canon: Canon,
|
|
67
95
|
exceptions: Exception[],
|
|
68
|
-
|
|
69
|
-
):
|
|
96
|
+
ports: CheckPorts = {},
|
|
97
|
+
): CheckReport {
|
|
70
98
|
const repo = loadRepo(repoRoot, canon);
|
|
71
99
|
let peers: PeersOutcome | undefined;
|
|
72
100
|
if (canon.rules.includes('peers') && repo.paths.has(LOCKFILE)) {
|
|
73
|
-
if (
|
|
74
|
-
peers = peersOutcome(
|
|
101
|
+
if (ports.peers === undefined) throw new Error('checkRepo: peers group needs a PeersReader');
|
|
102
|
+
peers = peersOutcome(ports.peers(repoRoot));
|
|
103
|
+
}
|
|
104
|
+
let repoRules: RepoRulesOutcome | undefined;
|
|
105
|
+
if (canon.rules.includes('repo-rules')) {
|
|
106
|
+
if (ports.repoRules === undefined) {
|
|
107
|
+
throw new Error('checkRepo: repo-rules group needs a RepoRulesPort');
|
|
108
|
+
}
|
|
109
|
+
repoRules = readRepoRules(repoRoot, ports.repoRules);
|
|
75
110
|
}
|
|
76
|
-
return
|
|
111
|
+
return {
|
|
112
|
+
findings: check(repo, canon, exceptions, peers, repoRules),
|
|
113
|
+
notes: repoRulesNotes(repoRules),
|
|
114
|
+
};
|
|
77
115
|
}
|
|
78
116
|
|
|
79
117
|
export interface SyncResult {
|
|
@@ -87,7 +125,7 @@ export interface SyncResult {
|
|
|
87
125
|
export function syncRepo(repoRoot: string, canon: Canon, exceptions: Exception[]): SyncResult {
|
|
88
126
|
const repo = loadRepo(repoRoot, canon);
|
|
89
127
|
const result: SyncResult = { applied: [], held: [] };
|
|
90
|
-
for (const d of resolve(plan(repo, canon), exceptions).findings) {
|
|
128
|
+
for (const d of resolve(plan(repo, canon, exceptions), exceptions).findings) {
|
|
91
129
|
if (isHeld(d)) result.held.push(d);
|
|
92
130
|
else result.applied.push(d);
|
|
93
131
|
}
|
package/src/cli.ts
CHANGED
|
@@ -3,6 +3,8 @@ import { spawnSync } from 'node:child_process';
|
|
|
3
3
|
import { existsSync } from 'node:fs';
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
5
|
|
|
6
|
+
import { main as repoRulesMain } from '@alxwlw/repo-rules';
|
|
7
|
+
|
|
6
8
|
import { assertKnownGroups, loadCanon, readCanonSource } from './canon.ts';
|
|
7
9
|
import { checkRepo, syncOutput, syncRepo } from './check.ts';
|
|
8
10
|
import { type Profile, PROFILES, readStackConfig, StackConfigError } from './config.ts';
|
|
@@ -10,10 +12,12 @@ import { allowedLine, isHeld } from './exceptions.ts';
|
|
|
10
12
|
import { type Finding, isDrift } from './findings.ts';
|
|
11
13
|
import { ghGitHub } from './gh.ts';
|
|
12
14
|
import { initConfig } from './init.ts';
|
|
15
|
+
import { ownVersion } from './own-packages.ts';
|
|
13
16
|
import type { PeersReader } from './peers.ts';
|
|
14
17
|
import { peersBaseline } from './peers-baseline.ts';
|
|
15
18
|
import { npmRegistryReader } from './registry.ts';
|
|
16
|
-
import
|
|
19
|
+
import type { RepoRulesReader } from './repo-rules.ts';
|
|
20
|
+
import { type RunProcess, SYNC_PR_WAIT, syncPr, withoutGhToken } from './sync-pr.ts';
|
|
17
21
|
|
|
18
22
|
function fail(message: string): never {
|
|
19
23
|
console.error(message);
|
|
@@ -84,10 +88,59 @@ const pnpmPeers: PeersReader = (cwd) => {
|
|
|
84
88
|
return { status: r.status, signal: r.signal, stdout: r.stdout, stderr: r.stderr };
|
|
85
89
|
};
|
|
86
90
|
|
|
91
|
+
// Боевой adapter порта repo-rules: main не бросает, вывод собирается в строки без записи в поток.
|
|
92
|
+
const inProcessRepoRules: RepoRulesReader = (argv, env) => {
|
|
93
|
+
const out: string[] = [];
|
|
94
|
+
const err: string[] = [];
|
|
95
|
+
const code = repoRulesMain(
|
|
96
|
+
argv,
|
|
97
|
+
env,
|
|
98
|
+
(s) => void out.push(s),
|
|
99
|
+
(s) => void err.push(s),
|
|
100
|
+
);
|
|
101
|
+
return { code, out: out.join('\n'), err: err.join('\n') };
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// Проводник: аргументы после `repo-rules` уходят в repo-rules как есть, флаги stack здесь не разбираются.
|
|
105
|
+
// Версия правил — версия самого stack: пакет берётся из зависимостей stack, не из репозитория потребителя.
|
|
106
|
+
if (Bun.argv[2] === 'repo-rules') {
|
|
107
|
+
// Вывод собирается и дописывается до выхода: process.exit сразу после write обрывает канал на 128 КиБ.
|
|
108
|
+
let out = '';
|
|
109
|
+
let err = '';
|
|
110
|
+
const code = repoRulesMain(
|
|
111
|
+
Bun.argv.slice(3),
|
|
112
|
+
process.env,
|
|
113
|
+
(s) => void (out += `${s}\n`),
|
|
114
|
+
(s) => void (err += `${s}\n`),
|
|
115
|
+
);
|
|
116
|
+
// Ошибка записи (диск полон, канал закрыт) — одна строка и код 2, как в бинарнике repo-rules.
|
|
117
|
+
let writeError: Error | undefined;
|
|
118
|
+
const flush = (stream: NodeJS.WriteStream, text: string) =>
|
|
119
|
+
new Promise<void>((resolve) => {
|
|
120
|
+
if (text)
|
|
121
|
+
stream.write(text, (e) => {
|
|
122
|
+
writeError ??= e ?? undefined;
|
|
123
|
+
resolve();
|
|
124
|
+
});
|
|
125
|
+
else resolve();
|
|
126
|
+
});
|
|
127
|
+
await Promise.all([flush(process.stdout, out), flush(process.stderr, err)]);
|
|
128
|
+
if (writeError) {
|
|
129
|
+
process.stderr.write(`repo-rules: ${writeError.message}\n`);
|
|
130
|
+
process.exit(2);
|
|
131
|
+
}
|
|
132
|
+
process.exit(code);
|
|
133
|
+
}
|
|
134
|
+
|
|
87
135
|
const { values, positionals } = parseCliArgs();
|
|
88
136
|
|
|
89
137
|
const repoRoot = values.repo ?? process.cwd();
|
|
90
138
|
const command = positionals[0];
|
|
139
|
+
if (positionals.includes('repo-rules')) {
|
|
140
|
+
fail(
|
|
141
|
+
'repo-rules takes its own arguments and must come first: stack repo-rules [-C <dir>] <command>',
|
|
142
|
+
);
|
|
143
|
+
}
|
|
91
144
|
|
|
92
145
|
try {
|
|
93
146
|
if (command === 'init') {
|
|
@@ -107,7 +160,11 @@ try {
|
|
|
107
160
|
for (const line of stdout) console.log(line);
|
|
108
161
|
} else if (command === 'check') {
|
|
109
162
|
const cfg = readStackConfig(repoRoot);
|
|
110
|
-
const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions,
|
|
163
|
+
const { findings, notes } = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions, {
|
|
164
|
+
peers: pnpmPeers,
|
|
165
|
+
repoRules: { read: inProcessRepoRules, env: process.env, base: values.base },
|
|
166
|
+
});
|
|
167
|
+
for (const n of notes) console.warn(n);
|
|
111
168
|
const blocking = findings.filter((f) => !isHeld(f));
|
|
112
169
|
for (const f of findings.filter(isHeld)) console.warn(allowedLine(f));
|
|
113
170
|
for (const f of blocking) console.error(`${f.code}: ${f.target} — ${f.message}`);
|
|
@@ -137,6 +194,7 @@ try {
|
|
|
137
194
|
registry: npmRegistryReader(),
|
|
138
195
|
print: (stream, line) => (stream === 'out' ? console.log(line) : console.error(line)),
|
|
139
196
|
peers: pnpmPeers,
|
|
197
|
+
repoRules: inProcessRepoRules,
|
|
140
198
|
},
|
|
141
199
|
),
|
|
142
200
|
);
|
|
@@ -150,7 +208,7 @@ try {
|
|
|
150
208
|
process.exit(r.code);
|
|
151
209
|
} else {
|
|
152
210
|
fail(
|
|
153
|
-
`unknown command "${command ?? ''}". Available: init, sync, check, sync-pr, peers-baseline`,
|
|
211
|
+
`unknown command "${command ?? ''}". Available: init, sync, check, sync-pr, peers-baseline, repo-rules`,
|
|
154
212
|
);
|
|
155
213
|
}
|
|
156
214
|
} catch (error) {
|
package/src/exceptions.ts
CHANGED
|
@@ -92,14 +92,24 @@ const ADDRESS: { [C in FindingCode]: ((f: FindingOf<C>) => Address) | 'unsuppres
|
|
|
92
92
|
'dependabot-config': 'unsuppressible',
|
|
93
93
|
// Версия в moon toolchains — второй пин поверх .prototools; исключение держит её по файлу.
|
|
94
94
|
'moon-toolchain-version': () => ({ file: '.moon/toolchains.yml' }),
|
|
95
|
+
// moon 2 файл под именем moon 1 не читает; исключение держит находку по файлу.
|
|
96
|
+
'moon-v1-toolchain': (f) => ({ file: f.file }),
|
|
95
97
|
// Ветка по умолчанию в moon workspace; исключение по найденному пути держит и drift, и отчёт.
|
|
96
98
|
'moon-default-branch': (f) => ({ file: f.file }),
|
|
99
|
+
// Копии пинов тулчейна — адрес сам Dockerfile или workflow.
|
|
100
|
+
'toolchain-pin': (f) => ({ file: f.file }),
|
|
101
|
+
// Засев принадлежит репозиторию: исключение по файлу держит находку «канон не подключён».
|
|
102
|
+
'canon-not-extended': (f) => ({ file: f.file }),
|
|
97
103
|
'unreadable-file': 'unsuppressible',
|
|
98
104
|
'stale-exception': 'unsuppressible',
|
|
99
105
|
// Исключение для находок peers — сам baseline; отказ от гейта — убрать группу из with.
|
|
100
106
|
'peer-dependency': 'unsuppressible',
|
|
101
107
|
'stale-peer-baseline': 'unsuppressible',
|
|
102
108
|
'peers-unavailable': 'unsuppressible',
|
|
109
|
+
// Исключение для находок repo-rules — сам baseline; отказ от гейта — убрать группу из with.
|
|
110
|
+
'repo-rules-violation': 'unsuppressible',
|
|
111
|
+
'stale-repo-rules-baseline': 'unsuppressible',
|
|
112
|
+
'repo-rules-unavailable': 'unsuppressible',
|
|
103
113
|
};
|
|
104
114
|
|
|
105
115
|
export function addressOf(f: Finding): Address | undefined {
|
package/src/findings.ts
CHANGED
|
@@ -11,7 +11,16 @@ interface FindingBase {
|
|
|
11
11
|
// находки без предмета не подавляются никогда.
|
|
12
12
|
export type Finding = FindingBase &
|
|
13
13
|
(
|
|
14
|
-
| {
|
|
14
|
+
| {
|
|
15
|
+
code:
|
|
16
|
+
| 'file-drift'
|
|
17
|
+
| 'file-missing'
|
|
18
|
+
| 'moon-default-branch'
|
|
19
|
+
| 'toolchain-pin'
|
|
20
|
+
| 'moon-v1-toolchain'
|
|
21
|
+
| 'canon-not-extended';
|
|
22
|
+
file: string;
|
|
23
|
+
}
|
|
15
24
|
| { code: 'catalog-drift' | 'catalog-missing'; catalog: string; name: string }
|
|
16
25
|
| { code: 'inline-version' | 'release-age-exclude'; name: string }
|
|
17
26
|
| {
|
|
@@ -25,7 +34,10 @@ export type Finding = FindingBase &
|
|
|
25
34
|
| 'stale-exception'
|
|
26
35
|
| 'peer-dependency'
|
|
27
36
|
| 'stale-peer-baseline'
|
|
28
|
-
| 'peers-unavailable'
|
|
37
|
+
| 'peers-unavailable'
|
|
38
|
+
| 'repo-rules-violation'
|
|
39
|
+
| 'stale-repo-rules-baseline'
|
|
40
|
+
| 'repo-rules-unavailable';
|
|
29
41
|
}
|
|
30
42
|
);
|
|
31
43
|
export type FindingCode = Finding['code'];
|
package/src/moon-toolchains.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Canon } from './canon.ts';
|
|
2
2
|
import type { Finding } from './findings.ts';
|
|
3
|
-
import { MOON_TOOLCHAINS, type Repo } from './repo.ts';
|
|
3
|
+
import { MOON_TOOLCHAIN_V1, MOON_TOOLCHAINS, type Repo } from './repo.ts';
|
|
4
4
|
|
|
5
5
|
// Версию инструмента задаёт .prototools: `version` в moon toolchains — второй пин, и после подъёма
|
|
6
6
|
// канона moon разойдётся с ним. Находка при любой заданной версии, даже равной пину; только отчёт.
|
|
@@ -18,3 +18,17 @@ export function checkMoonToolchains(repo: Repo, canon: Canon): Finding[] {
|
|
|
18
18
|
}
|
|
19
19
|
return findings;
|
|
20
20
|
}
|
|
21
|
+
|
|
22
|
+
// Файл MOON_TOOLCHAIN_V1 moon 2 как конфиг не читает (ни ошибки на невалидном YAML, ни действия пина), поэтому
|
|
23
|
+
// содержимое не смотрится и не разбирается: важно само наличие пути. Только отчёт; sync файл не трогает.
|
|
24
|
+
export function checkMoonV1Toolchain(repo: Repo): Finding[] {
|
|
25
|
+
if (!repo.paths.has(MOON_TOOLCHAIN_V1)) return [];
|
|
26
|
+
return [
|
|
27
|
+
{
|
|
28
|
+
code: 'moon-v1-toolchain',
|
|
29
|
+
target: MOON_TOOLCHAIN_V1,
|
|
30
|
+
file: MOON_TOOLCHAIN_V1,
|
|
31
|
+
message: `moon 2 does not read this file — it reads ${MOON_TOOLCHAINS} — so nothing in it applies; move the settings still needed there and delete it`,
|
|
32
|
+
},
|
|
33
|
+
];
|
|
34
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
import type { Wanted } from './registry.ts';
|
|
6
|
+
|
|
7
|
+
export const SCOPE = '@alxwlw/';
|
|
8
|
+
|
|
9
|
+
export interface StackManifest {
|
|
10
|
+
version: string;
|
|
11
|
+
dependencies?: Record<string, string>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// package.json пакета: он лежит рядом с src/, как canon/ (canonDir()).
|
|
15
|
+
export function ownManifest(): StackManifest {
|
|
16
|
+
const path = join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
|
|
17
|
+
return JSON.parse(readFileSync(path, 'utf8')) as StackManifest;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function ownVersion(): string {
|
|
21
|
+
return ownManifest().version;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Свои пакеты: записи SCOPE каталога dev в его порядке и с его версиями, затем зависимости SCOPE из
|
|
25
|
+
// manifest, которых в списке ещё нет, в версии самого пакета (строка из dependencies может быть
|
|
26
|
+
// диапазоном или `workspace:` и в `имя@версия` не годится).
|
|
27
|
+
export function ownPackages(
|
|
28
|
+
dev: Record<string, string> | undefined,
|
|
29
|
+
manifest: StackManifest,
|
|
30
|
+
): Wanted[] {
|
|
31
|
+
const own: Wanted[] = Object.entries(dev ?? {})
|
|
32
|
+
.filter(([name]) => name.startsWith(SCOPE))
|
|
33
|
+
.map(([name, version]) => ({ name, version }));
|
|
34
|
+
for (const name of Object.keys(manifest.dependencies ?? {})) {
|
|
35
|
+
if (!name.startsWith(SCOPE) || own.some((p) => p.name === name)) continue;
|
|
36
|
+
own.push({ name, version: manifest.version });
|
|
37
|
+
}
|
|
38
|
+
return own;
|
|
39
|
+
}
|
package/src/release-age.ts
CHANGED
|
@@ -2,10 +2,10 @@ import { isScalar, isSeq } from 'yaml';
|
|
|
2
2
|
|
|
3
3
|
import type { Canon } from './canon.ts';
|
|
4
4
|
import type { Drift } from './findings.ts';
|
|
5
|
+
import { SCOPE } from './own-packages.ts';
|
|
5
6
|
import { type Repo, WORKSPACE_FILE } from './repo.ts';
|
|
6
7
|
|
|
7
8
|
const KEY = 'minimumReleaseAgeExclude';
|
|
8
|
-
const SCOPE = '@alxwlw/';
|
|
9
9
|
|
|
10
10
|
// Покрывает ли строка исключения версию пакета: голое имя, `@alxwlw/*` или `<имя>@<список через ||>`.
|
|
11
11
|
function covers(entry: string, name: string, version: string): boolean {
|
|
@@ -18,9 +18,11 @@ function covers(entry: string, name: string, version: string): boolean {
|
|
|
18
18
|
.some((v) => v.trim() === version);
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
// Пока в pnpm-workspace.yaml включён minimumReleaseAge, свежий
|
|
22
|
-
// отвергает в день публикации: sync держит версии канона в
|
|
23
|
-
// и их порядок не
|
|
21
|
+
// Пока в pnpm-workspace.yaml включён minimumReleaseAge, свежий свой пакет канона (каталог dev и
|
|
22
|
+
// зависимости stack) pnpm install отвергает в день публикации: sync держит версии канона в
|
|
23
|
+
// minimumReleaseAgeExclude. Чужие записи и их порядок не трогаются. Своя запись, не покрывающая
|
|
24
|
+
// версию, приводится к одной текущей (список не растёт от релиза к релизу); запись, которая версию
|
|
25
|
+
// уже покрывает, не трогается; нет записи — новая в конец.
|
|
24
26
|
// Правило называет намерение: позицию новой записи и создание списка (ключа нет, ключ без значения)
|
|
25
27
|
// решает применитель, поэтому находки не зависят друг от друга и любую из них можно удержать.
|
|
26
28
|
export function planReleaseAgeExcludes(repo: Repo, canon: Canon): Drift[] {
|
|
@@ -35,8 +37,7 @@ export function planReleaseAgeExcludes(repo: Repo, canon: Canon): Drift[] {
|
|
|
35
37
|
isScalar(n) && typeof n.value === 'string' ? n.value : undefined,
|
|
36
38
|
);
|
|
37
39
|
const plan: Drift[] = [];
|
|
38
|
-
for (const
|
|
39
|
-
if (!name.startsWith(SCOPE)) continue;
|
|
40
|
+
for (const { name, version } of canon.ownPackages) {
|
|
40
41
|
if (items.some((s) => s !== undefined && covers(s, name, version))) continue;
|
|
41
42
|
// Существующие элементы не сдвигаются, новые идут в конец: индекс своей записи верен при любом
|
|
42
43
|
// подмножестве применённых правок.
|
|
@@ -53,7 +54,7 @@ export function planReleaseAgeExcludes(repo: Repo, canon: Canon): Drift[] {
|
|
|
53
54
|
kind: 'yaml-set',
|
|
54
55
|
file: WORKSPACE_FILE,
|
|
55
56
|
path: [KEY, own],
|
|
56
|
-
value: `${
|
|
57
|
+
value: `${name}@${version}`,
|
|
57
58
|
}
|
|
58
59
|
: { kind: 'yaml-append', file: WORKSPACE_FILE, path: [KEY], value: `${name}@${version}` },
|
|
59
60
|
});
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Правило группы repo-rules: находки и пометки из исхода двух вызовов repo-rules. Чистые функции над
|
|
2
|
+
// значениями; сами вызовы и разбор — repo-rules.ts.
|
|
3
|
+
|
|
4
|
+
import type { Finding } from './findings.ts';
|
|
5
|
+
import type { RepoRulesOutcome, RepoRulesPart } from './repo-rules.ts';
|
|
6
|
+
|
|
7
|
+
const TRAILER_HINT =
|
|
8
|
+
'repo-rules diff: intended? add a commit trailer "Tests-Removed: <reason>" in the range';
|
|
9
|
+
|
|
10
|
+
function partFindings(part: RepoRulesPart | { skipped: string }, target: string): Finding[] {
|
|
11
|
+
if ('skipped' in part) return [];
|
|
12
|
+
if ('unavailable' in part) {
|
|
13
|
+
return [{ code: 'repo-rules-unavailable', target, message: part.unavailable }];
|
|
14
|
+
}
|
|
15
|
+
return [
|
|
16
|
+
...part.violations.map((v): Finding => ({
|
|
17
|
+
code: 'repo-rules-violation',
|
|
18
|
+
target: v.line > 0 ? `${v.path}:${v.line}` : v.path,
|
|
19
|
+
message: `${v.rule}: ${v.message}`,
|
|
20
|
+
})),
|
|
21
|
+
...part.stale.map((s): Finding => ({
|
|
22
|
+
code: 'stale-repo-rules-baseline',
|
|
23
|
+
target: s.path,
|
|
24
|
+
message: `${s.rule}: recorded ${s.baseline}, now ${s.actual}; lower it with: stack repo-rules baseline`,
|
|
25
|
+
})),
|
|
26
|
+
];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function checkRepoRules(outcome: RepoRulesOutcome | undefined): Finding[] {
|
|
30
|
+
if (outcome === undefined) throw new Error('checkRepoRules: no repo-rules outcome');
|
|
31
|
+
return [
|
|
32
|
+
...partFindings(outcome.check, 'repo-rules check'),
|
|
33
|
+
...partFindings(outcome.diff, 'repo-rules diff'),
|
|
34
|
+
];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Пометка — часть проверки, которая пропущена или о чём стоит знать; выход она не меняет.
|
|
38
|
+
export function repoRulesNotes(outcome: RepoRulesOutcome | undefined): string[] {
|
|
39
|
+
if (outcome === undefined) return [];
|
|
40
|
+
const notes: string[] = [];
|
|
41
|
+
if (!('unavailable' in outcome.check)) {
|
|
42
|
+
for (const n of outcome.check.notes) notes.push(`repo-rules check: ${n}`);
|
|
43
|
+
}
|
|
44
|
+
const diff = outcome.diff;
|
|
45
|
+
if ('skipped' in diff) notes.push(`repo-rules diff: ${diff.skipped}`);
|
|
46
|
+
else if (!('unavailable' in diff)) {
|
|
47
|
+
for (const n of diff.notes) notes.push(`repo-rules diff: ${n}`);
|
|
48
|
+
if (diff.violations.length > 0) notes.push(TRAILER_HINT);
|
|
49
|
+
}
|
|
50
|
+
return notes;
|
|
51
|
+
}
|