From bdc54f11c832bd39797fa4f4c53c0d3413e62ba0 Mon Sep 17 00:00:00 2001 From: John Coffey Date: Mon, 12 Oct 2026 09:11:28 -0700 Subject: [PATCH] The interface: inbuxa on its own, six screens, the plan before anything MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `inbuxa` with no arguments (or `inbuxa install` with no options) opens the installer spec's interface in the terminal: what it found on this machine, the names, which components go here and how, what answers on 80 and 443, the whole plan, and the install. It fills in the same plan.Options the flags do, builds the plan with plan.Build and installs with apply.Run: it is a way of choosing, not a second installer. The plan screen shows the command that does the same without it, and nothing happens until a "y". - Components: what the machine can't do is greyed out with the reason beside it; what it lacks and the installer can add (docker, compose) is offered and added, with --install-deps in the command. The defaults are the flags' defaults. Front ends without a server here point to join. - Reach offers Caddy or your own web server. --proxy snippets is left out: the plan describes it, but nothing writes those files yet (now said in the README). - The install screen ticks off apply's steps with its output underneath, asks before stopping a running install, and ends on the credentials and addresses, printed again once the terminal is given back. - Without root it refuses at the plan, saying why. Without a terminal it says which flags do the same, exit 2. A window under 60x16 says so. The terminal layer is ours and the standard library's (installer spec §8, decision 1): raw mode, size and SIGWINCH through syscall, key decoding, full redraws, NO_COLOR honored, the terminal restored on every way out. Also: the survey's text moved to plan.SurveyText, which the first screen and `inbuxa survey` share; and plan.Available now says host installs of the console and the webmail aren't built, so --console host is refused at the plan instead of after it. Tests: key decoding, fitting and wrapping, and the wizard driven by keys against an installer that changes nothing (defaults, loopback, the server on the host, refusals, root and the y, stopping, a machine without docker, a small window), under -race. e2e/cases/interface.sh drives the binary in a pseudo-terminal on a fresh Debian 13 lab through a whole loopback install: 22/22. install-local, install-host, install-public, status-export and topology pass unchanged. --- README.md | 20 +- cmd/inbuxa/main.go | 137 ++---- e2e/cases/interface.sh | 125 +++++ internal/plan/plan.go | 12 +- internal/plan/survey.go | 101 ++++ internal/tui/install.go | 886 +++++++++++++++++++++++++++++++++++ internal/tui/install_test.go | 278 +++++++++++ internal/tui/keys.go | 104 ++++ internal/tui/keys_test.go | 48 ++ internal/tui/run.go | 109 +++++ internal/tui/term_linux.go | 58 +++ internal/tui/term_other.go | 23 + internal/tui/view.go | 136 ++++++ 13 files changed, 1931 insertions(+), 106 deletions(-) create mode 100644 e2e/cases/interface.sh create mode 100644 internal/plan/survey.go create mode 100644 internal/tui/install.go create mode 100644 internal/tui/install_test.go create mode 100644 internal/tui/keys.go create mode 100644 internal/tui/keys_test.go create mode 100644 internal/tui/run.go create mode 100644 internal/tui/term_linux.go create mode 100644 internal/tui/term_other.go create mode 100644 internal/tui/view.go diff --git a/README.md b/README.md index 89b25d4..bb28808 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ One program that installs the **inbuxa** suite on the machine you run it on: the mail server, the administration console and the webmail, each as a container or on the host, in any mixture. + inbuxa the interface: all of the below, a screen at a time inbuxa survey what this machine is, as the installer sees it inbuxa install --dry-run … what would happen, before any of it does inbuxa install … do it @@ -34,6 +35,17 @@ deliver, with the reason. This is early. What is built: +- **`inbuxa`** on its own (or `inbuxa install` with no options) -- the + interface: six screens, always in the same order. What it found on this + machine; the names; which components go here and how, with what the + machine can't do greyed out and the reason beside it; what answers on 80 + and 443; the whole plan, with the command that does the same without the + interface; and the install, ticking off its steps, ending on the + credentials and addresses, which stay in the terminal afterwards. Nothing + happens until you answer y. It fills in the same options the flags do -- + it is not a second installer -- and it is built on the standard library + alone, like the rest. Without a terminal it says which flags to use. + - **`survey`** -- the machine's facts: distribution, init, whether Docker is usable *by this user*, Node's version, which of the suite's ports are free and what holds the ones that are not, memory, disk, and whether an install @@ -87,9 +99,10 @@ This is early. What is built: installing. It exits non-zero when they disagree, so a machine can be asked in a script whether it still matches itself. -Not built yet: host installs of the console and the webmail, the terminal -interface, `upgrade`, `uninstall`, and moving the server between a -container and the host. The design is in the inbuxa specification (§6.1 and +Not built yet: host installs of the console and the webmail, `join` in the +interface (it is a command for now), `upgrade`, `uninstall`, moving the +server between a container and the host, and `--proxy snippets`, which the +plan describes but nothing writes yet. The design is in the inbuxa specification (§6.1 and the installer draft); the phases are there too. inbuxa install --local --domain example.test --install-deps --yes @@ -130,6 +143,7 @@ is tested on a throwaway virtual machine rather than on anybody's desk: e2e/vm/run.sh e2e/cases/install-public.sh the same with real ports and certificates e2e/vm/run.sh e2e/cases/install-host.sh the server on the host, the rest beside it e2e/vm/run.sh e2e/cases/join.sh front ends joined to a server elsewhere + e2e/vm/run.sh e2e/cases/interface.sh the interface, driven key by key in a terminal e2e/vm/run.sh e2e/cases/topology.sh growing and shrinking from a file e2e/vm/run.sh e2e/cases/status-export.sh intent against reality, and the file OLD_REF= e2e/vm/run.sh e2e/cases/upgrade-volumes.sh diff --git a/cmd/inbuxa/main.go b/cmd/inbuxa/main.go index dacdfd7..2e1879c 100644 --- a/cmd/inbuxa/main.go +++ b/cmd/inbuxa/main.go @@ -28,6 +28,7 @@ import ( "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/plan" "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/state" "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/topology" + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/tui" ) // version is stamped by the release build; a build from a working tree says @@ -36,6 +37,8 @@ var version = "dev" const usage = `inbuxa -- install the inbuxa suite on this machine + inbuxa the interface: the same as install, with the + machine's own facts on screen inbuxa install [flags] install or converge (no flags: the interface) inbuxa join URL [flags] the console and the webmail here, for a server already running at URL @@ -102,12 +105,8 @@ func main() { runtime.GOOS) os.Exit(2) } - if len(os.Args) < 2 { - // The interface is the no-argument case. Until it lands, say so - // plainly rather than pretending: a half-built screen is worse than - // a sentence telling you which flags to use. - fmt.Fprint(os.Stderr, "the interface is not built yet -- run `inbuxa install --help` for the flags\n") - os.Exit(2) + if len(os.Args) < 2 || (os.Args[1] == "install" && len(os.Args) == 2) { + os.Exit(interactive()) } switch os.Args[1] { case "install": @@ -360,6 +359,42 @@ func join(args []string) int { return 0 } +// interactive is the no-argument case: the interface, when there is a +// terminal to show it on. Without one -- a pipe, a CI job -- it says which +// flags do the same, rather than waiting on keys that will never come. +func interactive() int { + if !tui.IsTerminal(os.Stdin) || !tui.IsTerminal(os.Stdout) { + fmt.Fprint(os.Stderr, "no terminal to show the installer in -- run `inbuxa install --help` for the flags that do the same\n") + return 2 + } + w := tui.NewWizard(host.Survey(context.Background()), installer{}) + if err := tui.Run(w, os.Stdin, os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, err.Error()) + return 1 + } + summary, ran, ok := w.Outcome() + if !ran { + return 0 + } + fmt.Println(strings.Join(summary, "\n")) + if !ok { + return 1 + } + return 0 +} + +// installer is what the interface installs with: the same apply.Run and +// apply.Verify the flags use. +type installer struct{} + +func (installer) Run(ctx context.Context, p plan.Plan, f host.Facts, log apply.Log) (*apply.Result, error) { + return apply.Run(ctx, p, f, log) +} + +func (installer) Verify(ctx context.Context, res *apply.Result, o plan.Options, log apply.Log) []string { + return apply.Verify(ctx, res, true, o.Shape(plan.Console) != plan.Skip, o.Shape(plan.Webmail) != plan.Skip, log) +} + // printer is apply's log on the flag path: steps as lines, everything a // command says indented under the step that ran it. type printer struct{} @@ -702,91 +737,5 @@ func shape(s string) (plan.Shape, error) { } // render is the first screen, as text: what this machine is, and what that -// allows. Every line is something a later choice depends on. -func render(f host.Facts) string { - var b strings.Builder - b.WriteString("This machine\n") - os_ := f.OS.Pretty - if os_ == "" { - os_ = "an unrecognized Linux" - } - fmt.Fprintf(&b, " %-22s %s\n", "system", os_) - fmt.Fprintf(&b, " %-22s %s\n", "init", yes(f.Systemd, "systemd", "not systemd -- host installs are unavailable")) - fmt.Fprintf(&b, " %-22s %s\n", "running as", yes(f.Root, "root", "an ordinary user -- installing will fail")) - if f.MemoryMB > 0 { - fmt.Fprintf(&b, " %-22s %d MB\n", "memory", f.MemoryMB) - } - if f.DiskFreeGB > 0 { - fmt.Fprintf(&b, " %-22s %d GB free\n", "disk", f.DiskFreeGB) - } - - runtime := "none: neither docker nor podman is installed" - switch { - case f.Runtime.Usable: - runtime = f.Runtime.Kind + " " + f.Runtime.Version + ", compose " + f.Runtime.Compose - if f.Runtime.Socket != "" { - runtime += ", at " + f.Runtime.Socket - } - case f.Runtime.Present: - runtime = f.Runtime.Kind + " installed but not usable: " + f.Runtime.Why - } - fmt.Fprintf(&b, " %-22s %s\n", "container runtime", runtime) - - glibc := "could not be read" - if f.Glibc.Version != "" { - glibc = f.Glibc.Version - if !f.Glibc.AtLeast(plan.ServerGlibcMajor, plan.ServerGlibcMinor) { - glibc += fmt.Sprintf(" (older than the %d.%d the server binary needs)", plan.ServerGlibcMajor, plan.ServerGlibcMinor) - } - } - fmt.Fprintf(&b, " %-22s %s\n", "glibc", glibc) - - node := "not installed" - switch { - case f.Node.Present && f.Node.Major >= 22: - node = f.Node.Version + " at " + f.Node.Path - case f.Node.Present: - node = f.Node.Version + " (too old for a host install of the webmail)" - } - fmt.Fprintf(&b, " %-22s %s\n", "node", node) - if f.Existing != "" { - fmt.Fprintf(&b, " %-22s %s\n", "existing install", f.Existing) - } - - b.WriteString("\nPorts\n") - for _, p := range f.Ports { - state := "free" - switch { - case p.Free: - case p.Unknown: - state = "cannot tell without root" - default: - state = "held" - if p.Holder != "" { - state += " by " + p.Holder - } - } - fmt.Fprintf(&b, " %-6d %-42s %s\n", p.Number, p.For, state) - } - - b.WriteString("\nWhat this machine allows\n") - for _, c := range []plan.Component{plan.Server, plan.Console, plan.Webmail} { - var shapes []string - for _, s := range []plan.Shape{plan.Container, plan.Host} { - if a := plan.Available(f, c, s); a.OK { - shapes = append(shapes, string(s)) - } else { - shapes = append(shapes, fmt.Sprintf("%s (no: %s)", s, a.Why)) - } - } - fmt.Fprintf(&b, " %-10s %s\n", c, strings.Join(shapes, " ")) - } - return b.String() -} - -func yes(b bool, t, f string) string { - if b { - return t - } - return f -} +// allows. The interface's first screen is the same text. +func render(f host.Facts) string { return plan.SurveyText(f) } diff --git a/e2e/cases/interface.sh b/e2e/cases/interface.sh new file mode 100644 index 0000000..8a40605 --- /dev/null +++ b/e2e/cases/interface.sh @@ -0,0 +1,125 @@ +#!/bin/bash +# SPDX-FileCopyrightText: 2026 Coffey Labs LLC +# SPDX-License-Identifier: AGPL-3.0-or-later +# +# The interface, driven the way a person drives it: `inbuxa` with no +# arguments in a terminal (a pseudo-terminal here), keys pressed one screen at +# a time, on a machine with nothing on it. Loopback evaluation, everything +# else as it comes. +# +# What only the interface can get wrong is checked: each screen arrives, the +# machine's missing container runtime is offered rather than refused, the +# plan shows the command that does the same, nothing happens before the "y", +# the install finishes on screen, the terminal is given back, and the +# summary is left in it. Then what install-local.sh checks of the result. +# +# Run from the host with: e2e/vm/run.sh e2e/cases/interface.sh +set -uo pipefail + +pass=0; fail=0 +ok() { echo " ok $*"; pass=$((pass+1)); } +bad() { echo " FAIL $*"; fail=$((fail+1)); } + +DIR=/var/lib/inbuxa +command -v python3 >/dev/null || { bad "no python3 on this machine to drive a terminal with"; echo "==> $pass passed, $fail failed"; exit 1; } + +cat > /tmp/drive.py <<'PY' +import os, pty, re, select, struct, sys, time, fcntl, termios + +pid, fd = pty.fork() +if pid == 0: + os.environ["TERM"] = "xterm-256color" + os.execv("/tmp/inbuxa", ["/tmp/inbuxa"]) +fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 32, 110, 0, 0)) + +seen = "" +def plain(s): + return re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", s) +def pump(t): + global seen + end = time.time() + t + while time.time() < end: + r, _, _ = select.select([fd], [], [], 0.1) + if r: + try: + seen += os.read(fd, 65536).decode("utf-8", "replace") + except OSError: + return False + return True +def frame(): + return plain(seen.split("\x1b[H")[-1]) +def wait_for(text, timeout, label): + # Words, not lines: the interface wraps to the window, and a phrase can + # be split across two lines of it. + end = time.time() + timeout + while time.time() < end: + if text in " ".join(frame().replace("|", " ").split()): + print("OK", label); return True + if not pump(0.5): + break + print("FAIL", label, "-- never saw:", text) + print("\n".join(" | " + l for l in frame().split("\r\n")[:30])) + return False +def keys(s): + os.write(fd, s.encode()); pump(0.4) + +ENTER, DOWN = "\r", "\x1b[B" +ok = wait_for("What this machine allows", 30, "screen 1: what it found") +keys(ENTER) +ok &= wait_for("Where it will be reached", 10, "screen 2: names") +keys(DOWN * 6 + " ") +ok &= wait_for("example.test", 5, "loopback fills an evaluation domain") +keys(ENTER) +ok &= wait_for("What goes on this machine", 10, "screen 3: components") +ok &= wait_for("will install what is missing", 5, "the missing runtime is offered, not refused") +keys(ENTER) +ok &= wait_for("publishes nothing", 10, "screen 4: reach, on loopback") +keys(ENTER) +ok &= wait_for("Nothing has happened yet", 10, "screen 5: the plan") +keys("\x1b[6~" * 4) +ok &= wait_for("--local --domain example.test --install-deps --yes", 5, "the plan shows the command that does the same") +keys(ENTER) +ok &= wait_for("Install now?", 5, "a confirmation before anything happens") +print("OK nothing installed before the y" if not os.path.exists("/var/lib/inbuxa/compose.yaml") else "FAIL something was written before the y") +keys("y") +ok &= wait_for("Done.", 1500, "screen 6: the install finishes on screen") +keys("q") +pump(2) +after = plain(seen.split("\x1b[?1049l")[-1]) if "\x1b[?1049l" in seen else "" +print("OK the terminal is given back" if "\x1b[?1049l" in seen and "\x1b[?25h" in seen else "FAIL the terminal was not restored") +print("OK the summary is left in the terminal" if "administrator" in after and "credentials.txt" in after else "FAIL no summary after the interface closed: " + repr(after[-300:])) +_, status = os.waitpid(pid, 0) +code = os.waitstatus_to_exitcode(status) +print(("OK" if code == 0 else "FAIL") + f" exit status {code}") +PY + +echo "==> the interface, from a machine with nothing on it" +OUT="$(python3 /tmp/drive.py 2>&1)" +while IFS= read -r line; do + case "$line" in + OK\ *) ok "${line#OK }" ;; + FAIL\ *) bad "${line#FAIL }" ;; + *) echo "$line" ;; + esac +done <<<"$OUT" + +echo +echo "==> what it installed" +rt() { command -v docker >/dev/null 2>&1 && echo docker || echo podman; } +STATE="$($(rt) compose -f $DIR/compose.yaml ps --format '{{.Service}} {{.State}}' 2>/dev/null)" +for s in server console webmail; do + grep -q "^$s running" <<<"$STATE" && ok "$s is running" || { bad "$s is not running"; echo "$STATE" | sed 's/^/ /'; } +done +[ "$(stat -c %a $DIR/credentials.txt 2>/dev/null)" = 600 ] && ok "credentials.txt, 600" || bad "credentials.txt missing or not 600" +grep -q '"shapes"' /etc/inbuxa/install.json 2>/dev/null && ok "the install is recorded" || bad "no install record" +/tmp/inbuxa status >/dev/null 2>&1 && ok "status: intent and reality agree" || bad "status disagrees" +curl -fsS http://127.0.0.1:8080/api/health 2>/dev/null | grep -q '"ok":true' && ok "the webmail is healthy" || bad "the webmail is not healthy" + +echo +echo "==> without a terminal it says which flags do the same" +OUT="$(/tmp/inbuxa &1)"; rc=$? +[ $rc -eq 2 ] && grep -q "install --help" <<<"$OUT" && ok "no terminal: a sentence, exit 2" || bad "no terminal: exit $rc, $OUT" + +echo +echo "==> $pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/internal/plan/plan.go b/internal/plan/plan.go index b6e9552..98d4e97 100644 --- a/internal/plan/plan.go +++ b/internal/plan/plan.go @@ -184,16 +184,10 @@ func Available(f host.Facts, c Component, s Shape) Availability { } return Availability{OK: true} case Console: - // Static files behind whatever serves them: nothing to run. - return Availability{OK: true} + return Availability{Why: "not built yet: the console runs in a container for now"} case Webmail: - if !f.Node.Present { - return Availability{Why: "a host install of the webmail needs Node 22 or newer; none is installed"} - } - if f.Node.Major < 22 { - return Availability{Why: fmt.Sprintf("a host install of the webmail needs Node 22 or newer; found %s", f.Node.Version)} - } - return Availability{OK: true} + // Phase 2: a unit with a pinned Node (deps already fetches one). + return Availability{Why: "not built yet: the webmail runs in a container for now"} } } return Availability{Why: "unknown shape"} diff --git a/internal/plan/survey.go b/internal/plan/survey.go new file mode 100644 index 0000000..17471c7 --- /dev/null +++ b/internal/plan/survey.go @@ -0,0 +1,101 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package plan + +import ( + "fmt" + "strings" + + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/host" +) + +// SurveyText is the first screen, as text: what this machine is, and what that +// allows. Every line is something a later choice depends on. +func SurveyText(f host.Facts) string { + var b strings.Builder + b.WriteString("This machine\n") + os_ := f.OS.Pretty + if os_ == "" { + os_ = "an unrecognized Linux" + } + fmt.Fprintf(&b, " %-22s %s\n", "system", os_) + fmt.Fprintf(&b, " %-22s %s\n", "init", yes(f.Systemd, "systemd", "not systemd -- host installs are unavailable")) + fmt.Fprintf(&b, " %-22s %s\n", "running as", yes(f.Root, "root", "an ordinary user -- installing will fail")) + if f.MemoryMB > 0 { + fmt.Fprintf(&b, " %-22s %d MB\n", "memory", f.MemoryMB) + } + if f.DiskFreeGB > 0 { + fmt.Fprintf(&b, " %-22s %d GB free\n", "disk", f.DiskFreeGB) + } + + runtime := "none: neither docker nor podman is installed" + switch { + case f.Runtime.Usable: + runtime = f.Runtime.Kind + " " + f.Runtime.Version + ", compose " + f.Runtime.Compose + if f.Runtime.Socket != "" { + runtime += ", at " + f.Runtime.Socket + } + case f.Runtime.Present: + runtime = f.Runtime.Kind + " installed but not usable: " + f.Runtime.Why + } + fmt.Fprintf(&b, " %-22s %s\n", "container runtime", runtime) + + glibc := "could not be read" + if f.Glibc.Version != "" { + glibc = f.Glibc.Version + if !f.Glibc.AtLeast(ServerGlibcMajor, ServerGlibcMinor) { + glibc += fmt.Sprintf(" (older than the %d.%d the server binary needs)", ServerGlibcMajor, ServerGlibcMinor) + } + } + fmt.Fprintf(&b, " %-22s %s\n", "glibc", glibc) + + node := "not installed" + switch { + case f.Node.Present && f.Node.Major >= 22: + node = f.Node.Version + " at " + f.Node.Path + case f.Node.Present: + node = f.Node.Version + " (too old for a host install of the webmail)" + } + fmt.Fprintf(&b, " %-22s %s\n", "node", node) + if f.Existing != "" { + fmt.Fprintf(&b, " %-22s %s\n", "existing install", f.Existing) + } + + b.WriteString("\nPorts\n") + for _, p := range f.Ports { + state := "free" + switch { + case p.Free: + case p.Unknown: + state = "cannot tell without root" + default: + state = "held" + if p.Holder != "" { + state += " by " + p.Holder + } + } + fmt.Fprintf(&b, " %-6d %-42s %s\n", p.Number, p.For, state) + } + + b.WriteString("\nWhat this machine allows\n") + for _, c := range []Component{Server, Console, Webmail} { + var shapes []string + for _, s := range []Shape{Container, Host} { + if a := Available(f, c, s); a.OK { + shapes = append(shapes, string(s)) + } else { + shapes = append(shapes, fmt.Sprintf("%s (no: %s)", s, a.Why)) + } + } + fmt.Fprintf(&b, " %-10s %s\n", c, strings.Join(shapes, " ")) + } + return b.String() +} + +func yes(b bool, t, f string) string { + if b { + return t + } + return f +} diff --git a/internal/tui/install.go b/internal/tui/install.go new file mode 100644 index 0000000..32948fb --- /dev/null +++ b/internal/tui/install.go @@ -0,0 +1,886 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package tui + +// The installer's interface: six screens, always in this order, with the +// plan in front of the operator before anything happens (installer spec §4). +// +// It is a way of filling in the flags with the machine's own facts on +// screen, not a second implementation. Every screen writes into the same +// plan.Options the flags do, the plan is plan.Build's, the install is +// apply.Run's, and the plan screen shows the command that would do the same +// without the interface. + +import ( + "context" + "fmt" + "io" + "path/filepath" + "strings" + "sync" + + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/apply" + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/host" + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/plan" +) + +const ( + screenFound = iota + screenNames + screenComponents + screenReach + screenPlan + screenApply +) + +var screenTitles = []string{"What it found", "Names", "Components", "Reach", "The plan", "Install"} + +// Installer carries out an install. In the program it is apply.Run and +// apply.Verify; tests give it something that changes nothing. +type Installer interface { + Run(ctx context.Context, p plan.Plan, f host.Facts, log apply.Log) (*apply.Result, error) + Verify(ctx context.Context, res *apply.Result, o plan.Options, log apply.Log) []string +} + +// Wizard is the interface's state. +type Wizard struct { + Facts host.Facts + Installer Installer + + o plan.Options + screen int + scroll int + message string // a refusal or a hint, shown above the footer + + fields []*field + focus int + + row int + shapes map[plan.Component]plan.Shape + + proxy int // 0 caddy, 1 your own + + built plan.Plan + buildErr error + confirming bool + + progress *progress + cancel context.CancelFunc + stopping bool + changed chan struct{} +} + +type field struct { + label, hint string + value []rune + cursor int + toggle bool // a yes/no field, in value "yes" or "" + placeholder func(o plan.Options) string +} + +func (f *field) text() string { return string(f.value) } + +// NewWizard starts at the first screen with what the flags default to. +func NewWizard(f host.Facts, inst Installer) *Wizard { + w := &Wizard{Facts: f, Installer: inst, changed: make(chan struct{}, 1)} + w.o.Dir = "/var/lib/inbuxa" + under := func(prefix string) func(plan.Options) string { + return func(o plan.Options) string { + if o.Domain == "" { + return prefix + "DOMAIN" + } + return prefix + o.Domain + } + } + w.fields = []*field{ + {label: "Mail domain", hint: "the domain people's addresses are at", placeholder: func(plan.Options) string { return "example.com" }}, + {label: "Mail server", hint: "the server's own name, which MX points at", placeholder: under("mail.")}, + {label: "Console", hint: "where the administration console is served", placeholder: under("admin.")}, + {label: "Webmail", hint: "where people read their mail", placeholder: under("webmail.")}, + {label: "ACME contact", hint: "where the certificate authority writes about certificates", placeholder: under("postmaster@")}, + {label: "Directory", hint: "where the installation lives", value: []rune(w.o.Dir)}, + {label: "Try it on loopback", hint: "no public ports, no certificates, no DNS: an evaluation on this machine", toggle: true}, + } + for _, f := range w.fields { + f.cursor = len(f.value) + } + w.shapes = map[plan.Component]plan.Shape{plan.Server: plan.Container, plan.Console: plan.Container, plan.Webmail: plan.Container} + for _, c := range []plan.Component{plan.Server, plan.Console, plan.Webmail} { + w.shapes[c] = w.defaultShape(c) + } + return w +} + +// defaultShape is what the flags default to, a container, wherever the +// machine can run one or the installer can make it able to; the server goes +// on the host only where containers are out of reach altogether. +func (w *Wizard) defaultShape(c plan.Component) plan.Shape { + if _, blocked := w.cellNote(c, plan.Container); !blocked { + return plan.Container + } + if c == plan.Server && plan.Available(w.Facts, c, plan.Host).OK { + return plan.Host + } + return plan.Container +} + +// Changed is when an install moved on. +func (w *Wizard) Changed() <-chan struct{} { return w.changed } + +func (w *Wizard) poke() { + select { + case w.changed <- struct{}{}: + default: + } +} + +// Options is what the screens filled in, as the flags would have. +func (w *Wizard) Options() plan.Options { + o := w.o + o.Domain = strings.TrimSpace(w.fields[0].text()) + o.MailHost = strings.TrimSpace(w.fields[1].text()) + o.ConsoleHost = strings.TrimSpace(w.fields[2].text()) + o.WebmailHost = strings.TrimSpace(w.fields[3].text()) + o.ACMEEmail = strings.TrimSpace(w.fields[4].text()) + o.Dir = strings.TrimSpace(w.fields[5].text()) + o.Local = w.fields[6].text() == "yes" + o.Proxy = []string{"caddy", "none"}[w.proxy] + o.Choices = nil + for _, c := range []plan.Component{plan.Server, plan.Console, plan.Webmail} { + o.Choices = append(o.Choices, plan.Choice{Component: c, Shape: w.shapes[c]}) + } + // What the machine lacks for the shapes chosen is installed rather + // than refused: the components screen says what that will be. + o.InstallDeps = len(w.needs(o)) > 0 + return o +} + +func (w *Wizard) needs(o plan.Options) []string { + p, _ := plan.Build(w.Facts, withDeps(o)) + var names []string + for _, n := range p.Needs { + names = append(names, n.Name) + } + return names +} + +func withDeps(o plan.Options) plan.Options { + o.InstallDeps = true + if o.Domain == "" && !o.Local { + o.Domain = "example.com" // enough to build a plan to read the needs from + } + return o +} + +// Update handles one key. +func (w *Wizard) Update(k Key) bool { + if w.screen == screenApply { + return w.updateApply(k) + } + if k.Kind == KeyCtrlC { + return true + } + if w.confirming { + switch { + case k.Kind == KeyRune && (k.Rune == 'y' || k.Rune == 'Y'): + w.confirming = false + w.startInstall() + default: + w.confirming = false + w.message = "Nothing has happened." + } + return false + } + w.message = "" + // q quits everywhere but in a text field, where it is a letter + if k.Kind == KeyRune && k.Rune == 'q' && !(w.screen == screenNames && !w.fields[w.focus].toggle) { + return true + } + if k.Kind == KeyEsc && w.screen > screenFound { + w.screen-- + w.scroll = 0 + return false + } + switch w.screen { + case screenFound: + w.updateScroll(k) + if k.Kind == KeyEnter { + w.next() + } + case screenNames: + w.updateNames(k) + case screenComponents: + w.updateComponents(k) + case screenReach: + w.updateReach(k) + case screenPlan: + w.updateScroll(k) + if k.Kind == KeyEnter { + switch { + case w.buildErr != nil: + w.message = "The plan can't be carried out as it stands: Esc to go back and change it." + case !w.Facts.Root: + w.message = "Installing needs root: run it again as root (sudo inbuxa). Nothing has happened." + default: + w.confirming = true + } + } + } + return false +} + +func (w *Wizard) next() { + w.screen++ + w.scroll = 0 + if w.screen == screenPlan { + w.built, w.buildErr = plan.Build(w.Facts, w.Options()) + } +} + +func (w *Wizard) updateScroll(k Key) { + switch k.Kind { + case KeyUp: + w.scroll-- + case KeyDown: + w.scroll++ + case KeyPgUp: + w.scroll -= 10 + case KeyPgDn: + w.scroll += 10 + case KeyHome: + w.scroll = 0 + } + if w.scroll < 0 { + w.scroll = 0 + } +} + +func (w *Wizard) updateNames(k Key) { + f := w.fields[w.focus] + switch k.Kind { + case KeyUp, KeyBackTab: + if w.focus > 0 { + w.focus-- + } + case KeyDown, KeyTab: + if w.focus < len(w.fields)-1 { + w.focus++ + } + case KeyEnter: + if w.focus < len(w.fields)-1 { + w.focus++ + return + } + if why := w.namesProblem(); why != "" { + w.message = why + return + } + w.next() + case KeyRune: + if f.toggle { + if k.Rune == ' ' || k.Rune == 'y' || k.Rune == 'n' { + w.toggle(f, k.Rune) + } + return + } + f.value = append(f.value[:f.cursor], append([]rune{k.Rune}, f.value[f.cursor:]...)...) + f.cursor++ + case KeyBackspace: + if !f.toggle && f.cursor > 0 { + f.value = append(f.value[:f.cursor-1], f.value[f.cursor:]...) + f.cursor-- + } + case KeyDelete: + if !f.toggle && f.cursor < len(f.value) { + f.value = append(f.value[:f.cursor], f.value[f.cursor+1:]...) + } + case KeyLeft: + if f.cursor > 0 { + f.cursor-- + } + case KeyRight: + if f.cursor < len(f.value) { + f.cursor++ + } + case KeyHome: + f.cursor = 0 + case KeyEnd: + f.cursor = len(f.value) + case KeyCtrlU: + if !f.toggle { + f.value, f.cursor = nil, 0 + } + } +} + +func (w *Wizard) toggle(f *field, r rune) { + on := f.text() == "yes" + switch r { + case 'y': + on = true + case 'n': + on = false + default: + on = !on + } + if on { + f.value = []rune("yes") + // A loopback evaluation still needs a domain for its mailboxes; + // the one reserved for testing is the honest default. + if strings.TrimSpace(w.fields[0].text()) == "" { + w.fields[0].value = []rune("example.test") + w.fields[0].cursor = len(w.fields[0].value) + } + } else { + f.value = nil + } +} + +// namesProblem is why the names can't be used yet, or "". +func (w *Wizard) namesProblem() string { + o := w.Options() + if o.Domain == "" { + return "A mail domain is needed (or turn on \"Try it on loopback\")." + } + for i, v := range []string{o.Domain, o.MailHost, o.ConsoleHost, o.WebmailHost} { + if v != "" && (strings.ContainsAny(v, " /:@") || !strings.Contains(v, ".")) { + return fmt.Sprintf("%s %q is not a name like example.com.", w.fields[i].label, v) + } + } + if o.ACMEEmail != "" && !strings.Contains(o.ACMEEmail, "@") { + return "The ACME contact is an email address." + } + if o.Dir == "" || !filepath.IsAbs(o.Dir) { + return "The directory is a full path, like /var/lib/inbuxa." + } + return "" +} + +var shapeOrder = []plan.Shape{plan.Skip, plan.Container, plan.Host} + +func (w *Wizard) updateComponents(k Key) { + comps := []plan.Component{plan.Server, plan.Console, plan.Webmail} + c := comps[w.row] + idx := 0 + for i, s := range shapeOrder { + if s == w.shapes[c] { + idx = i + } + } + switch k.Kind { + case KeyUp, KeyBackTab: + if w.row > 0 { + w.row-- + } + case KeyDown, KeyTab: + if w.row < len(comps)-1 { + w.row++ + } + case KeyLeft: + if idx > 0 { + w.shapes[c] = shapeOrder[idx-1] + } + case KeyRight: + if idx < len(shapeOrder)-1 { + w.shapes[c] = shapeOrder[idx+1] + } + case KeyRune: + switch k.Rune { + case 's': + w.shapes[c] = plan.Skip + case 'c': + w.shapes[c] = plan.Container + case 'h': + w.shapes[c] = plan.Host + } + case KeyEnter: + if why := w.componentsProblem(); why != "" { + w.message = why + return + } + w.next() + } +} + +// cellNote is what a choice means on this machine: "" when it simply works. +func (w *Wizard) cellNote(c plan.Component, s plan.Shape) (note string, blocked bool) { + if s == plan.Skip { + return "", false + } + a := plan.Available(w.Facts, c, s) + if a.OK { + return "", false + } + // Missing but fixable: the plan installs it, and says so. + o := w.Options() + o.Choices = []plan.Choice{{Component: c, Shape: s}} + if _, err := plan.Build(w.Facts, withDeps(o)); err == nil { + return a.Why + " -- the installer will install what is missing", false + } + return a.Why, true +} + +func (w *Wizard) componentsProblem() string { + any := false + for _, c := range []plan.Component{plan.Server, plan.Console, plan.Webmail} { + if w.shapes[c] != plan.Skip { + any = true + } + if note, blocked := w.cellNote(c, w.shapes[c]); blocked { + return fmt.Sprintf("%s can't be a %s install here: %s", c, w.shapes[c], note) + } + } + if !any { + return "Choose at least one component." + } + if w.shapes[plan.Server] == plan.Skip { + return "Front ends for a server on another machine are installed with inbuxa join, not here: keep the server, or quit and use join." + } + return "" +} + +func (w *Wizard) updateReach(k Key) { + if w.Options().Local { + if k.Kind == KeyEnter { + w.next() + } + return + } + switch k.Kind { + case KeyUp: + w.proxy = 0 + case KeyDown: + w.proxy = 1 + case KeyEnter: + w.next() + } +} + +// View draws the current screen. +func (w *Wizard) View(width, height int) []string { + if width < 60 || height < 16 { + return []string{"", " The window is too small for the installer.", " Make it at least 60 by 16, or press q to quit."} + } + var out []string + steps := make([]string, len(screenTitles)) + for i, t := range screenTitles { + switch { + case i == w.screen: + steps[i] = Bold(Accent(t)) + case i < w.screen: + steps[i] = t + default: + steps[i] = Dim(t) + } + } + out = append(out, " "+Bold("inbuxa installer")+Dim(" · ")+strings.Join(steps, Dim(" › ")), "") + + var body []string + var help string + switch w.screen { + case screenFound: + body = indent(strings.Split(strings.TrimRight(plan.SurveyText(w.Facts), "\n"), "\n")) + help = "Enter: continue ↑↓: scroll q: quit" + case screenNames: + body, help = w.viewNames(width) + case screenComponents: + body, help = w.viewComponents(width) + case screenReach: + body, help = w.viewReach(width) + case screenPlan: + body, help = w.viewPlan(width) + case screenApply: + body, help = w.viewApply(width, height-5) + } + + room := height - len(out) - 3 + if w.screen == screenFound || w.screen == screenPlan { + if max := len(body) - room; w.scroll > max { + w.scroll = max + } + if w.scroll < 0 { + w.scroll = 0 + } + body = body[w.scroll:] + } + if len(body) > room { + body = append(body[:room-1], Dim(" … ↓ for more")) + } + out = append(out, body...) + for len(out) < height-2 { + out = append(out, "") + } + switch { + case w.confirming: + out = append(out, " "+Bold(Warn("Install now? This changes this machine. y to go ahead, any other key not to."))) + case w.message != "": + out = append(out, " "+Warn(w.message)) + default: + out = append(out, "") + } + out = append(out, " "+Dim(help)) + return out +} + +func indent(lines []string) []string { + out := make([]string, len(lines)) + for i, l := range lines { + out[i] = " " + l + } + return out +} + +func (w *Wizard) viewNames(width int) ([]string, string) { + o := w.Options() + local := o.Local + body := []string{" " + Bold("Where it will be reached"), ""} + for i, f := range w.fields { + label := Pad(f.label, 20) + var val string + switch { + case f.toggle: + val = "[ ]" + if f.text() == "yes" { + val = "[x]" + } + if i == w.focus { + val = Reverse(val) + } + case len(f.value) == 0 && i != w.focus: + val = Dim(f.placeholder(o)) + case i == w.focus: + s := f.value + before, at, after := string(s[:f.cursor]), " ", "" + if f.cursor < len(s) { + at, after = string(s[f.cursor]), string(s[f.cursor+1:]) + } + val = before + Reverse(at) + after + if len(f.value) == 0 { + val = Reverse(" ") + Dim(f.placeholder(o)) + } + default: + val = f.text() + } + dimmed := local && i >= 1 && i <= 4 + line := " " + if i == w.focus { + line = Accent("› ") + } + if dimmed { + line += Dim(label + f.text()) + } else { + line += label + val + } + body = append(body, line) + if i == w.focus { + body = append(body, " "+Dim(Pad("", 18)+f.hint)) + } + } + if local { + body = append(body, "", " "+Dim("On loopback the names only name the mail domain; nothing is published.")) + } + return body, "↑↓ Tab: move type to edit Space: toggle Enter: next Esc: back Ctrl-C: quit" +} + +func (w *Wizard) viewComponents(width int) ([]string, string) { + body := []string{" " + Bold("What goes on this machine, and how"), ""} + comps := []plan.Component{plan.Server, plan.Console, plan.Webmail} + labels := map[plan.Component]string{plan.Server: "Mail server", plan.Console: "Console", plan.Webmail: "Webmail"} + for i, c := range comps { + line := " " + if i == w.row { + line = Accent("› ") + } + line += Pad(labels[c], 14) + for _, s := range shapeOrder { + cell := " " + string(s) + " " + _, blocked := w.cellNote(c, s) + switch { + case w.shapes[c] == s && blocked: + cell = Reverse(Bad(cell)) + case w.shapes[c] == s: + cell = Reverse(cell) + case blocked: + cell = Dim(cell) + } + line += cell + " " + } + body = append(body, line) + if note, blocked := w.cellNote(c, w.shapes[c]); note != "" { + style := Dim + if blocked { + style = Bad + } + for _, l := range WrapProse(note, width-20) { + body = append(body, " "+style(l)) + } + } + } + body = append(body, "", + " "+Dim("container: an image, run with this machine's docker or podman"), + " "+Dim("host: the release binary under systemd (the server only, for now)"), + " "+Dim("skip: not on this machine")) + return body, "↑↓: component ←→ or s/c/h: choose Enter: next Esc: back q: quit" +} + +func (w *Wizard) viewReach(width int) ([]string, string) { + body := []string{" " + Bold("What answers on ports 80 and 443"), ""} + if w.Options().Local { + body = append(body, " A loopback evaluation publishes nothing: no proxy, no certificates.", + " The server, the console and the webmail answer on 127.0.0.1 only.") + return body, "Enter: continue Esc: back q: quit" + } + options := []struct{ name, about string }{ + {"Caddy, managed by the installer", "It holds 80 and 443, gets certificates for every name, and passes the server's own certificate challenges through."}, + {"Your own web server", "Nothing here takes 80 or 443. Point yours at 127.0.0.1:8081 for the server, 127.0.0.1:8082 for the console and 127.0.0.1:8080 for the webmail; certificates are yours to arrange."}, + } + for i, opt := range options { + mark := "( )" + if w.proxy == i { + mark = Accent("(•)") + } + line := " " + mark + " " + opt.name + if w.proxy == i { + line = " " + mark + " " + Bold(opt.name) + } + body = append(body, line) + for _, l := range WrapProse(opt.about, width-10) { + body = append(body, " "+Dim(l)) + } + body = append(body, "") + } + return body, "↑↓: choose Enter: next Esc: back q: quit" +} + +func (w *Wizard) viewPlan(width int) ([]string, string) { + if w.buildErr != nil { + body := []string{" " + Bad(Bold("This can't be carried out as it stands")), ""} + for _, l := range WrapProse(w.buildErr.Error(), width-6) { + body = append(body, " "+l) + } + return body, "Esc: back q: quit" + } + body := []string{" " + Dim("Nothing has happened yet. This is everything that will."), ""} + for _, l := range strings.Split(strings.TrimRight(w.built.String(), "\n"), "\n") { + for _, wl := range Wrap(l, width-4) { + body = append(body, " "+wl) + } + } + body = append(body, "", " "+Dim("The same, without the interface:")) + for _, l := range Wrap(Command(w.built.Options), width-6) { + body = append(body, " "+Accent(l)) + } + return body, "Enter: install ↑↓ PgUp PgDn: scroll Esc: back q: quit" +} + +// Command is the flags that do what the screens chose, leaving out what +// would be the default anyway. +func Command(o plan.Options) string { + args := []string{"inbuxa", "install"} + add := func(flag, v, def string) { + if v != "" && v != def { + args = append(args, flag, v) + } + } + if o.Local { + args = append(args, "--local") + } + add("--domain", o.Domain, "") + add("--mail-host", o.MailHost, "mail."+o.Domain) + add("--console-host", o.ConsoleHost, "admin."+o.Domain) + add("--webmail-host", o.WebmailHost, "webmail."+o.Domain) + add("--email", o.ACMEEmail, "postmaster@"+o.Domain) + add("--server", string(o.Shape(plan.Server)), "container") + add("--console", string(o.Shape(plan.Console)), "container") + add("--webmail", string(o.Shape(plan.Webmail)), "container") + if !o.Local { + add("--proxy", o.Proxy, "caddy") + } + add("--dir", o.Dir, "/var/lib/inbuxa") + if o.InstallDeps { + args = append(args, "--install-deps") + } + return strings.Join(append(args, "--yes"), " ") +} + +// ---- the install itself ---- + +// progress is what the install has said so far. apply calls it from its own +// goroutine; the screen reads it under the lock. +type progress struct { + mu sync.Mutex + steps []string + lines []string + done bool + err error + result *apply.Result + problems []string + poke func() +} + +func (p *progress) Step(format string, a ...any) { + p.mu.Lock() + s := fmt.Sprintf(format, a...) + p.steps = append(p.steps, s) + p.lines = append(p.lines, s) + p.mu.Unlock() + p.poke() +} + +func (p *progress) Info(format string, a ...any) { + p.mu.Lock() + p.lines = append(p.lines, " "+fmt.Sprintf(format, a...)) + p.mu.Unlock() + p.poke() +} + +func (p *progress) Out() io.Writer { return lineWriter{p} } + +type lineWriter struct{ p *progress } + +func (l lineWriter) Write(b []byte) (int, error) { + l.p.mu.Lock() + for _, line := range strings.Split(strings.TrimRight(string(b), "\n"), "\n") { + if strings.TrimSpace(line) != "" { + l.p.lines = append(l.p.lines, " "+strings.TrimRight(line, "\r")) + } + } + l.p.mu.Unlock() + l.p.poke() + return len(b), nil +} + +func (w *Wizard) startInstall() { + w.screen = screenApply + w.message = "" + ctx, cancel := context.WithCancel(context.Background()) + w.cancel = cancel + pr := &progress{poke: w.poke} + w.progress = pr + p := w.built + go func() { + res, err := w.Installer.Run(ctx, p, w.Facts, pr) + var problems []string + if err == nil { + pr.Step("checking it works") + problems = w.Installer.Verify(ctx, res, p.Options, pr) + } + pr.mu.Lock() + pr.done, pr.err, pr.result, pr.problems = true, err, res, problems + pr.mu.Unlock() + pr.poke() + }() +} + +func (w *Wizard) updateApply(k Key) bool { + pr := w.progress + pr.mu.Lock() + done := pr.done + pr.mu.Unlock() + if done { + return k.Kind == KeyCtrlC || k.Kind == KeyEnter || (k.Kind == KeyRune && k.Rune == 'q') + } + if w.stopping { + if k.Kind == KeyRune && (k.Rune == 'y' || k.Rune == 'Y') { + w.cancel() + w.message = "Stopping after the step that is running…" + } else { + w.message = "Carrying on." + } + w.stopping = false + return false + } + if k.Kind == KeyCtrlC || (k.Kind == KeyRune && k.Rune == 'q') { + w.stopping = true + w.message = "Stop the install? It will be left part done; running it again picks up from there. y to stop." + } + return false +} + +func (w *Wizard) viewApply(width, room int) ([]string, string) { + pr := w.progress + pr.mu.Lock() + defer pr.mu.Unlock() + var body []string + for i, s := range pr.steps { + mark := Good("✓") + switch { + case i == len(pr.steps)-1 && !pr.done: + mark = Accent("›") + case i == len(pr.steps)-1 && pr.err != nil: + mark = Bad("✗") + } + body = append(body, " "+mark+" "+s) + } + if pr.done { + body = append(body, "") + body = append(body, Summary(pr.result, pr.err, pr.problems)...) + return body, "Enter or q: leave (the summary stays in your terminal)" + } + // Under the steps, the last of what is being said + logRoom := room - len(body) - 2 + if logRoom > 2 { + body = append(body, "", " "+Dim("─ "+strings.Repeat("─", width-8))) + tail := pr.lines + if len(tail) > logRoom-1 { + tail = tail[len(tail)-(logRoom-1):] + } + for _, l := range tail { + body = append(body, " "+Dim(l)) + } + } + return body, "q or Ctrl-C: stop" +} + +// Summary is what the install leaves the operator holding, as the flag path +// prints it; the interface shows it, then prints it again once the terminal +// is back, so it stays in the scrollback. +func Summary(res *apply.Result, err error, problems []string) []string { + var out []string + if err != nil { + out = append(out, " "+Bad(Bold("Stopped: "))+err.Error()) + if res != nil && res.AdminUser != "" { + out = append(out, "", " The administrator was already created; its password is in "+filepath.Join(res.Dir, "credentials.txt")+".") + } + return out + } + head := Good(Bold("Done.")) + if len(problems) > 0 { + head = Warn(Bold("Installed, with problems to look at:")) + } + out = append(out, " "+head+" "+res.Dir) + for _, p := range problems { + out = append(out, " "+Warn("problem: ")+p) + } + row := func(k, v string) { + if v != "" { + out = append(out, fmt.Sprintf(" %-15s%s", k, v)) + } + } + row("administrator", res.AdminUser) + row("first mailbox", res.FirstUser) + row("passwords", filepath.Join(res.Dir, "credentials.txt")) + row("console", res.ConsoleURL) + row("webmail", res.WebmailURL) + if res.Certificate != "" { + row("certificate", "issued by "+res.Certificate) + } + row("dns records", res.ZoneFile) + return out +} + +// Outcome is how the install ended, once the interface has closed: the +// summary to print, and whether it succeeded. +func (w *Wizard) Outcome() (summary []string, ran, ok bool) { + if w.progress == nil { + return nil, false, true + } + pr := w.progress + pr.mu.Lock() + defer pr.mu.Unlock() + if !pr.done { + return []string{" The install was left before it finished; run inbuxa again to pick it up."}, true, false + } + return Summary(pr.result, pr.err, pr.problems), true, pr.err == nil && len(pr.problems) == 0 +} diff --git a/internal/tui/install_test.go b/internal/tui/install_test.go new file mode 100644 index 0000000..a123b4d --- /dev/null +++ b/internal/tui/install_test.go @@ -0,0 +1,278 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package tui + +import ( + "context" + "strings" + "sync" + "testing" + "time" + + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/apply" + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/host" + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/plan" +) + +// debian13 is a machine where everything the installer offers can work. +func debian13(root bool) host.Facts { + return host.Facts{ + OS: host.OSInfo{ID: "debian", VersionID: "13", Pretty: "Debian GNU/Linux 13 (trixie)", Family: "debian"}, + Root: root, + Systemd: true, + Runtime: host.Runtime{Kind: "docker", Present: true, Usable: true, Version: "26.1", Compose: "v2"}, + Glibc: host.Glibc{Version: "2.41", Major: 2, Minor: 41}, + MemoryMB: 4096, DiskFreeGB: 50, + } +} + +// fakeInstaller changes nothing and remembers what it was asked to do. +type fakeInstaller struct { + mu sync.Mutex + got *plan.Plan + fail error + hold chan struct{} // when set, Run waits on it +} + +func (f *fakeInstaller) Run(ctx context.Context, p plan.Plan, _ host.Facts, log apply.Log) (*apply.Result, error) { + f.mu.Lock() + f.got = &p + f.mu.Unlock() + log.Step("writing the deployment into %s", p.Options.Dir) + log.Info("compose.yaml, .env") + if f.hold != nil { + select { + case <-f.hold: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + if f.fail != nil { + return nil, f.fail + } + return &apply.Result{Dir: p.Options.Dir, AdminUser: "admin@" + p.Options.Domain, FirstUser: "postmaster@" + p.Options.Domain}, nil +} + +func (f *fakeInstaller) Verify(context.Context, *apply.Result, plan.Options, apply.Log) []string { + return nil +} + +func typeText(w *Wizard, s string) { + for _, r := range s { + w.Update(Key{Kind: KeyRune, Rune: r}) + } +} + +func press(w *Wizard, kinds ...KeyKind) { + for _, k := range kinds { + w.Update(Key{Kind: k}) + } +} + +// toPlan goes from the first screen to the plan with a domain and the +// defaults everywhere else. +func toPlan(t *testing.T, w *Wizard, domain string) { + t.Helper() + press(w, KeyEnter) // what it found + typeText(w, domain) + for i := 0; i < len(w.fields); i++ { + press(w, KeyEnter) + } + if w.screen != screenComponents { + t.Fatalf("names did not lead on: %q", w.message) + } + press(w, KeyEnter) // components + press(w, KeyEnter) // reach + if w.screen != screenPlan { + t.Fatalf("not at the plan, at %d: %q", w.screen, w.message) + } +} + +func TestTheDefaultsAreTheFlagsDefaults(t *testing.T) { + w := NewWizard(debian13(true), &fakeInstaller{}) + toPlan(t, w, "example.org") + if w.buildErr != nil { + t.Fatal(w.buildErr) + } + if got := Command(w.built.Options); got != "inbuxa install --domain example.org --yes" { + t.Errorf("command = %q", got) + } + o := w.Options() + if o.Proxy != "caddy" || o.Dir != "/var/lib/inbuxa" || o.Local || o.InstallDeps { + t.Errorf("options = %+v", o) + } +} + +func TestLoopbackFillsAnEvaluationDomain(t *testing.T) { + w := NewWizard(debian13(true), &fakeInstaller{}) + press(w, KeyEnter) + for w.focus < len(w.fields)-1 { + press(w, KeyDown) + } + w.Update(Key{Kind: KeyRune, Rune: ' '}) + press(w, KeyEnter, KeyEnter, KeyEnter) + if w.screen != screenPlan || w.buildErr != nil { + t.Fatalf("screen %d, %v, %q", w.screen, w.buildErr, w.message) + } + if got := Command(w.built.Options); got != "inbuxa install --local --domain example.test --yes" { + t.Errorf("command = %q", got) + } +} + +func TestTheServerOnTheHost(t *testing.T) { + w := NewWizard(debian13(true), &fakeInstaller{}) + press(w, KeyEnter) + typeText(w, "example.org") + for i := 0; i < len(w.fields); i++ { + press(w, KeyEnter) + } + w.Update(Key{Kind: KeyRune, Rune: 'h'}) // the server row is first + press(w, KeyEnter, KeyEnter) + if w.buildErr != nil { + t.Fatal(w.buildErr) + } + if got := Command(w.built.Options); !strings.Contains(got, "--server host") { + t.Errorf("command = %q", got) + } +} + +func TestWhatCannotBeBuiltIsRefusedOnItsScreen(t *testing.T) { + w := NewWizard(debian13(true), &fakeInstaller{}) + press(w, KeyEnter) + typeText(w, "example.org") + for i := 0; i < len(w.fields); i++ { + press(w, KeyEnter) + } + press(w, KeyDown) // the console + w.Update(Key{Kind: KeyRune, Rune: 'h'}) // on the host: not built + press(w, KeyEnter) + if w.screen != screenComponents || !strings.Contains(w.message, "not built yet") { + t.Errorf("a console host install got through: screen %d, %q", w.screen, w.message) + } + w.Update(Key{Kind: KeyRune, Rune: 'c'}) + press(w, KeyUp) + w.Update(Key{Kind: KeyRune, Rune: 's'}) // no server + press(w, KeyEnter) + if w.screen != screenComponents || !strings.Contains(w.message, "join") { + t.Errorf("front ends without a server got through: %q", w.message) + } +} + +func TestANameThatIsNotOneIsRefused(t *testing.T) { + w := NewWizard(debian13(true), &fakeInstaller{}) + press(w, KeyEnter) + typeText(w, "not a domain") + for i := 0; i < len(w.fields); i++ { + press(w, KeyEnter) + } + if w.screen != screenNames || !strings.Contains(w.message, "not a name") { + t.Errorf("screen %d, %q", w.screen, w.message) + } + // Ctrl-U clears it, and a real one goes through + w.focus = 0 + press(w, KeyCtrlU) + typeText(w, "example.org") + w.focus = len(w.fields) - 1 + press(w, KeyEnter) + if w.screen != screenComponents { + t.Errorf("a good name was refused: %q", w.message) + } +} + +func TestInstallingNeedsRootAndAYes(t *testing.T) { + inst := &fakeInstaller{} + w := NewWizard(debian13(false), inst) + toPlan(t, w, "example.org") + press(w, KeyEnter) + if w.confirming || !strings.Contains(w.message, "root") { + t.Fatalf("not root, and it offered to install: %q", w.message) + } + + w = NewWizard(debian13(true), inst) + toPlan(t, w, "example.org") + press(w, KeyEnter) + if !w.confirming { + t.Fatal("no confirmation before installing") + } + w.Update(Key{Kind: KeyRune, Rune: 'n'}) + if w.screen != screenPlan || inst.got != nil { + t.Fatal("a no installed anyway") + } + press(w, KeyEnter) + w.Update(Key{Kind: KeyRune, Rune: 'y'}) + waitDone(t, w) + if inst.got == nil || inst.got.Options.Domain != "example.org" { + t.Fatalf("installed %+v", inst.got) + } + summary, ran, ok := w.Outcome() + if !ran || !ok || !strings.Contains(strings.Join(summary, "\n"), "admin@example.org") { + t.Errorf("outcome %v %v %q", ran, ok, summary) + } + view := strings.Join(w.View(100, 30), "\n") + if !strings.Contains(view, "Done.") || !strings.Contains(view, "credentials.txt") { + t.Errorf("the last screen:\n%s", view) + } +} + +func TestStoppingAnInstallAsksFirst(t *testing.T) { + inst := &fakeInstaller{hold: make(chan struct{})} + w := NewWizard(debian13(true), inst) + toPlan(t, w, "example.org") + press(w, KeyEnter) + w.Update(Key{Kind: KeyRune, Rune: 'y'}) + if quit := w.Update(Key{Kind: KeyCtrlC}); quit || !w.stopping { + t.Fatal("Ctrl-C during an install did not ask first") + } + w.Update(Key{Kind: KeyRune, Rune: 'y'}) + waitDone(t, w) + _, ran, ok := w.Outcome() + if !ran || ok { + t.Errorf("a stopped install reported ok=%v", ok) + } +} + +func TestASmallWindowSaysSo(t *testing.T) { + w := NewWizard(debian13(true), &fakeInstaller{}) + if v := strings.Join(w.View(40, 10), " "); !strings.Contains(v, "too small") { + t.Errorf("view = %q", v) + } + for _, line := range w.View(80, 24) { + if Width(Fit(line, 80)) > 80 { + t.Errorf("a line is wider than the window: %q", line) + } + } +} + +func waitDone(t *testing.T, w *Wizard) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + w.progress.mu.Lock() + done := w.progress.done + w.progress.mu.Unlock() + if done { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatal("the install never finished") +} + +func TestNoRuntimeStillDefaultsToContainersTheInstallerWillAdd(t *testing.T) { + f := debian13(true) + f.Runtime = host.Runtime{Why: "no container runtime: neither docker nor podman is installed"} + w := NewWizard(f, &fakeInstaller{}) + for _, c := range []plan.Component{plan.Server, plan.Console, plan.Webmail} { + if w.shapes[c] != plan.Container { + t.Errorf("%s defaults to %s with docker installable, as the flags would not", c, w.shapes[c]) + } + } + toPlan(t, w, "example.org") + if w.buildErr != nil { + t.Fatal(w.buildErr) + } + if got := Command(w.built.Options); got != "inbuxa install --domain example.org --install-deps --yes" { + t.Errorf("command = %q", got) + } +} diff --git a/internal/tui/keys.go b/internal/tui/keys.go new file mode 100644 index 0000000..3b03e90 --- /dev/null +++ b/internal/tui/keys.go @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package tui + +import "unicode/utf8" + +// KeyKind is what a key press was, once its bytes are decoded. +type KeyKind int + +const ( + KeyRune KeyKind = iota // a character, in Key.Rune + KeyEnter + KeyEsc + KeyTab + KeyBackTab + KeyBackspace + KeyDelete + KeyUp + KeyDown + KeyLeft + KeyRight + KeyHome + KeyEnd + KeyPgUp + KeyPgDn + KeyCtrlC + KeyCtrlU // clear the field +) + +// Key is one key press. +type Key struct { + Kind KeyKind + Rune rune +} + +// decode turns what one read from the terminal returned into key presses. A +// terminal sends an escape sequence in one write, so one read holds all of +// it; an Esc on its own is the Esc key. +func decode(b []byte) []Key { + var keys []Key + for len(b) > 0 { + k, n := decodeOne(b) + if n == 0 { + break + } + if k != nil { + keys = append(keys, *k) + } + b = b[n:] + } + return keys +} + +var csi = map[string]KeyKind{ + "A": KeyUp, "B": KeyDown, "C": KeyRight, "D": KeyLeft, + "H": KeyHome, "F": KeyEnd, "Z": KeyBackTab, + "1~": KeyHome, "7~": KeyHome, "4~": KeyEnd, "8~": KeyEnd, + "3~": KeyDelete, "5~": KeyPgUp, "6~": KeyPgDn, +} + +func decodeOne(b []byte) (*Key, int) { + key := func(k KeyKind) *Key { return &Key{Kind: k} } + switch c := b[0]; { + case c == 0x1b: + if len(b) == 1 { + return key(KeyEsc), 1 + } + if b[1] == '[' || b[1] == 'O' { + // CSI or SS3: parameters, then one final byte in @..~ + for i := 2; i < len(b); i++ { + if b[i] >= 0x40 && b[i] <= 0x7e { + if k, ok := csi[string(b[2:i+1])]; ok { + return key(k), i + 1 + } + return nil, i + 1 // a sequence this does not use + } + } + return nil, len(b) + } + return key(KeyEsc), 1 + case c == 0x03: + return key(KeyCtrlC), 1 + case c == 0x15: + return key(KeyCtrlU), 1 + case c == 0x01: + return key(KeyHome), 1 + case c == 0x05: + return key(KeyEnd), 1 + case c == '\r' || c == '\n': + return key(KeyEnter), 1 + case c == '\t': + return key(KeyTab), 1 + case c == 0x7f || c == 0x08: + return key(KeyBackspace), 1 + case c < 0x20: + return nil, 1 // another control character: ignored + } + r, n := utf8.DecodeRune(b) + if r == utf8.RuneError && n <= 1 { + return nil, 1 + } + return &Key{Kind: KeyRune, Rune: r}, n +} diff --git a/internal/tui/keys_test.go b/internal/tui/keys_test.go new file mode 100644 index 0000000..ba739cc --- /dev/null +++ b/internal/tui/keys_test.go @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package tui + +import ( + "reflect" + "testing" +) + +func TestDecode(t *testing.T) { + k := func(kind KeyKind) Key { return Key{Kind: kind} } + r := func(c rune) Key { return Key{Kind: KeyRune, Rune: c} } + for _, tc := range []struct { + in string + want []Key + }{ + {"a", []Key{r('a')}}, + {"é", []Key{r('é')}}, + {"\r", []Key{k(KeyEnter)}}, + {"\x1b", []Key{k(KeyEsc)}}, + {"\x1b[A\x1b[B\x1b[C\x1b[D", []Key{k(KeyUp), k(KeyDown), k(KeyRight), k(KeyLeft)}}, + {"\x1bOA", []Key{k(KeyUp)}}, + {"\x1b[Z", []Key{k(KeyBackTab)}}, + {"\x1b[3~\x1b[5~\x1b[6~", []Key{k(KeyDelete), k(KeyPgUp), k(KeyPgDn)}}, + {"\x1b[1;5C", nil}, // Ctrl-Right: not used, swallowed whole + {"ab\x7f", []Key{r('a'), r('b'), k(KeyBackspace)}}, + {"\x03", []Key{k(KeyCtrlC)}}, + {"\x1bx", []Key{k(KeyEsc), r('x')}}, + } { + if got := decode([]byte(tc.in)); !reflect.DeepEqual(got, tc.want) { + t.Errorf("decode(%q) = %v, want %v", tc.in, got, tc.want) + } + } +} + +func TestFitKeepsEscapesWhole(t *testing.T) { + s := Bold("abcdef") + "ghij" + if got := Width(Fit(s, 5)); got != 5 { + t.Errorf("Fit to 5 is %d wide: %q", got, Fit(s, 5)) + } + if Fit("abc", 5) != "abc" { + t.Error("a short line was changed") + } + if w := Wrap(" one two three four five six", 12); len(w) < 2 || w[1][:4] != " " { + t.Errorf("wrap = %q", w) + } +} diff --git a/internal/tui/run.go b/internal/tui/run.go new file mode 100644 index 0000000..1ecafc4 --- /dev/null +++ b/internal/tui/run.go @@ -0,0 +1,109 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package tui + +import ( + "fmt" + "io" + "os" + "os/signal" + "strings" +) + +// Model is what the terminal shows and what keys do to it. +type Model interface { + // Update handles a key and says whether the program should end. + Update(Key) (quit bool) + // View is the whole screen, as lines; Run fits them to the window. + View(w, h int) []string +} + +// Ticker is a Model that changes on its own -- an install making progress -- +// and says so on the channel, so the screen is redrawn without a key. +type Ticker interface { + Changed() <-chan struct{} +} + +const ( + altScreenOn = "\x1b[?1049h" + altScreenOff = "\x1b[?1049l" + cursorHide = "\x1b[?25l" + cursorShow = "\x1b[?25h" +) + +// Run gives the terminal to m until m says to quit. The terminal is put back +// as it was however Run ends, a panic included: a mail-server installer that +// leaves a terminal in raw mode has failed at the one thing it was trusted +// with first. +func Run(m Model, in, out *os.File) (err error) { + restore, err := rawMode(in) + if err != nil { + return fmt.Errorf("the terminal would not switch to raw mode: %w", err) + } + io.WriteString(out, altScreenOn+cursorHide) + defer func() { + io.WriteString(out, "\x1b[0m"+cursorShow+altScreenOff) + restore() + if r := recover(); r != nil { + err = fmt.Errorf("the interface stopped: %v", r) + } + }() + + keys := make(chan []Key) + go func() { + buf := make([]byte, 256) + for { + n, err := in.Read(buf) + if err != nil { + close(keys) + return + } + keys <- decode(buf[:n]) + } + }() + resized := make(chan os.Signal, 1) + signal.Notify(resized, resizeSignal) + defer signal.Stop(resized) + var changed <-chan struct{} + if t, ok := m.(Ticker); ok { + changed = t.Changed() + } + + for { + draw(m, out) + select { + case ks, ok := <-keys: + if !ok { + return nil + } + for _, k := range ks { + if m.Update(k) { + return nil + } + } + case <-resized: + case <-changed: + } + } +} + +// draw paints the whole frame. Every line is rewritten and the rest of each +// line cleared, which is plenty for six screens of text and leaves no +// half-drawn state to get wrong. +func draw(m Model, out io.Writer) { + w, h := size(os.Stdout) + lines := m.View(w, h) + var b strings.Builder + b.WriteString("\x1b[H") + for i := 0; i < h; i++ { + if i < len(lines) { + b.WriteString(Fit(lines[i], w)) + } + b.WriteString("\x1b[0m\x1b[K") + if i < h-1 { + b.WriteString("\r\n") + } + } + io.WriteString(out, b.String()) +} diff --git a/internal/tui/term_linux.go b/internal/tui/term_linux.go new file mode 100644 index 0000000..2dff589 --- /dev/null +++ b/internal/tui/term_linux.go @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +//go:build linux + +package tui + +import ( + "os" + "syscall" + "unsafe" +) + +// rawMode puts the terminal into raw mode -- keys arrive one at a time, not +// echoed, with no line editing and no signals from Ctrl-C -- and returns how +// to put it back. Nothing else in the program touches termios. +func rawMode(f *os.File) (restore func(), err error) { + fd := f.Fd() + var old syscall.Termios + if _, _, e := syscall.Syscall(syscall.SYS_IOCTL, fd, syscall.TCGETS, uintptr(unsafe.Pointer(&old))); e != 0 { + return nil, e + } + raw := old + raw.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | + syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON + raw.Oflag &^= syscall.OPOST + raw.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN + raw.Cflag &^= syscall.CSIZE | syscall.PARENB + raw.Cflag |= syscall.CS8 + raw.Cc[syscall.VMIN] = 1 + raw.Cc[syscall.VTIME] = 0 + if _, _, e := syscall.Syscall(syscall.SYS_IOCTL, fd, syscall.TCSETS, uintptr(unsafe.Pointer(&raw))); e != 0 { + return nil, e + } + return func() { + syscall.Syscall(syscall.SYS_IOCTL, fd, syscall.TCSETS, uintptr(unsafe.Pointer(&old))) + }, nil +} + +// size is the terminal's width and height in cells. +func size(f *os.File) (w, h int) { + var ws struct{ Row, Col, X, Y uint16 } + if _, _, e := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TIOCGWINSZ, uintptr(unsafe.Pointer(&ws))); e != 0 || ws.Col == 0 { + return 80, 24 + } + return int(ws.Col), int(ws.Row) +} + +// IsTerminal is whether f is a terminal at all, which is what decides between +// the interface and a sentence about the flags. +func IsTerminal(f *os.File) bool { + var t syscall.Termios + _, _, e := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), syscall.TCGETS, uintptr(unsafe.Pointer(&t))) + return e == 0 +} + +// resizeSignal is the signal a terminal sends when its window changes size. +var resizeSignal os.Signal = syscall.SIGWINCH diff --git a/internal/tui/term_other.go b/internal/tui/term_other.go new file mode 100644 index 0000000..0c8d5f2 --- /dev/null +++ b/internal/tui/term_other.go @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +//go:build !linux + +package tui + +import ( + "errors" + "os" + "syscall" +) + +// The installer runs on Linux only (main says so before anything else), but +// it compiles everywhere; these keep it compiling. + +func rawMode(*os.File) (func(), error) { return nil, errors.New("not a Linux terminal") } +func size(*os.File) (int, int) { return 80, 24 } + +// IsTerminal is false off Linux: the interface is never started there. +func IsTerminal(*os.File) bool { return false } + +var resizeSignal os.Signal = syscall.SIGINT diff --git a/internal/tui/view.go b/internal/tui/view.go new file mode 100644 index 0000000..ecb390b --- /dev/null +++ b/internal/tui/view.go @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package tui + +import ( + "os" + "strings" + "unicode/utf8" +) + +// Styles are SGR sequences around text. Colour is dropped when NO_COLOR is +// set (no-color.org); bold, dim and reverse stay, because they carry +// meaning -- what is selected, what can't be chosen -- that the text alone +// would not. +var noColor = os.Getenv("NO_COLOR") != "" + +func sgr(code, s string) string { return "\x1b[" + code + "m" + s + "\x1b[0m" } +func colour(code, s string) string { + if noColor { + return s + } + return sgr(code, s) +} + +func Bold(s string) string { return sgr("1", s) } +func Dim(s string) string { return sgr("2", s) } +func Reverse(s string) string { return sgr("7", s) } +func Accent(s string) string { return colour("36", s) } +func Good(s string) string { return colour("32", s) } +func Bad(s string) string { return colour("31", s) } +func Warn(s string) string { return colour("33", s) } + +// Width is how many cells a string takes, escape sequences not counted. The +// interface's own text is ASCII and Latin; wide characters count as one, +// which only ever costs a cell of padding. +func Width(s string) int { + n := 0 + for i := 0; i < len(s); { + if s[i] == 0x1b { + i = skipEscape(s, i) + continue + } + _, size := utf8.DecodeRuneInString(s[i:]) + i += size + n++ + } + return n +} + +func skipEscape(s string, i int) int { + j := i + 1 + if j < len(s) && s[j] == '[' { + j++ + for j < len(s) && !(s[j] >= 0x40 && s[j] <= 0x7e) { + j++ + } + } + return j + 1 +} + +// Fit cuts a line to w cells, keeping its escape sequences whole and ending +// with an ellipsis when something was cut. +func Fit(s string, w int) string { + if w <= 0 { + return "" + } + if Width(s) <= w { + return s + } + var b strings.Builder + n := 0 + for i := 0; i < len(s); { + if s[i] == 0x1b { + j := skipEscape(s, i) + b.WriteString(s[i:min(j, len(s))]) + i = j + continue + } + _, size := utf8.DecodeRuneInString(s[i:]) + if n == w-1 { + b.WriteString("…") + break + } + b.WriteString(s[i : i+size]) + i += size + n++ + } + b.WriteString("\x1b[0m") + return b.String() +} + +// Wrap breaks plain text into lines of at most w cells, at spaces where it +// can, with continuation lines hung two cells further in, which keeps a +// plan's detail lines readable as one item each. +func Wrap(s string, w int) []string { return wrap(s, w, 2) } + +// WrapProse is Wrap for running text: continuation lines start where the +// first did. +func WrapProse(s string, w int) []string { return wrap(s, w, 0) } + +func wrap(s string, w, hang int) []string { + if w < 10 { + w = 10 + } + var out []string + for _, para := range strings.Split(s, "\n") { + indent := len(para) - len(strings.TrimLeft(para, " ")) + if Width(para) <= w { + out = append(out, para) + continue + } + line := "" + for _, word := range strings.Fields(para) { + switch { + case line == "": + line = strings.Repeat(" ", indent) + word + case Width(line)+1+Width(word) > w: + out = append(out, line) + line = strings.Repeat(" ", indent+hang) + word + default: + line += " " + word + } + } + out = append(out, line) + } + return out +} + +// Pad fills a line out to w cells. +func Pad(s string, w int) string { + if n := Width(s); n < w { + return s + strings.Repeat(" ", w-n) + } + return s +} -- 2.54.0