diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..56425b72 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,112 @@ +# Contributing + +## Build and test + +```bash +make build +make test +``` + +`go test ./...` runs on every pull request. It needs no API token: every test +runs offline against fakes. + +## SDK coverage + +The CLI is built on [`latitudesh-go-sdk`](https://github.com/latitudesh/latitudesh-go-sdk). +`sdk-coverage.yaml` at the repository root records, for every SDK method, +which command calls it or why it deliberately has none. A method with no entry +is **pending**, and a group with no entry at all is a new command group waiting +to be added. The file is an exception list, not a work queue: nothing waits on +someone writing a line first. + +See what is pending against the pinned SDK: + +```bash +make coverage-report +go run ./cmd/sdkcoverage report -format markdown +go run ./cmd/sdkcoverage report -format json | jq '.pending' +``` + +Check the manifest against a newer SDK without touching `go.mod`: + +```bash +dir=$(go mod download -json github.com/latitudesh/latitudesh-go-sdk@latest | jq -r '.Dir') +go run ./cmd/sdkcoverage report -sdk-dir "$dir" -format text +``` + +The report lists one suggested command per operation, following the CLI's +own conventions rather than the SDK's method names: + +- a noun the SDK flattened into several CRUD methods (`CreateLksNodePool`, + `ListLksNodePools`, ...) becomes a subgroup with plain verbs + (`lks node-pools create`), like `kubernetes clusters create` today; a noun + that is only listed is a reference collection and becomes a subgroup too + (`lks sites list`, like `kubernetes versions list`); a noun that is only + got and updated is a setting of its parent and stays a hyphenated leaf + (`servers get-deploy-config`); +- one operation reachable through two routes (`POST /virtual_machine_backups` + and `POST /virtual_machines/{id}/backups`) folds into a single suggestion, + since the CLI exposes it as one command with a flag for the parent. The + `methods` array in the JSON output names every SDK method behind a + suggestion. + +These are hints for the tracking issue and the scaffold prompt, not +decisions: the final name is settled when the command is written and mapped +in the manifest. When the UX is decided before the code and the automatic +name would be wrong, record it under `groups..suggested.`: a +BGP session is a server announcing an elastic IP, so it is +`elastic-ips attach --server`, not a `bgp-sessions` subgroup. A suggestion +names a command that does not exist yet. When the method is to be served by +a command the CLI already has (listing BGP sessions inside `elastic-ips +get`), record it under `groups..extends.` instead: the path +must exist, the method stays pending, and the report marks the command +*extend* (`"extends": true` in the JSON) so the scaffold grows it rather than +creating a new one. Do not map it under `commands` until the command +actually calls the method; that is what counts it as covered. + +Inspect the two inputs the tool reconciles: + +```bash +go run ./cmd/sdkcoverage groups +go run ./cmd/sdkcoverage commands +``` + +### Keeping the manifest honest + +`TestCLISDKCoverage` (in `cmd/`) runs with the rest of the suite and fails only +on contradictions: + +- a command path in the manifest that the CLI does not register; +- a method or group the SDK no longer exposes; +- a leaf command that no method claims and that is not listed under + `commands_without_sdk`; +- a method both mapped and excluded, or an exclusion without a known reason; +- a `suggested` command that already exists, or an `extends` command that + does not, or an `extends` entry for a method that is already mapped (the + extension landed: drop the entry); +- a pending method whose automatic name is a command the CLI already has + (`RetrieveVolume` reads as `volume get`): list it under `extends` if that + command is to call it, or give it a new name under `suggested`; +- two SDK groups under one command group proposing the same command. + +An SDK bump that adds methods is not a failure. When you add, rename or remove +a command, update `sdk-coverage.yaml` in the same PR: + +- a new command that calls an SDK method goes under + `groups..commands.`; +- a group whose commands belong under an existing family (VM backups under + `virtual-machines`) declares it with `groups..command_group`, so the + report and the scaffold place them next to their siblings. Set it too when + the first commands you map for a group all sit in one of its subgroups + (only `lks node-pools ...` mapped for an `lks` group): the group is + otherwise inferred as the shortest parent of its mapped commands, and the + remaining suggestions would land inside that subgroup; +- a command that calls no SDK method (local state, self-update) goes under + `commands_without_sdk`; +- a method you looked at and chose not to expose goes under + `groups..excluded.` with a `reason` (`api_constraint`, + `product_decision` or `deprecated`) and, ideally, a note; +- a whole product that is not ready for the CLI (a preview behind a feature + flag) goes under `groups..excluded_group` with the same fields. + +`make coverage-check` runs the same check from the command line. diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..6b797b6e --- /dev/null +++ b/Makefile @@ -0,0 +1,15 @@ +.PHONY: build test coverage-report coverage-check + +build: + go build -o lsh . + +test: + go test ./... + +# SDK coverage: which latitudesh-go-sdk methods have a command. See +# CONTRIBUTING.md, "SDK coverage". +coverage-report: + go run ./cmd/sdkcoverage report -format text + +coverage-check: + go run ./cmd/sdkcoverage check diff --git a/README.md b/README.md index 314b7edc..4daf457a 100755 --- a/README.md +++ b/README.md @@ -289,4 +289,4 @@ For more information, see the documentation. - [Open an issue](https://github.com/latitudesh/cli/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) for questions, feedback, bug reports or feature requests. -- We welcome pull requests for bug fixes, new features, and improvements to the examples. +- We welcome pull requests for bug fixes, new features, and improvements to the examples. See [CONTRIBUTING.md](CONTRIBUTING.md) for how to build, test and keep the SDK coverage manifest up to date. diff --git a/cmd/sdk_coverage_test.go b/cmd/sdk_coverage_test.go new file mode 100644 index 00000000..e26ec8a1 --- /dev/null +++ b/cmd/sdk_coverage_test.go @@ -0,0 +1,53 @@ +package cmd + +import ( + "path/filepath" + "testing" + + "github.com/latitudesh/lsh/internal/sdkcoverage" +) + +// TestCLISDKCoverage keeps sdk-coverage.yaml honest about the gap between what +// latitudesh-go-sdk exposes and what this CLI ships. +// +// It is a static check: no network, no API token. It fails only on +// contradictions: a manifest path the CLI does not register, a method or group +// the SDK no longer exposes, a leaf command no entry claims, or a half-written +// exclusion. An SDK bump that adds methods is NOT a failure: a pending method is +// what triggers scaffolding, and failing would block every bump on a product +// decision its author was never asked to make. Pending work surfaces in +// `go run ./cmd/sdkcoverage report` instead. +func TestCLISDKCoverage(t *testing.T) { + sdkDir, err := sdkcoverage.PinnedModuleDir() + if err != nil { + t.Fatalf("resolving the pinned SDK module: %v", err) + } + surface, err := sdkcoverage.ParseSurface(sdkDir) + if err != nil { + t.Fatalf("parsing the SDK surface at %s: %v", sdkDir, err) + } + + manifestPath := filepath.Join("..", sdkcoverage.ManifestFile) + manifest, err := sdkcoverage.LoadManifest(manifestPath) + if err != nil { + t.Fatalf("loading %s: %v", manifestPath, err) + } + + root, err := Root() + if err != nil { + t.Fatalf("building the command tree: %v", err) + } + leaves := sdkcoverage.LeafCommands(root) + if len(leaves) == 0 { + t.Fatal("the CLI registered no commands; tree introspection is broken") + } + + report := sdkcoverage.Reconcile(surface, manifest, leaves) + for _, v := range report.Violations { + t.Errorf("%s", v) + } + if !report.OK() { + t.Logf("%d SDK group(s) parsed from %s; %d leaf command(s) registered", len(surface.Groups), sdkDir, len(leaves)) + t.Log("fix the mismatch by updating " + sdkcoverage.ManifestFile + " (see its header comment)") + } +} diff --git a/cmd/sdkcoverage/main.go b/cmd/sdkcoverage/main.go new file mode 100644 index 00000000..698ccdd7 --- /dev/null +++ b/cmd/sdkcoverage/main.go @@ -0,0 +1,176 @@ +// Command sdkcoverage reports which latitudesh-go-sdk methods the lsh CLI +// exposes as commands, and fails when the SDK, the coverage manifest and the +// command tree disagree. +// +// Usage: +// +// sdkcoverage report [-format markdown|text|json] [-sdk-dir DIR] +// sdkcoverage check # exit 1 on any violation +// sdkcoverage groups [-sdk-dir DIR] # dump the raw SDK surface +// sdkcoverage commands # dump the CLI's leaf command paths +// +// Everything runs offline against the module cache; no API token is involved. +package main + +import ( + "flag" + "fmt" + "os" + + "github.com/latitudesh/lsh/cmd" + "github.com/latitudesh/lsh/internal/sdkcoverage" +) + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, "sdkcoverage:", err) + os.Exit(1) + } +} + +func run(args []string) error { + if len(args) == 0 { + usage() + return fmt.Errorf("no command given") + } + command := args[0] + flags := flag.NewFlagSet(command, flag.ContinueOnError) + manifestPath := flags.String("manifest", sdkcoverage.ManifestFile, "path to the coverage manifest") + sdkDir := flags.String("sdk-dir", "", "SDK source directory (defaults to the pinned module in the module cache)") + format := flags.String("format", "markdown", "report format: markdown, text or json") + if err := flags.Parse(args[1:]); err != nil { + return err + } + + switch command { + case "groups": + return runGroups(*sdkDir) + case "commands": + return runCommands() + case "report": + return runReport(*manifestPath, *sdkDir, *format) + case "check": + return runCheck(*manifestPath, *sdkDir) + default: + usage() + return fmt.Errorf("unknown command %q", command) + } +} + +func usage() { + fmt.Fprint(os.Stderr, `usage: sdkcoverage [flags] + + report render the coverage report (markdown by default) + check exit non-zero when the SDK, the manifest and the CLI disagree + groups dump the raw SDK service-group surface, for seeding the manifest + commands dump the CLI's leaf command paths + +flags: + -manifest path coverage manifest (default: sdk-coverage.yaml in the working directory) + -sdk-dir path SDK source directory (default: pinned module in the module cache) + -format fmt markdown (default), text or json, for report +`) +} + +func loadSurface(sdkDir string) (sdkcoverage.Surface, string, error) { + if sdkDir == "" { + dir, err := sdkcoverage.PinnedModuleDir() + if err != nil { + return sdkcoverage.Surface{}, "", err + } + sdkDir = dir + } + surface, err := sdkcoverage.ParseSurface(sdkDir) + return surface, sdkDir, err +} + +func leafCommands() ([]string, error) { + root, err := cmd.Root() + if err != nil { + return nil, fmt.Errorf("building the command tree: %w", err) + } + return sdkcoverage.LeafCommands(root), nil +} + +func reconcile(manifestPath, sdkDir string) (sdkcoverage.Report, string, error) { + surface, dir, err := loadSurface(sdkDir) + if err != nil { + return sdkcoverage.Report{}, "", err + } + manifest, err := sdkcoverage.LoadManifest(manifestPath) + if err != nil { + return sdkcoverage.Report{}, "", err + } + leaves, err := leafCommands() + if err != nil { + return sdkcoverage.Report{}, "", err + } + return sdkcoverage.Reconcile(surface, manifest, leaves), sdkcoverage.VersionFromDir(dir), nil +} + +func runGroups(sdkDir string) error { + surface, dir, err := loadSurface(sdkDir) + if err != nil { + return err + } + fmt.Printf("# %s\n# %d groups, %d methods\n\n", dir, len(surface.Groups), surface.MethodCount()) + for _, name := range surface.Names() { + group := surface.Groups[name] + fmt.Println(name) + for _, method := range group.Methods { + fmt.Printf(" - %s\n", method) + } + } + return nil +} + +func runCommands() error { + leaves, err := leafCommands() + if err != nil { + return err + } + for _, leaf := range leaves { + fmt.Println(leaf) + } + return nil +} + +func runReport(manifestPath, sdkDir, format string) error { + report, version, err := reconcile(manifestPath, sdkDir) + if err != nil { + return err + } + switch format { + case "markdown": + fmt.Print(report.Markdown(version)) + case "text": + fmt.Print(report.Text(version)) + case "json": + data, err := report.JSON(version) + if err != nil { + return err + } + fmt.Println(string(data)) + default: + return fmt.Errorf("unsupported report format %q (want markdown, text or json)", format) + } + return nil +} + +func runCheck(manifestPath, sdkDir string) error { + report, version, err := reconcile(manifestPath, sdkDir) + if err != nil { + return err + } + if !report.OK() { + fmt.Fprintf(os.Stderr, "%d violation(s):\n", len(report.Violations)) + for _, v := range report.Violations { + fmt.Fprintf(os.Stderr, " - %s\n", v) + } + return fmt.Errorf("%s is out of sync with the SDK or the command tree", manifestPath) + } + c := report.Counts() + fmt.Printf("ok: %s — %d/%d methods covered, %d excluded, %d pending; %d new top-level command groups\n", + version, c.Covered, c.Methods, c.Excluded, c.Pending, c.NewCommandGroups) + return nil +} diff --git a/internal/sdkcoverage/commands.go b/internal/sdkcoverage/commands.go new file mode 100644 index 00000000..ef05fd81 --- /dev/null +++ b/internal/sdkcoverage/commands.go @@ -0,0 +1,45 @@ +package sdkcoverage + +import ( + "sort" + "strings" + + "github.com/spf13/cobra" +) + +// LeafCommands returns the space-separated path of every command under root +// that does something when run ("servers list", "firewalls assignments +// create"), sorted. Hidden and deprecated commands are skipped, as are cobra's +// own help and completion commands: the manifest describes what users can +// run, not plumbing. +// +// A parent is reported through its children, and also on its own when it is +// runnable: `s3 configure` creates and saves an access key and has an +// `export` child. A parent with no Run only prints help and is not reported. +func LeafCommands(root *cobra.Command) []string { + var leaves []string + var walk func(c *cobra.Command, path []string) + walk = func(c *cobra.Command, path []string) { + for _, sub := range c.Commands() { + if sub.Hidden || sub.Deprecated != "" || !sub.IsAvailableCommand() { + continue + } + name := sub.Name() + if c == root && (name == "help" || name == "completion") { + continue + } + subPath := append(append([]string(nil), path...), name) + if sub.HasAvailableSubCommands() { + if sub.Runnable() { + leaves = append(leaves, strings.Join(subPath, " ")) + } + walk(sub, subPath) + continue + } + leaves = append(leaves, strings.Join(subPath, " ")) + } + } + walk(root, nil) + sort.Strings(leaves) + return leaves +} diff --git a/internal/sdkcoverage/manifest.go b/internal/sdkcoverage/manifest.go new file mode 100644 index 00000000..4dbe4eaf --- /dev/null +++ b/internal/sdkcoverage/manifest.go @@ -0,0 +1,178 @@ +package sdkcoverage + +import ( + "bytes" + "fmt" + "os" + + "gopkg.in/yaml.v3" +) + +// ManifestFile is the manifest's conventional name at the repository root. +const ManifestFile = "sdk-coverage.yaml" + +// SupportedManifestVersion is the only manifest schema version this code +// understands. Bump it together with any breaking change to the layout below. +const SupportedManifestVersion = 1 + +// Reason explains why an SDK method is deliberately not exposed as a command. +// It decides whether the exclusion should ever expire: an API limitation can +// disappear when the API grows, while a product decision does not. +type Reason string + +const ( + // ReasonAPIConstraint means the API does not offer enough to build a usable + // command (a stub, a broken endpoint, a response the SDK cannot decode). + ReasonAPIConstraint Reason = "api_constraint" + + // ReasonProductDecision means the team does not want this on the command + // line, whatever the API offers. + ReasonProductDecision Reason = "product_decision" + + // ReasonDeprecated means the upstream endpoint is going away. + ReasonDeprecated Reason = "deprecated" +) + +// Exclusion records why a method has no command. +type Exclusion struct { + Reason Reason `yaml:"reason"` + Notes string `yaml:"notes,omitempty"` +} + +// Paths is one or more command paths. A method usually backs one subcommand, +// but the mapping is many-to-many: BlockStorage.ListVolumes backs both +// `volume list` and `volume get`, and `servers reinstall` reads Servers.Get +// when it waits. The YAML form accepts a scalar or a list. +type Paths []string + +func (p *Paths) UnmarshalYAML(node *yaml.Node) error { + switch node.Kind { + case yaml.ScalarNode: + var s string + if err := node.Decode(&s); err != nil { + return err + } + *p = Paths{s} + return nil + case yaml.SequenceNode: + var list []string + if err := node.Decode(&list); err != nil { + return err + } + *p = Paths(list) + return nil + } + return fmt.Errorf("line %d: expected a command path or a list of paths", node.Line) +} + +// GroupEntry is the manifest record for one SDK service group. +// +// Coverage is per method: a method listed under Commands is covered by those +// commands, a method under Excluded was looked at and deliberately left out, +// and a method in neither is pending. A group with no entry at all is a new +// command group waiting to be scaffolded, which is why there is no "planned" +// state: nothing waits on a human writing a line first. +type GroupEntry struct { + // CommandGroup is the command path the group's methods live under, or + // should live under once scaffolded ("virtual-machines backups"). The SDK + // splits by resource where the CLI groups by product: VirtualMachineBackups + // and VirtualMachineRestores both belong under `virtual-machines`. When + // unset, the group is inferred from the mapped commands, or from the SDK + // group name for a group with none. + CommandGroup string `yaml:"command_group,omitempty"` + + // Commands maps an SDK method to the command path(s) that call it. Every + // path is verified against the cobra tree. + Commands map[string]Paths `yaml:"commands,omitempty"` + + // Excluded maps an SDK method to the reason it has no command. + Excluded map[string]Exclusion `yaml:"excluded,omitempty"` + + // ExcludedGroup leaves the whole group out with one reason, for a product + // that is not ready for the CLI (a preview behind a feature flag, a niche + // flow). Every method not mapped under Commands counts as excluded; the + // group is not scaffolded and does not show as pending. + ExcludedGroup *Exclusion `yaml:"excluded_group,omitempty"` + + // Suggested overrides the command the report proposes for a pending + // method, for cases where the UX was decided ahead of the code and the + // automatic naming would get it wrong: a BGP session is "a server + // announcing the elastic IP", so it is `elastic-ips attach --server`, not + // a `bgp-sessions` subgroup. The method stays pending; only its name in + // the report and the scaffold prompt changes. Several methods may share a + // suggestion (two routes, one command). + Suggested map[string]string `yaml:"suggested,omitempty"` + + // Extends maps a pending method to the existing command that is to call + // it: the UX grows that command (a flag, a column) instead of adding one. + // Listing an elastic IP's BGP sessions belongs in `elastic-ips get`, which + // does not call ListElasticIPBgpSessions yet. Unlike Suggested, the path + // must be a registered leaf, so a rename is caught; unlike Commands, the + // method stays pending until the command calls it, and the entry then + // moves to Commands. + Extends map[string]string `yaml:"extends,omitempty"` + + // Notes is free-form context for whoever scaffolds or reviews this group + // next. + Notes string `yaml:"notes,omitempty"` +} + +// Manifest is the hand-curated record of intent, keyed by the SDK's dotted group +// path. +type Manifest struct { + Version int `yaml:"version"` + SDKModule string `yaml:"sdk_module"` + Groups map[string]GroupEntry `yaml:"groups"` + + // CommandsWithoutSDK lists leaf commands that call no SDK method: local + // state (login, profile), self-update, or a hand-written HTTP call. They are + // verified against the cobra tree too, so a removed command cannot linger + // here. + CommandsWithoutSDK []string `yaml:"commands_without_sdk,omitempty"` +} + +// LoadManifest reads and parses the manifest at path. +func LoadManifest(path string) (Manifest, error) { + data, err := os.ReadFile(path) + if err != nil { + return Manifest{}, fmt.Errorf("sdkcoverage: reading manifest: %w", err) + } + + var manifest Manifest + // KnownFields makes a typo in a manifest key an error rather than a setting + // that silently does nothing. + decoder := yaml.NewDecoder(bytes.NewReader(data)) + decoder.KnownFields(true) + if err := decoder.Decode(&manifest); err != nil { + return Manifest{}, fmt.Errorf("sdkcoverage: parsing %s: %w", path, err) + } + + if manifest.Version != SupportedManifestVersion { + return Manifest{}, fmt.Errorf( + "sdkcoverage: %s declares version %d, but this build understands version %d", + path, manifest.Version, SupportedManifestVersion) + } + if manifest.SDKModule != SDKModulePath { + return Manifest{}, fmt.Errorf( + "sdkcoverage: %s declares sdk_module %q, but coverage is reconciled against %q", + path, manifest.SDKModule, SDKModulePath) + } + + if manifest.Groups == nil { + manifest.Groups = map[string]GroupEntry{} + } + return manifest, nil +} + +func knownReasons() []Reason { + return []Reason{ReasonAPIConstraint, ReasonProductDecision, ReasonDeprecated} +} + +func validReason(r Reason) bool { + for _, known := range knownReasons() { + if r == known { + return true + } + } + return false +} diff --git a/internal/sdkcoverage/naming.go b/internal/sdkcoverage/naming.go new file mode 100644 index 00000000..99364e01 --- /dev/null +++ b/internal/sdkcoverage/naming.go @@ -0,0 +1,473 @@ +package sdkcoverage + +import ( + "sort" + "strings" +) + +// verbPrefixes maps an SDK method-name prefix to the CLI verb it usually +// becomes. Prefix matching is deliberate: the generated SDK is not consistent +// (SSHKeys.Retrieve, BlockStorage.ListVolumes, PublicNetworks.DestroyPublicNetwork +// all have to land on the right verb). +var verbPrefixes = map[string]string{ + "Create": "create", + "Post": "create", + "Assign": "assign", + "List": "list", + "Get": "get", + "Retrieve": "get", + "Fetch": "get", + "Show": "get", + "Update": "update", + "Patch": "update", + "Put": "update", + "Modify": "update", + "Delete": "delete", + "Destroy": "delete", + "Remove": "delete", + "Lock": "lock", + "Unlock": "unlock", + "Start": "start", + "Exit": "exit", + "Run": "run", + "Reinstall": "reinstall", + "Schedule": "schedule", + "Unschedule": "unschedule", + "Refresh": "refresh", + "Mount": "mount", + "Map": "map", + "Unmap": "unmap", + "Attach": "attach", + "Detach": "detach", + "Exec": "exec", + "Sign": "sign", +} + +// orderedVerbPrefixes is verbPrefixes sorted longest-first so the most specific +// prefix wins: "Unschedule" before "Schedule", "Unlock" before "Lock". +var orderedVerbPrefixes = func() []string { + prefixes := make([]string, 0, len(verbPrefixes)) + for p := range verbPrefixes { + prefixes = append(prefixes, p) + } + sort.Slice(prefixes, func(i, j int) bool { + if len(prefixes[i]) != len(prefixes[j]) { + return len(prefixes[i]) > len(prefixes[j]) + } + return prefixes[i] < prefixes[j] + }) + return prefixes +}() + +// SuggestCommand proposes a command path for an SDK method, e.g. +// Lks.CreateLksNodePool under "lks" → "lks create-node-pool". It is a hint +// for the tracking issue and the scaffold prompt, not a decision: the verb +// comes from the method-name prefix, with the words that merely repeat the SDK +// group or the command group stripped from the remainder. +func SuggestCommand(group Group, groupCommand string, method string) string { + return suggestCommand(group, groupCommand, method, true) +} + +// SuggestSubcommand is SuggestCommand for a group that already has commands +// under groupCommand: the command group's noun is settled (BlockStorage is +// `volume`), so the SDK group's own noun is never reinjected into the leaf. +func SuggestSubcommand(group Group, groupCommand string, method string) string { + return suggestCommand(group, groupCommand, method, false) +} + +func suggestCommand(group Group, groupCommand string, method string, keepGroupNoun bool) string { + groupCommand, verb, rest := splitMethod(group, groupCommand, method, keepGroupNoun) + if verb == "" { + return groupCommand + " " + kebab(method) + } + if rest == "" { + return groupCommand + " " + verb + } + return groupCommand + " " + verb + "-" + kebab(rest) +} + +// splitMethod breaks a method into the command group it lands under, the +// CLI verb and the CamelCase remainder specific to the method. verb is "" +// when no known prefix matches. +func splitMethod(group Group, groupCommand string, method string, keepGroupNoun bool) (string, string, string) { + if groupCommand == "" { + groupCommand = kebab(lastSegment(group.Name)) + } + + verb, rest := "", method + for _, p := range orderedVerbPrefixes { + if strings.HasPrefix(method, p) { + verb, rest = verbPrefixes[p], method[len(p):] + break + } + } + if verb == "" { + return groupCommand, "", method + } + + // Drop the words that just repeat the SDK group ("Lks", "VirtualMachine", + // "ElasticIP") or the command group ("virtual-machines backups" already + // says "backup"), so the leaf is the verb plus what is specific to the + // method. A "Get" whose remainder is the plural noun (GetBaselines, + // GetPublicNetworks) is a list, not a lookup. + rest, plural := stripKnownWords(rest, group, groupCommand) + if verb == "get" && plural && rest == "" { + verb = "list" + } + + // When the SDK group's own noun is absent from the command group, a bare + // method (Create, List) must carry it or two groups sharing a command + // group collide: VirtualMachineRestores and VirtualMachineBackups both map + // under `virtual-machines backups`, so Restores.Create is `backups + // create-restore`, not a second `backups create`. A method that already + // spelled the noun (ObjectStorage.GetStorageAccessKeys) does not get it + // back: the strip above removed it as group noise, on purpose. + if keepGroupNoun && !strings.Contains(method, lastSegment(group.Name)) { + if noun := groupNounOutside(group, groupCommand); noun != "" && !strings.Contains(method, noun) { + rest = noun + rest + } + } + return groupCommand, verb, rest +} + +// crudVerbs are the verbs that, applied to the same noun, mean the noun is a +// resource of its own and deserves a subgroup rather than a hyphenated leaf. +var crudVerbs = map[string]bool{"create": true, "list": true, "get": true, "update": true, "delete": true} + +// collectionAdjectives qualify which members of a collection a list returns +// (ListLksAvailableVersions, ListLksAllocatableServers). The subgroup is the +// collection itself, so they drop out of its name. +var collectionAdjectives = map[string]bool{"available": true, "allocatable": true, "all": true} + +// SuggestCommands proposes one command per method for a whole group at once, +// which lets it spot resources the SDK flattened into method names. A noun +// that is a collection becomes a subgroup named after it with plain verbs +// under it, as `kubernetes clusters create` and `kubernetes versions list` +// already read: +// +// - a noun seen with several CRUD verbs (CreateLksNodePool, GetLksNodePool, +// ListLksNodePools, ...) is a resource: `lks node-pools create`; +// - a noun seen with list alone (ListLksSites, ListLksAvailableVersions) is +// a reference collection: `lks sites list`, `lks versions list`; +// - a noun seen only with get and update (Servers.GetDeployConfig / +// UpdateDeployConfig) is a singleton setting of its parent, not a +// collection, and stays a hyphenated leaf (`servers get-deploy-config`). +// +// A method with a resource noun and an extra qualifier +// (GetLksClusterKubeconfig) lands in the resource's subgroup with the +// qualifier on the leaf (`lks clusters get-kubeconfig`). +func SuggestCommands(group Group, groupCommand string, methods []string, keepGroupNoun bool) map[string]string { + type split struct{ groupCommand, verb, rest string } + parts := make(map[string]split, len(methods)) + rests := make([]string, 0, len(methods)) + verbsByNoun := map[string]map[string]bool{} + for _, m := range methods { + gc, verb, rest := splitMethod(group, groupCommand, m, keepGroupNoun) + if verb == "list" { + rest = stripCollectionAdjectives(rest) + } + parts[m] = split{gc, verb, rest} + if verb == "" || rest == "" { + continue + } + rests = append(rests, rest) + noun := strings.ToLower(singular(rest)) + if verbsByNoun[noun] == nil { + verbsByNoun[noun] = map[string]bool{} + } + verbsByNoun[noun][verb] = true + } + + // Evidence for a noun's plural: every method remainder, plus the SDK + // group's own name (VirtualMachineRestores spells Restores in the + // plural even when its methods are the bare Create/List/Get). + evidence := append(append([]string(nil), rests...), lastSegment(group.Name)) + + resources := map[string]bool{} + for noun, verbs := range verbsByNoun { + n := 0 + for v := range verbs { + if crudVerbs[v] { + n++ + } + } + if verbs["list"] || (n >= 2 && verbs["create"]) { + resources[noun] = true + } + } + + out := make(map[string]string, len(methods)) + for _, m := range methods { + p := parts[m] + if p.verb == "" { + out[m] = p.groupCommand + " " + kebab(m) + continue + } + if p.rest == "" { + out[m] = p.groupCommand + " " + p.verb + continue + } + // The remainder may be exactly a resource noun (NodePool / NodePools) + // or start with one followed by a qualifier (ClusterKubeconfig). + if noun, qualifier, pluralNoun, ok := leadingResource(p.rest, resources); ok { + // The subgroup is the collection, spelled in the plural unless the + // SDK itself only ever lists it in the singular (ListUsage, + // ListStorage): those are mass nouns, and "usages" is not a word. + sub := p.groupCommand + " " + kebab(collectionName(noun, evidence)) + // A list-only collection that the route nests under another + // resource of the group belongs to that resource: + // /lks/clusters/{}/nodepools/{}/nodes lists the nodes of one node + // pool, so it is `lks node-pools nodes list`, not a top-level + // `lks nodes list`. A resource with its own CRUD stays top-level + // even when its route is scoped by a parent (node pools live + // under a cluster the way VMs live under a project): the parent + // becomes a flag, as `kubernetes clusters create --project` does. + if listOnly(verbsByNoun[strings.ToLower(noun)]) { + if parent := routeParent(group.Routes[m], resources, rests); parent != "" && !strings.EqualFold(parent, noun) { + sub = p.groupCommand + " " + kebab(collectionName(parent, evidence)) + " " + kebab(collectionName(noun, evidence)) + } + } + verb := p.verb + // GetStorageBucketLifecycleRules next to GetStorageBucketLifecycleRule: + // the plural get is the list. + if verb == "get" && pluralNoun && qualifier == "" { + verb = "list" + } + if qualifier == "" { + out[m] = sub + " " + verb + } else { + out[m] = sub + " " + verb + "-" + kebab(qualifier) + } + continue + } + out[m] = p.groupCommand + " " + p.verb + "-" + kebab(p.rest) + } + return out +} + +// listOnly reports whether a noun was seen with the list verb and nothing +// else: a collection that is read but never created or deleted here. +func listOnly(verbs map[string]bool) bool { + return len(verbs) == 1 && verbs["list"] +} + +// routeParent returns the resource noun (in the group's own CamelCase +// spelling) that the route's final segment is nested under, when that parent +// is itself a resource of the group. For +// /lks/clusters/{}/nodepools/{}/nodes the parent segment is "nodepools", +// which matches the NodePool resource; for /lks/clusters/{}/kubeconfig the +// parent is "clusters". A route with no nesting, or whose parent is not a +// resource of this group (the project in /projects/{}/user_data), yields "". +func routeParent(route Route, resources map[string]bool, rests []string) string { + if route.Path == "" { + return "" + } + segs := strings.Split(strings.Trim(route.Normalized(), "/"), "/") + // Walk back from the final segment past its own id, then past the + // parent's id, to the parent segment. + i := len(segs) - 1 + if segs[i] == "{}" { + i-- + } + if i < 1 { + return "" + } + i-- // the segment before the final resource + if i >= 0 && segs[i] == "{}" { + i-- + } + if i < 0 { + return "" + } + parent := strings.ReplaceAll(segs[i], "_", "") + for noun := range resources { + if strings.EqualFold(singular(parent), strings.ReplaceAll(noun, " ", "")) || + strings.EqualFold(parent, plural(noun)) || strings.EqualFold(parent, noun) { + // Return the CamelCase spelling as the method remainders use it. + for _, rest := range rests { + if strings.EqualFold(singular(rest), noun) || strings.EqualFold(rest, noun) { + return singular(rest) + } + } + return noun + } + } + return "" +} + +// collectionName spells a resource noun as a subgroup. The plural is the +// norm (`clusters`, `node-pools`); when no method of the group ever spells +// the noun in the plural, the SDK is treating it as a mass noun (Usage, +// Storage) and the singular is kept. evidence is every method remainder the +// nouns were taken from, plus the group's own name. +func collectionName(noun string, evidence []string) string { + for _, rest := range evidence { + // The noun may be the whole remainder (NodePools) or lead it + // (LifecycleRules + qualifier); compare the leading span of the + // same word count, so compound nouns are matched whole. + words := splitWords(rest) + n := len(splitWords(noun)) + if n == 0 || n > len(words) { + continue + } + // The noun may lead the remainder (NodePools, LifecycleRulesFoo) or + // end the group name (VirtualMachineRestores); check both spans. + for _, span := range []string{strings.Join(words[:n], ""), strings.Join(words[len(words)-n:], "")} { + if strings.EqualFold(singular(span), noun) && !strings.EqualFold(span, noun) { + return plural(noun) // seen in the plural somewhere: a count noun + } + } + } + return noun +} + +// stripCollectionAdjectives drops leading adjectives that only qualify which +// members a list returns: AvailableVersions → Versions. +func stripCollectionAdjectives(rest string) string { + words := splitWords(rest) + for len(words) > 1 && collectionAdjectives[strings.ToLower(words[0])] { + words = words[1:] + } + return strings.Join(words, "") +} + +// leadingResource finds the longest resource noun that rest starts with, and +// returns it together with what follows and whether rest spelled it in the +// plural. Nouns are compared singularized and lower-cased; the returned noun +// keeps the CamelCase spelling from rest. +func leadingResource(rest string, resources map[string]bool) (noun, qualifier string, pluralNoun, ok bool) { + words := splitWords(rest) + for n := len(words); n >= 1; n-- { + candidate := strings.Join(words[:n], "") + if resources[strings.ToLower(singular(candidate))] { + return singular(candidate), strings.Join(words[n:], ""), singular(candidate) != candidate, true + } + } + return "", "", false, false +} + +// plural is the inverse of singular for the nouns the SDK uses. +func plural(w string) string { + lw := strings.ToLower(w) + switch { + case strings.HasSuffix(lw, "y") && !strings.HasSuffix(lw, "ey"): + return w[:len(w)-1] + "ies" + case strings.HasSuffix(lw, "s") || strings.HasSuffix(lw, "x") || strings.HasSuffix(lw, "ch") || strings.HasSuffix(lw, "sh"): + return w + "es" + } + return w + "s" +} + +// stripKnownWords removes the words of rest that name the SDK group or the +// command group, and reports whether the last removed word was plural. +// +// ManagedDatabases.CreateManagedDatabase under `databases` must strip +// "ManagedDatabase" even though "managed" is not in the command group, while +// Lks.CreateLksNodePool must keep "NodePool". +func stripKnownWords(rest string, group Group, groupCommand string) (string, bool) { + known := map[string]bool{} + for _, w := range splitWords(lastSegment(group.Name)) { + known[strings.ToLower(singular(w))] = true + } + for _, w := range commandWords(groupCommand) { + known[strings.ToLower(singular(w))] = true + } + var kept []string + plural := false + for _, w := range splitWords(rest) { + if known[strings.ToLower(singular(w))] { + plural = singular(w) != w + continue + } + kept = append(kept, w) + } + return strings.Join(kept, ""), plural +} + +// groupNounOutside returns the last word of the SDK group name, singular, +// when no word of the command group matches it; "" otherwise. The last word +// is the noun the group is about (VirtualMachineRestores → Restore). +func groupNounOutside(group Group, groupCommand string) string { + words := splitWords(lastSegment(group.Name)) + if len(words) == 0 { + return "" + } + noun := singular(words[len(words)-1]) + for _, w := range commandWords(groupCommand) { + if strings.EqualFold(singular(w), noun) { + return "" + } + } + // A group named after an acronym or a suffix like "Preview" carries no + // useful noun; the words that make it up are already stripped above. + if strings.EqualFold(noun, "preview") || len(words) == 1 && strings.ToUpper(words[0]) == words[0] { + return "" + } + return noun +} + +func commandWords(groupCommand string) []string { + return strings.FieldsFunc(groupCommand, func(r rune) bool { return r == ' ' || r == '-' || r == '_' }) +} + +func lastSegment(path string) string { + if i := strings.LastIndex(path, "."); i >= 0 { + return path[i+1:] + } + return path +} + +// kebab converts a CamelCase identifier to kebab-case, keeping acronyms +// together: "ElasticIPBgpSessions" → "elastic-ip-bgp-sessions". +func kebab(s string) string { + words := splitWords(s) + for i := range words { + words[i] = strings.ToLower(words[i]) + } + return strings.Join(words, "-") +} + +func splitWords(s string) []string { + var words []string + start := 0 + runes := []rune(s) + for i := 1; i < len(runes); i++ { + prev, cur := runes[i-1], runes[i] + next := rune(0) + if i+1 < len(runes) { + next = runes[i+1] + } + boundary := (isLower(prev) && isUpper(cur)) || + (isUpper(prev) && isUpper(cur) && isLower(next)) + if boundary { + words = append(words, string(runes[start:i])) + start = i + } + } + if start < len(runes) { + words = append(words, string(runes[start:])) + } + return words +} + +// singular reduces a plural word to its singular form. It covers the patterns +// the SDK's group and method names actually use (Databases, Sandboxes, +// Policies, Metrics, Status) and is only used to compare words, never to +// render them. +func singular(w string) string { + lw := strings.ToLower(w) + switch { + case strings.HasSuffix(lw, "ies"): + return w[:len(w)-3] + "y" + case strings.HasSuffix(lw, "xes") || strings.HasSuffix(lw, "ches") || strings.HasSuffix(lw, "shes"): + return w[:len(w)-2] + case strings.HasSuffix(lw, "ss") || strings.HasSuffix(lw, "us") || strings.HasSuffix(lw, "is"): + return w + case strings.HasSuffix(lw, "s"): + return w[:len(w)-1] + } + return w +} + +func isUpper(r rune) bool { return r >= 'A' && r <= 'Z' } +func isLower(r rune) bool { return r >= 'a' && r <= 'z' } diff --git a/internal/sdkcoverage/reconcile.go b/internal/sdkcoverage/reconcile.go new file mode 100644 index 00000000..c26ecf02 --- /dev/null +++ b/internal/sdkcoverage/reconcile.go @@ -0,0 +1,609 @@ +package sdkcoverage + +import ( + "fmt" + "sort" + "strings" +) + +// Violation is a disagreement between the SDK surface, the manifest, and the +// commands the CLI actually ships. Every violation is actionable by a human +// editing the manifest or the CLI. +// +// Violations are limited to contradictions. A method or group with no entry is +// deliberately not one: that is the normal trigger for scaffolding, so an SDK +// bump does not go red over new capability. +type Violation struct { + // Group is the SDK group the violation concerns, or "" when it concerns a + // command with no owning group. + Group string + Message string +} + +func (v Violation) String() string { + if v.Group == "" { + return v.Message + } + return v.Group + ": " + v.Message +} + +// Method is one row of the per-method ledger. +type Method struct { + Group string + Name string + Commands Paths // non-empty when covered + Excluded *Exclusion // non-nil when deliberately left out +} + +// Covered reports whether at least one command calls the method. +func (m Method) Covered() bool { return len(m.Commands) > 0 } + +// Pending reports whether the method is neither covered nor excluded. +func (m Method) Pending() bool { return !m.Covered() && m.Excluded == nil } + +// GroupReport is one SDK group with its methods classified. +type GroupReport struct { + Group + Notes string + Methods []Method + + // commandGroup is the manifest's command_group, when set. + commandGroup string + // newCommandGroup is true when no registered leaf lives under CommandGroup. + newCommandGroup bool + // suggested is the manifest's per-method override of the proposed command. + suggested map[string]string + // extends is the manifest's per-method existing command to grow. + extends map[string]string +} + +// CommandGroup is the command path the group's methods live (or should live) +// under: the manifest's command_group, else the shortest parent of the mapped +// commands (ties broken alphabetically), else the kebab-cased SDK group name. +// Taking the shortest parent rather than the first one keeps the answer +// independent of SDK method order: Firewalls maps both `firewalls list` and +// `firewalls assignments create`, and its group is `firewalls`. When every +// mapped command sits in a subgroup (`lks node-pools ...`), no inference can +// tell, and the manifest should set command_group. +func (g GroupReport) CommandGroup() string { + if g.commandGroup != "" { + return g.commandGroup + } + best := "" + for _, m := range g.Methods { + for _, p := range m.Commands { + i := strings.LastIndex(p, " ") + if i <= 0 { + continue + } + parent, depth := p[:i], strings.Count(p[:i], " ") + if best == "" || depth < strings.Count(best, " ") || (depth == strings.Count(best, " ") && parent < best) { + best = parent + } + } + } + if best != "" { + return best + } + return kebab(lastSegment(g.Name)) +} + +// NewCommandGroup reports whether the top-level command of the group's +// command group does not exist in the CLI yet: scaffolding it means a new +// root command (`lks`), not a subgroup or subcommand on an existing one +// (`virtual-machines backups`). Set by Reconcile against the registered +// leaves. +func (g GroupReport) NewCommandGroup() bool { return g.newCommandGroup } + +// topLevel is the first segment of a command path. +func topLevel(path string) string { + if i := strings.Index(path, " "); i > 0 { + return path[:i] + } + return path +} + +// Pending returns the group's pending methods. +func (g GroupReport) Pending() []Method { + var out []Method + for _, m := range g.Methods { + if m.Pending() { + out = append(out, m) + } + } + return out +} + +// Suggestion is one command the pending work would add. It usually backs a +// single SDK method, but the SDK exposes some operations through two routes +// (POST /virtual_machine_backups and POST /virtual_machines/{id}/backups) and +// those become one command with a flag, so a suggestion can carry several +// methods. +type Suggestion struct { + Command string + Methods []string + // Extends is true when Command already exists and grows to call the + // methods (the manifest's `extends`), rather than being added. + Extends bool +} + +// PendingSuggestions collapses the group's pending methods into commands. +// Two methods merge when they share the HTTP verb and their paths end the +// same way (the same resource, one nested under a parent): the command takes +// the shorter method's name and the parent becomes a flag. A name the +// manifest gives (suggested or extends) wins over the automatic one: named +// methods seed their command first, so a sibling route joins them rather than +// folding them under an automatic name, and a named method joins another +// command only by sharing its name. +func (g GroupReport) PendingSuggestions() []Suggestion { + pending := g.Pending() + merged := make(map[string]bool, len(pending)) + names := g.suggestions() + extended := make(map[string]bool, len(g.extends)) + for _, cmd := range g.extends { + extended[strings.TrimSpace(cmd)] = true + } + named := make(map[string]bool, len(g.suggested)+len(g.extends)) + for _, overrides := range []map[string]string{g.suggested, g.extends} { + for method := range overrides { + named[method] = true + } + } + seeds := make([]Method, 0, len(pending)) + for _, first := range []bool{true, false} { + for _, m := range pending { + if named[m.Name] == first { + seeds = append(seeds, m) + } + } + } + var out []Suggestion + + for _, m := range seeds { + if merged[m.Name] { + continue + } + s := Suggestion{Command: names[m.Name], Methods: []string{m.Name}, Extends: extended[names[m.Name]]} + merged[m.Name] = true + // Absorb every method that is one command with any method already in + // s: the same name, or a second route to one of them. Membership is + // transitive (List's nested route joins the command List was folded + // into), so keep sweeping until nothing new joins. + for changed := true; changed; { + changed = false + for _, other := range pending { + if merged[other.Name] { + continue + } + join := names[other.Name] == s.Command + for _, member := range s.Methods { + if join || named[other.Name] { + break + } + join = sameOperation(g.Routes[member], g.Routes[other.Name]) + } + if join { + s.Methods = append(s.Methods, other.Name) + merged[other.Name] = true + changed = true + } + } + } + out = append(out, s) + } + // Subgroups read together, verbs in a stable order inside each. + sort.SliceStable(out, func(i, j int) bool { return out[i].Command < out[j].Command }) + return out +} + +// sameOperation reports whether two routes are one operation reachable +// through a top-level and a nested path. They must share the verb, address +// the same kind of target (both a collection, or both one item), and the +// top-level spelling must name the nested resource with its parent as a +// prefix: "/virtual_machine_restores" and +// "/virtual_machines/{}/backups/{}/restores" qualify (restores under a +// backup, spelled virtual_machine_restores at the top). "/servers" and +// "/servers/{}" do not (a list and a get), and neither do +// "/storage/access_keys" and "/storage/buckets/{}/access_keys": the same +// final name under a different parent is a different listing, and the +// top-level route does not spell the parent. +func sameOperation(a, b Route) bool { + if a.Verb == "" || b.Verb == "" || a.Verb != b.Verb { + return false + } + pa, pb := a.Normalized(), b.Normalized() + if pa == pb { + return true + } + ra, ia := resourceAndItem(pa) + rb, ib := resourceAndItem(pb) + if ia != ib || ra == "" || rb == "" { + return false + } + return strings.HasSuffix(ra, "_"+rb) || strings.HasSuffix(rb, "_"+ra) +} + +// resourceAndItem splits a normalized path into its final resource name and +// whether it addresses one item (ends in "/{}") rather than the collection. +func resourceAndItem(p string) (resource string, item bool) { + if strings.HasSuffix(p, "/{}") { + item = true + p = strings.TrimSuffix(p, "/{}") + } + return p[strings.LastIndex(p, "/")+1:], item +} + +// Covered returns the group's covered methods. +func (g GroupReport) Covered() []Method { + var out []Method + for _, m := range g.Methods { + if m.Covered() { + out = append(out, m) + } + } + return out +} + +// NewGroup reports whether no method of the group has a command yet: the +// group needs a new command group, not a subcommand on an existing one. +func (g GroupReport) NewGroup() bool { return len(g.Covered()) == 0 } + +// Report is the full reconciliation result. +type Report struct { + Violations []Violation + Groups []GroupReport // every SDK group, sorted by name + + // leaves are the registered commands the report was reconciled against; + // the renderers use them to tell a new top-level command from a new + // subcommand. + leaves []string +} + +// OK reports whether the SDK, the manifest, and the CLI all agree. +func (r Report) OK() bool { return len(r.Violations) == 0 } + +// Counts summarises the ledger. The JSON names are part of the contract the +// sdk-watch workflow reads; keep them stable. +type Counts struct { + Groups int `json:"groups"` + // NewGroups is the number of SDK groups with no command at all. + NewGroups int `json:"new_groups"` + // NewCommandGroups is the number of distinct top-level commands the + // pending work would add to the CLI. + NewCommandGroups int `json:"new_command_groups"` + Methods int `json:"methods"` + Covered int `json:"covered"` + Excluded int `json:"excluded"` + Pending int `json:"pending"` + Violations int `json:"violations"` +} + +func (r Report) Counts() Counts { + c := Counts{Groups: len(r.Groups), Violations: len(r.Violations)} + newRoots := map[string]bool{} + cmds, newRoot := r.PendingByRoot() + for _, p := range cmds { + if newRoot[p.Root()] { + newRoots[p.Root()] = true + } + } + for _, g := range r.Groups { + if g.NewGroup() { + c.NewGroups++ + } + for _, m := range g.Methods { + c.Methods++ + switch { + case m.Covered(): + c.Covered++ + case m.Excluded != nil: + c.Excluded++ + default: + c.Pending++ + } + } + } + c.NewCommandGroups = len(newRoots) + return c +} + +// PendingGroups returns the groups that still have pending methods, ordered by +// command group so SDK groups that share one (VirtualMachines, +// VirtualMachineBackups, VirtualMachineRestores) read together, with the +// groups whose command group does not exist yet first. +func (r Report) PendingGroups() []GroupReport { + var out []GroupReport + for _, g := range r.Groups { + if len(g.Pending()) > 0 { + out = append(out, g) + } + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].NewCommandGroup() != out[j].NewCommandGroup() { + return out[i].NewCommandGroup() + } + if ci, cj := out[i].CommandGroup(), out[j].CommandGroup(); ci != cj { + return ci < cj + } + return out[i].Name < out[j].Name + }) + return out +} + +// PendingCommand is one suggested command with the SDK group and methods +// behind it. The report is organised around these rather than around SDK +// groups, because one SDK group can feed several command groups (Plans +// lists the LKS, database and storage catalogs, which belong next to their +// products) and several SDK groups can feed one (backups and restores). +type PendingCommand struct { + Command string + Group string // SDK group + Methods []string // SDK methods behind the command + Notes string // the SDK group's manifest notes + Extends bool // the command exists and grows; see Suggestion.Extends +} + +// Root is the command's top-level command (`lks` for `lks plans list`), +// which is how the report groups pending work: everything that lands under +// one root reads together, whatever SDK groups feed it. +func (p PendingCommand) Root() string { return topLevel(p.Command) } + +// PendingByRoot returns every suggested command, sorted by its root command +// and then by command, with the roots that do not exist in the CLI yet +// first. newRoot reports, per root, whether it is new. +func (r Report) PendingByRoot() (cmds []PendingCommand, newRoot map[string]bool) { + existing := map[string]bool{} + for _, l := range r.leaves { + existing[topLevel(l)] = true + } + newRoot = map[string]bool{} + for _, g := range r.Groups { + for _, s := range g.PendingSuggestions() { + p := PendingCommand{Command: s.Command, Group: g.Name, Methods: s.Methods, Notes: g.Notes, Extends: s.Extends} + cmds = append(cmds, p) + newRoot[p.Root()] = !existing[p.Root()] + } + } + sort.SliceStable(cmds, func(i, j int) bool { + ri, rj := cmds[i].Root(), cmds[j].Root() + if newRoot[ri] != newRoot[rj] { + return newRoot[ri] + } + if ri != rj { + return ri < rj + } + return cmds[i].Command < cmds[j].Command + }) + return cmds, newRoot +} + +// Reconcile cross-checks the SDK surface, the manifest, and the leaf commands +// the CLI registers. +// +// leaves is passed in as plain strings so this package never imports the +// command packages: the gate test lives next to them and would otherwise be an +// import cycle. +func Reconcile(surface Surface, manifest Manifest, leaves []string) Report { + report := Report{leaves: leaves} + + leafSet := make(map[string]bool, len(leaves)) + for _, l := range leaves { + leafSet[l] = true + } + claimed := make(map[string]string, len(leaves)) // leaf -> "Group.Method" + + addViolation := func(group, format string, args ...any) { + report.Violations = append(report.Violations, Violation{Group: group, Message: fmt.Sprintf(format, args...)}) + } + + for _, name := range surface.Names() { + group := surface.Groups[name] + entry := manifest.Groups[name] // zero value is a valid "no entry" + row := GroupReport{Group: group, Notes: entry.Notes, commandGroup: entry.CommandGroup, suggested: entry.Suggested, extends: entry.Extends} + known := make(map[string]bool, len(group.Methods)) + + if ex := entry.ExcludedGroup; ex != nil { + if ex.Reason == "" { + addViolation(name, "excluded_group needs a reason (%s)", reasonList()) + } else if !validReason(ex.Reason) { + addViolation(name, "excluded_group has unknown reason %q (want %s)", ex.Reason, reasonList()) + } + if len(entry.Excluded) > 0 { + addViolation(name, "excluded_group already covers every unmapped method; drop the per-method excluded entries") + } + } + + for _, method := range group.Methods { + known[method] = true + m := Method{Group: name, Name: method} + + if paths, ok := entry.Commands[method]; ok { + if len(paths) == 0 { + addViolation(name, "commands.%s lists no command path", method) + } + for _, p := range paths { + if !leafSet[p] { + addViolation(name, "commands.%s names %q, which the CLI does not register (`sdkcoverage commands` lists the current paths)", method, p) + continue + } + claimed[p] = name + "." + method + } + m.Commands = paths + } + if ex, ok := entry.Excluded[method]; ok { + if m.Covered() { + addViolation(name, "%s is both mapped under commands and listed under excluded; keep one", method) + } + if ex.Reason == "" { + addViolation(name, "excluded.%s needs a reason (%s)", method, reasonList()) + } else if !validReason(ex.Reason) { + addViolation(name, "excluded.%s has unknown reason %q (want %s)", method, ex.Reason, reasonList()) + } + ex := ex + m.Excluded = &ex + } + if !m.Covered() && m.Excluded == nil && entry.ExcludedGroup != nil { + m.Excluded = entry.ExcludedGroup + } + row.Methods = append(row.Methods, m) + } + + // Entries for methods the SDK no longer exposes: a rename or removal + // on an SDK bump that would otherwise pass unnoticed. + for _, method := range sortedKeys(entry.Commands) { + if !known[method] { + addViolation(name, "commands.%s: the SDK no longer exposes this method; rename or drop the entry", method) + } + } + for _, method := range sortedKeys(entry.Excluded) { + if !known[method] { + addViolation(name, "excluded.%s: the SDK no longer exposes this method; drop the entry", method) + } + } + for _, method := range sortedKeys(entry.Suggested) { + switch { + case !known[method]: + addViolation(name, "suggested.%s: the SDK no longer exposes this method; drop the entry", method) + case strings.TrimSpace(entry.Suggested[method]) == "": + addViolation(name, "suggested.%s is empty; give it a command path or drop it", method) + case len(entry.Commands[method]) > 0: + addViolation(name, "suggested.%s: the method is already mapped under commands, so the suggestion is moot; drop it", method) + case leafSet[strings.TrimSpace(entry.Suggested[method])]: + // A suggestion is a name for a command that does not exist + // yet. Naming one that does means the method is covered by + // it (commands), is to be added to it (extends), or is not + // what that command does (pick another name). + addViolation(name, "suggested.%s names %q, which the CLI already registers; map the method under commands if that command calls it, under extends if it is to call it, or suggest a new name", method, strings.TrimSpace(entry.Suggested[method])) + } + } + for _, method := range sortedKeys(entry.Extends) { + target := strings.TrimSpace(entry.Extends[method]) + _, suggested := entry.Suggested[method] + _, excluded := entry.Excluded[method] + switch { + case !known[method]: + addViolation(name, "extends.%s: the SDK no longer exposes this method; drop the entry", method) + case target == "": + addViolation(name, "extends.%s is empty; name the command to extend or drop it", method) + case len(entry.Commands[method]) > 0: + // The usual way this happens is the extension landing: the + // command now calls the method and was mapped, so the plan + // is done. + addViolation(name, "extends.%s: the method is already mapped under commands, so the extension is done; drop it", method) + case suggested: + addViolation(name, "extends.%s: the method also has a suggested command; keep one", method) + case excluded || entry.ExcludedGroup != nil: + addViolation(name, "extends.%s: the method is excluded, so there is nothing to extend; keep one", method) + case !leafSet[target]: + addViolation(name, "extends.%s names %q, which the CLI does not register; extend an existing command, or use suggested for a new one", method, target) + } + } + + // A command group is "new" when its top-level command does not exist. + // The SDK's VirtualMachineBackups has no command, yet its + // command_group `virtual-machines backups` nests under an existing + // root: the scaffold adds a subgroup, not a top-level command. + row.newCommandGroup = true + for _, leaf := range leaves { + if topLevel(leaf) == topLevel(row.CommandGroup()) { + row.newCommandGroup = false + break + } + } + report.Groups = append(report.Groups, row) + } + + for _, name := range sortedKeys(manifest.Groups) { + if _, ok := surface.Groups[name]; !ok { + addViolation(name, "listed in %s but the SDK no longer exposes this group; rename or delete the entry (`sdkcoverage groups` lists the current names)", ManifestFile) + } + } + + // commands_without_sdk must name real leaves, and must not overlap with a + // method mapping: a leaf cannot both call an SDK method and call none. + withoutSDK := make(map[string]bool, len(manifest.CommandsWithoutSDK)) + for _, p := range manifest.CommandsWithoutSDK { + withoutSDK[p] = true + if !leafSet[p] { + addViolation("", "commands_without_sdk names %q, which the CLI does not register", p) + } else if owner, ok := claimed[p]; ok { + addViolation("", "commands_without_sdk lists %q, but %s already maps it; keep one", p, owner) + } + } + + // Every leaf must be accounted for, otherwise the method it calls still + // reads as pending and would be scaffolded a second time. + for _, leaf := range leaves { + if _, ok := claimed[leaf]; ok || withoutSDK[leaf] { + continue + } + addViolation("", "the CLI registers %q but no SDK method claims it; add it under the method it calls, or under commands_without_sdk", leaf) + } + + // Two SDK groups placed under one command group must not propose the + // same command: Teams.Get and UserProfile.Get both read as `teams get` + // when UserProfile is filed under teams, and the scaffold would build + // one command over the other. A collision inside one group is fine + // (it is how two routes fold into one command) and is not reported, + // and neither is an extension: two groups may grow the same command. + // + // An automatic name must not be a command the CLI already registers + // either: BlockStorage.RetrieveVolume reads as `volume get`, and the + // report would tell the scaffold to add it again. Whether the method + // grows that command (extends) or needs its own (suggested) is a + // decision the manifest records; a `suggested` name that collides is + // already reported above. + owners := map[string][]string{} + for _, g := range report.Groups { + for _, s := range g.PendingSuggestions() { + if s.Extends { + continue + } + if leafSet[s.Command] && !anyKey(manifest.Groups[g.Name].Suggested, s.Methods) { + addViolation(g.Name, "%s would be suggested as %q, which the CLI already registers; list it under extends if that command is to call it, or name a new command under suggested", strings.Join(s.Methods, ", "), s.Command) + } + owners[s.Command] = append(owners[s.Command], g.Name) + } + } + for _, cmd := range sortedKeys(owners) { + if groups := owners[cmd]; len(groups) > 1 { + sort.Strings(groups) + addViolation("", "%s would be suggested for both %s; move one group to another command_group or name its command under suggested", cmd, strings.Join(groups, " and ")) + } + } + + sort.Slice(report.Violations, func(i, j int) bool { + if report.Violations[i].Group != report.Violations[j].Group { + return report.Violations[i].Group < report.Violations[j].Group + } + return report.Violations[i].Message < report.Violations[j].Message + }) + return report +} + +func sortedKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +// anyKey reports whether m has an entry for any of keys. +func anyKey[V any](m map[string]V, keys []string) bool { + for _, k := range keys { + if _, ok := m[k]; ok { + return true + } + } + return false +} + +func reasonList() string { + names := make([]string, 0, len(knownReasons())) + for _, r := range knownReasons() { + names = append(names, string(r)) + } + return strings.Join(names, ", ") +} diff --git a/internal/sdkcoverage/reconcile_test.go b/internal/sdkcoverage/reconcile_test.go new file mode 100644 index 00000000..defd9abf --- /dev/null +++ b/internal/sdkcoverage/reconcile_test.go @@ -0,0 +1,592 @@ +package sdkcoverage + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func miniSurface(t *testing.T) Surface { + t.Helper() + s, err := ParseSurface(miniSDK) + if err != nil { + t.Fatal(err) + } + return s +} + +func loadYAML(t *testing.T, body string) Manifest { + t.Helper() + path := filepath.Join(t.TempDir(), ManifestFile) + if err := os.WriteFile(path, []byte("version: 1\nsdk_module: "+SDKModulePath+"\n"+body), 0o644); err != nil { + t.Fatal(err) + } + m, err := LoadManifest(path) + if err != nil { + t.Fatalf("LoadManifest: %v", err) + } + return m +} + +const okManifest = ` +groups: + Servers: + commands: + List: servers list + Get: [servers get, servers create] + Create: servers create + excluded: + GetDeployConfig: {reason: product_decision, notes: dashboard only} + Projects: + commands: + List: projects list + Projects.SSHKeys: + commands: + PostProjectSSHKey: projects ssh-keys create + Firewalls: + commands: + List: firewalls list + Firewalls.Assignments: + commands: + Create: firewalls assignments create + Billing: + command_group: servers billing + Lks: + excluded_group: {reason: api_constraint, notes: preview} + Backups: + excluded_group: {reason: product_decision, notes: fixture} +commands_without_sdk: + - login +` + +var leaves = []string{ + "firewalls assignments create", "firewalls list", "login", + "projects list", "projects ssh-keys create", + "servers create", "servers get", "servers list", +} + +func TestReconcileCleanManifestHasNoViolations(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, okManifest), leaves) + if !report.OK() { + t.Fatalf("unexpected violations: %v", report.Violations) + } + c := report.Counts() + // Lks is excluded as a whole group (2 methods); Billing has no command + // but its command_group nests under the existing "servers" family, so it + // is pending without being a new top-level command group. + if c.Methods != 19 || c.Covered != 7 || c.Excluded != 11 || c.Pending != 1 || c.NewGroups != 3 || c.NewCommandGroups != 0 { + t.Errorf("counts = %+v", c) + } + pending := report.PendingGroups() + if len(pending) != 1 || pending[0].Name != "Billing" { + names := []string{} + for _, g := range pending { + names = append(names, g.Name) + } + t.Fatalf("pending groups = %v, want [Billing]", names) + } + if !pending[0].NewGroup() || pending[0].NewCommandGroup() || pending[0].CommandGroup() != "servers billing" { + t.Errorf("Billing: NewGroup=%v NewCommandGroup=%v CommandGroup=%q", pending[0].NewGroup(), pending[0].NewCommandGroup(), pending[0].CommandGroup()) + } + // A covered group infers its command group from its mapped commands. + for _, g := range report.Groups { + if g.Name == "Servers" && g.CommandGroup() != "servers" { + t.Errorf("Servers.CommandGroup() = %q, want servers", g.CommandGroup()) + } + } +} + +func TestReconcileReportsEveryContradiction(t *testing.T) { + manifest := loadYAML(t, ` +groups: + Servers: + commands: + List: servers lst + Lists: servers list + Get: servers get + excluded: + Get: {reason: product_decision} + Create: {reason: because} + GetDeployConfig: {} + Ghost: + commands: + List: servers create + Lks: + excluded_group: {} + excluded: + ListLksClusters: {reason: deprecated} +commands_without_sdk: + - servers get + - nope +`) + report := Reconcile(miniSurface(t), manifest, leaves) + + wants := []string{ + `commands.List names "servers lst"`, // path not registered + `commands.Lists: the SDK no longer exposes`, // method gone + `Get is both mapped under commands and listed`, // mapped and excluded + `excluded.Create has unknown reason "because"`, // bad reason + `excluded.GetDeployConfig needs a reason`, // missing reason + `Ghost: listed in sdk-coverage.yaml but the SDK`, // group gone + `commands_without_sdk lists "servers get", but`, // overlap + `commands_without_sdk names "nope"`, // unknown leaf + `registers "firewalls list" but no SDK method`, // unclaimed leaf + `Lks: excluded_group needs a reason`, // group exclusion without reason + `Lks: excluded_group already covers`, // group + per-method exclusion + } + joined := "" + for _, v := range report.Violations { + joined += v.String() + "\n" + } + for _, w := range wants { + if !strings.Contains(joined, w) { + t.Errorf("missing violation containing %q\nall violations:\n%s", w, joined) + } + } +} + +func TestLoadManifestRejectsUnknownKeysAndWrongIdentity(t *testing.T) { + dir := t.TempDir() + cases := map[string]string{ + "typo": "version: 1\nsdk_module: " + SDKModulePath + "\ngroupz: {}\n", + "version": "version: 2\nsdk_module: " + SDKModulePath + "\n", + "module": "version: 1\nsdk_module: example.com/other\n", + } + for name, body := range cases { + path := filepath.Join(dir, name+".yaml") + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + if _, err := LoadManifest(path); err == nil { + t.Errorf("%s: expected an error", name) + } + } +} + +func TestLeafCommandsSkipsHiddenAndHelp(t *testing.T) { + root := &cobra.Command{Use: "lsh"} + servers := &cobra.Command{Use: "servers"} + servers.AddCommand(&cobra.Command{Use: "list", Run: func(*cobra.Command, []string) {}}) + servers.AddCommand(&cobra.Command{Use: "secret", Hidden: true, Run: func(*cobra.Command, []string) {}}) + servers.AddCommand(&cobra.Command{Use: "old", Deprecated: "gone", Run: func(*cobra.Command, []string) {}}) + root.AddCommand(servers) + root.AddCommand(&cobra.Command{Use: "login", Run: func(*cobra.Command, []string) {}}) + root.AddCommand(&cobra.Command{Use: "help", Run: func(*cobra.Command, []string) {}}) + // A runnable parent is a command in its own right as well as a group: + // `s3 configure` saves an access key and has an `export` child. + configure := &cobra.Command{Use: "configure", Run: func(*cobra.Command, []string) {}} + configure.AddCommand(&cobra.Command{Use: "export", Run: func(*cobra.Command, []string) {}}) + root.AddCommand(configure) + + got := LeafCommands(root) + want := []string{"configure", "configure export", "login", "servers list"} + if strings.Join(got, "|") != strings.Join(want, "|") { + t.Errorf("LeafCommands = %v, want %v", got, want) + } +} + +// Methods that are one operation behind two routes collapse into a single +// suggested command carrying both method names. +func TestPendingSuggestionsMergeNestedRoutes(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, "groups:\n Backups:\n command_group: virtual-machines backups\n"), nil) + var backups GroupReport + for _, g := range report.Groups { + if g.Name == "Backups" { + backups = g + } + } + got := map[string][]string{} + for _, s := range backups.PendingSuggestions() { + got[s.Command] = s.Methods + } + want := map[string][]string{ + "virtual-machines backups create": {"Create", "CreateForVirtualMachine"}, + "virtual-machines backups get": {"Get"}, + "virtual-machines backups list": {"List", "ListForVirtualMachine"}, + } + if len(got) != len(want) { + t.Fatalf("suggestions = %v, want %v", got, want) + } + for cmd, methods := range want { + if strings.Join(got[cmd], ",") != strings.Join(methods, ",") { + t.Errorf("%s = %v, want %v", cmd, got[cmd], methods) + } + } +} + +// A `suggested` entry wins over the automatic name, and two methods given the +// same suggestion fold into one command. +func TestSuggestedOverridesAutomaticNaming(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Backups: + command_group: elastic-ips + suggested: + Create: elastic-ips attach + List: elastic-ips get + Get: elastic-ips get +`), nil) + var backups GroupReport + for _, g := range report.Groups { + if g.Name == "Backups" { + backups = g + } + } + got := map[string][]string{} + for _, s := range backups.PendingSuggestions() { + got[s.Command] = s.Methods + } + if strings.Join(got["elastic-ips attach"], ",") != "Create,CreateForVirtualMachine" { + t.Errorf("attach = %v, want Create plus its nested route", got["elastic-ips attach"]) + } + if strings.Join(got["elastic-ips get"], ",") != "Get,List,ListForVirtualMachine" { + t.Errorf("get = %v, want the two suggested methods plus List's nested route", got["elastic-ips get"]) + } +} + +func TestSuggestedContradictions(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Servers: + commands: + List: servers list + suggested: + List: servers ls + Nope: servers nope + Get: " " + GetDeployConfig: servers list +`), []string{"servers list"}) + joined := "" + for _, v := range report.Violations { + joined += v.String() + "\n" + } + for _, w := range []string{ + "suggested.List: the method is already mapped", + "suggested.Nope: the SDK no longer exposes", + "suggested.Get is empty", + `suggested.GetDeployConfig names "servers list", which the CLI already registers`, + } { + if !strings.Contains(joined, w) { + t.Errorf("missing violation containing %q\nall violations:\n%s", w, joined) + } + } +} + +// An `extends` entry grows a command the CLI already has: the method stays +// pending, every renderer marks the command as one to extend rather than add, +// and two groups growing the same command are not a collision. +func TestExtendsGrowsAnExistingCommand(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Servers: + commands: + List: servers list + extends: + Get: servers list + GetDeployConfig: servers list + Backups: + command_group: servers backups + extends: + Get: servers list +`), []string{"servers list"}) + if !report.OK() { + t.Fatalf("unexpected violations: %v", report.Violations) + } + if c := report.Counts(); c.Covered != 1 { + t.Errorf("Covered = %d, want 1: an extension does not cover its methods", c.Covered) + } + + cmds, _ := report.PendingByRoot() + got := map[string]PendingCommand{} + for _, p := range cmds { + got[p.Group+" | "+p.Command] = p + } + for key, methods := range map[string]string{ + "Servers | servers list": "Get,GetDeployConfig", + "Backups | servers list": "Get", + } { + p, ok := got[key] + if !ok || !p.Extends || strings.Join(p.Methods, ",") != methods { + t.Errorf("%s = %+v (found %v), want an extension of %s", key, p, ok, methods) + } + } + if p := got["Servers | servers create"]; p.Command == "" || p.Extends { + t.Errorf("servers create = %+v, want a command to add", p) + } + + if text := report.Text(""); !strings.Contains(text, "list (extend)") { + t.Errorf("text report does not mark the extension:\n%s", text) + } + if md := report.Markdown(""); !strings.Contains(md, "| `servers list` *(extend)* | Servers.Get, Servers.GetDeployConfig |") { + t.Errorf("markdown report does not mark the extension:\n%s", md) + } + js, err := report.JSON("") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(js), `"extends": true`) || !strings.Contains(string(js), `"extends": false`) { + t.Errorf("JSON report must carry extends on every command:\n%s", js) + } +} + +// A name the manifest gives a method (suggested or extends) survives route +// merging even when the SDK lists the other route first: the automatically +// named route joins the named one, not the other way round. +func TestExplicitNamesSurviveRouteMerging(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Backups: + command_group: virtual-machines backups + suggested: + CreateForVirtualMachine: virtual-machines backups snapshot + extends: + ListForVirtualMachine: virtual-machines get +`), []string{"virtual-machines get"}) + var backups GroupReport + for _, g := range report.Groups { + if g.Name == "Backups" { + backups = g + } + } + got := map[string]Suggestion{} + for _, s := range backups.PendingSuggestions() { + got[s.Command] = s + } + if s := got["virtual-machines backups snapshot"]; strings.Join(s.Methods, ",") != "CreateForVirtualMachine,Create" || s.Extends { + t.Errorf("snapshot = %+v, want the suggested route plus Create's top-level route", s) + } + if s := got["virtual-machines get"]; strings.Join(s.Methods, ",") != "ListForVirtualMachine,List" || !s.Extends { + t.Errorf("virtual-machines get = %+v, want an extension carrying both list routes", s) + } +} + +// Covering a resource's CRUD must not move what is left of it: NodePool is a +// resource because the SDK has CreateLksNodePool and ListLksNodePools, whether +// or not they are mapped yet, so the pending node listing stays under +// `lks node-pools`. +func TestPendingNamesStableAsCoverageGrows(t *testing.T) { + nodesCommand := func(body string, leaves []string) string { + report := Reconcile(miniSurface(t), loadYAML(t, body), leaves) + for _, g := range report.Groups { + if g.Name != "Lks" { + continue + } + for _, s := range g.PendingSuggestions() { + for _, m := range s.Methods { + if m == "ListLksNodes" { + return s.Command + } + } + } + } + return "" + } + before := nodesCommand("groups:\n Lks:\n command_group: lks\n", nil) + after := nodesCommand(` +groups: + Lks: + command_group: lks + commands: + CreateLksNodePool: lks node-pools create + ListLksNodePools: lks node-pools list +`, []string{"lks node-pools create", "lks node-pools list"}) + if before != "lks node-pools nodes list" || after != before { + t.Errorf("ListLksNodes = %q before mapping node pools and %q after, want lks node-pools nodes list both times", before, after) + } +} + +// The inferred command group does not depend on SDK method order: the +// shortest parent of the mapped commands wins, ties alphabetically. +func TestCommandGroupPrefersShortestParent(t *testing.T) { + for _, tc := range []struct{ create, list, want string }{ + // Create comes first in the SDK; its deeper parent must not win. + {"servers actions create", "servers list", "servers"}, + {"zeta create", "alpha list", "alpha"}, + } { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Servers: + commands: + Create: `+tc.create+` + List: `+tc.list+` +`), []string{tc.create, tc.list}) + for _, g := range report.Groups { + if g.Name == "Servers" && g.CommandGroup() != tc.want { + t.Errorf("mapped %q and %q: CommandGroup() = %q, want %q", tc.create, tc.list, g.CommandGroup(), tc.want) + } + } + } +} + +func TestExtendsContradictions(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Servers: + commands: + List: servers list + excluded: + GetDeployConfig: {reason: product_decision} + suggested: + Create: servers make + extends: + List: servers list + Nope: servers list + Get: " " + Create: servers list + GetDeployConfig: servers list + Firewalls: + extends: + List: firewalls ls + Lks: + excluded_group: {reason: api_constraint} + extends: + ListLksSites: servers list +`), []string{"servers list"}) + joined := "" + for _, v := range report.Violations { + joined += v.String() + "\n" + } + for _, w := range []string{ + "Servers: extends.List: the method is already mapped under commands, so the extension is done", + "Servers: extends.Nope: the SDK no longer exposes", + "Servers: extends.Get is empty", + "Servers: extends.Create: the method also has a suggested command", + "Servers: extends.GetDeployConfig: the method is excluded", + `Firewalls: extends.List names "firewalls ls", which the CLI does not register`, + "Lks: extends.ListLksSites: the method is excluded", + } { + if !strings.Contains(joined, w) { + t.Errorf("missing violation containing %q\nall violations:\n%s", w, joined) + } + } +} + +// Two covered SDK groups filed under one command group must not propose the +// same command (a new group carries its own noun and cannot collide); the +// gate names both so the manifest can separate them. This is the +// Teams.Get / UserProfile.Get case. +func TestReconcileReportsSuggestionCollisionsAcrossGroups(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Servers: + command_group: machines + commands: + Create: machines create + Backups: + command_group: machines + commands: + Create: machines create +`), []string{"machines create"}) + joined := "" + for _, v := range report.Violations { + joined += v.String() + "\n" + } + if !strings.Contains(joined, "machines list would be suggested for both Backups and Servers") { + t.Errorf("missing collision violation; got:\n%s", joined) + } + // Resolving it through `suggested` clears the violation. + fixed := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Servers: + command_group: machines + commands: + Create: machines create + Backups: + command_group: machines + commands: + Create: machines create + suggested: + List: machines backups list + ListForVirtualMachine: machines backups list + Get: machines backups get +`), []string{"machines create"}) + for _, v := range fixed.Violations { + if strings.Contains(v.String(), "would be suggested for both") { + t.Errorf("collision still reported after suggested override: %s", v) + } + } +} + +// An automatic name that is already a registered command would tell the +// scaffold to add it again: the gate asks the manifest to decide between +// growing that command (extends) and naming a new one (suggested). +func TestReconcileReportsAutomaticNamesThatExist(t *testing.T) { + leaves := []string{"servers create", "servers get", "servers list"} + violations := func(extra string) string { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Servers: + commands: + List: servers list + Create: [servers create, servers get] +`+extra), leaves) + joined := "" + for _, v := range report.Violations { + joined += v.String() + "\n" + } + return joined + } + const collision = `Servers: Get would be suggested as "servers get", which the CLI already registers` + + if got := violations(""); !strings.Contains(got, collision) { + t.Errorf("missing collision violation; got:\n%s", got) + } + for name, extra := range map[string]string{ + "extends": " extends:\n Get: servers get\n", + "suggested": " suggested:\n Get: servers show\n", + } { + if got := violations(extra); got != "" { + t.Errorf("%s should resolve the collision; got:\n%s", name, got) + } + } + // A colliding `suggested` name is reported once, by the suggested check. + got := violations(" suggested:\n Get: servers get\n") + if strings.Contains(got, collision) || !strings.Contains(got, `suggested.Get names "servers get"`) { + t.Errorf("want only the suggested violation; got:\n%s", got) + } +} + +// One SDK group can feed several command groups: the report organises +// pending commands by the command group they land under, not by SDK group, +// and a suggestion under a new root counts that root as new. +func TestPendingByRootFollowsSuggestedPrefix(t *testing.T) { + report := Reconcile(miniSurface(t), loadYAML(t, ` +groups: + Servers: + commands: + List: servers list + suggested: + GetDeployConfig: lks plans list + Backups: {excluded_group: {reason: product_decision}} + Billing: {excluded_group: {reason: product_decision}} + Firewalls: {excluded_group: {reason: product_decision}} + Firewalls.Assignments: {excluded_group: {reason: product_decision}} + Lks: {excluded_group: {reason: product_decision}} + Projects: {excluded_group: {reason: product_decision}} + Projects.SSHKeys: {excluded_group: {reason: product_decision}} +`), []string{"servers list"}) + cmds, newRoot := report.PendingByRoot() + var got []string + for _, p := range cmds { + got = append(got, p.Root()+" | "+p.Command+" | "+p.Group) + } + joined := strings.Join(got, "\n") + for _, want := range []string{"lks | lks plans list | Servers", "servers | servers create | Servers", "servers | servers get | Servers"} { + if !strings.Contains(joined, want) { + t.Errorf("missing %q in:\n%s", want, joined) + } + } + if !newRoot["lks"] || newRoot["servers"] { + t.Errorf("newRoot = %v, want lks new and servers existing", newRoot) + } + // The suggested command under a new root sorts first. + if len(cmds) == 0 || cmds[0].Command != "lks plans list" { + t.Errorf("first pending = %q, want the new-root suggestion", cmds[0].Command) + } + if c := report.Counts(); c.NewCommandGroups != 1 { + t.Errorf("NewCommandGroups = %d, want 1 (lks)", c.NewCommandGroups) + } +} diff --git a/internal/sdkcoverage/report.go b/internal/sdkcoverage/report.go new file mode 100644 index 00000000..1f6a1231 --- /dev/null +++ b/internal/sdkcoverage/report.go @@ -0,0 +1,280 @@ +package sdkcoverage + +import ( + "encoding/json" + "fmt" + "strings" +) + +// suggest proposes a command for a pending method. A group that already has +// commands keeps its settled noun (SuggestSubcommand); a group with none may +// need its own noun to avoid colliding with a sibling that shares the command +// group (SuggestCommand). +func (g GroupReport) suggest(method string) string { + return g.suggestions()[method] +} + +// suggestions names every pending method of the group in one pass, so +// resources the SDK flattened into method names become subgroups. Every +// method of the group is evidence, covered or not: which nouns are resources +// is a property of the SDK, so mapping the CRUD of LKS node pools must not +// move the pending node listing out of `lks node-pools`. A `suggested` or +// `extends` entry in the manifest wins over the automatic name (Reconcile +// rejects a method carrying both). +func (g GroupReport) suggestions() map[string]string { + names := make([]string, 0, len(g.Methods)) + for _, m := range g.Methods { + names = append(names, m.Name) + } + all := SuggestCommands(g.Group, g.CommandGroup(), names, g.NewGroup()) + out := make(map[string]string, len(all)) + for _, m := range g.Pending() { + out[m.Name] = all[m.Name] + } + for _, overrides := range []map[string]string{g.suggested, g.extends} { + for method, cmd := range overrides { + if _, ok := out[method]; ok { + out[method] = strings.TrimSpace(cmd) + } + } + } + return out +} + +// Markdown renders the report for a tracking issue or a roadmap document. +func (r Report) Markdown(sdkVersion string) string { + var b strings.Builder + c := r.Counts() + + b.WriteString("# lsh coverage of `latitudesh-go-sdk`\n\n") + if sdkVersion != "" { + fmt.Fprintf(&b, "SDK version: `%s`\n\n", sdkVersion) + } + fmt.Fprintf(&b, "%d of %d SDK methods have a command (%d excluded, %d pending). The pending work spans %d new top-level command groups.\n", + c.Covered, c.Methods, c.Excluded, c.Pending, c.NewCommandGroups) + + if len(r.Violations) > 0 { + fmt.Fprintf(&b, "\n## Violations (%d)\n\n", len(r.Violations)) + for _, v := range r.Violations { + fmt.Fprintf(&b, "- %s\n", v) + } + } + + cmds, newRoot := r.PendingByRoot() + if len(cmds) > 0 { + b.WriteString("\n## Pending\n\n") + b.WriteString("Commands to add, grouped by their top-level command. A root marked *new* does not exist in the CLI yet; a command marked *extend* exists and grows to call the methods (a flag, a column); a command listing several SDK methods is one operation reachable through more than one route.\n") + last := "" + for _, p := range cmds { + if root := p.Root(); root != last { + label := "`" + root + "`" + if newRoot[root] { + label += " *(new)*" + } + fmt.Fprintf(&b, "\n### %s\n\n", label) + b.WriteString("| Command | SDK methods |\n|---|---|\n") + last = root + } + label := "`" + p.Command + "`" + if p.Extends { + label += " *(extend)*" + } + fmt.Fprintf(&b, "| %s | %s |\n", label, methodRefs(p.Group, p.Methods)) + } + // Notes once per SDK group that contributed, after the tables. + b.WriteString("\n") + seen := map[string]bool{} + for _, p := range cmds { + if strings.TrimSpace(p.Notes) == "" || seen[p.Group] { + continue + } + seen[p.Group] = true + fmt.Fprintf(&b, "_%s:_ %s\n\n", p.Group, strings.TrimSpace(p.Notes)) + } + } + + var excluded []string + for _, g := range r.Groups { + for _, m := range g.Methods { + if m.Excluded != nil { + excluded = append(excluded, fmt.Sprintf("| `%s` | `%s` | %s | %s |", g.Name, m.Name, m.Excluded.Reason, orDash(m.Excluded.Notes))) + } + } + } + if len(excluded) > 0 { + b.WriteString("\n## Excluded\n\n| Group | Method | Reason | Notes |\n|---|---|---|---|\n") + b.WriteString(strings.Join(excluded, "\n") + "\n") + } + + b.WriteString("\n## Covered\n\n| Group | Methods | Commands |\n|---|---|---|\n") + for _, g := range r.Groups { + covered := g.Covered() + if len(covered) == 0 { + continue + } + fmt.Fprintf(&b, "| `%s` | %d/%d | %s |\n", g.Name, len(covered), len(g.Methods), codeList(commandsOf(covered))) + } + + return b.String() +} + +// Text renders a short summary for terminal use. +func (r Report) Text(sdkVersion string) string { + var b strings.Builder + c := r.Counts() + + if sdkVersion != "" { + fmt.Fprintf(&b, "SDK %s\n", sdkVersion) + } + fmt.Fprintf(&b, "%d/%d methods covered, %d excluded, %d pending; %d new top-level command groups\n", + c.Covered, c.Methods, c.Excluded, c.Pending, c.NewCommandGroups) + + if cmds, newRoot := r.PendingByRoot(); len(cmds) > 0 { + b.WriteString("\nPending:\n") + last := "" + for _, p := range cmds { + if root := p.Root(); root != last { + label := root + if newRoot[root] { + label += " (new command group)" + } + fmt.Fprintf(&b, " %s\n", label) + last = root + } + leaf := leafOf(p.Command, p.Root()) + if p.Extends { + leaf += " (extend)" + } + fmt.Fprintf(&b, " %-44s %s\n", leaf, methodRefs(p.Group, p.Methods)) + } + } + + if len(r.Violations) > 0 { + fmt.Fprintf(&b, "\n%d violation(s):\n", len(r.Violations)) + for _, v := range r.Violations { + fmt.Fprintf(&b, " %s\n", v) + } + } + return b.String() +} + +// jsonReport is the machine-readable document the sdk-watch workflow reads: +// `jq '.counts.pending'` gates whether there is anything to scaffold, and each +// pending entry carries a suggested command so the tracking issue and the +// scaffold job need no naming logic of their own. Keep the field names stable. +type jsonReport struct { + SDKModule string `json:"sdk_module"` + SDKVersion string `json:"sdk_version,omitempty"` + OK bool `json:"ok"` + Counts Counts `json:"counts"` + Violations []jsonViolation `json:"violations"` + Pending []jsonPending `json:"pending"` +} + +type jsonViolation struct { + Group string `json:"group,omitempty"` + Message string `json:"message"` +} + +type jsonPending struct { + // CommandGroup is the top-level command the commands live under. + CommandGroup string `json:"command_group"` + // NewCommandGroup is true when that top-level command does not exist in + // the CLI yet: scaffolding means a new root command, not a subcommand. + NewCommandGroup bool `json:"new_command_group"` + Commands []jsonSuggestion `json:"commands"` + // Notes carries the manifest notes of every SDK group feeding this + // command group, keyed by SDK group. + Notes map[string]string `json:"notes,omitempty"` +} + +// jsonSuggestion is one command to scaffold and the SDK method(s) behind it. +// Several methods means one operation reachable through more than one route; +// the scaffold exposes it once, with a flag for the parent. +type jsonSuggestion struct { + Command string `json:"command"` + Group string `json:"group"` + Methods []string `json:"methods"` + // Extends is true when Command already exists: the scaffold grows it (a + // flag, a column) to call the methods instead of creating a command. + Extends bool `json:"extends"` +} + +// JSON renders the report as an indented JSON document. +func (r Report) JSON(sdkVersion string) ([]byte, error) { + doc := jsonReport{ + SDKModule: SDKModulePath, + SDKVersion: sdkVersion, + OK: r.OK(), + Counts: r.Counts(), + Violations: make([]jsonViolation, 0, len(r.Violations)), + Pending: []jsonPending{}, + } + for _, v := range r.Violations { + doc.Violations = append(doc.Violations, jsonViolation{Group: v.Group, Message: v.Message}) + } + cmds, newRoot := r.PendingByRoot() + var cur *jsonPending + for _, p := range cmds { + if cur == nil || cur.CommandGroup != p.Root() { + doc.Pending = append(doc.Pending, jsonPending{CommandGroup: p.Root(), NewCommandGroup: newRoot[p.Root()], Commands: []jsonSuggestion{}}) + cur = &doc.Pending[len(doc.Pending)-1] + } + cur.Commands = append(cur.Commands, jsonSuggestion{Command: p.Command, Group: p.Group, Methods: p.Methods, Extends: p.Extends}) + if strings.TrimSpace(p.Notes) != "" { + if cur.Notes == nil { + cur.Notes = map[string]string{} + } + cur.Notes[p.Group] = strings.TrimSpace(p.Notes) + } + } + return json.MarshalIndent(doc, "", " ") +} + +// methodRefs renders "Group.Method" references, comma-separated. +func methodRefs(group string, methods []string) string { + refs := make([]string, len(methods)) + for i, m := range methods { + refs[i] = group + "." + m + } + return strings.Join(refs, ", ") +} + +// leafOf strips the command group prefix from a suggested command, so a +// listing under a "virtual-machines backups" heading shows "create", not the +// whole path again. +func leafOf(command, group string) string { + return strings.TrimPrefix(strings.TrimPrefix(command, group), " ") +} + +func commandsOf(methods []Method) []string { + seen := map[string]bool{} + var out []string + for _, m := range methods { + for _, p := range m.Commands { + if !seen[p] { + seen[p] = true + out = append(out, p) + } + } + } + return out +} + +func orDash(s string) string { + if strings.TrimSpace(s) == "" { + return "—" + } + return s +} + +func codeList(items []string) string { + if len(items) == 0 { + return "—" + } + quoted := make([]string, len(items)) + for i, item := range items { + quoted[i] = "`" + item + "`" + } + return strings.Join(quoted, ", ") +} diff --git a/internal/sdkcoverage/surface.go b/internal/sdkcoverage/surface.go new file mode 100644 index 00000000..204d9418 --- /dev/null +++ b/internal/sdkcoverage/surface.go @@ -0,0 +1,324 @@ +// Package sdkcoverage reconciles the service groups and methods exposed by the +// pinned latitudesh-go-sdk against the commands the lsh CLI ships, using a +// hand-curated manifest as the record of intent. +// +// The SDK is Speakeasy-generated: every service group is a struct hanging off +// the root client, and new platform capability shows up there first. Parsing is +// purely syntactic (go/ast, no type-checking) so it needs nothing but the module +// source already in the local module cache. +package sdkcoverage + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "sort" + "strconv" + "strings" +) + +// rootClientType is the SDK's top-level client struct. Its exported fields +// enumerate every service group the SDK exposes, which makes it the single +// authoritative starting point for the walk. +const rootClientType = "Latitudesh" + +// maxGroupDepth bounds the nesting walk. The SDK nests exactly one level today +// (Firewalls.Assignments, Teams.Members, Plans.VM, Projects.SSHKeys); the extra +// level is slack so a future addition still gets picked up. +const maxGroupDepth = 3 + +// Group is one SDK service group together with the exported methods declared on +// it. +type Group struct { + // Name is the dotted access path from the root client, e.g. "Firewalls" or + // "Firewalls.Assignments". + Name string + + // TypeName is the Go type backing the group. It usually matches the last + // segment of Name, but not always: the field Projects.SSHKeys is typed + // LatitudeshProjectsSSHKeys, so methods must be resolved by type, never by + // field name. + TypeName string + + // Methods are the exported method names on TypeName, sorted. + Methods []string + + // Routes maps a method name to the HTTP verb and path it calls, when the + // method body follows the generated shape (a NewRequestWithContext with a + // literal verb, and a url.JoinPath or utils.GenerateURL with a literal + // path). Used to recognise one operation reachable through two routes. + Routes map[string]Route +} + +// Route is the HTTP verb and path template an SDK method calls. +type Route struct { + Verb string + Path string +} + +// Normalized returns the path with every parameter collapsed to "{}", so +// "/virtual_machines/{virtual_machine_id}/backups" and +// "/virtual_machines/{id}/backups" compare equal. +func (r Route) Normalized() string { + var b strings.Builder + depth := 0 + for _, c := range r.Path { + switch { + case c == '{': + depth++ + b.WriteString("{}") + case c == '}': + depth-- + case depth == 0: + b.WriteRune(c) + } + } + return b.String() +} + +// Surface is the exported service-group surface of one SDK version, keyed by +// dotted path. +type Surface struct { + Groups map[string]Group +} + +// Names returns the dotted group paths in sorted order. +func (s Surface) Names() []string { + names := make([]string, 0, len(s.Groups)) + for name := range s.Groups { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// MethodCount is the number of methods across every group. +func (s Surface) MethodCount() int { + n := 0 + for _, g := range s.Groups { + n += len(g.Methods) + } + return n +} + +// ParseSurface reads every non-test .go file at the root of dir (the SDK's +// service groups all live in one flat package) and walks the root client struct +// to build the group graph. +func ParseSurface(dir string) (Surface, error) { + idx, err := indexPackage(dir) + if err != nil { + return Surface{}, err + } + if _, ok := idx.structFields[rootClientType]; !ok { + return Surface{}, fmt.Errorf("sdkcoverage: root client type %q not found in %s", rootClientType, dir) + } + + surface := Surface{Groups: make(map[string]Group)} + idx.collectGroups(rootClientType, "", 0, surface.Groups, map[string]bool{}) + return surface, nil +} + +// structField is an exported pointer-to-struct field, the shape the SDK uses for +// every service group. +type structField struct { + name string + typeName string +} + +// pkgIndex is the raw syntactic index of one SDK source tree. +type pkgIndex struct { + // structFields maps a struct type name to its exported pointer-to-struct + // fields, in declaration order. + structFields map[string][]structField + + // methods maps a receiver type name to its exported method names. + methods map[string][]string + + // routes maps "Type.Method" to the route its body calls, when found. + routes map[string]Route +} + +func indexPackage(dir string) (*pkgIndex, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return nil, fmt.Errorf("sdkcoverage: reading %s: %w", dir, err) + } + + idx := &pkgIndex{ + structFields: make(map[string][]structField), + methods: make(map[string][]string), + routes: make(map[string]Route), + } + fset := token.NewFileSet() + + for _, entry := range entries { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + file, err := parser.ParseFile(fset, filepath.Join(dir, name), nil, parser.SkipObjectResolution) + if err != nil { + return nil, fmt.Errorf("sdkcoverage: parsing %s: %w", name, err) + } + idx.addFile(file) + } + + return idx, nil +} + +func (idx *pkgIndex) addFile(file *ast.File) { + for _, decl := range file.Decls { + switch d := decl.(type) { + case *ast.FuncDecl: + if d.Recv == nil || d.Name == nil || !d.Name.IsExported() { + continue + } + if recv := receiverTypeName(d.Recv); recv != "" { + idx.methods[recv] = append(idx.methods[recv], d.Name.Name) + if route, ok := routeOf(d); ok { + idx.routes[recv+"."+d.Name.Name] = route + } + } + case *ast.GenDecl: + if d.Tok != token.TYPE { + continue + } + for _, spec := range d.Specs { + ts, ok := spec.(*ast.TypeSpec) + if !ok { + continue + } + st, ok := ts.Type.(*ast.StructType) + if !ok { + continue + } + idx.structFields[ts.Name.Name] = groupFields(st) + } + } + } +} + +// collectGroups walks the exported pointer-to-struct fields of typeName, +// recording each one that resolves to a struct in the same package as a group. +// seen guards against a struct referencing itself or an ancestor. +func (idx *pkgIndex) collectGroups(typeName, prefix string, depth int, out map[string]Group, seen map[string]bool) { + if depth >= maxGroupDepth || seen[typeName] { + return + } + seen[typeName] = true + + for _, field := range idx.structFields[typeName] { + if _, isLocalStruct := idx.structFields[field.typeName]; !isLocalStruct { + continue + } + + path := field.name + if prefix != "" { + path = prefix + "." + field.name + } + + methods := append([]string(nil), idx.methods[field.typeName]...) + sort.Strings(methods) + routes := make(map[string]Route) + for _, m := range methods { + if r, ok := idx.routes[field.typeName+"."+m]; ok { + routes[m] = r + } + } + out[path] = Group{Name: path, TypeName: field.typeName, Methods: methods, Routes: routes} + + idx.collectGroups(field.typeName, path, depth+1, out, seen) + } +} + +// groupFields keeps only exported fields of the form `Name *LocalType`. That +// excludes the root client's `SDKVersion string`, every unexported field, and +// qualified types such as `config.SDKConfiguration`. +func groupFields(st *ast.StructType) []structField { + if st.Fields == nil { + return nil + } + + var fields []structField + for _, field := range st.Fields.List { + star, ok := field.Type.(*ast.StarExpr) + if !ok { + continue + } + ident, ok := star.X.(*ast.Ident) + if !ok { + continue + } + for _, name := range field.Names { + if name.IsExported() { + fields = append(fields, structField{name: name.Name, typeName: ident.Name}) + } + } + } + return fields +} + +// routeOf finds the HTTP verb and path literal a generated method calls. The +// path is the string literal passed to url.JoinPath(baseURL, "...") or +// utils.GenerateURL(ctx, baseURL, "...", ...); the verb is the literal passed +// to http.NewRequestWithContext(ctx, "VERB", ...). Either missing means the +// body is not the generated shape, and no route is recorded. +func routeOf(fn *ast.FuncDecl) (Route, bool) { + var route Route + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + switch sel.Sel.Name { + case "JoinPath": + if len(call.Args) >= 2 { + route.Path = stringLit(call.Args[1]) + } + case "GenerateURL": + if len(call.Args) >= 3 { + route.Path = stringLit(call.Args[2]) + } + case "NewRequestWithContext": + if len(call.Args) >= 2 { + route.Verb = stringLit(call.Args[1]) + } + } + return true + }) + return route, route.Verb != "" && route.Path != "" +} + +func stringLit(e ast.Expr) string { + lit, ok := e.(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + return "" + } + s, err := strconv.Unquote(lit.Value) + if err != nil { + return "" + } + return s +} + +func receiverTypeName(recv *ast.FieldList) string { + if recv == nil || len(recv.List) == 0 { + return "" + } + switch t := recv.List[0].Type.(type) { + case *ast.StarExpr: + if ident, ok := t.X.(*ast.Ident); ok { + return ident.Name + } + case *ast.Ident: + return t.Name + } + return "" +} diff --git a/internal/sdkcoverage/surface_test.go b/internal/sdkcoverage/surface_test.go new file mode 100644 index 00000000..85becedd --- /dev/null +++ b/internal/sdkcoverage/surface_test.go @@ -0,0 +1,284 @@ +package sdkcoverage + +import ( + "reflect" + "testing" +) + +const miniSDK = "testdata/minisdk" + +func TestParseSurfaceFindsTopLevelAndNestedGroups(t *testing.T) { + surface, err := ParseSurface(miniSDK) + if err != nil { + t.Fatalf("ParseSurface: %v", err) + } + want := []string{"Backups", "Billing", "Firewalls", "Firewalls.Assignments", "Lks", "Projects", "Projects.SSHKeys", "Servers"} + if got := surface.Names(); !reflect.DeepEqual(got, want) { + t.Errorf("group paths:\n got %v\nwant %v", got, want) + } + if n := surface.MethodCount(); n != 19 { + t.Errorf("MethodCount = %d, want 19", n) + } +} + +// The field Projects.SSHKeys is typed LatitudeshProjectsSSHKeys, so anything +// that resolves methods by field name instead of by type silently reports an +// empty group. +func TestParseSurfaceResolvesNestedGroupByType(t *testing.T) { + surface, err := ParseSurface(miniSDK) + if err != nil { + t.Fatalf("ParseSurface: %v", err) + } + group := surface.Groups["Projects.SSHKeys"] + if group.TypeName != "LatitudeshProjectsSSHKeys" { + t.Errorf("TypeName = %q, want LatitudeshProjectsSSHKeys", group.TypeName) + } + if want := []string{"PostProjectSSHKey"}; !reflect.DeepEqual(group.Methods, want) { + t.Errorf("methods = %v, want %v", group.Methods, want) + } +} + +func TestParseSurfaceSkipsNonGroupsAndUnexported(t *testing.T) { + surface, err := ParseSurface(miniSDK) + if err != nil { + t.Fatalf("ParseSurface: %v", err) + } + for _, name := range []string{"SDKVersion", "sdkConfiguration", "hooks", "rootSDK", "Latitudesh"} { + if _, ok := surface.Groups[name]; ok { + t.Errorf("%q was collected as a group", name) + } + } + for _, m := range surface.Groups["Servers"].Methods { + if m == "unexportedIsSkipped" { + t.Error("unexported method was collected") + } + } +} + +func TestParseSurfaceErrorsWithoutRootClient(t *testing.T) { + // No Latitudesh struct means the SDK was restructured; that has to be a + // loud error, not an empty surface that makes the gate pass vacuously. + if _, err := ParseSurface("testdata"); err == nil { + t.Fatal("expected an error when the root client type is absent") + } +} + +func TestVersionFromDir(t *testing.T) { + cases := map[string]string{ + "/home/u/go/pkg/mod/github.com/latitudesh/latitudesh-go-sdk@v1.21.4": "v1.21.4", + "sdk@v1.22.0-rc.1": "v1.22.0-rc.1", + "/tmp/sdk@work": "sdk@work", + "/tmp/checkout": "checkout", + } + for dir, want := range cases { + if got := VersionFromDir(dir); got != want { + t.Errorf("VersionFromDir(%q) = %q, want %q", dir, got, want) + } + } +} + +func TestSingular(t *testing.T) { + cases := map[string]string{ + "Databases": "Database", "Database": "Database", "Sandboxes": "Sandbox", "Sandbox": "Sandbox", + "Policies": "Policy", "Metrics": "Metric", "Status": "Status", "Address": "Address", "Lks": "Lk", + } + for in, want := range cases { + if got := singular(in); got != want { + t.Errorf("singular(%q) = %q, want %q", in, got, want) + } + } +} + +// A covered group keeps the noun its commands already settled on: BlockStorage +// lives under `volume`, so a pending method is `volume map`, never +// `volume map-storage`. +func TestSuggestSubcommandKeepsSettledNoun(t *testing.T) { + cases := []struct{ group, groupCommand, method, want string }{ + {"BlockStorage", "volume", "MapVolume", "volume map"}, + {"UserProfile", "teams", "Get", "teams get"}, + {"Servers", "servers", "GetDeployConfig", "servers get-deploy-config"}, + } + for _, tc := range cases { + if got := SuggestSubcommand(Group{Name: tc.group}, tc.groupCommand, tc.method); got != tc.want { + t.Errorf("SuggestSubcommand(%s, %q, %s) = %q, want %q", tc.group, tc.groupCommand, tc.method, got, tc.want) + } + } +} + +// A noun the SDK flattened into several CRUD method names is a resource and +// becomes a subgroup with plain verbs, the way `kubernetes clusters create` +// and `firewalls assignments create` already read. +func TestSuggestCommandsPromotesResourcesToSubgroups(t *testing.T) { + lks := Group{Name: "Lks"} + methods := []string{ + "CreateLksCluster", "GetLksCluster", "ListLksClusters", "UpdateLksCluster", "DeleteLksCluster", "GetLksClusterKubeconfig", + "CreateLksNodePool", "GetLksNodePool", "ListLksNodePools", + "ListLksSites", "ListLksNodes", "ListLksAvailableVersions", "ListLksAllocatableServers", + } + got := SuggestCommands(lks, "lks", methods, true) + want := map[string]string{ + "CreateLksCluster": "lks clusters create", + "ListLksClusters": "lks clusters list", + "GetLksClusterKubeconfig": "lks clusters get-kubeconfig", + "CreateLksNodePool": "lks node-pools create", + "ListLksNodePools": "lks node-pools list", + // list alone marks a reference collection: a subgroup, like + // `kubernetes versions list`; adjectives that qualify the listing + // drop out of the subgroup's name. + "ListLksSites": "lks sites list", + "ListLksNodes": "lks nodes list", + "ListLksAvailableVersions": "lks versions list", + "ListLksAllocatableServers": "lks servers list", + } + for m, w := range want { + if got[m] != w { + t.Errorf("%s = %q, want %q", m, got[m], w) + } + } + + // A mass noun the SDK only ever lists in the singular (ListUsage, + // ListStorage) keeps that spelling: `billing usage list`, not "usages". + billing := SuggestCommands(Group{Name: "Billing"}, "billing", []string{"ListUsage"}, true) + if billing["ListUsage"] != "billing usage list" { + t.Errorf("ListUsage = %q, want billing usage list", billing["ListUsage"]) + } + plans := SuggestCommands(Group{Name: "Plans"}, "plans", []string{"ListStorage", "GetBandwidth"}, false) + if plans["ListStorage"] != "plans storage list" { + t.Errorf("ListStorage = %q, want plans storage list", plans["ListStorage"]) + } + + // A group whose methods are bare (Create, List, Get) takes its noun from + // the group name, and the group name is where the plural is spelled: + // VirtualMachineRestores under `virtual-machines backups` yields + // `backups restores list`, never a singular "restore" subgroup. + restores := SuggestCommands(Group{Name: "VirtualMachineRestores"}, "virtual-machines backups", []string{"Create", "Get", "List"}, true) + if restores["List"] != "virtual-machines backups restores list" || restores["Create"] != "virtual-machines backups restores create" { + t.Errorf("restores = %v", restores) + } + + // A noun that is only got and updated is a singleton setting of its + // parent, not a collection: no subgroup. + servers := SuggestCommands(Group{Name: "Servers"}, "servers", []string{"GetDeployConfig", "UpdateDeployConfig", "List"}, false) + if servers["GetDeployConfig"] != "servers get-deploy-config" || servers["UpdateDeployConfig"] != "servers update-deploy-config" { + t.Errorf("deploy config = %v, want hyphenated leaves", servers) + } + + // The plural get beside the singular get is the list. + s3 := SuggestCommands(Group{Name: "ObjectStorage"}, "s3", []string{ + "GetStorageBucketLifecycleRule", "GetStorageBucketLifecycleRules", "PostStorageBucketLifecycleRules", "DeleteStorageBucketLifecycleRule", + }, true) + if s3["GetStorageBucketLifecycleRules"] != "s3 bucket-lifecycle-rules list" || s3["GetStorageBucketLifecycleRule"] != "s3 bucket-lifecycle-rules get" { + t.Errorf("lifecycle rules = %v", s3) + } +} + +// A collection whose route nests it under another resource of the group is +// a sub-resource: nodes belong to one node pool. +func TestSuggestCommandsNestsByRoute(t *testing.T) { + surface, err := ParseSurface(miniSDK) + if err != nil { + t.Fatal(err) + } + lks := surface.Groups["Lks"] + got := SuggestCommands(lks, "lks", lks.Methods, true) + want := map[string]string{ + "ListLksNodePools": "lks node-pools list", + "ListLksNodes": "lks node-pools nodes list", + "ListLksSites": "lks sites list", + "ListLksClusters": "lks clusters list", + } + for m, w := range want { + if got[m] != w { + t.Errorf("%s = %q, want %q", m, got[m], w) + } + } +} + +func TestSuggestCommand(t *testing.T) { + lks := Group{Name: "Lks"} + servers := Group{Name: "Servers"} + eips := Group{Name: "ElasticIps"} + baselines := Group{Name: "BaselinesPreview"} + backups := Group{Name: "VirtualMachineBackups"} + cases := []struct { + group Group + groupCommand string + method, want string + }{ + {lks, "", "ListLksClusters", "lks list-clusters"}, + {lks, "", "CreateLksNodePool", "lks create-node-pool"}, + {servers, "servers", "GetDeployConfig", "servers get-deploy-config"}, + {servers, "servers", "List", "servers list"}, + {eips, "elastic-ips", "ListElasticIPBgpSessions", "elastic-ips list-bgp-sessions"}, + {baselines, "", "GetBaselines", "baselines-preview list"}, + {baselines, "", "GetBaseline", "baselines-preview get"}, + {backups, "virtual-machines backups", "CreateForVirtualMachine", "virtual-machines backups create-for"}, + {backups, "virtual-machines backups", "ListForVirtualMachine", "virtual-machines backups list-for"}, + {Group{Name: "ManagedDatabases"}, "databases", "CreateManagedDatabase", "databases create"}, + {Group{Name: "ManagedDatabases"}, "databases", "ListManagedDatabaseBackups", "databases list-backups"}, + {Group{Name: "SandboxesPreview"}, "sandboxes", "ExecSandbox", "sandboxes exec"}, + {Group{Name: "SandboxesPreview"}, "sandboxes", "GetSandboxes", "sandboxes list"}, + {Group{Name: "Plans.VM"}, "plans", "List", "plans list"}, + {Group{Name: "VirtualMachineRestores"}, "virtual-machines backups", "Create", "virtual-machines backups create-restore"}, + {Group{Name: "VirtualMachineRestores"}, "virtual-machines backups", "ListForBackup", "virtual-machines backups list-restore-for"}, + {Group{Name: "Roles"}, "teams roles", "List", "teams roles list"}, + {Group{Name: "Oddities"}, "", "Frobnicate", "oddities frobnicate"}, + } + for _, tc := range cases { + if got := SuggestCommand(tc.group, tc.groupCommand, tc.method); got != tc.want { + t.Errorf("SuggestCommand(%s, %q, %s) = %q, want %q", tc.group.Name, tc.groupCommand, tc.method, got, tc.want) + } + } +} + +func TestParseSurfaceExtractsRoutes(t *testing.T) { + surface, err := ParseSurface(miniSDK) + if err != nil { + t.Fatalf("ParseSurface: %v", err) + } + backups := surface.Groups["Backups"] + want := map[string]Route{ + "List": {Verb: "GET", Path: "/virtual_machine_backups"}, + "ListForVirtualMachine": {Verb: "GET", Path: "/virtual_machines/{virtual_machine_id}/backups"}, + "Create": {Verb: "POST", Path: "/virtual_machine_backups"}, + "Get": {Verb: "GET", Path: "/virtual_machine_backups/{id}"}, + } + for m, r := range want { + if got := backups.Routes[m]; got != r { + t.Errorf("Routes[%s] = %+v, want %+v", m, got, r) + } + } + // A body without the generated shape records no route. + if _, ok := surface.Groups["Servers"].Routes["List"]; ok { + t.Error("Servers.List has no request body and must not record a route") + } + if got := (Route{Path: "/virtual_machines/{virtual_machine_id}/backups/{backup_id}/restores"}).Normalized(); got != "/virtual_machines/{}/backups/{}/restores" { + t.Errorf("Normalized = %q", got) + } +} + +func TestSameOperation(t *testing.T) { + cases := []struct { + a, b Route + want bool + }{ + {Route{"POST", "/virtual_machine_backups"}, Route{"POST", "/virtual_machines/{virtual_machine_id}/backups"}, true}, + {Route{"GET", "/virtual_machine_restores"}, Route{"GET", "/virtual_machines/{vm}/backups/{b}/restores"}, true}, + // Two nested spellings of the same name do not merge with each other + // directly; both merge with the top-level "/virtual_machine_restores", + // which is what folds the three into one suggestion. + {Route{"GET", "/virtual_machine_backups/{backup_id}/restores"}, Route{"GET", "/virtual_machines/{vm}/backups/{b}/restores"}, false}, + {Route{"GET", "/virtual_machine_backups"}, Route{"POST", "/virtual_machine_backups"}, false}, // list vs create + {Route{"GET", "/servers"}, Route{"GET", "/servers/{server_id}"}, false}, // list vs get + // The same final name under a different parent, with no parent prefix + // in the top-level spelling, is a different listing. + {Route{"GET", "/storage/access_keys"}, Route{"GET", "/storage/buckets/{id}/access_keys"}, false}, + {Route{"GET", "/user_data"}, Route{"GET", "/projects/{project_id}/user_data"}, false}, + {Route{"", "/x"}, Route{"GET", "/x"}, false}, // unknown route never merges + } + for _, tc := range cases { + if got := sameOperation(tc.a, tc.b); got != tc.want { + t.Errorf("sameOperation(%v, %v) = %v, want %v", tc.a, tc.b, got, tc.want) + } + } +} diff --git a/internal/sdkcoverage/testdata/minisdk/latitudesh.go b/internal/sdkcoverage/testdata/minisdk/latitudesh.go new file mode 100644 index 00000000..2071c8cf --- /dev/null +++ b/internal/sdkcoverage/testdata/minisdk/latitudesh.go @@ -0,0 +1,123 @@ +// A frozen miniature of the latitudesh-go-sdk root package, used to pin the +// parser and the naming helper against the SDK's real quirks without depending +// on any particular version being present in the module cache. +// +// This tree lives under testdata/ so the go tool ignores it; it only ever has +// to be parseable, not buildable. +package latitudeshgosdk + +type Latitudesh struct { + SDKVersion string + + Servers *Servers + Projects *Projects + Firewalls *Firewalls + Lks *Lks + Billing *Billing + Backups *Backups + + sdkConfiguration config.SDKConfiguration + hooks *hooks.Hooks +} + +type Servers struct { + rootSDK *Latitudesh +} + +func (s *Servers) List() {} +func (s *Servers) Get() {} +func (s *Servers) Create() {} +func (s *Servers) GetDeployConfig() {} +func (s *Servers) unexportedIsSkipped() {} + +// Projects nests a subgroup whose field name differs from its type name, so +// methods must be resolved by type. +type Projects struct { + SSHKeys *LatitudeshProjectsSSHKeys + + rootSDK *Latitudesh +} + +func (s *Projects) List() {} + +type LatitudeshProjectsSSHKeys struct { + rootSDK *Latitudesh +} + +func (s *LatitudeshProjectsSSHKeys) PostProjectSSHKey() {} + +type Firewalls struct { + Assignments *Assignments + + rootSDK *Latitudesh +} + +func (s *Firewalls) List() {} + +type Assignments struct { + rootSDK *Latitudesh +} + +func (s *Assignments) Create() {} + +type Lks struct { + rootSDK *Latitudesh +} + +func (s *Lks) ListLksClusters() {} +func (s *Lks) CreateLksNodePool() {} + +// Nodes are listed per node pool: the route nests them under nodepools, so +// the suggested command is `lks node-pools nodes list`. +func (s *Lks) ListLksNodePools() { + opURL, _ := utils.GenerateURL(ctx, baseURL, "/lks/clusters/{cluster_id}/nodepools", request, nil) + _, _ = http.NewRequestWithContext(ctx, "GET", opURL, nil) +} + +func (s *Lks) ListLksNodes() { + opURL, _ := utils.GenerateURL(ctx, baseURL, "/lks/clusters/{cluster_id}/nodepools/{node_pool_id}/nodes", request, nil) + _, _ = http.NewRequestWithContext(ctx, "GET", opURL, nil) +} + +func (s *Lks) ListLksSites() { + opURL, _ := url.JoinPath(baseURL, "/lks/sites") + _, _ = http.NewRequestWithContext(ctx, "GET", opURL, nil) +} + +type Billing struct { + rootSDK *Latitudesh +} + +func (s *Billing) ListUsage() {} + +// Backups exposes the same operations through a top-level and a nested +// route, the shape the real VirtualMachineBackups group has. The bodies carry +// the literal verb and path the parser extracts. +type Backups struct { + rootSDK *Latitudesh +} + +func (s *Backups) List() { + opURL, _ := url.JoinPath(baseURL, "/virtual_machine_backups") + _, _ = http.NewRequestWithContext(ctx, "GET", opURL, nil) +} + +func (s *Backups) ListForVirtualMachine() { + opURL, _ := utils.GenerateURL(ctx, baseURL, "/virtual_machines/{virtual_machine_id}/backups", request, nil) + _, _ = http.NewRequestWithContext(ctx, "GET", opURL, nil) +} + +func (s *Backups) Create() { + opURL, _ := url.JoinPath(baseURL, "/virtual_machine_backups") + _, _ = http.NewRequestWithContext(ctx, "POST", opURL, nil) +} + +func (s *Backups) CreateForVirtualMachine() { + opURL, _ := utils.GenerateURL(ctx, baseURL, "/virtual_machines/{virtual_machine_id}/backups", request, nil) + _, _ = http.NewRequestWithContext(ctx, "POST", opURL, nil) +} + +func (s *Backups) Get() { + opURL, _ := utils.GenerateURL(ctx, baseURL, "/virtual_machine_backups/{id}", request, nil) + _, _ = http.NewRequestWithContext(ctx, "GET", opURL, nil) +} diff --git a/internal/sdkcoverage/version.go b/internal/sdkcoverage/version.go new file mode 100644 index 00000000..df9407ec --- /dev/null +++ b/internal/sdkcoverage/version.go @@ -0,0 +1,40 @@ +package sdkcoverage + +import ( + "fmt" + "os/exec" + "path/filepath" + "strings" +) + +// SDKModulePath is the Go module this package reconciles against. +const SDKModulePath = "github.com/latitudesh/latitudesh-go-sdk" + +// PinnedModuleDir resolves the local source directory of the SDK version this +// repo requires, so the surface can be parsed straight from the module cache +// with no network access. +func PinnedModuleDir() (string, error) { + out, err := exec.Command("go", "list", "-m", "-f", "{{.Dir}}", SDKModulePath).Output() + if err != nil { + return "", fmt.Errorf("sdkcoverage: resolving %s: %w", SDKModulePath, err) + } + dir := strings.TrimSpace(string(out)) + if dir == "" { + return "", fmt.Errorf("sdkcoverage: %s has no local directory (run `go mod download`)", SDKModulePath) + } + return dir, nil +} + +// VersionFromDir derives the version string reports display from the SDK +// source directory. Module-cache directories are named module@version, so the +// suffix after "@" is kept only when it looks like a Go module version. Any +// other basename (a hand-picked -sdk-dir) passes through whole. +func VersionFromDir(dir string) string { + base := filepath.Base(dir) + if at := strings.LastIndex(base, "@"); at >= 0 { + if v := base[at+1:]; len(v) > 1 && v[0] == 'v' && v[1] >= '0' && v[1] <= '9' { + return v + } + } + return base +} diff --git a/sdk-coverage.yaml b/sdk-coverage.yaml new file mode 100644 index 00000000..9bb5ac37 --- /dev/null +++ b/sdk-coverage.yaml @@ -0,0 +1,461 @@ +# Coverage of latitudesh-go-sdk service groups and methods by the lsh CLI. +# +# This is the record of intent the coverage tool reconciles against the SDK +# surface and the command tree. One SDK method ≈ one subcommand: +# +# groups..command_group: +# Where the group's commands live, or should live once scaffolded. The SDK +# splits by resource where the CLI groups by product: VirtualMachineBackups +# belongs under "virtual-machines backups". Optional for covered groups +# (inferred as the shortest parent of the mapped commands); set it for +# groups with no command, so the report and the scaffold place them next +# to their siblings, and for groups whose mapped commands all sit in a +# subgroup ("lks node-pools ..." for an Lks group that lives under "lks"). +# +# groups..commands.: | [, ...] +# The command(s) that call the method. A path is the space-separated +# command line without the binary name ("servers list"). Every path is +# verified against the cobra tree. A list is for the many-to-many cases +# (one method backing two commands). +# +# groups..excluded.: {reason, notes} +# groups..excluded_group: {reason, notes} +# Looked at and deliberately left out, per method or for the whole group +# (a preview behind a feature flag, a niche flow). reason is one of: +# api_constraint the API does not offer enough for a usable command +# product_decision we do not want it on the command line +# deprecated the upstream endpoint is going away +# +# groups..suggested.: +# Overrides the command the report proposes for a pending method, when +# the UX was decided ahead of the code and the automatic name would be +# wrong. The method stays pending; only its name in the report and the +# scaffold prompt changes. The path must not exist yet. +# +# groups..extends.: +# The existing command that is to call a pending method: the UX grows it +# (a flag, a column) instead of adding a command. The path must exist. +# The method stays pending and the report marks the command "extend"; +# once the command calls the method, move the entry to commands. +# +# commands_without_sdk: [, ...] +# Leaf commands that call no SDK method (local state, self-update, +# hand-written HTTP). Verified against the tree too. +# +# A method in neither commands nor excluded is PENDING, and a group with no +# entry at all is a new command group waiting to be scaffolded. Nothing waits +# on a human writing a line first; this is an exception list, not a work +# queue. +# +# The gate (`go test ./cmd -run TestCLISDKCoverage`, also `sdkcoverage check`) +# fails only on contradictions: a path the CLI does not register, a method or +# group the SDK no longer exposes, a leaf command no entry claims, a method +# both mapped and excluded, an exclusion without a known reason, a pending +# method whose proposed command already exists without an extends entry. +# +# Commands still served by the legacy go-swagger client (api_keys, plans, +# projects, servers create/get/update/destroy, virtual_networks) count as +# coverage: they deliver the capability to the user. They are mapped to the SDK +# method that hits the same endpoint. +# +# Regenerate the inputs with: go run ./cmd/sdkcoverage groups +# go run ./cmd/sdkcoverage commands +# Render the report with: go run ./cmd/sdkcoverage report + +version: 1 +sdk_module: github.com/latitudesh/latitudesh-go-sdk + +groups: + APIKeys: + commands: + List: api_keys list + Create: api_keys create + Delete: api_keys destroy + # PUT /auth/api_keys/{id} rotates the token. The command is named + # "update" for historical reasons. + Update: api_keys update + extends: + # PATCH, settings only: `update` grows --read-only and --allowed-ips. + UpdateAPIKey: api_keys update + notes: >- + Update rotates the key (PUT) and today requires --name, so renaming a + key also rotates it. The plan: `update` calls UpdateAPIKey (PATCH: + name, read_only, allowed_ips, token unchanged), and rotation moves to + an explicit `rotate` (subcommand or flag, decided when implemented). + For one release, `update --name` alone keeps rotating and warns on + stderr, so scripts that rotate through it do not silently stop. The + SDK drops an empty allowed_ips list (omitempty), so clearing every IP + restriction needs a spec/SDK fix. + + Billing: + command_group: billing + notes: GET /billing/usage is per project; `billing usage list` next to `traffic list`. + + BlockStorage: + commands: + ListVolumes: [volume list, volume get, volume mount] + DeleteVolume: volume delete + MountVolume: volume mount + extends: + RetrieveVolume: volume get + excluded: + CreateVolume: + reason: api_constraint + notes: "`volume create` exists but is a stub that prints a notice and calls nothing; map it here once implemented." + notes: >- + `volume get` filters ListVolumes client-side; it is to call + RetrieveVolume instead. + + ElasticIps: + commands: + ListElasticIps: elastic-ips list + CreateElasticIP: elastic-ips create + GetElasticIP: elastic-ips get + UpdateElasticIP: elastic-ips update + DeleteElasticIP: elastic-ips delete + extends: + # `get` is to list the announcing servers (BGP sessions) of a bgp-mode + # IP; it does not call either session read yet. + ListElasticIPBgpSessions: elastic-ips get + GetElasticIPBgpSession: elastic-ips get + suggested: + CreateElasticIPBgpSession: elastic-ips attach + DeleteElasticIPBgpSession: elastic-ips detach + notes: >- + The mode (routed or bgp) is a property of the IP, not a separate + product: `create` grows `--mode bgp --site ` (bgp IPs are not + tied to a server at creation). A BGP session is one server announcing + the IP and its only input is the server, so sessions are verbs on the + IP, not a subgroup: `attach --server` creates a session, `detach + --server` deletes it, and `get` lists the announcing servers with + their peer address. The existing `create --server` and `update + --server` keep their routed-mode meaning. + + Events: + commands: + List: events list + + FilesystemStorage: + commands: + ListFilesystems: storage-filesystems list + UpdateFilesystem: storage-filesystems update + DeleteFilesystem: storage-filesystems delete + + Firewalls: + commands: + List: firewalls list + Create: firewalls create + Get: firewalls get + Update: firewalls update + Delete: firewalls delete + ListAssignments: firewalls assignments list + GetAllFirewallAssignments: firewalls assignments list + DeleteAssignment: firewalls assignments delete + + Firewalls.Assignments: + command_group: firewalls assignments + commands: + Create: firewalls assignments create + + IPAddresses: + commands: + List: ips list + Get: ips get + + KubernetesClusters: + command_group: kubernetes clusters + commands: + ListKubernetesClusters: kubernetes clusters list + CreateKubernetesCluster: kubernetes clusters create + GetKubernetesCluster: [kubernetes clusters get, kubernetes clusters create] + DeleteKubernetesCluster: kubernetes clusters delete + GetKubernetesClusterKubeconfig: kubernetes kubeconfig + ListKubernetesAvailableVersions: kubernetes versions list + excluded: + UpdateKubernetesCluster: + reason: deprecated + notes: >- + The legacy managed Kubernetes API is going away, replaced by LKS + (`lks`). The existing `kubernetes` commands stay; the product does + not grow on the CLI. + + ObjectStorage: + commands: + GetStorageBuckets: s3 list + PostStorageBuckets: s3 create-bucket + DeleteStorageBuckets: s3 delete-bucket + # Object commands talk S3 (minio-go); their only API call resolves the + # bucket (endpoint, site, project). Commands with an API call of their + # own are listed under that method only, not here as well. + GetStorageBucket: + - s3 copy + - s3 delete + - s3 get + - s3 move + - s3 presign + - s3 sync + - s3 configure export + GetStorageBucketMetrics: s3 metrics + GetStorageUsage: s3 usage + GetStorageBucketLifecycleRules: [s3 lifecycle list, s3 lifecycle delete] + GetStorageBucketLifecycleRule: [s3 lifecycle get, s3 lifecycle update, s3 lifecycle delete] + PostStorageBucketLifecycleRules: s3 lifecycle create + PatchStorageBucketLifecycleRule: s3 lifecycle update + DeleteStorageBucketLifecycleRule: s3 lifecycle delete + PostStorageAccessKeys: [s3 access-keys create, s3 access-keys rotate, s3 create-bucket, s3 configure] + # list, get and import read GET /storage/access_keys by hand + # (keysAPI.rawGet, objectstorage.RawAccessKeyScopes): the raw document + # carries fields the SDK model drops. + GetStorageAccessKeys: [s3 access-keys list, s3 access-keys get, s3 access-keys import] + GetStorageBucketAccessKeys: s3 access-keys list + DeleteStorageAccessKeysUsername: [s3 access-keys delete, s3 access-keys rotate] + notes: >- + `lsh s3` (PR #97) is the namespace for buckets, objects, access keys + and lifecycle rules; `storage-objects` is a deprecated alias the gate + ignores. + + OperatingSystems: + commands: + ListPlans: operating-systems list + + Plans.VM: + command_group: virtual-machines plans + notes: >- + `virtual-machines create --plan` needs a plan ID the CLI cannot list + today; expose VM plans next to the VM commands, like `lks plans`. + + Plans: + commands: + # plans list/stock fetch GET /plans by hand (lsh.ServerURL()+"/plans"); + # plans get and list-bandwidth go through the legacy client. + List: [plans list, plans stock] + Get: plans get + GetBandwidth: plans list-bandwidth + excluded: + GetManagedDatabasePlans: + reason: deprecated + notes: The Managed Databases catalog; see ManagedDatabases. + suggested: + GetLksPlans: lks plans list + ListStorage: storage plans list + UpdateBandwidth: traffic bandwidth set + notes: >- + `plans` is the bare metal catalog. The other catalogs the API files + under /plans belong next to their products, like `virtual-machines + plans list`: LKS plans under `lks`, storage plans under a future + `storage` root. POST /plans/bandwidth is + not a plan at all: it sets how many bandwidth packages a project buys + in a region (project, region_slug, quantity; admins only), so it sits + with `traffic quota` as `traffic bandwidth set`. + + Projects: + commands: + List: [projects list, servers create] + Create: projects create + GetProject: projects get + Update: projects update + Delete: projects destroy + + Projects.SSHKeys: + command_group: projects ssh-keys + commands: + PostProjectSSHKey: projects ssh-keys create + + Regions: + commands: + Get: regions list + + SSHKeys: + commands: + ListAll: ssh-keys list + Create: ssh-keys create + Retrieve: ssh-keys get + Update: ssh-keys update + Delete: ssh-keys delete + List: projects ssh-keys list + Get: projects ssh-keys get + RemoveFromProject: projects ssh-keys delete + + Servers: + commands: + List: servers list + Create: servers create + Get: [servers get, servers create, servers reinstall] + Update: servers update + Delete: servers destroy + Reinstall: servers reinstall + Lock: servers lock + Unlock: servers unlock + RunAction: [servers power-on, servers power-off, servers reboot] + StartRescueMode: servers rescue-mode + ExitRescueMode: servers exit-rescue-mode + ScheduleDeletion: servers schedule-deletion + UnscheduleDeletion: servers unschedule-deletion + + Tags: + commands: + List: tags list + Create: tags create + Update: tags update + Delete: tags destroy + + TeamMembers: + command_group: teams members + commands: + PostTeamMembers: teams members add + Delete: teams members remove + + Teams: + command_group: teams + commands: + Create: teams create + Update: teams update + + Teams.Members: + command_group: teams members + commands: + GetTeamMembers: [teams members list, teams members remove] + + Traffic: + commands: + Get: traffic list + GetQuota: [traffic list, traffic quota] + + UserData: + commands: + List: user-data list + CreateNew: user-data create + Retrieve: user-data get + Update: user-data update + Delete: user-data delete + GetProjectUsersData: projects user-data list + Create: projects user-data create + GetProjectUserData: projects user-data get + UpdateForProject: projects user-data update + DeleteProjectUserData: projects user-data delete + + UserProfile: + commands: + ListTeams: [teams list, teams update] + excluded: + Get: + reason: product_decision + notes: "The signed-in user's profile stays out of the CLI for now; `auth status` already reads GET /user/profile through authclient to validate the token and print email and team." + Update: + reason: product_decision + notes: "Editing the signed-in user's name is a dashboard task for now; \"profile\" in the CLI means a local profile (`lsh profile list/use`), so a command here would also need another name." + notes: >- + /user/profile is the signed-in user, not a team. ListTeams is the + user's teams and backs `teams list`. + + VirtualMachines: + commands: + List: virtual-machines list + Create: virtual-machines create + Get: [virtual-machines get, virtual-machines create] + UpdateVirtualMachine: virtual-machines update + Delete: virtual-machines delete + CreateVirtualMachineAction: virtual-machines action + + VirtualMachineBackups: + command_group: virtual-machines backups + notes: >- + A backup is a sub-resource of a VM: the dashboard shows it on the VM's + page. Scaffold `backups list/get/create/delete` under + `virtual-machines`, not as a top-level command. + + VirtualMachineRestores: + command_group: virtual-machines backups + notes: >- + A restore always creates a new VM from a backup, so the user-facing + verb is `virtual-machines backups restore `; the list/get + methods back a `backups restores` subgroup for history only. + + Lks: + command_group: lks + notes: >- + Preview product, included on purpose: LKS is the managed Kubernetes + the docs promote. Distinct from `kubernetes` (the legacy managed + clusters). Resources are subgroups with plain verbs (`clusters`, + `node-pools`); reference lists are subgroups too, with `list` as their + only verb (`sites list`, `versions list`, `servers list` for the + servers that can join an allocated pool), the way + `kubernetes versions list` already reads. Nodes are listed per node + pool (`node-pools nodes list`). Plans.GetLksPlans belongs here as + `lks plans list`. + + ManagedDatabases: + excluded_group: + reason: deprecated + notes: The Managed Databases API is going away; no `databases` commands. + + PublicNetworks: + command_group: networks public + notes: >- + "Public networks" in the docs, next to private networks. The + `networks` root does not exist yet; the plan is `networks private` + (today's `virtual_networks`) and `networks public` as siblings. + + MarketplaceApps: + command_group: virtual-machines apps + notes: >- + Apps are only used by `virtual-machines create --app ` + (POST /virtual_machines accepts `marketplace_app` instead of + `operating_system`); `apps list/get` exist to discover the slug. + Catalog-only fields (description, logo, links) are not worth columns. + + Roles: + command_group: teams roles + notes: >- + Read-only catalog of the roles `teams members add --role` accepts; + lives under `teams`, not as a top-level command. + + Inference: + command_group: inference + + BaselinesPreview: + excluded_group: + reason: api_constraint + notes: "Preview behind the `baselines_api` feature flag with no product page yet; revisit at GA." + + SandboxesPreview: + excluded_group: + reason: api_constraint + notes: "Preview behind the `sandboxes_api` feature flag with no product page yet; revisit at GA." + + Clusters: + excluded_group: + reason: product_decision + notes: "GPU cluster requirements and node groups; only for projects with a GPU cluster (404 otherwise) and a sign-off flow. Needs product guidance before it gets commands." + + PrivateNetworks: + command_group: virtual_networks + commands: + List: virtual_networks list + Create: virtual_networks create + Get: virtual_networks get + Update: virtual_networks update + ListAssignments: virtual_networks assignments list + Assign: virtual_networks assignments create + DeleteAssignment: virtual_networks assignments destroy + + VirtualNetworks: + command_group: virtual_networks + commands: + Delete: virtual_networks destroy + +commands_without_sdk: + - login + - auth status + - auth logout + - profile list + - profile use + - update + - authentication + - automation + - output-formats + - profiles + - exit-codes + - object-storage + - s3 access-keys forget + - volume create