@alxwlw/stack 1.13.0 → 1.15.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/src/sync-pr.ts CHANGED
@@ -5,6 +5,8 @@ import { join } from 'node:path';
5
5
  import { loadCanon } from './canon.ts';
6
6
  import { syncOutput, syncRepo } from './check.ts';
7
7
  import { readStackConfig, StackConfigError } from './config.ts';
8
+ import type { PeersReader } from './peers.ts';
9
+ import { peersBaseline } from './peers-baseline.ts';
8
10
  import { type Registry, type WaitOptions, waitVisible } from './registry.ts';
9
11
 
10
12
  export interface NewPr {
@@ -14,11 +16,21 @@ export interface NewPr {
14
16
  body: string;
15
17
  }
16
18
 
19
+ export interface OpenPr {
20
+ number: number;
21
+ url: string;
22
+ head: string; // headRefName
23
+ base: string; // baseRefName
24
+ author: string; // логин; у GitHub App — `<slug>[bot]`, у PR без автора — ''
25
+ }
26
+
17
27
  // Порт GitHub. Боевой adapter — gh; тесты — литерал.
18
28
  export interface GitHub {
19
29
  botUserId(slug: string): Promise<number>;
20
- openPr(head: string): Promise<string | undefined>; // URL открытого PR с этой веткой
21
30
  createPr(pr: NewPr): Promise<string>; // URL созданного PR
31
+ defaultBranch(): Promise<string>;
32
+ openPrs(): Promise<OpenPr[]>; // все открытые PR репозитория
33
+ closePr(number: number, comment: string): Promise<void>; // закрыть с комментарием; ветку не трогает
22
34
  }
23
35
 
24
36
  export type Print = (stream: 'out' | 'err', line: string) => void;
@@ -83,7 +95,62 @@ function changedFiles(repoRoot: string): string[] {
83
95
  const message = (error: unknown): string =>
84
96
  error instanceof Error ? error.message : String(error);
85
97
 
86
- // Всё после установки и хука: список изменённых файлов, пользователь бота, ветка, commit, force-push, PR.
98
+ const SYNC_BRANCH = /^stack\/v(\d+\.\d+\.\d+)$/;
99
+
100
+ // PR бота из веток `stack/v<X.Y.Z>` строго старше version с той же базой; порядок входа сохраняется.
101
+ // Ветку проверяем первой: PR с чужой или битой веткой под правило не попадает, что бы ни лежало в других полях.
102
+ export function stalePrs(
103
+ prs: readonly OpenPr[],
104
+ opts: { version: string; base: string; bot: string },
105
+ ): OpenPr[] {
106
+ return prs.filter((pr) => {
107
+ const m = SYNC_BRANCH.exec(pr.head);
108
+ return (
109
+ m !== null &&
110
+ pr.author === opts.bot &&
111
+ pr.base === opts.base &&
112
+ Bun.semver.order(m[1] as string, opts.version) < 0
113
+ );
114
+ });
115
+ }
116
+
117
+ // Закрывает устаревшие PR по порядку: комментарий, затем удаление ветки. Первая ошибка останавливает.
118
+ // Ветку не трогаем, пока на ней открыт PR, который мы не закрываем (другая база).
119
+ async function closeStale(
120
+ repoRoot: string,
121
+ github: GitHub,
122
+ print: Print,
123
+ prs: readonly OpenPr[],
124
+ stale: readonly OpenPr[],
125
+ comment: string,
126
+ ): Promise<0 | 1> {
127
+ for (const pr of stale) {
128
+ try {
129
+ await github.closePr(pr.number, comment);
130
+ } catch (error) {
131
+ print('err', `sync-pr: closing PR ${pr.url} failed: ${message(error)}`);
132
+ return 1;
133
+ }
134
+ const other = prs.find((p) => p.head === pr.head && !stale.some((s) => s.number === p.number));
135
+ if (!other) {
136
+ const r = runGit(repoRoot, ['push', 'origin', '--delete', pr.head]);
137
+ if (!r.ok) {
138
+ print('err', `sync-pr: git push --delete ${pr.head} failed: ${r.stderr}`);
139
+ return 1;
140
+ }
141
+ }
142
+ print(
143
+ 'out',
144
+ other
145
+ ? `closed PR ${pr.url} (${pr.head} kept: ${other.url} is open on it)`
146
+ : `closed PR ${pr.url} (${pr.head})`,
147
+ );
148
+ }
149
+ return 0;
150
+ }
151
+
152
+ // Всё после установки и хука: список изменённых файлов, ветка по умолчанию, пользователь бота, ветка,
153
+ // commit, force-push, PR и закрытие PR старших версий.
87
154
  export async function publishChanges(
88
155
  opts: PublishOptions,
89
156
  github: GitHub,
@@ -92,6 +159,7 @@ export async function publishChanges(
92
159
  const { repoRoot, version, appSlug } = opts;
93
160
  const branch = `stack/v${version}`;
94
161
  const title = `chore(stack): канон ${version}`;
162
+ const bot = `${appSlug}[bot]`;
95
163
 
96
164
  let files: string[];
97
165
  try {
@@ -100,9 +168,36 @@ export async function publishChanges(
100
168
  print('err', `sync-pr: git status failed: ${message(error)}`);
101
169
  return 1;
102
170
  }
171
+
172
+ let base: string;
173
+ try {
174
+ base = opts.base || (await github.defaultBranch());
175
+ } catch (error) {
176
+ print('err', `sync-pr: default branch lookup failed: ${message(error)}`);
177
+ return 1;
178
+ }
179
+
180
+ const listOpen = async (): Promise<OpenPr[] | undefined> => {
181
+ try {
182
+ return await github.openPrs();
183
+ } catch (error) {
184
+ print('err', `sync-pr: listing open PRs failed: ${message(error)}`);
185
+ return undefined;
186
+ }
187
+ };
188
+
103
189
  if (files.length === 0) {
104
190
  print('out', 'canon already applied, nothing to commit');
105
- return 0;
191
+ const prs = await listOpen();
192
+ if (!prs) return 1;
193
+ return closeStale(
194
+ repoRoot,
195
+ github,
196
+ print,
197
+ prs,
198
+ stalePrs(prs, { version, base, bot }),
199
+ `Канон ${version} уже в \`${base}\` — этот PR устарел.`,
200
+ );
106
201
  }
107
202
 
108
203
  let id: number;
@@ -113,7 +208,6 @@ export async function publishChanges(
113
208
  return 1;
114
209
  }
115
210
 
116
- const bot = `${appSlug}[bot]`;
117
211
  const steps: [string, string[]][] = [
118
212
  ['checkout', ['checkout', '-B', branch]],
119
213
  ['add', ['add', '-A']],
@@ -140,28 +234,29 @@ export async function publishChanges(
140
234
  }
141
235
  print('out', `pushed ${branch}`);
142
236
 
143
- let url: string | undefined;
144
- try {
145
- url = await github.openPr(branch);
146
- } catch (error) {
147
- print('err', `sync-pr: finding the open PR failed: ${message(error)}`);
148
- return 1;
149
- }
237
+ const prs = await listOpen();
238
+ if (!prs) return 1;
239
+ let url = prs.find((p) => p.head === branch && p.base === base)?.url;
150
240
  if (url) {
151
241
  print('out', `updated PR ${url}`);
152
- return 0;
242
+ } else {
243
+ try {
244
+ url = await github.createPr({ head: branch, base, title, body: prBody(version, files) });
245
+ } catch (error) {
246
+ print('err', `sync-pr: creating the PR failed: ${message(error)}`);
247
+ return 1;
248
+ }
249
+ print('out', `opened PR ${url}`);
153
250
  }
154
251
 
155
- try {
156
- const pr: NewPr = { head: branch, title, body: prBody(version, files) };
157
- if (opts.base) pr.base = opts.base;
158
- url = await github.createPr(pr);
159
- } catch (error) {
160
- print('err', `sync-pr: creating the PR failed: ${message(error)}`);
161
- return 1;
162
- }
163
- print('out', `opened PR ${url}`);
164
- return 0;
252
+ return closeStale(
253
+ repoRoot,
254
+ github,
255
+ print,
256
+ prs,
257
+ stalePrs(prs, { version, base, bot }),
258
+ `Заменён ${url} — канон ${version}.`,
259
+ );
165
260
  }
166
261
 
167
262
  // Порт процессов: код выхода; вывод процесса идёт в лог job (боевой adapter наследует stdio).
@@ -181,6 +276,7 @@ export interface SyncPrPorts {
181
276
  github: GitHub;
182
277
  registry: Registry;
183
278
  print: Print;
279
+ peers: PeersReader;
184
280
  }
185
281
 
186
282
  // Как ATTEMPTS/INTERVAL шага ожидания в sync.yml.
@@ -246,6 +342,13 @@ export async function syncPr(opts: SyncPrOptions, ports: SyncPrPorts): Promise<0
246
342
  if (opts.install) step('pnpm', ['install', '--no-frozen-lockfile']);
247
343
  if (hook) step('pnpm', ['run', 'stack:post-sync'], { VERSION: version });
248
344
 
345
+ // Новый лок мог исправить записи baseline группы peers: они уходят в тот же коммит, иначе CI
346
+ // sync-PR краснел бы на stale-peer-baseline. Новые записи не добавляются, а код не меняет итог:
347
+ // и новые записи, и сбой pnpm покажет stack check в CI sync-PR. Группу проверяет peersBaseline.
348
+ const peers = peersBaseline(repoRoot, canon, 'drop-fixed', ports.peers);
349
+ for (const line of peers.out) print('out', line);
350
+ for (const line of peers.err) print('err', `sync-pr: peers baseline: ${line}`);
351
+
249
352
  return await publishChanges(opts, ports.github, print);
250
353
  } catch (error) {
251
354
  print('err', `sync-pr: ${message(error)}`);