parsimony/internal/cli/cli.go
tgiachi 2d8b0ccce6 feat(cli): command-line client for administration
- Add parsimony list, member, held, archive and queue subcommands over the REST API
- Read the token only from PARSIMONY_API_TOKEN; take the URL from --url or PARSIMONY_URL
- Print tables by default and JSON with --json
- Add member import from a file or stdin, reporting failing lines and exiting non-zero
- Require --yes for destructive commands
- Add parsimony serve; keep the old -config invocation working
- Run the CLI inside the container in the end-to-end test
- Test every command against the real API handler; mutation checks over the CLI
2026-11-09 16:57:25 +01:00

312 lines
8.5 KiB
Go

// Package cli is the command-line client for the Parsimony admin API.
package cli
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"text/tabwriter"
"time"
)
// IO bundles the standard streams so tests can drive the CLI.
type IO struct {
In io.Reader
Out, Err io.Writer
}
const usageText = `Usage: parsimony [--url URL] [--json] <command> [arguments]
Administration (talks to the REST API):
list ls show all lists
list add <name@domain> [--title T] create a list
list show <list> show one list
list set <list> [--title T] [--post members|moderated]
[--join open|closed] [--archive public|private|off]
list rm <list> --yes delete a list with its members and archive
member ls <list> [--emails] show subscribers
member add <list> <email> [--name N] subscribe (or re-enable) an address
member rm <list> <email> unsubscribe an address
member import <list> <file|-> subscribe addresses from a file or stdin,
one "email[,name]" per line
held ls <list> messages waiting for moderation
held approve <id> deliver a held message
held discard <id> delete a held message
archive ls <list> [--q TEXT] [--limit N] [--offset N]
archive show <id>
archive rm <id> --yes
queue ls outbound queue
queue rm <id> discard one queued delivery
Daemon:
serve [-config FILE] run the mailing list server
<list> is a list address (dev@example.org) or its numeric id.
Environment:
PARSIMONY_API_TOKEN bearer token for the API (required, never a flag)
PARSIMONY_URL API address, default http://127.0.0.1:8080 (--url overrides)
--json prints the API's JSON instead of tables.
Exit status: 0 success, 1 failure, 2 usage error.
`
// Run executes one CLI invocation and returns the process exit code.
func Run(args []string, io IO, getenv func(string) string) int {
c := &cmd{io: io, getenv: getenv}
fs := newFlagSet("parsimony")
fs.StringVar(&c.url, "url", "", "")
fs.BoolVar(&c.json, "json", false, "")
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
fmt.Fprint(io.Out, usageText)
return 0
}
return c.usageError(err.Error())
}
rest := fs.Args()
if len(rest) == 0 {
fmt.Fprint(io.Err, "usage: parsimony [--url URL] [--json] <command> (see parsimony help)\n")
return 2
}
if rest[0] == "help" {
fmt.Fprint(io.Out, usageText)
return 0
}
commands := map[string]map[string]func([]string) int{
"list": {"ls": c.listLs, "add": c.listAdd, "show": c.listShow, "set": c.listSet, "rm": c.listRm},
"member": {"ls": c.memberLs, "add": c.memberAdd, "rm": c.memberRm, "import": c.memberImport},
"held": {"ls": c.heldLs, "approve": c.heldApprove, "discard": c.heldDiscard},
"archive": {"ls": c.archiveLs, "show": c.archiveShow, "rm": c.archiveRm},
"queue": {"ls": c.queueLs, "rm": c.queueRm},
}
group, ok := commands[rest[0]]
if !ok {
return c.usageError("unknown command %q (see parsimony help)", rest[0])
}
if len(rest) < 2 {
return c.usageError("usage: parsimony %s <subcommand> (see parsimony help)", rest[0])
}
handler, ok := group[rest[1]]
if !ok {
return c.usageError("unknown command %q (see parsimony help)", rest[0]+" "+rest[1])
}
return handler(rest[2:])
}
// cmd holds what every command needs.
type cmd struct {
io IO
getenv func(string) string
url string
json bool
cl *client
}
func (c *cmd) usageError(format string, a ...any) int {
fmt.Fprintf(c.io.Err, "error: "+format+"\n", a...)
return 2
}
func (c *cmd) fail(err error) int {
fmt.Fprintf(c.io.Err, "error: %v\n", err)
return 1
}
// client builds the API client on first use, so usage errors never need a token.
func (c *cmd) client() (*client, error) {
if c.cl != nil {
return c.cl, nil
}
token := c.getenv("PARSIMONY_API_TOKEN")
if token == "" {
return nil, errors.New("PARSIMONY_API_TOKEN is not set")
}
base := c.url
if base == "" {
base = c.getenv("PARSIMONY_URL")
}
if base == "" {
base = "http://127.0.0.1:8080"
}
if _, err := url.Parse(base); err != nil {
return nil, fmt.Errorf("invalid URL %q", base)
}
c.cl = &client{base: strings.TrimRight(base, "/"), token: token, http: &http.Client{Timeout: 30 * time.Second}}
return c.cl, nil
}
// newFlagSet returns a flag set that reports errors itself instead of printing usage.
func newFlagSet(name string) *flag.FlagSet {
fs := flag.NewFlagSet(name, flag.ContinueOnError)
fs.SetOutput(io.Discard)
return fs
}
// parseArgs parses flags that may appear before, between or after positional arguments.
func parseArgs(fs *flag.FlagSet, args []string) ([]string, error) {
var pos []string
for {
if err := fs.Parse(args); err != nil {
return nil, err
}
args = fs.Args()
if len(args) == 0 {
return pos, nil
}
pos = append(pos, args[0])
args = args[1:]
}
}
// --- API client ---------------------------------------------------------------
type client struct {
base, token string
http *http.Client
}
type apiError struct {
status int
message string
}
func (e *apiError) Error() string { return e.message }
// do sends a request and returns the raw response body (nil for 204).
func (cl *client) do(method, path string, body any) (json.RawMessage, error) {
var rd io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
rd = bytes.NewReader(b)
}
req, err := http.NewRequest(method, cl.base+"/api/v1"+path, rd)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+cl.token)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := cl.http.Do(req)
if err != nil {
return nil, fmt.Errorf("cannot reach %s: %w", cl.base, errors.Unwrap(err))
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 300 {
msg := fmt.Sprintf("request failed (%d)", resp.StatusCode)
var e struct{ Error string }
if json.Unmarshal(data, &e) == nil && e.Error != "" {
msg = e.Error
}
return nil, &apiError{status: resp.StatusCode, message: msg}
}
if resp.StatusCode == http.StatusNoContent {
return nil, nil
}
return data, nil
}
func isNotFound(err error) bool {
var ae *apiError
return errors.As(err, &ae) && ae.status == http.StatusNotFound
}
// --- shared types and helpers ---------------------------------------------------
type list struct {
ID int64 `json:"id"`
Address string `json:"address"`
Title string `json:"title"`
PostPolicy string `json:"post_policy"`
JoinPolicy string `json:"join_policy"`
ArchivePolicy string `json:"archive_policy"`
}
// resolveList finds a list by numeric id or by address (case-insensitive).
func (c *cmd) resolveList(ref string) (list, error) {
cl, err := c.client()
if err != nil {
return list{}, err
}
if id, err := strconv.ParseInt(ref, 10, 64); err == nil {
raw, err := cl.do("GET", fmt.Sprintf("/lists/%d", id), nil)
if isNotFound(err) {
return list{}, fmt.Errorf("no such list: %s", ref)
}
if err != nil {
return list{}, err
}
var l list
return l, json.Unmarshal(raw, &l)
}
raw, err := cl.do("GET", "/lists", nil)
if err != nil {
return list{}, err
}
var all []list
if err := json.Unmarshal(raw, &all); err != nil {
return list{}, err
}
for _, l := range all {
if strings.EqualFold(l.Address, ref) {
return l, nil
}
}
return list{}, fmt.Errorf("no such list: %s", ref)
}
// printJSON writes raw API JSON, indented.
func (c *cmd) printJSON(raw json.RawMessage) int {
if raw == nil {
raw = json.RawMessage(`{"status":"ok"}`)
}
var buf bytes.Buffer
if err := json.Indent(&buf, raw, "", " "); err != nil {
return c.fail(err)
}
fmt.Fprintln(c.io.Out, buf.String())
return 0
}
func (c *cmd) table(rows [][]string) {
w := tabwriter.NewWriter(c.io.Out, 0, 8, 2, ' ', 0)
for _, r := range rows {
fmt.Fprintln(w, strings.Join(r, "\t"))
}
w.Flush()
}
func parseID(s string) (int64, bool) {
id, err := strconv.ParseInt(s, 10, 64)
return id, err == nil && id > 0
}
func formatDate(t time.Time) string { return t.UTC().Format("2006-01-02 15:04") }
func formatBytes(n int) string {
switch {
case n < 1024:
return fmt.Sprintf("%d B", n)
case n < 1024*1024:
return fmt.Sprintf("%.1f KB", float64(n)/1024)
}
return fmt.Sprintf("%.1f MB", float64(n)/(1024*1024))
}