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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Signed fixtures must keep their bytes on every platform.
selfupdate/testdata/minisign/** -text
2 changes: 2 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Default reviewers for every change.
* @dgrieser
4 changes: 3 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ jobs:
- uses: actions/setup-go@v7
with:
go-version: stable
- run: go run golang.org/x/vuln/cmd/govulncheck@latest ./...
# Pinned like golangci-lint, so a new release cannot fail an
# unchanged commit. The vulnerability database is always current.
- run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./...

cross:
name: Cross-compile
Expand Down
12 changes: 9 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,15 @@ make test-min # run the tests on Go 1.27.0, the oldest supported release
```

Interactive packages (`pick`, `live`, `progress`) are tested without a
terminal. To try them by hand, write a small `main` package in a scratch
directory with a `replace github.com/mittwald/cli-kit => ../cli-kit`
directive.
terminal. To try them by hand, run the demo program:
`go run ./examples/demo --help` lists its commands, and `make demo ARGS=pick`
runs one.

Code that reads untrusted input (escape sequences, archives, signatures,
redaction, style specifications) has fuzz targets. Their seeds run with
`go test`; `make fuzz` runs every target for `FUZZTIME` (30s by default).
Add a target when you add such a parser, and commit any failing input the
fuzzer finds under `testdata/fuzz` together with the fix.

## Ground rules

Expand Down
17 changes: 16 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ GOLANGCI_LINT ?= golangci-lint
# The oldest Go release cli-kit supports; keep it in sync with go.mod.
GO_MIN ?= go1.27.0

.PHONY: all test race cover lint fmt vet cross test-min test-locale tidy-check check
.PHONY: all test race cover lint fmt vet cross test-min test-locale fuzz demo tidy-check check

all: check

Expand Down Expand Up @@ -44,6 +44,21 @@ test-min:
test-locale:
LC_ALL=ja_JP.UTF-8 RUNEWIDTH_EASTASIAN=1 $(GO) test ./...

# Run every fuzz target for FUZZTIME each. Their seed corpora already run
# with the plain tests.
FUZZTIME ?= 30s
fuzz:
@set -e; for pkg in $$($(GO) list ./...); do \
for target in $$($(GO) test -list '^Fuzz' $$pkg | grep '^Fuzz' || true); do \
echo "$$pkg $$target"; \
$(GO) test -run '^$$' -fuzz "^$$target$$" -fuzztime $(FUZZTIME) $$pkg; \
done; \
done

# Try the interactive packages by hand: make demo ARGS=pick
demo:
$(GO) run ./examples/demo $(ARGS)

tidy-check:
$(GO) mod tidy -diff

Expand Down
35 changes: 25 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ compiled into your binary.
| [`table`](https://pkg.go.dev/github.com/mittwald/cli-kit/table) | Tables in plain, framed and Markdown styles, and CSV/TSV records, with spreadsheet formulas escaped on request |
| [`format`](https://pkg.go.dev/github.com/mittwald/cli-kit/format) | An `--output` flag value, JSON/YAML writers driven by the same struct tags, and compact ages ("3h", "5mo") |
| [`ics`](https://pkg.go.dev/github.com/mittwald/cli-kit/ics) | An RFC 5545 iCalendar writer |
| [`secret`](https://pkg.go.dev/github.com/mittwald/cli-kit/secret) | Credentials from flags, files, environment, stdin, the OS keyring or a hidden prompt, and redaction of known and recognizable secrets |
| [`selfupdate`](https://pkg.go.dev/github.com/mittwald/cli-kit/selfupdate) | Self-updates from GitHub Releases or a GitLab package registry, checked against the release's checksums file |
| [`secret`](https://pkg.go.dev/github.com/mittwald/cli-kit/secret) | Credentials from flags, files, environment, stdin, the OS keyring or a hidden prompt |
| [`redact`](https://pkg.go.dev/github.com/mittwald/cli-kit/redact) | Known secrets and recognizable credentials removed from text before it is logged, with the standard library only |
| [`selfupdate`](https://pkg.go.dev/github.com/mittwald/cli-kit/selfupdate) | Self-updates from GitHub Releases or a GitLab package registry, checked against the release's checksums file and, optionally, its minisign signature |
| [`cobrax`](https://pkg.go.dev/github.com/mittwald/cli-kit/cobrax) | Cobra helpers: `--color` and other auto/always/never flags, enum flags, deprecated flag spellings as hidden aliases, hardened, cached and prefix-filtered shell completion with an optional `--install` or a script written to a path, version command |
| [`fsx`](https://pkg.go.dev/github.com/mittwald/cli-kit/fsx) | Files replaced atomically with a chosen mode, refusing a symbolic link in their place |
| [`browser`](https://pkg.go.dev/github.com/mittwald/cli-kit/browser) | A web page opened in the user's browser, http and https URLs only, without a shell |
Expand All @@ -46,6 +47,13 @@ compiled into your binary.

## Examples

To see the interactive packages at work, run the demo program:

```shell
go run github.com/mittwald/cli-kit/examples/demo@latest --help
go run github.com/mittwald/cli-kit/examples/demo@latest pick
```

### Color and terminal

```go
Expand All @@ -65,7 +73,7 @@ fmt.Print(th.PaintDiff(term.Plain(diff))) // a diff from elsewhere: made plain f
fmt.Println(term.Sanitize(jobLog)) // its colors kept, every other escape gone
fmt.Println(term.PlainLine(name)) // one line, no escape sequence, no color
fmt.Println(th.PaintJSON(string(data))) // JSON from encoding/json: keys, strings, numbers, literals
author := theme.Hashed(name, nil) // the same color for the same name, on every run
author := th.Hashed(name) // the same color for the same name, on every run
if term.ShouldLink(links.Mode(), os.Stdout) {
fmt.Println(term.Hyperlink(url, term.PlainLine(name)))
}
Expand Down Expand Up @@ -164,18 +172,24 @@ without a terminal, set `StdinBusy` so that stdin is left alone.
### Self-update

```go
verifier, err := selfupdate.NewMinisign(publicKey) // "RWQ…", from minisign -G
u := &selfupdate.Updater{
Source: &selfupdate.GitHub{Owner: "example", Repo: "tool"},
Current: buildinfo.Get().Version,
Asset: selfupdate.VersionedAssets("tool"),
Source: &selfupdate.GitHub{Owner: "example", Repo: "tool"},
Current: buildinfo.Get().Version,
Asset: selfupdate.VersionedAssets("tool"),
Verifier: verifier, // checksums.txt must carry a valid checksums.txt.minisig
}
res, err := u.Update(ctx, false) // checks the archive against checksums.txt; refuses package-managed installs
```

The checksum detects a corrupted or altered download. It does not protect
against someone who can write the release's files, because the checksums
file is published in the same place. The archive must hold an executable
for the platform, and a credential is only sent to an `https` API address.
The checksum detects a corrupted or altered download. On its own it does
not protect against someone who can write the release's files, because the
checksums file is published in the same place. A `Verifier` closes that
gap: the checksums file must be signed with a key that never touches the
release, such as a minisign key held in a CI secret. The package
documentation shows the GoReleaser `signs` entry. The archive must hold an
executable for the platform, and a credential is only sent to an `https`
API address.

### Files, browser and logs

Expand All @@ -191,6 +205,7 @@ if verbose {
}
logger := slog.New(logx.NewLineHandler(os.Stderr, &logx.Options{Level: level}))
logger.Debug("sent a request", "path", path, "status", status) // plain, credentials redacted
logger.Debug("response", "body", redact.Values(body, token)) // the token the program sent, in any escaped form
```

### Shell completion and version
Expand Down
86 changes: 86 additions & 0 deletions examples/demo/interactive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package main

import (
"errors"
"fmt"
"os"
"strings"

"github.com/spf13/cobra"

"github.com/mittwald/cli-kit/pick"
"github.com/mittwald/cli-kit/theme"
)

// newPickCommand returns the pick command: a list to choose a release from,
// then a typed answer and a hidden one.
func newPickCommand() *cobra.Command {
return &cobra.Command{
Use: "pick",
Short: "Choose from a list, then type a text and a secret",
Args: cobra.NoArgs,
RunE: func(*cobra.Command, []string) error {
return runPick()
},
}
}

func runPick() error {
releases := []pick.Item{
{Cells: []string{"1.4.2", "latest", "2 days ago"}, Action: "deploy", Groups: []string{"stable"}},
{Cells: []string{"1.4.1", "current", "2 weeks ago"}, Action: "redeploy", Groups: []string{"stable"}},
{Cells: []string{"1.5.0-rc.1", "release candidate", "yesterday"}, Action: "try", Groups: []string{"preview"}},
{Cells: []string{"1.3.9", "end of life", "4 months ago"}, Muted: true, Groups: []string{"stable"}},
{Cells: []string{"1.2.0", "withdrawn"}, Disabled: true, Groups: []string{"stable"}},
}
// Views narrow the rows to their groups; Tab switches between them.
_, index, err := pick.SelectView(os.Stdin, os.Stderr, pick.Options{
Title: "Deploy which version of %s?",
Subject: "api",
Note: "Muted rows are old, the withdrawn one cannot be chosen.",
Items: releases,
Views: []pick.View{
{Name: "all"},
{Name: "stable", Groups: []string{"stable"}},
{Name: "preview", Groups: []string{"preview"}},
},
})
switch {
case errors.Is(err, pick.ErrNotATerminal):
fmt.Println("pick needs a terminal: run it without a pipe or redirection.")
return nil
case errors.Is(err, pick.ErrAborted):
fmt.Println("Nothing chosen.")
return nil
case err != nil:
return err
}
th := theme.Active().For(os.Stdout)
fmt.Println("Chose", th.Value.Paint(releases[index].Cells[0]))

note, err := pick.Input(os.Stdin, os.Stderr, pick.InputOptions{
Prompt: "Note for the deployment of %s: ",
// What a user typed is shown as plain text.
Subject: releases[index].Cells[0],
Value: "routine update",
})
if err != nil {
return ignoreAbort(err)
}
token, err := pick.Input(os.Stdin, os.Stderr, pick.InputOptions{Prompt: "Token (hidden): ", Secret: true})
if err != nil {
return ignoreAbort(err)
}
fmt.Printf("Note %q, token of %d characters %s\n",
note, len([]rune(token)), th.Muted.Paint("("+strings.Repeat("•", min(len([]rune(token)), 8))+")"))
return nil
}

// ignoreAbort turns Esc or Ctrl-C at a prompt into a quiet exit.
func ignoreAbort(err error) error {
if errors.Is(err, pick.ErrAborted) {
fmt.Println("Canceled.")
return nil
}
return err
}
77 changes: 77 additions & 0 deletions examples/demo/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Command demo shows the visual packages of cli-kit at work. Run it from the
// module root:
//
// go run ./examples/demo <command>
//
// The commands are:
//
// - pick: choose a release from a list with views and muted rows, then
// type a text answer and a hidden secret (needs a terminal)
// - progress: a progress bar over fake steps, with log lines that step
// around it and a stalled step that counts down its timeout
// - live: a block of lines redrawn in place
// - table: a table in every drawn style, or in the format --output names
// - theme: the color roles, a painted diff, painted JSON, a stable color
// per name and a style read from --style
// - term: hyperlinks, truncation, wrapping and hostile text made safe
// - version: the version, commit and build date
// - completion: shell completion scripts, with --install for bash, zsh
// and fish
//
// Every command keeps its output plain when it does not go to a terminal,
// so piping it through cat shows what a script would read. --color and
// --links take auto, always or never.
package main

import (
"fmt"
"os"

"github.com/spf13/cobra"

"github.com/mittwald/cli-kit/buildinfo"
"github.com/mittwald/cli-kit/cobrax"
"github.com/mittwald/cli-kit/live"
)

func main() {
os.Exit(run())
}

// run builds and executes the command tree. It is separate from main so its
// deferred calls run before the process exits.
func run() int {
// Never leave the cursor hidden or the terminal in raw mode, also when
// the demo is interrupted.
defer live.InstallSignalRestore()()

root := &cobra.Command{
Use: "demo",
Short: "Show the visual packages of cli-kit at work",
SilenceUsage: true,
SilenceErrors: true,
}
cobrax.AddColorFlag(root, "when to use color: auto, always or never")
links := cobrax.AddModeFlag(root, "links", "when to make links: auto, always or never")

info := buildinfo.Get()
cobrax.SetVersion(root, info)
root.AddCommand(
newPickCommand(),
newProgressCommand(),
newLiveCommand(),
newTableCommand(),
newThemeCommand(),
newTermCommand(links),
cobrax.NewVersionCommand(info),
)
cobrax.NoFileArgs(root)
// The completion command exists only once the subcommands are added.
cobrax.AddCompletionInstall(cobrax.HardenCompletion(root))

if err := root.Execute(); err != nil {
fmt.Fprintln(os.Stderr, "demo:", err)
return 1
}
return 0
}
Loading
Loading