diff --git a/docs-shopify.dev/generated/generated_docs_data_v2.json b/docs-shopify.dev/generated/generated_docs_data_v2.json index e1d654746ff..bce530df779 100644 --- a/docs-shopify.dev/generated/generated_docs_data_v2.json +++ b/docs-shopify.dev/generated/generated_docs_data_v2.json @@ -5149,9 +5149,45 @@ "description": "Print the command's JSON schemas.", "isOptional": true, "environmentValue": "SHOPIFY_FLAG_JSON_SCHEMA" + }, + { + "filePath": "docs-shopify.dev/commands/interfaces/config-autocorrect-status.interface.ts", + "syntaxKind": "PropertySignature", + "name": "--no-color", + "value": "''", + "description": "Disable color output.", + "isOptional": true, + "environmentValue": "SHOPIFY_FLAG_NO_COLOR" + }, + { + "filePath": "docs-shopify.dev/commands/interfaces/config-autocorrect-status.interface.ts", + "syntaxKind": "PropertySignature", + "name": "--no-input", + "value": "''", + "description": "Disable interactive prompts and browser authentication.", + "isOptional": true, + "environmentValue": "SHOPIFY_FLAG_NO_INPUT" + }, + { + "filePath": "docs-shopify.dev/commands/interfaces/config-autocorrect-status.interface.ts", + "syntaxKind": "PropertySignature", + "name": "--verbose", + "value": "''", + "description": "Increase the verbosity of the output. May include sensitive data.", + "isOptional": true, + "environmentValue": "SHOPIFY_FLAG_VERBOSE" + }, + { + "filePath": "docs-shopify.dev/commands/interfaces/config-autocorrect-status.interface.ts", + "syntaxKind": "PropertySignature", + "name": "-j, --json", + "value": "''", + "description": "Output the result as JSON. Automatically disables color output.", + "isOptional": true, + "environmentValue": "SHOPIFY_FLAG_JSON" } ], - "value": "export interface configautocorrectstatus {\n /**\n * Print the command's JSON schemas.\n * @environment SHOPIFY_FLAG_JSON_SCHEMA\n */\n '--json-schema'?: ''\n}" + "value": "export interface configautocorrectstatus {\n /**\n * Output the result as JSON. Automatically disables color output.\n * @environment SHOPIFY_FLAG_JSON\n */\n '-j, --json'?: ''\n\n /**\n * Print the command's JSON schemas.\n * @environment SHOPIFY_FLAG_JSON_SCHEMA\n */\n '--json-schema'?: ''\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Disable interactive prompts and browser authentication.\n * @environment SHOPIFY_FLAG_NO_INPUT\n */\n '--no-input'?: ''\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" } }, "configautoupgradeoff": { diff --git a/packages/cli/README.md b/packages/cli/README.md index b8940a5213b..047712bdf75 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -8110,13 +8110,29 @@ Check whether autocorrect is enabled or disabled. On by default. ``` USAGE - $ shopify config autocorrect status [--json-schema] + $ shopify config autocorrect status [-j] [--json-schema] [--no-color] [--no-input] [--verbose] FLAGS + -j, --json + Output the result as JSON. Automatically disables color output. + [env: SHOPIFY_FLAG_JSON] + --json-schema Print the command's JSON schemas. [env: SHOPIFY_FLAG_JSON_SCHEMA] + --no-color + Disable color output. + [env: SHOPIFY_FLAG_NO_COLOR] + + --no-input + Disable interactive prompts and browser authentication. + [env: SHOPIFY_FLAG_NO_INPUT] + + --verbose + Increase the verbosity of the output. May include sensitive data. + [env: SHOPIFY_FLAG_VERBOSE] + DESCRIPTION Check whether autocorrect is enabled or disabled. On by default. @@ -8126,6 +8142,28 @@ DESCRIPTION available. When autocorrection is disabled, you need to confirm that you want to run corrections for mistyped commands. + + + Use `--json-schema` to print the result, error, and event schemas. + + Output from `--json` conforms to the `AutocorrectResult` schema. + + ```json + { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + } + }, + "required": [ + "enabled" + ], + "additionalProperties": false, + "title": "AutocorrectResult", + "$schema": "http://json-schema.org/draft-07/schema#" + } + ``` ``` ## `shopify config autoupgrade off` diff --git a/packages/cli/oclif.manifest.json b/packages/cli/oclif.manifest.json index 5f8f925405d..b16eb97bf09 100644 --- a/packages/cli/oclif.manifest.json +++ b/packages/cli/oclif.manifest.json @@ -6060,16 +6060,48 @@ "args": { }, "customPluginName": "@shopify/plugin-did-you-mean", - "description": "Check whether autocorrect is enabled or disabled. On by default.\n\n When autocorrection is enabled, Shopify CLI automatically runs a corrected version of your command if a correction is available.\n\n When autocorrection is disabled, you need to confirm that you want to run corrections for mistyped commands.\n", + "description": "Check whether autocorrect is enabled or disabled. On by default.\n\n When autocorrection is enabled, Shopify CLI automatically runs a corrected version of your command if a correction is available.\n\n When autocorrection is disabled, you need to confirm that you want to run corrections for mistyped commands.\n\n\nUse `--json-schema` to print the result, error, and event schemas.\n\nOutput from `--json` conforms to the `AutocorrectResult` schema.\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"enabled\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"enabled\"\n ],\n \"additionalProperties\": false,\n \"title\": \"AutocorrectResult\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n}\n```", "descriptionWithMarkdown": "Check whether autocorrect is enabled or disabled. On by default.\n\n When autocorrection is enabled, Shopify CLI automatically runs a corrected version of your command if a correction is available.\n\n When autocorrection is disabled, you need to confirm that you want to run corrections for mistyped commands.\n", "enableJsonFlag": false, "flags": { + "json": { + "allowNo": false, + "char": "j", + "description": "Output the result as JSON. Automatically disables color output.", + "env": "SHOPIFY_FLAG_JSON", + "hidden": false, + "name": "json", + "type": "boolean" + }, "json-schema": { "allowNo": false, "description": "Print the command's JSON schemas.", "env": "SHOPIFY_FLAG_JSON_SCHEMA", "name": "json-schema", "type": "boolean" + }, + "no-color": { + "allowNo": false, + "description": "Disable color output.", + "env": "SHOPIFY_FLAG_NO_COLOR", + "hidden": false, + "name": "no-color", + "type": "boolean" + }, + "no-input": { + "allowNo": false, + "description": "Disable interactive prompts and browser authentication.", + "env": "SHOPIFY_FLAG_NO_INPUT", + "name": "no-input", + "type": "boolean" + }, + "verbose": { + "allowNo": false, + "description": "Increase the verbosity of the output. May include sensitive data.", + "env": "SHOPIFY_FLAG_VERBOSE", + "hidden": false, + "name": "verbose", + "type": "boolean" } }, "hasDynamicHelp": false, diff --git a/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js b/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js index 13b45e6fc77..70dda626d26 100644 --- a/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js +++ b/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js @@ -4,7 +4,6 @@ const commandExceptions = [ // Do not add new finite commands to this section. 'packages/plugin-did-you-mean/src/commands/config/autocorrect/off.ts', 'packages/plugin-did-you-mean/src/commands/config/autocorrect/on.ts', - 'packages/plugin-did-you-mean/src/commands/config/autocorrect/status.ts', // App Security commands, launched before adopting typed JSON output. Remove entries as they adopt it. 'packages/app/src/cli/commands/app/security/check.ts', diff --git a/packages/plugin-did-you-mean/src/commands/config/autocorrect/autocorrect.test.ts b/packages/plugin-did-you-mean/src/commands/config/autocorrect/autocorrect.test.ts new file mode 100644 index 00000000000..96252e03966 --- /dev/null +++ b/packages/plugin-did-you-mean/src/commands/config/autocorrect/autocorrect.test.ts @@ -0,0 +1,124 @@ +import AutocorrectStatus from './status.js' +import {isAutocorrectEnabled, setAutocorrect} from '../../../services/conf.js' +import {autocorrectJsonOutputSchema} from '../../../services/autocorrect/types.js' +import {launchCLI} from '@shopify/cli-kit/node/cli-launcher' +import {ShopifyConfig} from '@shopify/cli-kit/node/custom-oclif-loader' +import {AbortError} from '@shopify/cli-kit/node/error' +import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' +import {beforeEach, afterEach, expect, test, vi} from 'vitest' + +vi.mock('../../../services/conf.js') + +beforeEach(() => { + vi.stubEnv('CI', '1') + vi.stubEnv('SHOPIFY_CLI_NO_ANALYTICS', '1') + vi.spyOn(ShopifyConfig.prototype, 'runHook').mockResolvedValue({successes: [], failures: []}) +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +const commands = [{name: 'status', command: AutocorrectStatus, enabled: false}] + +test.each(commands)('$name exposes the result schema and JSON flags in help', ({command}) => { + expect(command.jsonOutputSchema).toBe(autocorrectJsonOutputSchema) + expect(command.flags.json.char).toBe('j') + expect(command.description).toContain('Output from `--json` conforms to the `AutocorrectResult` schema.') + expect(command.description).toContain('"enabled"') +}) + +test.each(commands)('$name writes one JSON document through the launcher', async ({name, command, enabled}) => { + vi.mocked(isAutocorrectEnabled).mockReturnValue(enabled) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await launchCLI({ + moduleURL: new URL('../../../../../cli/src/index.ts', import.meta.url).href, + argv: ['config', 'autocorrect', name, '--json'], + lazyCommandLoader: async () => command, + }) + + expect(stdout()).toBe(`${JSON.stringify({enabled}, null, 2)}\n`) + expect(stderr()).toBe('') + if (name === 'status') { + expect(setAutocorrect).not.toHaveBeenCalled() + } else { + expect(setAutocorrect).toHaveBeenCalledExactlyOnceWith(enabled) + } + }) +}) + +test.each(commands)('$name discovers its schema without accessing configuration', async ({name, command}) => { + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await launchCLI({ + moduleURL: new URL('../../../../../cli/src/index.ts', import.meta.url).href, + argv: ['config', 'autocorrect', name, '--json-schema'], + lazyCommandLoader: async () => command, + }) + + expect(JSON.parse(stdout()).definitions.Result).toMatchObject({ + type: 'object', + properties: {enabled: {type: 'boolean'}}, + required: ['enabled'], + additionalProperties: false, + }) + expect(stderr()).toBe('') + expect(setAutocorrect).not.toHaveBeenCalled() + expect(isAutocorrectEnabled).not.toHaveBeenCalled() + }) +}) + +test.each([ + {args: ['-j'], json: true}, + {args: ['--json', '--no-input'], json: true}, + {args: ['--no-input'], json: false}, +])('selects JSON independently from input policy for $args', async ({args, json}) => { + vi.mocked(isAutocorrectEnabled).mockReturnValue(true) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await AutocorrectStatus.run(args, import.meta.url) + + if (json) { + expect(JSON.parse(stdout())).toEqual({enabled: true}) + expect(stderr()).toBe('') + } else { + expect(stdout()).toBe('') + expect(stderr()).toContain('Autocorrect on.') + } + }) +}) + +test('selects JSON from SHOPIFY_FLAG_JSON', async () => { + vi.stubEnv('SHOPIFY_FLAG_JSON', '1') + vi.mocked(isAutocorrectEnabled).mockReturnValue(true) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await AutocorrectStatus.run([], import.meta.url) + + expect(JSON.parse(stdout())).toEqual({enabled: true}) + expect(stderr()).toBe('') + }) +}) + +test.each(commands)( + '$name emits a fatal error without a success result when configuration fails', + async ({command, name}) => { + vi.stubEnv('SHOPIFY_FLAG_JSON', '1') + const error = new AbortError('Cannot access autocorrect preference.') + const exit = vi.spyOn(process, 'exit').mockReturnValue(undefined as never) + const operation = name === 'status' ? isAutocorrectEnabled : setAutocorrect + vi.mocked(operation).mockImplementation(() => { + throw error + }) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await command.run(['--json'], import.meta.url) + + expect(JSON.parse(stdout())).toEqual({ + error: {type: 'abort', message: 'Cannot access autocorrect preference.'}, + }) + expect(stderr()).toBe('') + expect(exit).toHaveBeenCalledExactlyOnceWith(1) + }) + }, +) diff --git a/packages/plugin-did-you-mean/src/commands/config/autocorrect/status.test.ts b/packages/plugin-did-you-mean/src/commands/config/autocorrect/status.test.ts index 59e6ea86c45..ff7849931b0 100644 --- a/packages/plugin-did-you-mean/src/commands/config/autocorrect/status.test.ts +++ b/packages/plugin-did-you-mean/src/commands/config/autocorrect/status.test.ts @@ -1,20 +1,28 @@ import AutocorrectStatus from './status.js' import {isAutocorrectEnabled} from '../../../services/conf.js' -import {Config} from '@oclif/core' import {describe, expect, vi, test} from 'vitest' -import {mockAndCaptureOutput} from '@shopify/cli-kit/node/testing/output' +import {mockAndCaptureOutput, withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' vi.mock('../../../services/conf.js') describe('Autocorrect Status', () => { + test.each([true, false])('returns JSON when autocorrect is %s', async (enabled) => { + vi.mocked(isAutocorrectEnabled).mockReturnValue(enabled) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await AutocorrectStatus.run(['--json'], import.meta.url) + + expect(stdout()).toBe(`${JSON.stringify({enabled}, null, 2)}\n`) + expect(stderr()).toBe('') + }) + }) + test('Displays autocorrect off message if Autocorrect is off', async () => { // Given vi.mocked(isAutocorrectEnabled).mockReturnValue(false) - const config = new Config({root: __dirname}) const outputMock = mockAndCaptureOutput() outputMock.clear() // When - await new AutocorrectStatus([], config).run() + await AutocorrectStatus.run([], import.meta.url) // Then expect(outputMock.info()).toMatchInlineSnapshot(` @@ -30,11 +38,10 @@ describe('Autocorrect Status', () => { test('Displays autocorrect on message if Autocorrect is on', async () => { // Given vi.mocked(isAutocorrectEnabled).mockReturnValue(true) - const config = new Config({root: __dirname}) const outputMock = mockAndCaptureOutput() outputMock.clear() // When - await new AutocorrectStatus([], config).run() + await AutocorrectStatus.run([], import.meta.url) // Then expect(outputMock.info()).toMatchInlineSnapshot(` diff --git a/packages/plugin-did-you-mean/src/commands/config/autocorrect/status.ts b/packages/plugin-did-you-mean/src/commands/config/autocorrect/status.ts index 7816df38708..e263049ef31 100644 --- a/packages/plugin-did-you-mean/src/commands/config/autocorrect/status.ts +++ b/packages/plugin-did-you-mean/src/commands/config/autocorrect/status.ts @@ -1,7 +1,8 @@ -import {autocorrectStatus} from '../../../services/constants.js' -import {isAutocorrectEnabled} from '../../../services/conf.js' +import {getAutocorrectStatus} from '../../../services/autocorrect/index.js' +import {presentAutocorrectResult} from '../../../services/autocorrect/result.js' +import {autocorrectJsonOutputSchema} from '../../../services/autocorrect/types.js' import Command from '@shopify/cli-kit/node/base-command' -import {renderInfo} from '@shopify/cli-kit/node/ui' +import {globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli' export default class AutocorrectStatus extends Command { static summary = 'Check whether autocorrect is enabled or disabled. On by default.' @@ -15,11 +16,18 @@ export default class AutocorrectStatus extends Command { static description = this.descriptionForHelp() + static flags = { + ...globalFlags, + ...jsonFlag, + } + + static get jsonOutputSchema() { + return autocorrectJsonOutputSchema + } + async run(): Promise { - if (isAutocorrectEnabled()) { - renderInfo({body: autocorrectStatus.on}) - } else { - renderInfo({body: autocorrectStatus.off}) - } + const {flags} = await this.parse(AutocorrectStatus) + const result = getAutocorrectStatus() + presentAutocorrectResult(result, flags.json ? 'json' : 'text') } } diff --git a/packages/plugin-did-you-mean/src/services/autocorrect/index.test.ts b/packages/plugin-did-you-mean/src/services/autocorrect/index.test.ts new file mode 100644 index 00000000000..3b166579c4d --- /dev/null +++ b/packages/plugin-did-you-mean/src/services/autocorrect/index.test.ts @@ -0,0 +1,29 @@ +import {getAutocorrectStatus} from './index.js' +import * as conf from '../conf.js' +import {inTemporaryDirectory} from '@shopify/cli-kit/node/fs' +import {LocalStorage} from '@shopify/cli-kit/node/local-storage' +import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' +import {expect, test, vi} from 'vitest' + +test('returns the default and persisted preferences without changing configuration or printing output', async () => { + await inTemporaryDirectory(async (directory) => { + const storage = new LocalStorage({cwd: directory}) + const {isAutocorrectEnabled} = conf + vi.spyOn(conf, 'isAutocorrectEnabled').mockImplementation(() => isAutocorrectEnabled(storage)) + + await withCapturedStandardStreams(({stdout, stderr}) => { + expect(getAutocorrectStatus()).toEqual({enabled: false}) + expect(storage.get('autocorrectEnabled')).toBeUndefined() + + for (const enabled of [true, false]) { + storage.set('autocorrectEnabled', enabled) + expect(getAutocorrectStatus()).toEqual({enabled}) + const reloadedStorage = new LocalStorage({cwd: directory}) + expect(reloadedStorage.get('autocorrectEnabled')).toBe(enabled) + } + + expect(stdout()).toBe('') + expect(stderr()).toBe('') + }) + }) +}) diff --git a/packages/plugin-did-you-mean/src/services/autocorrect/index.ts b/packages/plugin-did-you-mean/src/services/autocorrect/index.ts new file mode 100644 index 00000000000..8905afb7a28 --- /dev/null +++ b/packages/plugin-did-you-mean/src/services/autocorrect/index.ts @@ -0,0 +1,6 @@ +import {isAutocorrectEnabled} from '../conf.js' +import type {AutocorrectResult} from './types.js' + +export function getAutocorrectStatus(): AutocorrectResult { + return {enabled: isAutocorrectEnabled()} +} diff --git a/packages/plugin-did-you-mean/src/services/autocorrect/result.test.ts b/packages/plugin-did-you-mean/src/services/autocorrect/result.test.ts new file mode 100644 index 00000000000..90c664acee2 --- /dev/null +++ b/packages/plugin-did-you-mean/src/services/autocorrect/result.test.ts @@ -0,0 +1,22 @@ +import {presentAutocorrectResult} from './result.js' +import {autocorrectJsonOutputSchema} from './types.js' +import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' +import {expect, test} from 'vitest' + +test.each([{}, {enabled: 'false'}, {enabled: null}, {enabled: false, message: 'disabled'}])( + 'rejects an invalid result %j', + (value) => { + expect(() => autocorrectJsonOutputSchema.validate(value)).toThrow() + }, +) + +test.each([true, false])('projects JSON output to the enabled preference %s', async (enabled) => { + const result = {enabled, internal: 'hidden'} + + await withCapturedStandardStreams(({stdout, stderr}) => { + presentAutocorrectResult(result, 'json') + + expect(stdout()).toBe(`${JSON.stringify({enabled}, null, 2)}\n`) + expect(stderr()).toBe('') + }) +}) diff --git a/packages/plugin-did-you-mean/src/services/autocorrect/result.ts b/packages/plugin-did-you-mean/src/services/autocorrect/result.ts new file mode 100644 index 00000000000..6a9b2468bd5 --- /dev/null +++ b/packages/plugin-did-you-mean/src/services/autocorrect/result.ts @@ -0,0 +1,13 @@ +import {autocorrectJsonOutputSchema, type AutocorrectResult} from './types.js' +import {autocorrectStatus} from '../constants.js' +import {outputResult} from '@shopify/cli-kit/node/output' +import {renderInfo} from '@shopify/cli-kit/node/ui' + +export function presentAutocorrectResult(result: AutocorrectResult, format: 'json' | 'text'): void { + if (format === 'json') { + outputResult(autocorrectJsonOutputSchema.encode({enabled: result.enabled})) + return + } + + renderInfo({body: result.enabled ? autocorrectStatus.on : autocorrectStatus.off}) +} diff --git a/packages/plugin-did-you-mean/src/services/autocorrect/types.ts b/packages/plugin-did-you-mean/src/services/autocorrect/types.ts new file mode 100644 index 00000000000..15a2ab67d03 --- /dev/null +++ b/packages/plugin-did-you-mean/src/services/autocorrect/types.ts @@ -0,0 +1,9 @@ +import {defineJsonOutputSchema, type InferJsonOutputSchema} from '@shopify/cli-kit/node/json-output-schema' +import {zod} from '@shopify/cli-kit/node/schema' + +export const autocorrectJsonOutputSchema = defineJsonOutputSchema({ + name: 'AutocorrectResult', + schema: zod.object({enabled: zod.boolean()}).strict(), +}) + +export type AutocorrectResult = InferJsonOutputSchema