@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
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.18.0",
|
|
14
|
+
"@alxwlw/oxlint-config": "1.18.0",
|
|
15
|
+
"@alxwlw/tsconfig": "1.18.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
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
name = "hadolint"
|
|
2
|
+
type = "cli"
|
|
3
|
+
|
|
4
|
+
[resolve]
|
|
5
|
+
git-url = "https://github.com/hadolint/hadolint"
|
|
6
|
+
|
|
7
|
+
[platform.linux]
|
|
8
|
+
download-file = "hadolint-linux-{arch}"
|
|
9
|
+
checksum-file = "checksums.sha256"
|
|
10
|
+
|
|
11
|
+
[platform.macos]
|
|
12
|
+
download-file = "hadolint-macos-{arch}"
|
|
13
|
+
checksum-file = "checksums.sha256"
|
|
14
|
+
|
|
15
|
+
[install]
|
|
16
|
+
download-url = "https://github.com/hadolint/hadolint/releases/download/v{version}/{download_file}"
|
|
17
|
+
checksum-url = "https://github.com/hadolint/hadolint/releases/download/v{version}/{checksum_file}"
|
|
18
|
+
|
|
19
|
+
[install.arch]
|
|
20
|
+
aarch64 = "arm64"
|
|
21
|
+
x86_64 = "x86_64"
|
package/canon/files/prototools
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
proto = "0.64.0"
|
|
3
3
|
node = "26.13.1"
|
|
4
4
|
pnpm = "12.21.0"
|
|
5
|
-
bun = "1.4.
|
|
5
|
+
bun = "1.4.5"
|
|
6
6
|
moon = "2.6.5"
|
|
7
7
|
uv = "0.13.9"
|
|
8
8
|
|
|
@@ -10,9 +10,11 @@ uv = "0.13.9"
|
|
|
10
10
|
actionlint = "1.7.12"
|
|
11
11
|
shellcheck = "0.11.0"
|
|
12
12
|
gitleaks = "8.30.1"
|
|
13
|
+
hadolint = "2.15.1"
|
|
13
14
|
|
|
14
15
|
[plugins]
|
|
15
16
|
# Vendored: upstream github.com/Phault/proto-toml-plugins was removed 2026-09-13, its URL now returns 404.
|
|
16
17
|
actionlint = "file://./.moon/proto-plugins/actionlint.toml"
|
|
17
18
|
shellcheck = "file://./.moon/proto-plugins/shellcheck.toml"
|
|
18
19
|
gitleaks = "file://./.moon/proto-plugins/gitleaks.toml"
|
|
20
|
+
hadolint = "file://./.moon/proto-plugins/hadolint.toml"
|
|
@@ -11,6 +11,15 @@ on:
|
|
|
11
11
|
type: choice
|
|
12
12
|
options: [info, debug]
|
|
13
13
|
default: info
|
|
14
|
+
# Сам файл токен не берёт (Renovate работает под RENOVATE_TOKEN, это PAT), но renovate.yml@v1 просит contents: read,
|
|
15
|
+
# а права вызывающего — потолок вызываемого: с {} workflow недействителен целиком.
|
|
16
|
+
permissions:
|
|
17
|
+
contents: read
|
|
18
|
+
# Группа уникальна на прогон: очередь держит джоб renovate вызываемого (renovate-<репозиторий>, без отмены).
|
|
19
|
+
# Та же группа у вызывающего и вызываемого дала бы тупик.
|
|
20
|
+
concurrency:
|
|
21
|
+
group: ${{ github.workflow }}-${{ github.run_id }}
|
|
22
|
+
cancel-in-progress: false
|
|
14
23
|
jobs:
|
|
15
24
|
renovate:
|
|
16
25
|
uses: alxwlw/stack/.github/workflows/renovate.yml@v1
|
|
@@ -3,6 +3,16 @@ on:
|
|
|
3
3
|
pull_request:
|
|
4
4
|
push:
|
|
5
5
|
branches: [main]
|
|
6
|
+
# Токен берёт check.yml: actions/checkout и git fetch шага history читают репозиторий — contents: read. Права
|
|
7
|
+
# вызывающего — потолок для вызываемого, поэтому право записано здесь, а не только в check.yml.
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
# Группа: PR отменяет свой прежний прогон, push в main не отменяется (группа с run_id уникальна: общая группа
|
|
11
|
+
# отменяла бы и ждущий прогон даже при cancel-in-progress: false). check.yml своего concurrency не имеет —
|
|
12
|
+
# та же группа у вызываемого дала бы тупик.
|
|
13
|
+
concurrency:
|
|
14
|
+
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
|
15
|
+
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
|
6
16
|
jobs:
|
|
7
17
|
check:
|
|
8
18
|
uses: alxwlw/stack/.github/workflows/check.yml@v1
|
|
@@ -3,6 +3,16 @@ on:
|
|
|
3
3
|
pull_request:
|
|
4
4
|
push:
|
|
5
5
|
branches: [main]
|
|
6
|
+
# Токен берёт check.yml: actions/checkout и git fetch шага history читают репозиторий — contents: read. Права
|
|
7
|
+
# вызывающего — потолок для вызываемого, поэтому право записано здесь, а не только в check.yml.
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
# Группа: PR отменяет свой прежний прогон, push в main не отменяется (группа с run_id уникальна: общая группа
|
|
11
|
+
# отменяла бы и ждущий прогон даже при cancel-in-progress: false). check.yml своего concurrency не имеет —
|
|
12
|
+
# та же группа у вызываемого дала бы тупик.
|
|
13
|
+
concurrency:
|
|
14
|
+
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
|
15
|
+
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
|
6
16
|
jobs:
|
|
7
17
|
check:
|
|
8
18
|
uses: alxwlw/stack/.github/workflows/check.yml@v1
|
|
@@ -5,6 +5,16 @@ on:
|
|
|
5
5
|
version:
|
|
6
6
|
required: true
|
|
7
7
|
type: string
|
|
8
|
+
# sync.yml сегодня GITHUB_TOKEN не берёт: клон и PR идут токеном приложения (secrets app-id и app-private-key).
|
|
9
|
+
# contents: read — потолок про запас: если sync.yml@v1 позже начнёт читать репозиторий этим токеном, workflow
|
|
10
|
+
# потребителя всё равно запустится до того, как его sync-PR с новой копией будет открыт.
|
|
11
|
+
permissions:
|
|
12
|
+
contents: read
|
|
13
|
+
# Группа уникальна на прогон: очередь по версии держит джоб sync вызываемого (stack-sync-<версия>, без отмены).
|
|
14
|
+
# Та же группа у вызывающего и вызываемого дала бы тупик.
|
|
15
|
+
concurrency:
|
|
16
|
+
group: ${{ github.workflow }}-${{ github.run_id }}
|
|
17
|
+
cancel-in-progress: false
|
|
8
18
|
jobs:
|
|
9
19
|
sync:
|
|
10
20
|
uses: alxwlw/stack/.github/workflows/sync.yml@v1
|
package/canon/manifest.json
CHANGED
|
@@ -63,6 +63,11 @@
|
|
|
63
63
|
"dest": ".moon/proto-plugins/gitleaks.toml",
|
|
64
64
|
"appliesTo": ["node", "contracts", "infra"]
|
|
65
65
|
},
|
|
66
|
+
{
|
|
67
|
+
"src": "files/proto-plugins/hadolint.toml",
|
|
68
|
+
"dest": ".moon/proto-plugins/hadolint.toml",
|
|
69
|
+
"appliesTo": ["node", "contracts", "infra"]
|
|
70
|
+
},
|
|
66
71
|
{
|
|
67
72
|
"src": "files/oxfmtrc.jsonc",
|
|
68
73
|
"dest": ".oxfmtrc.jsonc",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxwlw/stack",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.18.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -22,8 +22,10 @@
|
|
|
22
22
|
"provenance": true
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
+
"@alxwlw/repo-rules": "1.18.0",
|
|
25
26
|
"json5": "^2.2.3",
|
|
26
27
|
"jsonc-parser": "^3.3.1",
|
|
28
|
+
"markdownlint-cli2": "0.24.2",
|
|
27
29
|
"yaml": "^2.9.1"
|
|
28
30
|
}
|
|
29
31
|
}
|
package/schema.json
CHANGED
|
@@ -14,7 +14,16 @@
|
|
|
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": [
|
|
17
|
+
"enum": [
|
|
18
|
+
"depcruise",
|
|
19
|
+
"guardrails",
|
|
20
|
+
"knip",
|
|
21
|
+
"libs",
|
|
22
|
+
"moon-tasks",
|
|
23
|
+
"peers",
|
|
24
|
+
"renovate",
|
|
25
|
+
"repo-rules"
|
|
26
|
+
]
|
|
18
27
|
}
|
|
19
28
|
},
|
|
20
29
|
"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', 'guardrails'] 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,125 @@ 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 {
|
|
13
|
+
import { type GuardrailsOutcome, readGuardrails } from './guardrails.ts';
|
|
14
|
+
import type { GuardrailsPort } from './guardrails-port.ts';
|
|
15
|
+
import { checkGuardrails, guardrailsNotes } from './guardrails-rule.ts';
|
|
16
|
+
import { checkMoonToolchains, checkMoonV1Toolchain } from './moon-toolchains.ts';
|
|
14
17
|
import { checkMoonDefaultBranch, planMoonDefaultBranch } from './moon-workspace.ts';
|
|
15
18
|
import { planPackageManager } from './package-manager.ts';
|
|
16
19
|
import { type PeersOutcome, peersOutcome, type PeersReader } from './peers.ts';
|
|
17
20
|
import { checkPeers } from './peers-rule.ts';
|
|
18
21
|
import { planReleaseAgeExcludes } from './release-age.ts';
|
|
19
22
|
import { loadRepo, LOCKFILE, type Repo } from './repo.ts';
|
|
23
|
+
import { readRepoRules, type RepoRulesOutcome, type RepoRulesPort } from './repo-rules.ts';
|
|
24
|
+
import { checkRepoRules, repoRulesNotes } from './repo-rules-rule.ts';
|
|
25
|
+
import { checkSeedExtends } from './seed-extends.ts';
|
|
26
|
+
import { planToolchainPins } from './toolchain-pins-rule.ts';
|
|
27
|
+
import { checkWorkflowHygiene } from './workflow-hygiene.ts';
|
|
20
28
|
|
|
21
29
|
// План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, release-age,
|
|
22
|
-
// packageManager, ветка по умолчанию moon
|
|
23
|
-
|
|
30
|
+
// packageManager, ветка по умолчанию moon, копии пинов тулчейна. Правки одного файла друг от друга не
|
|
31
|
+
// зависят: sync применяет любое их подмножество. Исключения нужны правилу копий пинов: удержанный
|
|
32
|
+
// .prototools меняет, с какими пинами оно сверяется; сами находки гасит resolve.
|
|
33
|
+
export function plan(repo: Repo, canon: Canon, exceptions: readonly Exception[] = []): Drift[] {
|
|
24
34
|
return [
|
|
25
35
|
...planFiles(repo, canon),
|
|
26
36
|
...planCatalogs(repo, canon),
|
|
27
37
|
...planReleaseAgeExcludes(repo, canon),
|
|
28
38
|
...planPackageManager(repo, canon),
|
|
29
39
|
...planMoonDefaultBranch(repo),
|
|
40
|
+
...planToolchainPins(repo, canon, exceptions),
|
|
30
41
|
];
|
|
31
42
|
}
|
|
32
43
|
|
|
33
|
-
// Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts и moon,
|
|
34
|
-
//
|
|
35
|
-
// исключения. peers — исход `pnpm peers check`,
|
|
44
|
+
// Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts, засевы и moon,
|
|
45
|
+
// правила групп peers, repo-rules и guardrails, если они включены (в этом порядке); затем протухшие исключения.
|
|
46
|
+
// Все они проходят через исключения. peers — исход `pnpm peers check`, repoRules — исход двух вызовов
|
|
47
|
+
// repo-rules, guardrails — исход чтения отслеживаемых файлов, инструментов и скана коммитов PR; все три получает checkRepo.
|
|
36
48
|
export function check(
|
|
37
49
|
repo: Repo,
|
|
38
50
|
canon: Canon,
|
|
39
51
|
exceptions: Exception[],
|
|
40
52
|
peers?: PeersOutcome,
|
|
53
|
+
repoRules?: RepoRulesOutcome,
|
|
54
|
+
guardrails?: GuardrailsOutcome,
|
|
41
55
|
): Finding[] {
|
|
42
56
|
const r = resolve(
|
|
43
57
|
[
|
|
44
|
-
...plan(repo, canon),
|
|
58
|
+
...plan(repo, canon, exceptions),
|
|
45
59
|
...repo.unreadable,
|
|
46
60
|
...checkInlineVersions(repo, canon),
|
|
47
61
|
...checkEnginesNode(repo, canon),
|
|
48
62
|
...checkRenovatePreset(repo),
|
|
49
63
|
...checkDependabot(repo),
|
|
64
|
+
...checkSeedExtends(repo, canon),
|
|
50
65
|
...checkMoonToolchains(repo, canon),
|
|
66
|
+
...checkMoonV1Toolchain(repo),
|
|
51
67
|
...checkMoonDefaultBranch(repo),
|
|
52
68
|
...(canon.rules.includes('peers') ? checkPeers(repo, peers) : []),
|
|
69
|
+
...(canon.rules.includes('repo-rules') ? checkRepoRules(repoRules) : []),
|
|
70
|
+
...(canon.rules.includes('guardrails')
|
|
71
|
+
? [...checkGuardrails(guardrails), ...checkWorkflowHygiene(repo.files)]
|
|
72
|
+
: []),
|
|
53
73
|
],
|
|
54
74
|
exceptions,
|
|
55
75
|
);
|
|
56
76
|
return [...r.findings, ...r.stale];
|
|
57
77
|
}
|
|
58
78
|
|
|
59
|
-
export function planRepo(
|
|
60
|
-
|
|
79
|
+
export function planRepo(
|
|
80
|
+
repoRoot: string,
|
|
81
|
+
canon: Canon,
|
|
82
|
+
exceptions: readonly Exception[] = [],
|
|
83
|
+
): Drift[] {
|
|
84
|
+
return plan(loadRepo(repoRoot, canon), canon, exceptions);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Порты `checkRepo`: каждый нужен только своей группе. */
|
|
88
|
+
export interface CheckPorts {
|
|
89
|
+
peers?: PeersReader;
|
|
90
|
+
repoRules?: RepoRulesPort;
|
|
91
|
+
guardrails?: GuardrailsPort;
|
|
92
|
+
}
|
|
93
|
+
/** Итог check: находки (блокируют, если не удержаны) и пометки (выход не меняют). */
|
|
94
|
+
export interface CheckReport {
|
|
95
|
+
findings: Finding[];
|
|
96
|
+
notes: string[];
|
|
61
97
|
}
|
|
62
98
|
|
|
63
99
|
// pnpm запускается, только если группа peers включена и лок есть: без лока правило отвечает само.
|
|
100
|
+
// repo-rules — только если включена группа: два вызова через порт, пометки идут отдельно от находок.
|
|
101
|
+
// guardrails — тоже только если включена группа: один `git ls-files`, пробы версий, запуски инструментов, `git merge-base` и второй запуск gitleaks по коммитам PR.
|
|
64
102
|
export function checkRepo(
|
|
65
103
|
repoRoot: string,
|
|
66
104
|
canon: Canon,
|
|
67
105
|
exceptions: Exception[],
|
|
68
|
-
|
|
69
|
-
):
|
|
106
|
+
ports: CheckPorts = {},
|
|
107
|
+
): CheckReport {
|
|
70
108
|
const repo = loadRepo(repoRoot, canon);
|
|
71
109
|
let peers: PeersOutcome | undefined;
|
|
72
110
|
if (canon.rules.includes('peers') && repo.paths.has(LOCKFILE)) {
|
|
73
|
-
if (
|
|
74
|
-
peers = peersOutcome(
|
|
111
|
+
if (ports.peers === undefined) throw new Error('checkRepo: peers group needs a PeersReader');
|
|
112
|
+
peers = peersOutcome(ports.peers(repoRoot));
|
|
113
|
+
}
|
|
114
|
+
let repoRules: RepoRulesOutcome | undefined;
|
|
115
|
+
if (canon.rules.includes('repo-rules')) {
|
|
116
|
+
if (ports.repoRules === undefined) {
|
|
117
|
+
throw new Error('checkRepo: repo-rules group needs a RepoRulesPort');
|
|
118
|
+
}
|
|
119
|
+
repoRules = readRepoRules(repoRoot, ports.repoRules);
|
|
120
|
+
}
|
|
121
|
+
let guardrails: GuardrailsOutcome | undefined;
|
|
122
|
+
if (canon.rules.includes('guardrails')) {
|
|
123
|
+
if (ports.guardrails === undefined) {
|
|
124
|
+
throw new Error('checkRepo: guardrails group needs a GuardrailsPort');
|
|
125
|
+
}
|
|
126
|
+
guardrails = readGuardrails(repoRoot, repo.files.get('.prototools'), ports.guardrails);
|
|
75
127
|
}
|
|
76
|
-
return
|
|
128
|
+
return {
|
|
129
|
+
findings: check(repo, canon, exceptions, peers, repoRules, guardrails),
|
|
130
|
+
notes: [...repoRulesNotes(repoRules), ...guardrailsNotes(guardrails)],
|
|
131
|
+
};
|
|
77
132
|
}
|
|
78
133
|
|
|
79
134
|
export interface SyncResult {
|
|
@@ -87,7 +142,7 @@ export interface SyncResult {
|
|
|
87
142
|
export function syncRepo(repoRoot: string, canon: Canon, exceptions: Exception[]): SyncResult {
|
|
88
143
|
const repo = loadRepo(repoRoot, canon);
|
|
89
144
|
const result: SyncResult = { applied: [], held: [] };
|
|
90
|
-
for (const d of resolve(plan(repo, canon), exceptions).findings) {
|
|
145
|
+
for (const d of resolve(plan(repo, canon, exceptions), exceptions).findings) {
|
|
91
146
|
if (isHeld(d)) result.held.push(d);
|
|
92
147
|
else result.applied.push(d);
|
|
93
148
|
}
|
package/src/cli.ts
CHANGED
|
@@ -3,17 +3,22 @@ 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';
|
|
9
11
|
import { allowedLine, isHeld } from './exceptions.ts';
|
|
10
12
|
import { type Finding, isDrift } from './findings.ts';
|
|
11
13
|
import { ghGitHub } from './gh.ts';
|
|
14
|
+
import { spawnRunner } from './guardrails-port.ts';
|
|
12
15
|
import { initConfig } from './init.ts';
|
|
16
|
+
import { ownVersion } from './own-packages.ts';
|
|
13
17
|
import type { PeersReader } from './peers.ts';
|
|
14
18
|
import { peersBaseline } from './peers-baseline.ts';
|
|
15
19
|
import { npmRegistryReader } from './registry.ts';
|
|
16
|
-
import
|
|
20
|
+
import type { RepoRulesReader } from './repo-rules.ts';
|
|
21
|
+
import { type RunProcess, SYNC_PR_WAIT, syncPr, withoutGhToken } from './sync-pr.ts';
|
|
17
22
|
|
|
18
23
|
function fail(message: string): never {
|
|
19
24
|
console.error(message);
|
|
@@ -84,10 +89,59 @@ const pnpmPeers: PeersReader = (cwd) => {
|
|
|
84
89
|
return { status: r.status, signal: r.signal, stdout: r.stdout, stderr: r.stderr };
|
|
85
90
|
};
|
|
86
91
|
|
|
92
|
+
// Боевой adapter порта repo-rules: main не бросает, вывод собирается в строки без записи в поток.
|
|
93
|
+
const inProcessRepoRules: RepoRulesReader = (argv, env) => {
|
|
94
|
+
const out: string[] = [];
|
|
95
|
+
const err: string[] = [];
|
|
96
|
+
const code = repoRulesMain(
|
|
97
|
+
argv,
|
|
98
|
+
env,
|
|
99
|
+
(s) => void out.push(s),
|
|
100
|
+
(s) => void err.push(s),
|
|
101
|
+
);
|
|
102
|
+
return { code, out: out.join('\n'), err: err.join('\n') };
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// Проводник: аргументы после `repo-rules` уходят в repo-rules как есть, флаги stack здесь не разбираются.
|
|
106
|
+
// Версия правил — версия самого stack: пакет берётся из зависимостей stack, не из репозитория потребителя.
|
|
107
|
+
if (Bun.argv[2] === 'repo-rules') {
|
|
108
|
+
// Вывод собирается и дописывается до выхода: process.exit сразу после write обрывает канал на 128 КиБ.
|
|
109
|
+
let out = '';
|
|
110
|
+
let err = '';
|
|
111
|
+
const code = repoRulesMain(
|
|
112
|
+
Bun.argv.slice(3),
|
|
113
|
+
process.env,
|
|
114
|
+
(s) => void (out += `${s}\n`),
|
|
115
|
+
(s) => void (err += `${s}\n`),
|
|
116
|
+
);
|
|
117
|
+
// Ошибка записи (диск полон, канал закрыт) — одна строка и код 2, как в бинарнике repo-rules.
|
|
118
|
+
let writeError: Error | undefined;
|
|
119
|
+
const flush = (stream: NodeJS.WriteStream, text: string) =>
|
|
120
|
+
new Promise<void>((resolve) => {
|
|
121
|
+
if (text)
|
|
122
|
+
stream.write(text, (e) => {
|
|
123
|
+
writeError ??= e ?? undefined;
|
|
124
|
+
resolve();
|
|
125
|
+
});
|
|
126
|
+
else resolve();
|
|
127
|
+
});
|
|
128
|
+
await Promise.all([flush(process.stdout, out), flush(process.stderr, err)]);
|
|
129
|
+
if (writeError) {
|
|
130
|
+
process.stderr.write(`repo-rules: ${writeError.message}\n`);
|
|
131
|
+
process.exit(2);
|
|
132
|
+
}
|
|
133
|
+
process.exit(code);
|
|
134
|
+
}
|
|
135
|
+
|
|
87
136
|
const { values, positionals } = parseCliArgs();
|
|
88
137
|
|
|
89
138
|
const repoRoot = values.repo ?? process.cwd();
|
|
90
139
|
const command = positionals[0];
|
|
140
|
+
if (positionals.includes('repo-rules')) {
|
|
141
|
+
fail(
|
|
142
|
+
'repo-rules takes its own arguments and must come first: stack repo-rules [-C <dir>] <command>',
|
|
143
|
+
);
|
|
144
|
+
}
|
|
91
145
|
|
|
92
146
|
try {
|
|
93
147
|
if (command === 'init') {
|
|
@@ -107,7 +161,12 @@ try {
|
|
|
107
161
|
for (const line of stdout) console.log(line);
|
|
108
162
|
} else if (command === 'check') {
|
|
109
163
|
const cfg = readStackConfig(repoRoot);
|
|
110
|
-
const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions,
|
|
164
|
+
const { findings, notes } = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions, {
|
|
165
|
+
peers: pnpmPeers,
|
|
166
|
+
repoRules: { read: inProcessRepoRules, env: process.env, base: values.base },
|
|
167
|
+
guardrails: { run: spawnRunner(repoRoot), env: process.env, base: values.base },
|
|
168
|
+
});
|
|
169
|
+
for (const n of notes) console.warn(n);
|
|
111
170
|
const blocking = findings.filter((f) => !isHeld(f));
|
|
112
171
|
for (const f of findings.filter(isHeld)) console.warn(allowedLine(f));
|
|
113
172
|
for (const f of blocking) console.error(`${f.code}: ${f.target} — ${f.message}`);
|
|
@@ -137,6 +196,7 @@ try {
|
|
|
137
196
|
registry: npmRegistryReader(),
|
|
138
197
|
print: (stream, line) => (stream === 'out' ? console.log(line) : console.error(line)),
|
|
139
198
|
peers: pnpmPeers,
|
|
199
|
+
repoRules: inProcessRepoRules,
|
|
140
200
|
},
|
|
141
201
|
),
|
|
142
202
|
);
|
|
@@ -150,7 +210,7 @@ try {
|
|
|
150
210
|
process.exit(r.code);
|
|
151
211
|
} else {
|
|
152
212
|
fail(
|
|
153
|
-
`unknown command "${command ?? ''}". Available: init, sync, check, sync-pr, peers-baseline`,
|
|
213
|
+
`unknown command "${command ?? ''}". Available: init, sync, check, sync-pr, peers-baseline, repo-rules`,
|
|
154
214
|
);
|
|
155
215
|
}
|
|
156
216
|
} catch (error) {
|
package/src/exceptions.ts
CHANGED
|
@@ -92,14 +92,29 @@ 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',
|
|
113
|
+
// Находки guardrails — вывод инструментов над репозиторием; отказ от гейта — убрать группу из with.
|
|
114
|
+
'guardrails-violation': 'unsuppressible',
|
|
115
|
+
'guardrails-unavailable': 'unsuppressible',
|
|
116
|
+
// Гигиена workflow — наличие ключей в файле; отказ от гейта — убрать группу из with.
|
|
117
|
+
'workflow-hygiene': 'unsuppressible',
|
|
103
118
|
};
|
|
104
119
|
|
|
105
120
|
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,13 @@ 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'
|
|
41
|
+
| 'guardrails-violation'
|
|
42
|
+
| 'guardrails-unavailable'
|
|
43
|
+
| 'workflow-hygiene';
|
|
29
44
|
}
|
|
30
45
|
);
|
|
31
46
|
export type FindingCode = Finding['code'];
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import {
|
|
2
|
+
failureReason,
|
|
3
|
+
type GuardrailRun,
|
|
4
|
+
type GuardrailViolation,
|
|
5
|
+
type Unavailable,
|
|
6
|
+
} from './guardrails-port.ts';
|
|
7
|
+
import { QUIET_LEVELS } from './guardrails-shellcheck.ts';
|
|
8
|
+
|
|
9
|
+
// Флаги до файлов. shellcheck — путь пиненного бинарника или пусто (явно выключен: иначе actionlint
|
|
10
|
+
// берёт тот, что лежит в PATH); pyflakes не пинуется и выключен всегда.
|
|
11
|
+
export function actionlintArgv(shellcheck: string | undefined, files: readonly string[]): string[] {
|
|
12
|
+
return ['-format', '{{json .}}', `-shellcheck=${shellcheck ?? ''}`, '-pyflakes=', ...files];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const SHAPE = 'output has an unexpected shape: errors';
|
|
16
|
+
|
|
17
|
+
const SHELLCHECK_MESSAGE =
|
|
18
|
+
/^shellcheck reported issue in this script: SC(\d+):([a-z]+):\d+:\d+: (.*)$/s;
|
|
19
|
+
|
|
20
|
+
// Разбор `-format '{{json .}}'`: код 0 и 1 — вывод, прочее — недоступность. stderr при разобранном
|
|
21
|
+
// выводе не читается. Находка shellcheck внутри actionlint проходит тот же порог, что и shellcheck сам.
|
|
22
|
+
export function parseActionlint(run: GuardrailRun): GuardrailViolation[] | Unavailable {
|
|
23
|
+
if (run.code !== 0 && run.code !== 1) return { unavailable: failureReason(run) };
|
|
24
|
+
if (run.code === 0 && run.out.trim() === '') return [];
|
|
25
|
+
let data: unknown;
|
|
26
|
+
try {
|
|
27
|
+
data = JSON.parse(run.out);
|
|
28
|
+
} catch {
|
|
29
|
+
return { unavailable: 'output is not JSON' };
|
|
30
|
+
}
|
|
31
|
+
if (!Array.isArray(data)) return { unavailable: SHAPE };
|
|
32
|
+
const found: GuardrailViolation[] = [];
|
|
33
|
+
for (const item of data as unknown[]) {
|
|
34
|
+
if (typeof item !== 'object' || item === null) return { unavailable: SHAPE };
|
|
35
|
+
const { message, filepath, line, kind } = item as Record<string, unknown>;
|
|
36
|
+
if (
|
|
37
|
+
typeof message !== 'string' ||
|
|
38
|
+
typeof filepath !== 'string' ||
|
|
39
|
+
typeof line !== 'number' ||
|
|
40
|
+
typeof kind !== 'string'
|
|
41
|
+
) {
|
|
42
|
+
return { unavailable: SHAPE };
|
|
43
|
+
}
|
|
44
|
+
if (kind !== 'shellcheck') {
|
|
45
|
+
found.push({ tool: 'actionlint', rule: kind, path: filepath, line, message });
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
const m = SHELLCHECK_MESSAGE.exec(message);
|
|
49
|
+
if (m === null) {
|
|
50
|
+
found.push({ tool: 'actionlint', rule: 'shellcheck', path: filepath, line, message });
|
|
51
|
+
} else if (!QUIET_LEVELS.has(m[2] ?? '')) {
|
|
52
|
+
found.push({
|
|
53
|
+
tool: 'actionlint',
|
|
54
|
+
rule: `SC${m[1] ?? ''}`,
|
|
55
|
+
path: filepath,
|
|
56
|
+
line,
|
|
57
|
+
message: m[3] ?? '',
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (run.code === 1 && data.length === 0) {
|
|
62
|
+
return { unavailable: 'exited with 1 and reported nothing' };
|
|
63
|
+
}
|
|
64
|
+
return found;
|
|
65
|
+
}
|