diff --git a/.changeset/json-implies-unattended.md b/.changeset/json-implies-unattended.md new file mode 100644 index 0000000000..d8f7e58556 --- /dev/null +++ b/.changeset/json-implies-unattended.md @@ -0,0 +1,5 @@ +--- +"@sanity/cli-core": minor +--- + +feat(cli): treat `--json` as unattended mode, so a command emitting machine-readable output never stops at a prompt a caller can't answer diff --git a/packages/@sanity/cli-core/src/SanityCommand.ts b/packages/@sanity/cli-core/src/SanityCommand.ts index 70a24ec2f0..a3d9e81bce 100644 --- a/packages/@sanity/cli-core/src/SanityCommand.ts +++ b/packages/@sanity/cli-core/src/SanityCommand.ts @@ -240,10 +240,11 @@ export abstract class SanityCommand * * Most commands should take an explicit `--yes` flag to enable unattended mode, but * some commands may also be run in unattended mode if `process.stdin` is not a TTY - * (eg when running in a CI environment). + * (eg when running in a CI environment), or when `--json` asks for machine-readable + * output (a caller parsing JSON can't answer a prompt). */ public isUnattended(): boolean { - return this.flags.yes || !this.resolveIsInteractive() + return this.flags.yes || this.flags.json || !this.resolveIsInteractive() } /** diff --git a/packages/@sanity/cli/src/commands/tokens/__tests__/add.test.ts b/packages/@sanity/cli/src/commands/tokens/__tests__/add.test.ts index ab7d9328c6..70df43362d 100644 --- a/packages/@sanity/cli/src/commands/tokens/__tests__/add.test.ts +++ b/packages/@sanity/cli/src/commands/tokens/__tests__/add.test.ts @@ -152,18 +152,6 @@ describe('#tokens:add', () => { }) test('outputs JSON when --json flag is used', async () => { - const mockRoles = [ - { - appliesToRobots: true, - appliesToUsers: true, - description: 'Can read documents', - isCustom: false, - name: 'viewer', - projectId: 'test-project', - title: 'Viewer', - }, - ] - const mockToken = { id: 'token-json', key: 'sk_test_json1234', @@ -177,11 +165,7 @@ describe('#tokens:add', () => { ], } - mockApi({ - apiVersion: TOKENS_API_VERSION, - uri: '/projects/test-project/roles', - }).reply(200, mockRoles) - + // --json is unattended, so the role defaults to viewer without a roles prompt mockApi({ apiVersion: TOKENS_API_VERSION, method: 'post', @@ -194,6 +178,8 @@ describe('#tokens:add', () => { const parsedOutput = JSON.parse(stdout) expect(parsedOutput).toEqual(mockToken) + expect(mockedSelect).not.toHaveBeenCalled() + expect(mockedInput).not.toHaveBeenCalled() }) test('works in unattended mode with --yes flag', async () => { @@ -223,6 +209,8 @@ describe('#tokens:add', () => { expect(stdout).toContain('Token created successfully!') expect(stdout).toContain('Label: Unattended Token') + expect(mockedSelect).not.toHaveBeenCalled() + expect(mockedInput).not.toHaveBeenCalled() }) test('handles invalid role error', async () => {