feat(cli): --json on every command that shows or lists

ls, images, tools, size, ports, network (and -g), network log (and
--blocked), ssh-agent, git-protect, secret, history, space, retention and
doctor take --json: one JSON object on stdout with "version": 1 first,
messages on stderr (ui.DataOnly), lists [] when empty. Settings commands
only show with --json and refuse a value (json_shows_only). doctor --json
replaces --fixes: problems with key, fix (null without one) and message,
warnings, docker and every backend's features; it prints nothing else and
succeeds whatever is missing, and install.sh reads its problems with awk.
TestJSONShapes holds each command's field names and types. Each shape is
documented on its command's page, with the contract under Everyday
commands' Output for scripts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
w3cjandClaude Opus 5.5 committed 2026-11-01 03:06:56 -08:00
1 parent fe32d2a01c
commit cd6fc60576
90 files changed
+2093 -388

No files matched your search

+1 -1
View File
@@ -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), `word.go` devvm WORD's and help's words (did-you-mean); `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); `json.go`: `--json` (`printJSON`, `"version": 1`), its shapes in `json_test.go`; `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 |
+2 -2
View File
@@ -16,8 +16,8 @@ devvm doctor [flags]
## Options
```text
--fixes print only what's missing, for scripts: a KEY<tab>FIX<tab>MESSAGE line each, FIX being a command or empty; succeeds either way
-h, --help help for doctor
-h, --help help for doctor
--json print what it found as one JSON object, for scripts, and nothing else; succeeds whatever is missing
```
## Options inherited from parent commands
@@ -17,6 +17,7 @@ devvm git-protect [on|strict|off] [flags]
```text
-h, --help help for git-protect
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -17,6 +17,7 @@ devvm history [flags]
```text
-h, --help help for history
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -17,6 +17,7 @@ devvm images [flags]
```text
-h, --help help for images
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -17,6 +17,7 @@ devvm ls [flags]
```text
-h, --help help for ls
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -18,6 +18,7 @@ devvm network [on|off] [flags]
```text
-g, --global show or change whether new VMs get network policy instead
-h, --help help for network
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
@@ -19,6 +19,7 @@ devvm network log [flags]
--blocked list the blocks by host and port, with the command that allows each
-f, --follow then show each new one as it happens, until interrupted
-h, --help help for log
--json print it as one JSON object, for scripts
-n, --lines N show the last N connections and requests (default 50)
```
+1
View File
@@ -18,6 +18,7 @@ devvm ports [all|none|LIST] [flags]
```text
-g, --global show or change what new VMs forward instead
-h, --help help for ports
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -17,6 +17,7 @@ devvm retention [KEY=VALUE...] [flags]
```text
-h, --help help for retention
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -17,6 +17,7 @@ devvm secret [flags]
```text
-h, --help help for secret
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -20,6 +20,7 @@ devvm size [flags]
--disk GiB the VM's disk in GiB, at least what it has
-g, --global show or change the size new VMs get instead
-h, --help help for size
--json print it as one JSON object, for scripts
--memory GiB the VM's memory in GiB: 16, 16G or 16GiB
```
+1 -1
View File
@@ -17,7 +17,7 @@ devvm space [flags]
```text
-h, --help help for space
--json print it as JSON, for scripts
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -17,6 +17,7 @@ devvm ssh-agent [on|devvm|off] [flags]
```text
-h, --help help for ssh-agent
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+1
View File
@@ -17,6 +17,7 @@ devvm tools [flags]
```text
-h, --help help for tools
--json print it as one JSON object, for scripts
```
## Options inherited from parent commands
+9 -1
View File
@@ -302,7 +302,7 @@ Tables on `Stdout()` are colored as stdout is. A command gets a `ui.Table` from
- devvm space: `only copy` and `leftover` in KEPT need attention.
- devvm doctor: `native` is good, `emulated` needs attention, and `unreviewed` and `none` are bad.
`doctor --fixes` lines and devvm space `--json` are for scripts and stay plain.
Every command's `--json` output is for scripts and stays plain.
`mise run test` unsets `NO_COLOR`, `FORCE_COLOR` and `CLICOLOR_FORCE`, and `tests/e2e.sh` unsets the last two, so your own settings never change what they check.
@@ -310,6 +310,14 @@ Tables on `Stdout()` are colored as stdout is. A command gets a `ui.Table` from
A translation is `locales/<language>.toml` (`de.toml`) with the same tables, `one` and `other` translated (and the language's other plural forms, such as `few`), loaded by go-i18n the same way. Doc links are the same in every language: the docs site is English. devvm picks the language from the first of `LC_ALL`, `LC_MESSAGES` and `LANG` that is set (`de_DE.UTF-8` is German); `C` and `POSIX` are English. A message missing from a translation is shown in English.
## JSON output
Every command that shows or lists something takes `--json`, which `jsonFlag` in `internal/cli/json.go` adds. The command builds a struct of its own with snake_case `json` tags, next to the code that writes its table, and writes it with `printJSON`, which puts `"version": 1` (`jsonVersion`) first, writes HTML characters as they are and refuses anything but an object. A list it prints is never `nil`, so it's `[]` rather than `null`, and a field that doesn't apply is `omitempty`. Sizes are bytes unless the field's name gives the unit, as in `memory_gib`.
The root command's `PersistentPreRun` calls `u.DataOnly()` for any command given `--json`, so `Say`, `Info` and `LogNote` print to stderr from then on, and stdout gets only the JSON. A settings command that also changes its setting with a value wraps its `Args` in `showsOnly`, which refuses the value with `--json` (`json_shows_only`) before anything else runs.
`TestJSONShapes` in `internal/cli/json_test.go` holds each command's shape, a `path: type` line for each field of a sample with every field set. A field renamed, removed or given another type fails it. Shapes only gain fields, so a new field goes into the sample and the test, and any other change raises `jsonVersion`. A new command that shows or lists something gets `--json`, a row in that test, a CLI test and a section on its page with an example, which [output for scripts](../getting-started/commands.md#output-for-scripts) links to.
## Writing docs
The site is [Hugo](https://gohugo.io) with the [Hextra](https://imfing.github.io/hextra/) theme, built from `docs/`. Hextra is a Hugo module pinned in `docs/go.mod`; update it with `hugo mod get github.com/imfing/hextra@<version>` in `docs/`.
+47 -1
View File
@@ -123,6 +123,28 @@ A subfolder that is a git repo of its own is treated as a separate project, and
A value the VM's state doesn't have shows as `-`, so a VM whose creation didn't finish shows only its name, status and backend.
### devvm ls --json
`devvm ls --json` prints the same list as one JSON object, as [output for scripts](#output-for-scripts) describes. `vms` has a VM's columns as fields, sorted by name. `image` is the image alone, and `from` is the container image its base started from, which is left out for a base from Ubuntu's cloud image. `docker_layer` is the runtime a `docker` VM made for the docker layer runs under, and it's left out for other VMs. A value the VM's state doesn't have is `""`.
```json
{
"version": 1,
"vms": [
{
"name": "devvm-website-71a99b1076d92c",
"status": "Running",
"image": "base",
"from": "node:24",
"git": "on",
"net": "on",
"backend": "lima",
"folder": "/Users/you/code/website"
}
]
}
```
## Working on a clone
| | |
@@ -164,7 +186,7 @@ A value the VM's state doesn't have shows as `-`, so a VM whose creation didn't
| `devvm images` | list the images on every backend, then the shared tool images ([details](../using/images.md#listing-images)) |
| `devvm images rm IMAGE\|KEY...` | delete images, by name or by the key `devvm images` shows ([details](../using/images.md#deleting-images)) |
| `devvm gc` | delete the stale and unfinished images and the tool images no VM uses, after listing them, and never a VM ([details](../using/images.md#cleaning-up)) |
| `devvm space [--json]` | show what devvm keeps on this machine, the disk each kind takes, and what frees it ([details](../using/space.md#devvm-space)) |
| `devvm space` | show what devvm keeps on this machine, the disk each kind takes, and what frees it ([details](../using/space.md#devvm-space)) |
| `devvm retention [KEY=VALUE...]` | show the retention settings, which say what devvm deletes on its own, or change them, with `KEY=off` turning one off ([details](../using/settings.md#retention)) |
With `--backend NAME`, these commands build or delete on that backend instead of the one new VMs get. With `--from IMAGE`, they work on a base made from that container image ([details](../using/from.md)).
@@ -193,3 +215,27 @@ The completion script completes commands, flags and image names, including names
| bash | `source <(devvm completion bash)` | `~/.bashrc`, with the bash-completion package installed |
| zsh | `source <(devvm completion zsh)` | `~/.zshrc`, after `compinit` |
| fish | `devvm completion fish \| source` | `~/.config/fish/config.fish` |
## Output for scripts
Every command that shows or lists something takes `--json`, which prints what the command shows as one JSON object instead of a table or lines, so a script can read it. The object's first field is `"version": 1`, and the page for each command lists its other fields with an example. A shape only ever gains fields. devvm adds new fields to version 1, and any other change to a shape, such as a field renamed, removed or given another type, comes with a new version.
With `--json`, standard output gets only the JSON. devvm's messages, such as warnings and notes, still go to standard error, as they do without it, and the JSON is never colored. A list with nothing in it is `[]`, never `null`. Sizes are in bytes, unless a field's name gives the unit, such as `memory_gib`. A field that doesn't apply, such as a VM's `from` when its base is Ubuntu's cloud image, is left out.
A command that shows a setting when you run it bare and changes the setting when you give it a value, such as `devvm network` or `devvm size`, only shows with `--json`. devvm refuses a value given with `--json`, such as `devvm network --json off`, and changes nothing.
| Command | Its JSON |
| --- | --- |
| `devvm ls --json` | [the project VMs](#devvm-ls---json) |
| `devvm images --json` | [the images and the shared tool images](../using/images.md#devvm-images---json) |
| `devvm tools --json` | [this folder's VM's shared tools](../using/toolchains.md#devvm-tools---json) |
| `devvm size --json`, `devvm ports --json` | [this folder's VM's size and ports](../using/ports-size.md#as-json), or with `-g`, new VMs' |
| `devvm network --json` | [this folder's VM's network policy and allowlist](../safety/network.md#devvm-network---json), or with `-g`, new VMs' choice |
| `devvm network log --json` | [this folder's VM's network log, or with `--blocked` its blocks](../safety/network.md#devvm-network-log---json) |
| `devvm secret --json` | [the secrets, whether each is saved and the VMs using it](../safety/network.md#devvm-secret---json) |
| `devvm ssh-agent --json` | [this folder's VM's SSH agent forwarding and devvm's own agent's keys](../using/ssh.md#devvm-ssh-agent---json) |
| `devvm git-protect --json` | [this folder's VM's `.git` protection](../safety/git-protection.md#devvm-git-protect---json) |
| `devvm history --json` | [the saved exports of agents' history](../using/coding-agents.md#devvm-history---json) |
| `devvm space --json` | [what devvm keeps on this machine](../using/space.md#devvm-space---json) |
| `devvm retention --json` | [the retention settings](../using/settings.md#devvm-retention---json) |
| `devvm doctor --json` | [what devvm needs on this machine and what's missing](../internals/install.md#devvm-doctor---json), and it prints nothing else |
+1 -1
View File
@@ -6,7 +6,7 @@ weight: 95
These pages explain how devvm does what the other sections describe, for readers who want to check a claim, such as security reviewers and agents. They name the files devvm ships and the messages it prints. You don't need them to use devvm.
- [Overview](overview.md): what devvm does, step by step, when it makes, opens, stops and deletes a VM, and the state files it keeps.
- [Installing and updating](install.md): what the install script downloads and checks, `devvm doctor --fixes`, devvm's own files, and upgrading.
- [Installing and updating](install.md): what the install script downloads and checks, `devvm doctor --json`, devvm's own files, and upgrading.
- [Images and caching](images.md): how images and shared tools are built, keyed and cached, and how devvm checks what they start from.
- [Port forwarding](ports.md): how devvm's forwarder forwards a VM's ports to your machine.
- [The desktop](desktop.md): how `devvm desktop` serves a VM's desktop on your machine, checks its password and keeps your clipboard out, and why devvm doesn't forward X11.
+36 -6
View File
@@ -3,7 +3,7 @@ title: Installing and updating
weight: 2
---
This page explains what devvm's install script downloads and checks, what `devvm doctor --fixes` reports, where devvm keeps its own files, and what happens to older versions when you upgrade. [Installing](../getting-started/install.md) covers the commands you run.
This page explains what devvm's install script downloads and checks, what `devvm doctor --json` reports, where devvm keeps its own files, and what happens to older versions when you upgrade. [Installing](../getting-started/install.md) covers the commands you run.
## The install script
@@ -12,11 +12,11 @@ The script installs the release it comes with, or the one that `--version` names
1. It downloads the archive for this machine and the release's `SHA256SUMS`, over HTTPS only. The archive is `devvm-<version>-<os>-<arch>.tar.gz`, where the OS is `darwin` or `linux` and the processor is `arm64` or `amd64`. On Apple silicon, the script picks `arm64` even when it runs under Rosetta.
2. It checks the signature of `SHA256SUMS`, then the archive's checksum, as [the signature](#the-signature-and-what-it-trusts) describes. When either check fails, it installs nothing.
3. It puts devvm, which is one binary with its README, changelog and license, in `~/.local/lib/devvm/<version>`, and links `~/.local/bin/devvm` to it. When `~/.local/bin` isn't on `PATH`, the script says how to add it.
4. Unless you pass `--no-deps`, it runs `devvm doctor --fixes` and offers the [fixes](#devvm-doctor---fixes) that devvm reports, asking before each one. Then it runs `devvm doctor`, which shows doctor's warnings too, even when nothing is missing.
4. Unless you pass `--no-deps`, it runs `devvm doctor --json` and offers the [fixes](#devvm-doctor---json) that devvm reports, asking before each one. Then it runs `devvm doctor`, which shows doctor's warnings too, even when nothing is missing.
At the end, when `~/.local/bin` is on `PATH`, the script looks up which devvm `PATH` finds first with `command -v devvm`. It resolves that path's links and those of `~/.local/bin/devvm` with `readlink -f`, and when they differ it warns, naming the other copy's path and saying to remove it or to put `~/.local/bin` first. It only looks the other copy up and never runs it. When `~/.local/bin` isn't on `PATH`, the script prints only how to add it, so you don't get both.
`devvm doctor` makes the same check without `--fixes`. It looks up `devvm` on `PATH`, resolves its links and those of the running binary, and when they differ it prints a warning naming both. It skips the check when no devvm is on `PATH`. The warning doesn't change its exit status, and `--fixes` never prints it, so the install script doesn't offer it as a fix.
`devvm doctor` makes the same check. It looks up `devvm` on `PATH`, resolves its links and those of the running binary, and when they differ it prints a warning naming both. It skips the check when no devvm is on `PATH`. The warning doesn't change its exit status, and `--json` lists it among the warnings rather than the problems, so the install script doesn't offer it as a fix.
On macOS, the [Docker](../backends/docker.md#requirements) backend fetches one more file the first time a Docker VM or build needs it. That file is the same release's Linux archive, and devvm checks the devvm in it against the SHA-256 that the installed devvm has of it before using it. Homebrew's devvm already has its Linux build, which Homebrew builds from source.
@@ -38,9 +38,39 @@ The release's `SHA256SUMS` is signed in `SHA256SUMS.minisig`, made with the main
The signature catches an archive or a `SHA256SUMS` that someone replaced, which the checksum alone can't. It can't catch a release that was replaced whole, because `curl … | bash` runs the `install.sh` from that same release, key included, so the one-liner trusts GitHub's release files. Homebrew doesn't trust them, because the formula's checksum lives in a repository of its own, and a replaced GitHub release wouldn't match it. You can also download `install.sh` and read it before you run it.
## devvm doctor --fixes
## devvm doctor --json
`devvm doctor --fixes` prints only what's missing, one line each, for scripts such as the install script. Each line is `KEY<tab>FIX<tab>MESSAGE`, where `FIX` is a command, or empty when there's none to run, for example when virtualization is turned off in the firmware. The command succeeds either way. Doctor's warnings have no keys, because there's nothing for a script to fix, so `--fixes` never prints them. They're about another devvm on `PATH`, low free space, and a machine with less than 8 GiB of memory or fewer than 4 CPUs. These are the keys:
`devvm doctor --json` prints what doctor finds as one JSON object, for scripts such as the install script, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. It prints nothing else, because its problems and warnings are in the JSON, and it succeeds whatever is missing. A failure that stops the check, such as a backend devvm doesn't have, still goes to standard error and makes it fail.
- `backend` is the backend that doctor checked, the one new VMs get or the one `--backend` names.
- `problems` has what that backend is missing, each with its `key`, the `fix` command, and the `message` that `devvm doctor` prints for it. The `fix` is a command whose words are separated by spaces, without shell syntax, or `null` when there's none to run, for example when virtualization is turned off in the firmware.
- `warnings` has the messages of doctor's warnings, which have no keys, because there's nothing for a script to fix. They're about another devvm on `PATH`, low free space, and a machine with less than 8 GiB of memory or fewer than 4 CPUs.
- `docker` says whether Docker is installed, which only `--from` with an image that only Docker has needs.
- `features` has, for each backend, how it has each feature, as `native`, `emulated`, `unreviewed` or `none`. The example below shows two of Lima's features.
```json
{
"version": 1,
"backend": "lima",
"problems": [
{
"key": "lima",
"fix": "brew install lima",
"message": "Lima isn't installed. Run brew install lima to install it."
}
],
"warnings": [],
"docker": true,
"features": {
"lima": {
"agent-forwarding": "native",
"disk": "native"
}
}
}
```
These are the keys:
| Key | Missing | Fix |
| --- | --- | --- |
@@ -56,7 +86,7 @@ The signature catches an archive or a `SHA256SUMS` that someone replaced, which
| `docker-access` | access to Docker's socket, on Linux | `sudo usermod -aG docker USER`, then log in again |
| `docker-version`, `docker-os`, `docker-arch` | Docker 29.1 or newer, running Linux containers of this machine's processor | none |
The install script offers to fix three of these keys, asking first, and prints the message for the others:
The install script reads `problems` with `awk`, so it needs no JSON tool on this machine. It relies on the layout that devvm writes, with one field on each line, and it reads a problem's `key`, `fix` and `message` from their lines, with their escapes undone. It offers to fix three of these keys, asking first, and prints the message for the others:
- For `lima`, it runs the fix when there is one, which is Homebrew's. Without Homebrew, it offers Lima's latest release instead, which it checks against that release's `SHA256SUMS` and installs into `~/.local`.
- For `qemu` and `kvm-access`, it runs the fix when there is one, and the fix uses sudo. After you join the `kvm` group, the script doesn't run `devvm doctor`, because the group applies only to new logins, and it tells you to log out and back in first.
@@ -29,6 +29,17 @@ devvm git-protect on
On an existing VM, devvm ignores `--no-git-protect` and warns you. A `--clone` VM's protection can't be changed.
### devvm git-protect --json
`devvm git-protect --json` prints the VM's protection as one JSON object with `mode`, which is `on`, `strict`, `off` or `clone`, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. With `--json` the command only shows, so devvm refuses `on`, `strict` or `off` with it.
```json
{
"version": 1,
"mode": "on"
}
```
## Strict
The VM can add a submodule at any time, and `git status` and `git diff` on this machine read the submodule's config. So the submodule's `core.fsmonitor` would run on this machine before the VM's next launch locks it. `devvm git-protect strict` closes that gap by setting `diff.ignoreSubmodules = all` in the locked `.git/config`. `git status` and `git diff` on this machine then never look inside submodules, and they don't show the submodules' changes. `git submodule …` and `--recurse-submodules` still enter them, so for a repo with submodules you don't trust, use [`--clone`](../using/clone.md).
+98
View File
@@ -106,6 +106,32 @@ A rule is what [Rules](#rules) lists, without spaces or a comment. devvm refuses
If a VM was deleted outside devvm, a new VM with its name never gets its rules.
### devvm network --json
`devvm network --json` prints the VM's network policy and its allowlist as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. `policy` is `on`, `off` or `unenforced`, and `allowlist` has each policy file that has rules, in the order the proxy reads them, with its path and its rules. With `-g`, the object has only `policy`, which is what new VMs get: `ask`, `on` or `off`. With `--json` the command only shows, so devvm refuses `on`, `off` or `ask` with it.
```json
{
"version": 1,
"policy": "on",
"allowlist": [
{
"file": "/Users/you/.local/share/devvm/assets/7fdd969856e644e8/layers/base.policy",
"rules": [
"ports.ubuntu.com",
"github.com"
]
},
{
"file": "/Users/you/.local/share/devvm/vms/devvm-some-project-71a99b1076d92c.policy",
"rules": [
"example.com"
]
}
]
}
```
## Inside the VM
Every login in the VM has the proxy settings in its environment (`HTTP_PROXY`, `HTTPS_PROXY` and their lowercase forms, `NO_PROXY` for the VM itself, and `NODE_USE_ENV_PROXY`), and the [CA variables](../using/settings.md#a-companys-ca) that every VM has point the tools that don't read the system's store at devvm's CA. devvm also points apt, sudo, ssh and Docker at the proxy ([how](../internals/network.md#the-vms-setup)). A direct connection fails at once, even as root, and so does DNS, because names resolve in the proxy.
@@ -172,6 +198,30 @@ Saving, deleting, binding and unbinding apply at once to the proxies that are ru
`devvm secret unuse` and `devvm secret rm` take nothing back from a VM without network policy, because the value it got still works wherever it kept it, and devvm says so on `unuse`. Neither command revokes what a VM made with the secret ([what devvm doesn't protect](../internals/security.md#what-it-doesnt-protect)), so rotate it if that matters. Use a fine-grained GitHub token, scoped to the repos your VMs need.
#### devvm secret --json
`devvm secret --json` prints the list as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. Each of the `secrets` has its name, `saved`, which is `true` when it's saved or, for `claude`, in devvm's environment, and `used_by`, the names of the VMs using it. The JSON never holds a secret's value.
```json
{
"version": 1,
"secrets": [
{
"name": "claude",
"saved": true,
"used_by": [
"devvm-some-project-71a99b1076d92c"
]
},
{
"name": "github",
"saved": false,
"used_by": []
}
]
}
```
## Logs
`devvm network log` shows the proxy's decisions for this folder's VM, oldest first, one line each. A line has the time, `allowed`, `BLOCKED` or `cache`, and the host and port. An allowed line then has the rule that allowed it (`, decrypted` for an intercepted tunnel), the request (`GET /user`) and the secrets put in (`, token: github`), a blocked line has why it was blocked, and a `cache` line, a request to the [shared Nix cache](#nix), has the request and what came of it:
@@ -191,6 +241,54 @@ Saving, deleting, binding and unbinding apply at once to the proxies that are ru
`ALLOW WITH` is `-` for a request that the proxy refuses whatever the allowlist says, such as a GitHub call that makes a credential, and for a host that isn't a host name or an address. A VM without network policy logs nothing new, and `devvm network log` says so. The proxy keeps each VM's log to its last 10 to 20 MiB by starting a new file once the current one reaches 10 MiB and keeping one older file, which `devvm network log` reads too. `devvm rm` deletes the VM's logs, and [How it works](../internals/network.md#log-files) describes the files.
### devvm network log --json
`devvm network log --json` prints the last N events as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes, and devvm refuses it with `--follow`. Each of the `events` has what the proxy logged, without the VM's name. That's the `time`, the `event`, the `host` and the `port`, and, when the event has them, the request's `method` and `path`, the `rule` that allowed it, the `reason` it was blocked or what came of a cache request, the request's `User-Agent` header as `agent`, the `secrets` put in, `refused` for a request refused whatever the allowlist says, and the company proxy it went through as `upstream`. The `event` is `tunnel` for an allowed connection, `intercept` for an allowed tunnel that the proxy decrypted, `forward` for an allowed request, `blocked`, or `nix-cache` for a request to the shared Nix cache. A log with nothing in it gives `"events": []`.
```json
{
"version": 1,
"events": [
{
"time": "2026-10-09T10:00:00Z",
"event": "blocked",
"host": "example.com",
"port": 443,
"method": "CONNECT",
"reason": "not on the allowlist"
},
{
"time": "2026-10-09T10:00:06Z",
"event": "forward",
"host": "api.github.com",
"port": 443,
"method": "GET",
"path": "/user",
"secrets": [
"github"
]
}
]
}
```
With `--blocked`, each of the `blocked` has the `last` time it was blocked, the `count`, the `host` and the `port`, and `allow`, the rule that `devvm network allow` takes to allow it. A block that `ALLOW WITH` shows as `-` has no `allow`.
```json
{
"version": 1,
"blocked": [
{
"last": "2026-10-09T10:01:00Z",
"count": 2,
"host": "example.com",
"port": 443,
"allow": "example.com"
}
]
}
```
## Not covered
Anything an allowed host accepts can carry data out, including whatever your secrets allow, such as pushes and API calls.
+19
View File
@@ -83,6 +83,25 @@ Each VM's transcripts and sessions stay in that VM. `devvm history export [FILE]
`devvm history` lists the exports in `~/.local/share/devvm/exports`, oldest first, in a table with a header. It shows each export's file, the VM it's of, that VM's folder, the date and time devvm wrote it, and its size, with `-` for a folder devvm has no record of. Exports you wrote to a FILE of your own aren't listed, and `devvm history` changes nothing and starts no VM.
### devvm history --json
`devvm history --json` prints the same list as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. Each of the `exports` has its `file`, its `vm`, the VM's `folder`, which is `""` when devvm has no record of it, the `date` devvm wrote it in RFC 3339 with this machine's time zone, and its `size` in bytes.
```json
{
"version": 1,
"exports": [
{
"file": "/Users/you/.local/share/devvm/exports/devvm-website-71a99b1076d92c-20261001-120000.tar.gz",
"vm": "devvm-website-71a99b1076d92c",
"folder": "/Users/you/code/website",
"date": "2026-10-01T12:00:00+02:00",
"size": 1048576
}
]
}
```
After `devvm rm`, an export is the only copy of that VM's history, so devvm keeps the exports until you ask it to delete them. `devvm gc --history` deletes the exports in that folder, and `devvm gc --history --older-than 30d` deletes only those written 30 days ago or more. An export's age counts from the date and time in its name, which is this machine's local time when devvm wrote it, so across a change to or from daylight saving time an export reaches an age such as `30d` an hour earlier or later, for `--older-than` and for the `history.age` [retention setting](settings.md#retention) alike. gc lists each one by its VM and date first, and in a terminal it asks. Exports you wrote to a FILE of your own stay where they are.
The agents' logins aren't in the export, which leaves out `~/.claude/.credentials.json`, `~/.codex/auth.json`, and opencode's `auth.json`, `account.json` and `bin`. devvm starts a stopped VM for the export, and the VM stays running. devvm writes the file only once the export is complete, so a failed export leaves no file and leaves an existing FILE as it was. Only you can read the file, and devvm makes the exports folder yours alone each time it writes one there, whatever its mode was before. When FILE is in a folder of your own, that folder keeps its mode. If the export fails, `devvm rm` keeps the VM, and `devvm rm -f` deletes it without exporting.
+42
View File
@@ -139,6 +139,48 @@ The second table lists the [shared tools](#shared-tools) that devvm has built, b
After the tables, devvm says on stderr how many images are stale or unfinished and how much disk the unused tools take, when there are any. It ends with the disk that the images and shared tools take together, and when the [shared Nix cache](toolchains.md#nix-projects) holds anything, the disk it takes of its cap. `devvm space` shows the rest of what devvm keeps ([what devvm keeps](space.md#devvm-space)).
### devvm images --json
`devvm images --json` prints the same as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes, and devvm still says the same on stderr. `images` and `tools` have the tables' columns as fields, with sizes in bytes. An image's `digest` is the full SHA-256 of what its base started from, and `sized` says whether devvm knows its size. A tool image's `built` says whether devvm has built it, and only a built one has `backend` and `libc`. A value an image lacks, such as an unfinished build's name, is `""`. `total` is the disk the images and shared tools take together, `unused_tools` is the part the unused tool images take, and `nix_cache` has the shared Nix cache's files, the disk they take and its cap.
```json
{
"version": 1,
"images": [
{
"name": "base",
"from": "ubuntu 26.04 (20261001)",
"digest": "sha256:8eb876c2ccc4b6ff89e4a65d511815923b285e04503ba465809bf587f763da24",
"key": "7a76021c46ef",
"state": "current",
"size": 2254857830,
"sized": true,
"backend": "lima"
}
],
"tools": [
{
"name": "node",
"tool": "node",
"version": "24.11.0",
"built": true,
"backend": "lima",
"libc": "gnu",
"size": 125829120,
"vms": 1,
"state": "current"
}
],
"total": 2380686950,
"unused_tools": 0,
"nix_cache": {
"files": 0,
"size": 0,
"cap": 10737418240
}
}
```
### Deleting images
`devvm images rm IMAGE|KEY...` deletes images. You name each one by its name or by the key that `devvm images` shows:
+27
View File
@@ -110,3 +110,30 @@ The numbers leave a margin over what each step took when devvm's tests measured
devvm checks the disk that holds the backend's images and VMs. On Lima, that's the disk of devvm's Lima home. On smolvm, it's the disk of devvm's data folder, and on macOS also that of your home folder, where smolvm keeps its machines. Shared tool images come out into devvm's data folder on every backend, so a tools build also checks that folder's disk, which needs 0.5 GiB and 0.25 GiB for each tool, rounded up: 1 GiB for one tool and 3 GiB for all ten. The Docker backend keeps its images and VMs in the engine's own storage, which on Docker Desktop is a disk inside Desktop's VM, so devvm checks only the data folder's disk, for shared tool images. When devvm's data folder is on a small temporary disk, such as a tmpfs `/tmp` on Linux, devvm checks that disk.
`devvm doctor` also warns when that disk has less free space than building base needs, but the warning doesn't make doctor fail. When devvm refuses, see [Not enough free space](troubleshooting.md#not-enough-free-space) for how to make room.
## As JSON
`devvm size --json` and `devvm ports --json` print what the commands show as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. With `-g`, they print the same fields for new VMs. With `--json` they only show, so devvm refuses `--cpus`, `--memory`, `--disk` or a list of ports with it.
`devvm size --json` has `cpus`, `memory_gib` and `disk_gib`, and leaves out what isn't set. For `-g`, that's what new VMs take from the image. A Docker VM has no `disk_gib`, because its disk has no size of its own, and it has `disk_used_gib` instead, to a tenth of a GiB. When the VM's size changes at its next start, `pending` has the `cpus`, `memory_gib` and `disk_gib` that change.
```json
{
"version": 1,
"cpus": 4,
"memory_gib": 8,
"disk_gib": 100,
"pending": {
"memory_gib": 16
}
}
```
`devvm ports --json` has `ports`, which is `all`, `none` or a list of ports and ranges, written as `devvm ports` takes it.
```json
{
"version": 1,
"ports": "5173,8000-8010"
}
```
+19 -1
View File
@@ -63,6 +63,24 @@ devvm keeps what it makes until you delete it, and the retention settings tell i
Ages are a whole number of days, weeks or hours, such as `30d`, `2w` or `12h`. Sizes are a whole number of `K`, `M`, `G` or `T`, each 1024 of the one before, such as `500M` or `20G`, as `devvm space` shows them. The shared Nix cache also keeps to its size while VMs fill it, because a VM's proxy deletes the cache's least recently used files before a new file would take it past that size. A size you set applies to each VM from its next start. devvm applies the settings at the start of a command, at most once a day, except for `orphans.age`, which needs to ask each backend about its VMs, so only `devvm gc --retention` applies it. `devvm gc --retention` applies all of them at once. When it deletes something, devvm says what in one line. Retention never deletes a VM, an image, a shared tool that any VM's state lists, or anything in the backends' own caches, which only `devvm gc --caches` frees. When two devvms start at once, only one of them applies the settings.
### devvm retention --json
`devvm retention --json` prints the settings as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. `settings` has every key with its value as you wrote it, and `off` for each one that isn't set. With `--json` the command only shows, so devvm refuses a `KEY=VALUE` with it.
```json
{
"version": 1,
"settings": {
"history.age": "90d",
"history.count": "off",
"logs.runs": "off",
"nix-cache.size": "off",
"orphans.age": "off",
"tools.unused-age": "30d"
}
}
```
## A company's CA
Some company networks inspect TLS through a proxy, such as Zscaler or Netskope, that shows its own certificates, signed by the company's certificate authority (CA). This machine trusts that CA, but VMs and the VMs that devvm builds images in don't, so their TLS connections fail. To make them trust it, put the CA's certificate in `~/.config/devvm/ca`:
@@ -120,7 +138,7 @@ The tables that devvm ls, devvm images, devvm space and devvm doctor print are c
devvm uses only your terminal's 16 base colors, so your theme picks shades that read well on its background, light or dark. It never sets a background color.
devvm decides for standard output and standard error apart, and colors one only when it's a terminal, so output you pipe or redirect to a file stays plain, tables included. devvm space `--json` and devvm doctor `--fixes` are plain even in a terminal, and the run log is never colored. These environment variables change when devvm colors, and the first one that applies decides:
devvm decides for standard output and standard error apart, and colors one only when it's a terminal, so output you pipe or redirect to a file stays plain, tables included. What a command prints with `--json` is plain even in a terminal, and the run log is never colored. These environment variables change when devvm colors, and the first one that applies decides:
- `NO_COLOR`, set to anything but an empty value, turns colors off.
- `FORCE_COLOR` or `CLICOLOR_FORCE`, set to anything but `0`, turns them on even when the output isn't a terminal.
+57 -1
View File
@@ -7,7 +7,7 @@ devvm, the tools it runs and its backends keep files on this machine outside you
## devvm space
`devvm space` shows what devvm keeps on this machine, on every backend, and how much disk each kind of thing takes. It changes nothing and starts no VM, and it gives each backend 30 seconds to answer. `devvm space --json` prints the same as JSON, for scripts. The first table has a row for each kind of thing devvm has, followed by a total:
`devvm space` shows what devvm keeps on this machine, on every backend, and how much disk each kind of thing takes. It changes nothing and starts no VM, and it gives each backend 30 seconds to answer. `devvm space --json` prints the same as JSON, for scripts ([devvm space --json](#devvm-space---json)). The first table has a row for each kind of thing devvm has, followed by a total:
| Column | |
| --- | --- |
@@ -27,6 +27,62 @@ The second table lists the caches that belong to the backends, with the backend,
devvm never prunes these caches on its own. `devvm gc --caches` frees devvm's share of them, which is what devvm's builds put there and nothing of devvm's needs. For each backend in turn, it lists the entries it would delete with their sizes and asks, and without a terminal it refuses. With `--backend NAME`, it asks only about that backend's cache.
### devvm space --json
`devvm space --json` prints both tables as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes, and devvm still says on stderr what it says without `--json`. `devvm` has a row of the first table each, with sizes in bytes:
| Field | |
| --- | --- |
| `what`, `backend`, `count`, `size` | the row's `WHAT`, `BACKEND`, `COUNT` and `SIZE`, with `backend` left out when the row has none |
| `sized` | whether devvm knows the size, which `SIZE` shows as `-` when it doesn't |
| `kept` | the row's `KEPT` |
| `gc` | what `devvm gc` frees of it now |
| `rest` | the row's `FREED BY` |
| `retain`, `retain_frees` | the retention setting that applies to the row and what it would delete now, both left out when none is on |
`total` and `gc` are the totals row's `SIZE` and `GC`. `backends` has the second table's rows, each with its `backend`, `name`, `path`, `count`, `size` and `sized`. `unknown` names the backends that one of your VMs uses that didn't answer, and `strays` has the [VMs devvm has no state for](#vms-devvm-has-no-state-for), each with its `backend`, `name` and the `data` folder its label names. devvm leaves both out when they're empty.
```json
{
"version": 1,
"devvm": [
{
"what": "VMs",
"backend": "lima",
"count": 2,
"size": 5368709120,
"sized": true,
"kept": "only copy",
"gc": 0,
"rest": "devvm rm"
},
{
"what": "history",
"count": 3,
"size": 3145728,
"sized": true,
"kept": "only copy",
"gc": 0,
"rest": "gc --history",
"retain": "30d",
"retain_frees": 1048576
}
],
"total": 5371854848,
"gc": 0,
"backends": [
{
"backend": "lima",
"name": "download cache",
"path": "/Users/you/Library/Caches/lima",
"count": 1,
"size": 629145600,
"sized": true
}
]
}
```
## devvm's data folder
devvm keeps its state in `~/.local/share/devvm`, or in `$XDG_DATA_HOME/devvm` when `XDG_DATA_HOME` is set. Only you can read it, because each time devvm runs, it makes this folder and the settings folder, `~/.config/devvm`, yours alone (mode 700), whatever mode they had, so nothing inside either one is open to others. If devvm can't, for example because someone else owns a folder, it warns and goes on. Whenever devvm writes into the folders that hold history, logs, keys and secrets, which are `exports/`, `logs/`, `logs/runs/`, `run/`, `ca/` and the settings folder's `secrets/`, it makes them only yours again as well, whatever mode they had. Everything in it is devvm's own, and devvm makes all of it again when it's needed, except the exports, which are the only copy of a deleted VM's agent history.
+20
View File
@@ -71,3 +71,23 @@ devvm's own agent keeps your other keys out of reach, because it holds only the
- An encrypted key in the old PEM format needs converting first, with `ssh-keygen -p -f KEY`, because devvm can't read its fingerprint without the passphrase.
The agent drops each key 12 hours after it loads it, so a VM can't keep using the key indefinitely. `--lifetime 30m` changes that for one key, and it takes any duration that `ssh-add -t` takes, or `forever`. `--confirm` makes the agent ask you before each use, such as each push or each login, through an `ssh-askpass` program. macOS doesn't include one, so install it with `brew install theseal/ssh-askpass/ssh-askpass`. devvm keeps the keys and their options in `~/.config/devvm/agent-keys`, and running `devvm ssh-agent add` on the same key again replaces its options.
### devvm ssh-agent --json
`devvm ssh-agent --json` prints what `devvm ssh-agent` shows as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. `mode` is this folder's VM's choice, `off`, `on` or `devvm`. Each of the `keys` is a key you added to devvm's agent, with its `file`, the `fingerprint` devvm recorded, `confirm`, its `lifetime` and `loaded`, which says whether the agent holds it. As without `--json`, devvm loads the keys the agent lacks first, and with no key added, `keys` is `[]` and devvm doesn't start its agent. With `--json` the command only shows, so devvm refuses `on`, `devvm` or `off` with it.
```json
{
"version": 1,
"mode": "devvm",
"keys": [
{
"file": "/Users/you/.ssh/deploy_key",
"fingerprint": "SHA256:mVPwvezndPv/ARoIadVY98vAC0g+P/5633yTC4d/wXE",
"confirm": false,
"lifetime": "12h",
"loaded": true
}
]
}
```
+22
View File
@@ -107,6 +107,28 @@ A new VM gets the shared tools its image names, the toolchains and the [coding a
`devvm tools` changes nothing and starts no VM. It reads the tools lock as it is, without going online, so a release that came out since devvm last checked isn't in it yet.
### devvm tools --json
`devvm tools --json` prints the same table as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. Each of the `tools` has the tool's name and the VM's version. A tool that the lock has another build of also has `newer`, which is the lock's version, and `newer_built`, which says whether that version is built.
```json
{
"version": 1,
"tools": [
{
"tool": "node",
"version": "24.10.0",
"newer": "24.11.0",
"newer_built": false
},
{
"tool": "pnpm",
"version": "10.18.0"
}
]
}
```
The commands below change the VM's tools. They don't change the VM's disk, because its tools are mounted, so a change takes effect when devvm then opens a shell in the VM. Each takes the tools' names as separate words, as in `devvm tools add python claude`, and devvm refuses names joined with `+`.
- `devvm tools add TOOL...` builds the tools that the share lacks and adds them to the VM. A new agent's config folders are mounted too, which needs the VM to start again, so for a running VM devvm asks before restarting it ([adding to a VM](../getting-started/commands.md#adding-to-a-vm)).
+39 -3
View File
@@ -262,12 +262,48 @@ run_fix() {
if { : </dev/tty; } 2>/dev/null; then "${a[@]}" </dev/tty; else "${a[@]}" </dev/null; fi
}
# What devvm's own check says is missing ("KEY<TAB>FIX<TAB>MESSAGE" lines, from devvm doctor
# --fixes), and an offer to fix each.
# doctor_fixes: the problems in devvm doctor --json's output on stdin, a "KEY<TAB>FIX<TAB>MESSAGE"
# line each, FIX empty for a null one. It reads the layout devvm writes, a field a line, each
# value on its line; escapes in a value come out as the character, and tabs, newlines and \u ones
# as a space.
doctor_fixes() {
awk '
function unq(s, out, i, c) {
if (s == "null") return ""
s = substr(s, 2, length(s) - 2)
out = ""
for (i = 1; i <= length(s); i++) {
c = substr(s, i, 1)
if (c == "\\") {
i++
c = substr(s, i, 1)
if (c == "u") { c = " "; i += 4 } else if (c == "n" || c == "t" || c == "r" || c == "b" || c == "f") c = " "
}
out = out c
}
return out
}
/^ "problems": \[$/ { in_p = 1; next }
in_p && /^ \]/ { in_p = 0 }
in_p && /^ "(key|fix|message)": / {
name = $0
sub(/^ "/, "", name)
sub(/".*/, "", name)
v = $0
sub(/^ "[a-z]+": /, "", v)
sub(/,$/, "", v)
val[name] = unq(v)
if (name == "message") print val["key"] "\t" val["fix"] "\t" val["message"]
}
'
}
# What devvm's own check says is missing (devvm doctor --json's problems), and an offer to fix
# each.
install_deps() {
local devvm=$1 line rest key fix m fixes=() relogin=false
while IFS= read -r line; do [[ -z $line ]] || fixes+=("$line"); done \
< <(PATH="$prefix/bin:$PATH" "$devvm" doctor --fixes || true)
< <({ PATH="$prefix/bin:$PATH" "$devvm" doctor --json || true; } | doctor_fixes)
((${#fixes[@]})) || {
say "everything devvm needs is installed"
# Its warnings (a small machine, low free space) aren't fixes.
+9 -7
View File
@@ -29,14 +29,15 @@ type Listed struct {
// Ubuntu's cloud image, with its release's date when known (ubuntu
// 26.04 (20261001)); "" for an unfinished one.
Origin string
// DigestID is the first 12 hex digits of Origin's SHA-256, "" when
// unknown.
// SHA256 is Origin's SHA-256 in hex, "" when unknown; DigestID, its
// first 12 digits.
SHA256 string
DigestID string
Size int64 // the disk space it takes, when Sized
Sized bool
}
var sha256Hex = regexp.MustCompile(`sha256:([0-9a-f]{12})`)
var sha256Hex = regexp.MustCompile(`sha256:([0-9a-f]{12,64})`)
// Listing lists the backend's images by name, those without one last,
// with their state, origin and size.
@@ -55,7 +56,8 @@ func (b Images) Listing(ctx context.Context) ([]Listed, error) {
l.State = StateCurrent
}
if img.Name != "" {
l.Origin, l.DigestID = b.origin(img)
l.Origin, l.SHA256 = b.origin(img)
l.DigestID = l.SHA256[:min(12, len(l.SHA256))]
}
size, err := b.Backend.ImageSize(ctx, img.Key)
if err == nil {
@@ -77,9 +79,9 @@ func (b Images) Listing(ctx context.Context) ([]Listed, error) {
return out, nil
}
// origin is what an image's base started from, and its digest's first 12
// hex digits. An image above base on Ubuntu's cloud image records no
// digest: its base's record has it.
// origin is what an image's base started from, and its digest's SHA-256
// in hex. An image above base on Ubuntu's cloud image records no digest:
// its base's record has it.
func (b Images) origin(img Image) (origin, id string) {
d := img.Digest
if d == "" && img.From == "" && len(img.Chain) > 0 && img.Chain[0].Name == image.Base {
+70 -29
View File
@@ -3,8 +3,6 @@ package cli
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
@@ -26,7 +24,7 @@ import (
// newDoctorCmd is devvm doctor.
func newDoctorCmd(u *ui.UI, g *globals) *cobra.Command {
var fixes bool
var asJSON bool
cmd := &cobra.Command{
Use: "doctor",
Short: "Check what devvm needs on this machine",
@@ -49,17 +47,81 @@ func newDoctorCmd(u *ui.UI, g *globals) *cobra.Command {
Free: reg.Host.FreeSpace,
Host: func() (vm.Host, error) { return vm.ThisHost(reg.Host) },
}
err = d.run(cmd.Context(), u, reg.All(), b, fixes)
if asJSON {
return printJSON(u, d.report(cmd.Context(), reg.All(), b))
}
err = d.run(cmd.Context(), u, reg.All(), b)
if m, ok := errors.AsType[msg.M](err); ok {
u.Die(m)
}
return err
},
}
cmd.Flags().BoolVar(&fixes, "fixes", false, "print only what's missing, for scripts: a KEY<tab>FIX<tab>MESSAGE line each, FIX being a command or empty; succeeds either way")
f := cmd.Flags()
f.BoolVar(&asJSON, "json", false, "print what it found as one JSON object, for scripts, and nothing else; succeeds whatever is missing")
return cmd
}
// doctorOutput is devvm doctor --json: the backend new VMs get and what
// it's missing, doctor's warnings, whether Docker is installed, and every
// backend's features.
type doctorOutput struct {
Backend string `json:"backend"`
Problems []problemJSON `json:"problems"`
Warnings []string `json:"warnings"`
Docker bool `json:"docker"`
// Features is, for each backend, how it has each feature: native,
// emulated, unreviewed or none.
Features map[string]map[string]string `json:"features"`
}
// problemJSON is something the backend is missing: its key, the command
// that fixes it (null when there's none to run) and the message.
type problemJSON struct {
Key string `json:"key"`
Fix *string `json:"fix"`
Message string `json:"message"`
}
// report is what doctor finds, as doctor --json shows it. It prints
// nothing.
func (d doctor) report(ctx context.Context, all []backend.Backend, b backend.Backend) doctorOutput {
out := doctorOutput{Backend: b.Name(), Problems: []problemJSON{}, Warnings: []string{}, Features: map[string]map[string]string{}}
for _, p := range b.Problems(ctx) {
j := problemJSON{Key: p.Key, Message: p.Msg.Line()}
if p.Fix != "" {
j.Fix = &p.Fix
}
out.Problems = append(out.Problems, j)
}
for _, m := range d.warnings(b) {
out.Warnings = append(out.Warnings, m.Line())
}
_, err := exec.LookPath("docker")
out.Docker = err == nil
for _, be := range all {
fs := map[string]string{}
for _, f := range backend.Features {
fs[string(f)] = be.Caps()[f].String()
}
out.Features[be.Name()] = fs
}
return out
}
// warnings are doctor's warnings, which never make it fail: another devvm
// first on PATH, low free space, a small host.
func (d doctor) warnings(b backend.Backend) []msg.M {
var ms []msg.M
if m, ok := d.Path.other(); ok {
ms = append(ms, m)
}
if m, low := (backend.Space{Free: d.Free}).Warning(b); low {
ms = append(ms, m)
}
return append(ms, smallHost(d.Host)...)
}
// The host devvm recommends: base asks for 4 CPUs and 8 GiB.
const (
recommendedCPUs = 4
@@ -75,30 +137,20 @@ type doctor struct {
// run checks b, the backend new VMs get, and lists all's features. It
// returns the last problem's message when b has problems, having warned
// the others. With fixes, it writes only the problems' lines, and
// succeeds. Warnings (another devvm on PATH, low free space, a small
// the others. Warnings (another devvm on PATH, low free space, a small
// host) never change what it returns.
func (d doctor) run(ctx context.Context, u *ui.UI, all []backend.Backend, b backend.Backend, fixes bool) error {
func (d doctor) run(ctx context.Context, u *ui.UI, all []backend.Backend, b backend.Backend) error {
problems := b.Problems(ctx)
if fixes {
return writeFixes(u.Stdout(), problems)
}
if err := writeFeatures(u.Table(), all); err != nil {
return err
}
if m, ok := d.Path.other(); ok {
u.Warn(m)
}
if _, err := exec.LookPath("docker"); err == nil {
u.Say(msg.DockerFound())
} else {
u.Say(msg.DockerMissing())
}
sayProxyCA(u)
if m, low := (backend.Space{Free: d.Free}).Warning(b); low {
u.Warn(m)
}
for _, m := range smallHost(d.Host) {
for _, m := range d.warnings(b) {
u.Warn(m)
}
if len(problems) == 0 {
@@ -199,17 +251,6 @@ func (p onPath) other() (msg.M, bool) {
return msg.DevvmOtherFirst(first, self), true
}
// writeFixes writes a KEY<tab>FIX<tab>MESSAGE line for each problem, the
// message on one line.
func writeFixes(w io.Writer, problems []backend.Problem) error {
for _, p := range problems {
if _, err := fmt.Fprintf(w, "%s\t%s\t%s\n", p.Key, p.Fix, p.Msg.Line()); err != nil {
return err
}
}
return nil
}
// writeFeatures writes a table of every feature, with a column for each
// backend saying how it has it: native green, emulated yellow, unreviewed
// and none red.
+41 -25
View File
@@ -92,17 +92,43 @@ func TestOnPathOther(t *testing.T) {
}
}
// --fixes prints a KEY, FIX and message line for each problem.
func TestWriteFixes(t *testing.T) {
// --json has each problem's key, fix (null without one) and message, the
// warnings, and every backend's features; it prints nothing else.
func TestDoctorReport(t *testing.T) {
t.Setenv("DEVVM_MESSAGES", "names")
var out strings.Builder
err := writeFixes(&out, []backend.Problem{
b := backendtest.New("lima", backend.Caps{backend.FeatureSSH: backend.Native})
b.Missing = []backend.Problem{
{Key: "lima", Fix: "brew install lima", Msg: msg.LimaMissingFix("brew install lima")},
{Key: "kvm", Msg: msg.NoKVM()},
})
want := "lima\tbrew install lima\tlima_missing_fix fix=brew install lima\nkvm\t\tno_kvm\n"
if err != nil || out.String() != want {
t.Errorf("writeFixes: %q, %v; want %q", out.String(), err, want)
}
d := doctor{
Path: onPath{LookPath: func(string) (string, error) { return "", exec.ErrNotFound }, Executable: os.Executable},
Free: func(string) (uint64, error) { return 1 << 40, nil },
Host: func() (vm.Host, error) { return vm.Host{CPUs: 2, MemoryGiB: 16}, nil },
}
r := d.report(t.Context(), []backend.Backend{b}, b)
fix := "brew install lima"
want := []problemJSON{{Key: "lima", Fix: &fix, Message: "lima_missing_fix fix=brew install lima"}, {Key: "kvm", Message: "no_kvm"}}
if len(r.Problems) != 2 || r.Problems[0].Fix == nil || *r.Problems[0].Fix != fix || r.Problems[1].Fix != nil ||
r.Problems[0].Message != want[0].Message || r.Problems[1].Key != "kvm" {
t.Errorf("problems %+v, want %+v", r.Problems, want)
}
if !slices.Equal(r.Warnings, []string{"host_cpus_few have=2 want=4"}) || r.Backend != "lima" {
t.Errorf("warnings %q, backend %q", r.Warnings, r.Backend)
}
if r.Features["lima"]["ssh"] != "native" || r.Features["lima"]["disk"] != "none" {
t.Errorf("features %v", r.Features)
}
u, out, errOut := testUI()
if err := printJSON(u, r); err != nil || errOut.Len() > 0 {
t.Fatalf("printJSON: %v, stderr %q", err, errOut)
}
// install.sh reads this layout: a field a line, the problems' indented
// six spaces.
layout := "\n \"problems\": [\n {\n \"key\": \"lima\",\n \"fix\": \"brew install lima\",\n" +
" \"message\": \"lima_missing_fix fix=brew install lima\"\n },\n {\n \"key\": \"kvm\",\n \"fix\": null,\n"
if !strings.Contains(out.String(), layout) || !strings.HasPrefix(out.String(), "{\n \"version\": 1,\n") {
t.Errorf("printed %s", out)
}
}
@@ -133,7 +159,7 @@ func TestSmallHost(t *testing.T) {
}
// doctor's warnings about a small host go to stderr and never change
// what it returns, and --fixes prints only the problems' lines either way.
// what it returns.
func TestDoctorSmallHostWarnsOnly(t *testing.T) {
t.Setenv("DEVVM_MESSAGES", "names")
t.Setenv("HTTPS_PROXY", "")
@@ -143,27 +169,23 @@ func TestDoctorSmallHostWarnsOnly(t *testing.T) {
name string
host vm.Host
problems []backend.Problem
fixes bool
wantErr string // the message doctor returns; "" for none
wantOut string // --fixes' output
warned bool // whether stderr has the small host's warnings
}{
{"big, nothing missing", vm.Host{CPUs: 8, MemoryGiB: 16}, nil, false, "", "", false},
{"small, nothing missing", vm.Host{CPUs: 2, MemoryGiB: 4}, nil, false, "", "", true},
{"small, Lima missing", vm.Host{CPUs: 2, MemoryGiB: 4}, []backend.Problem{{Key: "lima", Msg: msg.LimaMissing()}}, false, "lima_missing", "", true},
{"small, --fixes, nothing missing", vm.Host{CPUs: 2, MemoryGiB: 4}, nil, true, "", "", false},
{"small, --fixes, Lima missing", vm.Host{CPUs: 2, MemoryGiB: 4}, []backend.Problem{{Key: "lima", Msg: msg.LimaMissing()}}, true, "", "lima\t\tlima_missing\n", false},
{"big, nothing missing", vm.Host{CPUs: 8, MemoryGiB: 16}, nil, "", false},
{"small, nothing missing", vm.Host{CPUs: 2, MemoryGiB: 4}, nil, "", true},
{"small, Lima missing", vm.Host{CPUs: 2, MemoryGiB: 4}, []backend.Problem{{Key: "lima", Msg: msg.LimaMissing()}}, "lima_missing", true},
} {
t.Run(c.name, func(t *testing.T) {
b := backendtest.New("lima", backend.Caps{})
b.Missing = c.problems
u, out, errOut := testUI()
u, _, errOut := testUI()
d := doctor{
Path: onPath{LookPath: notFound, Executable: os.Executable},
Free: func(string) (uint64, error) { return 1 << 40, nil },
Host: func() (vm.Host, error) { return c.host, nil },
}
err := d.run(t.Context(), u, []backend.Backend{b}, b, c.fixes)
err := d.run(t.Context(), u, []backend.Backend{b}, b)
gotErr := ""
if m, ok := errors.AsType[msg.M](err); ok {
gotErr = m.Names()
@@ -173,19 +195,13 @@ func TestDoctorSmallHostWarnsOnly(t *testing.T) {
if gotErr != c.wantErr {
t.Errorf("returned %q, want %q", gotErr, c.wantErr)
}
if c.fixes && out.String() != c.wantOut {
t.Errorf("--fixes printed %q, want %q", out.String(), c.wantOut)
}
if warned := strings.Contains(errOut.String(), "devvm: host_cpus_few have=2 want=4\n") &&
strings.Contains(errOut.String(), "devvm: host_memory_low have=4 want=8\n"); warned != c.warned {
t.Errorf("stderr %q: warned %v, want %v", errOut.String(), warned, c.warned)
}
if !c.warned && !c.fixes && c.problems == nil && errOut.Len() > 0 {
if !c.warned && c.problems == nil && errOut.Len() > 0 {
t.Errorf("stderr %q, want nothing", errOut.String())
}
if c.fixes && errOut.Len() > 0 {
t.Errorf("--fixes: stderr %q, want nothing", errOut.String())
}
})
}
}
+15 -6
View File
@@ -11,24 +11,33 @@ import (
// newGitProtectCmd is devvm git-protect [on|strict|off].
func newGitProtectCmd(u *ui.UI) *cobra.Command {
return &cobra.Command{
var asJSON bool
cmd := &cobra.Command{
Use: "git-protect [on|strict|off]",
Short: "Show or change .git protection for this folder's VM",
Long: "Show whether this folder's VM can change the parts of .git that run code on this machine: " +
"on (the default on macOS: hooks and config locked), strict (on, and host git status and diff " +
"stay out of submodules), off, or clone for a --clone VM. devvm git-protect on, strict or off " +
"changes it while the VM is stopped; on and strict lock .git as it is now. Locks need macOS.",
Args: maxArgs(1),
Args: showsOnly(maxArgs(1)),
ValidArgs: gitprotect.Modes,
RunE: func(cmd *cobra.Command, args []string) error {
var mode string
withEnv(u, func(env *vm.Env) error {
s := vm.Settings{Env: env}
if len(args) == 0 {
return s.GitProtect(cmd.Context(), u.Stdout())
if len(args) == 1 {
return s.SetGitProtect(cmd.Context(), args[0])
}
return s.SetGitProtect(cmd.Context(), args[0])
var err error
mode, err = s.GitProtect(cmd.Context())
return err
}, msg.GitProtectFailed)
return nil
if len(args) == 1 {
return nil
}
return printValue(u, asJSON, "mode", mode)
},
}
jsonFlag(cmd, &asJSON)
return cmd
}
+28
View File
@@ -21,6 +21,7 @@ import (
// newHistoryCmd is devvm history: the exports of agents' history in
// devvm's exports folder, and history export, which writes one.
func newHistoryCmd(u *ui.UI) *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "history",
Short: "List the saved exports of agents' history",
@@ -36,13 +37,40 @@ func newHistoryCmd(u *ui.UI) *cobra.Command {
es, err = exports(d)
}
fail(u, err, msg.HistoryFailed)
if asJSON {
return printJSON(u, historyJSON(es))
}
return writeHistory(u.Table(), es)
},
}
jsonFlag(cmd, &asJSON)
cmd.AddCommand(newHistoryExportCmd(u))
return cmd
}
// historyOutput is devvm history --json: the exports, oldest first, each
// with when it was written in RFC 3339 (this machine's zone) and its size
// in bytes. A folder devvm has no record of is "".
type historyOutput struct {
Exports []exportJSON `json:"exports"`
}
type exportJSON struct {
File string `json:"file"`
VM string `json:"vm"`
Folder string `json:"folder"`
Date string `json:"date"`
Size int64 `json:"size"`
}
func historyJSON(es []savedExport) historyOutput {
out := historyOutput{Exports: make([]exportJSON, 0, len(es))}
for _, e := range es {
out.Exports = append(out.Exports, exportJSON{File: e.Path, VM: e.VM, Folder: e.Folder, Date: e.At.Format(time.RFC3339), Size: e.Size})
}
return out
}
// writeHistory writes the exports as a table, a header first; a folder
// devvm has no record of is -.
func writeHistory(tab *ui.Table, es []savedExport) error {
+106 -11
View File
@@ -21,6 +21,7 @@ import (
// newImagesCmd is devvm images, and devvm images rm.
func newImagesCmd(u *ui.UI, g *globals) *cobra.Command {
var asJSON bool
c := &cobra.Command{
Use: "images",
Short: "List the images and the shared tools",
@@ -46,22 +47,20 @@ func newImagesCmd(u *ui.UI, g *globals) *cobra.Command {
fail(u, err, msg.ImagesFailed)
target, err := toolTargets(u, b)
fail(u, err, msg.ImagesFailed)
if err := writeImages(u.Table(), imgs, ts, target); err != nil {
nix := nixCacheOf(u, b.Dirs)
if asJSON {
err = printJSON(u, imagesJSON(imgs, ts, target, nix))
} else {
err = writeImages(u.Table(), imgs, ts, target)
}
if err != nil {
return err
}
if n := len(staleImages(imgs)); n > 0 {
u.Note(msg.ImagesStaleNote(n))
}
if size := toolsSize(tools.Unused(ts)); size > 0 {
u.Note(msg.ImagesUnused(humanSize(size)))
}
u.Note(msg.ImagesTotal(humanSize(imagesSize(imgs) + toolsSize(ts))))
if n, size, err := proxy.NixCacheUsage(b.Dirs.NixCache()); err == nil && n > 0 {
u.Note(msg.ImagesNixCache(humanSize(nixCacheCap(u, b.Dirs)), humanSize(size)))
}
imagesNotes(u, imgs, ts, nix)
return nil
},
}
jsonFlag(c, &asJSON)
c.AddCommand(&cobra.Command{
Use: "rm IMAGE|KEY...",
Short: "Delete images, by name or by key",
@@ -97,6 +96,102 @@ func newImagesCmd(u *ui.UI, g *globals) *cobra.Command {
return c
}
// nixCacheJSON is what the shared Nix cache holds: its files, the bytes
// they take, and its cap in bytes.
type nixCacheJSON struct {
Files int `json:"files"`
Size int64 `json:"size"`
Cap int64 `json:"cap"`
}
// nixCacheOf reads what the shared Nix cache holds; none when it can't.
func nixCacheOf(u *ui.UI, d paths.Dirs) nixCacheJSON {
n, size, err := proxy.NixCacheUsage(d.NixCache())
if err != nil {
return nixCacheJSON{Cap: nixCacheCap(u, d)}
}
return nixCacheJSON{Files: n, Size: size, Cap: nixCacheCap(u, d)}
}
// imagesNotes says, after devvm images' tables, how many images aren't
// current, what the unused tools take, the total, and the Nix cache's
// use of its cap.
func imagesNotes(u *ui.UI, imgs []listedImage, ts []tools.Listed, nix nixCacheJSON) {
if n := len(staleImages(imgs)); n > 0 {
u.Note(msg.ImagesStaleNote(n))
}
if size := toolsSize(tools.Unused(ts)); size > 0 {
u.Note(msg.ImagesUnused(humanSize(size)))
}
u.Note(msg.ImagesTotal(humanSize(imagesSize(imgs) + toolsSize(ts))))
if nix.Files > 0 {
u.Note(msg.ImagesNixCache(humanSize(nix.Cap), humanSize(nix.Size)))
}
}
// imagesOutput is devvm images --json: the images on every backend, the
// shared tool images, the bytes they take in all and of that what unused
// tool images take, and the shared Nix cache. Sizes are in bytes.
type imagesOutput struct {
Images []imageJSON `json:"images"`
Tools []toolImageJSON `json:"tools"`
Total int64 `json:"total"`
UnusedTools int64 `json:"unused_tools"`
NixCache nixCacheJSON `json:"nix_cache"`
}
// imageJSON is an image: "" for what an unfinished one lacks.
type imageJSON struct {
Name string `json:"name"`
From string `json:"from"`
Digest string `json:"digest"`
Key string `json:"key"`
State string `json:"state"`
Size int64 `json:"size"`
Sized bool `json:"sized"`
Backend string `json:"backend"`
}
// toolImageJSON is a shared tool image: its backend, C library, size and
// VMs only once it's built.
type toolImageJSON struct {
Name string `json:"name"`
Tool string `json:"tool"`
Version string `json:"version"`
Built bool `json:"built"`
Backend string `json:"backend,omitempty"`
Libc string `json:"libc,omitempty"`
Size int64 `json:"size"`
VMs int `json:"vms"`
State string `json:"state"`
}
func imagesJSON(imgs []listedImage, ts []tools.Listed, target func(tools.Listed) (be, libc string), nix nixCacheJSON) imagesOutput {
out := imagesOutput{
Images: make([]imageJSON, 0, len(imgs)), Tools: make([]toolImageJSON, 0, len(ts)),
Total: imagesSize(imgs) + toolsSize(ts), UnusedTools: toolsSize(tools.Unused(ts)), NixCache: nix,
}
for _, l := range imgs {
digest := ""
if l.SHA256 != "" {
digest = "sha256:" + l.SHA256
}
out.Images = append(out.Images, imageJSON{
Name: l.Name, From: l.Origin, Digest: digest, Key: l.Key, State: l.State,
Size: l.Size, Sized: l.Sized, Backend: l.Backend,
})
}
for _, t := range ts {
j := toolImageJSON{Name: t.Name, Tool: t.Tool, Version: t.Version, Built: t.Built, State: t.State}
if t.Built {
j.Size, j.VMs = t.Size, t.VMs
j.Backend, j.Libc = target(t)
}
out.Tools = append(out.Tools, j)
}
return out
}
// listedImage is an image, its backend's name and the images on it.
type listedImage struct {
build.Listed
+87
View File
@@ -0,0 +1,87 @@
package cli
import (
"bytes"
"encoding/json"
"errors"
"io"
"strconv"
"github.com/spf13/cobra"
"github.com/w3cj/devvm/internal/msg"
"github.com/w3cj/devvm/internal/ui"
)
// jsonVersion is the version of every --json shape. A shape only gains
// fields; any other change to one is a new version.
const jsonVersion = 1
// jsonFlag adds --json to a command that shows or lists something.
func jsonFlag(c *cobra.Command, on *bool) {
c.Flags().BoolVar(on, "json", false, "print it as one JSON object, for scripts")
}
// wantsJSON reports whether the command was given --json.
func wantsJSON(cmd *cobra.Command) bool {
f := cmd.Flags().Lookup("json")
return f != nil && f.Changed && f.Value.String() == "true"
}
// showsOnly checks a command that shows a setting bare and changes it
// with a value: with --json it only shows, so a value (an argument, or
// one of the flags in sets) is refused before next checks the arguments.
func showsOnly(next cobra.PositionalArgs, sets ...string) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
if wantsJSON(cmd) {
given := len(args) > 0
for _, f := range sets {
given = given || cmd.Flags().Changed(f)
}
if given {
return msg.JSONShowsOnly(cmd.CommandPath())
}
}
if next == nil {
return nil
}
return next(cmd, args)
}
}
// printValue writes a setting's value on a line of its own, or with
// asJSON as an object with its key.
func printValue(u *ui.UI, asJSON bool, key, value string) error {
if asJSON {
return printJSON(u, map[string]string{key: value})
}
_, err := io.WriteString(u.Stdout(), value+"\n")
return err
}
// printJSON writes v, a struct, to stdout as one indented JSON object
// with "version" first. HTML characters are written as they are.
func printJSON(u *ui.UI, v any) error {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return err
}
body := bytes.TrimSpace(buf.Bytes())
if len(body) < 2 || body[0] != '{' {
return errors.New("--json output isn't an object")
}
obj := []byte(`{"version":` + strconv.Itoa(jsonVersion))
if rest := bytes.TrimSpace(body[1:]); string(rest) != "}" {
obj = append(obj, ',')
}
obj = append(obj, body[1:]...)
var out bytes.Buffer
if err := json.Indent(&out, obj, "", " "); err != nil {
return err
}
out.WriteByte('\n')
_, err := u.Stdout().Write(out.Bytes())
return err
}
+208
View File
@@ -0,0 +1,208 @@
package cli
import (
"encoding/json"
"slices"
"sort"
"strings"
"testing"
"time"
"github.com/w3cj/devvm/internal/backend"
"github.com/w3cj/devvm/internal/build"
"github.com/w3cj/devvm/internal/netpolicy"
"github.com/w3cj/devvm/internal/sshagent"
"github.com/w3cj/devvm/internal/state"
"github.com/w3cj/devvm/internal/tools"
"github.com/w3cj/devvm/internal/vm"
)
// shape is a JSON value's fields, one "path: type" line each, sorted: an
// array's elements are path[], and only its first is read.
func shape(t *testing.T, data []byte) []string {
t.Helper()
var v any
if err := json.Unmarshal(data, &v); err != nil {
t.Fatalf("%v:\n%s", err, data)
}
var out []string
var walk func(path string, v any)
walk = func(path string, v any) {
switch x := v.(type) {
case map[string]any:
for k, e := range x {
walk(strings.TrimPrefix(path+"."+k, "."), e)
}
case []any:
if len(x) == 0 {
out = append(out, path+": empty")
return
}
walk(path+"[]", x[0])
case string:
out = append(out, path+": string")
case float64:
out = append(out, path+": number")
case bool:
out = append(out, path+": bool")
case nil:
out = append(out, path+": null")
}
}
walk("", v)
sort.Strings(out)
return out
}
// Each command's --json shape: its field names and types, from a sample
// with every field set. A field is only ever added: a change to one that
// fails here is a new jsonVersion.
func TestJSONShapes(t *testing.T) {
yes := true
used := 1.5
fix := "brew install lima"
at := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC)
for _, tc := range []struct {
command string
v any
want []string
}{
{
"ls", lsJSON([]vm.Listed{{Name: "devvm-a", Status: "Running", Image: "base", From: "node:24", Git: "on", Net: "on", Backend: "docker", DockerLayer: "sysbox", Folder: "/a"}}),
[]string{
"vms[].backend: string", "vms[].docker_layer: string", "vms[].folder: string", "vms[].from: string", "vms[].git: string", "vms[].image: string",
"vms[].name: string", "vms[].net: string", "vms[].status: string",
},
},
{
"images", imagesJSON(
[]listedImage{{Listed: build.Listed{Image: build.Image{Key: "k", Name: "base"}, SHA256: "ab", State: "current", Origin: "ubuntu 26.04", Size: 1, Sized: true}, Backend: "lima"}},
[]tools.Listed{{Name: "node", Tool: "node", Version: "24", Built: true, Size: 2, VMs: 1, State: "current"}},
func(tools.Listed) (string, string) { return "lima", "gnu" }, nixCacheJSON{Files: 1, Size: 2, Cap: 3}),
[]string{
"images[].backend: string", "images[].digest: string", "images[].from: string", "images[].key: string", "images[].name: string",
"images[].size: number", "images[].sized: bool", "images[].state: string",
"nix_cache.cap: number", "nix_cache.files: number", "nix_cache.size: number",
"tools[].backend: string", "tools[].built: bool", "tools[].libc: string", "tools[].name: string", "tools[].size: number",
"tools[].state: string", "tools[].tool: string", "tools[].version: string", "tools[].vms: number",
"total: number", "unused_tools: number",
},
},
{
"tools", toolsJSON([]tools.VMTool{{Tool: "node", Version: "24.1", Newer: "24.2", Built: true}}),
[]string{"tools[].newer: string", "tools[].newer_built: bool", "tools[].tool: string", "tools[].version: string"},
},
{
"size", sizeJSON(vm.SizeShown{Size: backend.Size{CPUs: 4, MemoryGiB: 8, DiskGiB: 100}, DiskUsedGiB: used, DiskMeasured: true, Pending: backend.Size{CPUs: 2, MemoryGiB: 4, DiskGiB: 120}}),
[]string{
"cpus: number", "disk_gib: number", "disk_used_gib: number", "memory_gib: number",
"pending.cpus: number", "pending.disk_gib: number", "pending.memory_gib: number",
},
},
{"ports", map[string]string{"ports": "all"}, []string{"ports: string"}},
{
"network",
networkOutput{Policy: "on", Allowlist: []policyFileJSON{{File: "/p", Rules: []string{"a.test"}}}},
[]string{"allowlist[].file: string", "allowlist[].rules[]: string", "policy: string"},
},
{"network -g", map[string]string{"policy": "ask"}, []string{"policy: string"}},
{
"network log",
logOutput{Events: []logEventJSON{{
Time: "t", Event: "forward", Host: "h", Port: 443, Method: "GET", Path: "/",
Rule: "h", Reason: "r", Agent: "claude", Secrets: []string{"github"}, Refused: true, Upstream: "proxy:3128",
}}},
[]string{
"events[].agent: string", "events[].event: string", "events[].host: string", "events[].method: string", "events[].path: string",
"events[].port: number", "events[].reason: string", "events[].refused: bool", "events[].rule: string", "events[].secrets[]: string",
"events[].time: string", "events[].upstream: string",
},
},
{
"network log --blocked",
blockedOutput{Blocked: []blockJSON{blockJSON(netpolicy.Block{Last: "t", Count: 2, Host: "h", Port: 443, Allow: "h"})}},
[]string{"blocked[].allow: string", "blocked[].count: number", "blocked[].host: string", "blocked[].last: string", "blocked[].port: number"},
},
{
"ssh-agent",
sshAgentOutput{Mode: "devvm", Keys: []agentKeyJSON{agentKeyJSON(sshagent.ListedKey{File: "/k", Fingerprint: "SHA256:x", Confirm: true, Lifetime: "12h", Loaded: true})}},
[]string{"keys[].confirm: bool", "keys[].file: string", "keys[].fingerprint: string", "keys[].lifetime: string", "keys[].loaded: bool", "mode: string"},
},
{"git-protect", map[string]string{"mode": "on"}, []string{"mode: string"}},
{
"secret",
secretOutput{Secrets: []secretJSON{{Name: "github", Saved: true, UsedBy: []string{"devvm-a"}}}},
[]string{"secrets[].name: string", "secrets[].saved: bool", "secrets[].used_by[]: string"},
},
{
"history", historyJSON([]savedExport{{Path: "/e.tar.gz", VM: "devvm-a", Folder: "/a", At: at, Size: 3}}),
[]string{"exports[].date: string", "exports[].file: string", "exports[].folder: string", "exports[].size: number", "exports[].vm: string"},
},
{"space", spaceReport{
Rows: []spaceRow{{What: "VMs", Backend: "lima", Count: 1, Size: 1, Sized: true, Kept: keptOnlyCopy, GC: 1, Rest: "devvm rm", Retain: "30d", RetainFrees: 1}},
Total: 1, GC: 1,
Caches: []cacheRow{{Backend: "lima", Name: "images", Path: "/c", Count: 1, Size: 1, Sized: true}},
Unknown: []string{"docker"}, Strays: []strayVM{{Backend: "lima", Name: "devvm-b", Data: "/d"}},
}, []string{
"backends[].backend: string", "backends[].count: number", "backends[].name: string", "backends[].path: string",
"backends[].size: number", "backends[].sized: bool",
"devvm[].backend: string", "devvm[].count: number", "devvm[].gc: number", "devvm[].kept: string", "devvm[].rest: string",
"devvm[].retain: string", "devvm[].retain_frees: number", "devvm[].size: number", "devvm[].sized: bool", "devvm[].what: string",
"gc: number", "strays[].backend: string", "strays[].data: string", "strays[].name: string", "total: number", "unknown[]: string",
}},
{"retention", retentionJSON(state.Retention{}), retentionShape()},
{
"doctor",
doctorOutput{
Backend: "lima", Problems: []problemJSON{{Key: "lima", Fix: &fix, Message: "m"}, {Key: "kvm", Message: "m"}},
Warnings: []string{"w"}, Docker: yes, Features: map[string]map[string]string{"lima": {"ssh": "native"}},
},
[]string{
"backend: string", "docker: bool", "features.lima.ssh: string", "problems[].fix: string", "problems[].key: string",
"problems[].message: string", "warnings[]: string",
},
},
} {
t.Run(tc.command, func(t *testing.T) {
u, out, _ := testUI()
if err := printJSON(u, tc.v); err != nil {
t.Fatal(err)
}
want := append([]string{"version: number"}, tc.want...)
sort.Strings(want)
if got := shape(t, out.Bytes()); !slices.Equal(got, want) {
t.Errorf("devvm %s --json:\n%s\nwant:\n%s", tc.command, strings.Join(got, "\n"), strings.Join(want, "\n"))
}
})
}
}
// retentionShape is every retention setting's key, a string each.
func retentionShape() []string {
var out []string
for _, k := range state.RetentionKeys() {
out = append(out, "settings."+k+": string")
}
return out
}
// printJSON writes one indented object, "version" first, HTML characters
// as they are; nothing but an object.
func TestPrintJSON(t *testing.T) {
for _, tc := range []struct {
v any
want string
}{
{struct{}{}, "{\n \"version\": 1\n}\n"},
{map[string]string{"a": "<b>&"}, "{\n \"version\": 1,\n \"a\": \"<b>&\"\n}\n"},
} {
u, out, _ := testUI()
if err := printJSON(u, tc.v); err != nil || out.String() != tc.want {
t.Errorf("printJSON(%v) = %q, %v; want %q", tc.v, out, err, tc.want)
}
}
u, out, _ := testUI()
if err := printJSON(u, []string{"a"}); err == nil || out.Len() != 0 {
t.Errorf("an array: %q, %v", out, err)
}
}
+45 -3
View File
@@ -16,7 +16,8 @@ import (
// newLsCmd is devvm ls.
func newLsCmd(u *ui.UI) *cobra.Command {
return &cobra.Command{
var asJSON bool
cmd := &cobra.Command{
Use: "ls",
Short: "List the project VMs",
Long: "List the project VMs on every backend, by name: each one's status, image, .git protection " +
@@ -32,7 +33,12 @@ func newLsCmd(u *ui.UI) *cobra.Command {
ls, err = listVMs(cmd, u, dirs)
}
fail(u, err, msg.LsFailed)
if err := writeList(u.Table(), ls); err != nil {
if asJSON {
err = printJSON(u, lsJSON(ls))
} else {
err = writeList(u.Table(), ls)
}
if err != nil {
return err
}
for _, l := range ls {
@@ -43,6 +49,38 @@ func newLsCmd(u *ui.UI) *cobra.Command {
return nil
},
}
jsonFlag(cmd, &asJSON)
return cmd
}
// lsOutput is devvm ls --json: the project VMs, by name. What a VM's
// state doesn't have is "".
type lsOutput struct {
VMs []vmJSON `json:"vms"`
}
type vmJSON struct {
Name string `json:"name"`
Status string `json:"status"`
Image string `json:"image"`
From string `json:"from,omitempty"`
Git string `json:"git"`
Net string `json:"net"`
Backend string `json:"backend"`
// DockerLayer is the runtime a docker VM runs the docker layer under.
DockerLayer string `json:"docker_layer,omitempty"`
Folder string `json:"folder"`
}
func lsJSON(ls []vm.Listed) lsOutput {
out := lsOutput{VMs: make([]vmJSON, 0, len(ls))}
for _, l := range ls {
out.VMs = append(out.VMs, vmJSON{
Name: l.Name, Status: l.Status, Image: l.Image, From: l.From, Git: l.Git, Net: l.Net,
Backend: l.Backend, DockerLayer: l.DockerLayer, Folder: l.Folder,
})
}
return out
}
func listVMs(cmd *cobra.Command, u *ui.UI, dirs paths.Dirs) ([]vm.Listed, error) {
@@ -63,7 +101,11 @@ func writeList(tab *ui.Table, ls []vm.Listed) error {
if l.DockerLayer != "" {
backend += " (" + l.DockerLayer + ")"
}
tab.Row(cell(l.Name), cellAs(l.Status, vmStatuses), cell(l.Image), cellAs(l.Git, gitModes),
image := l.Image
if l.From != "" {
image = msg.ImageFrom(l.From, l.Image).Line()
}
tab.Row(cell(l.Name), cellAs(l.Status, vmStatuses), cell(image), cellAs(l.Git, gitModes),
cellAs(l.Net, netModes), cell(backend), cell(l.Folder))
}
return tab.Flush()
+125 -8
View File
@@ -1,6 +1,7 @@
package cli
import (
"io"
"slices"
"strings"
@@ -16,7 +17,7 @@ import (
// newNetworkCmd is devvm network [on|off], with -g [on|off|ask] for what
// new VMs get, and allow, deny, rm RULE... [-g] and log.
func newNetworkCmd(u *ui.UI) *cobra.Command {
var global bool
var global, asJSON bool
cmd := &cobra.Command{
Use: "network [on|off]",
Short: "Show or change the network policy of this folder's VM",
@@ -27,7 +28,7 @@ func newNetworkCmd(u *ui.UI) *cobra.Command {
"devvm restart. Secrets the VM got while it was off still work once it's on. With -g, show or " +
"change whether new VMs get network policy instead: ask (in a terminal, and on without one), " +
"on or off. devvm's --network-policy and --no-network-policy still choose for one new VM.",
Args: func(cmd *cobra.Command, args []string) error {
Args: showsOnly(func(cmd *cobra.Command, args []string) error {
if err := maxArgs(1)(cmd, args); err != nil || len(args) == 0 {
return err
}
@@ -42,7 +43,7 @@ func newNetworkCmd(u *ui.UI) *cobra.Command {
return msg.ArgNotChoice(strings.Join(choices, ", "), cmd.CommandPath(), msg.Shown(args[0]))
}
return nil
},
}),
ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]cobra.Completion, cobra.ShellCompDirective) {
switch {
case len(args) > 0:
@@ -57,27 +58,70 @@ func newNetworkCmd(u *ui.UI) *cobra.Command {
if global {
failed = msg.NetDefaultFailed
}
var (
mode string
shown vm.NetworkShown
)
withEnv(u, func(env *vm.Env) error {
n := vm.Net{Env: env}
var err error
switch {
case global && len(args) == 0:
return n.NetworkDefault(u.Stdout())
mode, err = n.NetworkDefault()
case global:
return n.SetNetworkDefault(args[0])
err = n.SetNetworkDefault(args[0])
case len(args) == 0:
return n.Network(cmd.Context(), u.Stdout())
shown, err = n.Network(cmd.Context())
default:
err = n.SetNetwork(cmd.Context(), args[0] == state.NetworkOn)
}
return n.SetNetwork(cmd.Context(), args[0] == state.NetworkOn)
return err
}, failed)
return nil
switch {
case len(args) == 1:
return nil
case global:
return printValue(u, asJSON, "policy", mode)
}
return printNetwork(u, asJSON, shown)
},
}
cmd.Flags().BoolVarP(&global, "global", "g", false, "show or change whether new VMs get network policy instead")
jsonFlag(cmd, &asJSON)
cmd.AddCommand(newNetworkRuleCmds(u)...)
cmd.AddCommand(newNetworkLogCmd(u))
return cmd
}
// networkOutput is devvm network --json: the VM's network policy and its
// allowlist, each policy file with rules in the order its proxy reads
// them.
type networkOutput struct {
Policy string `json:"policy"`
Allowlist []policyFileJSON `json:"allowlist"`
}
type policyFileJSON struct {
File string `json:"file"`
Rules []string `json:"rules"`
}
// printNetwork writes the VM's network policy: its line then its rules,
// or with asJSON as networkOutput.
func printNetwork(u *ui.UI, asJSON bool, s vm.NetworkShown) error {
if !asJSON {
if _, err := io.WriteString(u.Stdout(), s.Policy+"\n"); err != nil {
return err
}
return netpolicy.WriteRules(u.Stdout(), s.Rules)
}
out := networkOutput{Policy: s.Policy, Allowlist: []policyFileJSON{}}
for _, f := range s.Rules {
out.Allowlist = append(out.Allowlist, policyFileJSON{File: f.Path, Rules: f.Rules})
}
return printJSON(u, out)
}
// newNetworkRuleCmds are devvm network allow, deny and rm RULE... [-g].
func newNetworkRuleCmds(u *ui.UI) []*cobra.Command {
sub := func(use, short, long string, deny, remove bool) *cobra.Command {
@@ -125,6 +169,7 @@ func newNetworkRuleCmds(u *ui.UI) []*cobra.Command {
func newNetworkLogCmd(u *ui.UI) *cobra.Command {
var lines uint
var o vm.LogOptions
var asJSON bool
cmd := &cobra.Command{
Use: "log",
Short: "Show what this folder's VM connected to and what its network policy blocked",
@@ -136,6 +181,9 @@ func newNetworkLogCmd(u *ui.UI) *cobra.Command {
Args: noArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
o.Lines = int(min(lines, 1<<31-1))
if asJSON {
return printLogJSON(cmd, u, o)
}
withEnv(u, func(env *vm.Env) error { return vm.Net{Env: env}.Log(cmd.Context(), u.Stdout(), o) }, msg.LogFailed)
return nil
},
@@ -144,7 +192,76 @@ func newNetworkLogCmd(u *ui.UI) *cobra.Command {
f.UintVarP(&lines, "lines", "n", 50, "show the last `N` connections and requests")
f.BoolVarP(&o.Follow, "follow", "f", false, "then show each new one as it happens, until interrupted")
f.BoolVar(&o.Blocked, "blocked", false, "list the blocks by host and port, with the command that allows each")
jsonFlag(cmd, &asJSON)
exclusive(cmd, "blocked", "follow")
exclusive(cmd, "blocked", "lines")
exclusive(cmd, "json", "follow")
return cmd
}
// logEventJSON is an event in devvm network log --json: what the VM's
// proxy logged of a connection or request, leaving out what it lacks.
type logEventJSON struct {
Time string `json:"time"`
Event string `json:"event"`
Host string `json:"host"`
Port int `json:"port"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Rule string `json:"rule,omitempty"`
Reason string `json:"reason,omitempty"`
Agent string `json:"agent,omitempty"`
Secrets []string `json:"secrets,omitempty"`
Refused bool `json:"refused,omitempty"`
Upstream string `json:"upstream,omitempty"`
}
// logOutput is devvm network log --json; blockedOutput, with --blocked.
type logOutput struct {
Events []logEventJSON `json:"events"`
}
type blockJSON struct {
Last string `json:"last"`
Count int `json:"count"`
Host string `json:"host"`
Port int `json:"port"`
Allow string `json:"allow,omitempty"`
}
type blockedOutput struct {
Blocked []blockJSON `json:"blocked"`
}
// printLogJSON writes the folder's VM's network log as logOutput, or with
// o.Blocked its blocks as blockedOutput.
func printLogJSON(cmd *cobra.Command, u *ui.UI, o vm.LogOptions) error {
var (
events []netpolicy.Event
blocks []netpolicy.Block
)
withEnv(u, func(env *vm.Env) error {
var err error
if o.Blocked {
blocks, err = vm.Net{Env: env}.LogBlocks(cmd.Context())
} else {
events, err = vm.Net{Env: env}.LogEvents(cmd.Context(), o.Lines)
}
return err
}, msg.LogFailed)
if o.Blocked {
out := blockedOutput{Blocked: make([]blockJSON, 0, len(blocks))}
for _, b := range blocks {
out.Blocked = append(out.Blocked, blockJSON(b))
}
return printJSON(u, out)
}
out := logOutput{Events: make([]logEventJSON, 0, len(events))}
for _, e := range events {
out.Events = append(out.Events, logEventJSON{
Time: e.Time, Event: e.Event, Host: e.Host, Port: e.Port, Method: e.Method, Path: e.Path, Rule: e.Rule,
Reason: e.Reason, Agent: e.Agent, Secrets: e.Secrets, Refused: e.Refused, Upstream: e.Upstream,
})
}
return printJSON(u, out)
}
+18 -12
View File
@@ -11,17 +11,24 @@ import (
// newPortsCmd is devvm ports [all|none|LIST], and add and rm LIST, each
// with -g for what new VMs forward.
func newPortsCmd(u *ui.UI) *cobra.Command {
var global bool
var global, asJSON bool
// run shows the ports without a change, else makes it.
run := func(cmd *cobra.Command, c *vm.PortsChange) {
run := func(cmd *cobra.Command, c *vm.PortsChange) error {
var ports string
withEnv(u, func(env *vm.Env) error {
s := vm.Settings{Env: env}
if c == nil {
return s.Ports(cmd.Context(), u.Stdout(), global)
if c != nil {
c.Global = global
return s.SetPorts(cmd.Context(), *c)
}
c.Global = global
return s.SetPorts(cmd.Context(), *c)
var err error
ports, err = s.Ports(cmd.Context(), global)
return err
}, msg.PortsFailed)
if c != nil {
return nil
}
return printValue(u, asJSON, "ports", ports)
}
cmd := &cobra.Command{
Use: "ports [all|none|LIST]",
@@ -31,13 +38,13 @@ func newPortsCmd(u *ui.UI) *cobra.Command {
"changes it at once: a stopped VM forwards the new ports from its next start, and a running one's " +
"forwarder starts again with them, closing the connections open through it, while the VM runs on. " +
"With -g, show or change what new VMs forward instead.",
Args: cobra.MatchAll(maxArgs(1), func(_ *cobra.Command, args []string) error {
Args: showsOnly(cobra.MatchAll(maxArgs(1), func(_ *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
_, err := vm.ParsePorts(args[0])
return err
}),
})),
ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]cobra.Completion, cobra.ShellCompDirective) {
if len(args) > 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
@@ -49,11 +56,11 @@ func newPortsCmd(u *ui.UI) *cobra.Command {
if len(args) == 1 {
c = &vm.PortsChange{List: args[0]}
}
run(cmd, c)
return nil
return run(cmd, c)
},
}
cmd.PersistentFlags().BoolVarP(&global, "global", "g", false, "show or change what new VMs forward instead")
jsonFlag(cmd, &asJSON)
sub := func(op, short, long string) *cobra.Command {
return &cobra.Command{
Use: op + " LIST",
@@ -64,8 +71,7 @@ func newPortsCmd(u *ui.UI) *cobra.Command {
return err
}),
RunE: func(cmd *cobra.Command, args []string) error {
run(cmd, &vm.PortsChange{Op: op, List: args[0]})
return nil
return run(cmd, &vm.PortsChange{Op: op, List: args[0]})
},
}
}
+33 -8
View File
@@ -35,7 +35,8 @@ const retainLockAge = 10 * time.Minute
// newRetentionCmd is devvm retention [KEY=VALUE...]: the retention
// settings, shown bare.
func newRetentionCmd(u *ui.UI) *cobra.Command {
return &cobra.Command{
var asJSON bool
cmd := &cobra.Command{
Use: "retention [KEY=VALUE...]",
Short: "Show or change the retention settings: what devvm deletes on its own",
Long: "Show each retention setting and its value, off when it isn't set, or change them, each " +
@@ -48,18 +49,21 @@ func newRetentionCmd(u *ui.UI) *cobra.Command {
"or value, or one with no value, and then writes nothing. devvm applies the settings once a day, " +
"and devvm gc --retention applies them at once. They never delete a VM, an image or a tool any " +
"VM has.",
Args: func(_ *cobra.Command, args []string) error {
Args: showsOnly(func(_ *cobra.Command, args []string) error {
if err := state.CheckRetention(args); err != nil {
return msg.RetentionBad(err.Error()).Because(err)
}
return nil
},
}),
RunE: func(_ *cobra.Command, args []string) error {
dirs, err := paths.FromEnv()
fail(u, err, msg.RetentionSettingsFailed)
if len(args) == 0 {
r, err := state.ReadRetention(dirs)
fail(u, err, msg.RetentionSettingsFailed)
if asJSON {
return printJSON(u, retentionJSON(r))
}
_, err = u.Stdout().Write([]byte(retentionShown(r)))
return err
}
@@ -69,6 +73,8 @@ func newRetentionCmd(u *ui.UI) *cobra.Command {
return nil
},
}
jsonFlag(cmd, &asJSON)
return cmd
}
// retentionShown is every retention setting as KEY=VALUE lines, in the
@@ -76,15 +82,34 @@ func newRetentionCmd(u *ui.UI) *cobra.Command {
func retentionShown(r state.Retention) string {
var b strings.Builder
for _, key := range state.RetentionKeys() {
v := r.Raw[key]
if v == "" {
v = state.RetainOff
}
b.WriteString(key + "=" + v + "\n")
b.WriteString(key + "=" + retentionValue(r, key) + "\n")
}
return b.String()
}
// retentionValue is a retention setting's value as written, off when it
// isn't set.
func retentionValue(r state.Retention, key string) string {
if v := r.Raw[key]; v != "" {
return v
}
return state.RetainOff
}
// retentionOutput is devvm retention --json: every setting by its key,
// with its value as written, off when it isn't set.
type retentionOutput struct {
Settings map[string]string `json:"settings"`
}
func retentionJSON(r state.Retention) retentionOutput {
out := retentionOutput{Settings: map[string]string{}}
for _, key := range state.RetentionKeys() {
out.Settings[key] = retentionValue(r, key)
}
return out
}
// retained is what retention deleted.
type retained struct{ exports, tools, orphans, nixFiles int }
+3
View File
@@ -38,6 +38,9 @@ func NewRoot(u *ui.UI) *cobra.Command {
SilenceUsage: true,
SilenceErrors: true,
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
if wantsJSON(cmd) {
u.DataOnly() // stdout is the JSON's alone
}
makePrivate(u)
if !skipsRetention(cmd) {
autoRetain(cmd.Context(), u)
+42 -4
View File
@@ -2,6 +2,7 @@ package cli
import (
"os"
"strings"
"github.com/spf13/cobra"
@@ -29,6 +30,7 @@ func oneSecret(cmd *cobra.Command) {
// newSecretCmd is devvm secret: the secrets kept on this machine, listed.
func newSecretCmd(u *ui.UI) *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "secret",
Short: "List the secrets kept on this machine, for VMs to use",
@@ -38,8 +40,9 @@ func newSecretCmd(u *ui.UI) *cobra.Command {
"puts the secret into requests for the secret's hosts. Without network policy, the VM gets the " +
"secret itself.",
Args: noArgs,
RunE: func(cmd *cobra.Command, _ []string) error { return listSecrets(cmd, u) },
RunE: func(cmd *cobra.Command, _ []string) error { return listSecrets(cmd, u, asJSON) },
}
jsonFlag(cmd, &asJSON)
cmd.AddCommand(newSecretSetCmd(u), newSecretRmCmd(u),
newSecretUseCmd(u, "use", true), newSecretUseCmd(u, "unuse", false), newSecretGetCmd(u))
return cmd
@@ -97,9 +100,44 @@ func newSecretRmCmd(u *ui.UI) *cobra.Command {
return cmd
}
func listSecrets(cmd *cobra.Command, u *ui.UI) error {
withEnv(u, func(env *vm.Env) error { return vm.Net{Env: env}.Secrets(cmd.Context(), u.Stdout()) }, msg.SecretFailed)
return nil
// secretOutput is devvm secret --json: each secret's name, whether it's
// saved and the VMs using it, never its value.
type secretOutput struct {
Secrets []secretJSON `json:"secrets"`
}
type secretJSON struct {
Name string `json:"name"`
Saved bool `json:"saved"`
UsedBy []string `json:"used_by"`
}
// listSecrets writes the secrets as a table, or with asJSON as
// secretOutput.
func listSecrets(cmd *cobra.Command, u *ui.UI, asJSON bool) error {
var ss []vm.SecretListed
withEnv(u, func(env *vm.Env) error {
var err error
ss, err = vm.Net{Env: env}.Secrets(cmd.Context())
return err
}, msg.SecretFailed)
if asJSON {
out := secretOutput{Secrets: make([]secretJSON, 0, len(ss))}
for _, s := range ss {
out.Secrets = append(out.Secrets, secretJSON{Name: s.Name, Saved: s.Saved, UsedBy: append([]string{}, s.UsedBy...)})
}
return printJSON(u, out)
}
tab := u.Table()
tab.Header("NAME", "SAVED", "USED BY")
for _, s := range ss {
saved := "no"
if s.Saved {
saved = "yes"
}
tab.Row(cell(s.Name), cell(saved), cell(strings.Join(s.UsedBy, ", ")))
}
return tab.Flush()
}
// newSecretUseCmd is devvm secret use (use) or unuse.
+54 -7
View File
@@ -1,8 +1,11 @@
package cli
import (
"io"
"github.com/spf13/cobra"
"github.com/w3cj/devvm/internal/backend"
"github.com/w3cj/devvm/internal/msg"
"github.com/w3cj/devvm/internal/ui"
"github.com/w3cj/devvm/internal/vm"
@@ -13,8 +16,8 @@ import (
// root's for new VMs.
func newSizeCmd(u *ui.UI) *cobra.Command {
var (
global bool
s vm.Size
global, asJSON bool
s vm.Size
)
cmd := &cobra.Command{
Use: "size",
@@ -23,16 +26,26 @@ func newSizeCmd(u *ui.UI) *cobra.Command {
"--cpus, --memory and --disk change them, at once for a stopped VM, from its next start for " +
"a running one: devvm restart. A disk only grows. With -g, show or change the size new VMs " +
"get instead; what it leaves unset is the image's.",
Args: noArgs,
Args: showsOnly(noArgs, "cpus", "memory", "disk"),
RunE: func(cmd *cobra.Command, _ []string) error {
var shown vm.SizeShown
withEnv(u, func(env *vm.Env) error {
set := vm.Settings{Env: env}
if s == (vm.Size{}) {
return set.ShowSize(cmd.Context(), u.Stdout(), global)
if s != (vm.Size{}) {
return set.SetSize(cmd.Context(), s, global)
}
return set.SetSize(cmd.Context(), s, global)
var err error
shown, err = set.ShowSize(cmd.Context(), global)
return err
}, msg.SizeFailed)
return nil
switch {
case s != (vm.Size{}):
return nil
case asJSON:
return printJSON(u, sizeJSON(shown))
}
_, err := io.WriteString(u.Stdout(), shown.Text())
return err
},
}
f := cmd.Flags()
@@ -40,5 +53,39 @@ func newSizeCmd(u *ui.UI) *cobra.Command {
f.StringVar(&s.CPUs, "cpus", "", "the `N` CPUs the VM gets")
f.StringVar(&s.Memory, "memory", "", "the VM's memory in `GiB`: 16, 16G or 16GiB")
f.StringVar(&s.Disk, "disk", "", "the VM's disk in `GiB`, at least what it has")
jsonFlag(cmd, &asJSON)
return cmd
}
// sizeShape is a size in devvm size --json: what's unset (the image's,
// for -g; a disk on a backend that sizes none) is left out.
type sizeShape struct {
CPUs int `json:"cpus,omitempty"`
MemoryGiB float64 `json:"memory_gib,omitempty"`
DiskGiB float64 `json:"disk_gib,omitempty"`
}
func shapeOfSize(s backend.Size) sizeShape {
return sizeShape{CPUs: s.CPUs, MemoryGiB: s.MemoryGiB, DiskGiB: s.DiskGiB}
}
// sizeOutput is devvm size --json: the VM's size, what its disk holds on
// a backend that sizes no disks, and what changes at its next start; with
// -g, the size new VMs get.
type sizeOutput struct {
sizeShape
DiskUsedGiB *float64 `json:"disk_used_gib,omitempty"`
Pending *sizeShape `json:"pending,omitempty"`
}
func sizeJSON(s vm.SizeShown) sizeOutput {
out := sizeOutput{sizeShape: shapeOfSize(s.Size)}
if s.DiskMeasured {
out.DiskUsedGiB = &s.DiskUsedGiB
}
if s.Pending != (backend.Size{}) {
p := shapeOfSize(s.Pending)
out.Pending = &p
}
return out
}
+12 -6
View File
@@ -3,7 +3,6 @@ package cli
import (
"cmp"
"context"
"encoding/json"
"errors"
"io/fs"
"os"
@@ -63,11 +62,18 @@ func newSpaceCmd(u *ui.UI, g *globals) *cobra.Command {
u.Note(msg.SpaceStray(s.Backend, s.Data, s.Name))
}
if asJSON {
enc := json.NewEncoder(u.Stdout())
enc.SetIndent("", " ")
return enc.Encode(r)
// Lists are [] when empty, never null.
if r.Rows == nil {
r.Rows = []spaceRow{}
}
if r.Caches == nil {
r.Caches = []cacheRow{}
}
err = printJSON(u, r)
} else {
err = writeSpace(u.Table(), r)
}
if err := writeSpace(u.Table(), r); err != nil {
if err != nil {
return err
}
if len(r.Caches) > 0 {
@@ -76,7 +82,7 @@ func newSpaceCmd(u *ui.UI, g *globals) *cobra.Command {
return nil
},
}
c.Flags().BoolVar(&asJSON, "json", false, "print it as JSON, for scripts")
jsonFlag(c, &asJSON)
return c
}
+52 -10
View File
@@ -1,6 +1,8 @@
package cli
import (
"io"
"github.com/spf13/cobra"
"github.com/w3cj/devvm/internal/msg"
@@ -12,6 +14,7 @@ import (
// newSSHAgentCmd is devvm ssh-agent [on|devvm|off], and devvm's own
// agent's add and rm.
func newSSHAgentCmd(u *ui.UI) *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "ssh-agent [on|devvm|off]",
Short: "Show or change SSH agent forwarding for this folder's VM",
@@ -21,26 +24,65 @@ func newSSHAgentCmd(u *ui.UI) *cobra.Command {
"first, and each key added to it: its file, its fingerprint and how it's loaded. devvm ssh-agent " +
"on, devvm or off changes the VM's forwarding from its next start: devvm restart. While it's on " +
"and you're connected, anything in the VM can use the agent's keys.",
Args: maxArgs(1),
Args: showsOnly(maxArgs(1)),
ValidArgs: sshagent.Modes,
RunE: func(cmd *cobra.Command, args []string) error {
withEnv(u, func(env *vm.Env) error {
s := vm.Settings{Env: env}
if len(args) == 0 {
return s.SSHAgent(cmd.Context(), u.Stdout())
}
return s.SetSSHAgent(cmd.Context(), args[0])
}, msg.SSHAgentFailed)
if len(args) == 0 {
withEnv(u, func(env *vm.Env) error { return vm.Settings{Env: env}.AgentKeys(cmd.Context(), u.Stdout()) }, msg.AgentKeysFailed)
if len(args) == 1 {
withEnv(u, func(env *vm.Env) error { return vm.Settings{Env: env}.SetSSHAgent(cmd.Context(), args[0]) }, msg.SSHAgentFailed)
return nil
}
var mode string
withEnv(u, func(env *vm.Env) error {
var err error
mode, err = vm.Settings{Env: env}.SSHAgent(cmd.Context())
return err
}, msg.SSHAgentFailed)
if asJSON {
return printAgentJSON(cmd, u, mode)
}
if _, err := io.WriteString(u.Stdout(), mode+"\n"); err != nil {
return err
}
withEnv(u, func(env *vm.Env) error { return vm.Settings{Env: env}.AgentKeys(cmd.Context(), u.Stdout()) }, msg.AgentKeysFailed)
return nil
},
}
jsonFlag(cmd, &asJSON)
cmd.AddCommand(newSSHAgentAddCmd(u), newSSHAgentRmCmd(u))
return cmd
}
// sshAgentOutput is devvm ssh-agent --json: the VM's forwarding, and the
// keys added to devvm's own agent.
type sshAgentOutput struct {
Mode string `json:"mode"`
Keys []agentKeyJSON `json:"keys"`
}
type agentKeyJSON struct {
File string `json:"file"`
Fingerprint string `json:"fingerprint,omitempty"`
Confirm bool `json:"confirm"`
Lifetime string `json:"lifetime"`
Loaded bool `json:"loaded"`
}
// printAgentJSON writes the VM's forwarding mode and devvm's own agent's
// keys as sshAgentOutput.
func printAgentJSON(cmd *cobra.Command, u *ui.UI, mode string) error {
var keys []sshagent.ListedKey
withEnv(u, func(env *vm.Env) error {
var err error
keys, err = vm.Settings{Env: env}.AgentKeyList(cmd.Context())
return err
}, msg.AgentKeysFailed)
out := sshAgentOutput{Mode: mode, Keys: make([]agentKeyJSON, 0, len(keys))}
for _, k := range keys {
out.Keys = append(out.Keys, agentKeyJSON(k))
}
return printJSON(u, out)
}
func newSSHAgentAddCmd(u *ui.UI) *cobra.Command {
var o sshagent.AddOptions
cmd := &cobra.Command{
+31
View File
@@ -16,6 +16,7 @@ import (
// newToolsCmd is devvm tools: this folder's VM's shared tools, and add,
// rm and update, which change them.
func newToolsCmd(u *ui.UI, g *globals) *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "tools",
Short: "Show this folder's VM's shared tools",
@@ -30,13 +31,43 @@ func newToolsCmd(u *ui.UI, g *globals) *cobra.Command {
ts, err = vm.Tools{Env: env}.List(cmd.Context())
return err
}, msg.ToolsFailed)
if asJSON {
return printJSON(u, toolsJSON(ts))
}
return writeTools(u.Table(), ts)
},
}
jsonFlag(cmd, &asJSON)
cmd.AddCommand(newToolsAddCmd(u, g), newToolsRmCmd(u, g), newToolsUpdateCmd(u, g))
return cmd
}
// toolsOutput is devvm tools --json: the VM's shared tools, each with the
// newer version the tools lock has, when it has one, and whether that one
// is built.
type toolsOutput struct {
Tools []vmToolJSON `json:"tools"`
}
type vmToolJSON struct {
Tool string `json:"tool"`
Version string `json:"version"`
Newer string `json:"newer,omitempty"`
Built *bool `json:"newer_built,omitempty"`
}
func toolsJSON(ts []tools.VMTool) toolsOutput {
out := toolsOutput{Tools: make([]vmToolJSON, 0, len(ts))}
for _, t := range ts {
j := vmToolJSON{Tool: t.Tool, Version: t.Version, Newer: t.Newer}
if t.Newer != "" {
j.Built = &t.Built
}
out.Tools = append(out.Tools, j)
}
return out
}
// writeTools writes a VM's tools as a table, a header first.
func writeTools(tab *ui.Table, ts []tools.VMTool) error {
tab.Header("TOOL", "VERSION", "NEWER", "BUILT")
+1
View File
@@ -182,6 +182,7 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede
"net_off_log": "safety/network#turning-it-on-or-off",
"net_off_policy": "safety/network#turning-it-on-or-off",
"net_ask_global": "safety/network#turning-it-on-or-off",
"json_shows_only": "getting-started/commands#output-for-scripts",
"net_flag_ignored": "safety/network#turning-it-on-or-off",
"net_on_old_tokens": "safety/network#turning-it-on-or-off",
"net_off_next_start": "safety/network#turning-it-on-or-off",
+6
View File
@@ -1504,6 +1504,11 @@ func InterruptedVM(vm string) M {
return M{id: "interrupted_vm", vals: []val{{"vm", vm}}}
}
// JSONShowsOnly is [json_shows_only]: "{{.command}} --json only shows, so it takes no value. Run it without --json to change the setting."
func JSONShowsOnly(command string) M {
return M{id: "json_shows_only", vals: []val{{"command", command}}}
}
// Kept is [kept]: "kept {{.vm}}"
func Kept(vm string) M {
return M{id: "kept", vals: []val{{"vm", vm}}}
@@ -3251,6 +3256,7 @@ var specs = map[string]spec{
"images_unused": {fields: []string{"size"}},
"interrupted_image": {fields: []string{"vm"}},
"interrupted_vm": {fields: []string{"vm"}},
"json_shows_only": {fields: []string{"command"}},
"kept": {fields: []string{"vm"}},
"key_loaded": {},
"key_loaded_keychain": {},
+91 -36
View File
@@ -94,6 +94,46 @@ func (l *Log) Write(ctx context.Context, w io.Writer, n int, follow bool) error
}
}
// Event is one event of a VM's network log, as its proxy wrote it.
type Event = proxy.Event
// Events returns the log's last n events, the previous file's (Old)
// first. Lines that aren't events are skipped.
func (l *Log) Events(n int) ([]Event, error) {
var last []Event
err := l.each(func(line string) {
var e Event
if json.Unmarshal([]byte(line), &e) != nil || e.Event == "" || n <= 0 {
return
}
if len(last) == n {
last = last[1:]
}
last = append(last, e)
})
return last, err
}
// each calls line for each line of the log, the previous file's (Old)
// first, and for what follows its last newline.
func (l *Log) each(line func(string)) error {
f, err := os.Open(l.Path)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
if err := l.readOld(f, line); err != nil {
return err
}
var read int64
rest, err := readLines(bufio.NewReader(f), &read, line)
if err != nil {
return err
}
line(rest)
return nil
}
// readOld calls line for each line of Old, unless it's cur, the log
// already open.
func (l *Log) readOld(cur *os.File, line func(string)) error {
@@ -238,11 +278,11 @@ func FormatEvent(line string) (string, bool) {
if e.Upstream != "" {
d += ", through " + e.Upstream
}
return fmt.Sprintf("%s %-7s %s %s", oneLine(e.Time), what, hostPort(e), oneLine(d)), true
return fmt.Sprintf("%s %-7s %s %s", oneLine(e.Time), what, hostPort(e.Host, e.Port), oneLine(d)), true
}
func hostPort(e proxy.Event) string {
return net.JoinHostPort(oneLine(e.Host), strconv.Itoa(e.Port))
func hostPort(host string, port int) string {
return net.JoinHostPort(oneLine(host), strconv.Itoa(port))
}
// oneLine drops every control character from s (C0, newlines and tabs
@@ -257,29 +297,29 @@ func oneLine(s string) string {
}, s)
}
// WriteBlocked writes the log's blocks (Old's too) to w as a table, one row per host
// and port, by when it was last blocked: the last time, how many times,
// and the devvm network allow command that allows it. A request refused
// whatever the allowlist says, or a host the policy doesn't take, gets -
// instead: the command is meant to be pasted into a shell.
func (l *Log) WriteBlocked(w io.Writer) error {
f, err := os.Open(l.Path)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
type row struct {
last, host, allow string
count int
}
// Block is a host and port a VM's proxy blocked, as devvm network log
// --blocked lists it.
type Block struct {
Last string // when it was last blocked
Count int // how many times
Host string
Port int
// Allow is the rule devvm network allow takes to allow it; "" for a
// request refused whatever the allowlist says, or a host the policy
// doesn't take.
Allow string
}
// Blocks returns the log's blocks (Old's too), one per host and port, by
// when each was last blocked.
func (l *Log) Blocks() ([]Block, error) {
type key struct {
host string
port int
refused bool
}
rows := map[key]*row{}
var read int64
add := func(l string) {
rows := map[key]*Block{}
err := l.each(func(l string) {
var e proxy.Event
if json.Unmarshal([]byte(l), &e) != nil || e.Event != "blocked" {
return
@@ -287,32 +327,47 @@ func (l *Log) WriteBlocked(w io.Writer) error {
k := key{e.Host, e.Port, e.Refused}
r := rows[k]
if r == nil {
r = &row{host: hostPort(e), allow: "-"}
r = &Block{Host: e.Host, Port: e.Port}
if rule, ok := proxy.AllowRule(e.Host, e.Port); ok && !e.Refused {
r.allow = "devvm network allow " + rule
r.Allow = rule
}
rows[k] = r
}
r.count++
r.last = oneLine(e.Time)
r.Count++
r.Last = e.Time
})
if err != nil {
return nil, err
}
if err := l.readOld(f, add); err != nil {
return err
sorted := make([]Block, 0, len(rows))
for _, r := range rows {
sorted = append(sorted, *r)
}
rest, err := readLines(bufio.NewReader(f), &read, add)
slices.SortFunc(sorted, func(a, b Block) int {
return cmp.Or(cmp.Compare(a.Last, b.Last), cmp.Compare(hostPort(a.Host, a.Port), hostPort(b.Host, b.Port)))
})
return sorted, nil
}
// WriteBlocked writes the log's blocks (Blocks) to w as a table, one row
// per host and port, by when it was last blocked: the last time, how many
// times, and the devvm network allow command that allows it. A request
// refused whatever the allowlist says, or a host the policy doesn't take,
// gets - instead: the command is meant to be pasted into a shell. The VM
// chose the host: control characters are dropped.
func (l *Log) WriteBlocked(w io.Writer) error {
blocks, err := l.Blocks()
if err != nil {
return err
}
add(rest)
sorted := make([]*row, 0, len(rows))
for _, r := range rows {
sorted = append(sorted, r)
}
slices.SortFunc(sorted, func(a, b *row) int { return cmp.Or(cmp.Compare(a.last, b.last), cmp.Compare(a.host, b.host)) })
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
_, _ = fmt.Fprintln(tw, "LAST\tCOUNT\tHOST\tALLOW WITH")
for _, r := range sorted {
_, _ = fmt.Fprintf(tw, "%s\t%d\t%s\t%s\n", r.last, r.count, r.host, r.allow)
for _, b := range blocks {
allow := "-"
if b.Allow != "" {
allow = "devvm network allow " + b.Allow
}
_, _ = fmt.Fprintf(tw, "%s\t%d\t%s\t%s\n", oneLine(b.Last), b.Count, hostPort(b.Host, b.Port), allow)
}
return tw.Flush()
}
+14
View File
@@ -283,4 +283,18 @@ func TestWriteBlocked(t *testing.T) {
if b.String() != want {
t.Errorf("WriteBlocked:\n%s\nwant:\n%s", b.String(), want)
}
blocks, err := (&Log{Path: path}).Blocks()
if err != nil || len(blocks) != 5 {
t.Fatalf("Blocks = %+v, %v", blocks, err)
}
if got, want := blocks[3], (Block{Last: "T4", Count: 2, Host: "a.test", Port: 443, Allow: "a.test"}); got != want {
t.Errorf("Blocks[3] = %+v, want %+v", got, want)
}
if blocks[4].Allow != "" {
t.Errorf("a refused block has a rule: %+v", blocks[4])
}
events, err := (&Log{Path: path}).Events(3)
if err != nil || len(events) != 3 || events[0].Host != "fd00::1" || events[2].Host != "api.github.com" {
t.Errorf("Events(3) = %+v, %v", events, err)
}
}
+22 -8
View File
@@ -87,13 +87,19 @@ func RemoveRule(path, rule string) (bool, error) {
return true, writeRules(path, kept)
}
// WriteRules writes the rules of each policy file that has any to w: the
// file's path after #, then its rules, indented, comments left out.
func WriteRules(w io.Writer, files []string) error {
// RuleFile is a policy file and its rules, comments left out.
type RuleFile struct {
Path string
Rules []string
}
// ReadRules returns each of files that has rules, in order, with them.
func ReadRules(files []string) ([]RuleFile, error) {
var out []RuleFile
for _, f := range files {
lines, err := readRules(f)
if err != nil {
return err
return nil, err
}
var rules []string
for _, l := range lines {
@@ -101,13 +107,21 @@ func WriteRules(w io.Writer, files []string) error {
rules = append(rules, r)
}
}
if len(rules) == 0 {
continue
if len(rules) > 0 {
out = append(out, RuleFile{Path: f, Rules: rules})
}
if _, err := fmt.Fprintf(w, "# %s\n", f); err != nil {
}
return out, nil
}
// WriteRules writes each policy file's rules to w: the file's path after
// #, then its rules, indented.
func WriteRules(w io.Writer, files []RuleFile) error {
for _, f := range files {
if _, err := fmt.Fprintf(w, "# %s\n", f.Path); err != nil {
return err
}
for _, r := range rules {
for _, r := range f.Rules {
if _, err := fmt.Fprintf(w, " %s\n", r); err != nil {
return err
}
+5 -1
View File
@@ -107,8 +107,12 @@ func TestWriteRules(t *testing.T) {
if err := os.WriteFile(b, []byte("# only a comment\n"), 0o600); err != nil {
t.Fatal(err)
}
files, err := ReadRules([]string{a, b, c})
if err != nil || len(files) != 1 || files[0].Path != a || strings.Join(files[0].Rules, " ") != "x.test !y.test" {
t.Fatalf("ReadRules = %+v, %v", files, err)
}
var out strings.Builder
if err := WriteRules(&out, []string{a, b, c}); err != nil {
if err := WriteRules(&out, files); err != nil {
t.Fatal(err)
}
if want := "# " + a + "\n x.test\n !y.test\n"; out.String() != want {
+39
View File
@@ -505,3 +505,42 @@ func (a *Agent) Keys(ctx context.Context, w io.Writer) error {
}
return nil
}
// ListedKey is a key added to devvm's own agent, as devvm ssh-agent
// --json lists it.
type ListedKey struct {
File string // the key file
Fingerprint string // its fingerprint when added, "" if unknown
Confirm bool // the agent asks before each use
Lifetime string // how long the agent keeps it once loaded: 12h, forever
Loaded bool // the agent holds it now
}
// KeyList returns the keys added to the agent, loading those it lacks
// first, each with whether the agent holds it. With none added, it
// returns none and doesn't start the agent.
func (a *Agent) KeyList(ctx context.Context) ([]ListedKey, error) {
keys, err := state.ReadAgentKeys(a.Dirs)
if err != nil || len(keys) == 0 {
return nil, err
}
if err := a.Ensure(ctx); err != nil {
return nil, err
}
out, _ := a.list(ctx)
fps, _ := held(out)
listed := make([]ListedKey, 0, len(keys))
for _, k := range keys {
l := ListedKey{File: k.File, Fingerprint: k.Fingerprint, Lifetime: DefaultLifetime}
for _, o := range strings.Fields(k.Options) {
if o == "confirm" {
l.Confirm = true
} else if v, ok := strings.CutPrefix(o, "lifetime="); ok {
l.Lifetime = v
}
}
l.Loaded = k.Fingerprint != "" && slices.Contains(fps, k.Fingerprint)
listed = append(listed, l)
}
return listed, nil
}
+11
View File
@@ -344,6 +344,14 @@ func TestKeys(t *testing.T) {
if b.String() != want {
t.Errorf("keys:\n%s\nwant:\n%s", b.String(), want)
}
listed, err := a.KeyList(t.Context())
wantList := []ListedKey{
{File: k1, Fingerprint: "SHA256:fp-a", Lifetime: "12h", Loaded: true},
{File: k2, Fingerprint: "SHA256:fp-b", Lifetime: "1h", Loaded: true},
}
if err != nil || !slices.Equal(listed, wantList) {
t.Errorf("KeyList = %+v, %v; want %+v", listed, names(err), wantList)
}
}
// With no key added, keys writes nothing and starts no agent.
@@ -356,6 +364,9 @@ func TestKeysNone(t *testing.T) {
if b.Len() != 0 || len(f.calls) != 0 || f.up || len(out.lines) != 0 {
t.Errorf("wrote %q, calls %q, said %q", b.String(), f.calls, out.lines)
}
if l, err := a.KeyList(t.Context()); err != nil || l != nil || len(f.calls) != 0 {
t.Errorf("KeyList = %+v, %v, calls %q", l, err, f.calls)
}
}
// rm takes the key out of the agent, by its fingerprint, and out of the
+1 -1
View File
@@ -30,7 +30,7 @@ func devvm() rules {
"internal/backend/docker.Docker": {86, "a backend: backend.Backend's 28 methods, the optional ones it implements and Docker's own, its ssh, ports, agent and docker layer emulations among them; its docker commands are its client's"},
"internal/backend/backendtest.Fake": {35, "backend.Backend's 28 methods and what tests ask of it"},
"internal/paths.Dirs": {42, "one method per folder or file devvm uses: a list"},
"internal/ui.UI": {44, "the one terminal: messages, errors with the caller's exit code, prompts, status line, tables, run log and how many are kept, cleanups, signals"},
"internal/ui.UI": {45, "the one terminal: messages and where they go, errors with the caller's exit code, prompts, status line, tables, run log and how many are kept, cleanups, signals"},
},
allowedVars: map[string]string{
"internal/cli.version": ldflags,
+2 -1
View File
@@ -111,7 +111,8 @@ func (u *UI) LogNote() {
u.log.noted = true
u.log.Unlock()
if !noted {
u.write(u.stdout, " "+u.outStyle.message(msg.LogDetails(path))+"\n")
w, st := says(u)
u.write(w, " "+st.message(msg.LogDetails(path))+"\n")
}
}
+22 -2
View File
@@ -51,6 +51,9 @@ type UI struct {
interruptGrace time.Duration
interrupted atomic.Bool
// dataOnly sends what Say, Info and LogNote print to stderr, so
// stdout gets only data (DataOnly).
dataOnly atomic.Bool
// commands is read-locked while a logged command runs, so an
// interrupt can wait for the run's commands to end before cleaning up.
commands sync.RWMutex
@@ -147,13 +150,30 @@ func (u *UI) write(w io.Writer, s string) {
_, _ = io.WriteString(w, s)
}
// DataOnly keeps stdout for data from now on: what Say, Info and LogNote
// print goes to stderr instead, for a command whose output is JSON.
func (u *UI) DataOnly() { u.dataOnly.Store(true) }
// says is where u's Say, Info and LogNote print, with its style: stdout,
// stderr after DataOnly.
func says(u *UI) (io.Writer, style) {
if u.dataOnly.Load() {
return u.stderr, u.errStyle
}
return u.stdout, u.outStyle
}
// Say prints the message to stdout.
func (u *UI) Say(m msg.M) { u.write(u.stdout, u.outStyle.message(m)+"\n") }
func (u *UI) Say(m msg.M) {
w, st := says(u)
u.write(w, st.message(m)+"\n")
}
// Info prints "==> " (bold in a terminal) and the message to stdout: what
// devvm did.
func (u *UI) Info(m msg.M) {
u.write(u.stdout, u.outStyle.paint(sgrBold, "==>")+" "+u.outStyle.message(m)+"\n")
w, st := says(u)
u.write(w, st.paint(sgrBold, "==>")+" "+st.message(m)+"\n")
}
// Note prints the message to stderr.
+7
View File
@@ -70,6 +70,13 @@ func TestStreamsAndPrefixes(t *testing.T) {
if out.String() != tc.stdout || errOut.String() != tc.stder {
t.Errorf("stdout %q, stderr %q; want %q, %q", out, errOut, tc.stdout, tc.stder)
}
// With DataOnly, every message goes to stderr.
u, out, errOut = testUI(t, "")
u.DataOnly()
tc.print(u, m)
if out.Len() != 0 || errOut.String() != tc.stdout+tc.stder {
t.Errorf("DataOnly: stdout %q, stderr %q; want nothing, %q", out, errOut, tc.stdout+tc.stder)
}
})
}
}
+4 -3
View File
@@ -20,7 +20,8 @@ import (
type Listed struct {
Name string
Status string // as its backend reports it
Image string // its image's label: node+claude, base (from node:24)
Image string // its image: node+claude, base
From string // the container image its base started from (--from), if any
Git string // its .git protection: on, off, or clone for a --clone VM
Net string // its network policy: on, off or unenforced (netpolicy.Listed)
Backend string
@@ -79,8 +80,8 @@ func listed(ctx context.Context, d paths.Dirs, b backend.Backend, in backend.Ins
Git: st.Get(gitprotect.KeyGitProtect), Backend: b.Name(), DockerLayer: st.Get(KeyDockerLayer),
Folder: st.Get(state.KeyDir),
}
if from := st.Get(state.KeyFrom); l.Image != "" && from != "" {
l.Image = msg.ImageFrom(from, l.Image).Line()
if l.Image != "" {
l.From = st.Get(state.KeyFrom)
}
if isClone(st) {
l.Git = ModeClone
+1 -1
View File
@@ -86,7 +86,7 @@ func TestList(t *testing.T) {
{Name: other, Status: "Running", Image: "go", Git: "on", Net: "off", Backend: "other", Folder: "/p/api"},
{Name: clone, Status: "Stopped", Image: "base", Git: "clone", Net: "unenforced", Backend: "lima", Folder: "/p/cl"},
{Name: half, Status: "Stopped", Backend: "lima"},
{Name: img, Status: "Stopped", Image: "image_from from=node:24 image=base", Git: "off", Net: "off", Backend: "lima", Folder: "/p/img-foo"},
{Name: img, Status: "Stopped", Image: "base", From: "node:24", Git: "off", Net: "off", Backend: "lima", Folder: "/p/img-foo"},
{Name: web, Status: "Running", Image: "node+claude", Git: "on", Net: "unenforced", Backend: "lima", Folder: "/p/web"},
}
if !reflect.DeepEqual(got, want) {
+63 -32
View File
@@ -19,42 +19,40 @@ import (
// (secret.go).
type Net struct{ *Env }
// Network writes the folder's VM's network policy to w, as devvm ls
// shows it (on, off or unenforced), then its allowlist: each policy file
// its proxy reads that has rules, in order.
func (e Net) Network(ctx context.Context, w io.Writer) error {
// NetworkShown is the folder's VM's network policy, as devvm network
// shows it.
type NetworkShown struct {
Policy string // on, off or unenforced, as devvm ls shows it
// Rules are the rules of each policy file its proxy reads that has
// any, in order.
Rules []netpolicy.RuleFile
}
// Network returns the folder's VM's network policy and its allowlist.
func (e Net) Network(ctx context.Context) (NetworkShown, error) {
var s NetworkShown
t, err := e.existing(ctx, "")
if err != nil {
return err
return s, err
}
in, err := t.b.Inspect(ctx, t.f.Name)
if err != nil {
return err
return s, err
}
shown, err := netpolicy.Listed(ctx, t.b, t.st, in.Status == backend.StatusRunning)
if err != nil {
return err
if s.Policy, err = netpolicy.Listed(ctx, t.b, t.st, in.Status == backend.StatusRunning); err != nil {
return s, err
}
files, err := e.Proxy.PolicyFiles(t.f.Name, t.st.Get(state.KeyImage))
if err != nil {
return err
return s, err
}
if _, err := io.WriteString(w, shown+"\n"); err != nil {
return err
}
return netpolicy.WriteRules(w, files)
s.Rules, err = netpolicy.ReadRules(files)
return s, err
}
// NetworkDefault writes to w whether new VMs get network policy: ask, on
// or off.
func (e Net) NetworkDefault(w io.Writer) error {
mode, err := state.ReadNetwork(e.Dirs)
if err != nil {
return err
}
_, err = io.WriteString(w, mode+"\n")
return err
}
// NetworkDefault returns whether new VMs get network policy: ask, on or
// off.
func (e Net) NetworkDefault() (string, error) { return state.ReadNetwork(e.Dirs) }
// SetNetworkDefault saves whether new VMs get network policy (a
// state.NetworkChoices value), as devvm setup does. The flags of devvm
@@ -127,9 +125,46 @@ type LogOptions struct {
// and blocked. A VM without network policy logs nothing new, and devvm
// says so.
func (e Net) Log(ctx context.Context, w io.Writer, o LogOptions) error {
l, vm, err := e.netLog(ctx, o.Follow)
if err != nil || l == nil {
if err == nil {
e.Info(msg.LogEmpty(vm))
}
return err
}
if o.Blocked {
return l.WriteBlocked(w)
}
return l.Write(ctx, w, o.Lines, o.Follow)
}
// LogEvents returns the last n events of the folder's VM's network log,
// oldest first: none when it has none.
func (e Net) LogEvents(ctx context.Context, n int) ([]netpolicy.Event, error) {
l, _, err := e.netLog(ctx, false)
if err != nil || l == nil {
return nil, err
}
return l.Events(n)
}
// LogBlocks returns the blocks in the folder's VM's network log, one per
// host and port, by when each was last blocked: none when it has none.
func (e Net) LogBlocks(ctx context.Context) ([]netpolicy.Block, error) {
l, _, err := e.netLog(ctx, false)
if err != nil || l == nil {
return nil, err
}
return l.Blocks()
}
// netLog returns the folder's VM's network log and the VM's name; a nil
// log when there's nothing to show (follow: nothing to follow). A VM
// without network policy logs nothing new, and devvm says so.
func (e Net) netLog(ctx context.Context, follow bool) (*netpolicy.Log, string, error) {
t, err := e.findExisting(ctx, "")
if err != nil {
return err
return nil, "", err
}
vm := t.f.Name
if !netpolicy.On(t.st) {
@@ -140,14 +175,10 @@ func (e Net) Log(ctx context.Context, w io.Writer, o LogOptions) error {
// One it just rotated is empty, with its events in the old one.
fi, err := os.Stat(l.Path)
_, oerr := os.Stat(l.Old())
if errors.Is(err, os.ErrNotExist) || err == nil && fi.Size() == 0 && !o.Follow && errors.Is(oerr, os.ErrNotExist) {
e.Info(msg.LogEmpty(vm))
return nil
if errors.Is(err, os.ErrNotExist) || err == nil && fi.Size() == 0 && !follow && errors.Is(oerr, os.ErrNotExist) {
return nil, vm, nil
}
if o.Blocked {
return l.WriteBlocked(w)
}
return l.Write(ctx, w, o.Lines, o.Follow)
return l, vm, nil
}
// policyVM finds the folder's VM for devvm network allow, deny and rm,
+3 -5
View File
@@ -24,11 +24,9 @@ func TestNetwork(t *testing.T) {
n, l := Net{e}, Launch{e}
shown := func(want string) {
t.Helper()
var b strings.Builder
err := n.Network(t.Context(), &b)
line, rules, _ := strings.Cut(b.String(), "\n")
if err != nil || line != want || !strings.HasPrefix(rules, "# ") || !strings.Contains(rules, "/layers/base.policy\n ") {
t.Errorf("Network = %q, %v; want %s", b.String(), names(err), want)
s, err := n.Network(t.Context())
if err != nil || s.Policy != want || len(s.Rules) == 0 || !strings.HasSuffix(s.Rules[0].Path, "/layers/base.policy") || len(s.Rules[0].Rules) == 0 {
t.Errorf("Network = %+v, %v; want %s", s, names(err), want)
}
}
shown("off")
+8 -17
View File
@@ -2,7 +2,6 @@ package vm
import (
"context"
"io"
"regexp"
"slices"
"strconv"
@@ -153,25 +152,17 @@ func orAll(ports string) string {
// portsVM finds the folder's VM for devvm ports.
func (e Settings) portsVM(ctx context.Context) (*found, error) { return e.folderVM(ctx, msg.NoVMPorts) }
// Ports writes to w which ports the folder's VM forwards (all, none or a
// Ports returns which ports the folder's VM forwards (all, none or a
// list); with global, what new VMs forward.
func (e Settings) Ports(ctx context.Context, w io.Writer, global bool) error {
ports := ""
func (e Settings) Ports(ctx context.Context, global bool) (string, error) {
if global {
def, err := e.defaultPorts()
if err != nil {
return err
}
ports = def
} else {
t, err := e.portsVM(ctx)
if err != nil {
return err
}
ports = orAll(t.st.Get(KeyPorts))
return e.defaultPorts()
}
_, err := io.WriteString(w, ports+"\n")
return err
t, err := e.portsVM(ctx)
if err != nil {
return "", err
}
return orAll(t.st.Get(KeyPorts)), nil
}
// SetPorts changes which ports the folder's VM forwards: a stopped VM's
+2 -3
View File
@@ -169,9 +169,8 @@ func TestSetPortsRunning(t *testing.T) {
if !slices.Equal(infos, []string{"ports_forwarding ports=5173,8080-8081 vm=" + vm}) || !slices.Equal(warned, []string{"ports_taken count=1 ports=8080 vm=" + vm}) {
t.Errorf("said %q, warned %q", infos, warned)
}
var b strings.Builder
if err := s.Ports(t.Context(), &b, false); err != nil || b.String() != "5173,8080-8081\n" {
t.Errorf("ports: %q, %v", b.String(), err)
if ports, err := s.Ports(t.Context(), false); err != nil || ports != "5173,8080-8081" {
t.Errorf("ports: %q, %v", ports, err)
}
if err := f.Stop(t.Context(), vm); err != nil {
t.Fatal(err)
+20 -19
View File
@@ -3,10 +3,6 @@ package vm
import (
"context"
"errors"
"fmt"
"io"
"strings"
"text/tabwriter"
"github.com/w3cj/devvm/internal/msg"
"github.com/w3cj/devvm/internal/netpolicy"
@@ -51,12 +47,22 @@ func (e Net) SecretRm(ctx context.Context, name string) error {
return nil
}
// Secrets writes the known secrets to w as a table: whether a value is
// saved (or, for claude, in devvm's environment), and the VMs using each.
func (e Net) Secrets(ctx context.Context, w io.Writer) error {
// SecretListed is a known secret as devvm secret lists it: never its
// value.
type SecretListed struct {
Name string
// Saved is whether a value is saved (or, for claude, in devvm's
// environment).
Saved bool
UsedBy []string // the VMs using it, by name
}
// Secrets returns the known secrets, each with whether a value is saved
// and the VMs using it.
func (e Net) Secrets(ctx context.Context) ([]SecretListed, error) {
names, err := state.VMNames(e.Dirs)
if err != nil {
return err
return nil, err
}
users := map[string][]string{}
for _, vm := range names {
@@ -68,22 +74,17 @@ func (e Net) Secrets(ctx context.Context, w io.Writer) error {
users[s] = append(users[s], vm)
}
}
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
_, _ = fmt.Fprintln(tw, "NAME\tSAVED\tUSED BY")
out := make([]SecretListed, 0, len(secrets.Known))
for _, s := range secrets.Known {
saved := "yes"
saved := true
if _, err := e.Proxy.Secrets.Value(ctx, s.Name); errors.Is(err, secrets.ErrNone) {
saved = "no"
saved = false
} else if err != nil {
return err
return nil, err
}
used := "-"
if len(users[s.Name]) > 0 {
used = strings.Join(users[s.Name], ", ")
}
_, _ = fmt.Fprintln(tw, s.Name+"\t"+saved+"\t"+used)
out = append(out, SecretListed{Name: s.Name, Saved: saved, UsedBy: users[s.Name]})
}
return tw.Flush()
return out, nil
}
// SecretUse binds a known secret to the folder's VM (use), or unbinds it.
+13 -5
View File
@@ -19,13 +19,21 @@ func TestSecrets(t *testing.T) {
ctx := t.Context()
list := func() string {
t.Helper()
var b strings.Builder
if err := n.Secrets(ctx, &b); err != nil {
ss, err := n.Secrets(ctx)
if err != nil {
t.Fatal(names(err))
}
var b strings.Builder
for _, s := range ss {
saved := "no"
if s.Saved {
saved = "yes"
}
b.WriteString(s.Name + " " + saved + " " + strings.Join(s.UsedBy, ",") + "\n")
}
return b.String()
}
if got, want := list(), "NAME SAVED USED BY\nclaude no -\ngithub no -\n"; got != want {
if got, want := list(), "claude no \ngithub no \n"; got != want {
t.Errorf("Secrets = %q, want %q", got, want)
}
if err := n.SecretSave(ctx, "github", " ghp_testfake\n"); err != nil {
@@ -34,7 +42,7 @@ func TestSecrets(t *testing.T) {
if err := n.SecretUse(ctx, "github", true); err != nil {
t.Fatal(names(err))
}
if got := list(); !strings.Contains(got, "github yes "+vm+"\n") {
if got := list(); !strings.Contains(got, "github yes "+vm+"\n") {
t.Errorf("Secrets = %q", got)
}
if err := n.SecretSave(ctx, "claude", "not-a-setup-token"); names(err) != "not_setup_token" {
@@ -59,7 +67,7 @@ func TestSecrets(t *testing.T) {
if err := n.SecretUse(ctx, "claude", false); names(err) != "secret_with_image vm="+vm {
t.Errorf("SecretUse(claude, false) = %v", names(err))
}
if got := list(); !strings.Contains(got, "claude no "+vm+"\n") {
if got := list(); !strings.Contains(got, "claude no "+vm+"\n") {
t.Errorf("Secrets = %q", got)
}
}
+7 -10
View File
@@ -2,7 +2,6 @@ package vm
import (
"context"
"io"
"os"
"path/filepath"
@@ -16,19 +15,17 @@ import (
// agent forwarding (sshagent.go).
type Settings struct{ *Env }
// GitProtect writes the folder's VM's .git protection to w: on, strict,
// off, or clone for a --clone VM, which mounts no .git.
func (e Settings) GitProtect(ctx context.Context, w io.Writer) error {
// GitProtect returns the folder's VM's .git protection: on, strict, off,
// or clone for a --clone VM, which mounts no .git.
func (e Settings) GitProtect(ctx context.Context) (string, error) {
t, err := e.folderVM(ctx, msg.NoVMGitProtect)
if err != nil {
return err
return "", err
}
mode := ModeClone
if !isClone(t.st) {
mode = e.Protector(t.f.Dir).Mode(t.st)
if isClone(t.st) {
return ModeClone, nil
}
_, err = io.WriteString(w, mode+"\n")
return err
return e.Protector(t.f.Dir).Mode(t.st), nil
}
// SetGitProtect turns the folder's VM's .git protection on, strict or
+74 -38
View File
@@ -3,7 +3,6 @@ package vm
import (
"bufio"
"context"
"io"
"io/fs"
"math"
"regexp"
@@ -200,72 +199,109 @@ func (e *Env) applySize(ctx context.Context, b backend.Backend, st *state.VM, in
return b.SetSize(ctx, st.Name(), edit)
}
// ShowSize writes to w the size of the folder's VM (cpus=4 memory=8GiB
// disk=100GiB), saying what changes at its next start; with global, the
// size new VMs get, a key=value line each, empty for the image's.
func (e Settings) ShowSize(ctx context.Context, w io.Writer, global bool) error {
// SizeShown is a size as devvm size shows it: the folder's VM's, or with
// -g the one new VMs get, 0 for what's the image's.
type SizeShown struct {
backend.Size
// DiskUsedGiB is what the VM's disk holds, to a tenth of a GiB, on a
// backend that sizes no disks (DiskMeasured).
DiskUsedGiB float64
DiskMeasured bool
// Pending is what changes at the VM's next start, 0 for what doesn't.
Pending backend.Size
Global bool
}
// Text is the size as devvm size prints it: cpus=4 memory=8GiB
// disk=100GiB for a VM, and a key=value line each for -g, empty for the
// image's.
func (s SizeShown) Text() string {
if s.Global {
var b strings.Builder
for _, kv := range [][2]string{{KeyCPUs, intText(s.CPUs)}, {KeyMemory, gibValue(s.MemoryGiB)}, {KeyDisk, gibValue(s.DiskGiB)}} {
b.WriteString(kv[0] + "=" + kv[1] + "\n")
}
return b.String()
}
line := SizeText(s.Size)
if s.DiskMeasured {
line += " " + KeyDiskUsed + "=" + strconv.FormatFloat(s.DiskUsedGiB, 'f', -1, 64) + "GiB"
}
return line + "\n"
}
// intText and gibValue write a size's numbers as the size file has them,
// "" for 0.
func intText(n int) string {
if n == 0 {
return ""
}
return strconv.Itoa(n)
}
func gibValue(n float64) string {
if n == 0 {
return ""
}
return strconv.FormatFloat(n, 'g', -1, 64)
}
// ShowSize returns the size of the folder's VM, saying what changes at
// its next start; with global, the size new VMs get.
func (e Settings) ShowSize(ctx context.Context, global bool) (SizeShown, error) {
if global {
def, err := e.defaultSize()
if err != nil {
return err
return SizeShown{}, err
}
var b strings.Builder
for _, kv := range def.fields() {
b.WriteString(kv[0] + "=" + kv[1] + "\n")
}
_, err = io.WriteString(w, b.String())
return err
return SizeShown{Size: def.Backend(), Global: true}, nil
}
t, err := e.folderVM(ctx, msg.NoVMSize)
if err != nil {
return err
return SizeShown{}, err
}
in, err := t.b.Inspect(ctx, t.f.Name)
if err != nil {
return err
return SizeShown{}, err
}
line := SizeText(in.Size)
s := SizeShown{Size: in.Size, Pending: pendingSize(t.st, in.Size)}
used, over, err := e.diskUsed(ctx, t.b, t.f.Name)
if err != nil {
return err
return SizeShown{}, err
}
if used != "" {
line += " " + KeyDiskUsed + "=" + used + "GiB"
}
if _, err := io.WriteString(w, line+"\n"); err != nil {
return err
if used >= 0 {
s.DiskUsedGiB, s.DiskMeasured = gib(used), true
}
if over != nil {
e.Warn(*over)
}
if p := pendingSize(t.st, in.Size); p != (backend.Size{}) {
e.Note(msg.SizePending(SizeText(p), t.f.Name))
if s.Pending != (backend.Size{}) {
e.Note(msg.SizePending(SizeText(s.Pending), t.f.Name))
}
return nil
return s, nil
}
// KeyDiskUsed is what devvm size shows of a VM whose backend sizes no
// disks (backend.DiskUser): what its disk holds, in GiB.
const KeyDiskUsed = "disk_used"
// diskUsed is what the VM's disk holds, in GiB, on a backend that sizes
// no disks, with the warning for one past the size VMs get elsewhere;
// "" on other backends.
func (e *Env) diskUsed(ctx context.Context, b backend.Backend, vm string) (string, *msg.M, error) {
// diskUsed is the bytes the VM's disk holds on a backend that sizes no
// disks, with the warning for one past the size VMs get elsewhere; -1 on
// other backends.
func (e *Env) diskUsed(ctx context.Context, b backend.Backend, vm string) (int64, *msg.M, error) {
du, ok := b.(backend.DiskUser)
if !ok {
return "", nil, nil
return -1, nil, nil
}
used, limit, err := du.DiskUsed(ctx, vm)
if err != nil {
return "", nil, err
return -1, nil, err
}
shown := gibText(used)
if limit > 0 && used > limit {
m := msg.DiskOver(b.Name(), gibText(limit), shown, vm)
return shown, &m, nil
m := msg.DiskOver(b.Name(), gibText(limit), gibText(used), vm)
return used, &m, nil
}
return shown, nil, nil
return used, nil, nil
}
// warnDisk warns when the VM's disk holds more than VMs get elsewhere, on
@@ -277,10 +313,10 @@ func (e *Env) warnDisk(ctx context.Context, b backend.Backend, vm string) {
}
}
// gibText is bytes in GiB, to a tenth.
func gibText(n int64) string {
return strconv.FormatFloat(math.Round(float64(n)/(1<<30)*10)/10, 'f', -1, 64)
}
// gib is bytes in GiB, to a tenth; gibText, written out.
func gib(n int64) float64 { return math.Round(float64(n)/(1<<30)*10) / 10 }
func gibText(n int64) string { return strconv.FormatFloat(gib(n), 'f', -1, 64) }
// SetSize changes the folder's VM's size to what s sets: at once when it's
// stopped, from its next start when it runs. A disk only grows. With
+14 -14
View File
@@ -132,8 +132,11 @@ func TestSizeText(t *testing.T) {
func TestSetSize(t *testing.T) {
e, f, _ := upEnv(t, allNative())
s := Settings{e}
var b strings.Builder
if err := s.ShowSize(t.Context(), &b, false); names(err) != "no_vm_size dir="+e.Dir {
shown := func(global bool) (string, error) {
got, err := s.ShowSize(t.Context(), global)
return got.Text(), err
}
if _, err := shown(false); names(err) != "no_vm_size dir="+e.Dir {
t.Errorf("no VM: %s", names(err))
}
st := existingVM(t, e, Options{Image: "base", NoNetworkPolicy: true})
@@ -187,9 +190,8 @@ func TestSetSize(t *testing.T) {
if len(set) != 1 || set[0] != (backend.Size{CPUs: 2, DiskGiB: 120}) {
t.Errorf("SetSize calls = %+v", set)
}
b.Reset()
if err := s.ShowSize(t.Context(), &b, false); err != nil || b.String() != "cpus=2 memory=8GiB disk=120GiB\n" {
t.Errorf("ShowSize = %q, %v", b.String(), names(err))
if got, err := shown(false); err != nil || got != "cpus=2 memory=8GiB disk=120GiB\n" {
t.Errorf("ShowSize = %q, %v", got, names(err))
}
if err := s.SetSize(t.Context(), Size{CPUs: "2", Memory: "3"}, true); err != nil {
@@ -201,9 +203,8 @@ func TestSetSize(t *testing.T) {
if err := s.SetSize(t.Context(), Size{CPUs: "16"}, true); names(err) != "too_many_cpus have=8 want=16" {
t.Errorf("-g --cpus 16: %s", names(err))
}
b.Reset()
if err := s.ShowSize(t.Context(), &b, true); err != nil || b.String() != "cpus=2\nmemory=4\ndisk=\n" {
t.Errorf("ShowSize -g = %q, %v", b.String(), names(err))
if got, err := shown(true); err != nil || got != "cpus=2\nmemory=4\ndisk=\n" {
t.Errorf("ShowSize -g = %q, %v", got, names(err))
}
}
@@ -237,14 +238,13 @@ func TestDiskUsed(t *testing.T) {
in := f.Instances[st.Name()]
in.Size = backend.Size{CPUs: 4, MemoryGiB: 8}
f.Instances[st.Name()] = in
var b strings.Builder
if err := (Settings{e}).ShowSize(t.Context(), &b, false); err != nil || b.String() != "cpus=4 memory=8GiB disk_used=1.5GiB\n" || len(warned) != 0 {
t.Errorf("ShowSize = %q, %v, warned %q", b.String(), names(err), warned)
s, err := (Settings{e}).ShowSize(t.Context(), false)
if err != nil || s.Text() != "cpus=4 memory=8GiB disk_used=1.5GiB\n" || !s.DiskMeasured || s.DiskUsedGiB != 1.5 || len(warned) != 0 {
t.Errorf("ShowSize = %+v, %v, warned %q", s, names(err), warned)
}
df.used = 101 << 30
b.Reset()
if err := (Settings{e}).ShowSize(t.Context(), &b, false); err != nil || b.String() != "cpus=4 memory=8GiB disk_used=101GiB\n" {
t.Errorf("ShowSize = %q, %v", b.String(), names(err))
if s, err := (Settings{e}).ShowSize(t.Context(), false); err != nil || s.Text() != "cpus=4 memory=8GiB disk_used=101GiB\n" {
t.Errorf("ShowSize = %q, %v", s.Text(), names(err))
}
if len(warned) != 1 || warned[0] != "disk_over backend=fake limit=100 used=101 vm="+st.Name() {
t.Errorf("warned %q", warned)
+11 -6
View File
@@ -22,15 +22,14 @@ func (e Settings) agentVM(ctx context.Context) (*found, error) {
return e.folderVM(ctx, msg.NoVMSSHAgent)
}
// SSHAgent writes the folder's VM's SSH agent forwarding to w: off, on
// (the user's agent) or devvm (devvm's own).
func (e Settings) SSHAgent(ctx context.Context, w io.Writer) error {
// SSHAgent returns the folder's VM's SSH agent forwarding: off, on (the
// user's agent) or devvm (devvm's own).
func (e Settings) SSHAgent(ctx context.Context) (string, error) {
t, err := e.agentVM(ctx)
if err != nil {
return err
return "", err
}
_, err = io.WriteString(w, sshagent.Mode(t.st)+"\n")
return err
return sshagent.Mode(t.st), nil
}
// SetSSHAgent changes the folder's VM's SSH agent forwarding, from its
@@ -104,6 +103,12 @@ func (e Settings) AgentKeys(ctx context.Context, w io.Writer) error {
return e.Agent.Keys(ctx, w)
}
// AgentKeyList returns the keys added to devvm's own SSH agent, each with
// whether the agent holds it, loading those it lacks first.
func (e Settings) AgentKeyList(ctx context.Context) ([]sshagent.ListedKey, error) {
return e.Agent.KeyList(ctx)
}
// checkAgent is for a VM that forwards the user's SSH agent: forwarding
// an empty one does nothing, so when the agent has no keys and ~/.ssh
// has one, it offers to load it.
+3 -5
View File
@@ -187,16 +187,14 @@ func TestSetSSHAgent(t *testing.T) {
agent := &agentCalls{}
e.Agent.Run = agent.run
s := Settings{e}
var b strings.Builder
if err := s.SSHAgent(t.Context(), &b); names(err) != "no_vm_ssh_agent dir="+e.Dir {
if _, err := s.SSHAgent(t.Context()); names(err) != "no_vm_ssh_agent dir="+e.Dir {
t.Errorf("no VM: %s", names(err))
}
st := existingVM(t, e, Options{Image: "base", NoNetworkPolicy: true})
shown := func(want string) {
t.Helper()
b.Reset()
if err := s.SSHAgent(t.Context(), &b); err != nil || b.String() != want+"\n" {
t.Errorf("SSHAgent = %q, %v; want %s", b.String(), names(err), want)
if mode, err := s.SSHAgent(t.Context()); err != nil || mode != want {
t.Errorf("SSHAgent = %q, %v; want %s", mode, names(err), want)
}
}
shown("off")
+4
View File
@@ -78,6 +78,10 @@ other = "{{.flag}} and {{.other}} can't be given together."
description = "reason is why, in English"
other = "Writing the command's output failed: {{.reason}}."
[json_shows_only]
description = "command is the command run, such as devvm network"
other = "{{.command}} --json only shows, so it takes no value. Run it without --json to change the setting."
[log_details]
other = "(details: {{.file}})"
+14 -11
View File
@@ -1,6 +1,7 @@
# doctor: what the backend new VMs get needs on this machine and how to
# get what's missing, each backend's features, and whether Docker is
# there. --fixes prints only what's missing, for scripts.
# there. --json prints what it found as JSON, for scripts, and nothing
# else.
env DEVVM_MESSAGES=names
env ALL=$PATH
chmod 0755 brew/brew
@@ -24,8 +25,9 @@ stdout '^doctor_ok backend=lima version=\S+\n\z'
! stderr .
stub_calls
stdout '^limactl --version\n\z'
exec devvm doctor --fixes
! stdout .
exec devvm doctor --json
stdout '^{\n "version": 1,\n "backend": "lima",\n "problems": \[\],\n "warnings": \[\],\n "docker": true,\n'
stdout '^ "egress-proxy": "emulated",$'
! stderr .
# Another backend, or one devvm doesn't have.
@@ -41,8 +43,9 @@ stdout '^FEATURE +DOCKER +LIMA +SMOLVM\n'
stdout '^docker_missing\n'
! stdout doctor_ok
stderr '^devvm: lima_missing$'
exec devvm doctor --fixes
stdout '^lima\t\tlima_missing\n'
exec devvm doctor --json
stdout '^ "key": "lima",\n "fix": null,\n "message": "lima_missing"\n'
stdout '^ "docker": false,$'
! stderr .
# Every command that needs the backend stops at the first problem.
@@ -56,13 +59,13 @@ cd ..
# With Homebrew, its command.
env PATH=$WORK/brew${:}$WORK/qemu${:}$DEVVM_BIN
exec devvm doctor --fixes
stdout '^lima\tbrew install lima\tlima_missing_fix fix=brew install lima\n'
exec devvm doctor --json
stdout '^ "key": "lima",\n "fix": "brew install lima",\n "message": "lima_missing_fix fix=brew install lima"\n'
# A limactl that doesn't run, as one built for another processor.
env PATH=$WORK/broken${:}$WORK/brew${:}$WORK/qemu${:}$DEVVM_BIN
exec devvm doctor --fixes
stdout '^lima\tbrew reinstall lima\tlima_broken_fix fix=brew reinstall lima\n'
exec devvm doctor --json
stdout '^ "key": "lima",\n "fix": "brew reinstall lima",\n "message": "lima_broken_fix fix=brew reinstall lima"\n'
! exec devvm doctor
stderr '^devvm: lima_broken_fix fix=brew reinstall lima$'
@@ -75,8 +78,8 @@ stderr '^devvm: lima_broken_fix fix=brew reinstall lima\ndevvm: lima_global_conf
env PATH=$ALL
! exec devvm doctor
stderr '^devvm: lima_global_config files=\S+/_config/default.yaml$'
exec devvm doctor --fixes
stdout '^lima-config\t\tlima_global_config files=\S+/_config/default.yaml\n\z'
exec devvm doctor --json
stdout '^ "problems": \[\n {\n "key": "lima-config",\n "fix": null,\n "message": "lima_global_config files=\S+/_config/default.yaml"\n }\n \],$'
-- brew/brew --
#!/bin/sh
+4
View File
@@ -47,6 +47,8 @@ exec devvm --no-network-policy --no-git-protect go
stderr '^devvm: no_subcommand command=devvm tools commands=add, rm, update given=now$'
exec devvm tools
stdout '^TOOL +VERSION +NEWER +BUILT\ngo +\S+ +- +-\n\z'
exec devvm tools --json
stdout '\A{\n "version": 1,\n "tools": \[\n {\n "tool": "go",\n "version": "\S+"\n }\n \]\n}\n\z'
exec devvm tools update
stdout '^==> checking_tools$'
stdout '^==> tools_newest vm=devvm-api-[0-9a-f]{14}$'
@@ -71,6 +73,8 @@ exec devvm
stderr '^devvm: newer_tools tools=go 9\.9\.9$'
exec devvm tools
stdout '^go +1\.0\.0 +9\.9\.9 +yes$'
exec devvm tools --json
stdout '\A{\n "version": 1,\n "tools": \[\n {\n "tool": "go",\n "version": "1\.0\.0",\n "newer": "9\.9\.9",\n "newer_built": true\n }\n \]\n}\n\z'
# tools rm: the tools leave its name and list, the rest stays; what it
# lacks is refused, and so is a layer. Names are separate words.
+4
View File
@@ -44,6 +44,10 @@ stdout '^chflags -R -P uchg /\S*/web/\.git/hooks$'
! stdout 'limactl (start|edit)'
exec devvm git-protect
stdout '\Astrict\n\z'
exec devvm git-protect --json
stdout '\A{\n "version": 1,\n "mode": "strict"\n}\n\z'
! exec devvm git-protect --json off
stderr '^devvm: json_shows_only command=devvm git-protect$'
exec sh -c 'cat "$VMS"/devvm-web-*'
stdout '^git_protect=strict$'
stdout '^git_inode=[0-9]+$'
+4
View File
@@ -17,6 +17,8 @@ stderr '^devvm: no_subcommand command=devvm history commands=export given=now$'
# None yet: the header alone, no VM needed.
exec devvm history
stdout '^FILE +VM +FOLDER +DATE +SIZE\n\z'
exec devvm history --json
stdout '\A{\n "version": 1,\n "exports": \[\]\n}\n\z'
exec devvm --no-network-policy base
exec sh -c 'limactl stop "$(basename "$VMS"/devvm-web-*)"'
@@ -58,4 +60,6 @@ stdout '^FILE +VM +FOLDER +DATE +SIZE\n'
stdout '^\S*/exports/devvm-old-12345612345612-20200101-000000\.tar\.gz +devvm-old-12345612345612 +- +2020-01-01 00:00 +\S+\n\S*/exports/devvm-web-'
stdout '^\S*/exports/devvm-web-[0-9a-f]{14}-[0-9]{8}-[0-9]{6}\.tar\.gz +devvm-web-[0-9a-f]{14} +\S*/web +[0-9-]+ [0-9:]+ +\S+$'
! stdout notes
exec devvm history --json
stdout '^ "file": "\S*/exports/devvm-old-12345612345612-20200101-000000\.tar\.gz",\n "vm": "devvm-old-12345612345612",\n "folder": "",\n "date": "2020-01-01T00:00:00[-+Z][0-9:]*",\n "size": \d+\n'
! stdout out/h
+8
View File
@@ -49,6 +49,14 @@ stderr '^images_total size=\S+$'
stdout '^node +- '
stub_calls
! stdout mise
# --json: the same as fields, sizes in bytes; the notes stay on stderr.
exec devvm images --json
stdout '^{\n "version": 1,\n "images": \[\n {\n "name": "base",\n "from": "ubuntu 26\.04 \(\d{8}\)",\n "digest": "sha256:[0-9a-f]{64}",\n "key": "[0-9a-f]{12}",\n "state": "current",\n "size": \d+,\n "sized": true,\n "backend": "lima"\n'
stdout '^ "name": "go",\n "tool": "go",\n "version": "1\.20\.0",\n "built": true,\n "backend": "smolvm",\n "libc": "musl",\n "size": \d+,\n "vms": 1,\n "state": "in use"\n'
stdout '^ "name": "go",\n "tool": "go",\n "version": "1\.27\.2",\n "built": false,\n "size": 0,\n "vms": 0,\n "state": "not built"\n'
stdout '^ "total": \d+,\n "unused_tools": \d+,\n "nix_cache": {\n "files": 0,\n "size": 0,\n "cap": \d+\n }\n}\n\z'
stderr '^images_total size=\S+$'
! stdout '^IMAGE'
# images rm: by key (an unfinished build), or by name; nothing else.
# A name is its image as it is now: foo is current again.
+82 -13
View File
@@ -105,30 +105,31 @@ stderr '^ remove it, or put \S+/prefix/bin before its folder in PATH$'
! stderr 'isn''t on your PATH'
! exists other-ran
# The fixes devvm suggests run once allowed; what it can't fix is shown.
exec bash deps.sh yes 'qemu\tsudo apt-get install -y qemu-system-arm\tQEMU not found\nkvm\t\t/dev/kvm not found: turn on virtualization\nlima\tbrew install lima\tLima not found\n'
stdout '^ /dev/kvm not found: turn on virtualization$'
# The fixes devvm suggests run once allowed; what it can't fix is shown,
# its escapes read.
exec bash deps.sh yes fixes.json
stdout '^ /dev/kvm not found: turn on "virtualization" \\ in the firmware$'
stdout '^checked$'
cmp ran ran-fixes.want
# After joining the kvm group: log in again, no check.
exec bash deps.sh yes 'kvm-access\tsudo usermod -aG kvm me\tno access to /dev/kvm\n'
exec bash deps.sh yes kvm.json
stdout 'Log out and back in'
! stdout '^checked$'
cmp ran ran-kvm.want
# Nothing runs without a yes.
exec bash deps.sh no 'kvm-access\tsudo usermod -aG kvm me\tno access to /dev/kvm\n'
exec bash deps.sh no kvm.json
stdout '^ skipped: sudo usermod -aG kvm me$'
! exists ran
# No Lima and no Homebrew: Lima's release, once allowed.
exec bash deps.sh lima 'lima\t\tLima not found\n'
exec bash deps.sh lima lima.json
stdout '^==> installed Lima 2.3.0: '
exists prefix/bin/limactl
# Nothing missing, nothing asked.
exec bash deps.sh asked ''
exec bash deps.sh asked none.json
cmp stdout deps-none.want
# The whole script: options, a release, the PATH hint.
@@ -393,14 +394,14 @@ mkdir -p "$WORK/links"
ln -s "$prefix/lib/devvm/0.1.0/devvm" "$WORK/links/devvm"
echo "linked: $(PATH="$WORK/links:$prefix/bin:$PATH" path_hint)"
-- deps.sh --
# deps.sh ANSWER LINES: install_deps with a devvm whose doctor --fixes
# prints LINES (printf's format) and whose doctor prints "checked"; the
# brew and sudo in bin/ log to $WORK/ran. ANSWER: yes (--yes), no (every
# question answered no), lima (yes, with a Lima release to install), asked
# (a question prints "asked").
# deps.sh ANSWER FILE: install_deps with a devvm whose doctor --json
# prints $WORK/FILE and whose doctor prints "checked"; the brew and sudo
# in bin/ log to $WORK/ran. ANSWER: yes (--yes), no (every question
# answered no), lima (yes, with a Lima release to install), asked (a
# question prints "asked").
. "$WORK/lib.sh"
mkdir -p "$WORK/fake"
printf '#!/bin/sh\n[ "$2" = --fixes ] && printf "%s" || echo checked\n' "$2" > "$WORK/fake/devvm"
printf '#!/bin/sh\n[ "$2" = --json ] && cat "$WORK/%s" || echo checked\n' "$2" > "$WORK/fake/devvm"
chmod 755 "$WORK/fake/devvm"
case $1 in
yes) yes=true ;;
@@ -409,6 +410,74 @@ case $1 in
asked) ask() { echo asked; } ;;
esac
install_deps "$WORK/fake/devvm"
-- fixes.json --
{
"version": 1,
"backend": "lima",
"problems": [
{
"key": "qemu",
"fix": "sudo apt-get install -y qemu-system-arm",
"message": "QEMU not found"
},
{
"key": "kvm",
"fix": null,
"message": "/dev/kvm not found: turn on \"virtualization\" \\ in the firmware"
},
{
"key": "lima",
"fix": "brew install lima",
"message": "Lima not found,"
}
],
"warnings": [],
"docker": false,
"features": {
"lima": {
"ssh": "native"
}
}
}
-- kvm.json --
{
"version": 1,
"backend": "lima",
"problems": [
{
"key": "kvm-access",
"fix": "sudo usermod -aG kvm me",
"message": "no access to /dev/kvm"
}
],
"warnings": [],
"docker": false,
"features": {}
}
-- lima.json --
{
"version": 1,
"backend": "lima",
"problems": [
{
"key": "lima",
"fix": null,
"message": "Lima not found"
}
],
"warnings": [],
"docker": false,
"features": {}
}
-- none.json --
{
"version": 1,
"backend": "lima",
"problems": [],
"warnings": [],
"docker": false,
"features": {}
}
-- deps-none.want --
==> everything devvm needs is installed
checked
+14
View File
@@ -53,6 +53,13 @@ stdout '^devvm-half-0123456789abcd +Stopped +- +- +- +lima +-\n'
! stdout devvm-tools-build
# Sorted by name.
stdout '\ndevvm-cl-.*\ndevvm-from-.*\ndevvm-half-.*\ndevvm-img-foo-.*\ndevvm-net-'
# --json: the same, the image and what its base started from apart, ""
# for what a VM lacks, and nothing else on stdout.
exec devvm ls --json
stdout '^{\n "version": 1,\n "vms": \[\n'
stdout '^ "name": "devvm-from-0123456789abcd",\n "status": "Running",\n "image": "base",\n "from": "node:24",\n "git": "on",\n "net": "off",\n "backend": "lima",\n "folder": "/p/from"\n'
stdout '^ "name": "devvm-half-0123456789abcd",\n "status": "Stopped",\n "image": "",\n "git": "",\n'
! stdout '^NAME'
# Lima can't list (not installed): fails, as a VM's state names it; with
# none, the header alone.
@@ -63,7 +70,14 @@ stderr '^devvm: lima_missing$'
rm $VMS
exec devvm ls
cmp stdout $WORK/header.txt
exec devvm ls --json
cmp stdout $WORK/none.json
-- none.json --
{
"version": 1,
"vms": []
}
-- header.txt --
NAME STATUS IMAGE GIT NET BACKEND FOLDER
-- clone.state --
+2
View File
@@ -180,6 +180,8 @@ exec cat $XDG_CONFIG_HOME/devvm/network
stdout '\Aoff\n\z'
exec devvm network -g
stdout '\Aoff\n\z'
exec devvm network -g --json
stdout '\A{\n "version": 1,\n "policy": "off"\n}\n\z'
mkdir $WORK/offsaved
cd $WORK/offsaved
exec devvm --no-git-protect base
+13
View File
@@ -14,6 +14,9 @@ exec devvm --network-policy --no-git-protect base
exec devvm network log
stdout '^==> log_empty vm=devvm-net-[0-9a-f]{14}$'
! stderr .
exec devvm network log --json
stdout '\A{\n "version": 1,\n "events": \[\]\n}\n\z'
! stderr .
# Allowed and blocked connections and requests, oldest first, the last 50
# or the last N.
@@ -29,12 +32,22 @@ exec devvm network log --lines 0
stderr '^devvm: flag_bad_value flag=--lines form=N value=x$'
! exec devvm network log -n -1
stderr '^devvm: flag_bad_value flag=--lines form=N value=-1$'
# --json: the events as the proxy logged them, without the VM's name;
# never followed.
exec devvm network log --json -n 3
stdout '\A{\n "version": 1,\n "events": \[\n {\n "time": "2026-10-09T10:00:08Z",\n "event": "tunnel",\n "host": "fd00::1",\n "port": 22,\n "method": "CONNECT",\n "rule": "\[fd00::1\]:22"\n },\n'
! stdout '"vm"'
! exec devvm network log --json -f
stderr '^devvm: flags_exclusive flag=--(json|follow) other=--(json|follow)$'
# The blocks by host and port, by when last blocked, with the command
# that allows each: only for a host name or address, and never for a
# request refused whatever the allowlist says.
exec devvm network log --blocked
cmp stdout $WORK/blocked.txt
exec devvm network log --blocked --json
stdout '\A{\n "version": 1,\n "blocked": \[\n {\n "last": "2026-10-09T10:00:07Z",\n "count": 1,\n "host": "api.github.com",\n "port": 443\n },\n'
stdout '^ "last": "2026-10-09T10:01:00Z",\n "count": 2,\n "host": "a.test",\n "port": 443,\n "allow": "a.test"\n'
! exec devvm network log --blocked -f
stderr '^devvm: flags_exclusive flag=--blocked other=--follow$'
+7
View File
@@ -77,6 +77,13 @@ stdout '^ github\.com$'
stdout '^# \S*/config/devvm/policy\n \*\.corp\.test\n# \S*/vms/devvm-net-[0-9a-f]{14}\.policy\n !bad\.example\.com\n example\.com\n'
! stdout mine
! stderr .
# --json: the same, each file with its rules; it only shows.
exec devvm network --json
stdout '\A{\n "version": 1,\n "policy": "(on|unenforced)",\n "allowlist": \[\n {\n "file": "\S*/layers/base\.policy",\n "rules": \[\n'
stdout '^ "file": "\S*/vms/devvm-net-[0-9a-f]{14}\.policy",\n "rules": \[\n "!bad\.example\.com",\n "example\.com"\n \]\n'
! stderr .
! exec devvm network --json off
stderr '^devvm: json_shows_only command=devvm network$'
# A VM without network policy: devvm network shows it off, with its
# rules, and changing them says they don't apply.
+6
View File
@@ -36,6 +36,12 @@ exec sh -c 'cat "$CFG/ports"'
stdout '\A3000-3999,5173\n\z'
exec devvm ports -g
stdout '\A3000-3999,5173\n\z'
exec devvm ports -g --json
stdout '\A{\n "version": 1,\n "ports": "3000-3999,5173"\n}\n\z'
! exec devvm ports -g --json all
stderr '^devvm: json_shows_only command=devvm ports$'
! exec devvm ports add --json 1
stderr '^devvm: flag_unknown command=devvm ports add flag=--json$'
! exec devvm ports -g add all
stderr '^devvm: ports_list_needed value="all"$'
! exec devvm ports -g rm none
+16
View File
@@ -45,6 +45,10 @@ exec cat $XDG_CONFIG_HOME/devvm/retention
cmp stdout want-retention
exec devvm retention
cmp stdout want-shown
exec devvm retention --json
cmp stdout want-shown.json
! exec devvm retention --json history.count=5
stderr '^devvm: json_shows_only command=devvm retention$'
! exec devvm retention history.count=x
cmp $XDG_CONFIG_HOME/devvm/retention want-retention
exec devvm space
@@ -118,6 +122,18 @@ history.count=off
tools.unused-age=1d
orphans.age=off
nix-cache.size=off
-- want-shown.json --
{
"version": 1,
"settings": {
"history.age": "30d",
"history.count": "off",
"logs.runs": "off",
"nix-cache.size": "off",
"orphans.age": "off",
"tools.unused-age": "1d"
}
}
-- want-all-off --
logs.runs=off
history.age=off
+6
View File
@@ -32,6 +32,10 @@ stdout '^sk-ant-oat01-testfake$'
exec devvm secret
stdout '^NAME +SAVED +USED BY$'
stdout '^claude +yes +-$'
# --json: saved or not, never the token.
exec devvm secret --json
stdout '\A{\n "version": 1,\n "secrets": \[\n {\n "name": "claude",\n "saved": true,\n "used_by": \[\]\n },\n'
! stdout 'sk-ant'
env CLAUDE_CODE_OAUTH_TOKEN=
# Only devvm's own names: never a path.
@@ -119,6 +123,8 @@ exec sh -c 'cat "$VMS"/devvm-off-*'
stdout '^secrets=github$'
exec devvm secret
stdout '^github +no +devvm-off-[0-9a-f]{14}$'
exec devvm secret --json
stdout '^ "name": "github",\n "saved": false,\n "used_by": \[\n "devvm-off-[0-9a-f]{14}"\n \]\n'
exec devvm secret unuse github
stdout '^==> secret_unused secret=github vm=devvm-off-[0-9a-f]{14}$'
stderr '^secret_unuse_copied secret=github vm=devvm-off-[0-9a-f]{14}$'
+11
View File
@@ -32,6 +32,11 @@ exec devvm size -g --memory=2.5GiB
stdout '^==> size_defaults size=cpus=2 memory=2\.5GiB$'
exec devvm size -g
cmp stdout $WORK/set
# --json: what's unset left out; it only shows.
exec devvm size -g --json
stdout '\A{\n "version": 1,\n "cpus": 2,\n "memory_gib": 2\.5\n}\n\z'
! exec devvm size -g --json --cpus 4
stderr '^devvm: json_shows_only command=devvm size$'
exec sh -c 'cat "$CFG/size"'
stdout '^cpus=2$'
stdout '^memory=2\.5$'
@@ -56,6 +61,9 @@ exec sh -c 'echo "2 8589934592 107374182400" > "$STUB_DIR/size-$(basename "$VMS"
exec devvm size
stdout '\Acpus=2 memory=8GiB disk=100GiB\n\z'
! stderr .
exec devvm size --json
stdout '\A{\n "version": 1,\n "cpus": 2,\n "memory_gib": 8,\n "disk_gib": 100\n}\n\z'
! stderr .
exec sh -c ': > "$STUB_LOG"'
exec devvm size --cpus 1 --memory 3
stderr '^devvm: size_next_start vm=devvm-web-[0-9a-f]{14}$'
@@ -68,6 +76,9 @@ stdout '^memory=3$'
exec devvm size
stdout '\Acpus=2 memory=8GiB disk=100GiB\n\z'
stderr '^size_pending size=cpus=1 memory=3GiB vm=devvm-web-[0-9a-f]{14}$'
exec devvm size --json
stdout '^ "disk_gib": 100,\n "pending": {\n "cpus": 1,\n "memory_gib": 3\n }\n}\n\z'
stderr '^size_pending '
# Back to what it has: nothing waits.
exec devvm size --cpus 2 --memory 8
stdout '^==> vm_size size=cpus=2 memory=8GiB disk=100GiB vm=devvm-web-[0-9a-f]{14}$'
+1
View File
@@ -49,6 +49,7 @@ stub_calls
# --json, for scripts.
exec devvm space --json
stdout '^{\n "version": 1,\n "devvm": \[\n'
stdout '"what": "leftover state"'
stdout '"kept": "only copy"'
stdout '"total": \d+'
+6
View File
@@ -35,6 +35,8 @@ stdout '^ ForwardAgent no$'
! stdout IdentityAgent
exec devvm ssh-agent
stdout '\Aoff\n\z'
exec devvm ssh-agent --json
stdout '\A{\n "version": 1,\n "mode": "off",\n "keys": \[\]\n}\n\z'
exec devvm --ssh-agent
stderr '^devvm: ssh_agent_flag_ignored$'
@@ -97,6 +99,10 @@ stderr '^devvm: agent_key_mounted key=\S*/web/key vm=devvm-web-[0-9a-f]{14}$'
# holds and those added to it.
exec devvm ssh-agent
stdout '\Aon\n256 SHA256:fp-deploy deploy \(ED25519\)\n\S*/keys/deploy: SHA256:fp-deploy lifetime=12h\n\z'
exec devvm ssh-agent --json
stdout '\A{\n "version": 1,\n "mode": "on",\n "keys": \[\n {\n "file": "\S*/keys/deploy",\n "fingerprint": "SHA256:fp-deploy",\n "confirm": false,\n "lifetime": "12h",\n "loaded": true\n }\n \]\n}\n\z'
! exec devvm ssh-agent --json off
stderr '^devvm: json_shows_only command=devvm ssh-agent$'
# devvm ssh-agent devvm on the running VM: from its next start. Until
# then devvm's connections and its ssh config entry carry the agent it
+5 -3
View File
@@ -639,7 +639,7 @@ fi
if want images; then
section "images"
check "devvm doctor finds everything it needs on this host" bash -c "'$D' doctor </dev/null >'$work/last.log' 2>&1 &&
[[ -z \$('$D' doctor --fixes </dev/null) ]]"
'$D' doctor --json </dev/null | grep -qxF ' \"problems\": [],'"
# base stays cached between runs (--clean deletes it); the fixture layers' images are this run's.
check "build base" quiet env DEVVM_MESSAGES=names "$D" build base
# Its key: the build's, else the newest base from Ubuntu's image (from's bases are cached too).
@@ -838,6 +838,8 @@ check "it gets --cpus, --memory and --disk" in_vm "$vm" \
check "devvm size shows it" bash -c "cd '$p' && [[ \$('$D' size 2>&1) == 'cpus=2 memory=3GiB disk=120GiB' ]]"
check "ls lists it, and no image" bash -c "'$D' ls >'$work/ls.out' 2>&1 &&
grep -Eq '^$vm +Running +base +(on|off) +off +lima +$p\$' '$work/ls.out' && ! grep -q '^devvm-img-' '$work/ls.out'"
check "ls --json and size --json show it" bash -c "'$D' ls --json 2>/dev/null | grep -qxF ' \"name\": \"$vm\",' &&
cd '$p' && '$D' size --json 2>/dev/null | grep -qxF ' \"disk_gib\": 120'"
check "the folder is mounted read-write" bash -c "limactl shell --workdir / $vm bash -c 'echo from-vm > $p/vm.txt' </dev/null && grep -qx from-vm '$p/vm.txt'"
# On Linux hosts the mount is 9p, whose subfolders' events reach no watcher, even the VM's own.
if [[ "$(uname -s)" == Darwin ]]; then
@@ -1934,7 +1936,7 @@ check "the shared tools resolve to upstream's newest" quiet "$D" _refresh-tools
section "smolvm: images"
check "devvm doctor finds everything smolvm needs" bash -c "'$D' doctor --backend smolvm </dev/null >'$work/last.log' 2>&1 &&
[[ -z \$('$D' doctor --backend smolvm --fixes </dev/null) ]]"
'$D' doctor --backend smolvm --json </dev/null | grep -qxF ' \"problems\": [],'"
check "build base" quiet env DEVVM_MESSAGES=names "$D" "${S[@]}" build base
kb=$(sed -n 's/^==> building_image image=base key=\([0-9a-f]*\)$/\1/p' "$work/last.log")
# A cached base: the pack recorded as base, not --from another image (the Alpine checks' bases).
@@ -3886,7 +3888,7 @@ docker_linux() {
check "devvm doctor finds everything, an engine of this machine's, builds confined, network policy emulated" bash -c "
DEVVM_MESSAGES=names '$D' doctor --backend docker </dev/null >'$work/last.log' 2>&1 &&
grep -qE '^docker_engine_linux version=' '$work/last.log' && grep -qE '^build-confinement +native ' '$work/last.log' &&
grep -qE '^egress-proxy +emulated ' '$work/last.log' && [[ -z \$('$D' doctor --backend docker --fixes </dev/null) ]]"
grep -qE '^egress-proxy +emulated ' '$work/last.log' && '$D' doctor --backend docker --json </dev/null | grep -qxF ' \"problems\": [],'"
check "build base" quiet env DEVVM_MESSAGES=names "$D" "${B[@]}" build base
kb=$(sed -n 's/^==> building_image image=base key=\([0-9a-f]*\)$/\1/p' "$work/last.log")
[[ -n $kb ]] || kb=$(for k in $(keys_of base); do grep -qx from= "$images/$k" && d_img "devvm-$dns:$k" && echo "$k"; done | head -1)