@alxwlw/stack 1.16.1 → 1.18.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/proto-plugins/hadolint.toml +21 -0
- package/canon/files/prototools +3 -1
- package/canon/files/workflow-renovate.yml +9 -0
- package/canon/files/workflow-stack-check-infra.yml +10 -0
- package/canon/files/workflow-stack-check.yml +10 -0
- package/canon/files/workflow-stack-sync.yml +10 -0
- package/canon/manifest.json +5 -0
- package/package.json +3 -1
- package/schema.json +10 -1
- package/src/canon.ts +18 -5
- package/src/check.ts +70 -15
- package/src/cli.ts +63 -3
- package/src/exceptions.ts +15 -0
- package/src/findings.ts +17 -2
- package/src/guardrails-actionlint.ts +65 -0
- package/src/guardrails-bin.ts +129 -0
- package/src/guardrails-commits.ts +42 -0
- package/src/guardrails-files.ts +91 -0
- package/src/guardrails-gitleaks.ts +135 -0
- package/src/guardrails-hadolint.ts +67 -0
- package/src/guardrails-markdownlint.ts +114 -0
- package/src/guardrails-port.ts +112 -0
- package/src/guardrails-rule.ts +73 -0
- package/src/guardrails-shellcheck.ts +55 -0
- package/src/guardrails-yamllint.ts +90 -0
- package/src/guardrails.ts +358 -0
- package/src/markdownlint-cli2.d.ts +23 -0
- package/src/markdownlint-run.bunfig.toml +3 -0
- package/src/markdownlint-run.ts +67 -0
- 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 +128 -0
- package/src/sync-pr.ts +31 -17
- package/src/toolchain-pins-rule.ts +56 -0
- package/src/toolchain-pins.ts +179 -0
- package/src/workflow-hygiene.ts +77 -0
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
// Читатель группы guardrails: отслеживаемые файлы, бинарники ровно версии пина, запуск actionlint,
|
|
2
|
+
// shellcheck, gitleaks, hadolint, markdownlint-cli2 и yamllint за прогон; gitleaks запускается дважды
|
|
3
|
+
// (файлы и коммиты PR), когда скан коммитов идёт. Всё внешнее идёт через порт; правило и пометки —
|
|
4
|
+
// guardrails-rule.ts.
|
|
5
|
+
|
|
6
|
+
import { mkdtempSync, realpathSync, rmSync } from 'node:fs';
|
|
7
|
+
import { tmpdir } from 'node:os';
|
|
8
|
+
import { join, resolve } from 'node:path';
|
|
9
|
+
|
|
10
|
+
import { actionlintArgv, parseActionlint } from './guardrails-actionlint.ts';
|
|
11
|
+
import { locateTool, repoPins } from './guardrails-bin.ts';
|
|
12
|
+
import { type CommitsPart, mergeBase, mergeBaseArgv, prBase } from './guardrails-commits.ts';
|
|
13
|
+
import {
|
|
14
|
+
dockerfiles,
|
|
15
|
+
markdownFiles,
|
|
16
|
+
regularFiles,
|
|
17
|
+
shellScripts,
|
|
18
|
+
TRACKED_FILES_ARGV,
|
|
19
|
+
trackedFiles,
|
|
20
|
+
workflowFiles,
|
|
21
|
+
yamlFiles,
|
|
22
|
+
} from './guardrails-files.ts';
|
|
23
|
+
import {
|
|
24
|
+
copyTracked,
|
|
25
|
+
GITLEAKS_CONFIG_FILE,
|
|
26
|
+
gitleaksDirArgv,
|
|
27
|
+
gitleaksGitArgv,
|
|
28
|
+
type GitleaksLeak,
|
|
29
|
+
parseGitleaks,
|
|
30
|
+
} from './guardrails-gitleaks.ts';
|
|
31
|
+
import { hadolintArgv, parseHadolint } from './guardrails-hadolint.ts';
|
|
32
|
+
import { markdownlintCommand, parseMarkdownlint } from './guardrails-markdownlint.ts';
|
|
33
|
+
import {
|
|
34
|
+
type GuardrailsPort,
|
|
35
|
+
type GuardrailTool,
|
|
36
|
+
type GuardrailViolation,
|
|
37
|
+
type Unavailable,
|
|
38
|
+
} from './guardrails-port.ts';
|
|
39
|
+
import { parseShellcheck, shellcheckArgv } from './guardrails-shellcheck.ts';
|
|
40
|
+
import {
|
|
41
|
+
parseYamllint,
|
|
42
|
+
YAMLLINT_CONFIG_FILES,
|
|
43
|
+
YAMLLINT_VERSION,
|
|
44
|
+
yamllintArgv,
|
|
45
|
+
yamllintConfig,
|
|
46
|
+
} from './guardrails-yamllint.ts';
|
|
47
|
+
|
|
48
|
+
export type ToolPart =
|
|
49
|
+
| { skipped: 'no files' }
|
|
50
|
+
| Unavailable
|
|
51
|
+
| { version: string; files: number; violations: GuardrailViolation[] };
|
|
52
|
+
|
|
53
|
+
export type GuardrailsOutcome =
|
|
54
|
+
| Unavailable
|
|
55
|
+
| { tools: Record<GuardrailTool, ToolPart>; commits: CommitsPart };
|
|
56
|
+
|
|
57
|
+
function isUnavailable(v: object): v is Unavailable {
|
|
58
|
+
return 'unavailable' in v;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Бинарник найден, файлы есть — инструмент запущен на них; разбор — parse. cwd и env — каталог и
|
|
62
|
+
// переопределения окружения процесса (порт: корень репозитория и окружение родителя без них).
|
|
63
|
+
function runPart(
|
|
64
|
+
located: { bin: string; version: string },
|
|
65
|
+
argv: string[],
|
|
66
|
+
files: number,
|
|
67
|
+
port: GuardrailsPort,
|
|
68
|
+
parse: (run: ReturnType<GuardrailsPort['run']>) => GuardrailViolation[] | Unavailable,
|
|
69
|
+
cwd?: string,
|
|
70
|
+
env?: Readonly<Record<string, string>>,
|
|
71
|
+
): ToolPart {
|
|
72
|
+
const parsed = parse(port.run(located.bin, argv, cwd, env));
|
|
73
|
+
if (!Array.isArray(parsed)) return parsed;
|
|
74
|
+
return { version: located.version, files, violations: parsed };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Копия отслеживаемых обычных файлов на время fn; каталог удаляется при любом исходе. Вход — только
|
|
78
|
+
// вывод regularFiles: copyTracked не проверяет, что пути остаются внутри каталога. Единственное
|
|
79
|
+
// место копии и её уборки: за прогон одна копия, и в ней идут оба прогона gitleaks (файлы и коммиты
|
|
80
|
+
// PR), hadolint, markdownlint-cli2 и yamllint.
|
|
81
|
+
function withTrackedCopy<T>(
|
|
82
|
+
root: string,
|
|
83
|
+
files: readonly string[],
|
|
84
|
+
fn: (dir: string) => T,
|
|
85
|
+
): T | Unavailable {
|
|
86
|
+
const copy = copyTracked(root, files);
|
|
87
|
+
if (isUnavailable(copy)) return copy;
|
|
88
|
+
try {
|
|
89
|
+
return fn(copy.dir);
|
|
90
|
+
} finally {
|
|
91
|
+
rmSync(copy.dir, { recursive: true, force: true });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Пометка недоступности по копии называет пути репозитория: `<copy>/` и `<realpath(copy)>/` убраны,
|
|
96
|
+
// оставшееся имя каталога — `.`. Длинная форма первой: на macOS копия `/tmp/X` — часть пути
|
|
97
|
+
// `/private/tmp/X`, и короткая первой исказила бы длинную.
|
|
98
|
+
export function inRepoTerms(reason: string, copy: string): string {
|
|
99
|
+
let real = copy;
|
|
100
|
+
try {
|
|
101
|
+
real = realpathSync(copy);
|
|
102
|
+
} catch {
|
|
103
|
+
// каталога нет — остаётся форма `dir`
|
|
104
|
+
}
|
|
105
|
+
const forms = [...new Set([real, copy])].sort((a, b) => b.length - a.length);
|
|
106
|
+
let out = reason;
|
|
107
|
+
for (const f of forms) out = out.split(`${f}/`).join('');
|
|
108
|
+
for (const f of forms) out = out.split(f).join('.');
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function inRepo<T extends object>(part: T, copy: string): T | Unavailable {
|
|
113
|
+
return 'unavailable' in part && typeof part.unavailable === 'string'
|
|
114
|
+
? { unavailable: inRepoTerms(part.unavailable, copy) }
|
|
115
|
+
: part;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function toViolation(leak: GitleaksLeak, suffix = ''): GuardrailViolation {
|
|
119
|
+
return {
|
|
120
|
+
tool: 'gitleaks',
|
|
121
|
+
rule: leak.rule,
|
|
122
|
+
path: leak.path,
|
|
123
|
+
line: leak.line,
|
|
124
|
+
message: `${leak.description || 'secret detected'}${suffix}`,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Часть gitleaks и часть коммитов; обе идут в копии файлов dir (cwd обоих запусков).
|
|
129
|
+
function readGitleaks(
|
|
130
|
+
root: string,
|
|
131
|
+
files: readonly string[],
|
|
132
|
+
gitleaks: { bin: string; version: string },
|
|
133
|
+
dir: string,
|
|
134
|
+
port: GuardrailsPort,
|
|
135
|
+
): { part: ToolPart; commits: CommitsPart } {
|
|
136
|
+
const parsed = parseGitleaks(port.run(gitleaks.bin, gitleaksDirArgv(), dir));
|
|
137
|
+
if (!Array.isArray(parsed)) return { part: parsed, commits: { skipped: 'gitleaks unavailable' } };
|
|
138
|
+
return {
|
|
139
|
+
part: {
|
|
140
|
+
version: gitleaks.version,
|
|
141
|
+
files: files.length,
|
|
142
|
+
violations: parsed.map((leak) => toViolation(leak)),
|
|
143
|
+
},
|
|
144
|
+
commits: readCommits(root, files, gitleaks.bin, dir, port),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// hadolint ищет конфиг в cwd, затем в XDG_CONFIG_HOME и HOME: оба указывают на новый пустой каталог,
|
|
149
|
+
// поэтому действует только отслеживаемый конфиг hadolint копии, иначе встроенный.
|
|
150
|
+
function readHadolint(
|
|
151
|
+
set: readonly string[],
|
|
152
|
+
hadolint: { bin: string; version: string },
|
|
153
|
+
dir: string,
|
|
154
|
+
port: GuardrailsPort,
|
|
155
|
+
): ToolPart {
|
|
156
|
+
let home: string;
|
|
157
|
+
try {
|
|
158
|
+
home = mkdtempSync(join(tmpdir(), 'stack-home-'));
|
|
159
|
+
} catch (e) {
|
|
160
|
+
// Как в copyTracked: нет или недоступен TMPDIR — недоступность, а не исключение из читателя.
|
|
161
|
+
return { unavailable: `home: ${e instanceof Error ? e.message : String(e)}` };
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
return runPart(hadolint, hadolintArgv(set), set.length, port, parseHadolint, dir, {
|
|
165
|
+
HOME: home,
|
|
166
|
+
XDG_CONFIG_HOME: home,
|
|
167
|
+
});
|
|
168
|
+
} finally {
|
|
169
|
+
rmSync(home, { recursive: true, force: true });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// yamllint запускается через uv из пина в копии: версия yamllint — константа, а не версия uv.
|
|
174
|
+
function readYamllint(
|
|
175
|
+
set: readonly string[],
|
|
176
|
+
config: string,
|
|
177
|
+
uv: { bin: string },
|
|
178
|
+
dir: string,
|
|
179
|
+
port: GuardrailsPort,
|
|
180
|
+
): ToolPart {
|
|
181
|
+
return runPart(
|
|
182
|
+
{ bin: uv.bin, version: YAMLLINT_VERSION },
|
|
183
|
+
yamllintArgv(config),
|
|
184
|
+
set.length,
|
|
185
|
+
port,
|
|
186
|
+
parseYamllint,
|
|
187
|
+
dir,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// markdownlint-cli2 идёт раннером stack под bun в копии: версия — из отчёта раннера (точная
|
|
192
|
+
// зависимость stack), число в пометке — число кандидатов (*.md, *.mdx), а не файлов после игноров.
|
|
193
|
+
function readMarkdownlint(set: readonly string[], dir: string, port: GuardrailsPort): ToolPart {
|
|
194
|
+
const { cmd, argv } = markdownlintCommand();
|
|
195
|
+
const parsed = parseMarkdownlint(port.run(cmd, argv, dir));
|
|
196
|
+
if ('unavailable' in parsed) return parsed;
|
|
197
|
+
return { version: parsed.version, files: set.length, violations: parsed.violations };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function readCommits(
|
|
201
|
+
root: string,
|
|
202
|
+
files: readonly string[],
|
|
203
|
+
bin: string,
|
|
204
|
+
dir: string,
|
|
205
|
+
port: GuardrailsPort,
|
|
206
|
+
): CommitsPart {
|
|
207
|
+
const pr = prBase(port.base, port.env);
|
|
208
|
+
if (!('base' in pr)) return pr;
|
|
209
|
+
const mb = mergeBase(port.run('git', mergeBaseArgv(pr.base), root), pr.base);
|
|
210
|
+
if (typeof mb !== 'string') return mb;
|
|
211
|
+
const range = `${mb}..HEAD`;
|
|
212
|
+
const parsed = parseGitleaks(
|
|
213
|
+
port.run(bin, gitleaksGitArgv(root, range, files.includes(GITLEAKS_CONFIG_FILE)), dir),
|
|
214
|
+
);
|
|
215
|
+
if (!Array.isArray(parsed)) return parsed;
|
|
216
|
+
return {
|
|
217
|
+
range: `${mb.slice(0, 12)}..HEAD`,
|
|
218
|
+
violations: parsed.map((leak) => toViolation(leak, ` (commit ${leak.commit.slice(0, 12)})`)),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function readGuardrails(
|
|
223
|
+
repoRoot: string,
|
|
224
|
+
prototools: string | undefined,
|
|
225
|
+
port: GuardrailsPort,
|
|
226
|
+
): GuardrailsOutcome {
|
|
227
|
+
// Скан коммитов идёт с cwd = копия и зовёт `git -C <корень>`: относительный корень там не найти.
|
|
228
|
+
const root = resolve(repoRoot);
|
|
229
|
+
const tracked = trackedFiles(port.run('git', [...TRACKED_FILES_ARGV]));
|
|
230
|
+
if (isUnavailable(tracked)) return tracked;
|
|
231
|
+
const files = regularFiles(root, tracked);
|
|
232
|
+
const workflows = workflowFiles(files);
|
|
233
|
+
const scripts = shellScripts(root, files);
|
|
234
|
+
|
|
235
|
+
const none: ToolPart = { skipped: 'no files' };
|
|
236
|
+
if (files.length === 0) {
|
|
237
|
+
return {
|
|
238
|
+
tools: {
|
|
239
|
+
actionlint: none,
|
|
240
|
+
shellcheck: none,
|
|
241
|
+
gitleaks: none,
|
|
242
|
+
hadolint: none,
|
|
243
|
+
'markdownlint-cli2': none,
|
|
244
|
+
yamllint: none,
|
|
245
|
+
},
|
|
246
|
+
commits: { skipped: 'no files' },
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const pins = repoPins(prototools);
|
|
251
|
+
// shellcheck нужен обоим наборам: скриптам — как инструмент, workflow — как пиненный бинарник actionlint.
|
|
252
|
+
const needShellcheck = workflows.length > 0 || scripts.length > 0;
|
|
253
|
+
const shellcheck = needShellcheck ? locateTool('shellcheck', pins, port) : undefined;
|
|
254
|
+
let shellcheckPart: ToolPart = none;
|
|
255
|
+
if (shellcheck !== undefined && isUnavailable(shellcheck)) shellcheckPart = shellcheck;
|
|
256
|
+
else if (shellcheck !== undefined && scripts.length > 0) {
|
|
257
|
+
shellcheckPart = runPart(
|
|
258
|
+
shellcheck,
|
|
259
|
+
shellcheckArgv(scripts),
|
|
260
|
+
scripts.length,
|
|
261
|
+
port,
|
|
262
|
+
parseShellcheck,
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
let actionlintPart: ToolPart = none;
|
|
267
|
+
if (workflows.length > 0) {
|
|
268
|
+
const actionlint = locateTool('actionlint', pins, port);
|
|
269
|
+
actionlintPart = isUnavailable(actionlint)
|
|
270
|
+
? actionlint
|
|
271
|
+
: runPart(
|
|
272
|
+
actionlint,
|
|
273
|
+
actionlintArgv(
|
|
274
|
+
shellcheck === undefined || isUnavailable(shellcheck) ? undefined : shellcheck.bin,
|
|
275
|
+
workflows,
|
|
276
|
+
),
|
|
277
|
+
workflows.length,
|
|
278
|
+
port,
|
|
279
|
+
parseActionlint,
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Одна копия на прогон: в ней gitleaks, hadolint, markdownlint-cli2 и yamllint. Бинарники ищутся до
|
|
284
|
+
// копии; она создаётся, когда её нужно найденному бинарнику или непустому набору Markdown.
|
|
285
|
+
// Копия файлов всегда непуста (files.length > 0), поэтому gitleaks ищется всегда;
|
|
286
|
+
// hadolint — только при Dockerfile среди файлов, markdownlint-cli2 — только при Markdown (бинарника
|
|
287
|
+
// нет: раннер — скрипт stack), yamllint — только при YAML и конфиге среди них (иначе uv не ищется).
|
|
288
|
+
const gitleaks = locateTool('gitleaks', pins, port);
|
|
289
|
+
const dockerSet = dockerfiles(files);
|
|
290
|
+
const hadolint = dockerSet.length > 0 ? locateTool('hadolint', pins, port) : undefined;
|
|
291
|
+
const markdownSet = markdownFiles(files);
|
|
292
|
+
const yamlSet = yamlFiles(files);
|
|
293
|
+
const yamlConfig = yamllintConfig(files);
|
|
294
|
+
const uv =
|
|
295
|
+
yamlSet.length > 0 && yamlConfig !== undefined ? locateTool('uv', pins, port) : undefined;
|
|
296
|
+
let gitleaksPart: ToolPart = isUnavailable(gitleaks) ? gitleaks : none;
|
|
297
|
+
let hadolintPart: ToolPart =
|
|
298
|
+
hadolint === undefined ? none : isUnavailable(hadolint) ? hadolint : none;
|
|
299
|
+
let markdownlintPart: ToolPart = none;
|
|
300
|
+
let yamllintPart: ToolPart = none;
|
|
301
|
+
if (yamlSet.length > 0) {
|
|
302
|
+
if (yamlConfig === undefined) {
|
|
303
|
+
yamllintPart = {
|
|
304
|
+
unavailable: `no yamllint config among tracked files (${YAMLLINT_CONFIG_FILES[0]})`,
|
|
305
|
+
};
|
|
306
|
+
} else if (uv !== undefined && isUnavailable(uv)) yamllintPart = uv;
|
|
307
|
+
}
|
|
308
|
+
let commits: CommitsPart = { skipped: 'gitleaks unavailable' };
|
|
309
|
+
const gitleaksReady = isUnavailable(gitleaks) ? undefined : gitleaks;
|
|
310
|
+
const hadolintReady = hadolint === undefined || isUnavailable(hadolint) ? undefined : hadolint;
|
|
311
|
+
const uvReady = uv === undefined || isUnavailable(uv) ? undefined : uv;
|
|
312
|
+
if (
|
|
313
|
+
gitleaksReady !== undefined ||
|
|
314
|
+
hadolintReady !== undefined ||
|
|
315
|
+
markdownSet.length > 0 ||
|
|
316
|
+
uvReady !== undefined
|
|
317
|
+
) {
|
|
318
|
+
const copied = withTrackedCopy(root, files, (dir) => {
|
|
319
|
+
if (gitleaksReady !== undefined) {
|
|
320
|
+
({ part: gitleaksPart, commits } = readGitleaks(root, files, gitleaksReady, dir, port));
|
|
321
|
+
}
|
|
322
|
+
if (hadolintReady !== undefined) {
|
|
323
|
+
hadolintPart = readHadolint(dockerSet, hadolintReady, dir, port);
|
|
324
|
+
}
|
|
325
|
+
if (markdownSet.length > 0) {
|
|
326
|
+
markdownlintPart = readMarkdownlint(markdownSet, dir, port);
|
|
327
|
+
}
|
|
328
|
+
if (uvReady !== undefined && yamlConfig !== undefined) {
|
|
329
|
+
yamllintPart = readYamllint(yamlSet, yamlConfig, uvReady, dir, port);
|
|
330
|
+
}
|
|
331
|
+
// Недоступность частей, шедших по копии, — пути репозитория, а не копии (она удаляется).
|
|
332
|
+
gitleaksPart = inRepo(gitleaksPart, dir);
|
|
333
|
+
commits = inRepo(commits, dir);
|
|
334
|
+
hadolintPart = inRepo(hadolintPart, dir);
|
|
335
|
+
markdownlintPart = inRepo(markdownlintPart, dir);
|
|
336
|
+
yamllintPart = inRepo(yamllintPart, dir);
|
|
337
|
+
return null;
|
|
338
|
+
});
|
|
339
|
+
// Сбой копии — недоступность у каждой части, которая в копии шла бы.
|
|
340
|
+
if (copied !== null) {
|
|
341
|
+
if (gitleaksReady !== undefined) gitleaksPart = { ...copied };
|
|
342
|
+
if (hadolintReady !== undefined) hadolintPart = { ...copied };
|
|
343
|
+
if (markdownSet.length > 0) markdownlintPart = { ...copied };
|
|
344
|
+
if (uvReady !== undefined) yamllintPart = { ...copied };
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return {
|
|
348
|
+
tools: {
|
|
349
|
+
actionlint: actionlintPart,
|
|
350
|
+
shellcheck: shellcheckPart,
|
|
351
|
+
gitleaks: gitleaksPart,
|
|
352
|
+
hadolint: hadolintPart,
|
|
353
|
+
'markdownlint-cli2': markdownlintPart,
|
|
354
|
+
yamllint: yamllintPart,
|
|
355
|
+
},
|
|
356
|
+
commits,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// markdownlint-cli2 не поставляет типов: объявлена только та часть API, которую зовёт раннер группы
|
|
2
|
+
// guardrails (markdownlint-run.ts); поля параметров — из JSDoc пакета.
|
|
3
|
+
declare module 'markdownlint-cli2' {
|
|
4
|
+
export interface LintResult {
|
|
5
|
+
fileName: string;
|
|
6
|
+
lineNumber: number;
|
|
7
|
+
ruleNames: string[];
|
|
8
|
+
ruleDescription: string;
|
|
9
|
+
errorDetail: string | null;
|
|
10
|
+
severity: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function main(params: {
|
|
14
|
+
directory: string;
|
|
15
|
+
argv: string[];
|
|
16
|
+
logMessage?: (message: string) => void;
|
|
17
|
+
logError?: (message: string) => void;
|
|
18
|
+
optionsOverride?: {
|
|
19
|
+
fix?: boolean;
|
|
20
|
+
outputFormatters?: [(options: { results: LintResult[] }) => void][];
|
|
21
|
+
};
|
|
22
|
+
}): Promise<number>;
|
|
23
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Раннер markdownlint-cli2 для группы guardrails: запускается bun-процессом в каталоге копии
|
|
2
|
+
// отслеживаемых файлов (cwd), печатает на stdout одну строку JSON MarkdownlintReport. `fix: false`
|
|
3
|
+
// закрывает и `"fix": true` конфига репозитория (иначе файлы были бы переписаны, а код был бы 0).
|
|
4
|
+
// Опция отключения импорта модулей не ставится: с ней строковые customRules молча выпадают, то есть
|
|
5
|
+
// «чисто»; без неё правило-пакет, которого нет в копии, — исключение main, то есть недоступность.
|
|
6
|
+
// Исключение main: его сообщение в stderr, код процесса 2, stdout пуст.
|
|
7
|
+
|
|
8
|
+
import { readFileSync } from 'node:fs';
|
|
9
|
+
import { dirname, join } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
|
|
12
|
+
import { type LintResult, main } from 'markdownlint-cli2';
|
|
13
|
+
|
|
14
|
+
import type { MarkdownlintReport, MarkdownlintResult } from './guardrails-markdownlint.ts';
|
|
15
|
+
|
|
16
|
+
const collected: MarkdownlintResult[] = [];
|
|
17
|
+
let formatted = false;
|
|
18
|
+
|
|
19
|
+
function collect(options: { results: LintResult[] }): void {
|
|
20
|
+
formatted = true;
|
|
21
|
+
for (const r of options.results) {
|
|
22
|
+
collected.push({
|
|
23
|
+
fileName: r.fileName,
|
|
24
|
+
lineNumber: r.lineNumber,
|
|
25
|
+
ruleNames: r.ruleNames,
|
|
26
|
+
ruleDescription: r.ruleDescription,
|
|
27
|
+
errorDetail: r.errorDetail,
|
|
28
|
+
severity: r.severity,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function packageVersion(): string {
|
|
34
|
+
const dir = dirname(fileURLToPath(import.meta.resolve('markdownlint-cli2')));
|
|
35
|
+
const manifest: unknown = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
|
|
36
|
+
if (
|
|
37
|
+
typeof manifest !== 'object' ||
|
|
38
|
+
manifest === null ||
|
|
39
|
+
!('version' in manifest) ||
|
|
40
|
+
typeof manifest.version !== 'string'
|
|
41
|
+
) {
|
|
42
|
+
throw new Error('markdownlint-cli2 package.json has no version');
|
|
43
|
+
}
|
|
44
|
+
return manifest.version;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
try {
|
|
48
|
+
const code = await main({
|
|
49
|
+
directory: process.cwd(),
|
|
50
|
+
argv: [],
|
|
51
|
+
logMessage: () => {},
|
|
52
|
+
logError: (message: string) => {
|
|
53
|
+
process.stderr.write(`${message}\n`);
|
|
54
|
+
},
|
|
55
|
+
optionsOverride: { fix: false, outputFormatters: [[collect]] },
|
|
56
|
+
});
|
|
57
|
+
const report: MarkdownlintReport = {
|
|
58
|
+
version: packageVersion(),
|
|
59
|
+
code,
|
|
60
|
+
formatted,
|
|
61
|
+
results: collected,
|
|
62
|
+
};
|
|
63
|
+
process.stdout.write(`${JSON.stringify(report)}\n`);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
66
|
+
process.exitCode = 2;
|
|
67
|
+
}
|
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
|
+
}
|