Skip to content
Closed
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
12 changes: 11 additions & 1 deletion codegen/functional/kb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,18 @@
* client is the CLI. It maps each `namespace.action` to `stack kb <namespace>
* <command>` and routes params/body to flags, reusing the shared mapper and
* generator that also drive the Elasticsearch functional tests.
*
* Definitions reference upstream `@elastic/schemas` names (e.g. `slo.find_slos_op`).
* Each definition is loaded with a precomputed `cliPath` built by
* `resolveKbCommandName` (which `src/kb/register.ts` also uses), so scripts
* invoke the CLI name (e.g. `stack kb slo list`); the upstream name is not
* registered for renamed commands.
*/

import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs'
import { join, basename } from 'node:path'
import { loadAllKbApis } from '../../src/kb/apis.ts'
import { resolveKbCommandName } from '../../src/kb/command-names.ts'
import { parseTestFile, shouldSkipServerlessProject, shouldSkipStackVersion, stackSinceFor } from './parser.ts'
import stackSince from './stack-since.json' with { type: 'json' }
import { generateScript, generateRunner, type RunnerScript } from './generator.ts'
Expand Down Expand Up @@ -85,7 +92,10 @@ const STREAM_IMPORT_PREAMBLE = [
'CONTENT_PACK="$SCRIPT_DIR/../cli-ft-content-pack.zip"'
]

const apis = await loadAllKbApis()
const apis = (await loadAllKbApis()).map((def) => ({
...def,
cliPath: [def.namespace, resolveKbCommandName(def.namespace, def.name)],
}))

mkdirSync(OUT_DIR, { recursive: true })

Expand Down
13 changes: 13 additions & 0 deletions codegen/functional/test/mapper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { buildActionMap, mapAction } from '../mapper.ts'
import type { EsApiDefinition } from '../../../src/es/types.ts'
import type { ApiActionDef } from '../types.ts'
import { resolveKbCommandName } from '../../../src/kb/command-names.ts'

