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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -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.<Group>.suggested.<Method>`: 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.<Group>.extends.<Method>` 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.<Group>.commands.<Method>`;
- a group whose commands belong under an existing family (VM backups under
`virtual-machines`) declares it with `groups.<Group>.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.<Group>.excluded.<Method>` 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.<Group>.excluded_group` with the same fields.

`make coverage-check` runs the same check from the command line.
15 changes: 15 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
53 changes: 53 additions & 0 deletions cmd/sdk_coverage_test.go
Original file line number Diff line number Diff line change
@@ -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)")
}
}
176 changes: 176 additions & 0 deletions cmd/sdkcoverage/main.go
Original file line number Diff line number Diff line change
@@ -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 <report|check|groups|commands> [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
}
Loading
Loading