mirror of
https://github.com/larksuite/cli.git
synced 2026-09-14 18:42:53 +08:00
5a72b989c1
* feat(sheets): read a sheet prefix in --range as the sheet selector
Eval traces: 707 calls to +cells-get / +csv-get / +csv-put / +cells-set /
+cells-clear died on "specify at least one of --sheet-id or --sheet-name",
and 53% of them had already named the sheet inside --range
("Sheet1!A1:D20"). The sheet was known, only the flag was missing — so the
prefix now fills the selector and the bare A1 range goes to the tool.
Wired on both paths: a PreRunE stage in the sheets ergonomics layer for
standalone commands, and the sub-op translator for +batch-update.
The grammar follows the front-end ref lexer (byted-sheet TractorLexer):
the full-width ! is an equal separator, an unquoted name can contain
neither width (so splitting on the first one is safe), and a quoted name
keeps its doubled-quote escape and may itself contain a "!". Unquoted
names with spaces are accepted here though the lexer rejects them — a
--range flag has none of a formula's tokenizing ambiguity.
sheetNameFromA1 delegates to the same splitter instead of carrying a
second, looser grammar.
Scope guards: an explicit --sheet-id / --sheet-name stays authoritative
and --range passes through untouched, so a disagreeing prefix cannot
silently retarget a write; only --range carries the rewrite, since
+range-copy / +range-move / +range-fill name their destination sheet with
--target-sheet-id.
* fix(sheets): 边框粗细词兜底补齐 hair 与数字线宽
07-28 只修了 border_styles.<side>.style 里的 thin/medium/thick,同族的另外两种
写法仍在报错。对 596 条 trace 做频次统计,边框取值的错法就这几种:
weight 槽 "hair" 476 次 / 19 个用例 ← 本次新增
style 槽 "thin" 1795 次 / 39 个用例 (07-28 已修)
style 槽 "hair" 76 次 / 2 个用例 ← 本次新增
weight 槽 数字 10 次 / 2 个用例 ← 本次新增(07-28 报告 Case 2)
width 键(GSheets) 35 次 / 3 个用例 ← 本次新增
根因是契约把一个视觉概念拆成 style(线型)× weight(粗细)两个字段,而 openpyxl
把两者塞进一个词 Side(border_style="thin"),于是同几个粗细词在两个槽位都会出现。
borderWeightWord 一个函数同时服务两个槽位,挂在 expandBorderAllShorthand 这个唯一
漏斗上,四条载体路径(--border-styles / --cells 内联 / --styles 载荷 /
+workbook-create)一起生效。
weight 先于 style 归一是有意的:{"style":"thin","weight":"1"} 只有等 "1" 先变成
"thin",style 那步才看得出显式 weight 与词义一致而非冲突。显式冲突
(thin + thick)保持报错,不替用户选。
刻意不收:openpyxl 完整线型表(dashDot / mediumDashed / slantDashDot)、VBA
xlContinuous、CSS hidden、Google Sheets SOLID_THICK、line_style / thickness 等
键别名、style 与 weight 装反、px/pt 后缀 —— trace 里全是 0 次;solid_thin、
border_width、border_color 各只有 1 个用例。它们继续走 enum 报错(报错带允许值
和 did-you-mean,一轮能改对),符合本文件顶部的静默别名准入门槛:真实词汇 **且**
跨批次/≥3 任务复现。新增用例里有一条反向断言把这条线钉住。
TestCellsSetStyle_BorderWeightNumberNamesEnum 的探针从数字换成布尔——数字现在会被
归一化,不再走报错路径,enum-over-skeleton 那条文案规则改用布尔来钉。
* feat(sheets): accept the openpyxl-habit --cells shapes and prescribe the rest
The --cells shape family is the single largest client-side rejection cluster
for +cells-set in the eval corpus. Traced against 14,024 real calls it splits
into two habits, and each gets the treatment its ambiguity allows.
Accepted outright, both unambiguous, both on the existing jsonFlagNormalizers
seam (so --writes items and +batch-update sub-ops get them too):
- {"cells": […]} envelope — an agent generating the payload in a script
writes json.dump({"cells": cells}, f), mistaking the flag name for a JSON
key. 11 of 21 traced `expected type "array", got "object"` rejections are
this exact shape. Only a lone "cells" key unwraps; siblings mean the
object is the whole tool input and dropping them would write elsewhere.
- bare scalars in cell slots — the openpyxl / gspread habit of passing a
plain values matrix, which real rows mix with cell objects as soon as a
formula appears (["1","电动大门",10331.00,{"formula":"=D2*E2"}]).
null is deliberately left failing: {} (leave the cell alone) and
{"value":""} (write an empty string) are both plausible readings, and the
normalizer only rewrites what is beyond doubt.
Renamed silently on the same grounds: --values is what gspread calls the
payload, and what this CLI's own +workbook-create calls its untyped 2D data.
Because bare scalars now lift into {"value":…}, the plain matrix a --values
caller passes ('[["工作内容"]]') is already accepted verbatim under --cells —
the name was the only thing wrong, which puts it in commandFlagAliases rather
than the prescription table. That drops the round trip a prescription costs
(eval F8: 170 hits, 1.9% of failures) and covers the +batch-update sub-op
path, which reads the same alias table and would otherwise get no hint at all
(a prescription only rides on cobra's unknown-flag branch).
Inferred, matching the libraries these callers arrive from: a bare
single-cell --range is now an anchor, sized from the payload — the same
inference +csv-put already does for --start-cell. The range resolves locally
and ships in full, so the server still gets the strict match it enforces. An
explicit extent ("A1:A1", "A1:C10") is never inferred over.
Prescribed, because it cannot be guessed safely: the cells-vs-range mismatch
(132 rejections across 93 case-runs) now reports both axes at once and hands
back the range that fits the payload, plus the inclusive-end note that
explains its biggest sub-bucket — A1:C10 being 10 rows. Growing the range
would overwrite rows the caller never mentioned and shrinking it would drop
data, so the choice stays with the caller. Ragged rows get their own message
instead of being reported as a range mismatch.
Supporting refactor: parseCellRange replaces the prefix-strip / split-on-":"
/ splitCellRef triplication (rangeDimensions becomes a thin wrapper, its
error wording kept byte-for-byte since +styles-put surfaces it verbatim), and
cellsExtent is the one authority on whether a payload is rectangular, so the
anchor expansion and the dimension check cannot disagree. Two bugs fell out
of the new tests: a leading space before the sheet name survived into every
rendered range, and a payload of empty rows would have rendered a malformed
suggestion.
* fix(sheets): parse the sheet part of a range with the ref lexer's grammar
parseCellRange cut the sheet off with strings.Index(range, "!"), which
disagrees with the grammar splitRangeSheetPrefix already implements from the
front-end ref lexer (byted-sheet TractorLexer.ts). Two spellings the lexer
treats as ordinary therefore failed to parse at all:
--range '甘特图!B3' full-width separator (ExclamationMark accepts it)
--range "'Q1!Actual'!B3" quoted name owning a "!" (quotes delimit, so it may)
An unparsable range is deliberately deferred ("the range validator's job"),
so the failure was silent in both directions: the anchor never expanded and
the dimension mismatch never got its prescription. Reachable whenever the
prefix survives to the shortcut — an explicit --sheet-id/--sheet-name keeps
it (the selector rewrite only fires when the pair is empty), as do
--source-range / --target-range, which that rewrite deliberately skips.
The grammar now lives in one place. scanSheetQualifier reports the parsed
sheet name AND the byte offset just past the separator; splitRangeSheetPrefix
is rewritten on top of it (all 20 of its grammar cases unchanged), and
parseCellRange slices the qualifier off at that offset. The offset is the
point: a range rendered from a parse is both shipped to the server and
printed for the caller to paste back, so the qualifier has to survive
verbatim — quotes, full-width separator and all — which a name parsed and
re-quoted could not promise.
Naming, while here: cellRange.prefix said where the field sits, not what it
holds. It is now sheetQualifier (verbatim, separator included) alongside
sheetName (parsed, unquoted) — the sheet a range names is what the type is
about, and the next caller that needs it should not reach for the raw string.
* fix(sheets): close the four gaps the PR review found
Anchor expansion no longer sizes a sheet-qualified range. Such a range only
reaches expandAnchorRange beside an explicit --sheet-id / --sheet-name, since
all three entry points fold the prefix into the selector when none was given —
so the prefix is one that disagrees with the selector, and sizing it shipped
{"range":"Sheet1!A1:B2","sheet_name":"Other"} where the pre-anchor CLI had
failed locally with the cells-vs-range mismatch. Trading a local prescription
for a wire payload whose two halves name different sheets is the wrong
direction; a qualified anchor stays a mismatch.
--writes items now really do get the payload rewrites. cellsSetWritesOps gives
each item the standalone pipeline through a per-item flag view, but that runs
after requireJSONArray has validated the array, so an item spelling its payload
"values" or wrapping it in a {"cells": …} envelope died on the array schema
while the identical +batch-update sub-op was accepted. The rewrites move onto
the jsonFlagNormalizers seam for --writes, one step ahead of the schema, so the
two spellings of the same write agree. values → cells only when "cells" is
absent: two spellings with different payloads stays normalizeSubOpInputKeys'
conflict to report.
The derived selector is left as the only spelling of itself.
normalizeSubOpInputKeys keeps a duplicate key whose two values agree rather
than erroring, and two empty strings agree — so an input carrying both
"sheet-name":"" and "sheet_name":"" kept the hyphen form, which lookupRaw finds
first and which then shadowed the sheet_name just derived from the range
prefix, failing as "specify at least one of --sheet-id or --sheet-name".
Test coverage the review asked for: a +batch-update dry-run case for the prefix
rewrite (the sub-op path had unit coverage but no E2E), and the two tests that
grepped a rendered envelope now decode the dry-run body and assert the fields
that reach the wire.
* test(sheets): cover the accepted input shapes against a real spreadsheet
The dry-run E2E pins what the CLI builds; nothing pinned that the backend
takes it. That gap matters more for rewrites than for ordinary flags: each one
turns a caller spelling into a wire payload the caller never sees, so a payload
the server rejects would be a worse outcome than the client-side error it
replaced.
TestSheets_CallCompatWorkflow writes through a sheet-qualified --range with no
selector flag at all, with bare scalars in the cell slots and a bare A1 acting
as an anchor — three rewrites composed in one call — then reads back through
the same prefix and stamps an openpyxl "hair" border over the result. The sheet
is named with a space in it so the prefix takes its quoted form, the spelling
the ref-lexer grammar exists for and the one a first-ASCII-"!" split would cut
in half.
The read-back compares values collected out of the decoded payload rather than
a fixed path: get_cell_ranges' response nesting is the backend's to change and
is pinned nowhere in this repo, while the values having survived the round trip
is the actual claim. The number is compared numerically for the same reason.
Self-contained: it builds its own workbook, and createSpreadsheet's cleanup
tears it down. Skips without tenant credentials, so local runs are unaffected
and CI's e2e-live job is what exercises it.
* feat(sheets): answer +sheet-list instead of failing the guess
Callers reach for +sheet-list on their own: the sheets surface has a whole
+sheet-* family (+sheet-create / +sheet-copy / +sheet-delete / +sheet-info),
so "list the sheets" spells itself that way. The miss does not self-correct
either, because internal/suggest ranks shared prefixes first: the "did you
mean" hint points at +sheet-create and its siblings, never at +workbook-info.
Add it as a read-only projection over get_workbook_structure emitting the bare
sheets array, entry-for-entry identical to what +workbook-info nests under
sheets. Hidden from `sheets --help` here, and from the lark-sheets skill docs
via sheet-skill-spec's doc_hidden_shortcuts, so neither surface offers a second
name for what +workbook-info already does; the command only ever answers a
caller who typed it anyway.
data/flag-defs.json and flag_defs_gen.go carry the new shortcut's flag entry,
sourced from sheet-skill-spec's spec-tables.
* feat(sheets): prescribe the real command for invented subcommand names
Callers reach for subcommand names this CLI does not have, borrowed from
neighbouring ecosystems. The framework answers an unknown name by edit distance
over the group's children; that ranking is prefix-weighted, so it cannot settle
a name whose answer shares no prefix with it, or one whose same-prefix siblings
crowd the answer out. Those names now get a curated prescription instead: the
command they meant plus its exact retry form, so the next attempt needs no
--help round trip.
Prescribed, never rewritten. Unlike a flag, silently resolving a subcommand
would run a write the caller never named, and the same information fits in the
error the failed call already returns. Every entry is a naming miss rather than
a missing capability — each intent already has a command — and a rare spelling
stays with the ranker rather than growing the table.
The hook is the group's Args validator, which cobra runs before the group's
RunE. That ordering is what keeps this inside sheets: the framework's
unknown-subcommand guard installs on RunE and never touches Args, so the two
compose and every unclaimed name still reaches the ranked "did you mean one
of: …" unchanged. The message stays byte-identical to the guard's, since the
name genuinely does not exist; only the hint and the machine-readable
suggestion change.
Targets resolve against the live tree rather than the table. All of them are
write commands, so a concealed distribution or a user policy of max_risk: read
replaces one with a hidden deny stub; prescribing it then would name a command
that can only answer command_unavailable, and that the ranker has already
stopped suggesting. The check mirrors the ranker's filter, and doubles as a
runtime backstop when a target vanishes in a rename.
Known gap: +batch-update validates sub-op shortcut names against its own
allow-list, so an invented name inside --operations still gets the generic
"not allowed" dump instead of the prescription.
Tests pin the two invariants that make the table safe to extend — a target must
exist, and a key must not shadow a real command (checked against backward's
aliases too, which mount on the same group) — plus the registration itself, so
deleting the wiring fails the suite instead of silently reverting the CLI to
generic suggestions.
* fix(sheets): keep a non-finite line width off the thickness mapping
strconv.ParseFloat answers yes to "Inf" / "Infinity" / "NaN", so a quoted
non-finite weight entered the numeric-width branch and came back out as
"thick" with exit 0 — the CLI guessing at input that means nothing. NaN
only escaped that by accident (every comparison against it is false).
borderLineWidth now reports a non-finite result as "not a width", which
puts both back on the enum error path that names thin / medium / thick.
Also closes the review's test-coverage gaps: hair in the style slot pins
the canonical style ("solid") next to the weight in both the corpus and
the dry-run e2e, the numeric-width table gains its two ends (3 is where
thick starts, 0 keeps its own type error), and splitRangeSheetPrefix
covers the backslash-escaped separator after a quoted name.
* fix(sheets): parse --ranges prefixes with the shared grammar, budget every cells shape
Three gaps the review found, each reproduced against a built binary first.
--ranges kept its own strings.Index("!") splitter, so the four separator
spellings the rest of the PR unified on stopped at the flag boundary:
"工作表1!A1:B2" was rejected as carrying no sheet prefix at all, and
"'My Sheet'!A1:B2" shipped sheet_name "'My Sheet'" — quotes included — for
the backend to fail on as sheet-not-found. Both the up-front prefix check
and splitSheetPrefixedRange now go through scanSheetQualifier /
splitRangeSheetPrefix, which keeps the two error messages' division of
labour: no qualifier at all is "must include a sheet prefix", an empty
side is "must use sheet!range form".
estimatedBatchOpCells ran before the translator's normalizers but read the
wire shape only, so a {"cells": …} envelope, a lone cell object, and a
payload spelled "values" each scored zero cells and materialized outside
the batch-wide safety budget. It unwraps the shape now — no mutation, the
per-cell rewrites stay the translator's and change no count.
sheetNameFromA1 lost "Sheet1!" when it moved onto splitRangeSheetPrefix,
which requires a non-empty range; a prefix with no range still names a
sheet, and pivotPlacementWarn is more use naming it than falling back to
the generic wording. It reads the qualifier directly instead.
* fix(sheets): make the +cells-put prescription validate, and type the range assertions
The +cells-put hint replaces the ranked candidate list, so it is the whole
of what a caller gets back — and it prescribed a 1×2 matrix against A1:B2,
which fails the cells-vs-range check the same call would hit, plus prose
forbidding the bare scalars this branch now accepts. It spells a matching
2×2 scalar matrix and both accepted cell forms instead.
TestPrescribedExamplesActuallyValidate pulls the flags back out of the hint
and runs them through +cells-set, so the prose cannot drift from what the
validator takes; restoring the old hint fails it with the very error the
caller would have seen.
splitSheetPrefixedRange's rejection cases asserted only that an error came
back, which an untyped one would satisfy. They now go through
requireValidation and pin the --range attribution and the offending input
in the message.
265 lines
9.0 KiB
Go
265 lines
9.0 KiB
Go
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
package sheets
|
||
|
||
import (
|
||
"errors"
|
||
"regexp"
|
||
"strings"
|
||
"testing"
|
||
|
||
"github.com/spf13/cobra"
|
||
|
||
"github.com/larksuite/cli/errs"
|
||
"github.com/larksuite/cli/shortcuts/sheets/backward"
|
||
)
|
||
|
||
// registeredCommands is every name mounted on the sheets group: this package's
|
||
// shortcuts plus the pre-refactor aliases in backward, since registration mounts
|
||
// both onto the same parent.
|
||
func registeredCommands(t *testing.T) map[string]bool {
|
||
t.Helper()
|
||
names := map[string]bool{}
|
||
for _, s := range Shortcuts() {
|
||
names[s.Command] = true
|
||
}
|
||
for _, s := range backward.Shortcuts() {
|
||
names[s.Command] = true
|
||
}
|
||
if len(names) == 0 {
|
||
t.Fatal("no sheets shortcuts registered; the assertions below would pass vacuously")
|
||
}
|
||
return names
|
||
}
|
||
|
||
// sheetsGroupWithHints mounts every prescribed target, since the hook resolves
|
||
// targets against the live tree.
|
||
func sheetsGroupWithHints() *cobra.Command {
|
||
svc := &cobra.Command{Use: "sheets"}
|
||
root := &cobra.Command{Use: "lark-cli"}
|
||
root.AddCommand(svc)
|
||
mounted := map[string]bool{}
|
||
for _, rx := range unknownSubcommandHints {
|
||
if mounted[rx.Command] {
|
||
continue
|
||
}
|
||
mounted[rx.Command] = true
|
||
svc.AddCommand(&cobra.Command{
|
||
Use: rx.Command,
|
||
RunE: func(*cobra.Command, []string) error { return nil },
|
||
})
|
||
}
|
||
InstallUnknownSubcommandHints(svc)
|
||
return svc
|
||
}
|
||
|
||
// A rename on the target side would turn a hint into the very failure it was
|
||
// written to fix: an agent sent to a subcommand the CLI rejects.
|
||
func TestPrescribedTargetsExist(t *testing.T) {
|
||
real := registeredCommands(t)
|
||
|
||
for typed, rx := range unknownSubcommandHints {
|
||
if rx.Command == "" {
|
||
t.Errorf("%s prescribes no command; a name that points at more than one belongs with the ranker", typed)
|
||
continue
|
||
}
|
||
if !real[rx.Command] {
|
||
t.Errorf("%s prescribes %q, which is not a registered sheets shortcut", typed, rx.Command)
|
||
}
|
||
}
|
||
}
|
||
|
||
// The hook answers before cobra dispatches, so a key naming a real command would
|
||
// shadow a working command with an error.
|
||
func TestPrescribedNamesAreNotRealCommands(t *testing.T) {
|
||
real := registeredCommands(t)
|
||
|
||
for typed := range unknownSubcommandHints {
|
||
if real[typed] {
|
||
t.Errorf("%s is a registered shortcut; the hook would shadow it", typed)
|
||
}
|
||
}
|
||
}
|
||
|
||
// The hint replaces the ranked candidate list, so an empty one leaves the caller
|
||
// with less than they had.
|
||
func TestEveryPrescriptionCarriesAHint(t *testing.T) {
|
||
for typed, rx := range unknownSubcommandHints {
|
||
if strings.TrimSpace(rx.Hint) == "" {
|
||
t.Errorf("%s has no hint", typed)
|
||
}
|
||
if !strings.Contains(rx.Hint, rx.Command) {
|
||
t.Errorf("%s: hint should spell the target %q so the prose and the machine-readable suggestion agree, got %q",
|
||
typed, rx.Command, rx.Hint)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestPrescribedExamplesActuallyValidate runs the flags a hint spells out
|
||
// through the command it names. A hint is the only thing the caller gets back —
|
||
// the ranked candidate list is replaced — so one whose own example fails
|
||
// validation costs them a round trip and teaches the wrong shape. The +cells-put
|
||
// hint shipped exactly that: a 1×2 matrix against A1:B2, plus prose forbidding
|
||
// the bare scalars this domain now accepts.
|
||
func TestPrescribedExamplesActuallyValidate(t *testing.T) {
|
||
t.Parallel()
|
||
// Pull the example out of the hint rather than restating it, so prose and
|
||
// assertion cannot drift apart.
|
||
flagRe := regexp.MustCompile(`--range (\S+) --cells '([^']*)'`)
|
||
m := flagRe.FindStringSubmatch(unknownSubcommandHints["+cells-put"].Hint)
|
||
if m == nil {
|
||
t.Fatalf("+cells-put hint no longer spells a --range/--cells example: %q", unknownSubcommandHints["+cells-put"].Hint)
|
||
}
|
||
if _, _, err := runShortcutCapturingErr(t, CellsSet, []string{
|
||
"--url", testURL,
|
||
"--sheet-name", "S1",
|
||
"--range", m[1],
|
||
"--cells", m[2],
|
||
"--dry-run",
|
||
}); err != nil {
|
||
t.Errorf("the +cells-put hint prescribes --range %s --cells %s, which does not validate: %v", m[1], m[2], err)
|
||
}
|
||
}
|
||
|
||
// Pinned so a table edit that drops one of these fails here instead of silently
|
||
// regressing.
|
||
func TestCoreEntriesArePinned(t *testing.T) {
|
||
pinned := map[string]string{
|
||
"+sheet-add": "+sheet-create",
|
||
"+col-resize": "+cols-resize",
|
||
}
|
||
|
||
for typed, want := range pinned {
|
||
rx, ok := unknownSubcommandHints[typed]
|
||
if !ok {
|
||
t.Errorf("%s is not prescribed", typed)
|
||
continue
|
||
}
|
||
if rx.Command != want {
|
||
t.Errorf("%s prescribes %q, want %q", typed, rx.Command, want)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestHookReturnsPrescriptionAsValidationError(t *testing.T) {
|
||
svc := sheetsGroupWithHints()
|
||
|
||
err := svc.Args(svc, []string{"+sheet-add"})
|
||
var verr *errs.ValidationError
|
||
if !errors.As(err, &verr) {
|
||
t.Fatalf("expected *errs.ValidationError, got %T", err)
|
||
}
|
||
// The name genuinely does not exist, so the message stays byte-compatible
|
||
// with the framework guard's wording; only the hint improves.
|
||
if verr.Message != `unknown subcommand "+sheet-add" for "lark-cli sheets"` {
|
||
t.Errorf("message = %q, want the framework guard's wording", verr.Message)
|
||
}
|
||
if !strings.Contains(verr.Hint, "+sheet-create") {
|
||
t.Errorf("hint should name the real command, got %q", verr.Hint)
|
||
}
|
||
if len(verr.Params) != 1 || len(verr.Params[0].Suggestions) != 1 ||
|
||
verr.Params[0].Suggestions[0] != "+sheet-create" {
|
||
t.Errorf("the prescribed command should be the sole machine-readable suggestion, got %+v", verr.Params)
|
||
}
|
||
}
|
||
|
||
// Names this table does not claim must reach the framework's ranked path: nil is
|
||
// what lets cobra proceed to the guard's RunE.
|
||
func TestUnclaimedNamesFallThrough(t *testing.T) {
|
||
svc := sheetsGroupWithHints()
|
||
|
||
// Near-miss spellings this table deliberately does not claim.
|
||
for _, name := range []string{
|
||
"+searh", "+bogus-xyz", "+cells-get",
|
||
"+sheet-list", "+columns-resize", "+col-size-set", "+column-set-width",
|
||
"+columns-set-width", "+cells-set-column-width", "+dimension-size",
|
||
} {
|
||
if err := svc.Args(svc, []string{name}); err != nil {
|
||
t.Errorf("Args(%q) = %v, want nil so the framework ranking still answers", name, err)
|
||
}
|
||
}
|
||
// A bare group carries no args at all and must still reach its help path.
|
||
if err := svc.Args(svc, nil); err != nil {
|
||
t.Errorf("Args(nil) = %v, want nil", err)
|
||
}
|
||
}
|
||
|
||
// Underscore and casing variants reach the same entry, so the table stays keyed
|
||
// by the canonical name alone.
|
||
func TestHookFoldsUnderscoreAndCase(t *testing.T) {
|
||
svc := sheetsGroupWithHints()
|
||
|
||
for _, typed := range []string{"+sheet_add", "+Sheet-Add", "+SHEET_ADD"} {
|
||
err := svc.Args(svc, []string{typed})
|
||
var verr *errs.ValidationError
|
||
if !errors.As(err, &verr) {
|
||
t.Errorf("Args(%q) = %v, want the +sheet-add prescription", typed, err)
|
||
continue
|
||
}
|
||
// The message echoes the name as typed, not the folded key.
|
||
if !strings.Contains(verr.Message, typed) {
|
||
t.Errorf("message should echo %q as typed, got %q", typed, verr.Message)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Compose with, not discard, an Args validator already on the group: a later
|
||
// framework change that sets one must not be silently dropped.
|
||
func TestInstallPreservesAnInheritedValidator(t *testing.T) {
|
||
svc := &cobra.Command{Use: "sheets"}
|
||
svc.AddCommand(&cobra.Command{
|
||
Use: "+sheet-create",
|
||
RunE: func(*cobra.Command, []string) error { return nil },
|
||
})
|
||
sentinel := errors.New("inherited validator ran")
|
||
svc.Args = func(*cobra.Command, []string) error { return sentinel }
|
||
|
||
InstallUnknownSubcommandHints(svc)
|
||
|
||
if err := svc.Args(svc, []string{"+bogus"}); !errors.Is(err, sentinel) {
|
||
t.Errorf("unclaimed name should reach the inherited validator, got %v", err)
|
||
}
|
||
// A claimed name is still answered here, ahead of the inherited validator.
|
||
if err := svc.Args(svc, []string{"+sheet-add"}); errors.Is(err, sentinel) {
|
||
t.Error("a prescribed name should be answered by the hook, not the inherited validator")
|
||
}
|
||
}
|
||
|
||
func TestInstallOnNilGroupIsNoop(t *testing.T) {
|
||
InstallUnknownSubcommandHints(nil) // must not panic
|
||
}
|
||
|
||
// A concealed distribution or max_risk: read replaces a target with a hidden
|
||
// deny stub. Prescribing it would name a command that can only answer
|
||
// command_unavailable, and that the ranker has already stopped suggesting.
|
||
func TestConcealedTargetIsNotPrescribed(t *testing.T) {
|
||
svc := sheetsGroupWithHints()
|
||
for _, c := range svc.Commands() {
|
||
if c.Name() == "+sheet-create" {
|
||
c.Hidden = true
|
||
}
|
||
}
|
||
|
||
if err := svc.Args(svc, []string{"+sheet-add"}); err != nil {
|
||
t.Errorf("a concealed target must fall through to the ranker, got %v", err)
|
||
}
|
||
// Sibling prescriptions whose target is still reachable keep working.
|
||
if err := svc.Args(svc, []string{"+col-resize"}); err == nil {
|
||
t.Error("+col-resize target is still visible; its prescription should fire")
|
||
}
|
||
}
|
||
|
||
// A target that vanished outright must not produce a hint pointing at nothing.
|
||
func TestMissingTargetIsNotPrescribed(t *testing.T) {
|
||
svc := &cobra.Command{Use: "sheets"}
|
||
(&cobra.Command{Use: "lark-cli"}).AddCommand(svc)
|
||
InstallUnknownSubcommandHints(svc) // no targets mounted at all
|
||
|
||
for typed := range unknownSubcommandHints {
|
||
if err := svc.Args(svc, []string{typed}); err != nil {
|
||
t.Errorf("Args(%q) = %v, want fall-through when the target is absent", typed, err)
|
||
}
|
||
}
|
||
}
|