const testDefs: EsApiDefinition[] = [
{
Expand Down Expand Up @@ -174,4 +176,15 @@ describe('mapAction', () => {
assert.ok(result)
assert.ok(!result.cliArgs.includes('--yes'))
})

it('maps a KB action to its canonical CLI name through cliPath', () => {
const def: ApiActionDef = {
namespace: 'slo',
name: 'find-slos-op',
method: 'GET',
cliPath: ['slo', resolveKbCommandName('slo', 'find-slos-op')],
}
const result = mapAction('slo.find_slos_op', {}, buildActionMap([def]), ['stack', 'kb'])
assert.deepStrictEqual(result?.cliArgs, ['stack', 'kb', 'slo', 'list'])
})
})
30 changes: 15 additions & 15 deletions docs/cli/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -105764,7 +105764,7 @@
"kb",
"slo"
],
"name": "find-slos-op",
"name": "list",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -105877,7 +105877,7 @@
"kb",
"slo"
],
"name": "create-slo-op",
"name": "create",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -105996,7 +105996,7 @@
"kb",
"slo"
],
"name": "bulk-delete-op",
"name": "bulk-delete",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106040,7 +106040,7 @@
"kb",
"slo"
],
"name": "bulk-delete-status-op",
"name": "bulk-delete-status",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106085,7 +106085,7 @@
"kb",
"slo"
],
"name": "delete-rollup-data-op",
"name": "delete-rollup-data",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106142,7 +106142,7 @@
"kb",
"slo"
],
"name": "bulk-snapshot-op",
"name": "bulk-snapshot",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106192,7 +106192,7 @@
"kb",
"slo"
],
"name": "get-definitions-op",
"name": "list-definitions",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106280,7 +106280,7 @@
"kb",
"slo"
],
"name": "delete-slo-instances-op",
"name": "delete-instances",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106323,7 +106323,7 @@
"kb",
"slo"
],
"name": "delete-slo-op",
"name": "delete",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106375,7 +106375,7 @@
"kb",
"slo"
],
"name": "get-slo-op",
"name": "get",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106437,7 +106437,7 @@
"kb",
"slo"
],
"name": "update-slo-op",
"name": "update",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106553,7 +106553,7 @@
"kb",
"slo"
],
"name": "reset-slo-op",
"name": "reset",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106595,7 +106595,7 @@
"kb",
"slo"
],
"name": "get-snapshot-op",
"name": "get-snapshot",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106657,7 +106657,7 @@
"kb",
"slo"
],
"name": "disable-slo-op",
"name": "disable",
"parameters": [
{
"role": "flag",
Expand Down Expand Up @@ -106699,7 +106699,7 @@
"kb",
"slo"
],
"name": "enable-slo-op",
"name": "enable",
"parameters": [
{
"role": "flag",
Expand Down
54 changes: 54 additions & 0 deletions src/kb/command-names.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/

/*
* CLI names for Kibana commands.
*
* Kibana command names come from `@elastic/schemas`, which derives them from Kibana's
* OpenAPI `operationId`s (e.g. `find-slos-op`). This table gives selected commands a
* short CLI name (`list*` for paginated results, `get*` for a single element).
* Commands without an entry keep their upstream name. A renamed command answers to its
* CLI name only: while the CLI is in technical preview, renames are clean breaks.
*
* Keys are upstream `@elastic/schemas` names (`def.name`), which also drive
* `loadKbApi` and request building. When upstream renames one, re-key the entry.
*
* No imports: this module is on the `kb --help` startup path and must not pull in
* schema definitions.
*/

/** CLI names keyed by Kibana namespace, then by upstream `@elastic/schemas` command name. */
export const KB_COMMAND_NAMES: Readonly<Record<string, Readonly<Record<string, string>>>> = {
slo: {
'find-slos-op': 'list',
'create-slo-op': 'create',
'get-slo-op': 'get',
'update-slo-op': 'update',
'delete-slo-op': 'delete',
'enable-slo-op': 'enable',
'disable-slo-op': 'disable',
'reset-slo-op': 'reset',
'get-definitions-op': 'list-definitions',
'get-snapshot-op': 'get-snapshot',
'bulk-snapshot-op': 'bulk-snapshot',
'bulk-delete-op': 'bulk-delete',
'bulk-delete-status-op': 'bulk-delete-status',
'delete-rollup-data-op': 'delete-rollup-data',
'delete-slo-instances-op': 'delete-instances',
},
}

/**
* Resolves the CLI name of a Kibana command.
*
* @param namespace - Kibana namespace of the command (e.g. `slo`)
* @param upstreamName - command name from `@elastic/schemas` (e.g. `find-slos-op`)
* @returns the CLI name; the upstream name when unmapped
*/
export function resolveKbCommandName (namespace: string, upstreamName: string): string {
const entries = Object.hasOwn(KB_COMMAND_NAMES, namespace) ? KB_COMMAND_NAMES[namespace] : undefined
const name = entries != null && Object.hasOwn(entries, upstreamName) ? entries[upstreamName] : undefined
return name ?? upstreamName
}
12 changes: 9 additions & 3 deletions src/kb/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type { AvailabilityTarget } from '../lib/availability.ts'
import { isAvailable, parseVersionHint } from '../lib/availability.ts'
import { getResolvedConfig } from '../config/store.ts'
import { buildStubLeaf } from '../lib/lazy-leaf.ts'
import { resolveKbCommandName } from './command-names.ts'
import { ACCEPT_EXPERIMENTAL_OPTION, warnIfExperimental } from '../lib/experimental.ts'
import type { ExperimentalNotice } from '../lib/experimental.ts'

Expand All @@ -35,7 +36,7 @@ function buildLeafHandle (
validateKbApiDefinition(def)
const intent = def.intent ?? inferIntentFromHttp(def.method)
return defineCommand({
name: def.name,
name: resolveKbCommandName(def.namespace, def.name),
description: def.description,
...(def.input !== undefined ? { input: def.input } : {}),
readOnly: def.method === 'GET' || def.method === 'HEAD',
Expand Down Expand Up @@ -139,6 +140,8 @@ export async function buildKbPresetCommand (opts: KbPresetOptions, deps?: KbHand
/**
* Sniffs `process.argv` to identify which KB leaf command the user
* intends to invoke. Returns `null` on ambiguity or help requests.
* `kb <namespace> <token>` matches CLI names; `kb <token>` matches upstream
* names only, so short CLI names like `list` cannot match across namespaces.
*/
function sniffInvokedLeaf (argv: readonly string[], manifest: readonly KbApiMeta[]): KbApiMeta | null {
const kbIdx = argv.findIndex((a, i) => i >= 2 && (a === 'kb' || a === 'kibana'))
Expand All @@ -147,7 +150,7 @@ function sniffInvokedLeaf (argv: readonly string[], manifest: readonly KbApiMeta
if (afterKb.length === 0) return null
const namespaces = new Set(manifest.map(m => m.namespace))
if (afterKb.length >= 2 && namespaces.has(afterKb[0]!)) {
return manifest.find(m => m.namespace === afterKb[0]! && m.name === afterKb[1]!) ?? null
return manifest.find(m => m.namespace === afterKb[0]! && resolveKbCommandName(m.namespace, m.name) === afterKb[1]!) ?? null
}
if (afterKb.length >= 1 && !namespaces.has(afterKb[0]!)) {
return manifest.find(m => m.name === afterKb[0]!) ?? null
Expand Down Expand Up @@ -200,7 +203,10 @@ export async function registerKbCommandsLazy (

function leafHandleFor (m: KbApiMeta): OpaqueCommandHandle {
if (invoked != null && invokedDef != null && m === invoked) return buildLeafHandle(invokedDef, target)
return buildStubLeaf(m, async () => buildLeafHandle(await loadKbApi(m), target))
return buildStubLeaf(
{ name: resolveKbCommandName(m.namespace!, m.name), description: m.description },
async () => buildLeafHandle(await loadKbApi(m), target),
)
}

const namespaceHandles: OpaqueCommandHandle[] = []
Expand Down
13 changes: 13 additions & 0 deletions test/cli-schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ interface CliParameter {

interface CliCommand {
name: string
aliases?: string[]
parameters: CliParameter[]
}

Expand Down Expand Up @@ -97,4 +98,16 @@ describe('cli schema', () => {
assert.equal(routing?.repeatable, true)
assert.equal(routing?.separator, undefined)
})

it('emits slo commands under their canonical names only', async () => {
const { code, stdout, stderr } = await runCliSchema()
assert.equal(code, 0, stderr)

const schema = JSON.parse(stdout) as { namespaces: CliNamespace[] }
const slo = ['stack', 'kb', 'slo']
const list = findCommand(schema.namespaces, slo, 'list')
assert.ok(list != null)
assert.equal(list.aliases, undefined)
assert.equal(findCommand(schema.namespaces, slo, 'find-slos-op'), undefined)
})
})
24 changes: 24 additions & 0 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,30 @@ describe('elastic CLI -- command and option error ordering', () => {
}
})

it('rejects a renamed kb slo command by its upstream name', async () => {
const dir = await mkdtemp(join(tmpdir(), 'elastic-cli-kb-upstream-name-'))
await writeFile(join(dir, '.elasticrc.yml'), [
'current_context: local',
'contexts:',
' local:',
' kibana:',
' url: http://localhost:5601',
'',
].join('\n'))

try {
const { code, stderr } = await runCli(
['stack', 'kb', 'slo', 'find-slos-op'],
{ cwd: dir, env: { HOME: dir, USERPROFILE: dir, XDG_CONFIG_HOME: dir } }
)

assert.equal(code, 1)
assert.match(stderr, /unknown command: find-slos-op/)
} finally {
await rm(dir, { recursive: true })
}
})

it('suggests the closest sibling for a near misspelling', async () => {
const dir = await mkdtemp(join(tmpdir(), 'elastic-cli-suggest-command-'))
await writeFile(join(dir, '.elasticrc.yml'), [
Expand Down
18 changes: 18 additions & 0 deletions test/completion-cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,24 @@ describe('elastic CLI -- shell completion end-to-end', () => {
assert.ok(out.candidates.includes('search'))
})

it('`__complete -- kb slo ""` lists slo canonical names and no upstream names', async () => {
const { code, stdout } = await runCli(['__complete', '--', 'kb', 'slo', ''])
assert.equal(code, 0)
const out = parseProtocol(stdout)
for (const expected of ['list', 'get']) {
assert.ok(out.candidates.includes(expected), `missing "${expected}" in ${out.candidates.join(',')}`)
}
for (const unexpected of ['find-slos-op', 'get-slo-op']) {
assert.ok(!out.candidates.includes(unexpected), `unexpected "${unexpected}" in ${out.candidates.join(',')}`)
}
})

it('`__complete -- kb slo list --` lists the flags of the leaf reached through its canonical name', async () => {
const { code, stdout } = await runCli(['__complete', '--', 'kb', 'slo', 'list', '--'])
assert.equal(code, 0)
assert.ok(parseProtocol(stdout).candidates.includes('--kql-query'))
})

it('`__complete -- --use-context ""` lists context names from a temp config', async () => {
const dir = await mkdtemp(join(tmpdir(), 'elastic-cli-complete-'))
try {
Expand Down
Loading
Loading