diff --git a/AGENTS.md b/AGENTS.md index 6ae78c49..15869e08 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch | Path | What | | --- | --- | | `cmd/devvm/` | the entry point: `ui.Main` makes the run's UI and runs the root command with it; the only `os.Exit` | -| `internal/cli/` | Cobra commands, one file each (root = up, `build`/`rebuild`, `images`, `gc`, `space`, `retention`, `layer`, `setup`, `restart`, `tools`, `adopt`, `rm`, `stop`, `history`, `ls`, `network` (its rules and log too), `doctor`, `secret`, `ssh-agent`, `host`, `code`, `desktop`, `limactl`, `ports`, `size`, `git-protect`, `completion`, hidden `version`, `_msg`, `_qemu`, `_proxy`, `_lima-ports`, `_smolvm-ports`, `_docker-ports`, `_docker-connect`, `_refresh-tools`); `args.go` checks arguments and flags (usage errors); `script_test.go` runs testscript; `docgen/` writes the CLI reference | +| `internal/cli/` | Cobra commands, one file each (root = up, `build`/`rebuild`, `images`, `gc`, `space`, `retention`, `layer`, `setup`, `restart`, `tools`, `adopt`, `rm`, `stop`, `history`, `ls`, `network` (its rules and log too), `doctor`, `secret`, `ssh-agent`, `host`, `code`, `desktop`, `limactl`, `ports`, `size`, `git-protect`, `completion`, hidden `version`, `_msg`, `_qemu`, `_proxy`, `_lima-ports`, `_smolvm-ports`, `_docker-ports`, `_docker-connect`, `_refresh-tools`); `args.go` checks arguments and flags (usage errors), `word.go` devvm WORD's and help's words (did-you-mean); `script_test.go` runs testscript; `docgen/` writes the CLI reference | | `internal/vm/` | `Env` (`env.go`: shared dependencies, finding and starting the folder's VM); `Launch`: a new VM (`up.go`), an existing one (`existing.go`), `ssh.go`, agents' mounts; `Lifecycle` (`lifecycle.go`); `Tools` (`tools.go`: a VM's shared tools); `Settings` (`settings.go`, `size.go`, `ports.go`, `sshagent.go`); `Net` (`network.go`, `secret.go`); `--clone` (`clone.go`); a devcontainer.json's mapping and commands (`devcontainer.go`); the setup it sends (`sync.go`) | | `internal/project/`, `internal/gitprotect/` | a project folder (VM name, unsafe folders, detection, set-id files); `.git` protection | | `internal/sshconfig/`, `internal/sshagent/` | the ssh config for running VMs by name, their pinned host keys, the `~/.ssh/config` Include line; each VM's SSH agent choice, devvm's own agent and its keys | @@ -66,7 +66,7 @@ Still to come: the release keys (`packaging/minisign.pub`, `packaging/release-si - **Every `//nolint` names its linters and says why** (nolintlint). Functions stay within revive's `function-length` and `cognitive-complexity` limits: split one that grows past them. - **Only `cmd/devvm` and `internal/cli` import `internal/ui`** (depguard): cli passes the run's `*ui.UI` to each command; other packages take what they need as fields (`Info`/`Warn func(msg.M)`, `LoggedCmd`, `AddCleanup`, `Interrupted`…), set from a small `UI` interface of their own that their constructors take, or cli asks first and passes the answer in. - **Fail with `u.Die(msg.X(...))`:** it prints and panics; `ui.Main` recovers, runs the cleanups, returns 1. Commands end with `fail` (`DieLogged` for a `LoggedError`). INT/TERM/HUP cancel the root context, wait for the logged command, run the cleanups and return 130; a second signal is ignored; after one, `Die` prints nothing. A logged command a signal ended (or 128+) waits up to 1 s for devvm's own interrupt, as Ctrl+C can end it first. -- **Arguments and flag values are checked before anything runs**, in `Args` (`noArgs`, `exactArgs`… from `args.go`, never Cobra's; values with `cobra.MatchAll`), `checkFlagValue` and `exclusive`: a usage error exits 2 and names the command's --help. Exit codes: 0, 1, 2, 130. +- **Arguments and flag values are checked before anything runs**, in `Args` (`noArgs`, `exactArgs`… from `args.go`, never Cobra's; values with `cobra.MatchAll`), `checkFlagValue` and `exclusive`: a usage error exits 2 and names the command's --help. Exit codes: 0, 1, 2, 130. A new command's name goes in `image.Reserved`, which layers can't take. - **Cleanups:** whatever a failure would leave (a build VM, a temp file) registers with the UI's `AddCleanup` and is removed once done; one only for interrupts checks `Interrupted()`. Cleanups get a fresh context. - **External commands run with the UI's `LoggedCmd(ctx, step, cmd)`** (a backend's `Runner`): output to the run log, failure via `DieLogged`. `WithSteps(ctx, n)` numbers steps. - **OS-specific code goes behind build tags** in `internal/platform` (`*_darwin.go`, `*_linux.go`, `*_other.go`). diff --git a/docs/content/docs/contributing/_index.md b/docs/content/docs/contributing/_index.md index f3ef141c..4cc1e7e5 100644 --- a/docs/content/docs/contributing/_index.md +++ b/docs/content/docs/contributing/_index.md @@ -114,6 +114,8 @@ Each command checks its arguments and flags before it does anything else, so a u `checkCommands` wraps every command's `Args` in these checks when `NewRoot` builds the tree. A message one of them returns is a usage error: `Execute` prints it, then `usage_help` naming the command's own `--help`, and exits with 2. `usage_error` is only the fallback for a parser error devvm doesn't know. What a command's `RunE` returns once it ran is a failure, which exits with 1, as `Die` does. `TestUsageErrorsEveryCommand` runs every command with an unknown flag, without the argument it needs and with too many, and checks that each is a usage error and nothing runs. +`image.Reserved` lists the words devvm keeps for its commands: every command's and subcommand's name, the hidden ones and `help` too, and the words kept for commands to come. `image.LayerName` refuses them, so `devvm layer new` refuses such a name and the image names leave such a layer file out, and `build.CheckLayers` refuses a layer file named with one, naming the file. A new command's name goes in the list, and `TestEveryCommandReserved` walks the tree to check that it's there. The root's `Args` runs `checkWord` (`internal/cli/word.go`) on a word without `+`: one that isn't base, a shared tool or a layer is a usage error that suggests the closest command, from Cobra's `SuggestionsFor` with `SuggestionsMinimumDistance` 2, and the closest image name within the same distance. devvm's own help command and the root's help func run the same check, so `devvm help WORD` and `devvm WORD --help` fail as `devvm WORD` does. The help func can't return an error, so it panics with a `wordPanic` that `execute` recovers. + ## CLI tests CLI tests are [testscript](https://pkg.go.dev/github.com/rogpeppe/go-internal/testscript) scripts in `testdata/script/*.txtar`, run by `internal/cli/script_test.go` against a freshly built `devvm`. Call it with `exec devvm …`: diff --git a/docs/content/docs/getting-started/commands.md b/docs/content/docs/getting-started/commands.md index 5b175c67..e104ee29 100644 --- a/docs/content/docs/getting-started/commands.md +++ b/docs/content/docs/getting-started/commands.md @@ -180,7 +180,7 @@ With `--backend NAME`, these commands build or delete on that backend instead of | `devvm completion SHELL` | print the shell completion script for `bash`, `zsh` or `fish` ([details](#shell-completion)) | | `devvm limactl ARGS...` | run Lima's `limactl` on the VMs and images in devvm's own Lima home, not `~/.lima` ([details](../backends/lima.md#running-limactl)) | -devvm never reads a command's name as an IMAGE, so `devvm build` runs the build command. To use one of your layers that's named like a command, write it as `base+NAME`. +devvm never reads a command's name as an IMAGE, so `devvm build` runs the build command, and a layer can't take a command's name. When the word after `devvm` is neither a command nor an image, devvm refuses it and suggests the closest command or image name, such as `devvm stop` for `devvm stpo`. `devvm stpo --help` and `devvm help stpo` are refused the same way. The folders devvm keeps its state in and the environment variables it reads are in [Settings and files](../using/settings.md). diff --git a/docs/content/docs/using/customizing.md b/docs/content/docs/using/customizing.md index a4d8f8fa..7fd4deda 100644 --- a/docs/content/docs/using/customizing.md +++ b/docs/content/docs/using/customizing.md @@ -15,7 +15,7 @@ devvm node+mailpit # a VM with node and your layer; or devvm build mailp A [layer](images.md#layers) is a script, `~/.config/devvm/layers/.sh`, that bash runs once as the VM's user, who has sudo, in an image on top of its parent. `devvm layer new NAME` writes a starter script, and also `NAME.policy` next to it unless that file exists. It refuses to overwrite a script that exists. -- **Names** are made of lowercase letters, digits and dashes, and start with a letter or digit. A name can't be `base`, a [built-in layer's](images.md#built-in-layers) name (`docker` or `nix`) or a shared tool's name (`node`, `claude` and so on). +- **Names** are made of lowercase letters, digits and dashes, and start with a letter or digit. A name can't be `base`, a [built-in layer's](images.md#built-in-layers) name (`docker` or `nix`) or a shared tool's name (`node`, `claude` and so on). It also can't be a word devvm keeps for its commands, such as `stop`, `log` or `add`, so `devvm stop` always runs the command. devvm refuses a layer file already in the folder with such a name wherever an image names it, and you rename the file to use it. - Built-in layers go in the same image names as yours, as in `devvm node+docker+mailpit`. - Put PATH changes in `~/.profile`. - Download files with `devvm-fetch URL SHA256 OUT`, which `base` installs. It fails when the file's checksum doesn't match. diff --git a/internal/build/build.go b/internal/build/build.go index 98d46a04..3259aa18 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -179,9 +179,15 @@ func (b *Env) Environments() []string { // CheckLayers refuses an image name with a part that isn't base, a shared // tool, a built-in layer or one of the user's layers. Names become file names: nothing else -// gets past it. +// gets past it. A layer of the user's named with a word devvm keeps for +// its commands is refused, naming its file. func (b *Env) CheckLayers(name string) error { for p := range strings.SplitSeq(name, "+") { + if image.IsReserved(p) { + if fi, err := os.Stat(b.userLayer(p)); err == nil && fi.Mode().IsRegular() { + return msg.LayerIsCommand(b.userLayer(p), p) + } + } if p != image.Base && !image.IsTool(p) && (!image.LayerName(p) || !b.isLayer(p)) { return msg.UnknownLayer(strings.Join(image.Agents, " "), strings.Join(b.Environments(), " "), p) } diff --git a/internal/build/layer.go b/internal/build/layer.go index 99164153..decb8174 100644 --- a/internal/build/layer.go +++ b/internal/build/layer.go @@ -32,12 +32,14 @@ const layerPolicy = `# Hosts a VM with the NAME layer can reach with network pol ` // CheckLayerName refuses a name a new layer can't have: base's, a shared -// tool's or a built-in layer's, or one that isn't lowercase letters, -// digits and dashes. +// tool's or a built-in layer's, a word devvm keeps for its commands, or +// one that isn't lowercase letters, digits and dashes. func CheckLayerName(name string) error { switch { case name == image.Base || image.IsTool(name) || image.IsBuiltin(name): return msg.LayerNameReserved(name) + case image.IsReserved(name): + return msg.LayerNameCommand(name) case !image.LayerName(name): return msg.LayerNameInvalid(name) } diff --git a/internal/cli/args.go b/internal/cli/args.go index cdd7bfb1..a0eba231 100644 --- a/internal/cli/args.go +++ b/internal/cli/args.go @@ -58,26 +58,7 @@ func checkCommands(root *cobra.Command) { root.SetFlagErrorFunc(func(c *cobra.Command, err error) error { return usage(flagError(c, err)) }) var walk func(c *cobra.Command) walk = func(c *cobra.Command) { - args := c.Args - c.Args = func(cmd *cobra.Command, a []string) error { - if err := checkFlags(cmd); err != nil { - return usage(err) - } - if args != nil { - if err := args(cmd, a); err != nil { - return usage(err) - } - } - return nil - } - if run := c.RunE; run != nil { - c.RunE = func(cmd *cobra.Command, a []string) error { - if err := run(cmd, a); err != nil { - return ranError{err} - } - return nil - } - } + checkCommand(c) for _, sub := range c.Commands() { walk(sub) } @@ -85,6 +66,31 @@ func checkCommands(root *cobra.Command) { walk(root) } +// checkCommand is what checkCommands does to each command: c checks its +// flags and arguments first, and RunE's errors are failures. +func checkCommand(c *cobra.Command) { + args := c.Args + c.Args = func(cmd *cobra.Command, a []string) error { + if err := checkFlags(cmd); err != nil { + return usage(err) + } + if args != nil { + if err := args(cmd, a); err != nil { + return usage(err) + } + } + return nil + } + if run := c.RunE; run != nil { + c.RunE = func(cmd *cobra.Command, a []string) error { + if err := run(cmd, a); err != nil { + return ranError{err} + } + return nil + } + } +} + // argsOf is the arguments in c's Use, without its flags: KEY_FILE, // [all|none|LIST], RULE...; "" for none. func argsOf(c *cobra.Command) string { diff --git a/internal/cli/root.go b/internal/cli/root.go index 628e4d03..52eaa6f0 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -4,6 +4,7 @@ package cli import ( "context" "errors" + "strings" "github.com/spf13/cobra" @@ -42,10 +43,16 @@ func NewRoot(u *ui.UI) *cobra.Command { autoRetain(cmd.Context(), u) } }, - Args: maxArgs(1), + Args: cobra.MatchAll(maxArgs(1), func(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + return nil + } + return checkWord(cmd, args[0]) + }), RunE: func(cmd *cobra.Command, args []string) error { return up(cmd.Context(), u, g, uf, args) }, + SuggestionsMinimumDistance: suggestDistance, } root.SetOut(u.Stdout()) addGlobals(root, g) @@ -56,6 +63,7 @@ func NewRoot(u *ui.UI) *cobra.Command { newRetentionCmd(u), newVersionCmd(u), newCompletionCmd(u)) addCompletions(root, u) checkCommands(root) + addHelp(root) return root } @@ -81,7 +89,17 @@ func Execute(ctx context.Context, u *ui.UI, args []string) int { } // execute runs root with args, as Execute does. -func execute(ctx context.Context, u *ui.UI, root *cobra.Command, args []string) int { +func execute(ctx context.Context, u *ui.UI, root *cobra.Command, args []string) (code int) { + defer func() { + if p := recover(); p != nil { + w, ok := p.(wordPanic) + if !ok { + panic(p) + } + printUsage(u, root, w.err) + code = usageCode + } + }() root.SetArgs(args) cmd, err := root.ExecuteContextC(ctx) if err == nil { @@ -98,8 +116,13 @@ func execute(ctx context.Context, u *ui.UI, root *cobra.Command, args []string) u.Error(m) return 1 } - // Anything else is the parser's, before the command ran. - u.Error(usage(err).m) - u.Note(msg.UsageHelp(cmd.CommandPath())) + // Anything else is the parser's, before the command ran. A word that's + // neither a command nor an image is devvm's, whichever command (help) + // refused it. + e := usage(err) + if strings.HasPrefix(e.m.ID(), "no_command_or_image") { + cmd = root + } + printUsage(u, cmd, e) return usageCode } diff --git a/internal/cli/word.go b/internal/cli/word.go new file mode 100644 index 00000000..21fcee6a --- /dev/null +++ b/internal/cli/word.go @@ -0,0 +1,177 @@ +package cli + +import ( + "errors" + "slices" + "strings" + + "github.com/spf13/cobra" + + "github.com/w3cj/devvm/internal/build" + "github.com/w3cj/devvm/internal/image" + "github.com/w3cj/devvm/internal/msg" + "github.com/w3cj/devvm/internal/paths" + "github.com/w3cj/devvm/internal/ui" +) + +// suggestDistance is how far, in Levenshtein distance, a word can be from +// a command's or an image's name for devvm to suggest it. +const suggestDistance = 2 + +// checkWord refuses devvm WORD when WORD is neither a command (which the +// parser would have run) nor an image: no +, and not base, a shared tool +// or a layer. It suggests the closest command and the closest image name +// when one is close. A layer of the user's named with a word devvm keeps +// for its commands is refused, naming its file. Image names with + are +// left to the VM's launch, which checks each part. +func checkWord(root *cobra.Command, word string) error { + if strings.Contains(word, "+") { + return nil + } + dirs, err := paths.FromEnv() + if err != nil { + return nil //nolint:nilerr // without its folders, devvm says why once it runs + } + b := &build.Env{Dirs: dirs} + images := slices.Concat(b.Environments(), image.Agents) + if slices.Contains(images, word) { + return nil + } + if image.IsReserved(word) { + if m, ok := errors.AsType[msg.M](b.CheckLayers(word)); ok && m.ID() == "layer_is_command" { + return m + } + } + // Cobra's suggestions, by distance or as a prefix: the closest first. + command := "" + if s := root.SuggestionsFor(word); len(s) > 0 { + command = s[0] + if c := closest(word, s); c != "" { + command = c + } + } + img := closest(word, images) + switch { + case command != "" && img != "": + return msg.NoCommandOrImageBoth(command, img, msg.Shown(word)) + case command != "": + return msg.NoCommandOrImageCommand(command, msg.Shown(word)) + case img != "": + return msg.NoCommandOrImageImage(img, msg.Shown(word)) + } + return msg.NoCommandOrImage(msg.Shown(word)) +} + +// closest is the name in names closest to word, ignoring case, within +// suggestDistance; "" when none is. +func closest(word string, names []string) string { + best, bestD := "", suggestDistance+1 + for _, n := range names { + if d := levenshtein(strings.ToLower(word), strings.ToLower(n)); d < bestD { + best, bestD = n, d + } + } + return best +} + +// levenshtein is the edit distance between a and b, by runes. +func levenshtein(a, b string) int { + ra, rb := []rune(a), []rune(b) + prev := make([]int, len(rb)+1) + for j := range prev { + prev[j] = j + } + for i := 1; i <= len(ra); i++ { + cur := make([]int, len(rb)+1) + cur[0] = i + for j := 1; j <= len(rb); j++ { + cost := 1 + if ra[i-1] == rb[j-1] { + cost = 0 + } + cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost) + } + prev = cur + } + return prev[len(rb)] +} + +// wordPanic is what the root's help panics with for devvm WORD --help +// when WORD is neither a command nor an image: execute recovers it and +// fails as for devvm WORD, since the help can't return an error. +type wordPanic struct{ err usageError } + +// addHelp gives root devvm's own help command, devvm help [COMMAND], and +// a help that refuses a word that's neither a command nor an image, as +// devvm WORD does: devvm help WORD and devvm WORD --help fail the same +// way instead of printing the root's help. +func addHelp(root *cobra.Command) { + help := &cobra.Command{ + Use: "help [COMMAND]", + Short: "Help about any command", + Long: "Print the help of devvm, or of COMMAND, as devvm COMMAND --help does.", + Args: func(c *cobra.Command, args []string) error { + _, err := helpTarget(c.Root(), args) + return err + }, + ValidArgsFunction: func(c *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { + target, _, err := c.Root().Find(args) + if err != nil { + return nil, cobra.ShellCompDirectiveNoFileComp + } + var out []cobra.Completion + for _, sub := range target.Commands() { + if sub.IsAvailableCommand() && strings.HasPrefix(sub.Name(), toComplete) { + out = append(out, sub.Name()) + } + } + return out, cobra.ShellCompDirectiveNoFileComp + }, + RunE: func(c *cobra.Command, args []string) error { + target, err := helpTarget(c.Root(), args) + if err != nil { + return err + } + target.InitDefaultHelpFlag() + return target.Help() + }, + } + checkCommand(help) + root.SetHelpCommand(help) + shown := root.HelpFunc() + root.SetHelpFunc(func(c *cobra.Command, args []string) { + if c == root { + if words := c.Flags().Args(); len(words) > 0 { + if err := checkWord(root, words[0]); err != nil { + panic(wordPanic{usage(err)}) + } + } + } + shown(c, args) + }) +} + +// helpTarget is the command devvm help ARGS shows: a word that's neither +// a command nor an image is refused, as devvm WORD refuses it, and one +// under a command with commands of its own as that command refuses it. +func helpTarget(root *cobra.Command, args []string) (*cobra.Command, error) { + target, rest, err := root.Find(args) + switch { + case err != nil: + return nil, err + case len(rest) == 0: + return target, nil + case target == root: + return root, checkWord(root, rest[0]) + case target.HasAvailableSubCommands(): + return nil, noArgs(target, rest[:1]) + } + return target, nil +} + +// printUsage prints a usage error: its message, then the line naming +// cmd's own --help. +func printUsage(u *ui.UI, cmd *cobra.Command, e usageError) { + u.Error(e.m) + u.Note(msg.UsageHelp(cmd.CommandPath())) +} diff --git a/internal/cli/word_test.go b/internal/cli/word_test.go new file mode 100644 index 00000000..7d1d0327 --- /dev/null +++ b/internal/cli/word_test.go @@ -0,0 +1,114 @@ +package cli + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/w3cj/devvm/internal/image" +) + +// Every command's name, hidden or not, and help's, is a word devvm keeps: +// no layer can take one. +func TestEveryCommandReserved(t *testing.T) { + t.Parallel() + u, _, _ := testUI() + names := []string{"help"} + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + names = append(names, sub.Name()) + walk(sub) + } + } + walk(NewRoot(u)) + for _, n := range names { + if !image.IsReserved(n) { + t.Errorf("command %s isn't in image.Reserved", n) + } + } +} + +// Base, the shared tools and the built-in layers are images, so none is +// a word devvm keeps for its commands. +func TestImagesNotReserved(t *testing.T) { + t.Parallel() + for _, n := range slices.Concat([]string{image.Base}, image.Toolchains, image.Agents, image.Builtins) { + if image.IsReserved(n) { + t.Errorf("%s is an image's name and a reserved word", n) + } + } +} + +func TestLevenshtein(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + a, b string + want int + }{ + {"", "", 0}, {"stop", "stop", 0}, {"sotp", "stop", 2}, {"nodee", "node", 1}, {"", "ab", 2}, {"kitten", "sitting", 3}, + } { + if got := levenshtein(tc.a, tc.b); got != tc.want { + t.Errorf("levenshtein(%q, %q) = %d, want %d", tc.a, tc.b, got, tc.want) + } + } + if got := closest("Pyhton", []string{"node", "python"}); got != "python" { + t.Errorf("closest(Pyhton) = %q, want python", got) + } + if got := closest("zzz", []string{"node", "python"}); got != "" { + t.Errorf("closest(zzz) = %q, want none", got) + } +} + +// devvm WORD, devvm WORD --help and devvm help WORD, for a word that's +// neither a command nor an image, fail alike: a usage error suggesting +// the closest command or image, naming devvm --help, and nothing runs. +// An image's name, joined with + or not, goes on to up. +func TestUnknownWord(t *testing.T) { + t.Setenv("DEVVM_MESSAGES", "names") + cfg := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", cfg) + t.Setenv("XDG_DATA_HOME", t.TempDir()) + if err := os.MkdirAll(filepath.Join(cfg, "devvm", "layers"), 0o700); err != nil { + t.Fatal(err) + } + for _, l := range []string{"pg", "link"} { + if err := os.WriteFile(filepath.Join(cfg, "devvm", "layers", l+".sh"), nil, 0o600); err != nil { + t.Fatal(err) + } + } + for _, tc := range []struct { + args []string + want string // the first line; "" for up running + }{ + {[]string{"stoop"}, "no_command_or_image_command command=stop word=stoop"}, + {[]string{"stoop", "--help"}, "no_command_or_image_command command=stop word=stoop"}, + {[]string{"help", "stoop"}, "no_command_or_image_command command=stop word=stoop"}, + {[]string{"imagse"}, "no_command_or_image_command command=images word=imagse"}, + {[]string{"pyton"}, "no_command_or_image_image image=python word=pyton"}, + {[]string{"pq"}, "no_command_or_image_both command=gc image=pg word=pq"}, + {[]string{"xyzzy"}, "no_command_or_image word=xyzzy"}, + {[]string{"link"}, "layer_is_command file=" + filepath.Join(cfg, "devvm", "layers", "link.sh") + " layer=link"}, + {[]string{"help", "tools", "nope"}, "no_subcommand command=devvm tools commands=add, rm, update given=nope"}, + {[]string{"pg"}, ""}, + {[]string{"node+sotp"}, ""}, + {[]string{"claude"}, ""}, + } { + s := stubbed(nil) + code := s.run(t, tc.args...) + got, _, _ := strings.Cut(s.errOut.String(), "\n") + if tc.want == "" { + if code != 0 || !slices.Equal(s.ran, []string{"devvm"}) { + t.Errorf("devvm %q: exit %d, ran %q, stderr %q; want up run", tc.args, code, s.ran, s.errOut) + } + continue + } + if code != usageCode || len(s.ran) > 0 || got != "devvm: "+tc.want { + t.Errorf("devvm %q: exit %d, ran %q, stderr %q; want %d and %q", tc.args, code, s.ran, s.errOut, usageCode, tc.want) + } + } +} diff --git a/internal/image/key.go b/internal/image/key.go index 85da5d7c..ad16b626 100644 --- a/internal/image/key.go +++ b/internal/image/key.go @@ -109,10 +109,11 @@ func (in Inputs) Outdated(chain Chain) ([]string, error) { } // LayerName reports whether a layer can have that name: lowercase letters, -// digits and dashes, starting with a letter or digit, and neither base nor -// a shared tool's name. Image names join layers with +. +// digits and dashes, starting with a letter or digit, and neither base, a +// shared tool's name nor a word devvm keeps for its commands. Image names +// join layers with +. func LayerName(name string) bool { - return name != Base && !IsTool(name) && layerName.MatchString(name) + return name != Base && !IsTool(name) && !IsReserved(name) && layerName.MatchString(name) } // DockerLayer is the built-in layer with Docker's engine. diff --git a/internal/image/reserved.go b/internal/image/reserved.go new file mode 100644 index 00000000..aa59e3d2 --- /dev/null +++ b/internal/image/reserved.go @@ -0,0 +1,25 @@ +package image + +import "slices" + +// Reserved are the words devvm keeps for its commands: every command's +// and subcommand's name, the hidden ones too, and the words kept for +// commands to come. A layer can't take one, so devvm WORD never means both +// a command and an image. A test checks that every command's name is +// here. +var Reserved = []string{ + // devvm's commands. + "adopt", "build", "code", "completion", "desktop", "doctor", "gc", "git-protect", "help", "history", + "host", "images", "layer", "limactl", "ls", "network", "ports", "rebuild", "restart", "retention", + "rm", "secret", "setup", "size", "space", "ssh-agent", "stop", "tools", "version", + // The hidden ones. + "_docker-connect", "_docker-ports", "_lima-ports", "_msg", "_proxy", "_qemu", "_refresh-tools", + "_smolvm-ports", + // Their commands. + "add", "allow", "deny", "export", "get", "log", "new", "set", "unuse", "update", "use", + // Kept for links between VMs. + "group", "join", "leave", "link", "publish", "unpublish", +} + +// IsReserved reports whether a word is one devvm keeps for its commands. +func IsReserved(name string) bool { return slices.Contains(Reserved, name) } diff --git a/internal/msg/docs.go b/internal/msg/docs.go index 68103b0b..9285268c 100644 --- a/internal/msg/docs.go +++ b/internal/msg/docs.go @@ -359,4 +359,10 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede "flag_bad_value": "using/troubleshooting#a-command-is-refused-before-it-runs", "flag_bad_switch": "using/troubleshooting#a-command-is-refused-before-it-runs", "flags_exclusive": "using/troubleshooting#a-command-is-refused-before-it-runs", + "no_command_or_image": "getting-started/commands#devvm-itself", + "no_command_or_image_command": "getting-started/commands#devvm-itself", + "no_command_or_image_image": "getting-started/commands#devvm-itself", + "no_command_or_image_both": "getting-started/commands#devvm-itself", + "layer_name_command": "using/customizing#your-own-layers", + "layer_is_command": "using/customizing#your-own-layers", } diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index cc7bab7a..3cd8d92d 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -1539,6 +1539,16 @@ func LayerExists(file string) M { return M{id: "layer_exists", vals: []val{{"file", file}}} } +// LayerIsCommand is [layer_is_command]: "Your layer {{.file}} is named {{.layer}}, a word devvm keeps for its commands, so devvm can't use it. Rename the file." +func LayerIsCommand(file string, layer string) M { + return M{id: "layer_is_command", vals: []val{{"file", file}, {"layer", layer}}} +} + +// LayerNameCommand is [layer_name_command]: "{{.layer}} is a word devvm keeps for its commands. Choose another name for your layer." +func LayerNameCommand(layer string) M { + return M{id: "layer_name_command", vals: []val{{"layer", layer}}} +} + // LayerNameInvalid is [layer_name_invalid]: "{{.layer}} can't be a layer's name. Use lowercase letters, digits and dashes, starting with a letter or a digit." func LayerNameInvalid(layer string) M { return M{id: "layer_name_invalid", vals: []val{{"layer", layer}}} @@ -1864,6 +1874,26 @@ func NoCodeCommand(host string) M { return M{id: "no_code_command", vals: []val{{"host", host}}} } +// NoCommandOrImage is [no_command_or_image]: "There's no devvm command or image named {{.word}}." +func NoCommandOrImage(word string) M { + return M{id: "no_command_or_image", vals: []val{{"word", word}}} +} + +// NoCommandOrImageBoth is [no_command_or_image_both]: "There's no devvm command or image named {{.word}}. Did you mean devvm {{.command}} or the image {{.image}}?" +func NoCommandOrImageBoth(command string, image string, word string) M { + return M{id: "no_command_or_image_both", vals: []val{{"command", command}, {"image", image}, {"word", word}}} +} + +// NoCommandOrImageCommand is [no_command_or_image_command]: "There's no devvm command or image named {{.word}}. Did you mean devvm {{.command}}?" +func NoCommandOrImageCommand(command string, word string) M { + return M{id: "no_command_or_image_command", vals: []val{{"command", command}, {"word", word}}} +} + +// NoCommandOrImageImage is [no_command_or_image_image]: "There's no devvm command or image named {{.word}}. Did you mean the image {{.image}}?" +func NoCommandOrImageImage(image string, word string) M { + return M{id: "no_command_or_image_image", vals: []val{{"image", image}, {"word", word}}} +} + // NoDevcontainerFlagIgnored is [no_devcontainer_flag_ignored]: "The --no-devcontainer flag applies only to new VMs." func NoDevcontainerFlagIgnored() M { return M{id: "no_devcontainer_flag_ignored"} @@ -3228,6 +3258,8 @@ var specs = map[string]spec{ "kvm_access": {fields: []string{"fix"}}, "layer_created": {fields: []string{"layer", "policy", "script"}}, "layer_exists": {fields: []string{"file"}}, + "layer_is_command": {fields: []string{"file", "layer"}}, + "layer_name_command": {fields: []string{"layer"}}, "layer_name_invalid": {fields: []string{"layer"}}, "layer_name_reserved": {fields: []string{"layer"}}, "layer_new_failed": {fields: []string{"reason"}}, @@ -3293,6 +3325,10 @@ var specs = map[string]spec{ "newer_tools": {fields: []string{"tools"}}, "no_claude_token": {fields: []string{"vm"}}, "no_code_command": {fields: []string{"host"}}, + "no_command_or_image": {fields: []string{"word"}}, + "no_command_or_image_both": {fields: []string{"command", "image", "word"}}, + "no_command_or_image_command": {fields: []string{"command", "word"}}, + "no_command_or_image_image": {fields: []string{"image", "word"}}, "no_devcontainer_flag_ignored": {}, "no_digest": {fields: []string{"from"}}, "no_feature": {fields: []string{"feature", "features"}}, diff --git a/internal/structure/structure_test.go b/internal/structure/structure_test.go index 728b7c85..b21d4ebd 100644 --- a/internal/structure/structure_test.go +++ b/internal/structure/structure_test.go @@ -49,6 +49,7 @@ func devvm() rules { "internal/image.Toolchains": table, "internal/image.Agents": table, "internal/image.Builtins": table, + "internal/image.Reserved": table, "internal/msg.docs": table, "internal/msg/gen.taken": table, "internal/msg/gen.initialisms": table, diff --git a/locales/en.toml b/locales/en.toml index 1db477de..f9cb2132 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -513,6 +513,29 @@ other = "{{.layer}} can't be a layer's name. Use lowercase letters, digits and d [layer_name_reserved] other = "{{.layer}} is the name of one of devvm's own images. Choose another name for your layer." +[layer_name_command] +other = "{{.layer}} is a word devvm keeps for its commands. Choose another name for your layer." + +[layer_is_command] +description = "file is the layer's script in the layers folder" +other = "Your layer {{.file}} is named {{.layer}}, a word devvm keeps for its commands, so devvm can't use it. Rename the file." + +[no_command_or_image] +description = "word is what was typed after devvm: neither a command nor an image's name" +other = "There's no devvm command or image named {{.word}}." + +[no_command_or_image_command] +description = "command is the devvm command closest to word" +other = "There's no devvm command or image named {{.word}}. Did you mean devvm {{.command}}?" + +[no_command_or_image_image] +description = "image is the image name closest to word" +other = "There's no devvm command or image named {{.word}}. Did you mean the image {{.image}}?" + +[no_command_or_image_both] +description = "command is the devvm command and image the image name closest to word" +other = "There's no devvm command or image named {{.word}}. Did you mean devvm {{.command}} or the image {{.image}}?" + [layer_exists] other = "{{.file}} already exists. Edit it, or choose another name." diff --git a/testdata/script/layer.txtar b/testdata/script/layer.txtar index 8880fe62..3da4f9a8 100644 --- a/testdata/script/layer.txtar +++ b/testdata/script/layer.txtar @@ -34,6 +34,13 @@ stderr '^devvm: layer_name_reserved layer=docker$' ! exec devvm layer new nix stderr '^devvm: layer_name_reserved layer=nix$' ! exists $LAYERS/nix.sh +! exec devvm layer new stop +stderr '^devvm: layer_name_command layer=stop$' +! exec devvm layer new add +stderr '^devvm: layer_name_command layer=add$' +! exec devvm layer new link +stderr '^devvm: layer_name_command layer=link$' +! exists $LAYERS/stop.sh ! exec devvm layer new My_DB stderr '^devvm: layer_name_invalid layer=My_DB$' ! exec devvm layer new ../x @@ -47,6 +54,20 @@ stderr '^devvm: no_subcommand command=devvm layer commands=new given=pg$' ! exists $LAYERS/node.sh ! exists $LAYERS/My_DB.sh +# A layer file named with a word devvm keeps for its commands is refused +# wherever an image names it, and images don't complete it; devvm stop +# stays the command. +cp $LAYERS/pg.sh $LAYERS/log.sh +! exec devvm build log +stderr '^devvm: layer_is_command file=\S*/devvm/layers/log\.sh layer=log$' +! exec devvm build node+log +stderr '^devvm: layer_is_command file=\S*/devvm/layers/log\.sh layer=log$' +! exec devvm log +stderr '^devvm: layer_is_command file=\S*/devvm/layers/log\.sh layer=log$' +exec devvm __complete build l +! stdout '^log$' +rm $LAYERS/log.sh + # A layers folder that can't be written to fails it. rm $LAYERS exec sh -c 'printf x > "$LAYERS"' diff --git a/testdata/script/up_checks.txtar b/testdata/script/up_checks.txtar index 203f0cd3..037920ef 100644 --- a/testdata/script/up_checks.txtar +++ b/testdata/script/up_checks.txtar @@ -79,6 +79,9 @@ cp $WORK/package.json package.json exec sh -c ': > "$STUB_LOG"' ! exec devvm --no-network-policy stray ! stdout detected +stderr '^devvm: no_command_or_image word=stray$' +stderr '^usage_help command=devvm$' +! exec devvm --no-network-policy node+stray stderr '^devvm: unknown_layer agents=claude codex opencode envs=base node python rust go docker foo nix layer=stray$' stub_calls ! stdout 'create|clone|start' diff --git a/tests/e2e.sh b/tests/e2e.sh index 00651e9d..cd74d73c 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -9,7 +9,7 @@ # port through devvm's forwarder (never a port a program here has), ssh by # name with pinned host keys, .git protection and shell, then devvm stop, opening it # again, restart, devvm size, devvm ports (a running VM's at once, never a listed port a -# program here has, a bad list a usage error), +# program here has, a bad list a usage error), a mistyped command refused with a suggestion, # devvm git-protect and rm, a VM from a devcontainer.json (its ports, variables, commands # once and at each start, a changed file, an image on this machine's registry refused), an agent VM's folders and history (devvm history export, rm's export), and SSH agent forwarding # (a throwaway agent's, and devvm's own with a throwaway key); clone makes a --clone @@ -992,6 +992,9 @@ check "a running VM's new ports apply at once" bash -c "cd '$p' && check "a bad port list is a usage error, exit 2, naming devvm ports --help, and the VM's ports stay" bash -c "cd '$p' && { '$D' ports 47170-x '$work/last.log' 2>&1; [[ \$? == 2 ]]; } && grep -qxF \"\$(m usage_help 'command=devvm ports')\" '$work/last.log' && [[ \$('$D' ports 2>/dev/null) == 47170-47173 ]]" +check "a word that's neither a command nor an image is a usage error suggesting the command, and the VM runs on" bash -c "cd '$p' && + { '$D' stoop '$work/last.log' 2>&1; [[ \$? == 2 ]]; } && + grep -qF \"\$(m no_command_or_image_command command=stop word=stoop)\" '$work/last.log' && [[ \$(status_of $vm) == Running ]]" check "a port added to a running VM reaches this machine at once, and once removed doesn't, the VM never restarted" ports_live "$p" "$vm" 47178 lima_serve lima_boot in_vm "$vm" 'pkill -f "[h]ttp.server -b 0.0.0.0 47178"' >/dev/null 2>&1 check "its new size waits for its next start" bash -c "cd '$p' && '$D' size --cpus 3 2>&1 | grep -qF \"\$(m size_next_start vm=$vm)\" &&