mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
feat(msg): generated typed messages with go-i18n
locales/en.toml holds every message; go generate ./internal/msg writes one typed function per message. internal/msg renders them through a go-i18n bundle in the user's language (LC_ALL, LC_MESSAGES, LANG), with names mode (DEVVM_MESSAGES=names) and doc links. devvm _msg prints a message's text. Tests check the generated file is current, every message renders and is called, and every doc link exists; lint runs the doc link check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
19 files changed
+1250
-21
No files matched your search
@@ -38,6 +38,8 @@ linters:
|
||||
- github.com/spf13/cobra
|
||||
- github.com/spf13/pflag
|
||||
- github.com/nicksnyder/go-i18n/v2
|
||||
# go-i18n's own TOML parser, for locales/*.toml.
|
||||
- github.com/BurntSushi/toml
|
||||
- golang.org/x/text
|
||||
- golang.org/x/term
|
||||
- golang.org/x/sys
|
||||
@@ -52,6 +54,7 @@ linters:
|
||||
- github.com/spf13/cobra
|
||||
- github.com/spf13/pflag
|
||||
- github.com/nicksnyder/go-i18n/v2
|
||||
- github.com/BurntSushi/toml
|
||||
- golang.org/x/text
|
||||
- golang.org/x/term
|
||||
- golang.org/x/sys
|
||||
|
||||
@@ -7,9 +7,11 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch
|
||||
| Path | What |
|
||||
| --- | --- |
|
||||
| `cmd/devvm/main.go` | the entry point: runs the root command and exits with its code. The only place that calls `os.Exit` |
|
||||
| `internal/cli/` | Cobra commands, one file each (only the empty root so far), and `script_test.go`, the testscript runner |
|
||||
| `internal/cli/` | Cobra commands, one file each (the empty root and the hidden `_msg` so far), and `script_test.go`, the testscript runner |
|
||||
| `internal/msg/` | messages: `messages_gen.go` (one function per message, generated), `M` (text in the user's language, names mode, doc links, `FromArgs` for `_msg`), the go-i18n bundle. `gen/` is the generator (`go generate ./internal/msg`); the tests check the generated file is current, every message renders, every one is called and every doc link exists |
|
||||
| `locales/` | `en.toml`, every message (other languages join as `<lang>.toml`), embedded by `locales.go` |
|
||||
| `internal/paths/` | names every folder and file devvm uses: the folder holding the binary (after following links), and `Dirs` (XDG data and config folders, devvm's Lima home, `DEVVM_LIMA_HOME`) with a method per state folder and config file |
|
||||
| `internal/state/` | reads and writes state files atomically, with `CorruptError` for unreadable ones: VM state (key=value, `backend=` included), image records and `--from` digests, and the config files (`size`, `ports`, `base-features`, `agent-keys`) |
|
||||
| `internal/state/` | reads and writes state files atomically, with `CorruptError` for unreadable ones: VM state (key=value, `backend=` included), image records and `--from` digests, and the config files (`size`, `ports`, `base-features`, `agent-keys`). Its errors aren't messages yet |
|
||||
| `testdata/script/*.txtar` | CLI tests (testscript) |
|
||||
| `testdata/stubs/` | stand-ins for host commands, first on `PATH` in tests; they log calls to `$STUB_LOG`. So far `uname` and `sw_vers` |
|
||||
| `docs/` | the docs site (Hugo + Hextra): `hugo.yaml`, `content/_index.md`, `content/docs/*.md`. Pages arrive with the behavior they describe |
|
||||
@@ -19,13 +21,13 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch
|
||||
| `.github/workflows/` | `ci.yml` (lint and test on macOS and Linux), `docs.yml` (the site on GitHub Pages) |
|
||||
| `.agents/skills/security-audit/`, `skills-lock.json` | the security-audit skill, used by the backend reviews |
|
||||
|
||||
Not there yet, and where it goes when its task arrives: `internal/ui` (say/info/note/warn/die/ask/confirm, tty, spinner, run logs, interrupts, the cleanup stack), `internal/msg` (generated message functions, the go-i18n bundle, doc links) with `locales/en.toml`, `internal/{project,image,tools,gitprotect,netpolicy,secrets,vm}`, `internal/backend/` (interface, `Caps`, registry; `lima/`, `smolvm/`, `docker/`), `internal/proxy` (stdlib only), `internal/platform` (build-tagged OS code). The in-VM scripts (`base.yaml`, `layers/`, `features/`, `tools/`, `guest/`, `oci/`) sit next to the binary; `tests/e2e.sh` drives real VMs; `install.sh`, `scripts/` and `packaging/` handle releases.
|
||||
Not there yet, and where it goes when its task arrives: `internal/ui` (say/info/note/warn/die/ask/confirm, tty, spinner, run logs, interrupts, the cleanup stack), `internal/{project,image,tools,gitprotect,netpolicy,secrets,vm}`, `internal/backend/` (interface, `Caps`, registry; `lima/`, `smolvm/`, `docker/`), `internal/proxy` (stdlib only), `internal/platform` (build-tagged OS code). The in-VM scripts (`base.yaml`, `layers/`, `features/`, `tools/`, `guest/`, `oci/`) sit next to the binary; `tests/e2e.sh` drives real VMs; `install.sh`, `scripts/` and `packaging/` handle releases.
|
||||
|
||||
## Tasks
|
||||
|
||||
`mise run <task>`:
|
||||
- `fmt`: gofumpt and goimports, through golangci-lint.
|
||||
- `lint`: golangci-lint, shellcheck on every shell script, then markdownlint-cli2, Vale and `lychee --offline` on `docs/content`. The message-link check joins it with `internal/msg`.
|
||||
- `lint`: golangci-lint, shellcheck on every shell script, then markdownlint-cli2, Vale and `lychee --offline` on `docs/content`, then the message-link check (`TestDocLinks` in `internal/msg`: every `doc =` in `locales/en.toml` is a page and heading).
|
||||
- `test`: `gotestsum -- -race -cover ./...`, including the testscript suites. Needs a C compiler for `-race`.
|
||||
- `vuln`: govulncheck.
|
||||
- `docs`: serves the site (`http://localhost:1313/devvm/`). Regenerating the CLI reference joins it once commands exist.
|
||||
@@ -49,12 +51,12 @@ Not there yet, and where it goes when its task arrives: `internal/ui` (say/info/
|
||||
|
||||
## Go conventions
|
||||
|
||||
`internal/ui` and `internal/msg` don't exist yet; these are the rules they're built to.
|
||||
`internal/ui` doesn't exist yet; these are the rules it's built to.
|
||||
|
||||
- **Only `internal/ui` prints.** forbidigo bans `fmt.Print*` and `os.Stdout`/`os.Stderr` elsewhere, and `os.Exit` outside `cmd/devvm`.
|
||||
- **Fail with `ui.Die(msg.X(...))`:** it panics with an exit error; `main` recovers it, runs the cleanup stack and exits 1. Ctrl+C (INT/TERM/HUP) cancels the root context and runs the same cleanups. Anything that leaves something behind on failure (a build VM, a temp file) registers its cleanup.
|
||||
- **OS-specific code goes behind build tags** in `internal/platform` (`*_darwin.go`, `*_linux.go`, `*_other.go`), so Windows can follow.
|
||||
- **Dependencies:** the depguard allowlist in `.golangci.yml` (cobra, pflag, go-i18n, x/text, x/term, x/sys; go-internal in tests). `internal/proxy` is stdlib only. Adding one is a decision: ask.
|
||||
- **Dependencies:** the depguard allowlist in `.golangci.yml` (cobra, pflag, go-i18n and its TOML parser BurntSushi/toml, x/text, x/term, x/sys; go-internal in tests). `internal/proxy` is stdlib only. Adding one is a decision: ask.
|
||||
- **External tools are called as commands, never linked** (`limactl`, `smolvm`, `docker`, `security`, `git`, `chflags`, `sandbox-exec`, `qemu-img`, `ssh-keygen`). Prefer the standard library to shelling out (`net/http`, `crypto/sha256`, `encoding/json`, `text/template`, `net.Dial`). Strings sent into a backend's shell are quoted with `shq()`.
|
||||
- **A command exists only once it's ported.** Cobra's docs generator writes `docs/content/docs/cli/`; a test fails when it's stale.
|
||||
- `CGO_ENABLED=0` for builds.
|
||||
@@ -69,7 +71,7 @@ Not there yet, and where it goes when its task arrives: `internal/ui` (say/info/
|
||||
## Messages
|
||||
|
||||
- **Succinct and direct.** Say what is being done, or what failed and what to do. No explanations; link a docs page when more is needed.
|
||||
- **Every message lives in `locales/en.toml`** and is called through its generated function (`msg.NoVM(dir)`); run `go generate ./internal/msg` after editing it. Template fields are snake_case (`{{.vm_name}}`); a `doc = "page#anchor"` adds the link. Never build prose with `fmt` outside `msg`.
|
||||
- **Every message lives in `locales/en.toml`** and is called through its generated function (`msg.NoVM(dir)`, parameters in sorted field order); run `go generate ./internal/msg` after editing it. Template fields are snake_case plain fields (`{{.vm_name}}`, no logic); `one` next to `other` makes it plural (`count int`); a `doc = "page#anchor"` adds the link. A message with no caller fails the tests: add it with its first caller. `msg.M` is an `error`, so a function can return one. Never build prose with `fmt` outside `msg`.
|
||||
- An error is one line. Explain why only when the user has to decide something; a prompt gets at most two lines of context. Status steps are a few words, lowercase. Commands are written as devvm x, not quoted. No "please", "note that" or "simply".
|
||||
- Not messages: data output (tables, files devvm writes) and text in scripts that run elsewhere.
|
||||
- **Tests check which message was printed and with what, never its wording:** `DEVVM_MESSAGES=names` prints `no_vm dir=/x`, and `devvm _msg NAME k=v…` gives e2e the text.
|
||||
@@ -118,5 +120,6 @@ Copied:
|
||||
|
||||
Ported from `devvm` (rewritten in Go, not copied):
|
||||
- paths and state (`internal/paths`, `internal/state`): the `*_dir`/`*_file` definitions, XDG and `DEVVM_LIMA_HOME`, `vm_get`/`vm_set`/`new_vm_state`, image records, `from-digests`, and reading and writing the `size`, `ports`, `base-features` and `agent-keys` files. Go's own formats; their callers come with their tasks. Bats cases converted to Go table tests: `cli.bats` "vm_set/vm_get: keys replace, values may contain '='" and the Lima home half of "devvm's own Lima home" (the `devvm limactl` half goes with that command); the file side of `from.bats` "refresh_from_digest records the registry's digest per tag" and of `build.bats`'s libc record. `images.bats` "the chosen features move from the old features file" is dropped: no migration from the bash files.
|
||||
- messages (`internal/msg`, `locales/en.toml`, `devvm _msg`): `messages.sh`'s `msg` helper and the unit tests' names-mode `msg` (values now in sorted key order), and `tests/lint-messages.sh`, whose checks are now the compiler, the generator and the msg tests. No bulk conversion of `messages.sh`: each task writes its own messages. Bats cases converted: `messages.bats` "msg passes values by name, as they are" (`TestValuesAsGiven`, `msg.txtar`) and "every message prints with the names devvm passes" (`TestEveryMessageRenders`); `lint.bats` "a missing, extra or repeated name, an argument that isn't name=value" and the unknown half of "unknown and unused messages" (`TestFromArgs`, `msg.txtar`; in Go code the compiler checks calls), its unused half (`TestEveryMessageIsUsed`), "messages use names, not positional arguments" (the generator's snake_case plain-field check, `TestGenerateRefuses`) and "devvm's calls match messages.sh" (`TestGeneratedFileIsCurrent` plus the compiler). Left to `internal/ui`: "each helper's stream and prefix", "warn and die prefix every line", "die prints the message and exits 1", "confirm" and "ask". Dropped as bash-specific: `lint.bats` "calls that pass exactly what each message uses" and the "helper with no message" case (the compiler), "helper names in strings, comments, heredocs and arguments aren't calls" (no text parsing in Go), "plain text passes until --strict" and "--strict: prose outside messages.sh" (forbidigo bans printing outside `internal/ui`; prose in `fmt` is a review rule).
|
||||
|
||||
Bash fixes copied: none yet.
|
||||
@@ -43,7 +43,7 @@ Run the tasks with `mise run <task>`:
|
||||
| Task | Does |
|
||||
| --- | --- |
|
||||
| `fmt` | formats Go code |
|
||||
| `lint` | runs golangci-lint, shellcheck and the docs linters |
|
||||
| `lint` | runs golangci-lint, shellcheck, the docs linters and the message link check |
|
||||
| `test` | runs the tests with the race detector and coverage |
|
||||
| `vuln` | runs govulncheck |
|
||||
| `docs` | serves the docs site |
|
||||
@@ -102,6 +102,57 @@ limactl list
|
||||
| `STUB_UNAME_M` | `uname -m` |
|
||||
| `STUB_SW_VERS` | `sw_vers -productVersion` |
|
||||
|
||||
## Messages
|
||||
|
||||
Every message devvm prints is a table in `locales/en.toml`, and Go code calls it through a function generated from it. `internal/msg` renders messages but never prints them; `internal/ui` does.
|
||||
|
||||
```toml
|
||||
[no_vm]
|
||||
other = "no VM for {{.dir}}: run devvm there to create one"
|
||||
doc = "images#where-state-lives"
|
||||
|
||||
[vm_count]
|
||||
one = "{{.count}} VM in {{.dir}}"
|
||||
other = "{{.count}} VMs in {{.dir}}"
|
||||
```
|
||||
|
||||
- **The ID** is the table's name, in snake_case.
|
||||
- **`other`** is the text: a Go template whose fields are snake_case (`{{.vm_name}}`). Only plain fields are allowed, no logic.
|
||||
- **`one`** is the text for a count of 1, when the wording changes with the count. Both texts then take `{{.count}}`.
|
||||
- **`doc`** links a page in `docs/content/docs` and a heading on it (`page#anchor`). devvm prints its address on the docs site on the line after the text.
|
||||
- **Style:** succinct and direct. Say what is being done, or what failed and what to do; link a page when more is needed. An error is one line.
|
||||
|
||||
After editing `en.toml`, run:
|
||||
|
||||
```sh
|
||||
mise exec -- go generate ./internal/msg
|
||||
```
|
||||
|
||||
It writes `internal/msg/messages_gen.go`, with one function per message. The parameters are the template's fields in sorted order, in camelCase, and `count int` for plural messages: `[no_vm]` becomes `msg.NoVM(dir string) msg.M`, and a value that's missing or extra is a compile error. `msg.M` is also an `error`.
|
||||
|
||||
The tests fail when:
|
||||
|
||||
- `messages_gen.go` is stale;
|
||||
- a message doesn't render with sample values, or shows `<no value>`;
|
||||
- a generated function is never called outside the generated file and the tests;
|
||||
- a `doc` page or heading doesn't exist. `mise run lint` runs this check too.
|
||||
|
||||
### Names mode
|
||||
|
||||
With `DEVVM_MESSAGES=names`, a message prints as its ID and its values in sorted key order, so tests check which message devvm printed and with what, never its wording or language:
|
||||
|
||||
```txtar
|
||||
env DEVVM_MESSAGES=names
|
||||
! exec devvm _msg nope
|
||||
stderr 'msg_unknown name=nope$'
|
||||
```
|
||||
|
||||
`devvm _msg NAME key=value…` prints a message's text (never its names), for end-to-end tests that look for it in a VM's output. It's hidden from the help.
|
||||
|
||||
### Translations
|
||||
|
||||
A translation is `locales/<language>.toml` (`de.toml`) with the same tables, `one` and `other` translated. Its `doc` is ignored: 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.
|
||||
|
||||
## 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/`.
|
||||
|
||||
@@ -3,13 +3,16 @@ module github.com/w3cj/devvm
|
||||
go 1.27.3
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.6.0
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1
|
||||
github.com/rogpeppe/go-internal v1.16.0
|
||||
github.com/spf13/cobra v1.10.2
|
||||
golang.org/x/text v0.32.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.9 // indirect
|
||||
golang.org/x/sys v0.26.0 // indirect
|
||||
golang.org/x/tools v0.26.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/tools v0.39.0 // indirect
|
||||
)
|
||||
@@ -1,6 +1,10 @@
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
|
||||
github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g=
|
||||
github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
@@ -8,9 +12,12 @@ github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ=
|
||||
golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
|
||||
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
@@ -0,0 +1,29 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// newMsgCmd is devvm _msg NAME key=value...: a message's text, for the
|
||||
// end-to-end tests to look for. Hidden: it's not for users.
|
||||
func newMsgCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "_msg NAME [key=value...]",
|
||||
Short: "Print a message's text",
|
||||
Hidden: true,
|
||||
DisableFlagParsing: true,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
m, err := msg.FromArgs(args[0], args[1:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(cmd.OutOrStdout(), m.Text())
|
||||
return err
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import "github.com/spf13/cobra"
|
||||
|
||||
// NewRoot returns the devvm command with every subcommand registered.
|
||||
func NewRoot() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
root := &cobra.Command{
|
||||
Use: "devvm",
|
||||
Short: "One isolated VM per project folder",
|
||||
SilenceUsage: true,
|
||||
@@ -14,6 +14,9 @@ func NewRoot() *cobra.Command {
|
||||
return cmd.Help()
|
||||
},
|
||||
}
|
||||
root.CompletionOptions.DisableDefaultCmd = true
|
||||
root.AddCommand(newMsgCmd())
|
||||
return root
|
||||
}
|
||||
|
||||
// Execute runs devvm with args and returns its exit code.
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
// Command gen writes internal/msg/messages_gen.go from locales/en.toml: one
|
||||
// Go function per message, taking the template's fields as parameters. Run
|
||||
// it with go generate ./internal/msg.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"go/token"
|
||||
"log"
|
||||
"os"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"text/template"
|
||||
"text/template/parse"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
// in and out are relative to internal/msg, where go generate runs.
|
||||
const (
|
||||
in = "../../locales/en.toml"
|
||||
out = "messages_gen.go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
src, err := os.ReadFile(in)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
code, err := generate(src)
|
||||
if err != nil {
|
||||
log.Fatalf("%s: %v", in, err)
|
||||
}
|
||||
if err := os.WriteFile(out, code, 0o600); err != nil { //nolint:gosec // a fixed path
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// message is one table of the message file.
|
||||
type message struct {
|
||||
id string
|
||||
other string
|
||||
one string
|
||||
doc string
|
||||
fields []string // the template's fields, sorted; "count" when plural
|
||||
}
|
||||
|
||||
func (m message) plural() bool { return m.one != "" }
|
||||
|
||||
var (
|
||||
idRe = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`)
|
||||
fieldRe = idRe
|
||||
docRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_/-]*(#[a-z0-9][a-z0-9_-]*)?$`)
|
||||
)
|
||||
|
||||
// parseMessages reads and checks the message file.
|
||||
func parseMessages(src []byte) ([]message, error) {
|
||||
var raw map[string]map[string]string
|
||||
if err := toml.Unmarshal(src, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var msgs []message
|
||||
for id, t := range raw {
|
||||
m, err := parseMessage(id, t)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[%s]: %w", id, err)
|
||||
}
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
slices.SortFunc(msgs, func(a, b message) int { return strings.Compare(a.id, b.id) })
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func parseMessage(id string, t map[string]string) (message, error) {
|
||||
if !idRe.MatchString(id) {
|
||||
return message{}, errors.New("the ID must be snake_case")
|
||||
}
|
||||
m := message{id: id}
|
||||
for k, v := range t {
|
||||
switch k {
|
||||
case "other":
|
||||
m.other = v
|
||||
case "one":
|
||||
m.one = v
|
||||
case "doc":
|
||||
m.doc = v
|
||||
default:
|
||||
return message{}, fmt.Errorf("unknown key %q (want other, one or doc)", k)
|
||||
}
|
||||
}
|
||||
if m.other == "" {
|
||||
return message{}, errors.New("no other text")
|
||||
}
|
||||
if m.doc != "" && !docRe.MatchString(m.doc) {
|
||||
return message{}, fmt.Errorf("doc %q is not page#anchor", m.doc)
|
||||
}
|
||||
fields := map[string]bool{}
|
||||
for _, text := range []string{m.other, m.one} {
|
||||
if err := templateFields(text, fields); err != nil {
|
||||
return message{}, err
|
||||
}
|
||||
}
|
||||
if m.plural() {
|
||||
fields["count"] = true
|
||||
} else if fields["count"] {
|
||||
return message{}, errors.New("{{.count}} is for plural messages: add a one text")
|
||||
}
|
||||
for f := range fields {
|
||||
if !fieldRe.MatchString(f) {
|
||||
return message{}, fmt.Errorf("field %q must be snake_case", f)
|
||||
}
|
||||
if p := goName(f, false); token.IsKeyword(p) || taken[p] {
|
||||
return message{}, fmt.Errorf("field %q is taken in Go; rename it", f)
|
||||
}
|
||||
m.fields = append(m.fields, f)
|
||||
}
|
||||
slices.Sort(m.fields)
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// templateFields adds the fields text uses ({{.dir}}) to fields. Only
|
||||
// plain fields are allowed: messages hold no logic.
|
||||
func templateFields(text string, fields map[string]bool) error {
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
tmpl, err := template.New("").Parse(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range tmpl.Root.Nodes {
|
||||
switch n := n.(type) {
|
||||
case *parse.TextNode:
|
||||
case *parse.ActionNode:
|
||||
f, ok := plainField(n)
|
||||
if !ok {
|
||||
return fmt.Errorf("%s: only plain fields like {{.dir}} are allowed", n)
|
||||
}
|
||||
fields[f] = true
|
||||
default:
|
||||
return fmt.Errorf("%s: only plain fields like {{.dir}} are allowed", n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func plainField(n *parse.ActionNode) (string, bool) {
|
||||
if len(n.Pipe.Decl) > 0 || len(n.Pipe.Cmds) != 1 || len(n.Pipe.Cmds[0].Args) != 1 {
|
||||
return "", false
|
||||
}
|
||||
f, ok := n.Pipe.Cmds[0].Args[0].(*parse.FieldNode)
|
||||
if !ok || len(f.Ident) != 1 {
|
||||
return "", false
|
||||
}
|
||||
return f.Ident[0], true
|
||||
}
|
||||
|
||||
// taken are names a parameter would shadow in the generated functions.
|
||||
var taken = map[string]bool{
|
||||
"any": true, "bool": true, "byte": true, "error": true, "false": true, "int": true,
|
||||
"nil": true, "string": true, "true": true, "len": true, "new": true, "make": true,
|
||||
"strconv": true, "val": true, "spec": true,
|
||||
}
|
||||
|
||||
// initialisms are written in capitals in Go names: vm_name is vmName,
|
||||
// no_vm is NoVM.
|
||||
var initialisms = map[string]bool{
|
||||
"api": true, "ca": true, "cli": true, "cpu": true, "dns": true, "gc": true, "http": true,
|
||||
"https": true, "id": true, "ip": true, "json": true, "oci": true, "os": true, "pid": true,
|
||||
"sha": true, "ssh": true, "tcp": true, "tls": true, "tty": true, "ui": true, "uid": true,
|
||||
"url": true, "vm": true, "vms": true, "xdg": true,
|
||||
}
|
||||
|
||||
// goName turns snake_case into a Go name, exported or not.
|
||||
func goName(s string, exported bool) string {
|
||||
var b strings.Builder
|
||||
for i, w := range strings.Split(s, "_") {
|
||||
switch {
|
||||
case i == 0 && !exported:
|
||||
b.WriteString(w)
|
||||
case w == "vms":
|
||||
b.WriteString("VMs")
|
||||
case initialisms[w]:
|
||||
b.WriteString(strings.ToUpper(w))
|
||||
default:
|
||||
b.WriteString(strings.ToUpper(w[:1]) + w[1:])
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// generate returns messages_gen.go for the message file src.
|
||||
func generate(src []byte) ([]byte, error) {
|
||||
msgs, err := parseMessages(src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
funcs := map[string]string{}
|
||||
for _, m := range msgs {
|
||||
name := goName(m.id, true)
|
||||
if other, ok := funcs[name]; ok {
|
||||
return nil, fmt.Errorf("[%s] and [%s] are both %s in Go", other, m.id, name)
|
||||
}
|
||||
funcs[name] = m.id
|
||||
}
|
||||
|
||||
var b bytes.Buffer
|
||||
b.WriteString("// Code generated by go generate ./internal/msg from locales/en.toml. DO NOT EDIT.\n\n")
|
||||
b.WriteString("package msg\n\n")
|
||||
if slices.ContainsFunc(msgs, message.plural) {
|
||||
b.WriteString("import \"strconv\"\n\n")
|
||||
}
|
||||
for _, m := range msgs {
|
||||
writeFunc(&b, m)
|
||||
}
|
||||
b.WriteString("// specs describes every message, by ID.\nvar specs = map[string]spec{\n")
|
||||
for _, m := range msgs {
|
||||
var s []string
|
||||
if m.doc != "" {
|
||||
s = append(s, fmt.Sprintf("doc: %q", m.doc))
|
||||
}
|
||||
if m.plural() {
|
||||
s = append(s, "plural: true")
|
||||
}
|
||||
if len(m.fields) > 0 {
|
||||
s = append(s, fmt.Sprintf("fields: %#v", m.fields))
|
||||
}
|
||||
fmt.Fprintf(&b, "\t%q: {%s},\n", m.id, strings.Join(s, ", "))
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
return format.Source(b.Bytes())
|
||||
}
|
||||
|
||||
func writeFunc(b *bytes.Buffer, m message) {
|
||||
var params, vals []string
|
||||
for _, f := range m.fields {
|
||||
p := goName(f, false)
|
||||
if f == "count" {
|
||||
params = append(params, p+" int")
|
||||
vals = append(vals, fmt.Sprintf("{%q, strconv.Itoa(%s)}", f, p))
|
||||
continue
|
||||
}
|
||||
params = append(params, p+" string")
|
||||
vals = append(vals, fmt.Sprintf("{%q, %s}", f, p))
|
||||
}
|
||||
fmt.Fprintf(b, "// %s is [%s]: %q\n", goName(m.id, true), m.id, m.other)
|
||||
fmt.Fprintf(b, "func %s(%s) M {\n", goName(m.id, true), strings.Join(params, ", "))
|
||||
fmt.Fprintf(b, "\treturn M{id: %q", m.id)
|
||||
if m.doc != "" {
|
||||
fmt.Fprintf(b, ", doc: %q", m.doc)
|
||||
}
|
||||
if m.plural() {
|
||||
b.WriteString(", plural: true, count: count")
|
||||
}
|
||||
if len(vals) > 0 {
|
||||
fmt.Fprintf(b, ", vals: []val{%s}", strings.Join(vals, ", "))
|
||||
}
|
||||
b.WriteString("}\n}\n\n")
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGeneratedFileIsCurrent(t *testing.T) {
|
||||
src, err := os.ReadFile("../../../locales/en.toml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err := generate(src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := os.ReadFile("../messages_gen.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != string(want) {
|
||||
t.Error("internal/msg/messages_gen.go is stale: run go generate ./internal/msg")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerate(t *testing.T) {
|
||||
code, err := generate([]byte(`
|
||||
[no_vm]
|
||||
other = "no VM for {{.dir}}: run devvm there to create one"
|
||||
doc = "images#where-state-lives"
|
||||
|
||||
[vm_count]
|
||||
one = "{{.vm_name}} has {{.count}} VM"
|
||||
other = "{{.vm_name}} has {{.count}} VMs"
|
||||
|
||||
[ssh_key_id]
|
||||
other = "key {{.key_id}} for {{.url}} on {{.vms}}"
|
||||
|
||||
[ready]
|
||||
other = "ready"
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`func NoVM(dir string) M {`,
|
||||
`return M{id: "no_vm", doc: "images#where-state-lives", vals: []val{{"dir", dir}}}`,
|
||||
`func VMCount(count int, vmName string) M {`,
|
||||
`return M{id: "vm_count", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"vm_name", vmName}}}`,
|
||||
`func SSHKeyID(keyID string, url string, vms string) M {`,
|
||||
`func Ready() M {`,
|
||||
`return M{id: "ready"}`,
|
||||
`import "strconv"`,
|
||||
`"no_vm": {doc: "images#where-state-lives", fields: []string{"dir"}},`,
|
||||
`"vm_count": {plural: true, fields: []string{"count", "vm_name"}},`,
|
||||
`"ready": {},`,
|
||||
} {
|
||||
if !strings.Contains(string(code), want) {
|
||||
t.Errorf("no %s in:\n%s", want, code)
|
||||
}
|
||||
}
|
||||
|
||||
code, err = generate([]byte("[ready]\nother = \"ready\"\n"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(code), "strconv") {
|
||||
t.Errorf("strconv imported without plurals:\n%s", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateRefuses(t *testing.T) {
|
||||
for _, tt := range []struct{ name, src, want string }{
|
||||
{"bad TOML", `[x`, "expected"},
|
||||
{"camelCase ID", "[noVM]\nother = \"x\"", "snake_case"},
|
||||
{"no other", "[x]\none = \"x\"", "no other text"},
|
||||
{"unknown key", "[x]\nother = \"x\"\ndescription = \"y\"", `unknown key "description"`},
|
||||
{"camelCase field", "[x]\nother = \"{{.vmName}}\"", `field "vmName" must be snake_case`},
|
||||
{"nested field", "[x]\nother = \"{{.vm.name}}\"", "only plain fields"},
|
||||
{"logic", "[x]\nother = \"{{if .a}}a{{end}}\"", "only plain fields"},
|
||||
{"a function", "[x]\nother = \"{{printf .a}}\"", "only plain fields"},
|
||||
{"a variable", "[x]\nother = \"{{$a := .a}}\"", "only plain fields"},
|
||||
{"bad template", "[x]\nother = \"{{.a\"", "unclosed action"},
|
||||
{"a Go keyword", "[x]\nother = \"{{.type}}\"", `field "type" is taken`},
|
||||
{"a Go type", "[x]\nother = \"{{.string}}\"", `field "string" is taken`},
|
||||
{"count without plurals", "[x]\nother = \"{{.count}}\"", "add a one text"},
|
||||
{"bad doc", "[x]\nother = \"x\"\ndoc = \"https://example.com\"", "not page#anchor"},
|
||||
{"same Go name", "[no_vm]\nother = \"x\"\n[no_v_m]\nother = \"y\"", "both NoVM"},
|
||||
} {
|
||||
_, err := generate([]byte(tt.src))
|
||||
if err == nil || !strings.Contains(err.Error(), tt.want) {
|
||||
t.Errorf("%s: got %v, want %q", tt.name, err, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Code generated by go generate ./internal/msg from locales/en.toml. DO NOT EDIT.
|
||||
|
||||
package msg
|
||||
|
||||
// HomeNotAbsolute is [home_not_absolute]: "HOME isn't an absolute path: set it to your home folder"
|
||||
func HomeNotAbsolute() M {
|
||||
return M{id: "home_not_absolute"}
|
||||
}
|
||||
|
||||
// MsgBadCount is [msg_bad_count]: "count must be a whole number, not {{.value}}"
|
||||
func MsgBadCount(value string) M {
|
||||
return M{id: "msg_bad_count", vals: []val{{"value", value}}}
|
||||
}
|
||||
|
||||
// MsgMissingValue is [msg_missing_value]: "{{.name}} needs {{.key}}="
|
||||
func MsgMissingValue(key string, name string) M {
|
||||
return M{id: "msg_missing_value", vals: []val{{"key", key}, {"name", name}}}
|
||||
}
|
||||
|
||||
// MsgNotPair is [msg_not_pair]: "{{.arg}} is not name=value"
|
||||
func MsgNotPair(arg string) M {
|
||||
return M{id: "msg_not_pair", vals: []val{{"arg", arg}}}
|
||||
}
|
||||
|
||||
// MsgRepeatedValue is [msg_repeated_value]: "{{.key}}= is given twice"
|
||||
func MsgRepeatedValue(key string) M {
|
||||
return M{id: "msg_repeated_value", vals: []val{{"key", key}}}
|
||||
}
|
||||
|
||||
// MsgUnexpectedValue is [msg_unexpected_value]: "{{.name}} takes no {{.key}}="
|
||||
func MsgUnexpectedValue(key string, name string) M {
|
||||
return M{id: "msg_unexpected_value", vals: []val{{"key", key}, {"name", name}}}
|
||||
}
|
||||
|
||||
// MsgUnknown is [msg_unknown]: "no message {{.name}}"
|
||||
func MsgUnknown(name string) M {
|
||||
return M{id: "msg_unknown", vals: []val{{"name", name}}}
|
||||
}
|
||||
|
||||
// specs describes every message, by ID.
|
||||
var specs = map[string]spec{
|
||||
"home_not_absolute": {},
|
||||
"msg_bad_count": {fields: []string{"value"}},
|
||||
"msg_missing_value": {fields: []string{"key", "name"}},
|
||||
"msg_not_pair": {fields: []string{"arg"}},
|
||||
"msg_repeated_value": {fields: []string{"key"}},
|
||||
"msg_unexpected_value": {fields: []string{"key", "name"}},
|
||||
"msg_unknown": {fields: []string{"name"}},
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// Package msg holds every message devvm prints, as typed functions generated
|
||||
// from locales/en.toml (NoVM(dir) for [no_vm]). It renders them in the
|
||||
// user's language, but never prints: internal/ui does.
|
||||
//
|
||||
// With DEVVM_MESSAGES=names, a message renders as its ID and values in
|
||||
// sorted key order (no_vm dir=/x), so tests never depend on wording or
|
||||
// language.
|
||||
package msg
|
||||
|
||||
//go:generate go run ./gen
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"maps"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
"golang.org/x/text/language"
|
||||
|
||||
"github.com/w3cj/devvm/locales"
|
||||
)
|
||||
|
||||
// DocsBase is the docs site's address; doc links are under it.
|
||||
const DocsBase = "https://w3cj.github.io/devvm/docs/"
|
||||
|
||||
// M is a message with its values, made by the generated functions.
|
||||
type M struct {
|
||||
id string
|
||||
doc string
|
||||
plural bool
|
||||
count int
|
||||
vals []val // in sorted key order
|
||||
}
|
||||
|
||||
type val struct{ key, value string }
|
||||
|
||||
// spec is what the generated table says about a message.
|
||||
type spec struct {
|
||||
doc string
|
||||
plural bool
|
||||
fields []string // sorted; "count" when plural
|
||||
}
|
||||
|
||||
// ID returns the message's ID, its table name in en.toml.
|
||||
func (m M) ID() string { return m.id }
|
||||
|
||||
// String returns the message as devvm prints it: its text, then its doc
|
||||
// link on a line of its own. With DEVVM_MESSAGES=names, its names instead.
|
||||
func (m M) String() string {
|
||||
if namesMode() {
|
||||
return m.Names()
|
||||
}
|
||||
if u := m.DocURL(); u != "" {
|
||||
return m.Text() + "\n" + u
|
||||
}
|
||||
return m.Text()
|
||||
}
|
||||
|
||||
// Error makes a message usable as an error. It's the same as String.
|
||||
func (m M) Error() string { return m.String() }
|
||||
|
||||
// Names returns the message's ID and values: no_vm dir=/x.
|
||||
func (m M) Names() string {
|
||||
var b strings.Builder
|
||||
b.WriteString(m.id)
|
||||
for _, v := range m.vals {
|
||||
b.WriteString(" " + v.key + "=" + v.value)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Text returns the message's text in the user's language, falling back to
|
||||
// English when it has no translation.
|
||||
func (m M) Text() string {
|
||||
return m.textIn(loadBundle(), userLanguage(os.Getenv))
|
||||
}
|
||||
|
||||
func (m M) textIn(b *i18n.Bundle, lang string) string {
|
||||
data := make(map[string]string, len(m.vals))
|
||||
for _, v := range m.vals {
|
||||
data[v.key] = v.value
|
||||
}
|
||||
lc := &i18n.LocalizeConfig{MessageID: m.id, TemplateData: data}
|
||||
if m.plural {
|
||||
lc.PluralCount = m.count
|
||||
}
|
||||
text, err := i18n.NewLocalizer(b, lang).Localize(lc)
|
||||
if text == "" && err != nil {
|
||||
// Only a message missing from en.toml gets here, which the
|
||||
// generated file rules out.
|
||||
return m.Names()
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// DocURL returns the address of the message's doc page, or "" when it has
|
||||
// none.
|
||||
func (m M) DocURL() string { return docURL(m.doc) }
|
||||
|
||||
// docURL turns "page#anchor" into the page's address on the docs site.
|
||||
func docURL(doc string) string {
|
||||
if doc == "" {
|
||||
return ""
|
||||
}
|
||||
page, anchor, _ := strings.Cut(doc, "#")
|
||||
u := DocsBase + page + "/"
|
||||
if anchor != "" {
|
||||
u += "#" + anchor
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func namesMode() bool { return os.Getenv("DEVVM_MESSAGES") == "names" }
|
||||
|
||||
// userLanguage returns the language messages are shown in, from the first
|
||||
// of LC_ALL, LC_MESSAGES and LANG that is set, as a BCP 47 tag ("de-DE"
|
||||
// for de_DE.UTF-8). C and POSIX are English.
|
||||
func userLanguage(getenv func(string) string) string {
|
||||
for _, name := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {
|
||||
v := getenv(name)
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
v, _, _ = strings.Cut(v, ".")
|
||||
v, _, _ = strings.Cut(v, "@")
|
||||
if v == "C" || v == "POSIX" {
|
||||
return "en"
|
||||
}
|
||||
return strings.ReplaceAll(v, "_", "-")
|
||||
}
|
||||
return "en"
|
||||
}
|
||||
|
||||
// loadBundle returns every embedded locale, English first.
|
||||
var loadBundle = sync.OnceValue(func() *i18n.Bundle {
|
||||
b, err := newBundle(locales.FS)
|
||||
if err != nil {
|
||||
// The files are embedded and checked by the tests.
|
||||
panic(err)
|
||||
}
|
||||
return b
|
||||
})
|
||||
|
||||
// localeTable is one message in a locale file. doc is read from the
|
||||
// generated table, so a translation's is ignored.
|
||||
type localeTable struct {
|
||||
One string `toml:"one"`
|
||||
Other string `toml:"other"`
|
||||
Doc string `toml:"doc"`
|
||||
}
|
||||
|
||||
// newBundle loads every *.toml file in fsys, named by language (en.toml).
|
||||
// go-i18n's own parser refuses a table that mixes its keys with others
|
||||
// (doc), so the files are read here.
|
||||
func newBundle(fsys fs.FS) (*i18n.Bundle, error) {
|
||||
b := i18n.NewBundle(language.English)
|
||||
files, err := fs.Glob(fsys, "*.toml")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
tag, err := language.Parse(strings.TrimSuffix(path.Base(file), ".toml"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := fs.ReadFile(fsys, file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var tables map[string]localeTable
|
||||
if err := toml.Unmarshal(data, &tables); err != nil {
|
||||
return nil, &fs.PathError{Op: "parse", Path: file, Err: err}
|
||||
}
|
||||
msgs := make([]*i18n.Message, 0, len(tables))
|
||||
for id, t := range tables {
|
||||
msgs = append(msgs, &i18n.Message{ID: id, One: t.One, Other: t.Other})
|
||||
}
|
||||
if err := b.AddMessages(tag, msgs...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// FromArgs makes a message from its ID and key=value arguments, checked
|
||||
// against its fields: what devvm _msg prints. A plural message's count is
|
||||
// given as count=N.
|
||||
func FromArgs(id string, args []string) (M, error) {
|
||||
s, ok := specs[id]
|
||||
if !ok {
|
||||
return M{}, MsgUnknown(id)
|
||||
}
|
||||
given := map[string]string{}
|
||||
for _, a := range args {
|
||||
k, v, ok := strings.Cut(a, "=")
|
||||
if !ok || k == "" {
|
||||
return M{}, MsgNotPair(a)
|
||||
}
|
||||
if _, dup := given[k]; dup {
|
||||
return M{}, MsgRepeatedValue(k)
|
||||
}
|
||||
given[k] = v
|
||||
}
|
||||
m := M{id: id, doc: s.doc, plural: s.plural}
|
||||
for _, f := range s.fields {
|
||||
v, ok := given[f]
|
||||
if !ok {
|
||||
return M{}, MsgMissingValue(f, id)
|
||||
}
|
||||
delete(given, f)
|
||||
if f == "count" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return M{}, MsgBadCount(v)
|
||||
}
|
||||
m.count, v = n, strconv.Itoa(n)
|
||||
}
|
||||
m.vals = append(m.vals, val{f, v})
|
||||
}
|
||||
if len(given) > 0 {
|
||||
return M{}, MsgUnexpectedValue(slices.Sorted(maps.Keys(given))[0], id)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package msg
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/w3cj/devvm/locales"
|
||||
)
|
||||
|
||||
// sample makes message id with a value for each field: the field's name,
|
||||
// and count for a plural message.
|
||||
func sample(t *testing.T, id string, count int) M {
|
||||
t.Helper()
|
||||
var args []string
|
||||
for _, f := range specs[id].fields {
|
||||
v := "v_" + f
|
||||
if f == "count" {
|
||||
v = strconv.Itoa(count)
|
||||
}
|
||||
args = append(args, f+"="+v)
|
||||
}
|
||||
m, err := FromArgs(id, args)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", id, err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestLocalesLoad(t *testing.T) {
|
||||
b, err := newBundle(locales.FS)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tags := b.LanguageTags(); len(tags) == 0 || tags[0].String() != "en" {
|
||||
t.Errorf("languages %v: want English first", tags)
|
||||
}
|
||||
}
|
||||
|
||||
// Every message renders in every language, with every value used.
|
||||
func TestEveryMessageRenders(t *testing.T) {
|
||||
b := loadBundle()
|
||||
for id, s := range specs {
|
||||
for _, count := range []int{1, 2} {
|
||||
m := sample(t, id, count)
|
||||
for _, tag := range b.LanguageTags() {
|
||||
text := m.textIn(b, tag.String())
|
||||
if text == "" || strings.Contains(text, "<no value>") {
|
||||
t.Errorf("%s in %s: %q", id, tag, text)
|
||||
}
|
||||
for _, f := range s.fields {
|
||||
if f != "count" && !strings.Contains(text, "v_"+f) {
|
||||
t.Errorf("%s in %s: %q doesn't show %s", id, tag, text, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !s.plural {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValuesAsGiven(t *testing.T) {
|
||||
v := `x y $HOME "q" <b> {{.name}}`
|
||||
if got, want := MsgUnknown(v).Text(), "no message "+v; got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNames(t *testing.T) {
|
||||
m := MsgMissingValue("dir", "no_vm")
|
||||
if got, want := m.Names(), "msg_missing_value key=dir name=no_vm"; got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
if got, want := HomeNotAbsolute().Names(), "home_not_absolute"; got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
t.Setenv("DEVVM_MESSAGES", "names")
|
||||
if got, want := m.String(), m.Names(); got != want {
|
||||
t.Errorf("String in names mode: got %q, want %q", got, want)
|
||||
}
|
||||
if got, want := m.Error(), m.Names(); got != want {
|
||||
t.Errorf("Error in names mode: got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringAddsDocLink(t *testing.T) {
|
||||
t.Setenv("DEVVM_MESSAGES", "")
|
||||
m := MsgUnknown("x")
|
||||
if got := m.String(); got != m.Text() {
|
||||
t.Errorf("no doc: got %q, want the text", got)
|
||||
}
|
||||
m.doc = "images#where-state-lives"
|
||||
want := m.Text() + "\nhttps://w3cj.github.io/devvm/docs/images/#where-state-lives"
|
||||
if got := m.String(); got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocURL(t *testing.T) {
|
||||
for doc, want := range map[string]string{
|
||||
"": "",
|
||||
"images": "https://w3cj.github.io/devvm/docs/images/",
|
||||
"images#where-state-lives": "https://w3cj.github.io/devvm/docs/images/#where-state-lives",
|
||||
"cli/devvm_ls": "https://w3cj.github.io/devvm/docs/cli/devvm_ls/",
|
||||
} {
|
||||
if got := docURL(doc); got != want {
|
||||
t.Errorf("docURL(%q) = %q, want %q", doc, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserLanguage(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
env map[string]string
|
||||
want string
|
||||
}{
|
||||
{nil, "en"},
|
||||
{map[string]string{"LANG": "de_DE.UTF-8"}, "de-DE"},
|
||||
{map[string]string{"LANG": "de_DE.UTF-8", "LC_MESSAGES": "fr_FR"}, "fr-FR"},
|
||||
{map[string]string{"LANG": "de_DE", "LC_MESSAGES": "fr_FR", "LC_ALL": "pt_BR.UTF-8"}, "pt-BR"},
|
||||
{map[string]string{"LANG": "sr_RS@latin"}, "sr-RS"},
|
||||
{map[string]string{"LANG": "de_DE", "LC_ALL": "C"}, "en"},
|
||||
{map[string]string{"LC_ALL": "POSIX"}, "en"},
|
||||
{map[string]string{"LC_ALL": "", "LANG": "ja_JP.UTF-8"}, "ja-JP"},
|
||||
} {
|
||||
if got := userLanguage(func(k string) string { return tt.env[k] }); got != tt.want {
|
||||
t.Errorf("%v: got %q, want %q", tt.env, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A translation is used for the messages it has; English for the rest.
|
||||
// Plural forms follow the count.
|
||||
func TestTranslationsAndPlurals(t *testing.T) {
|
||||
b, err := newBundle(fstest.MapFS{
|
||||
"en.toml": {Data: []byte(`
|
||||
[t_vms]
|
||||
one = "{{.count}} VM in {{.dir}}"
|
||||
other = "{{.count}} VMs in {{.dir}}"
|
||||
[t_plain]
|
||||
other = "plain"
|
||||
`)},
|
||||
"de.toml": {Data: []byte(`
|
||||
[t_vms]
|
||||
one = "{{.count}} VM in {{.dir}} (de)"
|
||||
other = "{{.count}} VMs in {{.dir}} (de)"
|
||||
`)},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vms := func(n int) M {
|
||||
return M{id: "t_vms", plural: true, count: n, vals: []val{{"count", strconv.Itoa(n)}, {"dir", "/x"}}}
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
m M
|
||||
lang, want string
|
||||
}{
|
||||
{vms(1), "en", "1 VM in /x"},
|
||||
{vms(2), "en", "2 VMs in /x"},
|
||||
{vms(1), "de-DE", "1 VM in /x (de)"},
|
||||
{vms(2), "de", "2 VMs in /x (de)"},
|
||||
{vms(2), "fr", "2 VMs in /x"},
|
||||
{M{id: "t_plain"}, "de", "plain"},
|
||||
{M{id: "t_missing"}, "en", "t_missing"},
|
||||
} {
|
||||
if got := tt.m.textIn(b, tt.lang); got != tt.want {
|
||||
t.Errorf("%s in %s: got %q, want %q", tt.m.Names(), tt.lang, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBundleErrors(t *testing.T) {
|
||||
for name, fsys := range map[string]fstest.MapFS{
|
||||
"bad TOML": {"en.toml": {Data: []byte("[x\n")}},
|
||||
"bad file name": {"not a tag.toml": {Data: []byte("")}},
|
||||
} {
|
||||
if _, err := newBundle(fsys); err == nil {
|
||||
t.Errorf("%s: want an error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromArgs(t *testing.T) {
|
||||
specs["t_plural"] = spec{plural: true, fields: []string{"count", "dir"}}
|
||||
defer delete(specs, "t_plural")
|
||||
for _, tt := range []struct {
|
||||
id string
|
||||
args []string
|
||||
want string // names of the message, or of the error
|
||||
}{
|
||||
{"msg_unknown", []string{"name=a b=c"}, "msg_unknown name=a b=c"},
|
||||
{"home_not_absolute", nil, "home_not_absolute"},
|
||||
{"msg_missing_value", []string{"name=n", "key=k"}, "msg_missing_value key=k name=n"},
|
||||
{"t_plural", []string{"dir=/x", "count=02"}, "t_plural count=2 dir=/x"},
|
||||
{"nope", nil, "msg_unknown name=nope"},
|
||||
{"msg_unknown", nil, "msg_missing_value key=name name=msg_unknown"},
|
||||
{"msg_unknown", []string{"name=a", "vm=b"}, "msg_unexpected_value key=vm name=msg_unknown"},
|
||||
{"msg_unknown", []string{"name=a", "name=b"}, "msg_repeated_value key=name"},
|
||||
{"msg_unknown", []string{"a"}, "msg_not_pair arg=a"},
|
||||
{"msg_unknown", []string{"=a"}, "msg_not_pair arg==a"},
|
||||
{"t_plural", []string{"dir=/x", "count=two"}, "msg_bad_count value=two"},
|
||||
} {
|
||||
m, err := FromArgs(tt.id, tt.args)
|
||||
got := m.Names()
|
||||
if err != nil {
|
||||
e, ok := errors.AsType[M](err)
|
||||
if !ok {
|
||||
t.Fatalf("%s %q: %v is not a message", tt.id, tt.args, err)
|
||||
}
|
||||
got = e.Names()
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("%s %q: got %q, want %q", tt.id, tt.args, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package msg
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// root is the repo's root, from this package's folder.
|
||||
const root = "../.."
|
||||
|
||||
// generatedFuncs returns the functions in messages_gen.go.
|
||||
func generatedFuncs(t *testing.T) map[string]bool {
|
||||
t.Helper()
|
||||
f, err := parser.ParseFile(token.NewFileSet(), "messages_gen.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
funcs := map[string]bool{}
|
||||
for _, d := range f.Decls {
|
||||
if fd, ok := d.(*ast.FuncDecl); ok {
|
||||
funcs[fd.Name.Name] = true
|
||||
}
|
||||
}
|
||||
return funcs
|
||||
}
|
||||
|
||||
// Every message is called somewhere other than the generated file and the
|
||||
// tests.
|
||||
func TestEveryMessageIsUsed(t *testing.T) {
|
||||
unused := generatedFuncs(t)
|
||||
fset := token.NewFileSet()
|
||||
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() {
|
||||
if name := d.Name(); path != root && (strings.HasPrefix(name, ".") || name == "testdata" || name == "docs") {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") || d.Name() == "messages_gen.go" {
|
||||
return nil
|
||||
}
|
||||
f, err := parser.ParseFile(fset, path, nil, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inMsg := filepath.Dir(path) == filepath.Join(root, "internal", "msg")
|
||||
ast.Inspect(f, func(n ast.Node) bool {
|
||||
switch n := n.(type) {
|
||||
case *ast.SelectorExpr:
|
||||
if x, ok := n.X.(*ast.Ident); ok && x.Name == "msg" {
|
||||
delete(unused, n.Sel.Name)
|
||||
}
|
||||
case *ast.Ident:
|
||||
if inMsg {
|
||||
delete(unused, n.Name)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name := range unused {
|
||||
t.Errorf("msg.%s is never used: call it, or delete its message from locales/en.toml", name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDocLinks checks that every doc link in locales/en.toml names a page
|
||||
// in docs/content/docs, and an anchor on it. mise run lint runs it.
|
||||
func TestDocLinks(t *testing.T) {
|
||||
content := filepath.Join(root, "docs", "content", "docs")
|
||||
for id, s := range specs {
|
||||
if s.doc == "" {
|
||||
continue
|
||||
}
|
||||
if err := checkDoc(content, s.doc); err != nil {
|
||||
t.Errorf("[%s] doc = %q: %v", id, s.doc, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkDoc reports whether doc ("page#anchor") is a page in dir with that
|
||||
// anchor.
|
||||
func checkDoc(dir, doc string) error {
|
||||
page, anchor, _ := strings.Cut(doc, "#")
|
||||
anchors, err := pageAnchors(filepath.Join(dir, filepath.FromSlash(page)+".md"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if anchor != "" && !anchors[anchor] {
|
||||
return fmt.Errorf("%s has no heading #%s", page, anchor)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
headingRe = regexp.MustCompile(`^#{1,6}\s+(.*?)\s*$`)
|
||||
customIDRe = regexp.MustCompile(`\s*\{#([^}]+)\}$`)
|
||||
notIDRe = regexp.MustCompile(`[^\p{L}\p{N}_ -]`)
|
||||
)
|
||||
|
||||
// pageAnchors returns the IDs Hugo gives a Markdown page's headings:
|
||||
// {#custom} when given, else the text lowercased, punctuation dropped and
|
||||
// spaces as hyphens. Headings in fenced code don't count.
|
||||
func pageAnchors(path string) (map[string]bool, error) {
|
||||
f, err := os.Open(path) //nolint:gosec // a docs page from en.toml
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, fmt.Errorf("no page %s", path)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
anchors := map[string]bool{}
|
||||
fence := ""
|
||||
s := bufio.NewScanner(f)
|
||||
for s.Scan() {
|
||||
line := s.Text()
|
||||
if t := strings.TrimSpace(line); strings.HasPrefix(t, "```") || strings.HasPrefix(t, "~~~") {
|
||||
switch {
|
||||
case fence == "":
|
||||
fence = t[:3]
|
||||
case strings.HasPrefix(t, fence):
|
||||
fence = ""
|
||||
}
|
||||
continue
|
||||
}
|
||||
m := headingRe.FindStringSubmatch(line)
|
||||
if fence != "" || m == nil {
|
||||
continue
|
||||
}
|
||||
text := m[1]
|
||||
if c := customIDRe.FindStringSubmatch(text); c != nil {
|
||||
anchors[c[1]] = true
|
||||
continue
|
||||
}
|
||||
text = notIDRe.ReplaceAllString(strings.ToLower(text), "")
|
||||
anchors[strings.ReplaceAll(text, " ", "-")] = true
|
||||
}
|
||||
return anchors, s.Err()
|
||||
}
|
||||
|
||||
func TestCheckDoc(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
page := "---\ntitle: T\n---\n\n## Where state lives\n\n### Sizes, ports & more\n\n## Custom {#short}\n\n" +
|
||||
"```sh\n# Not a heading\n```\n"
|
||||
if err := os.MkdirAll(filepath.Join(dir, "cli"), 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range []string{"images.md", "cli/devvm.md"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, p), []byte(page), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
doc string
|
||||
ok bool
|
||||
}{
|
||||
{"images", true},
|
||||
{"images#where-state-lives", true},
|
||||
{"images#sizes-ports--more", true},
|
||||
{"images#short", true},
|
||||
{"cli/devvm#where-state-lives", true},
|
||||
{"images#custom", false},
|
||||
{"images#not-a-heading", false},
|
||||
{"images#nope", false},
|
||||
{"nope", false},
|
||||
{"nope#where-state-lives", false},
|
||||
} {
|
||||
if err := checkDoc(dir, tt.doc); (err == nil) != tt.ok {
|
||||
t.Errorf("checkDoc(%q) = %v, want ok %t", tt.doc, err, tt.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
package paths
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
// Dirs holds the folders devvm keeps its state in. Every file devvm writes
|
||||
@@ -30,7 +31,7 @@ func FromEnv() (Dirs, error) {
|
||||
func fromEnv(getenv func(string) string) (Dirs, error) {
|
||||
home := getenv("HOME")
|
||||
if !filepath.IsAbs(home) {
|
||||
return Dirs{}, errors.New("HOME is not set to an absolute path")
|
||||
return Dirs{}, msg.HomeNotAbsolute()
|
||||
}
|
||||
d := Dirs{
|
||||
Data: filepath.Join(xdg(getenv, "XDG_DATA_HOME", home, ".local", "share"), "devvm"),
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package paths
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
)
|
||||
|
||||
func TestFromEnv(t *testing.T) {
|
||||
@@ -56,13 +59,14 @@ func TestFromEnv(t *testing.T) {
|
||||
|
||||
func TestFromEnvNeedsHome(t *testing.T) {
|
||||
for _, home := range []string{"", "rel"} {
|
||||
if _, err := fromEnv(func(k string) string {
|
||||
_, err := fromEnv(func(k string) string {
|
||||
if k == "HOME" {
|
||||
return home
|
||||
}
|
||||
return ""
|
||||
}); err == nil {
|
||||
t.Errorf("HOME=%q: want an error", home)
|
||||
})
|
||||
if m, ok := errors.AsType[msg.M](err); !ok || m.ID() != "home_not_absolute" {
|
||||
t.Errorf("HOME=%q: got %v, want home_not_absolute", home, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Every message devvm prints. Each table is one message: its ID is the
|
||||
# table's name, "other" is its text (a Go template with snake_case fields,
|
||||
# {{.vm_name}}), "one" is the text for a count of 1 when the wording changes
|
||||
# (both then take {{.count}}), and "doc" links a docs page ("page#anchor").
|
||||
# Run go generate ./internal/msg after editing.
|
||||
|
||||
[home_not_absolute]
|
||||
other = "HOME isn't an absolute path: set it to your home folder"
|
||||
|
||||
[msg_unknown]
|
||||
other = "no message {{.name}}"
|
||||
|
||||
[msg_not_pair]
|
||||
other = "{{.arg}} is not name=value"
|
||||
|
||||
[msg_missing_value]
|
||||
other = "{{.name}} needs {{.key}}="
|
||||
|
||||
[msg_unexpected_value]
|
||||
other = "{{.name}} takes no {{.key}}="
|
||||
|
||||
[msg_repeated_value]
|
||||
other = "{{.key}}= is given twice"
|
||||
|
||||
[msg_bad_count]
|
||||
other = "count must be a whole number, not {{.value}}"
|
||||
@@ -0,0 +1,11 @@
|
||||
// Package locales embeds devvm's message files, one per language
|
||||
// (en.toml, ...). internal/msg loads them; go generate ./internal/msg turns
|
||||
// en.toml into Go functions.
|
||||
package locales
|
||||
|
||||
import "embed"
|
||||
|
||||
// FS holds every *.toml message file.
|
||||
//
|
||||
//go:embed *.toml
|
||||
var FS embed.FS
|
||||
@@ -35,7 +35,9 @@ run = [
|
||||
"markdownlint-cli2 'docs/content/**/*.md'",
|
||||
"vale docs/content",
|
||||
"lychee --offline --no-progress --include-fragments 'docs/content/**/*.md'",
|
||||
# Message links: the check on doc pages linked from locales/en.toml.
|
||||
# Message links: every doc = "page#anchor" in locales/en.toml is a page
|
||||
# and heading in docs/content/docs.
|
||||
"go test ./internal/msg -run '^TestDocLinks$'",
|
||||
]
|
||||
|
||||
[tasks.test]
|
||||
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
# devvm _msg prints a message's text.
|
||||
exec devvm _msg msg_unknown name=x
|
||||
stdout '^no message x$'
|
||||
! stderr .
|
||||
|
||||
# Values are kept as given, spaces and = included.
|
||||
exec devvm _msg msg_unknown 'name=a b=c'
|
||||
stdout '^no message a b=c$'
|
||||
|
||||
# Names mode doesn't change _msg's text.
|
||||
env DEVVM_MESSAGES=names
|
||||
exec devvm _msg msg_unknown name=x
|
||||
stdout '^no message x$'
|
||||
|
||||
# Its errors are messages too: an unknown message, a missing, unexpected or
|
||||
# repeated value, an argument that isn't name=value.
|
||||
! exec devvm _msg nope
|
||||
stderr 'msg_unknown name=nope$'
|
||||
! stdout .
|
||||
! exec devvm _msg msg_unknown
|
||||
stderr 'msg_missing_value key=name name=msg_unknown$'
|
||||
! exec devvm _msg msg_unknown name=x vm=y
|
||||
stderr 'msg_unexpected_value key=vm name=msg_unknown$'
|
||||
! exec devvm _msg msg_unknown name=x name=y
|
||||
stderr 'msg_repeated_value key=name$'
|
||||
! exec devvm _msg msg_unknown x
|
||||
stderr 'msg_not_pair arg=x$'
|
||||
! exec devvm _msg
|
||||
stderr 'requires at least 1 arg'
|
||||
|
||||
# Without names mode, errors are the text.
|
||||
env DEVVM_MESSAGES=
|
||||
! exec devvm _msg nope
|
||||
stderr 'no message nope$'
|
||||
|
||||
# _msg isn't in the help.
|
||||
exec devvm --help
|
||||
! stdout _msg
|
||||
Reference in new issue
Block a user