diff --git a/.changeset/multipublish-jsr-gitignored-dist.md b/.changeset/multipublish-jsr-gitignored-dist.md new file mode 100644 index 00000000..2a634507 --- /dev/null +++ b/.changeset/multipublish-jsr-gitignored-dist.md @@ -0,0 +1,11 @@ +--- +"@stephansama/multipublish": patch +--- + +Fix JSR publishing of gitignored build output, and fail the run when a publish fails + +- Directories that `exports` point into (e.g. `dist`) are added to the JSR config's `publish.exclude` as negated globs, so gitignored build output is published instead of failing with `excluded-module` +- `defaultInclude` / `defaultExclude` now go to `publish.include` / `publish.exclude`, where JSR honors negated globs like `!config`, and a user's own `publish` block is kept +- A failed publish no longer exits `0`: the remaining platforms and packages are still attempted, then the CLI lists what failed and exits `1` +- Publish errors no longer repeat the publish command, which contained the JSR auth token +- An unscoped package with the `.npmrc` strategy now fails instead of being skipped silently diff --git a/core/multipublish/README.md b/core/multipublish/README.md index 9a9f1a98..46e094d4 100644 --- a/core/multipublish/README.md +++ b/core/multipublish/README.md @@ -93,7 +93,7 @@ You can configure `multipublish` by creating a configuration file (or object) in { "$schema": "./node_modules/@stephansama/multipublish/dist/schema.json", "platforms": [ - ["jsr", { "experimentalGenerateJSR": true, "defaultExclude": ["!dist"] }], + ["jsr", { "experimentalGenerateJSR": true }], [ "npm", { @@ -118,6 +118,12 @@ permissions: When publishing to JSR, you must either have a valid `jsr.json` or `deno.json`, or allow `experimentalGenerateJSR` using the config option. +JSR leaves out gitignored files, which usually includes your build output. multipublish adds a negated `publish.exclude` glob for every directory your `exports` point into (`!dist` for `./dist/index.mjs`), so build output is published without any config. + +`defaultInclude` and `defaultExclude` are added to the JSR config's `publish.include` and `publish.exclude`. Use them for anything else, e.g. `"defaultExclude": ["!config"]` to publish a gitignored `config` directory. JSR only honors negated globs there, not in the top-level `exclude`. + +If any publish fails, multipublish still tries the remaining platforms and packages, then exits with code `1` and lists what failed. + ### Changesets If you are using jsr this with changesets, please update your version script with a preversion script that calls the `multipublish` CLI in order to update your existing jsr configurations. diff --git a/core/multipublish/__snapshots__/tsnapi/index.snapshot.d.ts b/core/multipublish/__snapshots__/tsnapi/index.snapshot.d.ts index b111c738..8664e989 100644 --- a/core/multipublish/__snapshots__/tsnapi/index.snapshot.d.ts +++ b/core/multipublish/__snapshots__/tsnapi/index.snapshot.d.ts @@ -1,6 +1,13 @@ /** * Generated by tsnapi — public API snapshot of `@stephansama/multipublish` */ +// #region Classes +export declare class PublishError extends Error { + readonly failures: string[]; + constructor(_: string[]); +} +// #endregion + // #region Functions export declare function run(): Promise; // #endregion \ No newline at end of file diff --git a/core/multipublish/__snapshots__/tsnapi/index.snapshot.js b/core/multipublish/__snapshots__/tsnapi/index.snapshot.js index c25a313f..d81d41e8 100644 --- a/core/multipublish/__snapshots__/tsnapi/index.snapshot.js +++ b/core/multipublish/__snapshots__/tsnapi/index.snapshot.js @@ -1,6 +1,12 @@ /** * Generated by tsnapi — public API snapshot of `@stephansama/multipublish` */ +// #region Classes +export class PublishError extends Error { + constructor(_) {} +} +// #endregion + // #region Functions export async function run() {} // #endregion \ No newline at end of file diff --git a/core/multipublish/src/cli.test.ts b/core/multipublish/src/cli.test.ts new file mode 100644 index 00000000..af156fe0 --- /dev/null +++ b/core/multipublish/src/cli.test.ts @@ -0,0 +1,50 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ run: vi.fn() })); + +vi.mock("./index", async (importOriginal) => ({ + ...(await importOriginal()), + run: mocks.run, +})); + +describe("cli", () => { + beforeEach(() => { + vi.resetModules(); + process.exitCode = undefined; + }); + + afterEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; + }); + + it("should exit 0 when every publish succeeds", async () => { + mocks.run.mockImplementation(() => Promise.resolve()); + + await import("./cli"); + + expect(mocks.run).toHaveBeenCalledOnce(); + expect(process.exitCode).toBeUndefined(); + }); + + it("should print the summary and exit 1 when a publish fails", async () => { + const { PublishError } = await import("./index"); + mocks.run.mockRejectedValue(new PublishError(["pkg (jsr)"])); + const consoleError = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + await import("./cli"); + + expect(consoleError).toHaveBeenCalledWith( + "1 publish failed: pkg (jsr)", + ); + expect(process.exitCode).toBe(1); + }); + + it("should rethrow errors that aren't publish failures", async () => { + mocks.run.mockRejectedValue(new Error("bad config")); + + await expect(import("./cli")).rejects.toThrow("bad config"); + }); +}); diff --git a/core/multipublish/src/cli.ts b/core/multipublish/src/cli.ts index f75abd77..302df45a 100644 --- a/core/multipublish/src/cli.ts +++ b/core/multipublish/src/cli.ts @@ -1,5 +1,12 @@ #!/usr/bin/env node -import { run } from "./index"; +import { PublishError, run } from "./index"; -await run(); +try { + await run(); +} catch (error) { + // failed platforms were already logged, so print the summary without a stack + if (!(error instanceof PublishError)) throw error; + console.error(error.message); + process.exitCode = 1; +} diff --git a/core/multipublish/src/index.test.ts b/core/multipublish/src/index.test.ts index b4d1d234..7a928e96 100644 --- a/core/multipublish/src/index.test.ts +++ b/core/multipublish/src/index.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { run } from "./index"; +import { PublishError, run } from "./index"; const mocks = vi.hoisted(() => ({ findRoot: vi.fn(() => Promise.resolve({ rootDir: "/mock/root" })), @@ -86,4 +86,26 @@ describe("run", () => { expect(mocks.updateJsrConfigVersion).toHaveBeenCalledOnce(); expect(mocks.publishPlatform).not.toHaveBeenCalled(); }); + + it("should publish the remaining packages after a failure, then throw", async () => { + mocks.publishPlatform.mockRejectedValueOnce( + new Error("npm publish failed for pkg1"), + ); + const consoleError = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const error = await run().catch((error_: unknown) => error_); + + expect(mocks.publishPlatform).toHaveBeenCalledTimes(2); + expect(error).toBeInstanceOf(PublishError); + expect((error as PublishError).failures).toEqual(["pkg1 (npm)"]); + expect((error as PublishError).message).toBe( + "1 publish failed: pkg1 (npm)", + ); + expect(consoleError).toHaveBeenCalledWith( + "✖ pkg1 (npm): npm publish failed for pkg1", + ); + consoleError.mockRestore(); + }); }); diff --git a/core/multipublish/src/index.ts b/core/multipublish/src/index.ts index 25273d29..b9a4c60a 100644 --- a/core/multipublish/src/index.ts +++ b/core/multipublish/src/index.ts @@ -7,6 +7,16 @@ import { updateJsrConfigVersion } from "./jsr"; import { publishPlatform } from "./publish"; import { loadReleases } from "./release"; +/** Thrown by {@link run} after every platform was attempted, if any failed */ +export class PublishError extends Error { + constructor(readonly failures: string[]) { + super( + `${failures.length} publish${failures.length === 1 ? "" : "es"} failed: ${failures.join(", ")}`, + ); + this.name = "PublishError"; + } +} + export async function run() { const root = await findRoot(process.cwd()); const arguments_ = await getArguments(); @@ -27,6 +37,8 @@ export async function run() { return { ...pkg, version: release.version || pkg.packageJson.version }; }); + const failures: string[] = []; + for (const pkg of releasedPackages) { if (arguments_.versionJsr) { if (!pkg.packageJson.name.includes("/")) { @@ -41,8 +53,25 @@ export async function run() { continue; } + // keep publishing the other platforms and packages when one fails, so a + // registry outage doesn't block the rest, then fail the run at the end for (const platform of config.platforms) { - await publishPlatform(pkg, platform); + try { + await publishPlatform(pkg, platform); + } catch (error) { + const name = + typeof platform === "string" ? platform : platform[0]; + const message = + error instanceof Error ? error.message : String(error); + console.error( + `✖ ${pkg.packageJson.name} (${name}): ${message}`, + ); + failures.push(`${pkg.packageJson.name} (${name})`); + } } } + + if (failures.length > 0) { + throw new PublishError(failures); + } } diff --git a/core/multipublish/src/jsr.test.ts b/core/multipublish/src/jsr.test.ts index cfe30178..aa5f0b15 100644 --- a/core/multipublish/src/jsr.test.ts +++ b/core/multipublish/src/jsr.test.ts @@ -3,7 +3,12 @@ import { describe, expect, it } from "vitest"; import type { JsrSchema } from "./jsr"; import type { JsrPlatformOptionsSchema } from "./schema"; -import { jsrTransformer, updateIncludeExcludeList } from "./jsr"; +import { + includeExportDirectories, + jsrSchema, + jsrTransformer, + updateIncludeExcludeList, +} from "./jsr"; describe("jsr", () => { describe("jsrTransformer", () => { @@ -164,21 +169,28 @@ describe("jsr", () => { updateIncludeExcludeList(jsrConfig, appConfig); - expect(jsrConfig.include).toEqual(["src"]); - expect(jsrConfig.exclude).toEqual(["test"]); + expect(jsrConfig.publish).toEqual({ + exclude: ["test"], + include: ["src"], + }); + expect(jsrConfig.include).toBeUndefined(); + expect(jsrConfig.exclude).toBeUndefined(); }); - it("should merge with existing include/exclude", () => { + it("should merge with existing publish include/exclude", () => { const jsrConfig: JsrSchema = { - exclude: ["existing-exclude"], + exclude: ["top-level-exclude"], exports: "./index.ts", - include: ["existing-include"], name: "@scope/pkg", + publish: { + exclude: ["existing-exclude"], + include: ["existing-include"], + }, version: "1.0.0", }; const appConfig: JsrPlatformOptionsSchema = { allowSlowTypes: true, - defaultExclude: ["new-exclude"], + defaultExclude: ["new-exclude", "existing-exclude"], defaultInclude: ["new-include"], experimentalGenerateJSR: false, experimentalUpdateCatalogs: false, @@ -187,14 +199,111 @@ describe("jsr", () => { updateIncludeExcludeList(jsrConfig, appConfig); - expect(jsrConfig.include).toEqual([ - "existing-include", - "new-include", + expect(jsrConfig.publish).toEqual({ + exclude: ["existing-exclude", "new-exclude"], + include: ["existing-include", "new-include"], + }); + expect(jsrConfig.exclude).toEqual(["top-level-exclude"]); + }); + + it("should not add a publish block when there is nothing to add", () => { + const jsrConfig: JsrSchema = { + exports: "./index.ts", + name: "@scope/pkg", + version: "1.0.0", + }; + + updateIncludeExcludeList(jsrConfig, { + allowSlowTypes: true, + experimentalGenerateJSR: false, + experimentalUpdateCatalogs: false, + tokenEnvironmentKey: "test", + }); + + expect(jsrConfig.publish).toBeUndefined(); + }); + }); + + describe("includeExportDirectories", () => { + const base = { name: "@scope/pkg", version: "1.0.0" }; + + it("should un-exclude the directory of a string export", () => { + const jsrConfig: JsrSchema = { + ...base, + exports: "./dist/index.mjs", + }; + includeExportDirectories(jsrConfig); + expect(jsrConfig.publish?.exclude).toEqual(["!dist"]); + }); + + it("should un-exclude each directory of a record export once", () => { + const jsrConfig: JsrSchema = { + ...base, + exports: { + ".": "./dist/index.mjs", + "./cli": "./dist/cli.mjs", + "./schema.json": "./schema/schema.json", + }, + }; + includeExportDirectories(jsrConfig); + expect(jsrConfig.publish?.exclude).toEqual(["!dist", "!schema"]); + }); + + it("should only use the top-level directory of nested paths", () => { + const jsrConfig: JsrSchema = { + ...base, + exports: { ".": "dist/esm/index.mjs" }, + }; + includeExportDirectories(jsrConfig); + expect(jsrConfig.publish?.exclude).toEqual(["!dist"]); + }); + + it("should skip exports at the package root", () => { + const jsrConfig: JsrSchema = { ...base, exports: "./index.ts" }; + includeExportDirectories(jsrConfig); + expect(jsrConfig.publish).toBeUndefined(); + }); + + it("should put the directories before existing excludes, which jsr matches last-wins", () => { + const jsrConfig: JsrSchema = { + ...base, + exports: "./dist/index.mjs", + publish: { exclude: ["dist/**/*.map", "!config"] }, + }; + includeExportDirectories(jsrConfig); + expect(jsrConfig.publish?.exclude).toEqual([ + "!dist", + "dist/**/*.map", + "!config", ]); - expect(jsrConfig.exclude).toEqual([ - "existing-exclude", - "new-exclude", + }); + + it("should keep a directory that's already listed where it is", () => { + const jsrConfig: JsrSchema = { + ...base, + exports: "./dist/index.mjs", + publish: { exclude: ["dist/internal", "!dist"] }, + }; + includeExportDirectories(jsrConfig); + expect(jsrConfig.publish?.exclude).toEqual([ + "dist/internal", + "!dist", ]); }); }); + + describe("jsrSchema", () => { + it("should keep a user's publish block", () => { + const config = jsrSchema.parse({ + exports: "./dist/index.mjs", + name: "@scope/pkg", + publish: { exclude: ["!dist"], include: ["dist", "README.md"] }, + version: "1.0.0", + }); + expect(config.publish).toEqual({ + exclude: ["!dist"], + include: ["dist", "README.md"], + }); + }); + }); }); diff --git a/core/multipublish/src/jsr.ts b/core/multipublish/src/jsr.ts index 5fe0dc77..7329ba6d 100644 --- a/core/multipublish/src/jsr.ts +++ b/core/multipublish/src/jsr.ts @@ -56,20 +56,64 @@ export const jsrTransformer = packageJsonSchema.transform((schema) => ({ export { jsrTransformer as transformer }; +const leadingDotSlashRegex = /^\.\//; + +const globListSchema = z.array(z.string().trim()).optional(); + export type JsrSchema = z.infer; export const jsrSchema = z.object({ - exclude: z.array(z.string().trim()).optional(), + exclude: globListSchema, exports: z .string() .trim() .or(z.array(z.string().trim())) .or(z.record(z.string(), z.string().trim())), - include: z.array(z.string().trim()).optional(), + include: globListSchema, license: z.string().trim().optional(), name: z.string().trim().min(1), + /** + * Publish-only file filters. Unlike the top-level `include` / `exclude`, a + * negated `publish.exclude` glob (`!dist`) can publish gitignored files. + */ + publish: z + .object({ exclude: globListSchema, include: globListSchema }) + .optional(), version: z.string().trim(), }); +/** + * Un-exclude every directory the config's `exports` point into, e.g. `!dist` + * for `./dist/index.mjs`. Build output is usually gitignored, and jsr excludes + * gitignored files, so without this every export would fail with + * `excluded-module`. + * + * The globs are prepended, because jsr uses the last matching glob: a narrower + * exclude inside the directory (e.g. `dist/*.map`) has to come after `!dist` to + * still apply. A directory that's already listed keeps its position. + */ +export function includeExportDirectories(jsrConfig: JsrSchema) { + const exportPaths = + typeof jsrConfig.exports === "string" + ? [jsrConfig.exports] + : Object.values(jsrConfig.exports); + + const directories = exportPaths.flatMap((exportPath) => { + const [directory, ...rest] = exportPath + .replace(leadingDotSlashRegex, "") + .split("/"); + return directory && rest.length > 0 ? [`!${directory}`] : []; + }); + + const existing = jsrConfig.publish?.exclude ?? []; + const missing = [...new Set(directories)].filter( + (directory) => !existing.includes(directory), + ); + if (missing.length === 0) return; + + jsrConfig.publish ??= {}; + jsrConfig.publish.exclude = [...missing, ...existing]; +} + export async function loadConfig(basePath: string) { const files = await glob(basePath + "/{deno,jsr}.json{,c}"); if (files.length > 1) { @@ -86,19 +130,18 @@ export async function loadConfig(basePath: string) { return { config: jsrSchema.parse(JSON.parse(file)), filename: configFile }; } +/** + * Add the jsr platform's `defaultInclude` / `defaultExclude` to the config's + * `publish.include` / `publish.exclude`. They go under `publish` because jsr + * only honors negated globs like `!dist` (which publish gitignored files) + * there, not in the top-level `exclude`. + */ export function updateIncludeExcludeList( jsrConfig: JsrSchema, appConfig: JsrPlatformOptionsSchema, ) { - for (const key of ["include", "exclude"] as const) { - const capitalizedKey = key.at(0)?.toUpperCase() + key.slice(1); - const appConfigKey = - `default${capitalizedKey}` as `default${Capitalize}`; - const appConfigList = appConfig[appConfigKey] || []; - - jsrConfig[key] ??= []; - jsrConfig[key] = [...jsrConfig[key], ...appConfigList]; - } + addPublishGlobs(jsrConfig, "include", appConfig.defaultInclude); + addPublishGlobs(jsrConfig, "exclude", appConfig.defaultExclude); } export async function updateJsrConfigVersion( @@ -118,6 +161,17 @@ export async function updateJsrConfigVersion( ); } +function addPublishGlobs( + jsrConfig: JsrSchema, + key: "exclude" | "include", + globs: string[] = [], +) { + if (globs.length === 0) return; + jsrConfig.publish ??= {}; + const existing = jsrConfig.publish[key] ?? []; + jsrConfig.publish[key] = [...new Set([...existing, ...globs])]; +} + function convertPackageJsonExportsToJsr(exports: ExportsSchema) { if (typeof exports === "string") return exports; const keys = Object.keys(exports); diff --git a/core/multipublish/src/publish.test.ts b/core/multipublish/src/publish.test.ts index d78c727e..8026172d 100644 --- a/core/multipublish/src/publish.test.ts +++ b/core/multipublish/src/publish.test.ts @@ -1,6 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { publishPlatform } from "./publish"; +import * as utilities from "./utilities"; + +const jsrPackage = { + dir: "/path/to/pkg", + packageJson: { name: "@scope/pkg", version: "1.0.0" }, + relativeDir: "./pkg", +}; const mocks = vi.hoisted(() => ({ detectPackageManager: vi.fn(), @@ -222,5 +229,109 @@ describe("publish", () => { { stdio: "inherit" }, ); }); + + it("should un-exclude the directories its exports point into", async () => { + vi.stubEnv("JSR_AUTH_TOKEN", ""); + mocks.loadConfig.mockResolvedValue({ + config: { + exports: { ".": "./dist/index.mjs" }, + name: "@scope/pkg", + version: "1.0.0", + }, + filename: "/path/to/pkg/jsr.json", + }); + + await publishPlatform(jsrPackage, "jsr"); + + const written = JSON.parse( + mocks.writeFile.mock.calls[0]?.[1] as string, + ) as { publish?: { exclude?: string[] } }; + expect(written.publish?.exclude).toEqual(["!dist"]); + }); + + it("should throw without the token when jsr publish fails, and still clean up", async () => { + const token = "secret-token"; + vi.stubEnv("JSR_AUTH_TOKEN", token); + mocks.loadConfig.mockResolvedValue({ + config: { + exports: "index.ts", + name: "@scope/pkg", + version: "1.0.0", + }, + filename: "/path/to/pkg/jsr.json", + }); + mocks.execSync.mockImplementation((command: string) => { + throw Object.assign(new Error(`Command failed: ${command}`), { + status: 1, + }); + }); + + const error = await publishPlatform(jsrPackage, "jsr").catch( + (error_: unknown) => error_, + ); + + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe( + "jsr publish failed for @scope/pkg (exit code 1)", + ); + expect((error as Error).message).not.toContain(token); + expect(vi.mocked(utilities.gitClean)).toHaveBeenCalledWith( + "/path/to/pkg/jsr.json", + ); + }); + + it("should leave out the exit code when the failure has none", async () => { + vi.stubEnv("JSR_AUTH_TOKEN", ""); + mocks.loadConfig.mockResolvedValue({ + config: { + exports: "index.ts", + name: "@scope/pkg", + version: "1.0.0", + }, + filename: "/path/to/pkg/jsr.json", + }); + mocks.execSync.mockImplementation(() => { + throw new Error("spawn failed"); + }); + + // an Error instance makes toThrow compare the whole message + await expect(publishPlatform(jsrPackage, "jsr")).rejects.toThrow( + new Error("jsr publish failed for @scope/pkg"), + ); + }); + + it("should throw when npm publish fails, and still clean up", async () => { + vi.stubEnv("NODE_AUTH_TOKEN", "token"); + mocks.existsSync.mockReturnValue(false); + mocks.execSync.mockImplementation(() => { + throw Object.assign(new Error("Command failed"), { status: 2 }); + }); + + await expect(publishPlatform(jsrPackage, "npm")).rejects.toThrow( + "npm publish failed for @scope/pkg (exit code 2)", + ); + expect(vi.mocked(utilities.gitClean)).toHaveBeenCalledWith( + "/path/to/pkg/package.json", + ); + expect(vi.mocked(utilities.gitClean)).toHaveBeenCalledWith( + "/fake/root/.npmrc", + ); + }); + + it("should throw for an unscoped package with the .npmrc strategy", async () => { + vi.stubEnv("NODE_AUTH_TOKEN", "token"); + mocks.existsSync.mockReturnValue(false); + + await expect( + publishPlatform( + { + ...jsrPackage, + packageJson: { name: "pkg", version: "1.0.0" }, + }, + "npm", + ), + ).rejects.toThrow("pkg is not scoped"); + expect(mocks.execSync).not.toHaveBeenCalled(); + }); }); }); diff --git a/core/multipublish/src/publish.ts b/core/multipublish/src/publish.ts index 130ab262..61fab0d1 100644 --- a/core/multipublish/src/publish.ts +++ b/core/multipublish/src/publish.ts @@ -64,6 +64,7 @@ export async function publishPlatform( } jsr.updateIncludeExcludeList(userJsr.config, config); + jsr.includeExportDirectories(userJsr.config); const jsrFile = JSON.stringify(userJsr.config, undefined, 2); await fsp.writeFile(userJsr.filename, jsrFile); @@ -79,25 +80,23 @@ export async function publishPlatform( } const authToken = process.env[config.tokenEnvironmentKey]; + const jsrFilename = userJsr.filename; - await utilities.chdir(pkg.dir, () => { - cp.execSync( - [ + try { + await utilities.chdir(pkg.dir, () => { + execPublish(pkg, "jsr", [ jsrPublishCommand[packageManager], "--allow-dirty", config.allowSlowTypes && "--allow-slow-types", isDryRun && "--dry-run", authToken && `--token ${authToken}`, - ] - .filter((x): x is string => !!x) - .join(" "), - { stdio: "inherit" }, - ); - }); - - utilities.gitClean(userJsr.filename); - if (config.experimentalUpdateCatalogs) { - utilities.gitClean(packageJsonPath); + ]); + }); + } finally { + utilities.gitClean(jsrFilename); + if (config.experimentalUpdateCatalogs) { + utilities.gitClean(packageJsonPath); + } } break; @@ -126,8 +125,8 @@ export async function publishPlatform( const scope = pkg.packageJson.name.split("/").at(0); if (!scope?.startsWith("@")) { - return console.error( - "scope does not start with @ symbol. aborting.", + throw new Error( + `${pkg.packageJson.name} is not scoped, the .npmrc strategy needs an @scope`, ); } @@ -153,21 +152,18 @@ export async function publishPlatform( } } - await utilities.chdir(pkg.dir, () => { - cp.execSync( - [ + try { + await utilities.chdir(pkg.dir, () => { + execPublish(pkg, "npm", [ npmPublishCommand[packageManager], packageManager === "pnpm" && "--no-git-checks", isDryRun && "--dry-run", - ] - .filter(Boolean) - .join(" "), - { stdio: "inherit" }, - ); - }); - - utilities.gitClean(packageJsonPath); - if (config.strategy === ".npmrc") utilities.gitClean(npmrcPath); + ]); + }); + } finally { + utilities.gitClean(packageJsonPath); + if (config.strategy === ".npmrc") utilities.gitClean(npmrcPath); + } break; } default: { @@ -177,3 +173,33 @@ export async function publishPlatform( } } } + +/** + * Run a publish command with inherited stdio, so its output is already shown. + * The error `execSync` throws on failure repeats the whole command, auth token + * included, so throw one that names the package and exit code instead. + */ +function execPublish( + pkg: Package, + platform: string, + parts: Array, +) { + const command = parts.filter((part): part is string => !!part).join(" "); + + try { + cp.execSync(command, { stdio: "inherit" }); + } catch (error) { + const status = + error && + typeof error === "object" && + "status" in error && + typeof error.status === "number" + ? ` (exit code ${error.status})` + : ""; + + // eslint-disable-next-line preserve-caught-error -- the caught error's message repeats the command, auth token included + throw new Error( + `${platform} publish failed for ${pkg.packageJson.name}${status}`, + ); + } +} diff --git a/core/multipublish/src/utilities.test.ts b/core/multipublish/src/utilities.test.ts index 1fc2ef07..c92ee44d 100644 --- a/core/multipublish/src/utilities.test.ts +++ b/core/multipublish/src/utilities.test.ts @@ -41,6 +41,20 @@ describe("chdir", () => { }); }); +describe("chdir rethrow", () => { + it("should rethrow callback errors after changing back", async () => { + const initialDirectory = fs.realpathSync(process.cwd()); + + await expect( + chdir(os.tmpdir(), () => { + throw new Error("boom"); + }), + ).rejects.toThrow("boom"); + + expect(fs.realpathSync(process.cwd())).toBe(initialDirectory); + }); +}); + describe("gitClean", () => { it("should remove the specified file", () => { const temporaryFile = "dummy-file-for-testing.tmp"; diff --git a/core/multipublish/src/utilities.ts b/core/multipublish/src/utilities.ts index 75e11ac7..606789ce 100644 --- a/core/multipublish/src/utilities.ts +++ b/core/multipublish/src/utilities.ts @@ -13,8 +13,6 @@ export async function chdir( try { process.chdir(newDirectory); await callback(); - } catch (error) { - console.error(error); } finally { process.chdir(cwd); }