diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a943c75..668fb2f 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -109,14 +109,17 @@ jobs: name: Lint and Format Check runs-on: ubuntu-latest needs: [detect-changes] + # always(): on workflow_dispatch detect-changes is skipped, and a skipped + # dependency would otherwise skip this job (and every release job after it). if: | + always() && ( github.event_name == 'push' || github.event_name == 'workflow_dispatch' || needs.detect-changes.outputs.rs-changed == 'true' || needs.detect-changes.outputs.toml-changed == 'true' || needs.detect-changes.outputs.mjs-changed == 'true' || needs.detect-changes.outputs.docs-changed == 'true' || - needs.detect-changes.outputs.workflow-changed == 'true' + needs.detect-changes.outputs.workflow-changed == 'true') steps: - uses: actions/checkout@v4 @@ -150,6 +153,9 @@ jobs: - name: Check file size limit run: node scripts/check-file-size.mjs + - name: Test release scripts + run: node --test scripts/crates-io.test.mjs + # === TEST === test: name: Test (${{ matrix.os }}) @@ -212,6 +218,9 @@ jobs: - name: Check package run: cargo package --list + - name: Verify crates.io package + run: cargo publish --dry-run + # === BENCHMARKS === bench: name: Benchmarks @@ -253,10 +262,15 @@ jobs: auto-release: name: Auto Release needs: [lint, test, build] - if: github.event_name == 'push' && github.ref == 'refs/heads/main' + # always(): changelog is skipped on push, and a skipped job anywhere in the + # dependency chain would otherwise skip this job, so no release ever ran. + if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.build.result == 'success' runs-on: ubuntu-latest permissions: contents: write + # crates.io trusted publishing: crates-io-auth-action trades this job's + # GitHub OIDC token for a short-lived crates.io publish token. + id-token: write steps: - uses: actions/checkout@v4 with: @@ -280,12 +294,22 @@ jobs: id: bump_type run: node scripts/get-bump-type.mjs + - name: Check crates.io for current version + id: crate_status + run: node scripts/crates-io.mjs status + - name: Check if version already released or no fragments id: check + env: + PUBLISHED: ${{ steps.crate_status.outputs.published }} run: | if [ "${{ steps.bump_type.outputs.has_fragments }}" != "true" ]; then CURRENT_VERSION=$(grep -Po '(?<=^version = ")[^"]*' Cargo.toml) - if git rev-parse "rust-v$CURRENT_VERSION" >/dev/null 2>&1; then + if [ "$PUBLISHED" != "true" ]; then + echo "No changelog fragments but links-queue $CURRENT_VERSION is not on crates.io yet" + echo "should_release=true" >> $GITHUB_OUTPUT + echo "skip_bump=true" >> $GITHUB_OUTPUT + elif git rev-parse "rust-v$CURRENT_VERSION" >/dev/null 2>&1; then echo "No changelog fragments and rust-v$CURRENT_VERSION already released" echo "should_release=false" >> $GITHUB_OUTPUT else @@ -306,6 +330,12 @@ jobs: node scripts/version-and-commit.mjs \ --bump-type "${{ steps.bump_type.outputs.bump_type }}" + # A re-run starts from the pre-release commit again; release the version + # an earlier attempt already tagged instead of the unbumped Cargo.toml. + - name: Check out already tagged version + if: steps.version.outputs.already_released == 'true' + run: git checkout "rust-v${{ steps.version.outputs.new_version }}" + - name: Get current version id: current_version if: steps.check.outputs.should_release == 'true' @@ -317,6 +347,25 @@ jobs: if: steps.check.outputs.should_release == 'true' run: cargo build --release + # Trusted publishing (OIDC) first, the token secret only as a fallback. + # The exchange fails until crates.io has a trusted publisher for this + # repository and rust.yml; continue-on-error lets the publish step fall + # back to CARGO_REGISTRY_TOKEN / CARGO_TOKEN, and that step still fails, + # with instructions, when neither credential works. The action's post + # step revokes the temporary token. + - name: Authenticate with crates.io (trusted publishing) + id: crates_auth + if: steps.check.outputs.should_release == 'true' + uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 + continue-on-error: true + + - name: Publish to crates.io + if: steps.check.outputs.should_release == 'true' + env: + CARGO_REGISTRY_TOKEN: ${{ steps.crates_auth.outputs.token || secrets.CARGO_REGISTRY_TOKEN || secrets.CARGO_TOKEN }} + TRUSTED_PUBLISHING: ${{ steps.crates_auth.outcome }} + run: node scripts/crates-io.mjs publish + - name: Create GitHub Release if: steps.check.outputs.should_release == 'true' env: @@ -330,10 +379,13 @@ jobs: manual-release: name: Manual Release needs: [lint, test, build] - if: github.event_name == 'workflow_dispatch' + if: always() && github.event_name == 'workflow_dispatch' && needs.build.result == 'success' runs-on: ubuntu-latest permissions: contents: write + # crates.io trusted publishing: crates-io-auth-action trades this job's + # GitHub OIDC token for a short-lived crates.io publish token. + id-token: write steps: - uses: actions/checkout@v4 with: @@ -370,10 +422,35 @@ jobs: --bump-type "${{ github.event.inputs.bump_type }}" \ --description "${{ github.event.inputs.description }}" + # A re-run starts from the pre-release commit again; release the version + # an earlier attempt already tagged instead of the unbumped Cargo.toml. + - name: Check out already tagged version + if: steps.version.outputs.already_released == 'true' + run: git checkout "rust-v${{ steps.version.outputs.new_version }}" + - name: Build release if: steps.version.outputs.version_committed == 'true' || steps.version.outputs.already_released == 'true' run: cargo build --release + # Trusted publishing (OIDC) first, the token secret only as a fallback. + # The exchange fails until crates.io has a trusted publisher for this + # repository and rust.yml; continue-on-error lets the publish step fall + # back to CARGO_REGISTRY_TOKEN / CARGO_TOKEN, and that step still fails, + # with instructions, when neither credential works. The action's post + # step revokes the temporary token. + - name: Authenticate with crates.io (trusted publishing) + id: crates_auth + if: steps.version.outputs.version_committed == 'true' || steps.version.outputs.already_released == 'true' + uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 + continue-on-error: true + + - name: Publish to crates.io + if: steps.version.outputs.version_committed == 'true' || steps.version.outputs.already_released == 'true' + env: + CARGO_REGISTRY_TOKEN: ${{ steps.crates_auth.outputs.token || secrets.CARGO_REGISTRY_TOKEN || secrets.CARGO_TOKEN }} + TRUSTED_PUBLISHING: ${{ steps.crates_auth.outcome }} + run: node scripts/crates-io.mjs publish + - name: Create GitHub Release if: steps.version.outputs.version_committed == 'true' || steps.version.outputs.already_released == 'true' env: diff --git a/docs/api/rust/README.md b/docs/api/rust/README.md index 97a83fa..a934b81 100644 --- a/docs/api/rust/README.md +++ b/docs/api/rust/README.md @@ -8,7 +8,7 @@ Add to your `Cargo.toml`: ```toml [dependencies] -links-queue = "0.11" +links-queue = "0.3" tokio = { version = "1", features = ["full"] } ``` diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md index 1c54ef7..61750bc 100644 --- a/docs/guides/getting-started.md +++ b/docs/guides/getting-started.md @@ -34,7 +34,7 @@ Add to your `Cargo.toml`: ```toml [dependencies] -links-queue = "0.11" +links-queue = "0.3" tokio = { version = "1", features = ["full"] } ``` diff --git a/experiments/issue-53-crates-io-publish-paths.sh b/experiments/issue-53-crates-io-publish-paths.sh new file mode 100755 index 0000000..029b984 --- /dev/null +++ b/experiments/issue-53-crates-io-publish-paths.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Issue #53: exercise rust/scripts/crates-io.mjs without publishing anything. +# 1. status of the real crate (not on crates.io before the first release) +# 2. publish without credentials -> explicit "credentials missing" error, exit 1 +# 3. publish of a version that already exists (serde 1.0.0) -> skipped, verified +set -u +SCRIPT="$(cd "$(dirname "$0")/.." && pwd)/rust/scripts/crates-io.mjs" + +(cd "$(dirname "$SCRIPT")/.." && node "$SCRIPT" status) + +(cd "$(dirname "$SCRIPT")/.." && env -u CARGO_REGISTRY_TOKEN TRUSTED_PUBLISHING=failure node "$SCRIPT" publish) +echo "publish without credentials exit=$?" + +TMP=$(mktemp -d) +printf '[package]\nname = "serde"\nversion = "1.0.0"\n' > "$TMP/Cargo.toml" +(cd "$TMP" && VERIFY_ATTEMPTS=1 node "$SCRIPT" publish) +echo "publish of existing version exit=$?" +rm -rf "$TMP" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 5b939df..55818ba 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -10,6 +10,8 @@ categories = ["development-tools"] repository = "https://github.com/link-foundation/links-queue" documentation = "https://github.com/link-foundation/links-queue" rust-version = "1.70" +# Release tooling stays in the repository; the crate ships the library and binary. +exclude = ["changelog.d/", "scripts/", "package-lock.json"] [lib] name = "links_queue" diff --git a/rust/README.md b/rust/README.md index 0b76030..df9a26f 100644 --- a/rust/README.md +++ b/rust/README.md @@ -11,6 +11,17 @@ Rust implementation of Links Queue - a universal queue system using links. ## Quick Start +### Installation + +The crate is published to [crates.io](https://crates.io/crates/links-queue): + +```bash +cargo add links-queue + +# Or install the command-line binary +cargo install links-queue +``` + ### Development ```bash @@ -52,6 +63,31 @@ rust/ └── CHANGELOG.md # Release history ``` +## Releasing + +Merging changelog fragments to `main` (or running the workflow manually) +bumps the version, publishes the crate to crates.io and creates a GitHub +release. Publishing tries **trusted publishing (OIDC)** first and falls back +to the `CARGO_REGISTRY_TOKEN` or `CARGO_TOKEN` repository secret, so no +long-lived token is needed once the trusted publisher is registered. + +crates.io registers trusted publishers only for existing crates, so the first +version needs a one-time setup by a maintainer: + +```bash +package-registry-manager setup --repository . --registry crates-io --execute +``` + +It publishes the first version with a short-lived crate-scoped token and +registers the trusted publisher. To do it by hand instead, publish once with a +token, then open and add the +GitHub trusted publisher: owner `link-foundation`, repository `links-queue`, +workflow `rust.yml`, no environment. If neither credential works, the release +job fails with these instructions. + +A version that was tagged but never reached crates.io is published by the next +run on `main`, or by re-running the failed run. + ## API ### Functions diff --git a/rust/changelog.d/20261023_080000_crates_io_trusted_publishing.md b/rust/changelog.d/20261023_080000_crates_io_trusted_publishing.md new file mode 100644 index 0000000..100b5e2 --- /dev/null +++ b/rust/changelog.d/20261023_080000_crates_io_trusted_publishing.md @@ -0,0 +1,13 @@ +--- +bump: patch +--- + +### Added + +- Publish the crate to crates.io from the release jobs, trying trusted publishing (OIDC) first and falling back to the `CARGO_REGISTRY_TOKEN` / `CARGO_TOKEN` secret, then verify that crates.io serves the new version. Missing or rejected credentials fail the release with setup instructions. + +### Fixed + +- Run the Auto Release and Manual Release jobs again: a skipped job in their dependency chain had skipped them, so no Rust version was ever released. +- Publish a version that was tagged but never reached crates.io on the next run or a re-run, and check publishability with `cargo publish --dry-run` in CI. +- Point the installation docs at the current `links-queue = "0.3"` version. diff --git a/rust/scripts/crates-io.mjs b/rust/scripts/crates-io.mjs new file mode 100644 index 0000000..9f44786 --- /dev/null +++ b/rust/scripts/crates-io.mjs @@ -0,0 +1,273 @@ +#!/usr/bin/env node + +/** + * crates.io helpers for the Rust CI/CD pipeline + * + * Usage: + * node scripts/crates-io.mjs status # Is the Cargo.toml version on crates.io? + * node scripts/crates-io.mjs publish # Publish it, then wait until crates.io serves it + * + * `status` writes `crate`, `version` and `published` (true, false or unknown) + * to $GITHUB_OUTPUT. + * + * `publish` reads these environment variables: + * CARGO_REGISTRY_TOKEN - token from trusted publishing (OIDC) or the + * CARGO_REGISTRY_TOKEN / CARGO_TOKEN secret fallback + * TRUSTED_PUBLISHING - outcome of the crates-io-auth-action step + * GITHUB_REPOSITORY - owner/repo, used in the setup instructions + * WORKFLOW_FILE - workflow registered as trusted publisher (rust.yml) + * VERIFY_ATTEMPTS - crates.io polls after publishing (default 30) + * VERIFY_INTERVAL_MS - delay between polls (default 10000) + * + * Only Node.js built-ins are used, so the script runs without installing + * anything and its helpers can be unit tested (scripts/crates-io.test.mjs). + */ + +import { readFileSync, appendFileSync } from 'fs'; +import { spawnSync } from 'child_process'; +import { pathToFileURL } from 'url'; + +const USER_AGENT = + 'links-queue-release (https://github.com/link-foundation/links-queue)'; + +/** + * Read the package name and version from Cargo.toml content + * @param {string} cargoToml + * @returns {{name: string, version: string}} + */ +export function parseCargoToml(cargoToml) { + const pkg = cargoToml.split(/^\[(?!package\])/m)[0]; + const name = pkg.match(/^name\s*=\s*"([^"]+)"/m); + const version = pkg.match(/^version\s*=\s*"([^"]+)"/m); + if (!name || !version) { + throw new Error('Could not parse [package] name and version'); + } + return { name: name[1], version: version[1] }; +} + +/** + * Describe the trusted publisher that crates.io must have registered + * @param {{name: string, repository: string, workflow: string}} options + * @returns {{settings: string, publisher: string}} + */ +export function trustedPublisher({ name, repository, workflow }) { + const [owner, repo] = repository.split('/'); + return { + settings: `https://crates.io/crates/${name}/settings`, + publisher: `owner ${owner}, repository ${repo}, workflow ${workflow}, no environment`, + }; +} + +/** + * Classify a failed `cargo publish` output + * @param {string} output + * @returns {'already-published' | 'credentials' | 'other'} + */ +export function classifyPublishFailure(output) { + if (/already (uploaded|exists)/i.test(output)) { + return 'already-published'; + } + if ( + /unauthorized|forbidden|\b40[13]\b|invalid token|token (expired|rejected)|no token found|please provide a non-empty token/i.test( + output + ) + ) { + return 'credentials'; + } + return 'other'; +} + +/** + * Instructions shown when no crates.io credential is available + * @param {{name: string, repository: string, workflow: string}} options + * @returns {string[]} + */ +export function missingCredentialsHelp(options) { + const { settings, publisher } = trustedPublisher(options); + return [ + `::error title=crates.io credentials missing::Cannot publish ${options.name} to crates.io: trusted publishing is unavailable and neither CARGO_REGISTRY_TOKEN nor CARGO_TOKEN is set.`, + '', + 'How to fix (trusted publishing is preferred; it needs no long-lived secret):', + ' 1. First release only: crates.io registers a trusted publisher only for an', + ' existing crate, so publish the first version and register the publisher with', + ` package-registry-manager setup --repository . --registry crates-io --execute`, + ' or manually: publish once with a token, then as a crate owner open', + ` ${settings} -> Trusted Publishing -> Add -> GitHub`, + ` and enter: ${publisher}.`, + ' Docs: https://crates.io/docs/trusted-publishing', + ' 2. Token fallback: create a token at https://crates.io/settings/tokens', + ` (scopes 'publish-new' and 'publish-update') and add it at`, + ' Settings -> Secrets and variables -> Actions -> New repository secret', + ' named CARGO_REGISTRY_TOKEN (CARGO_TOKEN is also accepted).', + ' 3. Re-run the failed workflow run.', + ]; +} + +/** + * Instructions shown when crates.io rejects the credential + * @param {{name: string, repository: string, workflow: string, trusted: boolean}} options + * @returns {string[]} + */ +export function rejectedCredentialsHelp(options) { + const { settings, publisher } = trustedPublisher(options); + if (options.trusted) { + return [ + '::error title=crates.io credentials rejected::crates.io rejected the trusted publishing (OIDC) token.', + '', + 'How to fix:', + ` 1. Check the trusted publisher at ${settings} (Trusted Publishing).`, + ` It must read: ${publisher}.`, + ' 2. Re-run the failed workflow run. Docs: https://crates.io/docs/trusted-publishing', + ]; + } + return [ + '::error title=crates.io credentials rejected::crates.io rejected the CARGO_REGISTRY_TOKEN / CARGO_TOKEN secret (trusted publishing was unavailable).', + '', + 'How to fix (trusted publishing is preferred):', + ' 1. Register the trusted publisher so no token is needed: as a crate owner open', + ` ${settings} -> Trusted Publishing -> Add -> GitHub`, + ` and enter: ${publisher}.`, + ' 2. Or rotate the token, which may have expired or been revoked, at', + ' https://crates.io/settings/tokens and update the CARGO_REGISTRY_TOKEN secret.', + ' 3. Re-run the failed workflow run.', + ]; +} + +/** + * Ask crates.io whether a crate version exists + * @param {string} name + * @param {string} version + * @param {typeof fetch} [fetchImpl] + * @returns {Promise<'true' | 'false' | 'unknown'>} + */ +export async function isPublished(name, version, fetchImpl = fetch) { + try { + const response = await fetchImpl( + `https://crates.io/api/v1/crates/${name}/${version}`, + { headers: { 'User-Agent': USER_AGENT } } + ); + if (response.status === 200) { + return 'true'; + } + if (response.status === 404) { + return 'false'; + } + console.log(`crates.io answered HTTP ${response.status}`); + } catch (error) { + console.log(`crates.io request failed: ${error.message}`); + } + return 'unknown'; +} + +/** + * Append to GitHub Actions output file + * @param {string} key + * @param {string} value + */ +function setOutput(key, value) { + const outputFile = process.env.GITHUB_OUTPUT; + if (outputFile) { + appendFileSync(outputFile, `${key}=${value}\n`); + } + console.log(`${key}=${value}`); +} + +async function status(crate) { + setOutput('crate', crate.name); + setOutput('version', crate.version); + setOutput('published', await isPublished(crate.name, crate.version)); +} + +async function verify(crate) { + const attempts = Number(process.env.VERIFY_ATTEMPTS || 30); + const interval = Number(process.env.VERIFY_INTERVAL_MS || 10000); + for (let attempt = 1; attempt <= attempts; attempt++) { + if ((await isPublished(crate.name, crate.version)) === 'true') { + console.log( + `Verified: https://crates.io/crates/${crate.name}/${crate.version}` + ); + return true; + } + console.log( + `Waiting for crates.io to serve ${crate.name} ${crate.version} (${attempt}/${attempts})` + ); + await new Promise((resolve) => setTimeout(resolve, interval)); + } + console.log( + `::error title=crates.io verification failed::${crate.name} ${crate.version} is not visible on crates.io after publishing.` + ); + return false; +} + +async function publish(crate) { + const options = { + name: crate.name, + repository: process.env.GITHUB_REPOSITORY || 'link-foundation/links-queue', + workflow: process.env.WORKFLOW_FILE || 'rust.yml', + }; + const trusted = process.env.TRUSTED_PUBLISHING === 'success'; + + if ((await isPublished(crate.name, crate.version)) === 'true') { + console.log( + `${crate.name} ${crate.version} is already on crates.io, skipping cargo publish` + ); + return verify(crate); + } + + if (trusted) { + console.log('Publishing with a crates.io trusted publishing (OIDC) token.'); + } else { + const { settings, publisher } = trustedPublisher(options); + console.log( + `::warning title=crates.io trusted publishing unavailable::OIDC token exchange outcome: ${process.env.TRUSTED_PUBLISHING || 'skipped'}. Falling back to the CARGO_REGISTRY_TOKEN / CARGO_TOKEN secret. To publish without a long-lived token, register the trusted publisher at ${settings} (Trusted Publishing -> Add -> GitHub: ${publisher}).` + ); + } + + if (!process.env.CARGO_REGISTRY_TOKEN) { + console.log(missingCredentialsHelp(options).join('\n')); + return false; + } + + const result = spawnSync('cargo', ['publish'], { encoding: 'utf-8' }); + const output = `${result.stdout || ''}${result.stderr || ''}`; + console.log(output); + if (result.status === 0) { + return verify(crate); + } + + switch (classifyPublishFailure(output)) { + case 'already-published': + console.log( + '::warning::Version was published by another run; treating as success.' + ); + return verify(crate); + case 'credentials': + console.log(rejectedCredentialsHelp({ ...options, trusted }).join('\n')); + return false; + default: + console.log( + `::error title=cargo publish failed::cargo publish exited with ${result.status ?? result.error?.message}` + ); + return false; + } +} + +async function main() { + const command = process.argv[2]; + const crate = parseCargoToml(readFileSync('Cargo.toml', 'utf-8')); + + if (command === 'status') { + await status(crate); + } else if (command === 'publish') { + if (!(await publish(crate))) { + process.exit(1); + } + } else { + console.error('Usage: node scripts/crates-io.mjs '); + process.exit(1); + } +} + +if (import.meta.url === pathToFileURL(process.argv[1]).href) { + main(); +} diff --git a/rust/scripts/crates-io.test.mjs b/rust/scripts/crates-io.test.mjs new file mode 100644 index 0000000..c09bfc4 --- /dev/null +++ b/rust/scripts/crates-io.test.mjs @@ -0,0 +1,130 @@ +/** + * Unit tests for scripts/crates-io.mjs + * + * Run: node --test scripts/crates-io.test.mjs + */ + +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'fs'; + +import { + parseCargoToml, + trustedPublisher, + classifyPublishFailure, + missingCredentialsHelp, + rejectedCredentialsHelp, + isPublished, +} from './crates-io.mjs'; + +const options = { + name: 'links-queue', + repository: 'link-foundation/links-queue', + workflow: 'rust.yml', +}; + +test('parseCargoToml reads the package, not the [lib] name', () => { + const crate = parseCargoToml( + '[package]\nname = "links-queue"\nversion = "1.2.3"\n\n[lib]\nname = "links_queue"\n' + ); + assert.deepEqual(crate, { name: 'links-queue', version: '1.2.3' }); +}); + +test('parseCargoToml reads the real Cargo.toml', () => { + const crate = parseCargoToml( + readFileSync(new URL('../Cargo.toml', import.meta.url), 'utf-8') + ); + assert.equal(crate.name, 'links-queue'); + assert.match(crate.version, /^\d+\.\d+\.\d+$/); +}); + +test('parseCargoToml rejects a manifest without a package', () => { + assert.throws(() => parseCargoToml('[workspace]\nmembers = []\n')); +}); + +test('Cargo.toml stays publishable', () => { + const cargoToml = readFileSync( + new URL('../Cargo.toml', import.meta.url), + 'utf-8' + ); + assert.doesNotMatch(cargoToml, /^publish\s*=\s*false/m); +}); + +test('trustedPublisher matches the crates.io trusted publisher form', () => { + assert.deepEqual(trustedPublisher(options), { + settings: 'https://crates.io/crates/links-queue/settings', + publisher: + 'owner link-foundation, repository links-queue, workflow rust.yml, no environment', + }); +}); + +test('classifyPublishFailure recognizes already published versions', () => { + assert.equal( + classifyPublishFailure('error: crate version `0.3.1` is already uploaded'), + 'already-published' + ); + assert.equal( + classifyPublishFailure( + 'crate links-queue@0.3.1 already exists on crates.io index' + ), + 'already-published' + ); +}); + +test('classifyPublishFailure recognizes rejected credentials', () => { + for (const output of [ + 'the remote server responded with an error (status 403 Forbidden)', + 'status 401 Unauthorized: this token is invalid', + 'error: no token found, please run `cargo login`', + ]) { + assert.equal(classifyPublishFailure(output), 'credentials', output); + } +}); + +test('classifyPublishFailure leaves other failures alone', () => { + assert.equal( + classifyPublishFailure('error[E0425]: cannot find value `x` in this scope'), + 'other' + ); +}); + +test('missing credentials help explains both fixes', () => { + const help = missingCredentialsHelp(options).join('\n'); + assert.match(help, /^::error title=crates.io credentials missing::/); + assert.match(help, /package-registry-manager setup/); + assert.match(help, /https:\/\/crates.io\/crates\/links-queue\/settings/); + assert.match(help, /workflow rust.yml, no environment/); + assert.match(help, /CARGO_REGISTRY_TOKEN/); + assert.match(help, /CARGO_TOKEN/); +}); + +test('rejected credentials help depends on the credential used', () => { + assert.match( + rejectedCredentialsHelp({ ...options, trusted: true }).join('\n'), + /trusted publishing \(OIDC\) token/ + ); + assert.match( + rejectedCredentialsHelp({ ...options, trusted: false }).join('\n'), + /rotate the token/ + ); +}); + +test('isPublished maps crates.io answers', async () => { + const answer = (status) => async (url, init) => { + assert.equal(url, 'https://crates.io/api/v1/crates/links-queue/0.3.1'); + assert.match(init.headers['User-Agent'], /links-queue/); + return { status }; + }; + assert.equal(await isPublished('links-queue', '0.3.1', answer(200)), 'true'); + assert.equal(await isPublished('links-queue', '0.3.1', answer(404)), 'false'); + assert.equal( + await isPublished('links-queue', '0.3.1', answer(503)), + 'unknown' + ); + assert.equal( + await isPublished('links-queue', '0.3.1', async () => { + throw new Error('offline'); + }), + 'unknown' + ); +});