diff --git a/.craft.yml b/.craft.yml index 2cda5cb1a..83c45feeb 100644 --- a/.craft.yml +++ b/.craft.yml @@ -41,12 +41,19 @@ workspaces: Build: - "/^sentry-.*$/" - "npm-package" + - "npm-package-sentry-cli" + - "/^pypi-wheel-.*$/" - "mcp-server-npm-package" - "vercel" - "install-scripts" targets: - name: npm includeNames: '/^sentry-\d.*\.tgz$/' + # The same package under the v3 name. An npm owner deprecates it in + # favor of `sentry` after the first release. + - name: npm + id: "@sentry/cli" + includeNames: &npm-sentry-cli '/^sentry-cli-\d.*\.tgz$/' # The standalone MCP server, published at the CLI's version. - name: npm id: "@sentry/mcp-server" @@ -57,6 +64,25 @@ workspaces: manifest: server.json - name: github tagPrefix: "cli@" + # PyPI and Sentry's internal index, under the v3 package name. + - name: pypi + includeNames: &wheels '/^sentry_cli-.*\.whl$/' + - name: sentry-pypi + internalPypiRepo: getsentry/pypi + includeNames: *wheels + # The v3 download location, downloads.sentry-cdn.com/sentry-cli/. v4 + # binaries keep their own names, so URLs of v3 binary names keep serving + # v3: the v3 releases' files, and the 3.x files left in latest/. + - name: gcs + bucket: sentry-sdk-assets + includeNames: &cdn-binaries '/^sentry-(darwin|linux|windows)-(arm64|x64)(\.exe)?(\.gz)?$/' + paths: + - path: /sentry-cli/{{version}}/ + metadata: + cacheControl: public, max-age=2592000 + - path: /sentry-cli/latest/ + metadata: + cacheControl: public, max-age=600 - name: vercel projectId: prj_wVkOnIwI3eIQbGD1Gw7qS1MqFFIK - name: registry @@ -70,6 +96,21 @@ workspaces: checksums: - algorithm: sha256 format: hex + # The v3 app. Lists only the files the gcs target uploads: the registry + # target links every artifact that its target-level includeNames lets + # through, and ignores includeNames under an app. + - name: registry + id: "app:sentry-cli" + includeNames: *cdn-binaries + apps: + "app:sentry-cli": + name: "Sentry CLI" + packageUrl: "https://www.npmjs.com/package/sentry" + mainDocsUrl: "https://cli.sentry.dev" + urlTemplate: "https://downloads.sentry-cdn.com/sentry-cli/{{version}}/{{file}}" + checksums: + - algorithm: sha256 + format: hex - name: brew tap: getsentry/tools formula: sentry @@ -133,6 +174,10 @@ workspaces: assert_match version.to_s, shell_output("#{bin}/sentry --version").chomp end end + # Fail before publishing anything if an artifact for the v3 names is missing. + requireNames: + - *npm-sentry-cli + - *wheels # No preReleaseCommand: Craft bumps package.json through the npm target. packages/logger: changelog: diff --git a/.github/workflows/cli-build.yml b/.github/workflows/cli-build.yml index b7a50aa04..18efcf203 100644 --- a/.github/workflows/cli-build.yml +++ b/.github/workflows/cli-build.yml @@ -154,6 +154,25 @@ jobs: with: name: sentry-${{ matrix.target }}-gz path: packages/cli/dist-bin/*.gz + # PyPI `sentry-cli` (the v3 package name) ships one wheel per binary. + - name: Build PyPI wheel + working-directory: packages/cli + env: + TARGET: ${{ matrix.target }} + run: pnpm run ts script/build-wheel.ts "$TARGET" + - name: Smoke test PyPI wheel + if: matrix.target == 'linux-x64' + env: + SENTRY_AUTH_TOKEN: "" + SENTRY_TOKEN: "" + SENTRY_CONFIG_DIR: ${{ runner.temp }}/.sentry-smoke + run: pipx run --spec packages/cli/dist-wheel/sentry_cli-*.whl sentry --help + - name: Upload PyPI wheel artifact + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: pypi-wheel-${{ matrix.target }} + path: packages/cli/dist-wheel/*.whl + if-no-files-found: error generate-patches: name: Generate nightly delta patches @@ -289,6 +308,17 @@ jobs: with: name: npm-package path: packages/cli/*.tgz + # The same package under the v3 name, @sentry/cli. Packed after the + # upload above so npm-package holds only the sentry tarball. + - name: Pack @sentry/cli + working-directory: packages/cli + run: pnpm run ts script/pack-npm-alias.ts + - name: Upload @sentry/cli npm artifact + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: npm-package-sentry-cli + path: packages/cli/sentry-cli-*.tgz + if-no-files-found: error # Every CLI release also publishes @sentry/mcp-server at the same version. - name: Bundle mcp-server run: pnpm --filter @sentry/mcp-server run bundle diff --git a/apps/cli-docs/src/content/docs/getting-started.mdx b/apps/cli-docs/src/content/docs/getting-started.mdx index 2dfa943e9..c18a90db8 100644 --- a/apps/cli-docs/src/content/docs/getting-started.mdx +++ b/apps/cli-docs/src/content/docs/getting-started.mdx @@ -150,6 +150,37 @@ Homebrew installs shell completions but can't install agent skills into your hom sentry cli setup --no-modify-path --no-completions ``` +The v3 formula, `getsentry/tools/sentry-cli`, is renamed to +`getsentry/tools/sentry`, so installing it installs this formula. + +## pip + +The PyPI package `sentry-cli` installs the standalone binary as `sentry`: + +```bash +pipx install sentry-cli # or: pip install sentry-cli +``` + +It has wheels for macOS, Linux with glibc, and Windows on the platforms listed +above, and no source distribution, so pip cannot install it elsewhere, such as +on Alpine Linux. The `sentry` PyPI package (self-hosted Sentry) also installs a +`sentry` command; do not install both into the same environment. + +## Direct Download + +Each release's binaries are attached to its +[GitHub release](https://github.com/getsentry/toolkit/releases) and served +from `https://downloads.sentry-cdn.com/sentry-cli//`, as +`sentry--` (`.exe` on Windows) and gzipped as `.gz`. For example: + +```bash +curl -fsSL https://downloads.sentry-cdn.com/sentry-cli/latest/sentry-linux-x64.gz | gunzip > sentry +chmod +x sentry +``` + +The release registry, `https://release-registry.services.sentry.io/apps/sentry-cli/latest`, +lists their SHA-256 checksums. + ## Package Managers Install globally with your preferred package manager (the npm packages require **Node.js 20+**; on **22.15+** the built-in `node:sqlite` is used, on 20–22.14 a bundled WASM fallback is used transparently): @@ -161,6 +192,9 @@ Install globally with your preferred package manager (the npm packages require * bun="bun add -g sentry" /> +The v3 package name, `@sentry/cli`, also has v4 releases with the same code. +It is deprecated; install `sentry` instead. + Unlike the install script, package manager installs don't set up shell completions or agent skills. Run `sentry cli setup` once to enable them: ```bash diff --git a/apps/cli-docs/src/content/docs/migrating-from-v3.md b/apps/cli-docs/src/content/docs/migrating-from-v3.md index 83ff0121a..bd7d3ab52 100644 --- a/apps/cli-docs/src/content/docs/migrating-from-v3.md +++ b/apps/cli-docs/src/content/docs/migrating-from-v3.md @@ -23,7 +23,7 @@ own pace. | Area | v3 (`sentry-cli`) | v4 (`sentry`) | |------|-------------------|---------------| | Binary name | `sentry-cli` | `sentry` | -| npm package | `@sentry/cli` | `sentry` | +| npm package | `@sentry/cli` | `sentry` (`@sentry/cli@4` is the same code, deprecated) | | Command groups | plural (`releases`, `projects`) | singular (`release`, `project`) | | Output | plain text | Markdown on a TTY, plain when piped, `--json` for machines | | Exit codes | mostly `1` | [semantic ranges](/exit-codes/) (auth=1x, input=2x, API=3x…) | @@ -48,6 +48,9 @@ npm install -g sentry # or: pnpm add -g sentry / yarn global add sent brew uninstall sentry-cli brew install getsentry/tools/sentry +# pip +pip install --upgrade sentry-cli + # Install script curl https://cli.sentry.dev/install -fsS | bash @@ -62,6 +65,38 @@ sentry --version sentry auth status ``` +### Where v3 was published + +v4 is also published under the v3 names, so upgrading through the channel you +already use gets you v4. Every channel installs a `sentry` command; none +installs `sentry-cli`. Pin the major version to stay on v3. + +| v3 channel | What a v4 upgrade does | Stay on v3 | +|------------|------------------------|------------| +| npm `@sentry/cli` | Installs `@sentry/cli@4`, the `sentry` package under the old name. It is deprecated: switch to `sentry`. | `@sentry/cli@^3` | +| Homebrew `getsentry/tools/sentry-cli` | The formula is renamed to `getsentry/tools/sentry`. `brew update` moves your install to it, and `brew upgrade` installs v4. | `brew pin sentry-cli` before updating | +| PyPI `sentry-cli` | Installs the standalone v4 binary as `sentry`. | `sentry-cli<4` | +| `downloads.sentry-cdn.com/sentry-cli//` | v4 versions hold the v4 binaries, named like `sentry-linux-x64` and `sentry-darwin-arm64.gz`. | Use a 3.x version in the URL | +| Release registry `app:sentry-cli` | `latest` is v4, with download URLs on `downloads.sentry-cdn.com`. | `apps/sentry-cli/3` | +| `https://sentry.io/get-cli/` | Installs v4 with `https://cli.sentry.dev/install`, which needs bash. | `SENTRY_CLI_VERSION=3.8.2` | +| `sentry-cli update` | Finds no v4 binary under a v3 name, so it stops with "Could not get the latest release version." | Nothing to do | + +The v3 file names, such as `sentry-cli-Linux-x86_64`, exist only for v3 versions, +including under `downloads.sentry-cdn.com/sentry-cli/latest/`. A script that +downloads one of them keeps getting v3, never a v4 binary that it would run as +`sentry-cli`. + +A global install of `@sentry/cli@4` and one of `sentry` both provide the +`sentry` command, so npm refuses to install the second. Uninstall +`@sentry/cli` first. `sentry cli upgrade` keeps upgrading the npm package that +you installed, so it upgrades an `@sentry/cli` install in place. + +The PyPI wheels need macOS 13.5 or later, or Linux with glibc 2.28 or later, on +x64 or arm64, or Windows on x64. There are no musl (Alpine) wheels; use +`npm install -g sentry` there. The `sentry` PyPI package, which is self-hosted +Sentry, also installs a `sentry` command, so do not install both into one +environment. + ## The `sentry-cli` → `sentry` rename If you only ever call the top-level binary, the simplest bridge is a plain diff --git a/design/sentry-cli.md b/design/sentry-cli.md index aefd9c637..ee085820b 100644 --- a/design/sentry-cli.md +++ b/design/sentry-cli.md @@ -22,7 +22,10 @@ a terminal, with as little setup as the current project allows. - Targets: `/`, `/`, a project name, or a Sentry URL. - `--json` on list and view commands, and `-w`/`--web` on view commands. - The npm package `sentry`, release binaries, and the docs at - . + . Releases also go out under the v3 names: npm + `@sentry/cli`, PyPI `sentry-cli`, and `downloads.sentry-cdn.com/sentry-cli/`. + Each installs the `sentry` command. The Homebrew formula + `getsentry/tools/sentry-cli` is renamed to `getsentry/tools/sentry`. ## Rules diff --git a/docs/cli/README.md b/docs/cli/README.md index b00096715..52b2d48d5 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -14,7 +14,8 @@ CLI releases build it from that workspace. Start here for repository guides: [command conventions](../../packages/cli/CONTRIBUTING.md) — implementation details and command design. - [CLI build workflow](../../.github/workflows/cli-build.yml) and - [release configuration](../../.craft.yml) — binaries, npm packaging, and + [release configuration](../../.craft.yml) — binaries, npm and PyPI + packaging (including the v3 names `@sentry/cli` and `sentry-cli`), and release-gated website artifacts. - [Website packaging](../../apps/cli-docs/vercel/build-output.mjs) — the Vercel routes for `/install`, and the `/install/` function that diff --git a/packages/cli/.gitignore b/packages/cli/.gitignore index 6c3e2be57..89b0925b9 100644 --- a/packages/cli/.gitignore +++ b/packages/cli/.gitignore @@ -10,6 +10,7 @@ node_modules out dist dist-bin +dist-wheel dist-build # Scratch output of script/lib/split-bundle.ts .split-* diff --git a/packages/cli/packaging/npm-sentry-cli-README.md b/packages/cli/packaging/npm-sentry-cli-README.md new file mode 100644 index 000000000..dfa47bc6f --- /dev/null +++ b/packages/cli/packaging/npm-sentry-cli-README.md @@ -0,0 +1,15 @@ +# @sentry/cli + +Version 4 of the Sentry CLI is published as [`sentry`](https://www.npmjs.com/package/sentry). +`@sentry/cli` 4.x ships the same code under the old package name, so that +upgrades find it. Install `sentry` instead: + +```bash +npm install -g sentry +``` + +The command is now `sentry`, not `sentry-cli`, and the `SentryCli` class is +replaced by `createSentrySDK()`. Version 3 stays available as `@sentry/cli@3`. + +See [Migrating from v3](https://cli.sentry.dev/migrating-from-v3/) and the +[documentation](https://cli.sentry.dev). diff --git a/packages/cli/packaging/pypi-README.md b/packages/cli/packaging/pypi-README.md new file mode 100644 index 000000000..cf66255c9 --- /dev/null +++ b/packages/cli/packaging/pypi-README.md @@ -0,0 +1,21 @@ +# sentry-cli + +The command-line interface for [Sentry](https://sentry.io), built for +developers and AI agents. + +Each wheel contains the standalone `sentry` binary for one platform: macOS +(arm64, x64), Linux with glibc 2.28 or later (arm64, x64), and Windows (x64). +There is no source distribution, so pip cannot install it on other platforms, +such as Alpine Linux. Use `npm install -g sentry` there. + +```bash +pip install sentry-cli +sentry --help +``` + +Version 4 installs a `sentry` command, not `sentry-cli`. To keep version 3, +pin `sentry-cli<4`. The `sentry` package (self-hosted Sentry) also installs a +`sentry` command, so do not install both into the same environment. + +See [Migrating from v3](https://cli.sentry.dev/migrating-from-v3/) and the +[documentation](https://cli.sentry.dev). diff --git a/packages/cli/script/build-wheel.ts b/packages/cli/script/build-wheel.ts new file mode 100644 index 000000000..ff6ee671e --- /dev/null +++ b/packages/cli/script/build-wheel.ts @@ -0,0 +1,42 @@ +/** + * Build the PyPI wheel of one standalone binary. + * + * Usage (from packages/cli, after `pnpm run build -- --target `): + * pnpm run ts script/build-wheel.ts linux-x64 + * + * Reads dist-bin/sentry-[.exe] and writes dist-wheel/.whl. + */ + +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { extname, join } from "node:path"; +import pkg from "../package.json" with { type: "json" }; +import { buildWheel, WHEEL_TARGETS } from "./lib/python-wheel.js"; +import { logger } from "../src/lib/logger.js"; + +const OUT_DIR = "dist-wheel"; + +const target = process.argv[2] ?? ""; +const exe = WHEEL_TARGETS[target]?.exe; +if (!exe) { + logger.error( + `Usage: build-wheel.ts , one of: ${Object.keys(WHEEL_TARGETS).join(", ")}`, + ); + process.exit(1); +} + +const [binary, readme, license] = await Promise.all([ + readFile(join("dist-bin", `sentry-${target}${extname(exe)}`)), + readFile("packaging/pypi-README.md", "utf-8"), + readFile("LICENSE.md", "utf-8"), +]); +const wheel = buildWheel({ + target, + version: pkg.version, + binary, + summary: pkg.description, + readme, + license, +}); +await mkdir(OUT_DIR, { recursive: true }); +await writeFile(join(OUT_DIR, wheel.filename), wheel.contents); +logger.success(`Built ${OUT_DIR}/${wheel.filename}`); diff --git a/packages/cli/script/lib/npm-alias.ts b/packages/cli/script/lib/npm-alias.ts new file mode 100644 index 000000000..d7fce6082 --- /dev/null +++ b/packages/cli/script/lib/npm-alias.ts @@ -0,0 +1,45 @@ +/** + * The `@sentry/cli` npm package: the `sentry` package under the v3 name, so + * `npm install @sentry/cli@latest` gets version 4. + */ + +import { execFileSync } from "node:child_process"; +import { copyFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +export const NPM_ALIAS_NAME = "@sentry/cli"; + +/** + * Repack a `sentry` npm tarball as `@sentry/cli`, with the same files and the + * given README. npm names the result `sentry-cli-.tgz`. + * + * @param tarball - Tarball from `npm pack` of the `sentry` package + * @param readme - README that replaces the package's own + * @param outDir - Directory for the new tarball + */ +export async function packNpmAlias( + tarball: string, + readme: string, + outDir: string, +): Promise { + const dir = await mkdtemp(join(tmpdir(), "sentry-npm-alias-")); + try { + execFileSync("tar", ["-xzf", resolve(tarball), "-C", dir]); + // npm pack always puts the package in package/. + const packageDir = join(dir, "package"); + const manifestPath = join(packageDir, "package.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf-8")); + manifest.name = NPM_ALIAS_NAME; + manifest.publishConfig = { access: "public" }; + await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + await copyFile(readme, join(packageDir, "README.md")); + execFileSync( + "npm", + ["pack", "--ignore-scripts", "--pack-destination", resolve(outDir)], + { cwd: packageDir, stdio: ["ignore", "ignore", "inherit"] }, + ); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} diff --git a/packages/cli/script/lib/python-wheel.ts b/packages/cli/script/lib/python-wheel.ts new file mode 100644 index 000000000..862f537e9 --- /dev/null +++ b/packages/cli/script/lib/python-wheel.ts @@ -0,0 +1,145 @@ +/** + * Python wheels for the standalone binaries. + * + * The CLI is published on PyPI under the v3 name, `sentry-cli`. Each wheel + * holds one platform's binary as a data script, so pip puts a `sentry` (or + * `sentry.exe`) command on PATH and needs no Python code to run it. + * See https://packaging.python.org/en/latest/specifications/binary-distribution-format/ + */ + +import { createHash } from "node:crypto"; +import { type Zippable, zipSync } from "fflate"; + +/** Distribution name, normalized for wheel file names. */ +const DISTRIBUTION = "sentry_cli"; + +type WheelTarget = { + /** Wheel platform tag. */ + platform: string; + /** File name of the command in the scripts directory. */ + exe: string; +}; + +/** + * One wheel per binary target. The binaries embed Node's official builds: + * Linux ones need glibc 2.28, so there are no musllinux wheels. macOS ones need + * 13.5, but pip only matches `_0` tags from macOS 11 on, so 13.0 is the closest + * tag it installs. + */ +export const WHEEL_TARGETS: Record = { + "darwin-arm64": { platform: "macosx_13_0_arm64", exe: "sentry" }, + "darwin-x64": { platform: "macosx_13_0_x86_64", exe: "sentry" }, + "linux-arm64": { platform: "manylinux_2_28_aarch64", exe: "sentry" }, + "linux-x64": { platform: "manylinux_2_28_x86_64", exe: "sentry" }, + "windows-x64": { platform: "win_amd64", exe: "sentry.exe" }, +}; + +const SEMVER_RE = /^(\d+\.\d+\.\d+)(?:-(alpha|beta|rc|dev)\.(\d+))?$/; +const PEP440_PRERELEASE: Record = { + alpha: "a", + beta: "b", + rc: "rc", + dev: ".dev", +}; + +/** + * Convert a CLI version to its normalized PEP 440 form: `1.2.3-rc.1` becomes + * `1.2.3rc1`, and the nightly `1.2.3-dev.` becomes + * `1.2.3.dev`. + */ +export function toPep440Version(version: string): string { + const match = SEMVER_RE.exec(version); + if (!match) { + throw new Error(`Cannot convert CLI version ${version} to PEP 440`); + } + const [, release, prerelease, number] = match; + return prerelease + ? `${release}${PEP440_PRERELEASE[prerelease]}${number}` + : (release as string); +} + +/** Zip external attributes of a regular Unix file, as an unsigned 32-bit int. */ +function unixAttrs(mode: number): number { + return ((0o100000 | mode) << 16) >>> 0; +} + +/** RECORD hash: unpadded URL-safe base64 of the SHA-256 digest. */ +function recordHash(data: Uint8Array): string { + return `sha256=${createHash("sha256").update(data).digest("base64url")}`; +} + +export type WheelInput = { + /** Binary target, a key of {@link WHEEL_TARGETS}. */ + target: string; + /** CLI version, as in package.json. */ + version: string; + binary: Uint8Array; + summary: string; + /** Markdown shown on the PyPI project page. */ + readme: string; + license: string; +}; + +/** Build the wheel for one binary target. */ +export function buildWheel(input: WheelInput): { + filename: string; + contents: Uint8Array; +} { + const target = WHEEL_TARGETS[input.target]; + if (!target) { + throw new Error(`No wheel platform for binary target ${input.target}`); + } + const version = toPep440Version(input.version); + const tag = `py3-none-${target.platform}`; + const prefix = `${DISTRIBUTION}-${version}`; + const distInfo = `${prefix}.dist-info`; + const encoder = new TextEncoder(); + + const metadata = [ + "Metadata-Version: 2.1", + "Name: sentry-cli", + `Version: ${version}`, + `Summary: ${input.summary}`, + "Home-page: https://cli.sentry.dev", + "Author: Sentry", + "Author-email: oss@sentry.io", + "License: FSL-1.1-Apache-2.0", + "Project-URL: Source, https://github.com/getsentry/toolkit", + "Description-Content-Type: text/markdown", + "", + input.readme, + ].join("\n"); + const wheel = [ + "Wheel-Version: 1.0", + "Generator: getsentry/toolkit packages/cli/script/build-wheel.ts", + "Root-Is-Purelib: false", + `Tag: ${tag}`, + "", + ].join("\n"); + + const files: [path: string, data: Uint8Array][] = [ + [`${prefix}.data/scripts/${target.exe}`, input.binary], + [`${distInfo}/METADATA`, encoder.encode(metadata)], + [`${distInfo}/WHEEL`, encoder.encode(wheel)], + [`${distInfo}/LICENSE.md`, encoder.encode(input.license)], + ]; + const recordPath = `${distInfo}/RECORD`; + const record = [ + ...files.map( + ([path, data]) => `${path},${recordHash(data)},${data.byteLength}`, + ), + `${recordPath},,`, + "", + ].join("\n"); + files.push([recordPath, encoder.encode(record)]); + + const zippable: Zippable = {}; + for (const [path, data] of files) { + const executable = path.includes(".data/scripts/"); + zippable[path] = [ + data, + { os: 3, attrs: unixAttrs(executable ? 0o755 : 0o644) }, + ]; + } + return { filename: `${prefix}-${tag}.whl`, contents: zipSync(zippable) }; +} diff --git a/packages/cli/script/pack-npm-alias.ts b/packages/cli/script/pack-npm-alias.ts new file mode 100644 index 000000000..49d09e8de --- /dev/null +++ b/packages/cli/script/pack-npm-alias.ts @@ -0,0 +1,19 @@ +/** + * Pack `@sentry/cli` from the `sentry` tarball. + * + * Usage (from packages/cli, after `npm pack`): + * pnpm run ts script/pack-npm-alias.ts + * + * Reads sentry-.tgz and writes sentry-cli-.tgz. + */ + +import pkg from "../package.json" with { type: "json" }; +import { NPM_ALIAS_NAME, packNpmAlias } from "./lib/npm-alias.js"; +import { logger } from "../src/lib/logger.js"; + +await packNpmAlias( + `sentry-${pkg.version}.tgz`, + "packaging/npm-sentry-cli-README.md", + ".", +); +logger.success(`Packed ${NPM_ALIAS_NAME}@${pkg.version}`); diff --git a/packages/cli/src/commands/cli/uninstall.ts b/packages/cli/src/commands/cli/uninstall.ts index 49aadd43e..778db99f6 100644 --- a/packages/cli/src/commands/cli/uninstall.ts +++ b/packages/cli/src/commands/cli/uninstall.ts @@ -28,7 +28,10 @@ import { homedir } from "node:os"; import { basename, dirname } from "node:path"; import type { SentryContext } from "../../context.js"; import { getSkillInstallPath } from "../../lib/agent-skills.js"; -import { isHomebrewInstall } from "../../lib/binary.js"; +import { + getPackageManagerUninstallCommand, + isHomebrewInstall, +} from "../../lib/binary.js"; import { getCompletionPath } from "../../lib/completions.js"; import { closeDatabase, @@ -53,18 +56,6 @@ const SENTRY_MARKER = "# sentry"; /** Regex to strip `.exe` suffix from binary names (Windows). */ const EXE_SUFFIX_RE = /\.exe$/; -/** - * Uninstall hints for package manager installs — advise users to use - * their PM's own uninstall instead. - */ -const PM_UNINSTALL_HINTS: Record = { - npm: "npm uninstall -g sentry", - pnpm: "pnpm remove -g sentry", - bun: "bun remove -g sentry", - yarn: "yarn global remove sentry", - brew: "brew uninstall getsentry/tools/sentry", -}; - /** * Detect if the CLI is running via a package manager even without stored * install info. Checks `process.argv[1]` for node_modules indicators. @@ -481,12 +472,13 @@ export const uninstallCommand = buildDeleteCommand({ const installInfo = getInstallInfo(); const pmMethod = isHomebrewInstall() ? "brew" - : installInfo?.method && installInfo.method in PM_UNINSTALL_HINTS + : installInfo?.method && + getPackageManagerUninstallCommand(installInfo.method) ? installInfo.method : detectRuntimePackageManager(); if (pmMethod) { - const hint = PM_UNINSTALL_HINTS[pmMethod] ?? ""; + const hint = getPackageManagerUninstallCommand(pmMethod) ?? ""; const result: UninstallResult = { removed: [], skipped: [], diff --git a/packages/cli/src/commands/cli/upgrade.ts b/packages/cli/src/commands/cli/upgrade.ts index fc7019ada..dbfadf6ab 100644 --- a/packages/cli/src/commands/cli/upgrade.ts +++ b/packages/cli/src/commands/cli/upgrade.ts @@ -23,6 +23,7 @@ import { sentry } from "../../lib/app-identity.js"; import { compareVersions, determineInstallDir, + getPackageManagerUninstallCommand, isDowngrade, isNightlyVersion, LEGACY_INSTALL_SUBDIR, @@ -1035,18 +1036,11 @@ async function migrateToStandaloneForNightly(opts: { // Build warnings about the potentially shadowing old installation. // Note: install info is already recorded by the child `setup --install` // process, so no redundant setInstallInfo call is needed here. - const uninstallHints: Record = { - npm: "npm uninstall -g sentry", - pnpm: "pnpm remove -g sentry", - bun: "bun remove -g sentry", - yarn: "yarn global remove sentry", - brew: "brew uninstall getsentry/tools/sentry", - }; const warnings: string[] = []; warnings.push( `Your ${method}-installed sentry may still appear earlier in PATH.`, ); - const hint = uninstallHints[method]; + const hint = getPackageManagerUninstallCommand(method); if (hint) { warnings.push(`Consider removing it: ${hint}`); } diff --git a/packages/cli/src/lib/binary.ts b/packages/cli/src/lib/binary.ts index 1a580de0f..70ba34ec1 100644 --- a/packages/cli/src/lib/binary.ts +++ b/packages/cli/src/lib/binary.ts @@ -18,7 +18,7 @@ import { import { chmod, copyFile, mkdir, realpath, unlink } from "node:fs/promises"; import { delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path"; import { compare as semverCompare } from "semver"; -import { getUserAgent } from "./constants.js"; +import { getUserAgent, NODE_MODULES_DIRNAME } from "./constants.js"; import { buildTlsErrorDetail, customFetch, @@ -122,6 +122,54 @@ export function isHomebrewInstall(): boolean { return execPath.includes(HOMEBREW_CELLAR_SEGMENT); } +/** + * npm packages that install the CLI (see `.craft.yml`): `sentry`, and + * `@sentry/cli`, which v3 used. + */ +type NpmPackageName = "sentry" | "@sentry/cli"; + +/** + * The npm package that a global package-manager install runs from, read from + * the script path (`.../node_modules/@sentry/cli/dist/bin.cjs`). Upgrades and + * uninstalls must name that package: `sentry` and `@sentry/cli` both install + * the `sentry` command, so installing one over the other fails. + */ +export function getNpmPackageName( + scriptPath = process.argv[1] ?? "", +): NpmPackageName { + const segments = scriptPath.split(/[\\/]/); + const packageIndex = segments.lastIndexOf(NODE_MODULES_DIRNAME) + 1; + return packageIndex > 0 && + segments[packageIndex] === "@sentry" && + segments[packageIndex + 1] === "cli" + ? "@sentry/cli" + : "sentry"; +} + +/** + * The command that removes a package-manager install of the CLI, or + * undefined when `method` is not a package manager. + */ +export function getPackageManagerUninstallCommand( + method: string, +): string | undefined { + const packageName = getNpmPackageName(); + switch (method) { + case "npm": + return `npm uninstall -g ${packageName}`; + case "pnpm": + return `pnpm remove -g ${packageName}`; + case "bun": + return `bun remove -g ${packageName}`; + case "yarn": + return `yarn global remove ${packageName}`; + case "brew": + return "brew uninstall getsentry/tools/sentry"; + default: + return; + } +} + /** * How the CLI was installed. Determines the upgrade strategy. * diff --git a/packages/cli/src/lib/upgrade.ts b/packages/cli/src/lib/upgrade.ts index 843135d36..979420ad9 100644 --- a/packages/cli/src/lib/upgrade.ts +++ b/packages/cli/src/lib/upgrade.ts @@ -35,6 +35,7 @@ import { getGitHubHeaders, getGitHubLatestReleaseUrl, getGitHubReleaseByTagUrl, + getNpmPackageName, getPlatformBinaryName, type InstallationMethod, isHomebrewInstall, @@ -93,8 +94,10 @@ export type OfflineMode = false | "explicit" | "network-fallback"; /** The git tag used for the rolling nightly GitHub release (stable fallback only). */ export const NIGHTLY_TAG = "nightly"; -/** npm registry base URL */ -const NPM_REGISTRY_URL = "https://registry.npmjs.org/sentry"; +/** npm registry URL of the package the CLI runs from. */ +function getNpmRegistryUrl(): string { + return `https://registry.npmjs.org/${getNpmPackageName()}`; +} /** Regex to strip 'v' prefix from version strings */ export const VERSION_PREFIX_REGEX = /^v/; @@ -532,7 +535,7 @@ export async function fetchLatestFromGitHub( */ export async function fetchLatestFromNpm(): Promise { const response = await fetchWithUpgradeError( - `${NPM_REGISTRY_URL}/latest`, + `${getNpmRegistryUrl()}/latest`, { headers: { Accept: "application/json" } }, "npm registry", ); @@ -761,7 +764,7 @@ export async function versionExists( validateStableVersion(version, "Requested package version"); const response = await fetchWithUpgradeError( - `${NPM_REGISTRY_URL}/${version}`, + `${getNpmRegistryUrl()}/${version}`, { method: "HEAD" }, "npm registry", ); @@ -1288,7 +1291,8 @@ function executeUpgradeHomebrew(): Promise { } /** - * Execute upgrade via package manager global install. + * Execute upgrade via package manager global install of the package the CLI + * runs from (`sentry` or `@sentry/cli`). * * @param pm - Package manager to use * @param version - Target version to install @@ -1299,10 +1303,9 @@ function executeUpgradePackageManager( version: string, ): Promise { return new Promise((resolve, reject) => { + const spec = `${getNpmPackageName()}@${version}`; const args = - pm === "yarn" - ? ["global", "add", `sentry@${version}`] - : ["install", "-g", `sentry@${version}`]; + pm === "yarn" ? ["global", "add", spec] : ["install", "-g", spec]; // npm/pnpm/yarn are .cmd batch files on Windows; spawn() without // shell: true cannot execute .cmd files (ENOENT). diff --git a/packages/cli/test/lib/binary.test.ts b/packages/cli/test/lib/binary.test.ts index 62721aa1f..b6dfac58b 100644 --- a/packages/cli/test/lib/binary.test.ts +++ b/packages/cli/test/lib/binary.test.ts @@ -28,6 +28,8 @@ import { getBinaryPaths, getGitHubReleaseByTagUrl, getLegacyInstallDirs, + getNpmPackageName, + getPackageManagerUninstallCommand, getPlatformBinaryName, installBinary, isDowngrade, @@ -873,6 +875,75 @@ describe("isDowngrade", () => { }); }); +describe("getNpmPackageName", () => { + test("reads @sentry/cli from an npm global install path", () => { + expect( + getNpmPackageName("/usr/local/lib/node_modules/@sentry/cli/dist/bin.cjs"), + ).toBe("@sentry/cli"); + }); + + test("reads @sentry/cli from a pnpm store path", () => { + expect( + getNpmPackageName( + "/home/u/.local/share/pnpm/global/5/node_modules/.pnpm/@sentry+cli@4.0.0/node_modules/@sentry/cli/dist/bin.cjs", + ), + ).toBe("@sentry/cli"); + }); + + test("reads @sentry/cli from a Windows path", () => { + expect( + getNpmPackageName( + "C:\\Users\\u\\AppData\\Roaming\\npm\\node_modules\\@sentry\\cli\\dist\\bin.cjs", + ), + ).toBe("@sentry/cli"); + }); + + test("returns sentry for the sentry package and for non-npm installs", () => { + expect( + getNpmPackageName("/usr/local/lib/node_modules/sentry/dist/bin.cjs"), + ).toBe("sentry"); + // A dependency of the sentry package is not the installed package. + expect( + getNpmPackageName( + "/usr/local/lib/node_modules/@sentry/cli/node_modules/sentry/dist/bin.cjs", + ), + ).toBe("sentry"); + expect(getNpmPackageName("issue")).toBe("sentry"); + }); +}); + +describe("getPackageManagerUninstallCommand", () => { + let originalArgv: string[]; + + beforeEach(() => { + originalArgv = [...process.argv]; + }); + + afterEach(() => { + process.argv = originalArgv; + }); + + test("names the package the CLI runs from", () => { + process.argv[1] = "/usr/local/lib/node_modules/@sentry/cli/dist/bin.cjs"; + expect(getPackageManagerUninstallCommand("npm")).toBe( + "npm uninstall -g @sentry/cli", + ); + expect(getPackageManagerUninstallCommand("yarn")).toBe( + "yarn global remove @sentry/cli", + ); + + process.argv[1] = "/usr/local/lib/node_modules/sentry/dist/bin.cjs"; + expect(getPackageManagerUninstallCommand("pnpm")).toBe( + "pnpm remove -g sentry", + ); + }); + + test("returns undefined for non-package-manager methods", () => { + expect(getPackageManagerUninstallCommand("curl")).toBeUndefined(); + expect(getPackageManagerUninstallCommand("unknown")).toBeUndefined(); + }); +}); + describe("isMusl", () => { test("returns false on non-Linux platforms", () => { if (process.platform !== "linux") { diff --git a/packages/cli/test/lib/upgrade.test.ts b/packages/cli/test/lib/upgrade.test.ts index 4589c882e..d1dd6ce26 100644 --- a/packages/cli/test/lib/upgrade.test.ts +++ b/packages/cli/test/lib/upgrade.test.ts @@ -2581,6 +2581,58 @@ describe("executeUpgrade (package managers)", () => { expect(capturedOpts).toHaveProperty("shell", process.platform === "win32"); }); + describe("installed from @sentry/cli", () => { + let originalArgv: string[]; + + beforeEach(() => { + originalArgv = [...process.argv]; + process.argv[1] = join( + "/usr/local/lib", + "node_modules", + "@sentry", + "cli", + "dist", + "bin.cjs", + ); + }); + + afterEach(() => { + process.argv = originalArgv; + }); + + test("npm: upgrades @sentry/cli, not sentry", async () => { + let capturedArgs: string[] = []; + spawnImpl.fn = (_cmd, args) => { + capturedArgs = args; + return fakeProcess(0); + }; + await executeUpgrade("npm", "4.1.0"); + expect(capturedArgs).toEqual(["install", "-g", "@sentry/cli@4.1.0"]); + }); + + test("yarn: upgrades @sentry/cli, not sentry", async () => { + let capturedArgs: string[] = []; + spawnImpl.fn = (_cmd, args) => { + capturedArgs = args; + return fakeProcess(0); + }; + await executeUpgrade("yarn", "4.1.0"); + expect(capturedArgs).toEqual(["global", "add", "@sentry/cli@4.1.0"]); + }); + + test("fetchLatestFromNpm reads the @sentry/cli package", async () => { + let requestedUrl = ""; + mockFetch(async (url) => { + requestedUrl = extractInputUrl(url); + return Response.json({ version: "4.1.0" }); + }); + expect(await fetchLatestFromNpm()).toBe("4.1.0"); + expect(requestedUrl).toBe( + "https://registry.npmjs.org/@sentry/cli/latest", + ); + }); + }); + test("npm: throws UpgradeError on non-zero exit", async () => { spawnImpl.fn = () => fakeProcess(1); try { diff --git a/packages/cli/test/script/npm-alias.test.ts b/packages/cli/test/script/npm-alias.test.ts new file mode 100644 index 000000000..f9672a036 --- /dev/null +++ b/packages/cli/test/script/npm-alias.test.ts @@ -0,0 +1,84 @@ +import { execFileSync } from "node:child_process"; +import { + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { packNpmAlias } from "../../script/lib/npm-alias.js"; + +describe("packNpmAlias", () => { + let dir: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "sentry-npm-alias-test-")); + }); + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + /** Pack a minimal `sentry` package and return its tarball path. */ + function packSentry(): string { + const source = join(dir, "sentry"); + mkdirSync(join(source, "dist"), { recursive: true }); + writeFileSync( + join(source, "package.json"), + JSON.stringify({ + name: "sentry", + version: "4.0.0", + bin: { sentry: "./dist/bin.cjs" }, + files: ["dist/*.cjs", "README.md"], + // Must not run: the alias is packed with --ignore-scripts. + scripts: { prepack: "exit 1" }, + }), + ); + writeFileSync(join(source, "dist", "bin.cjs"), "#!/usr/bin/env node\n"); + writeFileSync(join(source, "README.md"), "# sentry\n"); + execFileSync( + "npm", + ["pack", "--ignore-scripts", "--pack-destination", dir], + { cwd: source, stdio: "ignore" }, + ); + return join(dir, "sentry-4.0.0.tgz"); + } + + test("renames the package and swaps the README", async () => { + const readme = join(dir, "alias-README.md"); + writeFileSync(readme, "# @sentry/cli\n"); + const out = join(dir, "out"); + mkdirSync(out); + + await packNpmAlias(packSentry(), readme, out); + + expect(readdirSync(out)).toEqual(["sentry-cli-4.0.0.tgz"]); + const extracted = join(dir, "extracted"); + mkdirSync(extracted); + execFileSync("tar", [ + "-xzf", + join(out, "sentry-cli-4.0.0.tgz"), + "-C", + extracted, + ]); + const manifest = JSON.parse( + readFileSync(join(extracted, "package", "package.json"), "utf-8"), + ); + expect(manifest).toMatchObject({ + name: "@sentry/cli", + version: "4.0.0", + bin: { sentry: "./dist/bin.cjs" }, + publishConfig: { access: "public" }, + }); + expect(readFileSync(join(extracted, "package", "README.md"), "utf-8")).toBe( + "# @sentry/cli\n", + ); + expect( + readFileSync(join(extracted, "package", "dist", "bin.cjs"), "utf-8"), + ).toBe("#!/usr/bin/env node\n"); + }); +}); diff --git a/packages/cli/test/script/python-wheel.test.ts b/packages/cli/test/script/python-wheel.test.ts new file mode 100644 index 000000000..4877526d8 --- /dev/null +++ b/packages/cli/test/script/python-wheel.test.ts @@ -0,0 +1,137 @@ +import { createHash } from "node:crypto"; +import { unzipSync } from "fflate"; +import { describe, expect, test } from "vitest"; +import { + buildWheel, + toPep440Version, + WHEEL_TARGETS, +} from "../../script/lib/python-wheel.js"; + +const decoder = new TextDecoder(); +const binary = new TextEncoder().encode("\x7fELF fake binary"); + +function build(target: string, version = "4.0.0") { + return buildWheel({ + target, + version, + binary, + summary: "Sentry CLI", + readme: "# sentry-cli\n", + license: "FSL", + }); +} + +/** External attributes of each entry, read from the zip central directory. */ +function externalAttrs(zip: Uint8Array): Map { + const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength); + const attrs = new Map(); + let offset = view.getUint32(zip.byteLength - 6, true); + while (view.getUint32(offset, true) === 0x02_01_4b_50) { + const nameLength = view.getUint16(offset + 28, true); + const extraLength = view.getUint16(offset + 30, true); + const commentLength = view.getUint16(offset + 32, true); + const name = decoder.decode( + zip.subarray(offset + 46, offset + 46 + nameLength), + ); + attrs.set(name, view.getUint32(offset + 38, true)); + offset += 46 + nameLength + extraLength + commentLength; + } + return attrs; +} + +describe("toPep440Version", () => { + test.each([ + ["4.0.0", "4.0.0"], + ["4.0.0-rc.1", "4.0.0rc1"], + ["4.1.0-alpha.0", "4.1.0a0"], + ["4.1.0-beta.2", "4.1.0b2"], + ["4.1.0-dev.1764150000", "4.1.0.dev1764150000"], + ])("%s → %s", (version, expected) => { + expect(toPep440Version(version)).toBe(expected); + }); + + test("rejects versions it cannot convert", () => { + expect(() => toPep440Version("4.0.0-preview")).toThrow(/PEP 440/); + }); +}); + +describe("buildWheel", () => { + test("names the wheel after the sentry-cli distribution and platform", () => { + expect(build("linux-x64").filename).toBe( + "sentry_cli-4.0.0-py3-none-manylinux_2_28_x86_64.whl", + ); + expect(build("darwin-arm64", "4.1.0-rc.1").filename).toBe( + "sentry_cli-4.1.0rc1-py3-none-macosx_13_0_arm64.whl", + ); + }); + + test("has a wheel for every standalone binary", () => { + expect(Object.keys(WHEEL_TARGETS).sort()).toEqual([ + "darwin-arm64", + "darwin-x64", + "linux-arm64", + "linux-x64", + "windows-x64", + ]); + }); + + test("installs the binary as the sentry command", () => { + const files = unzipSync(build("linux-x64").contents); + expect(Object.keys(files).sort()).toEqual([ + "sentry_cli-4.0.0.data/scripts/sentry", + "sentry_cli-4.0.0.dist-info/LICENSE.md", + "sentry_cli-4.0.0.dist-info/METADATA", + "sentry_cli-4.0.0.dist-info/RECORD", + "sentry_cli-4.0.0.dist-info/WHEEL", + ]); + expect(files["sentry_cli-4.0.0.data/scripts/sentry"]).toEqual(binary); + + const windows = unzipSync(build("windows-x64").contents); + expect(windows["sentry_cli-4.0.0.data/scripts/sentry.exe"]).toEqual(binary); + }); + + test("marks only the command executable", () => { + const attrs = externalAttrs(build("linux-x64").contents); + expect(attrs.get("sentry_cli-4.0.0.data/scripts/sentry")).toBe( + 0o100_755 * 0x1_00_00, + ); + expect(attrs.get("sentry_cli-4.0.0.dist-info/METADATA")).toBe( + 0o100_644 * 0x1_00_00, + ); + }); + + test("writes platform-specific WHEEL and METADATA", () => { + const files = unzipSync(build("linux-arm64").contents); + const wheel = decoder.decode(files["sentry_cli-4.0.0.dist-info/WHEEL"]); + expect(wheel).toContain("Root-Is-Purelib: false\n"); + expect(wheel).toContain("Tag: py3-none-manylinux_2_28_aarch64\n"); + + const metadata = decoder.decode( + files["sentry_cli-4.0.0.dist-info/METADATA"], + ); + expect(metadata).toMatch(/^Metadata-Version: 2\.1\nName: sentry-cli\n/); + expect(metadata).toContain("Version: 4.0.0\n"); + expect(metadata.endsWith("\n\n# sentry-cli\n")).toBe(true); + }); + + test("records the hash and size of every other file", () => { + const files = unzipSync(build("darwin-x64").contents); + const record = decoder + .decode(files["sentry_cli-4.0.0.dist-info/RECORD"]) + .trimEnd() + .split("\n"); + expect(record.at(-1)).toBe("sentry_cli-4.0.0.dist-info/RECORD,,"); + for (const line of record.slice(0, -1)) { + const [path, hash, size] = line.split(","); + const data = files[path as string] as Uint8Array; + const digest = createHash("sha256").update(data).digest("base64url"); + expect(hash).toBe(`sha256=${digest}`); + expect(Number(size)).toBe(data.byteLength); + } + expect(record).toHaveLength(Object.keys(files).length); + }); + + test("rejects unknown targets", () => { + expect(() => build("linux-riscv64")).toThrow(/No wheel platform/); + }); +});