mirror of
https://github.com/langgenius/dify.git
synced 2026-10-04 13:47:55 +08:00
style: format with vp fmt (#38803)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
fde08d24fe
commit
a84c2d36a3
6213 files changed
+227959
-187183
No files matched your search
@@ -3,12 +3,13 @@ function normalize(p: string): string {
|
||||
}
|
||||
|
||||
export function isExcludedCommandPath(relPath: string): boolean {
|
||||
return normalize(relPath).split('/').some(seg => seg.startsWith('_'))
|
||||
return normalize(relPath)
|
||||
.split('/')
|
||||
.some((seg) => seg.startsWith('_'))
|
||||
}
|
||||
|
||||
export function isCommandIndexPath(relPath: string): boolean {
|
||||
const n = normalize(relPath)
|
||||
if (!n.endsWith('/index.ts'))
|
||||
return false
|
||||
if (!n.endsWith('/index.ts')) return false
|
||||
return !isExcludedCommandPath(n)
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
import type { CommandOutput } from './output'
|
||||
import type { ArgDefinition, FlagDefinition, ICommand, InferArgs, InferFlags, OptionalArgValueType } from './types'
|
||||
import type {
|
||||
ArgDefinition,
|
||||
FlagDefinition,
|
||||
ICommand,
|
||||
InferArgs,
|
||||
InferFlags,
|
||||
OptionalArgValueType,
|
||||
} from './types'
|
||||
import { setVerbose } from './context'
|
||||
import { hasBooleanFlag, parseArgv, VERBOSE_CHAR, VERBOSE_FLAG } from './flags'
|
||||
|
||||
@@ -9,7 +16,7 @@ import { hasBooleanFlag, parseArgv, VERBOSE_CHAR, VERBOSE_FLAG } from './flags'
|
||||
export type CommandEffect = 'read' | 'write' | 'destructive'
|
||||
|
||||
export type CommandConstructor = {
|
||||
new(): Command
|
||||
new (): Command
|
||||
description?: string
|
||||
flags?: Record<string, FlagDefinition<OptionalArgValueType>>
|
||||
args?: Record<string, ArgDefinition<string | undefined>>
|
||||
@@ -19,13 +26,15 @@ export type CommandConstructor = {
|
||||
effect?: CommandEffect
|
||||
}
|
||||
|
||||
type InferCommandArgs<C extends CommandConstructor> = C['args'] extends Record<string, ArgDefinition<string | undefined>>
|
||||
? InferArgs<C['args']>
|
||||
: Record<string, string | undefined>
|
||||
type InferCommandArgs<C extends CommandConstructor> =
|
||||
C['args'] extends Record<string, ArgDefinition<string | undefined>>
|
||||
? InferArgs<C['args']>
|
||||
: Record<string, string | undefined>
|
||||
|
||||
type InferCommandFlags<C extends CommandConstructor> = C['flags'] extends Record<string, FlagDefinition<OptionalArgValueType>>
|
||||
? InferFlags<C['flags']>
|
||||
: Record<string, OptionalArgValueType>
|
||||
type InferCommandFlags<C extends CommandConstructor> =
|
||||
C['flags'] extends Record<string, FlagDefinition<OptionalArgValueType>>
|
||||
? InferFlags<C['flags']>
|
||||
: Record<string, OptionalArgValueType>
|
||||
|
||||
type ParseResult<C extends CommandConstructor> = {
|
||||
args: InferCommandArgs<C>
|
||||
|
||||
@@ -11,20 +11,35 @@ describe('OutputFormatNotSupportedError', () => {
|
||||
|
||||
describe('UnsupportedArgValueError', () => {
|
||||
it('includes both long and short option labels when a char exists', () => {
|
||||
const def: FlagDefinition = { type: 'string', description: 'output', char: 'o', options: ['json', 'yaml'] }
|
||||
const def: FlagDefinition = {
|
||||
type: 'string',
|
||||
description: 'output',
|
||||
char: 'o',
|
||||
options: ['json', 'yaml'],
|
||||
}
|
||||
const err = new UnsupportedArgValueError('output', def, 'csv')
|
||||
expect(err.message).toBe('illegal value csv for flag --output / -o')
|
||||
})
|
||||
|
||||
it('omits the short option label when the flag has no char', () => {
|
||||
const def: FlagDefinition = { type: 'string', description: 'app mode', options: ['chat', 'workflow'] }
|
||||
const def: FlagDefinition = {
|
||||
type: 'string',
|
||||
description: 'app mode',
|
||||
options: ['chat', 'workflow'],
|
||||
}
|
||||
const err = new UnsupportedArgValueError('mode', def, 'chatbot')
|
||||
expect(err.message).toBe('illegal value chatbot for flag --mode')
|
||||
})
|
||||
|
||||
it('lists supported values in the hint', () => {
|
||||
const def: FlagDefinition = { type: 'string', description: 'app mode', options: ['chat', 'workflow'] }
|
||||
expect(new UnsupportedArgValueError('mode', def, 'chatbot').hint).toBe('supported value: chat, workflow')
|
||||
const def: FlagDefinition = {
|
||||
type: 'string',
|
||||
description: 'app mode',
|
||||
options: ['chat', 'workflow'],
|
||||
}
|
||||
expect(new UnsupportedArgValueError('mode', def, 'chatbot').hint).toBe(
|
||||
'supported value: chat, workflow',
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves the hint empty when the flag declares no options', () => {
|
||||
|
||||
@@ -75,11 +75,15 @@ describe('parseArgv', () => {
|
||||
})
|
||||
|
||||
it('throws on non-integer value for integer flag', () => {
|
||||
expect(() => parseArgv(['alice', '--count', 'abc'], meta)).toThrow('expected integer, got "abc"')
|
||||
expect(() => parseArgv(['alice', '--count', 'abc'], meta)).toThrow(
|
||||
'expected integer, got "abc"',
|
||||
)
|
||||
})
|
||||
|
||||
it('throws on invalid boolean value', () => {
|
||||
expect(() => parseArgv(['alice', '--verbose=maybe'], meta)).toThrow('expected boolean, got "maybe"')
|
||||
expect(() => parseArgv(['alice', '--verbose=maybe'], meta)).toThrow(
|
||||
'expected boolean, got "maybe"',
|
||||
)
|
||||
})
|
||||
|
||||
it('throws when non-boolean flag has no value', () => {
|
||||
@@ -179,7 +183,10 @@ describe('parseArgv', () => {
|
||||
describe('options validation', () => {
|
||||
const metaWithOptions = {
|
||||
flags: {
|
||||
mode: Flags.string({ description: 'app mode', options: ['chat', 'workflow', 'completion'] }),
|
||||
mode: Flags.string({
|
||||
description: 'app mode',
|
||||
options: ['chat', 'workflow', 'completion'],
|
||||
}),
|
||||
},
|
||||
args: {},
|
||||
}
|
||||
@@ -196,9 +203,7 @@ describe('parseArgv', () => {
|
||||
})
|
||||
|
||||
it('rejects an invalid option value (= form)', () => {
|
||||
expect(() => parseArgv(['--mode=chatbot'], metaWithOptions)).toThrow(
|
||||
UnsupportedArgValueError,
|
||||
)
|
||||
expect(() => parseArgv(['--mode=chatbot'], metaWithOptions)).toThrow(UnsupportedArgValueError)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+58
-50
@@ -20,14 +20,14 @@ const GLOBAL_FLAGS: Record<string, FlagDefinition> = {
|
||||
}),
|
||||
}
|
||||
|
||||
function stringFlag<const Opts extends {
|
||||
description: string
|
||||
char?: string
|
||||
default?: string
|
||||
options?: readonly string[]
|
||||
}>(
|
||||
opts: Opts,
|
||||
): FlagDefinition<string> {
|
||||
function stringFlag<
|
||||
const Opts extends {
|
||||
description: string
|
||||
char?: string
|
||||
default?: string
|
||||
options?: readonly string[]
|
||||
},
|
||||
>(opts: Opts): FlagDefinition<string> {
|
||||
return {
|
||||
type: 'string',
|
||||
multiple: false,
|
||||
@@ -35,7 +35,7 @@ function stringFlag<const Opts extends {
|
||||
}
|
||||
}
|
||||
|
||||
function outputFormatFlag<const Opts extends { options: readonly string[], default?: string }>(
|
||||
function outputFormatFlag<const Opts extends { options: readonly string[]; default?: string }>(
|
||||
opts: Opts,
|
||||
): FlagDefinition<string> {
|
||||
return {
|
||||
@@ -47,9 +47,9 @@ function outputFormatFlag<const Opts extends { options: readonly string[], defau
|
||||
}
|
||||
}
|
||||
|
||||
function stringRepeatedFlag<const Opts extends { description: string, char?: string, default?: string[], multiple?: boolean }>(
|
||||
opts: Opts,
|
||||
): FlagDefinition<string[]> {
|
||||
function stringRepeatedFlag<
|
||||
const Opts extends { description: string; char?: string; default?: string[]; multiple?: boolean },
|
||||
>(opts: Opts): FlagDefinition<string[]> {
|
||||
return {
|
||||
type: 'string',
|
||||
multiple: true,
|
||||
@@ -57,17 +57,24 @@ function stringRepeatedFlag<const Opts extends { description: string, char?: str
|
||||
}
|
||||
}
|
||||
|
||||
function booleanFlag(opts: { description: string, char?: string, default?: boolean, helpGroup?: 'GLOBAL' }): FlagDefinition<boolean> {
|
||||
function booleanFlag(opts: {
|
||||
description: string
|
||||
char?: string
|
||||
default?: boolean
|
||||
helpGroup?: 'GLOBAL'
|
||||
}): FlagDefinition<boolean> {
|
||||
return { type: 'boolean', ...opts }
|
||||
}
|
||||
|
||||
function integerFlag<const Opts extends { description: string, char?: string, default?: number }>(
|
||||
function integerFlag<const Opts extends { description: string; char?: string; default?: number }>(
|
||||
opts: Opts,
|
||||
): FlagDefinition<Opts extends { default: number } ? number : number | undefined> {
|
||||
return { type: 'integer', ...opts } as FlagDefinition<Opts extends { default: number } ? number : number | undefined>
|
||||
return { type: 'integer', ...opts } as FlagDefinition<
|
||||
Opts extends { default: number } ? number : number | undefined
|
||||
>
|
||||
}
|
||||
|
||||
function stringArg<const Opts extends { description: string, required?: boolean }>(
|
||||
function stringArg<const Opts extends { description: string; required?: boolean }>(
|
||||
opts: Opts,
|
||||
): ArgDefinition<Opts extends { required: true } ? string : string | undefined> {
|
||||
return opts as ArgDefinition<Opts extends { required: true } ? string : string | undefined>
|
||||
@@ -81,17 +88,14 @@ function coerceFlagValue(raw: string, def: FlagDefinition): string | boolean | n
|
||||
switch (def.type) {
|
||||
case 'integer': {
|
||||
const n = Number(raw)
|
||||
if (Number.isNaN(n))
|
||||
throw new Error(`expected integer, got ${JSON.stringify(raw)}`)
|
||||
if (Number.isNaN(n)) throw new Error(`expected integer, got ${JSON.stringify(raw)}`)
|
||||
|
||||
return n
|
||||
}
|
||||
case 'boolean': {
|
||||
if (raw === 'true' || raw === '1')
|
||||
return true
|
||||
if (raw === 'true' || raw === '1') return true
|
||||
|
||||
if (raw === 'false' || raw === '0')
|
||||
return false
|
||||
if (raw === 'false' || raw === '0') return false
|
||||
|
||||
throw new Error(`expected boolean, got ${JSON.stringify(raw)}`)
|
||||
}
|
||||
@@ -100,20 +104,26 @@ function coerceFlagValue(raw: string, def: FlagDefinition): string | boolean | n
|
||||
}
|
||||
}
|
||||
|
||||
function accumulateFlagValue(flags: ParsedFlags, name: string, value: string | boolean | number, def: FlagDefinition): void {
|
||||
function accumulateFlagValue(
|
||||
flags: ParsedFlags,
|
||||
name: string,
|
||||
value: string | boolean | number,
|
||||
def: FlagDefinition,
|
||||
): void {
|
||||
if (def.multiple === true) {
|
||||
const existing = flags[name]
|
||||
flags[name] = Array.isArray(existing) ? [...existing, String(value)] : [String(value)]
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
flags[name] = value
|
||||
}
|
||||
}
|
||||
|
||||
function resolveByChar(char: string, flags: Record<string, FlagDefinition>): [name: string, def: FlagDefinition] | undefined {
|
||||
function resolveByChar(
|
||||
char: string,
|
||||
flags: Record<string, FlagDefinition>,
|
||||
): [name: string, def: FlagDefinition] | undefined {
|
||||
for (const [name, def] of Object.entries(flags)) {
|
||||
if (def.char === char)
|
||||
return [name, def]
|
||||
if (def.char === char) return [name, def]
|
||||
}
|
||||
|
||||
return undefined
|
||||
@@ -124,7 +134,12 @@ function validateFlagOptions(name: string, raw: string, def: FlagDefinition): vo
|
||||
throw new UnsupportedArgValueError(name, def, raw)
|
||||
}
|
||||
|
||||
type ResolvedFlag = { name: string, def: FlagDefinition, label: string, inlineRaw: string | undefined }
|
||||
type ResolvedFlag = {
|
||||
name: string
|
||||
def: FlagDefinition
|
||||
label: string
|
||||
inlineRaw: string | undefined
|
||||
}
|
||||
|
||||
function resolveToken(token: string, flags: Record<string, FlagDefinition>): ResolvedFlag | null {
|
||||
if (token.startsWith('--')) {
|
||||
@@ -132,16 +147,14 @@ function resolveToken(token: string, flags: Record<string, FlagDefinition>): Res
|
||||
const name = eqIdx !== -1 ? token.slice(2, eqIdx) : token.slice(2)
|
||||
const inlineRaw = eqIdx !== -1 ? token.slice(eqIdx + 1) : undefined
|
||||
const def = flags[name]
|
||||
if (!def)
|
||||
throw new Error(`unknown flag: --${name}`)
|
||||
if (!def) throw new Error(`unknown flag: --${name}`)
|
||||
return { name, def, label: `--${name}`, inlineRaw }
|
||||
}
|
||||
|
||||
if (token.length === 2 && token[1] !== undefined) {
|
||||
const char = token[1]
|
||||
const resolved = resolveByChar(char, flags)
|
||||
if (!resolved)
|
||||
throw new Error(`unknown flag: -${char}`)
|
||||
if (!resolved) throw new Error(`unknown flag: -${char}`)
|
||||
const [name, def] = resolved
|
||||
return { name, def, label: `-${char}`, inlineRaw: undefined }
|
||||
}
|
||||
@@ -153,18 +166,18 @@ function resolveToken(token: string, flags: Record<string, FlagDefinition>): Res
|
||||
// to call before the command-specific flag set is known (e.g. global flags).
|
||||
export function hasBooleanFlag(argv: readonly string[], name: string, char?: string): boolean {
|
||||
for (const token of argv) {
|
||||
if (token === '--')
|
||||
break
|
||||
if (token === `--${name}` || token === `--${name}=true` || token === `--${name}=1`)
|
||||
return true
|
||||
if (char !== undefined && token === `-${char}`)
|
||||
return true
|
||||
if (token === '--') break
|
||||
if (token === `--${name}` || token === `--${name}=true` || token === `--${name}=1`) return true
|
||||
if (char !== undefined && token === `-${char}`) return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export function parseArgv(argv: readonly string[], meta: CommandMeta): { args: ParsedArgs, flags: ParsedFlags } {
|
||||
export function parseArgv(
|
||||
argv: readonly string[],
|
||||
meta: CommandMeta,
|
||||
): { args: ParsedArgs; flags: ParsedFlags } {
|
||||
const flags: ParsedFlags = {}
|
||||
const positional: string[] = []
|
||||
const argDefs = Object.entries(meta.args)
|
||||
@@ -172,8 +185,7 @@ export function parseArgv(argv: readonly string[], meta: CommandMeta): { args: P
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const token = argv[i]
|
||||
if (token === undefined)
|
||||
break
|
||||
if (token === undefined) break
|
||||
|
||||
if (!pastDoubleDash && token === '--') {
|
||||
pastDoubleDash = true
|
||||
@@ -204,8 +216,7 @@ export function parseArgv(argv: readonly string[], meta: CommandMeta): { args: P
|
||||
let raw: string
|
||||
if (inlineRaw !== undefined) {
|
||||
raw = inlineRaw
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
i++
|
||||
const next = i < argv.length ? argv[i] : undefined
|
||||
if (next === undefined || next.startsWith('-'))
|
||||
@@ -220,21 +231,18 @@ export function parseArgv(argv: readonly string[], meta: CommandMeta): { args: P
|
||||
const args: ParsedArgs = {}
|
||||
for (let j = 0; j < argDefs.length; j++) {
|
||||
const entry = argDefs[j]
|
||||
if (!entry)
|
||||
continue
|
||||
if (!entry) continue
|
||||
|
||||
const [argName, argDef] = entry
|
||||
if (j < positional.length) {
|
||||
args[argName] = positional[j]
|
||||
}
|
||||
else if (argDef.required) {
|
||||
} else if (argDef.required) {
|
||||
throw new Error(`missing required argument: ${argName}`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [name, def] of Object.entries(meta.flags)) {
|
||||
if (!(name in flags) && def.default !== undefined)
|
||||
flags[name] = def.default
|
||||
if (!(name in flags) && def.default !== undefined) flags[name] = def.default
|
||||
}
|
||||
|
||||
return { args, flags }
|
||||
|
||||
@@ -151,7 +151,9 @@ describe('formatHelp structured output', () => {
|
||||
it('emits a JSON descriptor under json format', () => {
|
||||
const ctor = makeCmd({
|
||||
description: 'Lists apps',
|
||||
flags: { output: Flags.outputFormat({ options: ['json', 'yaml', 'name', 'wide'], default: '' }) },
|
||||
flags: {
|
||||
output: Flags.outputFormat({ options: ['json', 'yaml', 'name', 'wide'], default: '' }),
|
||||
},
|
||||
args: { id: Args.string({ description: 'app id', required: true }) },
|
||||
examples: ['<%= config.bin %> get app'],
|
||||
agentGuide: 'WORKFLOW',
|
||||
|
||||
+42
-36
@@ -40,16 +40,14 @@ function isStructured(format: string): boolean {
|
||||
}
|
||||
|
||||
function serialize(value: unknown, format: string): string {
|
||||
if (format === 'yaml')
|
||||
return dump(value, { indent: 2, lineWidth: -1 })
|
||||
if (format === 'yaml') return dump(value, { indent: 2, lineWidth: -1 })
|
||||
return `${JSON.stringify(value, null, 2)}\n`
|
||||
}
|
||||
|
||||
function flagLabel(name: string, def: FlagDefinition): string {
|
||||
const aliases: string[] = []
|
||||
|
||||
if (def.char)
|
||||
aliases.push(`-${def.char}`)
|
||||
if (def.char) aliases.push(`-${def.char}`)
|
||||
|
||||
aliases.push(`--${name}`)
|
||||
|
||||
@@ -59,14 +57,13 @@ function flagLabel(name: string, def: FlagDefinition): string {
|
||||
}
|
||||
|
||||
function flagDefault(def: FlagDefinition): string {
|
||||
if (def.default === undefined)
|
||||
return ''
|
||||
if (def.default === undefined) return ''
|
||||
|
||||
return ` [default: ${JSON.stringify(def.default)}]`
|
||||
}
|
||||
|
||||
function renderExamples(ctor: CommandConstructor): string[] {
|
||||
return (ctor.examples ?? []).map(ex => ex.replace('<%= config.bin %>', BIN))
|
||||
return (ctor.examples ?? []).map((ex) => ex.replace('<%= config.bin %>', BIN))
|
||||
}
|
||||
|
||||
function agentGuideOf(ctor: CommandConstructor): string {
|
||||
@@ -103,10 +100,13 @@ export function describeCommand(ctor: CommandConstructor, path: string): Command
|
||||
function formatHelpText(ctor: CommandConstructor, path: string): string {
|
||||
const lines: string[] = []
|
||||
|
||||
if (ctor.description)
|
||||
lines.push(ctor.description, '')
|
||||
if (ctor.description) lines.push(ctor.description, '')
|
||||
|
||||
lines.push('USAGE', ` $ ${BIN} ${path}${ctor.args && Object.keys(ctor.args).length > 0 ? ' [ARGS]' : ''}${ctor.flags && Object.keys(ctor.flags).length > 0 ? ' [FLAGS]' : ''}`, '')
|
||||
lines.push(
|
||||
'USAGE',
|
||||
` $ ${BIN} ${path}${ctor.args && Object.keys(ctor.args).length > 0 ? ' [ARGS]' : ''}${ctor.flags && Object.keys(ctor.flags).length > 0 ? ' [FLAGS]' : ''}`,
|
||||
'',
|
||||
)
|
||||
|
||||
if (ctor.args && Object.keys(ctor.args).length > 0) {
|
||||
lines.push('ARGUMENTS')
|
||||
@@ -141,15 +141,13 @@ function formatHelpText(ctor: CommandConstructor, path: string): string {
|
||||
|
||||
const guide = agentGuideOf(ctor)
|
||||
|
||||
if (guide.length > 0)
|
||||
lines.push(guide)
|
||||
if (guide.length > 0) lines.push(guide)
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
export function formatHelp(ctor: CommandConstructor, path: string, format = ''): string {
|
||||
if (isStructured(format))
|
||||
return serialize(describeCommand(ctor, path), format)
|
||||
if (isStructured(format)) return serialize(describeCommand(ctor, path), format)
|
||||
|
||||
return formatHelpText(ctor, path)
|
||||
}
|
||||
@@ -166,7 +164,9 @@ export function formatTopic(topic: HelpTopic, format = ''): string {
|
||||
// top-level overview and namespace drill-in (`difyctl <group> --help`) so both
|
||||
// derive from the same full-depth `collectCommands` walk and the canonical
|
||||
// space-joined command path.
|
||||
export function renderCommandRows(commands: Array<{ command: CommandConstructor, path: string[] }>): string {
|
||||
export function renderCommandRows(
|
||||
commands: Array<{ command: CommandConstructor; path: string[] }>,
|
||||
): string {
|
||||
const rows = commands.map(({ command, path }) => ({
|
||||
label: path.join(' '),
|
||||
desc: command.description ?? '',
|
||||
@@ -178,8 +178,7 @@ export function renderCommandRows(commands: Array<{ command: CommandConstructor,
|
||||
let prevGroup: string | undefined
|
||||
|
||||
for (const r of rows) {
|
||||
if (prevGroup !== undefined && r.group !== prevGroup)
|
||||
lines.push('')
|
||||
if (prevGroup !== undefined && r.group !== prevGroup) lines.push('')
|
||||
|
||||
prevGroup = r.group
|
||||
lines.push(r.desc ? ` ${r.label.padEnd(width)}${r.desc}` : ` ${r.label}`)
|
||||
@@ -193,9 +192,15 @@ export function renderCommandRows(commands: Array<{ command: CommandConstructor,
|
||||
// same shape as the top-level site map's `commands` — while text renders the
|
||||
// aligned rows. Keeps `<group> --help -o json` machine-readable like every
|
||||
// other help surface.
|
||||
export function formatCommandList(commands: Array<{ command: CommandConstructor, path: string[] }>, format: string): string {
|
||||
export function formatCommandList(
|
||||
commands: Array<{ command: CommandConstructor; path: string[] }>,
|
||||
format: string,
|
||||
): string {
|
||||
if (isStructured(format))
|
||||
return serialize({ commands: commands.map(({ command, path }) => describeCommand(command, path.join(' '))) }, format)
|
||||
return serialize(
|
||||
{ commands: commands.map(({ command, path }) => describeCommand(command, path.join(' '))) },
|
||||
format,
|
||||
)
|
||||
|
||||
return `COMMANDS\n${renderCommandRows(commands)}\n`
|
||||
}
|
||||
@@ -203,20 +208,16 @@ export function formatCommandList(commands: Array<{ command: CommandConstructor,
|
||||
// Curated onboarding examples for the top-level overview (gh-style): the
|
||||
// shortest path from zero to a structured app run. Editorial, not an exhaustive
|
||||
// dump — per-command examples live in each command's own `--help`.
|
||||
const ROOT_EXAMPLES = [
|
||||
`${BIN} auth login`,
|
||||
`${BIN} get app`,
|
||||
`${BIN} run app <id> "hello" -o json`,
|
||||
]
|
||||
const ROOT_EXAMPLES = [`${BIN} auth login`, `${BIN} get app`, `${BIN} run app <id> "hello" -o json`]
|
||||
|
||||
function renderTopicRows(): string {
|
||||
const width = TOPICS.reduce((max, t) => Math.max(max, t.name.length), 0) + 2
|
||||
return TOPICS.map(t => ` ${t.name.padEnd(width)}${t.summary}`).join('\n')
|
||||
return TOPICS.map((t) => ` ${t.name.padEnd(width)}${t.summary}`).join('\n')
|
||||
}
|
||||
|
||||
function renderGlobalFlagRows(): string {
|
||||
const width = GLOBAL_FLAG_HELP.reduce((max, f) => Math.max(max, f.label.length), 0) + 2
|
||||
return GLOBAL_FLAG_HELP.map(f => ` ${f.label.padEnd(width)}${f.description}`).join('\n')
|
||||
return GLOBAL_FLAG_HELP.map((f) => ` ${f.label.padEnd(width)}${f.description}`).join('\n')
|
||||
}
|
||||
|
||||
function formatTopLevelHelpText(tree: CommandTree): string {
|
||||
@@ -224,12 +225,12 @@ function formatTopLevelHelpText(tree: CommandTree): string {
|
||||
`${BIN} — Dify command-line interface`,
|
||||
`USAGE\n ${BIN} <command> <subcommand> [flags]`,
|
||||
`COMMANDS\n${renderCommandRows(collectCommands(tree))}`,
|
||||
`EXAMPLES\n${ROOT_EXAMPLES.map(ex => ` $ ${ex}`).join('\n')}`,
|
||||
`EXAMPLES\n${ROOT_EXAMPLES.map((ex) => ` $ ${ex}`).join('\n')}`,
|
||||
`GLOBAL FLAGS\n${renderGlobalFlagRows()}`,
|
||||
`GUIDES\n${renderTopicRows()}`,
|
||||
`LEARN MORE\n`
|
||||
+ ` Use \`${BIN} <command> --help\` for details on a command.\n`
|
||||
+ ` New here? Run \`${BIN} help account\`. Agents: \`${BIN} help agent\` or \`${BIN} --help -o json\`.`,
|
||||
`LEARN MORE\n` +
|
||||
` Use \`${BIN} <command> --help\` for details on a command.\n` +
|
||||
` New here? Run \`${BIN} help account\`. Agents: \`${BIN} help agent\` or \`${BIN} --help -o json\`.`,
|
||||
]
|
||||
|
||||
return `${sections.join('\n\n')}\n`
|
||||
@@ -237,12 +238,17 @@ function formatTopLevelHelpText(tree: CommandTree): string {
|
||||
|
||||
export function formatTopLevelHelp(tree: CommandTree, format: string): string {
|
||||
if (isStructured(format)) {
|
||||
return serialize({
|
||||
bin: BIN,
|
||||
contract: CONTRACT,
|
||||
commands: collectCommands(tree).map(({ command, path }) => describeCommand(command, path.join(' '))),
|
||||
topics: TOPICS.map(t => ({ name: t.name, summary: t.summary })),
|
||||
}, format)
|
||||
return serialize(
|
||||
{
|
||||
bin: BIN,
|
||||
contract: CONTRACT,
|
||||
commands: collectCommands(tree).map(({ command, path }) =>
|
||||
describeCommand(command, path.join(' ')),
|
||||
),
|
||||
topics: TOPICS.map((t) => ({ name: t.name, summary: t.summary })),
|
||||
},
|
||||
format,
|
||||
)
|
||||
}
|
||||
|
||||
return formatTopLevelHelpText(tree)
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import type { FormattedPrintable, NamePrintable, TablePrintable } from './output'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { OutputFormatNotSupportedError } from './errors'
|
||||
import {
|
||||
formatted,
|
||||
raw,
|
||||
stringifyOutput,
|
||||
table,
|
||||
} from './output'
|
||||
import { formatted, raw, stringifyOutput, table } from './output'
|
||||
|
||||
function makeFormatted(opts: { text?: string, json?: unknown, name?: string }): FormattedPrintable & NamePrintable {
|
||||
function makeFormatted(opts: {
|
||||
text?: string
|
||||
json?: unknown
|
||||
name?: string
|
||||
}): FormattedPrintable & NamePrintable {
|
||||
return {
|
||||
text: () => opts.text ?? 'hello',
|
||||
json: () => opts.json ?? { msg: 'hello' },
|
||||
@@ -17,16 +16,17 @@ function makeFormatted(opts: { text?: string, json?: unknown, name?: string }):
|
||||
}
|
||||
|
||||
function makeTable(opts: {
|
||||
columns?: Array<{ name: string, priority: number }>
|
||||
columns?: Array<{ name: string; priority: number }>
|
||||
rows?: Array<Array<string | number | boolean | null | undefined>>
|
||||
json?: unknown
|
||||
name?: string
|
||||
}): TablePrintable & NamePrintable {
|
||||
return {
|
||||
tableColumns: () => opts.columns ?? [
|
||||
{ name: 'NAME', priority: 0 },
|
||||
{ name: 'STATUS', priority: 0 },
|
||||
],
|
||||
tableColumns: () =>
|
||||
opts.columns ?? [
|
||||
{ name: 'NAME', priority: 0 },
|
||||
{ name: 'STATUS', priority: 0 },
|
||||
],
|
||||
tableRows: () => opts.rows ?? [['alice', 'active']],
|
||||
json: () => opts.json ?? [{ name: 'alice', status: 'active' }],
|
||||
name: () => opts.name ?? 'table-name',
|
||||
@@ -145,7 +145,7 @@ describe('stringifyOutput — table', () => {
|
||||
],
|
||||
})
|
||||
const result = stringifyOutput(table({ format: '', data }))
|
||||
const lines = result.split('\n').filter(l => l.length > 0)
|
||||
const lines = result.split('\n').filter((l) => l.length > 0)
|
||||
// 'hello' display width 5, '猜谜' display width 4 — column width=5
|
||||
// padding after 'hello': 5-5+2=2 spaces → 'hello aaa'
|
||||
// padding after '猜谜': 5-4+2=3 spaces → '猜谜 bbb'
|
||||
@@ -185,8 +185,14 @@ describe('stringifyOutput — table', () => {
|
||||
|
||||
it('table renders column padding correctly', () => {
|
||||
const data = makeTable({
|
||||
columns: [{ name: 'NAME', priority: 0 }, { name: 'ID', priority: 0 }],
|
||||
rows: [['alice-longname', '1'], ['bob', '2']],
|
||||
columns: [
|
||||
{ name: 'NAME', priority: 0 },
|
||||
{ name: 'ID', priority: 0 },
|
||||
],
|
||||
rows: [
|
||||
['alice-longname', '1'],
|
||||
['bob', '2'],
|
||||
],
|
||||
})
|
||||
const result = stringifyOutput(table({ format: '', data }))
|
||||
const lines = result.split('\n').filter(Boolean)
|
||||
|
||||
+36
-34
@@ -52,7 +52,10 @@ export type FormattedOutput<TData extends FormattedPrintable> = {
|
||||
readonly data: TData
|
||||
}
|
||||
|
||||
export type CommandOutput = RawOutput | TableOutput<TablePrintable> | FormattedOutput<FormattedPrintable>
|
||||
export type CommandOutput =
|
||||
| RawOutput
|
||||
| TableOutput<TablePrintable>
|
||||
| FormattedOutput<FormattedPrintable>
|
||||
|
||||
export function raw(data: string): RawOutput {
|
||||
return { kind: 'raw', data }
|
||||
@@ -121,58 +124,57 @@ function renderTable(output: TableOutput<TablePrintable>): string {
|
||||
const keep: number[] = []
|
||||
for (let i = 0; i < columns.length; i++) {
|
||||
const column = columns[i]
|
||||
if (column !== undefined && (column.priority === 0 || wide))
|
||||
keep.push(i)
|
||||
if (column !== undefined && (column.priority === 0 || wide)) keep.push(i)
|
||||
}
|
||||
|
||||
const rows = [
|
||||
keep.map(i => columns[i]?.name ?? ''),
|
||||
...output.data.tableRows().map(row => keep.map((idx) => {
|
||||
const cell = row[idx]
|
||||
return cell === null || cell === undefined ? '' : String(cell)
|
||||
})),
|
||||
keep.map((i) => columns[i]?.name ?? ''),
|
||||
...output.data.tableRows().map((row) =>
|
||||
keep.map((idx) => {
|
||||
const cell = row[idx]
|
||||
return cell === null || cell === undefined ? '' : String(cell)
|
||||
}),
|
||||
),
|
||||
]
|
||||
return formatTable(rows)
|
||||
}
|
||||
|
||||
function isWideCodePoint(cp: number): boolean {
|
||||
return (
|
||||
(cp >= 0x1100 && cp <= 0x115F)
|
||||
|| cp === 0x2329 || cp === 0x232A
|
||||
|| (cp >= 0x2E80 && cp <= 0x3247)
|
||||
|| (cp >= 0x3250 && cp <= 0x4DBF)
|
||||
|| (cp >= 0x4E00 && cp <= 0xA4C6)
|
||||
|| (cp >= 0xA960 && cp <= 0xA97C)
|
||||
|| (cp >= 0xAC00 && cp <= 0xD7A3)
|
||||
|| (cp >= 0xF900 && cp <= 0xFAFF)
|
||||
|| (cp >= 0xFE10 && cp <= 0xFE19)
|
||||
|| (cp >= 0xFE30 && cp <= 0xFE6B)
|
||||
|| (cp >= 0xFF01 && cp <= 0xFF60)
|
||||
|| (cp >= 0xFFE0 && cp <= 0xFFE6)
|
||||
|| (cp >= 0x1B000 && cp <= 0x1B001)
|
||||
|| (cp >= 0x1F200 && cp <= 0x1F251)
|
||||
|| (cp >= 0x20000 && cp <= 0x3FFFD)
|
||||
(cp >= 0x1100 && cp <= 0x115f) ||
|
||||
cp === 0x2329 ||
|
||||
cp === 0x232a ||
|
||||
(cp >= 0x2e80 && cp <= 0x3247) ||
|
||||
(cp >= 0x3250 && cp <= 0x4dbf) ||
|
||||
(cp >= 0x4e00 && cp <= 0xa4c6) ||
|
||||
(cp >= 0xa960 && cp <= 0xa97c) ||
|
||||
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
||||
(cp >= 0xf900 && cp <= 0xfaff) ||
|
||||
(cp >= 0xfe10 && cp <= 0xfe19) ||
|
||||
(cp >= 0xfe30 && cp <= 0xfe6b) ||
|
||||
(cp >= 0xff01 && cp <= 0xff60) ||
|
||||
(cp >= 0xffe0 && cp <= 0xffe6) ||
|
||||
(cp >= 0x1b000 && cp <= 0x1b001) ||
|
||||
(cp >= 0x1f200 && cp <= 0x1f251) ||
|
||||
(cp >= 0x20000 && cp <= 0x3fffd)
|
||||
)
|
||||
}
|
||||
|
||||
function displayWidth(s: string): number {
|
||||
let w = 0
|
||||
for (const ch of s)
|
||||
w += isWideCodePoint(ch.codePointAt(0) ?? 0) ? 2 : 1
|
||||
for (const ch of s) w += isWideCodePoint(ch.codePointAt(0) ?? 0) ? 2 : 1
|
||||
return w
|
||||
}
|
||||
|
||||
function formatTable(rows: readonly (readonly string[])[]): string {
|
||||
if (rows.length === 0)
|
||||
return ''
|
||||
if (rows.length === 0) return ''
|
||||
const colCount = rows[0]?.length ?? 0
|
||||
const widths: number[] = Array.from({ length: colCount }, () => 0)
|
||||
for (const row of rows) {
|
||||
for (let i = 0; i < colCount; i++) {
|
||||
const cell = row[i] ?? ''
|
||||
const w = displayWidth(cell)
|
||||
if (w > (widths[i] ?? 0))
|
||||
widths[i] = w
|
||||
if (w > (widths[i] ?? 0)) widths[i] = w
|
||||
}
|
||||
}
|
||||
const lines = rows.map((row) => {
|
||||
@@ -182,8 +184,7 @@ function formatTable(rows: readonly (readonly string[])[]): string {
|
||||
const isLast = i === colCount - 1
|
||||
if (isLast) {
|
||||
cells.push(cell)
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
const pad = (widths[i] ?? 0) - displayWidth(cell) + 2
|
||||
cells.push(cell + ' '.repeat(pad))
|
||||
}
|
||||
@@ -194,11 +195,12 @@ function formatTable(rows: readonly (readonly string[])[]): string {
|
||||
}
|
||||
|
||||
function toName(data: TablePrintable | FormattedPrintable): string {
|
||||
if (!isNamePrintable(data))
|
||||
throw new OutputFormatNotSupportedError('name')
|
||||
if (!isNamePrintable(data)) throw new OutputFormatNotSupportedError('name')
|
||||
return data.name()
|
||||
}
|
||||
|
||||
function isNamePrintable(data: TablePrintable | FormattedPrintable): data is (TablePrintable | FormattedPrintable) & NamePrintable {
|
||||
function isNamePrintable(
|
||||
data: TablePrintable | FormattedPrintable,
|
||||
): data is (TablePrintable | FormattedPrintable) & NamePrintable {
|
||||
return typeof (data as { name?: unknown }).name === 'function'
|
||||
}
|
||||
@@ -225,7 +225,9 @@ describe('findSuggestions — cross-namespace fallback', () => {
|
||||
|
||||
it('produces a deterministic, stable result across runs', () => {
|
||||
expect(findSuggestions(realish, ['login'])).toEqual(findSuggestions(realish, ['login']))
|
||||
expect(findSuggestions(realish, ['device', 'list'])).toEqual(findSuggestions(realish, ['device', 'list']))
|
||||
expect(findSuggestions(realish, ['device', 'list'])).toEqual(
|
||||
findSuggestions(realish, ['device', 'list']),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -14,19 +14,17 @@ function buildPath(parts: string[]): string {
|
||||
export function resolveCommand(
|
||||
tree: CommandTree,
|
||||
argv: string[],
|
||||
): { command: CommandConstructor, path: string[] } | undefined {
|
||||
): { command: CommandConstructor; path: string[] } | undefined {
|
||||
const path: string[] = []
|
||||
let node: CommandNode | undefined
|
||||
let lastMatch: { command: CommandConstructor, path: string[] } | undefined
|
||||
let lastMatch: { command: CommandConstructor; path: string[] } | undefined
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const token = argv[i]
|
||||
if (token === undefined || token.startsWith('-'))
|
||||
break
|
||||
if (token === undefined || token.startsWith('-')) break
|
||||
|
||||
const next = path.length === 0 ? tree[token] : node?.subcommands[token]
|
||||
if (!next)
|
||||
break
|
||||
if (!next) break
|
||||
|
||||
node = next
|
||||
path.push(token)
|
||||
@@ -49,9 +47,10 @@ function editDistance(a: string, b: string): number {
|
||||
for (let i = 1; i <= m; i++) {
|
||||
const curr: number[] = [i]
|
||||
for (let j = 1; j <= n; j++) {
|
||||
curr[j] = a[i - 1] === b[j - 1]
|
||||
? (prev[j - 1] ?? 0)
|
||||
: 1 + Math.min(prev[j] ?? 0, curr[j - 1] ?? 0, prev[j - 1] ?? 0)
|
||||
curr[j] =
|
||||
a[i - 1] === b[j - 1]
|
||||
? (prev[j - 1] ?? 0)
|
||||
: 1 + Math.min(prev[j] ?? 0, curr[j - 1] ?? 0, prev[j - 1] ?? 0)
|
||||
}
|
||||
prev = curr
|
||||
}
|
||||
@@ -60,18 +59,15 @@ function editDistance(a: string, b: string): number {
|
||||
|
||||
export function collectCommands(
|
||||
tree: CommandTree,
|
||||
): Array<{ command: CommandConstructor, path: string[] }> {
|
||||
const results: Array<{ command: CommandConstructor, path: string[] }> = []
|
||||
): Array<{ command: CommandConstructor; path: string[] }> {
|
||||
const results: Array<{ command: CommandConstructor; path: string[] }> = []
|
||||
|
||||
function walk(node: CommandNode, path: string[]): void {
|
||||
if (node.command && node.command.hidden !== true)
|
||||
results.push({ command: node.command, path })
|
||||
for (const [key, child] of Object.entries(node.subcommands))
|
||||
walk(child, [...path, key])
|
||||
if (node.command && node.command.hidden !== true) results.push({ command: node.command, path })
|
||||
for (const [key, child] of Object.entries(node.subcommands)) walk(child, [...path, key])
|
||||
}
|
||||
|
||||
for (const [key, node] of Object.entries(tree))
|
||||
walk(node, [key])
|
||||
for (const [key, node] of Object.entries(tree)) walk(node, [key])
|
||||
|
||||
return results
|
||||
}
|
||||
@@ -89,8 +85,7 @@ function relThreshold(token: string): number {
|
||||
function positionalTokens(argv: string[]): string[] {
|
||||
const tokens: string[] = []
|
||||
for (const token of argv) {
|
||||
if (token.startsWith('-'))
|
||||
break
|
||||
if (token.startsWith('-')) break
|
||||
tokens.push(token)
|
||||
}
|
||||
return tokens
|
||||
@@ -101,18 +96,15 @@ function positionalTokens(argv: string[]): string[] {
|
||||
// null when no alignment exists (e.g. more tokens than segments).
|
||||
function minSubsequenceCost(tokens: string[], segments: string[]): number | null {
|
||||
const [head, ...rest] = tokens
|
||||
if (head === undefined)
|
||||
return 0
|
||||
if (head === undefined) return 0
|
||||
|
||||
const threshold = relThreshold(head)
|
||||
let best: number | null = null
|
||||
for (const [index, segment] of segments.entries()) {
|
||||
const cost = editDistance(head, segment)
|
||||
if (cost > threshold)
|
||||
continue
|
||||
if (cost > threshold) continue
|
||||
const tail = minSubsequenceCost(rest, segments.slice(index + 1))
|
||||
if (tail !== null && (best === null || cost + tail < best))
|
||||
best = cost + tail
|
||||
if (tail !== null && (best === null || cost + tail < best)) best = cost + tail
|
||||
}
|
||||
return best
|
||||
}
|
||||
@@ -124,68 +116,62 @@ function minSubsequenceCost(tokens: string[], segments: string[]): number | null
|
||||
function scoreFallback(tree: CommandTree, tokens: string[]): string[] {
|
||||
const last = tokens.length - 1
|
||||
const lastToken = tokens[last]
|
||||
if (lastToken === undefined)
|
||||
return []
|
||||
if (lastToken === undefined) return []
|
||||
const prefix = tokens.slice(0, last)
|
||||
|
||||
const scored: Array<{ path: string, score: number, spelling: number, depth: number }> = []
|
||||
const scored: Array<{ path: string; score: number; spelling: number; depth: number }> = []
|
||||
for (const { path } of collectCommands(tree)) {
|
||||
const leaf = path[path.length - 1] ?? ''
|
||||
const leafCost = editDistance(lastToken, leaf)
|
||||
if (leafCost > relThreshold(lastToken))
|
||||
continue
|
||||
if (leafCost > relThreshold(lastToken)) continue
|
||||
|
||||
const prefixCost = minSubsequenceCost(prefix, path.slice(0, -1))
|
||||
if (prefixCost === null)
|
||||
continue
|
||||
if (prefixCost === null) continue
|
||||
|
||||
const spelling = leafCost + prefixCost
|
||||
const score = spelling + OMIT_PENALTY * (path.length - tokens.length)
|
||||
if (score >= MAX_SCORE)
|
||||
continue
|
||||
if (score >= MAX_SCORE) continue
|
||||
|
||||
scored.push({ path: buildPath(path), score, spelling, depth: path.length })
|
||||
}
|
||||
|
||||
if (scored.length === 0)
|
||||
return []
|
||||
if (scored.length === 0) return []
|
||||
|
||||
scored.sort((a, b) => a.score - b.score || a.depth - b.depth || a.path.localeCompare(b.path))
|
||||
|
||||
// An exact leaf living under several namespaces is unroutable — staying silent
|
||||
// beats guessing an arbitrary one.
|
||||
const best = scored[0]?.score
|
||||
const tied = scored.filter(item => item.score === best)
|
||||
if (tied.length >= 2 && tied.every(item => item.spelling === 0))
|
||||
return []
|
||||
const tied = scored.filter((item) => item.score === best)
|
||||
if (tied.length >= 2 && tied.every((item) => item.spelling === 0)) return []
|
||||
|
||||
return scored.map(item => item.path)
|
||||
return scored.map((item) => item.path)
|
||||
}
|
||||
|
||||
export function findSuggestions(tree: CommandTree, argv: string[]): string[] {
|
||||
const results: string[] = []
|
||||
|
||||
function collectAll(node: CommandNode, path: string[]): void {
|
||||
if (node.command && node.command.hidden !== true)
|
||||
results.push(buildPath(path))
|
||||
for (const [key, child] of Object.entries(node.subcommands))
|
||||
collectAll(child, [...path, key])
|
||||
if (node.command && node.command.hidden !== true) results.push(buildPath(path))
|
||||
for (const [key, child] of Object.entries(node.subcommands)) collectAll(child, [...path, key])
|
||||
}
|
||||
|
||||
function traverse(nodes: Record<string, CommandNode>, tokens: string[], path: string[]): void {
|
||||
const token = tokens[0]
|
||||
if (token === undefined || token.startsWith('-'))
|
||||
return
|
||||
if (token === undefined || token.startsWith('-')) return
|
||||
|
||||
const rest = tokens.slice(1)
|
||||
const nextToken = rest.at(0)
|
||||
for (const [key, node] of Object.entries(nodes)) {
|
||||
if (editDistance(token, key) <= 1) {
|
||||
const newPath = [...path, key]
|
||||
if (nextToken === undefined || nextToken.startsWith('-') || Object.keys(node.subcommands).length === 0) {
|
||||
if (
|
||||
nextToken === undefined ||
|
||||
nextToken.startsWith('-') ||
|
||||
Object.keys(node.subcommands).length === 0
|
||||
) {
|
||||
collectAll(node, newPath)
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
traverse(node.subcommands, rest, newPath)
|
||||
}
|
||||
}
|
||||
@@ -195,8 +181,7 @@ export function findSuggestions(tree: CommandTree, argv: string[]): string[] {
|
||||
// Same-level typos and namespace listing first; only fall back to
|
||||
// cross-namespace scoring when the level-by-level walk finds nothing.
|
||||
traverse(tree, argv, [])
|
||||
if (results.length > 0)
|
||||
return results
|
||||
if (results.length > 0) return results
|
||||
|
||||
return scoreFallback(tree, positionalTokens(argv))
|
||||
}
|
||||
@@ -81,8 +81,7 @@ async function captureRun(tree: CommandTree, argv: string[]): Promise<Captured>
|
||||
|
||||
try {
|
||||
await run(tree, argv)
|
||||
}
|
||||
finally {
|
||||
} finally {
|
||||
process.stdout.write = origStdout
|
||||
process.stderr.write = origStderr
|
||||
process.exit = origExit
|
||||
@@ -172,7 +171,9 @@ describe('run() catch routing', () => {
|
||||
it('routes Server5xx error with http_status line and generic exit', async () => {
|
||||
class Throwing extends Command {
|
||||
async run(_argv: string[]) {
|
||||
throw HttpClientError.from(newError(ErrorCode.Server5xx, 'upstream boom')).withHttpStatus(502)
|
||||
throw HttpClientError.from(newError(ErrorCode.Server5xx, 'upstream boom')).withHttpStatus(
|
||||
502,
|
||||
)
|
||||
}
|
||||
}
|
||||
const result = await captureRun(makeTree(Throwing), ['cmd'])
|
||||
@@ -219,7 +220,9 @@ describe('run() catch routing', () => {
|
||||
}
|
||||
}
|
||||
const result = await captureRun(makeTree(Throwing), ['cmd', '-o', 'json'])
|
||||
expect(result.stderr).toBe(`${JSON.stringify({ error: { code: 'unknown', message: 'boom' } })}\n`)
|
||||
expect(result.stderr).toBe(
|
||||
`${JSON.stringify({ error: { code: 'unknown', message: 'boom' } })}\n`,
|
||||
)
|
||||
expect(result.exit).toBe(ExitCode.Generic)
|
||||
expect(result.stdout).toBe('')
|
||||
})
|
||||
@@ -269,11 +272,9 @@ describe('run() catch routing', () => {
|
||||
}) as typeof process.stderr.write
|
||||
try {
|
||||
await run(makeTree(Throwing), ['cmd', '-o', 'json'])
|
||||
}
|
||||
catch (e) {
|
||||
} catch (e) {
|
||||
expect((e as Error).message).toBe('__exit__')
|
||||
}
|
||||
finally {
|
||||
} finally {
|
||||
process.exit = origExit
|
||||
process.stderr.write = origStderr
|
||||
}
|
||||
@@ -311,10 +312,10 @@ describe('run() catch routing', () => {
|
||||
|
||||
async run(_argv: string[]) {}
|
||||
}
|
||||
const result = await captureRun(
|
||||
{ cmd: { command: CtorBang, subcommands: {} } },
|
||||
['cmd', '--output=json'],
|
||||
)
|
||||
const result = await captureRun({ cmd: { command: CtorBang, subcommands: {} } }, [
|
||||
'cmd',
|
||||
'--output=json',
|
||||
])
|
||||
expect(result.stderr).toContain('"code":"unknown"')
|
||||
expect(result.stderr).toContain('"message":"ctor-bang"')
|
||||
expect(result.exit).toBe(ExitCode.Generic)
|
||||
@@ -333,7 +334,7 @@ describe('hidden commands', () => {
|
||||
async run() {}
|
||||
}
|
||||
const tree: CommandTree = {
|
||||
'visible': { command: Visible, subcommands: {} },
|
||||
visible: { command: Visible, subcommands: {} },
|
||||
'secret-debug': { command: Hidden, subcommands: {} },
|
||||
}
|
||||
const result = await captureRun(tree, [])
|
||||
@@ -354,7 +355,7 @@ describe('hidden commands', () => {
|
||||
const tree: CommandTree = {
|
||||
topic: {
|
||||
subcommands: {
|
||||
'public': { command: Public, subcommands: {} },
|
||||
public: { command: Public, subcommands: {} },
|
||||
'debug-only': { command: HiddenSub, subcommands: {} },
|
||||
},
|
||||
},
|
||||
@@ -368,7 +369,9 @@ describe('hidden commands', () => {
|
||||
let ran = false
|
||||
class Hidden extends Command {
|
||||
static hidden = true
|
||||
async run() { ran = true }
|
||||
async run() {
|
||||
ran = true
|
||||
}
|
||||
}
|
||||
const tree: CommandTree = {
|
||||
'secret-debug': { command: Hidden, subcommands: {} },
|
||||
@@ -390,9 +393,7 @@ describe('deprecated commands', () => {
|
||||
old: { command: Old, subcommands: {} },
|
||||
}
|
||||
const result = await captureRun(tree, ['old'])
|
||||
expect(result.stderr).toBe(
|
||||
'deprecated: use `difyctl run app` instead; removal in 2.0\n',
|
||||
)
|
||||
expect(result.stderr).toBe('deprecated: use `difyctl run app` instead; removal in 2.0\n')
|
||||
expect(result.stdout).toBe('old-ran\n')
|
||||
expect(result.exit).toBeUndefined()
|
||||
})
|
||||
@@ -467,7 +468,9 @@ describe('run() help routing', () => {
|
||||
|
||||
it('does not print trailing whitespace on group rows', async () => {
|
||||
const groupTree: CommandTree = {
|
||||
auth: { subcommands: { devices: { subcommands: { list: { command: GetApp, subcommands: {} } } } } },
|
||||
auth: {
|
||||
subcommands: { devices: { subcommands: { list: { command: GetApp, subcommands: {} } } } },
|
||||
},
|
||||
}
|
||||
const result = await captureRun(groupTree, ['help'])
|
||||
expect(result.stdout).not.toMatch(/ \n/)
|
||||
@@ -548,7 +551,7 @@ describe('run() help routing', () => {
|
||||
expect(result.exit).toBeUndefined()
|
||||
expect(result.stdout).not.toContain('COMMANDS')
|
||||
const parsed = JSON.parse(result.stdout) as { commands: Array<{ command: string }> }
|
||||
expect(parsed.commands.map(c => c.command)).toEqual([
|
||||
expect(parsed.commands.map((c) => c.command)).toEqual([
|
||||
'auth login',
|
||||
'auth devices list',
|
||||
'auth devices revoke',
|
||||
|
||||
+17
-28
@@ -14,10 +14,8 @@ export async function run(tree: CommandTree, argv: string[]): Promise<void> {
|
||||
const helpArgv: string[] = []
|
||||
|
||||
for (const a of argv) {
|
||||
if (a === 'help' || a === '--help' || a === '-h')
|
||||
continue
|
||||
if (a.startsWith('-'))
|
||||
break
|
||||
if (a === 'help' || a === '--help' || a === '-h') continue
|
||||
if (a.startsWith('-')) break
|
||||
helpArgv.push(a)
|
||||
}
|
||||
|
||||
@@ -48,7 +46,7 @@ export async function run(tree: CommandTree, argv: string[]): Promise<void> {
|
||||
// misses them; surface their subtree instead of erroring. A strict-prefix
|
||||
// match over the full-depth command walk keeps this purely derived.
|
||||
const subtree = collectCommands(tree).filter(
|
||||
c => c.path.length > helpArgv.length && helpArgv.every((token, i) => c.path[i] === token),
|
||||
(c) => c.path.length > helpArgv.length && helpArgv.every((token, i) => c.path[i] === token),
|
||||
)
|
||||
|
||||
if (subtree.length > 0) {
|
||||
@@ -63,8 +61,7 @@ export async function run(tree: CommandTree, argv: string[]): Promise<void> {
|
||||
if (suggestions.length > 0) {
|
||||
process.stderr.write('\nDid you mean:\n')
|
||||
|
||||
for (const s of suggestions.slice(0, 5))
|
||||
process.stderr.write(` ${s}\n`)
|
||||
for (const s of suggestions.slice(0, 5)) process.stderr.write(` ${s}\n`)
|
||||
}
|
||||
|
||||
process.exit(1)
|
||||
@@ -84,8 +81,7 @@ export async function run(tree: CommandTree, argv: string[]): Promise<void> {
|
||||
if (suggestions.length > 0) {
|
||||
process.stderr.write('\nDid you mean:\n')
|
||||
|
||||
for (const s of suggestions.slice(0, 5))
|
||||
process.stderr.write(` ${s}\n`)
|
||||
for (const s of suggestions.slice(0, 5)) process.stderr.write(` ${s}\n`)
|
||||
}
|
||||
|
||||
process.exit(1)
|
||||
@@ -100,15 +96,13 @@ export async function run(tree: CommandTree, argv: string[]): Promise<void> {
|
||||
cmd.processGlobalFlags(commandArgv)
|
||||
|
||||
const output = await cmd.run(commandArgv)
|
||||
if (output !== undefined)
|
||||
process.stdout.write(stringifyOutput(output))
|
||||
}
|
||||
catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'EPIPE')
|
||||
process.exit(0)
|
||||
const e = err instanceof BaseError
|
||||
? err
|
||||
: unknownError(err instanceof Error ? err.message : String(err), err)
|
||||
if (output !== undefined) process.stdout.write(stringifyOutput(output))
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'EPIPE') process.exit(0)
|
||||
const e =
|
||||
err instanceof BaseError
|
||||
? err
|
||||
: unknownError(err instanceof Error ? err.message : String(err), err)
|
||||
const format = sniffOutputFormat(argv)
|
||||
process.stderr.write(`${formatErrorForCli(e, { format, isErrTTY: process.stderr.isTTY })}\n`)
|
||||
process.exit(e.exit())
|
||||
@@ -118,21 +112,16 @@ export async function run(tree: CommandTree, argv: string[]): Promise<void> {
|
||||
export function sniffOutputFormat(argv: readonly string[]): string {
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const t = argv[i]
|
||||
if (t === undefined)
|
||||
continue
|
||||
if (t === '--')
|
||||
return ''
|
||||
if (t === undefined) continue
|
||||
if (t === '--') return ''
|
||||
|
||||
if (t === '--output' || t === '-o') {
|
||||
const next = argv[i + 1]
|
||||
if (next !== undefined && !next.startsWith('-'))
|
||||
return next
|
||||
if (next !== undefined && !next.startsWith('-')) return next
|
||||
continue
|
||||
}
|
||||
if (t.startsWith('--output='))
|
||||
return t.slice('--output='.length)
|
||||
if (t.startsWith('-o='))
|
||||
return t.slice('-o='.length)
|
||||
if (t.startsWith('--output=')) return t.slice('--output='.length)
|
||||
if (t.startsWith('-o=')) return t.slice('-o='.length)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user