diff --git a/apps/cli-docs/src/fragments/commands/wizard.md b/apps/cli-docs/src/fragments/commands/wizard.md index 91218e991..5412b86ff 100644 --- a/apps/cli-docs/src/fragments/commands/wizard.md +++ b/apps/cli-docs/src/fragments/commands/wizard.md @@ -17,6 +17,10 @@ takes an optional `/` first, then an optional integration: like an integration, write `my-org/nextjs`. - `-f`/`--force` changes a project with uncommitted changes without asking, and installs the SDK even when the package manager's checks fail. +- For `appleSnapshots`, `--app-target` and `--hosted-test-target` name the + Xcode app target and hosted XCTest target to use instead of picking them. + Without a terminal, the wizard uses the only target or stops with the list, + so pass these when the project has several. It logs in with your `sentry auth login` account, or starts a login when you have none, on the Sentry instance the rest of the CLI uses: `SENTRY_URL`, or @@ -35,7 +39,7 @@ changes nothing. ## Coming from `@sentry/wizard` `sentry wizard` takes the same integration ids as `npx @sentry/wizard -i`, -but not its flags or `SENTRY_WIZARD_*` environment variables: +but not most of its flags or its `SENTRY_WIZARD_*` environment variables: | `@sentry/wizard` | `sentry wizard` | | -------------------------------------- | ------------------------------------------------ | @@ -46,6 +50,9 @@ but not its flags or `SENTRY_WIZARD_*` environment variables: | `--force-install`, `--ignore-git-changes` | `-f`/`--force` | | `--disable-telemetry` | `SENTRY_CLI_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` | | `--debug` | `--verbose` or `--log-level debug` | +| `--app-target`, `--hosted-test-target` | The same flags | +| `--non-interactive` | Automatic when stdin is not a terminal | +| `--xcode-project-dir` | Run the wizard in that directory | | `--signup`, `--promo-code`, `--coming-from` | Sign up at https://sentry.io/signup/ first | The Cordova and Electron wizards were retired. Follow their setup guides in diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md index fe5382422..8a6a10225 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/wizard.md @@ -23,6 +23,8 @@ Set up the Sentry SDK in your project interactively **Flags:** - `-f, --force - Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail` +- `--app-target - Xcode app target that SnapshotPreviews uses, instead of picking one (appleSnapshots only)` +- `--hosted-test-target - Hosted XCTest target that renders the snapshots, instead of picking one (appleSnapshots only)` **Examples:** diff --git a/packages/cli/src/commands/wizard.ts b/packages/cli/src/commands/wizard.ts index 01311bd7a..45b48e34e 100644 --- a/packages/cli/src/commands/wizard.ts +++ b/packages/cli/src/commands/wizard.ts @@ -17,7 +17,7 @@ import { parseOrgProjectInput, } from "../lib/arg-parsing.js"; import { buildCommand } from "../lib/command.js"; -import { ORG_PROJECT_TARGET } from "../lib/completion-target.js"; +import { ORG_PROJECT_TARGET, parseText } from "../lib/completion-target.js"; import { getEnv } from "../lib/env.js"; import { ValidationError, WizardExitError } from "../lib/errors.js"; import { parseBoolValue } from "../lib/parse-bool.js"; @@ -39,6 +39,8 @@ const usageHint = () => sentry`wizard ${USAGE}`; type WizardFlags = { readonly force: boolean; + readonly "app-target"?: string; + readonly "hosted-test-target"?: string; }; /** Parsed `sentry wizard` arguments. */ @@ -208,6 +210,20 @@ export const wizardCommand = buildCommand({ "Change a project with uncommitted changes without asking, and install the SDK even when the package manager's checks fail", default: false, }, + "app-target": { + kind: "parsed", + parse: parseText, + optional: true, + brief: + "Xcode app target that SnapshotPreviews uses, instead of picking one (appleSnapshots only)", + }, + "hosted-test-target": { + kind: "parsed", + parse: parseText, + optional: true, + brief: + "Hosted XCTest target that renders the snapshots, instead of picking one (appleSnapshots only)", + }, }, aliases: { f: "force" }, }, @@ -224,6 +240,10 @@ export const wizardCommand = buildCommand({ ignoreGitChanges: flags.force, spotlight: isSpotlightEnabled(), }, + appleSnapshotsTargets: { + appTarget: flags["app-target"], + hostedTestTarget: flags["hosted-test-target"], + }, }); } catch (error) { if (!(error instanceof WizardExitError)) { diff --git a/packages/cli/src/lib/wizard/apple/options.ts b/packages/cli/src/lib/wizard/apple/options.ts index e5df01eee..115a57283 100644 --- a/packages/cli/src/lib/wizard/apple/options.ts +++ b/packages/cli/src/lib/wizard/apple/options.ts @@ -12,4 +12,8 @@ export interface AppleWizardOptions extends WizardOptions { export interface AppleSnapshotsWizardOptions extends AppleWizardOptions { /** Fail with the choices instead of prompting, such as when stdin is not a terminal. */ nonInteractive: boolean; + /** App target to use instead of picking one (`--app-target`). */ + appTarget?: string | undefined; + /** Hosted XCTest target to use instead of picking one (`--hosted-test-target`). */ + hostedTestTarget?: string | undefined; } diff --git a/packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts b/packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts index 0fd2d14c8..0b08871e5 100644 --- a/packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts +++ b/packages/cli/src/lib/wizard/apple/snapshots/apple-snapshots-wizard.ts @@ -187,6 +187,19 @@ async function resolveAppTargetName( options: AppleSnapshotsWizardOptions, ): Promise { const appTargetNames = xcodeProject.getAllTargets(); + if (options.appTarget) { + if (appTargetNames.includes(options.appTarget)) { + return options.appTarget; + } + + clack.log.error( + `Xcode app target ${ + options.appTarget + } was not found. Available app targets: ${formatList(appTargetNames)}.`, + ); + return undefined; + } + if (appTargetNames.length === 0) { clack.log.error("No application target found."); return undefined; @@ -197,7 +210,7 @@ async function resolveAppTargetName( [ "Could not automatically select an Xcode app target in non-interactive mode.", `Available app targets: ${formatList(appTargetNames)}.`, - "Run the wizard in a terminal to choose the app target that SnapshotPreviews should use.", + "Pass --app-target to select the app target that SnapshotPreviews should use.", ].join(" "), ); return undefined; @@ -216,6 +229,22 @@ async function resolveHostedTestTargetName( options: AppleSnapshotsWizardOptions, ): Promise { const hostedTestTargetNames = xcodeProject.getHostedUnitTestTargetNames(); + if (options.hostedTestTarget) { + if (hostedTestTargetNames.includes(options.hostedTestTarget)) { + return options.hostedTestTarget; + } + + clack.log.error( + [ + `Hosted XCTest target ${options.hostedTestTarget} was not found or does not define TEST_HOST.`, + `Available hosted XCTest targets: ${formatList( + hostedTestTargetNames, + )}.`, + ].join(" "), + ); + return undefined; + } + const inferredHostedTestTargetNames = xcodeProject.getHostedUnitTestTargetNamesForApplicationTarget( appTargetName, @@ -276,7 +305,7 @@ async function selectHostedTestTargetName({ `Available hosted XCTest targets: ${formatList( hostedTestTargetNames, )}.`, - "Run the wizard in a terminal to choose the target.", + "Pass --hosted-test-target to select the target explicitly.", manualAppleSnapshotsSetupInstructions({ appTargetName, hostedTestTargetName: hostedTestTargetNames[0], diff --git a/packages/cli/src/lib/wizard/run.ts b/packages/cli/src/lib/wizard/run.ts index 7adbdd846..77fa34ee8 100644 --- a/packages/cli/src/lib/wizard/run.ts +++ b/packages/cli/src/lib/wizard/run.ts @@ -8,6 +8,7 @@ import { isatty } from "node:tty"; import { ValidationError } from "../errors.js"; +import type { AppleSnapshotsWizardOptions } from "./apple/options.js"; import { abortIfCancelled } from "./utils/clack/index.js"; import { clack } from "./utils/clack/prompts.js"; import type { WizardOptions } from "./utils/types.js"; @@ -44,8 +45,17 @@ export type WizardIntegration = (typeof WIZARD_INTEGRATIONS)[number]["id"]; export const INTEGRATION_IDS: readonly WizardIntegration[] = WIZARD_INTEGRATIONS.map((integration) => integration.id); +/** `--app-target` and `--hosted-test-target`, which only Apple Snapshots reads. */ +type AppleSnapshotsTargets = Pick< + AppleSnapshotsWizardOptions, + "appTarget" | "hostedTestTarget" +>; + /** Runs the wizard of one integration. */ -type WizardRunner = (options: WizardOptions) => Promise; +type WizardRunner = ( + options: WizardOptions, + appleSnapshotsTargets: AppleSnapshotsTargets, +) => Promise; /** * The flow of each integration. Integrations without one are still being @@ -60,12 +70,16 @@ const WIZARD_RUNNERS: Partial> = { const { runAppleWizard } = await import("./apple/apple-wizard.js"); await runAppleWizard(options); }, - appleSnapshots: async (options) => { + appleSnapshots: async (options, appleSnapshotsTargets) => { const { runAppleSnapshotsWizard } = await import("./apple/snapshots/apple-snapshots-wizard.js"); // Without a terminal to prompt on, pick the only target or fail with // the choices, as the CLI does for auto-login (`isatty(0)`). - await runAppleSnapshotsWizard({ ...options, nonInteractive: !isatty(0) }); + await runAppleSnapshotsWizard({ + ...options, + ...appleSnapshotsTargets, + nonInteractive: !isatty(0), + }); }, reactNative: async (options) => { const { runReactNativeWizard } = @@ -80,6 +94,8 @@ export type RunWizardArgs = { integration?: WizardIntegration | undefined; /** The options every wizard flow takes. */ wizardOptions: WizardOptions; + /** The Xcode targets Apple Snapshots uses instead of picking them. */ + appleSnapshotsTargets?: AppleSnapshotsTargets | undefined; }; /** @@ -99,7 +115,7 @@ export async function runWizard(args: RunWizardArgs): Promise { "integration", ); } - await runner(args.wizardOptions); + await runner(args.wizardOptions, args.appleSnapshotsTargets ?? {}); } /** Ask which integration to set up, out of the ones that have a flow. */ diff --git a/packages/cli/test/commands/wizard.test.ts b/packages/cli/test/commands/wizard.test.ts index 3705740bb..5a8de8d1f 100644 --- a/packages/cli/test/commands/wizard.test.ts +++ b/packages/cli/test/commands/wizard.test.ts @@ -1,18 +1,24 @@ /** * Tests for `sentry wizard`: its command line (`[/] - * []` and `--force`, nothing else), what it passes to a wizard - * flow, and how a stopped wizard sets the exit code. + * []`, `--force`, and the Apple Snapshots target flags), what it + * passes to a wizard flow, and how a stopped wizard sets the exit code. */ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; -const { runNextjsWizard, isTelemetryEnabled } = vi.hoisted(() => ({ - runNextjsWizard: vi.fn<(options: unknown) => Promise>(), - isTelemetryEnabled: vi.fn<() => boolean>(), -})); +const { runNextjsWizard, runAppleSnapshotsWizard, isTelemetryEnabled } = + vi.hoisted(() => ({ + runNextjsWizard: vi.fn<(options: unknown) => Promise>(), + runAppleSnapshotsWizard: vi.fn<(options: unknown) => Promise>(), + isTelemetryEnabled: vi.fn<() => boolean>(), + })); vi.mock("../../src/lib/wizard/nextjs/nextjs-wizard.js", () => ({ runNextjsWizard, })); +vi.mock( + "../../src/lib/wizard/apple/snapshots/apple-snapshots-wizard.js", + () => ({ runAppleSnapshotsWizard }), +); vi.mock("../../src/lib/telemetry.js", async (importOriginal) => ({ ...(await importOriginal()), isTelemetryEnabled, @@ -80,7 +86,7 @@ describe("sentry wizard flags", () => { }, }).parameters; - test("--force (-f) is the wizard's only flag, and it is not hidden", () => { + test("the wizard's flags are --force (-f) and the Apple Snapshots targets, none hidden", () => { const { flags = {}, aliases = {} } = wizardCommand.parameters as { flags?: Record; aliases?: Record; @@ -92,8 +98,10 @@ describe("sentry wizard flags", () => { ([alias]) => !(alias in (injected.aliases ?? {})), ); - expect(ownFlags).toEqual(["force"]); - expect(flags["force"]?.hidden).toBeUndefined(); + expect(ownFlags).toEqual(["force", "app-target", "hosted-test-target"]); + for (const name of ownFlags) { + expect(flags[name]?.hidden).toBeUndefined(); + } expect(Object.fromEntries(ownAliases)).toEqual({ f: "force" }); }); }); @@ -206,6 +214,22 @@ describe("sentry wizard", () => { }); }); + test("--app-target and --hosted-test-target reach the Apple Snapshots flow", async () => { + runAppleSnapshotsWizard.mockResolvedValue(undefined); + + await runWizardCommand( + { "app-target": "App", "hosted-test-target": "AppTests" }, + "appleSnapshots", + ); + + expect(runAppleSnapshotsWizard).toHaveBeenCalledWith( + expect.objectContaining({ + appTarget: "App", + hostedTestTarget: "AppTests", + }), + ); + }); + test("--force both force-installs and skips the uncommitted changes prompt", async () => { await runWizardCommand({ force: true }, "nextjs"); diff --git a/packages/cli/test/lib/wizard/apple/snapshots/apple-snapshots-wizard.test.ts b/packages/cli/test/lib/wizard/apple/snapshots/apple-snapshots-wizard.test.ts index b7a427e3b..a7b748ea5 100644 --- a/packages/cli/test/lib/wizard/apple/snapshots/apple-snapshots-wizard.test.ts +++ b/packages/cli/test/lib/wizard/apple/snapshots/apple-snapshots-wizard.test.ts @@ -429,6 +429,95 @@ describe("runAppleSnapshotsWizard", () => { }); }); + it("uses --app-target and --hosted-test-target without prompting among several targets when non-interactive", async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "snapshots-wizard-")); + const xcodeProject = { + getBundleIdentifierForTarget: vi.fn(() => "com.getsentry.App"), + getAllTargets: vi.fn(() => ["App", "OtherApp"]), + getHostedUnitTestTargetNames: vi.fn(() => [ + "AppTests", + "AppSnapshotTests", + ]), + getHostedUnitTestTargetNamesForApplicationTarget: vi.fn(() => [ + "AppTests", + "AppSnapshotTests", + ]), + write: mocks.write, + xcodeprojPath: path.join(tempDir, "App.xcodeproj"), + }; + mocks.lookupXcodeProject.mockResolvedValue(xcodeProject); + + await runAppleSnapshotsWizard({ + telemetryEnabled: true, + projectDir: tempDir, + ignoreGitChanges: true, + nonInteractive: true, + appTarget: "OtherApp", + hostedTestTarget: "AppSnapshotTests", + }); + + expect(mocks.askForItemSelection).not.toHaveBeenCalled(); + expect(mocks.error).not.toHaveBeenCalled(); + expect(mocks.configureSnapshotPreviewsXcodeProject).toHaveBeenCalledWith({ + xcodeProject, + hostedTestTargetName: "AppSnapshotTests", + previewTargetNames: ["OtherApp"], + }); + }); + + it("aborts with the app targets when --app-target names an unknown target", async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "snapshots-wizard-")); + const xcodeProject = { + getAllTargets: vi.fn(() => ["App", "OtherApp"]), + xcodeprojPath: path.join(tempDir, "App.xcodeproj"), + }; + mocks.lookupXcodeProject.mockResolvedValue(xcodeProject); + + await expect( + runAppleSnapshotsWizard({ + telemetryEnabled: true, + projectDir: tempDir, + ignoreGitChanges: true, + nonInteractive: false, + appTarget: "Missing", + }), + ).rejects.toThrow("aborted"); + + expect(mocks.askForItemSelection).not.toHaveBeenCalled(); + expect(mocks.error).toHaveBeenCalledWith( + "Xcode app target Missing was not found. Available app targets: App, OtherApp.", + ); + expect(mocks.configureSnapshotPreviewsXcodeProject).not.toHaveBeenCalled(); + }); + + it("aborts with the hosted XCTest targets when --hosted-test-target names an unknown target", async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "snapshots-wizard-")); + const xcodeProject = { + getAllTargets: vi.fn(() => ["App"]), + getHostedUnitTestTargetNames: vi.fn(() => ["AppTests"]), + getHostedUnitTestTargetNamesForApplicationTarget: vi.fn(() => [ + "AppTests", + ]), + xcodeprojPath: path.join(tempDir, "App.xcodeproj"), + }; + mocks.lookupXcodeProject.mockResolvedValue(xcodeProject); + + await expect( + runAppleSnapshotsWizard({ + telemetryEnabled: true, + projectDir: tempDir, + ignoreGitChanges: true, + nonInteractive: true, + hostedTestTarget: "Missing", + }), + ).rejects.toThrow("aborted"); + + expect(mocks.error).toHaveBeenCalledWith( + "Hosted XCTest target Missing was not found or does not define TEST_HOST. Available hosted XCTest targets: AppTests.", + ); + expect(mocks.configureSnapshotPreviewsXcodeProject).not.toHaveBeenCalled(); + }); + it("aborts when app target selection is ambiguous in non-interactive mode", async () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "snapshots-wizard-")); const xcodeProject = { @@ -449,7 +538,7 @@ describe("runAppleSnapshotsWizard", () => { expect(mocks.askForItemSelection).not.toHaveBeenCalled(); expect(mocks.error).toHaveBeenCalledWith( expect.stringContaining( - "Run the wizard in a terminal to choose the app target", + "Pass --app-target to select the app target", ), ); expect(mocks.configureSnapshotPreviewsXcodeProject).not.toHaveBeenCalled(); @@ -486,7 +575,7 @@ describe("runAppleSnapshotsWizard", () => { expect(mocks.askForItemSelection).not.toHaveBeenCalled(); expect(mocks.error).toHaveBeenCalledWith( expect.stringContaining( - "Run the wizard in a terminal to choose the target", + "Pass --hosted-test-target to select the target", ), ); expect(mocks.error).toHaveBeenCalledWith( diff --git a/packages/wizard/README.md b/packages/wizard/README.md index a81156d8b..28a56e3bc 100644 --- a/packages/wizard/README.md +++ b/packages/wizard/README.md @@ -28,6 +28,7 @@ the old flags translated: - `--force-install`, `--ignore-git-changes`, `-f` and `--force` become `-f`. - `-u`/`--url ` sets `SENTRY_URL` for the run. - `--spotlight` sets `SENTRY_SPOTLIGHT=1` for the run. +- `--app-target ` and `--hosted-test-target ` pass through. - Positional arguments and `--help` pass through. Every other old flag is ignored with a notice, including `--project` without diff --git a/packages/wizard/bin/sentry-wizard.js b/packages/wizard/bin/sentry-wizard.js index de18ecca5..10a8633c6 100755 --- a/packages/wizard/bin/sentry-wizard.js +++ b/packages/wizard/bin/sentry-wizard.js @@ -54,6 +54,9 @@ function findSentryBin() { } } +/** Old flags that `sentry wizard` takes unchanged, with their value. */ +const PASSED_THROUGH = ["app-target", "hosted-test-target"]; + /** Old flags with a `sentry wizard` equivalent, by name. */ const TRANSLATED = new Map([ ["i", "integration"], @@ -62,6 +65,7 @@ const TRANSLATED = new Map([ ["url", "url"], ["org", "org"], ["project", "project"], + ...PASSED_THROUGH.map((name) => /** @type {const} */ ([name, name])), ]); /** Flags that become `-f`, including `-f` itself. */ @@ -73,23 +77,17 @@ const FORCE_FLAGS = new Set([ ]); /** Old flags without an equivalent that take a value, which is dropped too. */ -const VALUE_FLAGS = new Set([ - "promo-code", - "coming-from", - "xcode-project-dir", - "app-target", - "hosted-test-target", -]); +const VALUE_FLAGS = new Set(["promo-code", "coming-from", "xcode-project-dir"]); /** Old flags that take every value up to the next flag. */ const ARRAY_FLAGS = new Set(["p", "platform"]); /** * Translate `@sentry/wizard` arguments to `sentry wizard [/] - * [] [-f]`, plus the CLI's environment variables for `--url` and - * `--spotlight`. Other arguments, such as a target or integration already - * written as positionals, pass through. Values are never printed: some old - * flags carried tokens. + * [] [--app-target ] [--hosted-test-target ] [-f]`, + * plus the CLI's environment variables for `--url` and `--spotlight`. Other + * arguments, such as a target or integration already written as positionals, + * pass through. Values are never printed: some old flags carried tokens. * * @param {readonly string[]} args * @returns {{ args: string[], env: Record, notices: string[] }} @@ -161,11 +159,16 @@ function translateArgs(args) { } const integration = values.get("integration"); const url = values.get("url"); + const passedThrough = PASSED_THROUGH.flatMap((name) => { + const value = values.get(name); + return value === undefined ? [] : [`--${name}`, value]; + }); return { args: [ ...(org === undefined ? [] : [`${org}/${project ?? ""}`]), ...positionals, ...(integration === undefined ? [] : [integration]), + ...passedThrough, ...(force ? ["-f"] : []), ...(help ? ["--help"] : []), ], diff --git a/packages/wizard/test/sentry-wizard.test.ts b/packages/wizard/test/sentry-wizard.test.ts index e0bebf746..2876dae2f 100644 --- a/packages/wizard/test/sentry-wizard.test.ts +++ b/packages/wizard/test/sentry-wizard.test.ts @@ -201,6 +201,41 @@ describe("sentry-wizard", () => { }); }); + test("passes --app-target and --hosted-test-target on with their values", async () => { + const result = run(bin, [ + "--app-target", + "App", + "-i", + "appleSnapshots", + "--hosted-test-target=AppTests", + ]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(result.stderr()).toBe(NOTICE); + expect(JSON.parse(result.stdout())).toEqual({ + args: [ + "wizard", + "appleSnapshots", + "--app-target", + "App", + "--hosted-test-target", + "AppTests", + ], + }); + }); + + test("drops --app-target without a value, with a notice", async () => { + const result = run(bin, ["-i", "appleSnapshots", "--app-target"]); + + expect(await result.done).toEqual({ code: 0, signal: null }); + expect(result.stderr()).toBe( + NOTICE + "Ignoring --app-target: it needs a value.\n", + ); + expect(JSON.parse(result.stdout())).toEqual({ + args: ["wizard", "appleSnapshots"], + }); + }); + test("drops other old flags and their values, with a notice for each", async () => { const result = run(bin, [ "--project",