zx-bulk-release 3.3.0 → 4.0.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +23 -22
  3. package/package.json +6 -6
  4. package/src/main/js/cli.js +3 -3
  5. package/src/main/js/config.js +2 -1
  6. package/src/main/js/post/api/git.js +96 -47
  7. package/src/main/js/post/api/npm.js +24 -15
  8. package/src/main/js/post/courier/channels/changelog.js +5 -10
  9. package/src/main/js/post/courier/channels/cmd.js +5 -1
  10. package/src/main/js/post/courier/channels/gh-pages.js +4 -4
  11. package/src/main/js/post/courier/channels/gh-release.js +3 -3
  12. package/src/main/js/post/courier/channels/git-tag.js +6 -26
  13. package/src/main/js/post/courier/channels/index.js +19 -0
  14. package/src/main/js/post/courier/channels/meta.js +4 -4
  15. package/src/main/js/post/courier/channels/npm.js +20 -17
  16. package/src/main/js/post/courier/execute.js +88 -0
  17. package/src/main/js/post/courier/index.js +112 -283
  18. package/src/main/js/post/courier/plan.js +149 -0
  19. package/src/main/js/post/courier/semaphore.js +14 -24
  20. package/src/main/js/post/courier/seniority.js +7 -17
  21. package/src/main/js/post/depot/context.js +12 -1
  22. package/src/main/js/post/depot/deps.js +13 -1
  23. package/src/main/js/post/depot/exec.js +2 -2
  24. package/src/main/js/post/depot/reconcile.js +15 -23
  25. package/src/main/js/post/depot/steps/clean.js +1 -2
  26. package/src/main/js/post/depot/steps/contextify.js +9 -0
  27. package/src/main/js/post/depot/steps/pack.js +6 -4
  28. package/src/main/js/post/depot/steps/publish.js +2 -2
  29. package/src/main/js/post/log.js +10 -1
  30. package/src/main/js/post/modes/deliver.js +14 -36
  31. package/src/main/js/post/modes/pack.js +8 -16
  32. package/src/main/js/post/modes/receive.js +7 -14
  33. package/src/main/js/post/modes/verify.js +17 -2
  34. package/src/main/js/post/parcel/build.js +17 -2
  35. package/src/main/js/post/parcel/directive.js +10 -24
  36. package/src/main/js/post/parcel/index.js +5 -0
  37. package/src/main/js/post/parcel/verify-directive.js +81 -0
  38. package/src/main/js/post/parcel/verify.js +82 -78
  39. package/src/main/js/post/release.js +5 -4
  40. package/src/main/js/post/tar.js +65 -21
  41. package/src/main/js/util.js +32 -5
  42. package/src/test/js/utils/mock.js +0 -3
  43. package/src/test/js/utils/repo.js +10 -4
