Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/no-input.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@shopify/cli-kit': minor
'@shopify/cli': minor
---

Add a global `--no-input` flag to disable interactive prompts and browser authentication.
1,158 changes: 1,043 additions & 115 deletions docs-shopify.dev/generated/generated_docs_data_v2.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/app/src/cli/commands/organization/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {authAliasFlag, globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli'
import BaseCommand from '@shopify/cli-kit/node/base-command'

export default class OrganizationList extends BaseCommand {
static baseFlags = authAliasFlag
static baseFlags = {...BaseCommand.baseFlags, ...authAliasFlag}

static summary = 'List Shopify organizations you have access to.'

Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/cli/utilities/app-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface AppCommandOutput {
}

export default abstract class AppCommand extends BaseCommand {
static baseFlags = authAliasFlag
static baseFlags = {...BaseCommand.baseFlags, ...authAliasFlag}

environmentsFilename(): string {
return configurationFileNames.appEnvironments
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import {err, ok} from '../../../public/node/result.js'
import {AbortError} from '../../../public/node/error.js'
import {isCI, openURL} from '../../../public/node/system.js'
import * as output from '../../../public/node/output.js'
import {setInputDisabled} from '../../../public/node/global-context.js'

import {beforeEach, describe, expect, test, vi} from 'vitest'
import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest'
import {Response} from 'node-fetch'

vi.mock('../../../public/node/context/fqdn.js')
Expand All @@ -25,11 +26,14 @@ vi.mock('./exchange.js')
vi.mock('../../../public/node/system.js')

beforeEach(() => {
setInputDisabled(false)
vi.mocked(isTTY).mockReturnValue(true)
vi.mocked(isCI).mockReturnValue(false)
vi.mocked(openURL).mockResolvedValue(true)
})

afterEach(() => setInputDisabled(false))

describe('requestDeviceAuthorization', () => {
const data: any = {
device_code: 'device_code',
Expand Down Expand Up @@ -160,6 +164,19 @@ describe('requestDeviceAuthorization', () => {
expect(outputInfo).not.toHaveBeenCalledWith('👉 Press any key to open the login page on your browser')
})

test('does not open the browser when input is disabled', async () => {
const response = new Response(JSON.stringify(data))
vi.mocked(shopifyFetch).mockResolvedValue(response)
vi.mocked(identityFqdn).mockResolvedValue('fqdn.com')
vi.mocked(clientId).mockReturnValue('clientId')
setInputDisabled(true)

await expect(requestDeviceAuthorization(['scope1', 'scope2'])).rejects.toThrow(
'Authorization is required to continue, but the current environment does not support interactive prompts.',
)
expect(openURL).not.toHaveBeenCalled()
})

test('when the response is not valid JSON, throw an error with context', async () => {
// Given
const response = new Response('not valid JSON')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {exchangeDeviceCodeForAccessToken} from './exchange.js'
import {IdentityToken} from './schema.js'
import {identityFqdn} from '../../../public/node/context/fqdn.js'
import {shopifyFetch} from '../../../public/node/http.js'
import {isInputDisabled} from '../../../public/node/global-context.js'
import {outputContent, outputDebug, outputInfo, outputToken} from '../../../public/node/output.js'
import {AbortError, BugError} from '../../../public/node/error.js'
import {isCI, openURL} from '../../../public/node/system.js'
Expand Down Expand Up @@ -71,7 +72,7 @@ export async function requestDeviceAuthorization(scopes: string[]): Promise<Devi

outputInfo('\nTo run this command, log in to Shopify.')

if (isCI()) {
if (isInputDisabled() || isCI()) {
throw new AbortError(
'Authorization is required to continue, but the current environment does not support interactive prompts.',
'To resolve this, specify credentials in your environment, or run the command in an interactive environment such as your local terminal.',
Expand Down
54 changes: 54 additions & 0 deletions packages/cli-kit/src/public/node/base-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {inTemporaryDirectory, mkdir, writeFile} from './fs.js'
import {joinPath, resolvePath, cwd} from './path.js'
import {mockAndCaptureOutput} from './testing/output.js'
import {unstyled} from './output.js'
import {isInputDisabled, setInputDisabled} from './global-context.js'
import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest'
import {Flags} from '@oclif/core'

Expand All @@ -23,12 +24,14 @@ beforeEach(() => {
})

afterEach(() => {
setInputDisabled(false)
Object.defineProperty(process.stdin, 'isTTY', {value: originalStdinIsTTY, configurable: true, writable: true})
Object.defineProperty(process.stdout, 'isTTY', {value: originalStdoutIsTTY, configurable: true, writable: true})
})

let testResult: Record<string, unknown> = {}
let testError: Error | undefined
let inputDisabledDuringRun = false

class MockCommand extends Command {
/* eslint-disable @shopify/cli/command-flags-with-env */
Expand Down Expand Up @@ -149,6 +152,20 @@ class MockCommandWithoutEnvironmentFlag extends Command {
}
}

class MockCommandWithOnlyBaseFlags extends Command {
static flags = {}

async run(): Promise<void> {
const {flags} = await this.parse(MockCommandWithOnlyBaseFlags)
testResult = flags
inputDisabledDuringRun = isInputDisabled()
}

async catch(error: Error): Promise<void> {
testError = error
}
}

const validEnvironment = {
someString: 'stringy',
someBoolean: true,
Expand Down Expand Up @@ -212,6 +229,7 @@ describe('applying environments', async () => {
test(testName, async () => {
testResult = {}
testError = undefined
inputDisabledDuringRun = false

await inTemporaryDirectory(async (tmpDir) => {
await writeFile(joinPath(tmpDir, 'shopify.environments.toml'), encodeTOML(allEnvironments as any))
Expand Down Expand Up @@ -469,6 +487,34 @@ describe('applying environments', async () => {
},
)

runTestInTmpDir('provides --no-input to commands through the base flags', async () => {
// When
await MockCommandWithOnlyBaseFlags.run(['--no-input'])

// Then
expect(testError).toBeUndefined()
expect(testResult['no-input']).toBe(true)
expect(inputDisabledDuringRun).toBe(true)
expect(isInputDisabled()).toBe(false)
})

runTestInTmpDir('treats --no-input as non-interactive in a TTY', async (tmpDir: string) => {
// When
expect(MockCommandWithRequiredFlagInNonTTY.baseFlags).toHaveProperty('no-input')
await MockCommandWithRequiredFlagInNonTTY.run(['--path', tmpDir, '--no-input'])

// Then
expect(unstyled(testError!.message)).toMatch('Flag not specified:\n\n--nonTTYRequiredFlag')
})

runTestInTmpDir('supports disabling input through the environment', async (tmpDir: string) => {
vi.stubEnv('SHOPIFY_FLAG_NO_INPUT', 'true')

await MockCommandWithRequiredFlagInNonTTY.run(['--path', tmpDir])

expect(unstyled(testError!.message)).toMatch('Flag not specified:\n\n--nonTTYRequiredFlag')
})

runTestInTmpDir('does not throw in TTY mode when a non-TTY required argument is missing', async (tmpDir: string) => {
// Given — simulate interactive terminal
Object.defineProperty(process.stdin, 'isTTY', {value: true, configurable: true, writable: true})
Expand All @@ -493,6 +539,14 @@ describe('applying environments', async () => {
expect(unstyled(testError!.message)).toMatch('Flag not specified:\n\n--nonTTYRequiredFlag')
})

runTestInTmpDir('treats piped stdin as non-interactive', async (tmpDir: string) => {
Object.defineProperty(process.stdin, 'isTTY', {value: false, configurable: true, writable: true})

await MockCommandWithRequiredFlagInNonTTY.run(['--path', tmpDir])

expect(unstyled(testError!.message)).toMatch('Flag not specified:\n\n--nonTTYRequiredFlag')
})

runTestInTmpDir('reports all missing declarative non-TTY requirements', async (tmpDir: string) => {
// Given
vi.stubEnv('CI', 'true')
Expand Down
35 changes: 25 additions & 10 deletions packages/cli-kit/src/public/node/base-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {setCurrentSessionAlias} from './session.js'
import {terminalSupportsPrompting} from './system.js'
import {hashString} from './crypto.js'
import {isTruthy} from './context/utilities.js'
import {setCurrentCommandId} from './global-context.js'
import {setCurrentCommandId, setInputDisabled} from './global-context.js'
import {noInputFlag} from './no-input.js'
import {JsonMap} from '../../private/common/json.js'
import {underscore} from '../common/string.js'
import {Command, Config, Errors} from '@oclif/core'
Expand All @@ -31,7 +32,7 @@ interface EnvironmentFlags {
}

abstract class BaseCommand extends Command {
static baseFlags: FlagInput<{}> = {}
static baseFlags = noInputFlag

public static get requiresSyncAnalytics(): boolean {
return false
Expand Down Expand Up @@ -62,6 +63,14 @@ abstract class BaseCommand extends Command {
return Errors.handle(error)
}

protected async finally(error: Error | undefined): Promise<void> {
try {
await super.finally(error)
} finally {
setInputDisabled(false)
}
}

protected async init(): Promise<unknown> {
this.exitWithTimestampWhenEnvVariablePresent()
setCurrentCommandId(this.id ?? '')
Expand Down Expand Up @@ -112,14 +121,15 @@ abstract class BaseCommand extends Command {
}

protected async parse<
TFlags extends FlagOutput & {path?: string; verbose?: boolean; 'auth-alias'?: string},
TFlags extends FlagOutput & {path?: string; verbose?: boolean; 'auth-alias'?: string; 'no-input'?: boolean},
TGlobalFlags extends FlagOutput,
TArgs extends ArgOutput,
>(
options?: Input<TFlags, TGlobalFlags, TArgs>,
argv?: string[],
): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs> & {argv: string[]}> {
let result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, argv)
setInputDisabled(result.flags['no-input'] === true)
result = await this.resultWithEnvironment<TFlags, TGlobalFlags, TArgs>(result, options, argv)
await setCurrentSessionAlias(result.flags['auth-alias'])
await addFromParsedFlags(result.flags)
Expand Down Expand Up @@ -343,16 +353,21 @@ export function noDefaultsOptions<TFlags extends FlagOutput, TGlobalFlags extend
if (!options?.flags) return options
return {
...options,
flags: Object.fromEntries(
Object.entries(options.flags).map(([label, settings]) => {
const copiedSettings = {...(settings as {default?: unknown})}
delete copiedSettings.default
return [label, copiedSettings]
}),
) as FlagInput<TFlags>,
flags: flagsWithoutDefaults(options.flags),
baseFlags: options.baseFlags ? flagsWithoutDefaults(options.baseFlags) : undefined,
}
}

function flagsWithoutDefaults<TFlags extends FlagOutput>(flags: FlagInput<TFlags>): FlagInput<TFlags> {
return Object.fromEntries(
Object.entries(flags).map(([label, settings]) => {
const copiedSettings = {...(settings as {default?: unknown})}
delete copiedSettings.default
return [label, copiedSettings]
}),
) as FlagInput<TFlags>
}

/**
* Converts the environment's settings to arguments as though passed on the command
* line, skipping any arguments the user specified on the command line.
Expand Down
11 changes: 11 additions & 0 deletions packages/cli-kit/src/public/node/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {clearCache, runCLI, runCreateCLI, portFlag, requiredIfNonInteractive} from './cli.js'
import {findUpAndReadPackageJson} from './node-package-manager.js'
import {mockAndCaptureOutput} from './testing/output.js'
import {isInputDisabled} from './global-context.js'
import * as confStore from '../../private/node/conf-store.js'
import {describe, expect, test, vi} from 'vitest'
import {Flags} from '@oclif/core'
Expand All @@ -14,6 +15,16 @@ describe('cli', () => {
expect(launchCLI).toHaveBeenCalledWith({moduleURL: 'test'})
})

test('disables input while the CLI runs with --no-input and resets it afterwards', async () => {
const launchCLI = vi.fn(async () => {
expect(isInputDisabled()).toBe(true)
})

await runCLI({moduleURL: 'test', development: false}, launchCLI, ['--no-input'])

expect(isInputDisabled()).toBe(false)
})

test('triggers no colour mode based on --no-color flag', async () => {
const launchCLI = vi.fn()
const env = {} as any
Expand Down
18 changes: 12 additions & 6 deletions packages/cli-kit/src/public/node/cli.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {isTruthy} from './context/utilities.js'
import {setInputDisabled} from './global-context.js'
import {launchCLI as defaultLaunchCli} from './cli-launcher.js'
import {environmentVariables} from '../../private/node/constants.js'
import {Flags} from '@oclif/core'
Expand Down Expand Up @@ -86,13 +87,18 @@ export async function runCLI(
env: NodeJS.ProcessEnv = process.env,
versions: NodeJS.ProcessVersions = process.versions,
): Promise<void> {
setupEnvironmentVariables(options, argv, env)
if (options.runInCreateMode) {
await addInitToArgvWhenRunningCreateCLI(options, argv)
setInputDisabled(argv.includes('--no-input') || isTruthy(env.SHOPIFY_FLAG_NO_INPUT))
try {
setupEnvironmentVariables(options, argv, env)
if (options.runInCreateMode) {
await addInitToArgvWhenRunningCreateCLI(options, argv)
}
forceNoColor(argv, env)
await exitIfOldNodeVersion(versions)
return await launchCLI({moduleURL: options.moduleURL, lazyCommandLoader: options.lazyCommandLoader})
} finally {
setInputDisabled(false)
}
forceNoColor(argv, env)
await exitIfOldNodeVersion(versions)
return launchCLI({moduleURL: options.moduleURL, lazyCommandLoader: options.lazyCommandLoader})
}

async function addInitToArgvWhenRunningCreateCLI(
Expand Down
11 changes: 11 additions & 0 deletions packages/cli-kit/src/public/node/context/local.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from './local.js'
import {fileExists} from '../fs.js'
import {exec} from '../system.js'
import {setInputDisabled} from '../global-context.js'

import {afterEach, expect, describe, vi, test} from 'vitest'
import * as os from 'os'
Expand All @@ -34,6 +35,7 @@ describe('isTerminalInteractive', () => {
const originalEnv = {...process.env}

afterEach(() => {
setInputDisabled(false)
process.stdout.isTTY = originalIsTTY
process.env.TERM = originalEnv.TERM
if (originalEnv.CI === undefined) {
Expand Down Expand Up @@ -77,6 +79,15 @@ describe('isTerminalInteractive', () => {
process.env.TERM = 'xterm-256color'
expect(isTerminalInteractive()).toBe(false)
})

test('returns false when user input is disabled', () => {
process.stdout.isTTY = true
delete process.env.CI
process.env.TERM = 'xterm-256color'
setInputDisabled(true)

expect(isTerminalInteractive()).toBe(false)
})
})

describe('isUnitTest', () => {
Expand Down
3 changes: 2 additions & 1 deletion packages/cli-kit/src/public/node/context/local.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {isTruthy} from './utilities.js'
import {isInputDisabled} from '../global-context.js'
import {getCIMetadata, isSet, Metadata} from '../../../private/node/context/utilities.js'
import {defaultThemeKitAccessDomain, environmentVariables, pathConstants} from '../../../private/node/constants.js'
import {randomUUID} from 'crypto'
Expand All @@ -22,7 +23,7 @@ async function lazyExec(command: string, args: string[]): Promise<void> {
* @returns True if the terminal is interactive.
*/
export function isTerminalInteractive(): boolean {
return Boolean(process.stdout.isTTY && process.env.TERM !== 'dumb' && !('CI' in process.env))
return Boolean(!isInputDisabled() && process.stdout.isTTY && process.env.TERM !== 'dumb' && !('CI' in process.env))
}

/**
Expand Down
Loading
Loading