rman 2.32.0 → 2.33.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.
@@ -1,4 +1,4 @@
1
- import type { PublishFilesKeys } from '../../../core/interfaces/publish-target.js';
1
+ import type { PublishFilesKeys, PublishHookKeys } from '../../../core/interfaces/publish-target.js';
2
2
  import type { ConfigValue, RmanConfig, ScopedVars } from '../../../interfaces/rman-config.interface.js';
3
3
  import type { CiService } from './services/ci.service.js';
4
4
  /**
@@ -27,7 +27,7 @@ export declare namespace RmanNodeConfig {
27
27
  */
28
28
  interface NpmPublishOptions extends NpmPublishOptionsKeys, ScopedVars {
29
29
  }
30
- interface NpmPublishOptionsKeys extends PublishFilesKeys {
30
+ interface NpmPublishOptionsKeys extends PublishFilesKeys, PublishHookKeys {
31
31
  /** Where this package's publishable output lives, relative to its own directory (e.g.
32
32
  * `"build"`). Per-package cascaded, so a root `"[*]"` block can say it once for the whole
33
33
  * repository instead of repeating `publishConfig.directory` in every `package.json` - which
@@ -1,4 +1,4 @@
1
- import type { PublishFilesKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
1
+ import type { PublishFilesKeys, PublishHookKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
2
2
  import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.interface.js';
3
3
  /**
4
4
  * **`publish.cloudflare.*`** - this target's own config block, declared beside it and reaching
@@ -9,7 +9,7 @@ import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.in
9
9
  */
10
10
  export interface CloudflarePublishOptions extends CloudflarePublishOptionsKeys, ScopedVars {
11
11
  }
12
- export interface CloudflarePublishOptionsKeys extends PublishFilesKeys {
12
+ export interface CloudflarePublishOptionsKeys extends PublishFilesKeys, PublishHookKeys {
13
13
  /**
14
14
  * What the package deploys as: `"pages"` - a directory of static files uploaded to a Pages
15
15
  * project (`wrangler pages deploy`) - or `"workers"` - a Worker, static assets included, as its
@@ -1,4 +1,4 @@
1
- import type { PublishFilesKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
1
+ import type { PublishFilesKeys, PublishHookKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
2
2
  import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.interface.js';
3
3
  /**
4
4
  * **`publish.docker.*`** - this target's own config block, declared here rather than centrally.
@@ -15,7 +15,7 @@ export interface DockerPublishOptions extends DockerPublishOptionsKeys, ScopedVa
15
15
  /** Every key here is a **value**, so every one is a `ConfigValue` - this target declares no step,
16
16
  * which is what makes the whole block uniform (see `VersionExtraKeys` for the interface where it
17
17
  * is not). */
18
- export interface DockerPublishOptionsKeys extends PublishFilesKeys {
18
+ export interface DockerPublishOptionsKeys extends PublishFilesKeys, PublishHookKeys {
19
19
  /** DockerHub image name/repository - bare (e.g. `"my-app"`) to be prefixed with
20
20
  * `--docker-namespace`/`DOCKERHUB_NAMESPACE`, or already-namespaced (contains a `/`) to use
21
21
  * verbatim. */
@@ -1,4 +1,4 @@
1
- import type { PublishFilesKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
1
+ import type { PublishFilesKeys, PublishHookKeys, PublishTarget } from '../../../core/interfaces/publish-target.js';
2
2
  import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.interface.js';
3
3
  /**
4
4
  * **`publish.spm.*`** - this target's own config block, reaching `RmanConfig` through the
@@ -6,7 +6,7 @@ import type { ConfigValue, ScopedVars } from '../../../interfaces/rman-config.in
6
6
  */
7
7
  export interface SpmPublishOptions extends SpmPublishOptionsKeys, ScopedVars {
8
8
  }
9
- export interface SpmPublishOptionsKeys extends PublishFilesKeys {
9
+ export interface SpmPublishOptionsKeys extends PublishFilesKeys, PublishHookKeys {
10
10
  /** Who may see the package: `"public"` or `"private"`. spm's own default - a new package is
11
11
  * private - applies when unset. `--spm-access` overrides it. */
12
12
  access?: ConfigValue<'public' | 'private'>;
@@ -2,6 +2,7 @@ import type { CloudflarePublishOptions } from '../builtins/publish-targets/cloud
2
2
  import type { DockerPublishOptions } from '../builtins/publish-targets/docker/docker.target.js';
3
3
  import type { SpmPublishOptions } from '../builtins/publish-targets/spm/spm.target.js';
4
4
  import type { RmanApplication } from '../core/application.js';
5
+ import { type PublishHookKeys } from '../core/interfaces/publish-target.js';
5
6
  import { type RmanConfig } from '../interfaces/rman-config.interface.js';
6
7
  /** Hoisted for `ArgsOf` - see `version.command.ts` and `RmanConfig.ArgsOf` for why. */
7
8
  declare const COMMAND: "publish";
@@ -105,7 +106,7 @@ declare const config: {
105
106
  * ... are not identical` (measured) - so `publish` is contributed once, here, and everything under
106
107
  * it merges into this one interface first.
107
108
  */
108
- export interface PublishExtraKeys extends PublishTargetConfigs {
109
+ export interface PublishExtraKeys extends PublishTargetConfigs, PublishHookKeys {
109
110
  }
110
111
  /** Where a target declares its own `publish.<target>` config block. Augmented, never edited. */
111
112
  export interface PublishTargetConfigs {
@@ -2,8 +2,9 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import readline from 'node:readline/promises';
4
4
  import colors from 'ansi-colors';
5
- import { shipsTo, unknownTargets } from '../core/interfaces/publish-target.js';
5
+ import { shipsTo, unknownTargets, } from '../core/interfaces/publish-target.js';
6
6
  import { registerCommand } from '../interfaces/rman-config.interface.js';
7
+ import { RunService } from '../services/run.service.js';
7
8
  import { assertAllowedBranch, branchGuardOptions, readBranchGuardOptions } from '../utils/branch-guard.js';
8
9
  import { UNCOMMITTED } from '../utils/git.js';
9
10
  import { packageFilterOptions, readPackageFilterOptions } from '../utils/package-filter.js';
@@ -213,6 +214,37 @@ const publishCommand = registerCommand(app => {
213
214
  const outcomes = [];
214
215
  const results = new Map();
215
216
  const publishedBy = new Map();
217
+ const log = args.json ? console.error : console.log;
218
+ /** A hook that failed takes its package out: the entry becomes an `'error'` in the plan the
219
+ * target is handed - so the target leaves it alone - and in the recap. */
220
+ const failHook = (label, plan, i, reason) => {
221
+ plan[i] = { ...plan[i], status: 'error', reason };
222
+ log(colors.red('failed'), colors.gray(`[${label}] `) + colors.cyan(plan[i].package.name), colors.red(reason));
223
+ outcomes.push({ target: label, entry: plan[i] });
224
+ };
225
+ /** `publish.before`, once per package with anything to publish, ahead of every target. */
226
+ const publishing = new Map();
227
+ for (const [target, plan] of plans) {
228
+ for (const e of plan)
229
+ if (e.status === 'publish')
230
+ publishing.set(e.package, [...(publishing.get(e.package) ?? []), target]);
231
+ }
232
+ for (const [pkg, shipsWith] of publishing) {
233
+ const steps = hookSteps(pkg, ['publish'], 'before');
234
+ if (!steps.length)
235
+ continue;
236
+ try {
237
+ await RunService.runHook(pkg, steps, ['publish'], {
238
+ RMAN_PUBLISH_TARGETS: shipsWith.map(t => t.name).join(','),
239
+ });
240
+ }
241
+ catch (e) {
242
+ for (const target of shipsWith) {
243
+ const plan = plans.get(target);
244
+ failHook(target.name, plan, plan.findIndex(x => x.package === pkg), `publish.before: ${e.message}`);
245
+ }
246
+ }
247
+ }
216
248
  let waited = false;
217
249
  for (const [target, plan] of plans) {
218
250
  /** Once, before the first target built from what the others published - see
@@ -224,17 +256,68 @@ const publishCommand = registerCommand(app => {
224
256
  const files = plan.filter(e => e.status === 'publish').flatMap(e => filesFor(e.package, target));
225
257
  const staged = files.length ? PublishFiles.stage(repository.dirname, `[${target.name}]`, files) : undefined;
226
258
  let applied;
259
+ const at = ['publish', target.name];
227
260
  try {
261
+ /** The target's own `before`, with its files already in place - the package as it ships. */
262
+ for (let i = 0; i < plan.length; i++) {
263
+ const entry = plan[i];
264
+ const steps = entry.status === 'publish' ? hookSteps(entry.package, at, 'before') : [];
265
+ if (!steps.length)
266
+ continue;
267
+ try {
268
+ await RunService.runHook(entry.package, steps, at, { RMAN_PUBLISH_TARGET: target.name });
269
+ }
270
+ catch (e) {
271
+ failHook(target.name, plan, i, `publish.${target.name}.before: ${e.message}`);
272
+ }
273
+ }
228
274
  applied = await target.applyPlan(ctx, plan);
229
275
  }
230
276
  finally {
231
277
  staged?.restore();
232
278
  }
279
+ /** The target's own `after`, for each package it did publish. A failure here is reported, but
280
+ * the package is on the registry - the reason says so. */
281
+ for (let i = 0; i < applied.length; i++) {
282
+ const entry = applied[i];
283
+ const planned = plan.find(e => e.package === entry.package);
284
+ const steps = entry.status === 'publish' && planned?.status === 'publish' ? hookSteps(entry.package, at, 'after') : [];
285
+ if (!steps.length)
286
+ continue;
287
+ try {
288
+ await RunService.runHook(entry.package, steps, at, { RMAN_PUBLISH_TARGET: target.name });
289
+ }
290
+ catch (e) {
291
+ applied[i] = {
292
+ ...entry,
293
+ status: 'error',
294
+ reason: `published, but publish.${target.name}.after: ${e.message}`,
295
+ };
296
+ }
297
+ }
233
298
  results.set(target, applied);
234
299
  const done = printApplied(applied, plan, target.name, args.json ? console.error : console.log);
235
300
  outcomes.push(...done);
236
301
  publishedBy.set(target, done.filter(o => o.entry.status === 'publish').map(o => o.entry));
237
302
  }
303
+ /** `publish.after`, once per package every one of whose targets published it. */
304
+ for (const [pkg, shipsWith] of publishing) {
305
+ const done = shipsWith.every(t => results.get(t)?.find(e => e.package === pkg)?.status === 'publish');
306
+ const steps = done ? hookSteps(pkg, ['publish'], 'after') : [];
307
+ if (!steps.length)
308
+ continue;
309
+ try {
310
+ await RunService.runHook(pkg, steps, ['publish'], {
311
+ RMAN_PUBLISH_TARGETS: shipsWith.map(t => t.name).join(','),
312
+ });
313
+ }
314
+ catch (e) {
315
+ const entry = results.get(shipsWith[0]).find(x => x.package === pkg);
316
+ const reason = `published, but publish.after: ${e.message}`;
317
+ log(colors.red('failed'), colors.gray('[publish] ') + colors.cyan(pkg.name), colors.red(reason));
318
+ outcomes.push({ target: 'publish', entry: { ...entry, status: 'error', reason } });
319
+ }
320
+ }
238
321
  printJson(jsonResult(plans, results));
239
322
  if (!args.json)
240
323
  printRecap(outcomes);
@@ -529,3 +612,12 @@ async function confirm(question) {
529
612
  rl.close();
530
613
  }
531
614
  }
615
+ /** The hook steps at `at.<slot>` of `pkg`'s config - `publish.before`, `publish.spm.after` - as a
616
+ * list, refused when one is not a step. */
617
+ function hookSteps(pkg, at, slot) {
618
+ let node = pkg.config;
619
+ for (const key of at)
620
+ node = node && typeof node === 'object' ? node[key] : undefined;
621
+ const value = node && typeof node === 'object' ? node[slot] : undefined;
622
+ return value === undefined ? [] : RunService.normalizeScriptValue(value, `${at.join('.')}.${slot}`, { topo: false });
623
+ }
package/constants.js CHANGED
@@ -1 +1 @@
1
- export const version = '2.32.0';
1
+ export const version = '2.33.0';
@@ -65,6 +65,11 @@ export const STEP_PATHS = [
65
65
  'version.before',
66
66
  'version.exec',
67
67
  'version.after',
68
+ /** `rman publish`'s hooks, around the package's publish and around each target's. */
69
+ 'publish.before',
70
+ 'publish.after',
71
+ 'publish.*.before',
72
+ 'publish.*.after',
68
73
  /**
69
74
  * The step inside a step's **object** form (`{ topo: true, command: buildWithTsc() }`).
70
75
  *
@@ -3,6 +3,7 @@ import type { PackageFilterOptions } from '../../utils/package-filter.js';
3
3
  import type { RmanApplication } from '../application.js';
4
4
  import type { Package } from '../classes/package.js';
5
5
  import type { Repository } from '../classes/repository.js';
6
+ import type { RunStepValue } from './run-step.js';
6
7
  /**
7
8
  * **Where a package's artifact ships, as a contribution.**
8
9
  *
@@ -140,6 +141,23 @@ export declare namespace PublishTarget {
140
141
  };
141
142
  }
142
143
  }
144
+ /**
145
+ * `publish.before` / `publish.after`, and the same pair in every `publish.<target>` block - steps run
146
+ * in the package's directory around its publish, in this order: `publish.before`, then for each
147
+ * target `publish.<target>.before`, the publish, `publish.<target>.after`, and `publish.after` once
148
+ * every target has published it.
149
+ *
150
+ * Only for a package with something to publish - never for one `up-to-date` or skipped, never under
151
+ * `--dry-run`. A failing `before` fails that package (for every target, or for that one) with the
152
+ * step's output as the reason. A shell step sees `RMAN_PUBLISH_TARGET` (that target) or
153
+ * `RMAN_PUBLISH_TARGETS` (all of the package's, comma separated).
154
+ */
155
+ export interface PublishHookKeys {
156
+ /** Run before publishing - `npx spm verify`, `npm run lint`. A string, a function, or a list. */
157
+ before?: RunStepValue | RunStepValue[];
158
+ /** Run after publishing succeeded. */
159
+ after?: RunStepValue | RunStepValue[];
160
+ }
143
161
  /**
144
162
  * `publish.<target>.files` - files copied into the package just before that target publishes it,
145
163
  * and put back afterwards. Every target's block takes it; `publish` itself does the copying.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rman",
3
3
  "description": "Repository manager",
4
- "version": "2.32.0",
4
+ "version": "2.33.0",
5
5
  "author": "Panates",
6
6
  "license": "MIT",
7
7
  "dependencies": {
@@ -999,6 +999,11 @@ const MARKER = /^<!-- rman:documented-up-to ([0-9a-f]{7,40}) -->[ \t]*\r?\n+/m;
999
999
  * - **No file at all** - the whole history, because nothing has been documented. Measured without
1000
1000
  * it: the first `--write` in a repository with a `v1.0.0` tag documented only the commits *after*
1001
1001
  * that tag, and the ones before it were never written anywhere and never would be.
1002
+ * - **A marker naming a commit HEAD does not descend from** - the file came from another repository
1003
+ * without its history, or its branch was rewritten - counts as no marker, with a warning.
1004
+ * Measured on `syncbridge-io/public-modules`: seven changelogs moved in from another repository
1005
+ * carried such a marker, and `version` died at apply time with `fatal: Invalid revision range`
1006
+ * while the plan had looked fine.
1002
1007
  * - **A file with no marker** - one rman did not write, or wrote before markers existed. Fall back
1003
1008
  * to ordinary detection, which is where `catchUpFile` still earns its place: it widens the tag
1004
1009
  * boundary backwards to the file's last commit, so a stale changelog catches up rather than
@@ -1027,8 +1032,15 @@ async function resolveBoundary(git, pkg, changelogFile, options) {
1027
1032
  if (!exists)
1028
1033
  return undefined;
1029
1034
  const marker = MARKER.exec(fs.readFileSync(changelogFile, 'utf-8'));
1030
- if (marker)
1035
+ if (marker && (await git.isAncestor(marker[1])))
1031
1036
  return marker[1];
1037
+ /** A marker naming a commit HEAD does not descend from is a record of somewhere else - the file
1038
+ * was copied in from another repository, or the branch it was written on was rewritten. Read
1039
+ * as "no marker", which is the case built to guess, and said so. */
1040
+ if (marker) {
1041
+ console.error(`warning: ${path.relative(pkg.repository?.dirname ?? process.cwd(), changelogFile)} is documented up to ` +
1042
+ `${marker[1].slice(0, 7)}, which is not in this branch's history - continuing from the package's last release`);
1043
+ }
1032
1044
  }
1033
1045
  return ChangeHashService.detect(git, pkg, {
1034
1046
  from: options.from,
@@ -281,6 +281,15 @@ export declare namespace RunService {
281
281
  * semantics of the shell case too, since `cd x && y` in one process is not the same as two.
282
282
  */
283
283
  export function runLifecycleSlot(pkg: Package, script: string, slot: keyof ScriptSlots, fallback?: RunStepValue[]): Promise<void>;
284
+ /**
285
+ * Runs hook steps from the config alone - a `publish.before`, say - in the package's directory, in
286
+ * order, stopping at the first that fails. Output goes to stderr as it comes, so a command whose
287
+ * stdout is a document keeps it one. Throws with the failed step's last lines.
288
+ *
289
+ * `at` is where the values sit in the config (`['publish', 'spm']`), so a function step is handed
290
+ * the `vars` its own block sees; `env` is added to a shell step's environment.
291
+ */
292
+ export function runHook(pkg: Package, values: RunStepValue[], at: readonly string[], env?: Record<string, string>): Promise<void>;
284
293
  export function getConfig(pkg: Package, script: string): Record<string, unknown>;
285
294
  /**
286
295
  * The context a function step or `if` is handed - see [`RunStepContext`](../core/run-step.ts).
@@ -611,6 +611,48 @@ export class RunService extends Service {
611
611
  }
612
612
  }
613
613
  RunService.runLifecycleSlot = runLifecycleSlot;
614
+ /**
615
+ * Runs hook steps from the config alone - a `publish.before`, say - in the package's directory, in
616
+ * order, stopping at the first that fails. Output goes to stderr as it comes, so a command whose
617
+ * stdout is a document keeps it one. Throws with the failed step's last lines.
618
+ *
619
+ * `at` is where the values sit in the config (`['publish', 'spm']`), so a function step is handed
620
+ * the `vars` its own block sees; `env` is added to a shell step's environment.
621
+ */
622
+ /* **No contributed slots, unlike `runLifecycleSlot`.** A step source maps npm's
623
+ * `pre<script>`/`post<script>`, and for `publish` those are `prepublish`/`postpublish` - which
624
+ * `npm publish` runs itself. Read here too, they would run twice. */
625
+ async function runHook(pkg, values, at, env) {
626
+ for (const value of values) {
627
+ const step = toStep(at[at.length - 1] ?? 'hook', value);
628
+ if (step.if !== undefined &&
629
+ !(await passesIf(pkg.repository, pkg, step.if, pkg.dirname, new Map(), undefined, at))) {
630
+ continue;
631
+ }
632
+ const lines = [];
633
+ const onLine = (line) => {
634
+ lines.push(line);
635
+ process.stderr.write(line + '\n');
636
+ };
637
+ try {
638
+ if (step.run) {
639
+ await step.run(createStepContext(pkg, pkg.dirname, undefined, onLine, undefined, at));
640
+ }
641
+ else {
642
+ await exec(step.command, { cwd: pkg.dirname, app: pkg.repository.app, env, onLine });
643
+ }
644
+ }
645
+ catch (e) {
646
+ const tail = lines
647
+ .map(l => l.trim())
648
+ .filter(Boolean)
649
+ .slice(-4);
650
+ throw new Error(`"${step.label}" failed${e?.message ? ` (${e.message})` : ''}` +
651
+ (tail.length ? ':\n' + tail.map(l => ` ${l}`).join('\n') : ''), { cause: e });
652
+ }
653
+ }
654
+ }
655
+ RunService.runHook = runHook;
614
656
  function getConfig(pkg, script) {
615
657
  const runCfg = pkg.config?.run;
616
658
  const cfg = runCfg && typeof runCfg === 'object' ? runCfg[script] : undefined;
package/utils/git.d.ts CHANGED
@@ -87,6 +87,9 @@ export declare class GitHelper {
87
87
  /** The best common ancestor of `a` and `b` - `undefined` if none exists (unrelated histories,
88
88
  * an invalid ref, ...). */
89
89
  mergeBase(a: string, b: string): Promise<string | undefined>;
90
+ /** Whether `sha` is a commit `ref` descends from - `false` for one this repository does not have
91
+ * at all (history brought over without its commits, a rewritten branch). */
92
+ isAncestor(sha: string, ref?: string): Promise<boolean>;
90
93
  /** The most recent tag matching the glob `pattern` that HEAD actually descends from (unlike
91
94
  * `listTags`, this follows commit ancestry rather than just sorting tag names - the right
92
95
  * choice for a single repo-wide tag scheme, where a package has no tag of its own). */
package/utils/git.js CHANGED
@@ -296,6 +296,17 @@ export class GitHelper {
296
296
  return undefined;
297
297
  }
298
298
  }
299
+ /** Whether `sha` is a commit `ref` descends from - `false` for one this repository does not have
300
+ * at all (history brought over without its commits, a rewritten branch). */
301
+ async isAncestor(sha, ref = 'HEAD') {
302
+ try {
303
+ await execFileAsync('git', ['merge-base', '--is-ancestor', sha, ref], { cwd: this.cwd });
304
+ return true;
305
+ }
306
+ catch {
307
+ return false;
308
+ }
309
+ }
299
310
  /** The most recent tag matching the glob `pattern` that HEAD actually descends from (unlike
300
311
  * `listTags`, this follows commit ancestry rather than just sorting tag names - the right
301
312
  * choice for a single repo-wide tag scheme, where a package has no tag of its own). */