package/CHANGELOG.md CHANGED
@@ -1,3 +1,31 @@
1
+ ## [4.0.0](https://github.com/semrel-extra/zx-bulk-release/compare/v3.3.0...v4.0.0) (2026-10-12)
2
+
3
+ ### Features
4
+ * feat: v4 ([ab56758](https://github.com/semrel-extra/zx-bulk-release/commit/ab567580f75924c9196419e0994f2e699fbc25ef))
5
+
6
+ ### BREAKING CHANGES
7
+ * significant internal refactoring ([ab56758](https://github.com/semrel-extra/zx-bulk-release/commit/ab567580f75924c9196419e0994f2e699fbc25ef))
8
+
9
+ ### Fixes & improvements
10
+ * fix: settle before exiting in every mode; preflight analyzes from fetched tags ([049647c](https://github.com/semrel-extra/zx-bulk-release/commit/049647ce3acc5e43f7ff6cbb0ef364cc375b4cff))
11
+ * fix(verify): bind the directive and every parcel to the trusted context ([167f70a](https://github.com/semrel-extra/zx-bulk-release/commit/167f70ad34d407b65a0e43cb1d8aa7260b1e285b))
12
+ * fix(courier): one executor — claim before act, settle before deciding ([ca12cf1](https://github.com/semrel-extra/zx-bulk-release/commit/ca12cf180f7f601f7bd1090c4989e8acf39df597))
13
+ * fix(courier): claim tags at the release commit, decide by the remote state ([95d9746](https://github.com/semrel-extra/zx-bulk-release/commit/95d974638b9045fbfce947fc41290abc9f5d5a6c))
14
+ * fix(git): one writer per repo, identity via env, retries from the remote tip ([164b356](https://github.com/semrel-extra/zx-bulk-release/commit/164b356bafac7db2c43c70f3fe2b873a52dc1979))
15
+ * fix: print every failure once, redacted, and keep queued calls in their caller context ([3c2d0cf](https://github.com/semrel-extra/zx-bulk-release/commit/3c2d0cfaa0c4125d1393d1c190f716eabcbb4433))
16
+ * fix(verify): check package identity of parcels ([18a83a2](https://github.com/semrel-extra/zx-bulk-release/commit/18a83a24dd2248b423f475923bc48c40be563b97))
17
+
18
+ ## [3.3.1](https://github.com/semrel-extra/zx-bulk-release/compare/v3.3.0...v3.3.1) (2026-10-12)
19
+
20
+ ### Fixes & improvements
21
+ * fix: settle before exiting in every mode; preflight analyzes from fetched tags ([049647c](https://github.com/semrel-extra/zx-bulk-release/commit/049647ce3acc5e43f7ff6cbb0ef364cc375b4cff))
22
+ * fix(verify): bind the directive and every parcel to the trusted context ([167f70a](https://github.com/semrel-extra/zx-bulk-release/commit/167f70ad34d407b65a0e43cb1d8aa7260b1e285b))
23
+ * fix(courier): one executor — claim before act, settle before deciding ([ca12cf1](https://github.com/semrel-extra/zx-bulk-release/commit/ca12cf180f7f601f7bd1090c4989e8acf39df597))
24
+ * fix(courier): claim tags at the release commit, decide by the remote state ([95d9746](https://github.com/semrel-extra/zx-bulk-release/commit/95d974638b9045fbfce947fc41290abc9f5d5a6c))
25
+ * fix(git): one writer per repo, identity via env, retries from the remote tip ([164b356](https://github.com/semrel-extra/zx-bulk-release/commit/164b356bafac7db2c43c70f3fe2b873a52dc1979))
26
+ * fix: print every failure once, redacted, and keep queued calls in their caller context ([3c2d0cf](https://github.com/semrel-extra/zx-bulk-release/commit/3c2d0cfaa0c4125d1393d1c190f716eabcbb4433))
27
+ * fix(verify): check package identity of parcels ([18a83a2](https://github.com/semrel-extra/zx-bulk-release/commit/18a83a24dd2248b423f475923bc48c40be563b97))
28
+
1
29
  ## [3.3.0](https://github.com/semrel-extra/zx-bulk-release/compare/v3.2.0...v3.3.0) (2026-10-03)
2
30
 
3
31
  ### Features
package/README.md CHANGED
@@ -18,7 +18,7 @@
18
18
  * **Coordinated delivery**: multiple release agents can safely serve the same monorepo concurrently via git-tag-based semaphores.
19
19
 
20
20
  > [!NOTE]
21
- > **[Migration guide v2 → v3](./docs/MIGRATION_V2_V3.md)** | **[Delivery specification](./docs/DELIVER_SPEC.md)** | **[Security model](./docs/SECURITY.md)** | **[Architecture](./docs/ARCHITECTURE.md)**
21
+ > **[Upgrading v3 → v4](./docs/MIGRATION_V3_V4.md)** | **[Migration guide v2 → v3](./docs/MIGRATION_V2_V3.md)** | **[Delivery specification](./docs/DELIVER_SPEC.md)** | **[Security model](./docs/SECURITY.md)** | **[Architecture](./docs/ARCHITECTURE.md)**
22
22
 
23
23
  ## Roadmap
24
24
  * [x] Store release metrics to `meta`.
@@ -192,9 +192,9 @@ jobs:
192
192
  GIT_COMMITTER_EMAIL: semrel-extra-bot@hotmail.com
193
193
  ```
194
194
 
195
- After delivery, each tar is replaced with a marker (`released`, `skip`, `conflict`, or `orphan`). In the four-phase mode, parcels are verified against the trusted context (uploaded before deps install) before any delivery begins.
195
+ After delivery, each settled tar is replaced with a marker (`released`, `conflict`, or `orphan`); a parcel the deliver env can't deliver (missing credentials) stays a valid tarball for one that can. In the four-phase mode, parcels are verified against the trusted context (uploaded before deps install) before any delivery begins.
196
196
 
197
- **Recovery** is simply re-running the deliver job. Only undelivered tars (not yet replaced with markers) will be processed. No rebuild required.
197
+ **Recovery** is simply re-running the deliver job. What already went out comes back as a duplicate — the release tag is at our commit, the version is in the registry — and the rest is delivered. No rebuild required.
198
198
 
199
199
  ### JS API
200
200
  ```js
@@ -420,7 +420,7 @@ all-in-one: topo -> contextify -> analyze -> preflight -> build -> test -> pack
420
420
 
421
421
  By default, packages marked as `private` are omitted. Override with `--include-private`.
422
422
 
423
- **Preflight** runs between `analyze` and `build`. It checks tag availability on git remote and eliminates version conflicts before wasting build/test time. If a tag is already taken by a newer commit, preflight re-resolves the version. If taken by the same or an older commit, the package is skipped.
423
+ **Preflight** runs between `analyze` and `build`. It checks tag availability on git remote and eliminates version conflicts before wasting build/test time. If a tag is already taken by an older commit, preflight analyzes the package again from that release: a new version, or no release if nothing changed since. If taken by the same or a newer commit, the package is skipped.
424
424
 
425
425
  ### Steps
426
426
  Each step has a uniform signature `(pkg, ctx)`:
@@ -429,9 +429,9 @@ Each step has a uniform signature `(pkg, ctx)`:
429
429
  - **`preflight`** — checks tag availability on remote, re-resolves version on conflict, skips duplicates.
430
430
  - **`build`** — runs `buildCmd` (with dep traversal and optional npm artifact fetch).
431
431
  - **`test`** — runs `testCmd`.
432
- - **`pack`** — stages delivery artifacts into self-describing tar containers (`npm pack`, docs copy, assets, release notes). Each tar is named `parcel.{sha7}.{channel}.{name}.{version}.{hash6}.tar` and contains a `manifest.json` with channel name, delivery instructions, and template credentials (`${{ENV_VAR}}`). A directive meta-parcel is also generated, listing all parcels and their delivery steps. After this step, everything the courier needs is outside the project dir.
432
+ - **`pack`** — stages delivery artifacts into self-describing tar containers (`npm pack`, docs copy, assets, release notes). Each tar is named `parcel.{sha7}.{channel}.{name}.{version}.{hash6}.tar` and contains a `manifest.json` with channel name, delivery instructions, and template credentials (`${{ENV_VAR}}`). A directive meta-parcel is also generated, listing each package's parcels and the dependencies between packages. After this step, everything the courier needs is outside the project dir.
433
433
  - **`publish`** — hands tars to courier's `deliver()`, runs `cmd` channel separately. Tag push is handled by the `git-tag` channel.
434
- - **`clean`** — restores `package.json` files and unsets git user config.
434
+ - **`clean`** — restores `package.json` files.
435
435
 
436
436
  Set `config.releaseRules` to override the default rules preset:
437
437
  ```js
@@ -451,34 +451,35 @@ parcel.{sha7}.{channel}.{name}.{version}.{hash6}.tar
451
451
  assets/ — (gh-release channel) release assets
452
452
  docs/ — (gh-pages channel) documentation files
453
453
  ```
454
- The `sha7` prefix groups all parcels of one commit. `name` is the sanitized package name (`@scope/pkg` → `scope-pkg`). The `hash6` suffix is a content hash for deduplication — two builds of the same commit producing identical content yield the same filename (last-writer-wins), while different content gets a different hash.
454
+ The `sha7` prefix groups all parcels of one commit. `name` is the package name encoded for a file name: `[a-z0-9-]` stay as is, `@scope/pkg` becomes `scope__pkg`, any other character is escaped as `_xx` (UTF-8 bytes) — different packages never share a parcel name. The `hash6` suffix is a content hash for deduplication — two builds of the same commit producing identical content yield the same filename (last-writer-wins), while different content gets a different hash. Like the rest of the parcel format, names assume that all phases of a pipeline run the same zbr version.
455
455
 
456
- A **directive** meta-parcel (`parcel.{sha7}.directive.{ts}.tar`) is generated alongside regular parcels. It contains the complete delivery map: package queue, per-package channel steps, and an authoritative list of parcel filenames. The directive enables coordinated delivery — see [DELIVER_SPEC.md](./docs/DELIVER_SPEC.md).
456
+ A **directive** meta-parcel (`parcel.{sha7}.directive.{ts}.tar`) is generated alongside regular parcels. It contains the complete delivery map: the packages, the dependencies between them, and each package's parcels. The directive enables coordinated delivery — see [DELIVER_SPEC.md](./docs/DELIVER_SPEC.md).
457
457
 
458
458
  The manifest contains `${{ENV_VAR}}` placeholders that are resolved by the courier at delivery time via `resolveManifest()`. This ensures credentials never touch the build phase.
459
459
 
460
460
  ### Channels
461
- Delivery channels are a registry of `{name, when, prepare?, run, requires?, snapshot?, transport?}` objects:
462
- - **git-tag** — pushes the release tag to git remote. Runs before other channels. Returns `conflict` if the tag already exists. Skipped in snapshot mode.
461
+ Delivery channels are a registry of `{name, stage?, when, prepare?, run(manifest, dir, {gitRoot}), requires?, snapshot?, transport?}` objects. A package's channels go in stages: **claim** (`git-tag`) → **publish** (`npm`) → **announce** (`gh-release`, `meta`, `changelog`, `gh-pages`); a channel without a stage publishes. Nothing else of a package goes out until its claim is released — the release tag is ours. Snapshots have no claim.
462
+ - **git-tag** — pushes the release tag at the release commit. The remote decides the outcome: `ok` if pushed, `duplicate` if the tag is already at our commit (a re-run), `conflict` if it is at another commit; a rejected push that leaves no tag is an error. Skipped in snapshot mode.
463
463
  - **meta** — pushes release metadata to the `meta` branch (or as a GH release asset). Checks docs seniority before committing.
464
- - **npm** — publishes to the npm registry. Returns `duplicate` on `EPUBLISHCONFLICT` / 403.
465
- - **gh-release** — creates a GitHub release with optional file assets (requires tag to exist). Returns `duplicate` on 422.
464
+ - **npm** — publishes to the npm registry. Returns `duplicate` on `EPUBLISHCONFLICT` / "cannot publish over", or when the registry already has the version.
465
+ - **gh-release** — creates a GitHub release with optional file assets (after the claim, so the tag exists). Returns `duplicate` when the release `already_exists`.
466
466
  - **gh-pages** — pushes docs to a `gh-pages` branch. Checks docs seniority before committing.
467
- - **changelog** — pushes a changelog entry to a `changelog` branch. Checks docs seniority before committing.
468
- - **cmd** — runs a custom `publishCmd` (depot-side, not through courier; `transport: false`).
467
+ - **changelog** — pushes a changelog entry to a `changelog` branch, once per release. Checks docs seniority before committing.
468
+ - **cmd** — runs a custom `publishCmd` (depot-side, not through courier; `transport: false`). Its env carries the release identity in `GIT_AUTHOR_*`/`GIT_COMMITTER_*` (`GIT_COMMITTER_NAME`/`GIT_COMMITTER_EMAIL`, or the default bot), unless your env sets them; not in snapshot mode.
469
469
 
470
- Each channel declares `requires` — a list of manifest fields that must be present after credential resolution. Courier validates before delivery; missing credentials produce a warning and `skip` marker.
470
+ Each channel declares `requires` — a list of manifest fields that must be present after credential resolution. Courier validates before delivery; a parcel with missing credentials is held: a warning, and the tar stays valid for an env that has them.
471
471
 
472
- Channels return one of: `ok` (success), `duplicate` (already published, goal achieved), or `conflict` (version collision, needs rebuild). Unrecoverable errors are thrown.
472
+ Channels return one of: `ok` (success), `duplicate` (already published, goal achieved), or `conflict` (version collision, needs rebuild). Unrecoverable errors are thrown — after everything in flight has settled, together.
473
473
 
474
474
  ### Coordinated delivery
475
475
  When multiple zbr processes target the same monorepo concurrently, delivery is coordinated via git-tag-based semaphores:
476
476
 
477
- 1. **Directive** — each build produces a meta-parcel listing all packages and their delivery steps.
478
- 2. **Semaphore lock** — before delivering, a process pushes `zbr-deliver.{sha7}` as an annotated tag. Atomic push = ownership. Failure = another process is working.
479
- 3. **Orphan cleanup** — the directive invalidates parcels not in its authoritative list (stale artifacts from previous builds).
480
- 4. **Conflict resolution** — if `git-tag` returns `conflict`, all parcels of that package are marked, and a `zbr-rebuild.{sha7}` tag signals CI to rebuild with fresh versions.
481
- 5. **Partial delivery** — skipped parcels (missing credentials) remain valid tarballs. Another process with the right credentials can pick them up later.
477
+ 1. **Directive** — each build produces a meta-parcel listing its packages, their dependencies and parcels.
478
+ 2. **Semaphore lock** — before delivering, a process pushes `zbr-deliver.{sha7}` at the release commit. Atomic push = ownership. A tag already there = another process is working.
479
+ 3. **Orphan cleanup** — the directive invalidates parcels none of its packages lists (stale artifacts from previous builds).
480
+ 4. **Claim before act** — a package's channels go out only once its release tag is ours (snapshots have none).
481
+ 5. **Conflict resolution** — if `git-tag` returns `conflict`, the parcels of that package and of the packages depending on it are marked, and a `zbr-rebuild.{sha7}` tag signals CI to rebuild with fresh versions.
482
+ 6. **Partial delivery** — held parcels (missing credentials) remain valid tarballs. Another process with the right credentials can pick them up later.
482
483
 
483
484
  See [DELIVER_SPEC.md](./docs/DELIVER_SPEC.md) for the full protocol specification.
484
485
 
@@ -488,7 +489,7 @@ depot (build phase) courier (deliver phase)
488
489
  manifest: { token: '${{NPM_TOKEN}}' } -> resolveManifest(manifest, env)
489
490
  -> { token: 'actual-secret' }
490
491
  ```
491
- Template credentials (`${{ENV_VAR}}`) are written into manifests at pack time. Courier resolves them from `process.env` at delivery time. This means the build phase never sees real secrets — including git push credentials (`GH_TOKEN`, `GIT_COMMITTER_NAME`, `GIT_COMMITTER_EMAIL`) which are now resolved by the `git-tag` channel at delivery time.
492
+ Template credentials (`${{ENV_VAR}}`) are written into manifests at pack time. Courier resolves them from `process.env` at delivery time. This means the build phase never sees real secrets — including git push credentials (`GH_TOKEN`, `GIT_COMMITTER_NAME`, `GIT_COMMITTER_EMAIL`) which are resolved by the `git-tag` channel at delivery time. zbr never writes git config: the identity goes with each git command it runs.
492
493
 
493
494
  ### Tags
494
495
  [Lerna](https://github.com/lerna/lerna) tags (like `@pkg/name@v1.0.0-beta.0`) are suitable for monorepos, but they don't follow [semver spec](https://semver.org/). Therefore, we propose another contract:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "zx-bulk-release",
3
3
  "alias": "bulk-release",
4
- "version": "3.3.0",
4
+ "version": "4.0.0",
5
5
  "description": "zx-based alternative for multi-semantic-release",
6
6
  "type": "module",
7
7
  "exports": {
@@ -29,15 +29,15 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@semrel-extra/topo": "^1.14.1",
32
- "tar-stream": "^3.2.1",
32
+ "tar-stream": "^3.2.2",
33
33
  "zx-extra": "4.0.20"
34
34
  },
35
35
  "devDependencies": {
36
- "@vitest/coverage-v8": "^5.0.3",
36
+ "@vitest/coverage-v8": "^5.0.4",
37
37
  "esbuild": "^0.28.2",
38
- "verdaccio": "6.10.4",
39
- "vite": "^8.3.2",
40
- "vitest": "^5.0.3"
38
+ "verdaccio": "6.10.5",
39
+ "vite": "^8.3.4",
40
+ "vitest": "^5.0.4"
41
41
  },
42
42
  "publishConfig": {
43
43
  "access": "public"
@@ -3,6 +3,7 @@
3
3
  import {argv} from 'zx-extra'
4
4
  import {run, version} from './index.js'
5
5
  import {normalizeFlags} from './config.js'
6
+ import {log, wasPrinted} from './post/log.js'
6
7
 
7
8
  const flags = normalizeFlags(argv)
8
9
 
@@ -45,7 +46,6 @@ try {
45
46
  await run({flags})
46
47
  process.exit(0)
47
48
  } catch (e) {
48
- if (e?.exitCode !== undefined) process.exit(e.exitCode)
49
- console.error(e)
50
- process.exit(1)
49
+ if (!wasPrinted(e)) log.error(e)
50
+ process.exit(e?.exitCode || 1)
51
51
  }
@@ -3,6 +3,7 @@ import { fs, path, YAML } from 'zx'
3
3
  import { asArray, camelize, memoizeBy } from './util.js'
4
4
  import { GH_URL, resolveGhApiUrl } from './post/api/gh.js'
5
5
  import { DEFAULT_GIT_COMMITTER_NAME, DEFAULT_GIT_COMMITTER_EMAIL } from './post/api/git.js'
6
+ import { DEFAULT_NPM_REGISTRY } from './post/api/npm.js'
6
7
 
7
8
  const CONFIG_NAME = 'release'
8
9
  const CONFIG_FILES = [
@@ -110,7 +111,7 @@ export const parseEnv = ({GH_USER, GH_USERNAME, GH_META, GH_URL: _GH_URL, GITHUB
110
111
  npmToken: NPM_TOKEN,
111
112
  npmProvenance: NPM_PROVENANCE,
112
113
  npmOidc: NPM_OIDC || (!NPM_TOKEN && ACTIONS_ID_TOKEN_REQUEST_URL),
113
- npmRegistry: NPM_REGISTRY || 'https://registry.npmjs.org',
114
+ npmRegistry: NPM_REGISTRY || DEFAULT_NPM_REGISTRY,
114
115
  gitCommitterName: GIT_COMMITTER_NAME || DEFAULT_GIT_COMMITTER_NAME,
115
116
  gitCommitterEmail: GIT_COMMITTER_EMAIL || DEFAULT_GIT_COMMITTER_EMAIL,
116
117
  }
@@ -1,10 +1,23 @@
1
1
  import {$, fs, path, tempy, copy} from 'zx-extra'
2
2
  import {log} from '../log.js'
3
- import {attempt2, attempt3, memoizeBy} from '../../util.js'
3
+ import {attempt3, keyedQueue, memoizeBy} from '../../util.js'
4
4
 
5
5
  export const DEFAULT_GIT_COMMITTER_NAME = 'Semrel Extra Bot'
6
6
  export const DEFAULT_GIT_COMMITTER_EMAIL = 'semrel-extra-bot@hotmail.com'
7
7
 
8
+ // One writer per local repo: commands that write .git run one at a time per repo root.
9
+ // Locked operations never call each other.
10
+ const lock = keyedQueue()
11
+ const exclusive = async (cwd, fn) => lock(await getRoot(cwd), fn)
12
+
13
+ // The release identity as env, so zbr never writes repo config. Identity vars the env already sets win,
14
+ // as they did over the repo config zbr used to write.
15
+ export const identity = (_name, _email) => {
16
+ const name = _name || $.env.GIT_COMMITTER_NAME || DEFAULT_GIT_COMMITTER_NAME
17
+ const email = _email || $.env.GIT_COMMITTER_EMAIL || DEFAULT_GIT_COMMITTER_EMAIL
18
+ return {GIT_AUTHOR_NAME: name, GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_NAME: name, GIT_COMMITTER_EMAIL: email, ...$.env}
19
+ }
20
+
8
21
  export const fetchRepo = memoizeBy(async ({cwd: _cwd, branch, origin: _origin, basicAuth}) => {
9
22
  if (!_origin && !_cwd) throw new Error('fetchRepo requires either origin or cwd')
10
23
  const origin = _origin || (await getRepo(_cwd, {basicAuth})).repoAuthedUrl
@@ -21,37 +34,54 @@ export const fetchRepo = memoizeBy(async ({cwd: _cwd, branch, origin: _origin, b
21
34
  return cwd
22
35
  }, async ({cwd, branch, origin}) => origin ? `${origin}:${branch}` : `${await getRoot(cwd)}:${branch}`)
23
36
 
24
- export const pushCommit = async ({cwd, from, to, branch, origin, msg, ignoreFiles, files = [], basicAuth, gitCommitterEmail, gitCommitterName}) => {
37
+ // Each attempt is a fresh read-modify-write on top of the remote tip, so a failed one leaves nothing behind.
38
+ // files[].contents: string | object (as JSON) | (prev: string) => string
39
+ export const pushCommit = async ({cwd, from, to = '.', branch, origin, msg, ignoreFiles, files = [], basicAuth, gitCommitterEmail, gitCommitterName}) => {
25
40
  const _cwd = await fetchRepo({cwd, branch, origin, basicAuth})
26
- const _$ = $({cwd: _cwd})
27
-
28
- for (let {relpath, contents} of files) {
29
- const _contents = typeof contents === 'string' ? contents : JSON.stringify(contents, null, 2)
30
- await fs.outputFile(path.resolve(_cwd, to, relpath), _contents)
31
- }
32
- if (from) await copy({baseFrom: cwd, from, baseTo: _cwd, to, ignoreFiles, cwd})
33
-
34
- try {
35
- await setUserConfig(_cwd, gitCommitterName, gitCommitterEmail)
36
- await _$`git add . &&
37
- git commit -m ${msg}`
38
- } catch {
39
- log.warn(`no changes to commit to ${branch}`)
40
- return
41
- }
41
+ const _$ = $({cwd: _cwd, env: identity(gitCommitterName, gitCommitterEmail)})
42
+
43
+ return exclusive(_cwd, () => attempt3(async () => {
44
+ await resetBranch(_cwd, branch)
45
+ for (const {relpath, contents} of files) {
46
+ const file = path.resolve(_cwd, to, relpath)
47
+ const value = typeof contents === 'function' ? contents(await fs.readFile(file, 'utf8').catch(() => '')) : contents
48
+ await fs.outputFile(file, typeof value === 'string' ? value : JSON.stringify(value, null, 2))
49
+ }
50
+ if (from) await copy({baseFrom: cwd, from, baseTo: _cwd, to, ignoreFiles, cwd})
42
51
 
43
- return attempt3(
44
- () => _$`git push origin HEAD:refs/heads/${branch}`,
45
- (e) => {
46
- log.warn('git push failed, rebasing', 'branch', branch, e)
47
- return attempt2(() => _$`git fetch origin ${branch} &&
48
- git rebase origin/${branch}`)
52
+ await _$`git add .`
53
+ if ((await $({cwd: _cwd, nothrow: true})`git diff --cached --quiet`).exitCode === 0) {
54
+ log.warn(`no changes to commit to ${branch}`)
55
+ return 'unchanged'
49
56
  }
50
- )
57
+ await _$`git commit -m ${msg}`
58
+ await _$`git push origin HEAD:refs/heads/${branch}`
59
+ return 'ok'
60
+ }, (e) => log.warn('git push failed, retrying', 'branch', branch, e)))
61
+ }
62
+
63
+ // The remote tip of the branch, or an empty unborn one if there is none yet. Pushes are never forced,
64
+ // so taking a failed fetch for a new branch can only lead to a rejected push.
65
+ const resetBranch = async (cwd, branch) => {
66
+ const _$ = $({cwd})
67
+ const fetched = (await $({cwd, nothrow: true})`git fetch --depth 1 origin ${branch}`).exitCode === 0
68
+ await (fetched ? _$`git reset -q --hard FETCH_HEAD` : _$`git update-ref -d HEAD && git read-tree --empty`)
69
+ await _$`git clean -fdqx`
51
70
  }
52
71
 
53
72
  export const getRoot = memoizeBy(async (cwd) => (await $({cwd})`git rev-parse --show-toplevel`).toString().trim())
54
73
 
74
+ // The repo around cwd, or a fresh one bound to origin when there is no checkout.
75
+ export const openRepo = async (cwd, origin) => {
76
+ const found = await $({cwd, quiet: true, nothrow: true})`git rev-parse --show-toplevel`
77
+ if (found.exitCode === 0) return found.toString().trim()
78
+
79
+ const dir = tempy.temporaryDirectory()
80
+ await $({cwd: dir})`git init -q && git remote add origin ${origin}`
81
+ log.info('no checkout: delivering from a fresh repo')
82
+ return dir
83
+ }
84
+
55
85
  export const getSha = memoizeBy(async (cwd) => (await $({cwd})`git rev-parse HEAD`).toString().trim(), getRoot)
56
86
 
57
87
  export const getCommitTimestamp = memoizeBy(async (cwd) => (await $({cwd})`git log -1 --format=%ct`).toString().trim(), getRoot)
@@ -104,35 +134,54 @@ export const getTags = memoizeBy(
104
134
  async (cwd, ref = '*') => `${await getRoot(cwd)}:${ref}`,
105
135
  )
106
136
 
107
- export const pushTag = async ({cwd, tag, sha, gitCommitterName, gitCommitterEmail}) => {
108
- await setUserConfig(cwd, gitCommitterName, gitCommitterEmail)
137
+ export const fetchTags = (cwd) => exclusive(cwd, async () => {
138
+ await $({cwd})`git fetch origin --tags --force`
139
+ clearTagsCache()
140
+ })
141
+
142
+ // Once per run and repo: every preflight compares against the same commit, so one deepening serves them all.
143
+ export const deepen = memoizeBy((cwd, depth) => exclusive(cwd, () =>
144
+ $({cwd})`git fetch origin --deepen=${depth}`
145
+ ), async (cwd, depth) => `${await getRoot(cwd)}:${depth}`)
109
146
 
110
- const target = sha ? [sha] : []
111
- await $({cwd})`git tag -m ${tag} ${tag} ${target}`
112
- await $({cwd})`git push origin ${tag}`
147
+ export const isAncestor = async (cwd, ancestor, descendant) => {
148
+ const res = await $({cwd, nothrow: true})`git merge-base --is-ancestor ${ancestor} ${descendant}`
149
+ if (res.exitCode !== 0 && res.exitCode !== 1) throw res
150
+ return res.exitCode === 0
113
151
  }
114
152
 
115
- // Memoize prevents .git/config lock
116
- // https://github.com/qiwi/packasso/actions/runs/4539987310/jobs/8000403413#step:7:282
117
- export const setUserConfig = memoizeBy(async(cwd, gitCommitterName, gitCommitterEmail) => $({cwd})`
118
- git config user.name ${gitCommitterName} &&
119
- git config user.email ${gitCommitterEmail}
120
- `)
153
+ // Claims a tag for a commit. The outcome is read from the remote, not from the error text:
154
+ // {pushed: true} — the tag is ours now; {pushed: false, commit} — it already exists and points to `commit`.
155
+ export const pushTag = ({cwd, tag, sha, message = tag, gitCommitterName, gitCommitterEmail}) => exclusive(cwd, async () => {
156
+ await ensureCommit(cwd, sha)
157
+ await $({cwd, env: identity(gitCommitterName, gitCommitterEmail)})`git tag -f -a -m ${message} ${tag} ${sha}`
158
+ const push = await $({cwd, nothrow: true})`git push origin refs/tags/${tag}`
159
+ if (push.exitCode === 0) return {pushed: true, commit: sha}
160
+
161
+ const commit = await getRemoteTagCommit(cwd, tag)
162
+ if (!commit) throw push // rejected by a hook or a ruleset, no access, no network
163
+ return {pushed: false, commit}
164
+ })
165
+
166
+ // A tag target must be local: fetch the commit itself, not whatever the branch tips are now.
167
+ const ensureCommit = async (cwd, sha) => {
168
+ if ((await $({cwd, nothrow: true, quiet: true})`git cat-file -e ${sha}^{commit}`).exitCode === 0) return
169
+ await $({cwd})`git fetch --depth=1 origin ${sha}`
170
+ }
121
171
 
122
- export const unsetUserConfig = async(cwd) => $({cwd, nothrow: true})`
123
- git config --unset user.name &&
124
- git config --unset user.email`
172
+ export const listRemoteTags = async (cwd) =>
173
+ (await $({cwd})`git ls-remote --tags --refs origin`).toString()
174
+ .split('\n').filter(Boolean).map(line => line.split('\t')[1].slice('refs/tags/'.length))
125
175
 
126
- export const getRemoteTagSha = async (cwd, tag) =>
127
- (await $({cwd, nothrow: true})`git ls-remote --tags origin refs/tags/${tag}`)
128
- .toString().split('\t')[0]?.trim() || null
176
+ // The commit a remote tag points to (peeled), or null if the tag is absent or the remote is unreachable.
177
+ export const getRemoteTagCommit = async (cwd, tag) => {
178
+ const ref = `refs/tags/${tag}`
179
+ const refs = Object.fromEntries((await $({cwd, nothrow: true})`git ls-remote origin ${ref} ${ref}^{}`)
180
+ .toString().split('\n').filter(Boolean).map(line => line.split('\t').reverse()))
181
+ return refs[`${ref}^{}`] || refs[ref] || null
182
+ }
129
183
 
130
184
  export const deleteRemoteTag = async (cwd, tag) =>
131
185
  $({cwd, nothrow: true})`git push origin :refs/tags/${tag}`
132
186
 
133
- export const pushAnnotatedTag = async (cwd, tag, message) => {
134
- await $({cwd})`git tag -a ${tag} -m ${message}`
135
- await $({cwd})`git push origin ${tag}`
136
- }
137
-
138
187
  export const clearTagsCache = () => { $.memo?.delete?.(getTags) }
@@ -8,6 +8,7 @@ import {$, semver, fs, INI, fetch, tempy} from 'zx-extra'
8
8
  import {log} from '../log.js'
9
9
  import {attempt2, memoizeBy} from '../../util.js'
10
10
 
11
+ export const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org'
11
12
  const FETCH_TIMEOUT_MS = 15_000
12
13
  const NPM_OIDC_VER = '11.5.0'
13
14
  const NPM_VER = (await $`npm --version`).toString().trim()
@@ -78,20 +79,12 @@ export const npmRestore = async (pkg) => {
78
79
  }
79
80
 
80
81
  export const npmPublish = async (pkg) => {
81
- const {name, version, manifest, config: {npmPublish, npmRegistry, npmToken, npmConfig, npmProvenance, npmOidc}} = pkg
82
+ const {name, version, manifest, config: {npmPublish, npmRegistry, npmProvenance, npmOidc}} = pkg
82
83
 
83
84
  if (manifest.private || npmPublish === false) return
84
85
 
85
86
  log.info(`publishing npm package ${name} ${version} to ${npmRegistry}`)
86
87
 
87
- const npmTag = pkg.preversion ? 'snapshot' : 'latest'
88
- const npmFlags = [
89
- '--no-workspaces',
90
- '--no-git-tag-version',
91
- `--tag=${npmTag}`,
92
- npmRegistry && `--registry=${npmRegistry}`,
93
- ]
94
-
95
88
  // OIDC trusted publishing: no auth token must be present for npm to use OIDC flow.
96
89
  // https://docs.npmjs.com/trusted-publishers/
97
90
  if (npmOidc) {
@@ -99,23 +92,39 @@ export const npmPublish = async (pkg) => {
99
92
  throw new Error(`npm OIDC trusted publishing requires npm >= ${NPM_OIDC_VER}, got ${NPM_VER}`)
100
93
  }
101
94
  log.info('npm publish: OIDC trusted publishing enabled')
102
- npmFlags.push('--provenance')
103
- } else {
104
- const npmrc = await getNpmrc({npmConfig, npmToken, npmRegistry})
105
- npmFlags.push(`--userconfig=${npmrc}`)
106
- if (npmProvenance) npmFlags.push('--provenance')
107
95
  }
108
96
 
97
+ const npmTag = pkg.preversion ? 'snapshot' : 'latest'
98
+ const npmFlags = [
99
+ '--no-workspaces',
100
+ '--no-git-tag-version',
101
+ `--tag=${npmTag}`,
102
+ ...await registryFlags(pkg.config),
103
+ (npmOidc || npmProvenance) && '--provenance',
104
+ ]
105
+
109
106
  // Publish from pre-built tarball (courier mode) or project dir (legacy).
110
107
  const target = pkg.npmTarball || pkg.absPath
111
108
  await $`npm publish ${target} ${npmFlags.filter(Boolean)}`
112
109
  }
113
110
 
111
+ // Whether the registry has this version, read the way publish reaches it: same registry, same npmrc,
112
+ // so scopes and auth resolve alike. The name comes from a parcel, so it goes after `--`.
113
+ export const npmPublished = async ({name, version, config}) =>
114
+ (await $({nothrow: true})`npm view ${await registryFlags(config)} -- ${name}@${version} version`).toString() === version
115
+
116
+ const registryFlags = async ({npmRegistry, npmToken, npmConfig, npmOidc}) => [
117
+ npmRegistry && `--registry=${npmRegistry}`,
118
+ !npmOidc && `--userconfig=${await getNpmrc({npmConfig, npmToken, npmRegistry})}`,
119
+ ].filter(Boolean)
120
+
121
+ // npm looks a token up by registry (`//host/path/:_authToken`): an unset registry means npm's default one.
114
122
  export const getNpmrc = memoizeBy(async ({npmConfig, npmToken, npmRegistry}) => {
115
123
  if (npmConfig) return npmConfig
116
124
 
117
125
  const npmrc = tempy.temporaryFile({name: '.npmrc'})
118
- await fs.writeFile(npmrc, `${npmRegistry.replace(/^https?:\/\//, '//')}/:_authToken=${npmToken}`, {encoding: 'utf8'})
126
+ const registry = (npmRegistry || DEFAULT_NPM_REGISTRY).replace(/^https?:\/\//, '//').replace(/\/?$/, '/')
127
+ await fs.writeFile(npmrc, `${registry}:_authToken=${npmToken}`, {encoding: 'utf8'})
119
128
 
120
129
  return npmrc
121
130
  }, ({npmConfig, npmToken, npmRegistry}) => `${npmConfig}:${npmToken}:${npmRegistry}`)
@@ -1,37 +1,32 @@
1
- import {fs, path} from 'zx-extra'
2
- import {queuefy} from '../../../util.js'
3
1
  import {api} from '../../api/index.js'
4
2
  import {log} from '../../log.js'
5
3
  import {hasHigherVersion} from '../seniority.js'
6
4
 
7
- const run = queuefy(async (manifest, dir) => {
5
+ const run = async (manifest, dir, {gitRoot}) => {
8
6
  const {name, version, releaseNotes, branch, file, msg, repoAuthedUrl, gitCommitterEmail, gitCommitterName, ghBasicAuth} = manifest
9
7
 
10
- if (await hasHigherVersion(dir, name, version)) {
8
+ if (await hasHigherVersion(gitRoot, name, version)) {
11
9
  log.warn(`skipping changelog for ${name}@${version}: higher version already released`)
12
10
  return 'ok'
13
11
  }
14
12
 
15
13
  log.info('push changelog')
16
14
 
17
- const _cwd = await api.git.fetchRepo({branch, origin: repoAuthedUrl, basicAuth: ghBasicAuth})
18
- const filePath = path.resolve(_cwd, file)
19
- const prev = await fs.readFile(filePath, 'utf8').catch(() => '')
20
- await fs.outputFile(filePath, releaseNotes + '\n' + prev)
21
-
22
15
  await api.git.pushCommit({
23
16
  branch,
24
17
  msg,
18
+ files: [{relpath: file, contents: (prev) => prev.includes(releaseNotes) ? prev : releaseNotes + '\n' + prev}],
25
19
  origin: repoAuthedUrl,
26
20
  gitCommitterEmail,
27
21
  gitCommitterName,
28
22
  basicAuth: ghBasicAuth,
29
23
  })
30
24
  return 'ok'
31
- })
25
+ }
32
26
 
33
27
  export default {
34
28
  name: 'changelog',
29
+ stage: 'announce',
35
30
  requires: ['repoAuthedUrl'],
36
31
  when: (pkg) => !!pkg.config.changelog,
37
32
  run,
@@ -1,7 +1,11 @@
1
+ import {api} from '../../api/index.js'
2
+
1
3
  export default {
2
4
  name: 'cmd',
3
5
  when: (pkg) => !!(pkg.ctx?.flags?.publishCmd ?? pkg.config.publishCmd),
4
- run: (pkg, exec) => exec(pkg, 'publishCmd'),
6
+ // After the release tag publishCmd commits and tags as the release, as when zbr kept this identity in the repo config.
7
+ // A snapshot pushes no tag, so there the command runs with the user's own identity, as before.
8
+ run: (pkg, exec) => exec(pkg, 'publishCmd', pkg.ctx?.flags?.snapshot ? undefined : api.git.identity()),
5
9
  snapshot: true,
6
10
  transport: false,
7
11
  }
@@ -1,14 +1,13 @@
1
1
  import {path} from 'zx-extra'
2
- import {queuefy} from '../../../util.js'
3
2
  import {log} from '../../log.js'
4
3
  import {api} from '../../api/index.js'
5
4
  import {hasHigherVersion} from '../seniority.js'
6
5
 
7
- const run = queuefy(async (manifest, dir) => {
6
+ const run = async (manifest, dir, {gitRoot}) => {
8
7
  const {name, version, branch, to, msg, repoAuthedUrl, gitCommitterEmail, gitCommitterName, ghBasicAuth} = manifest
9
8
  const docsDir = path.join(dir, 'docs')
10
9
 
11
- if (await hasHigherVersion(docsDir, name, version)) {
10
+ if (await hasHigherVersion(gitRoot, name, version)) {
12
11
  log.warn(`skipping gh-pages for ${name}@${version}: higher version already released`)
13
12
  return 'ok'
14
13
  }
@@ -27,10 +26,11 @@ const run = queuefy(async (manifest, dir) => {
27
26
  basicAuth: ghBasicAuth,
28
27
  })
29
28
  return 'ok'
30
- })
29
+ }
31
30
 
32
31
  export default {
33
32
  name: 'gh-pages',
33
+ stage: 'announce',
34
34
  requires: ['repoAuthedUrl'],
35
35
  when: (pkg) => !!pkg.config.ghPages,
36
36
  run,
@@ -2,12 +2,11 @@ import {fs, path} from 'zx-extra'
2
2
  import {log} from '../../log.js'
3
3
  import {api} from '../../api/index.js'
4
4
 
5
- const isDuplicate = (e) =>
6
- /already_exists|Validation Failed|422/i.test(e?.message || e?.stderr || '')
5
+ // Only a release that already exists for the tag is a duplicate; any other validation error is a failure.
6
+ const isDuplicate = (e) => /already_exists/.test(e?.message || '')
7
7
 
8
8
  const run = async (manifest, dir) => {
9
9
  const {tag, token, apiUrl, repoName, releaseNotes, assets} = manifest
10
- if (!token) return null
11
10
 
12
11
  log.info('create gh release')
13
12
  const now = Date.now()
@@ -39,6 +38,7 @@ const run = async (manifest, dir) => {
39
38
 
40
39
  export default {
41
40
  name: 'gh-release',
41
+ stage: 'announce',
42
42
  requires: ['token', 'repoName'],
43
43
  when: (pkg) => !!pkg.config.ghToken,
44
44
  run,
@@ -1,35 +1,15 @@
1
- import {$} from 'zx-extra'
2
1
  import {api} from '../../api/index.js'
3
- import {DEFAULT_GIT_COMMITTER_NAME, DEFAULT_GIT_COMMITTER_EMAIL} from '../../api/git.js'
4
2
 
5
- export const isTagConflict = (e) =>
6
- /already exists|updates were rejected|failed to push/i.test(e?.message || e?.stderr || '')
7
-
8
- const ensureSha = async (cwd, sha) => {
9
- if (!sha) return
10
- const check = await $({cwd, nothrow: true, quiet: true})`git cat-file -e ${sha}`
11
- if (check.exitCode !== 0) {
12
- await $({cwd, quiet: true})`git fetch origin --depth 1`
13
- }
14
- }
15
-
16
- const run = async (manifest, dir) => {
17
- const {tag, sha, cwd} = manifest
18
- const gitCommitterName = manifest.gitCommitterName || DEFAULT_GIT_COMMITTER_NAME
19
- const gitCommitterEmail = manifest.gitCommitterEmail || DEFAULT_GIT_COMMITTER_EMAIL
20
- try {
21
- await ensureSha(cwd, sha)
22
- await api.git.pushTag({cwd, tag, sha, gitCommitterName, gitCommitterEmail})
23
- return 'ok'
24
- } catch (e) {
25
- if (isTagConflict(e)) return 'conflict'
26
- throw e
27
- }
3
+ // The claim: whoever owns the tag owns the version. A tag at our commit is ours already (a re-run).
4
+ const run = async ({tag, sha, gitCommitterName, gitCommitterEmail}, dir, {gitRoot}) => {
5
+ const {pushed, commit} = await api.git.pushTag({cwd: gitRoot, tag, sha, gitCommitterName, gitCommitterEmail})
6
+ return pushed ? 'ok' : commit === sha ? 'duplicate' : 'conflict'
28
7
  }
29
8
 
30
9
  export default {
31
10
  name: 'git-tag',
32
- requires: ['tag', 'cwd'],
11
+ stage: 'claim',
12
+ requires: ['tag', 'sha'],
33
13
  when: (pkg) => !pkg.ctx?.flags?.snapshot,
34
14
  run,
35
15
  }