From 2d8b0ccce683a7f4fa55ecd54644f1ad022e975d Mon Sep 17 00:00:00 2001 From: tgiachi Date: Mon, 9 Nov 2026 16:57:25 +0100 Subject: [PATCH] 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 --- Dockerfile | 2 +- README.md | 28 +- e2e/e2e_test.go | 25 ++ internal/cli/cli.go | 312 ++++++++++++++++++++ internal/cli/cli_test.go | 440 ++++++++++++++++++++++++++++ internal/cli/commands.go | 607 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 1412 insertions(+), 2 deletions(-) create mode 100644 internal/cli/cli.go create mode 100644 internal/cli/cli_test.go create mode 100644 internal/cli/commands.go diff --git a/Dockerfile b/Dockerfile index adf55c7..7481f13 100644 --- a/Dockerfile +++ b/Dockerfile @@ -24,4 +24,4 @@ VOLUME /data EXPOSE 2424 8080 8081 USER 65532:65532 # Mount the config read-only at /etc/parsimony/parsimony.yaml; keep "db: /data/parsimony.db" in it. -ENTRYPOINT ["/parsimony", "-config", "/etc/parsimony/parsimony.yaml"] +ENTRYPOINT ["/parsimony", "serve", "-config", "/etc/parsimony/parsimony.yaml"] diff --git a/README.md b/README.md index 3fdebd2..df11e3b 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ A modern, single-binary mailing list manager: an evolution of Mailman. Public pages hide email addresses. - Per-recipient one-click unsubscribe links (RFC 8058) with signed tokens. - SQLite storage, one YAML config file. +- Command-line client for administration and scripts (`parsimony list|member|held|archive|queue`). - Admin REST API under `/api/v1` (see `docs/openapi.yaml`). - Admin web UI (Vite, React, shadcn/ui) served by the API listener at `/`: lists, settings, members, held queue and archive. @@ -25,7 +26,7 @@ A modern, single-binary mailing list manager: an evolution of Mailman. ``` cp parsimony.example.yaml parsimony.yaml -PARSIMONY_API_TOKEN= go run ./cmd/parsimony -config parsimony.yaml +PARSIMONY_API_TOKEN= go run ./cmd/parsimony serve -config parsimony.yaml ``` The API is disabled when `PARSIMONY_API_TOKEN` is not set. @@ -45,6 +46,31 @@ the unsubscribe links in every message use it. Keep the `api` listener private. curl -H "Authorization: Bearer $PARSIMONY_API_TOKEN" -d '{"name":"dev","domain":"example.org","title":"Dev"}' localhost:8080/api/v1/lists ``` +## Command line + +The same binary is an administration client. It talks to the REST API, so it works against a local or remote daemon. + +``` +export PARSIMONY_API_TOKEN=... # the token is never a flag +export PARSIMONY_URL=http://127.0.0.1:8080 # default; --url overrides + +parsimony list add dev@example.org --title "Developers" +parsimony list set dev@example.org --post moderated --archive public +parsimony member add dev@example.org alice@example.com --name Alice +parsimony member import dev@example.org subscribers.txt # "email[,name]" per line, "-" reads stdin +parsimony held ls dev@example.org +parsimony held approve 12 +parsimony archive ls dev@example.org --q "deploy" +parsimony queue ls +parsimony --json list ls # JSON for scripts +parsimony help +``` + +`` is an address or a numeric id. Destructive commands (`list rm`, `archive rm`) need `--yes`. +Exit status: 0 success, 1 failure (including lines that failed in `member import`), 2 usage error. +`parsimony serve -config FILE` runs the daemon; the old `parsimony -config FILE` form still works. +In the container: `docker exec parsimony /parsimony list ls`. + ## Docker The image runs as an unprivileged user (uid 65532) and works with a read-only root filesystem. diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go index 2f20154..91d2a42 100644 --- a/e2e/e2e_test.go +++ b/e2e/e2e_test.go @@ -519,6 +519,31 @@ func TestWholePath(t *testing.T) { } }) + t.Run("the CLI works inside the read-only container", func(t *testing.T) { + out, err := docker("exec", parsimonyC, "/parsimony", "list", "ls") + if err != nil || !strings.Contains(out, list) { + t.Fatalf("list ls: %v\n%s", err, out) + } + // Bulk import through stdin, as when migrating from Mailman. + imp := exec.Command("docker", "exec", "-i", parsimonyC, "/parsimony", "member", "import", list, "-") + imp.Stdin = strings.NewReader("# exported subscribers\nalice@members.test\nerin@members.test,Erin\n") + b, err := imp.CombinedOutput() + if err != nil || !strings.Contains(string(b), "Imported 2") { + t.Fatalf("member import: %v\n%s", err, b) + } + out, _ = docker("exec", parsimonyC, "/parsimony", "member", "ls", list, "--emails") + if !strings.Contains(out, "erin@members.test") || !strings.Contains(out, "alice@members.test") { + t.Fatalf("members: %s", out) + } + // Failures give a non-zero exit status. + if out, err := docker("exec", parsimonyC, "/parsimony", "list", "show", "ghost@"+domain); err == nil || !strings.Contains(out, "no such list") { + t.Fatalf("an unknown list must fail: %v %s", err, out) + } + if out, err := docker("exec", parsimonyC, "/parsimony", "queue", "ls"); err != nil || !strings.Contains(out, "Pending:") { + t.Fatalf("queue ls: %v %s", err, out) + } + }) + t.Run("the queue ends empty", func(t *testing.T) { waitQueueEmpty(t) }) diff --git a/internal/cli/cli.go b/internal/cli/cli.go new file mode 100644 index 0000000..f279966 --- /dev/null +++ b/internal/cli/cli.go @@ -0,0 +1,312 @@ +// 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] [arguments] + +Administration (talks to the REST API): + list ls show all lists + list add [--title T] create a list + list show show one list + list set [--title T] [--post members|moderated] + [--join open|closed] [--archive public|private|off] + list rm --yes delete a list with its members and archive + + member ls [--emails] show subscribers + member add [--name N] subscribe (or re-enable) an address + member rm unsubscribe an address + member import subscribe addresses from a file or stdin, + one "email[,name]" per line + + held ls messages waiting for moderation + held approve deliver a held message + held discard delete a held message + + archive ls [--q TEXT] [--limit N] [--offset N] + archive show + archive rm --yes + + queue ls outbound queue + queue rm discard one queued delivery + +Daemon: + serve [-config FILE] run the mailing list server + + 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] (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 (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)) +} diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go new file mode 100644 index 0000000..34e8c7c --- /dev/null +++ b/internal/cli/cli_test.go @@ -0,0 +1,440 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "codeberg.org/squidd/parsimony/internal/api" + "codeberg.org/squidd/parsimony/internal/store" +) + +const token = "cli-token" + +type fakeReleaser struct{ released []int64 } + +func (f *fakeReleaser) Release(_ context.Context, id int64) error { + f.released = append(f.released, id) + return nil +} + +type env struct { + s *store.Store + srv *httptest.Server + rel *fakeReleaser +} + +// newEnv serves the real API handler over HTTP: the CLI talks to the real thing. +func newEnv(t *testing.T) *env { + t.Helper() + s, err := store.Open(":memory:") + if err != nil { + t.Fatal(err) + } + rel := &fakeReleaser{} + srv := httptest.NewServer(api.New(s, token, rel)) + t.Cleanup(func() { srv.Close(); s.Close() }) + return &env{s: s, srv: srv, rel: rel} +} + +// run executes the CLI like a shell would and returns exit code, stdout and stderr. +func (e *env) run(t *testing.T, args ...string) (int, string, string) { + t.Helper() + return e.runEnv(t, map[string]string{"PARSIMONY_API_TOKEN": token, "PARSIMONY_URL": e.srv.URL}, "", args...) +} + +func (e *env) runEnv(t *testing.T, vars map[string]string, stdin string, args ...string) (int, string, string) { + t.Helper() + var out, errb bytes.Buffer + code := Run(args, IO{In: strings.NewReader(stdin), Out: &out, Err: &errb}, func(k string) string { return vars[k] }) + return code, out.String(), errb.String() +} + +func (e *env) ok(t *testing.T, args ...string) string { + t.Helper() + code, out, errs := e.run(t, args...) + if code != 0 { + t.Fatalf("%v: exit %d\nstdout: %s\nstderr: %s", args, code, out, errs) + } + return out +} + +func (e *env) fails(t *testing.T, wantCode int, wantErr string, args ...string) { + t.Helper() + code, out, errs := e.run(t, args...) + if code != wantCode { + t.Fatalf("%v: exit %d, want %d\nstdout: %s\nstderr: %s", args, code, wantCode, out, errs) + } + if !strings.Contains(errs, wantErr) { + t.Fatalf("%v: stderr %q lacks %q", args, errs, wantErr) + } + if out != "" { + t.Fatalf("%v: errors must not print to stdout: %q", args, out) + } +} + +func TestHelpAndUsageErrors(t *testing.T) { + e := newEnv(t) + for _, args := range [][]string{{"help"}, {"-h"}, {"--help"}} { + code, out, _ := e.run(t, args...) + if code != 0 || !strings.Contains(out, "list") || !strings.Contains(out, "PARSIMONY_API_TOKEN") { + t.Fatalf("%v: %d %q", args, code, out) + } + } + e.fails(t, 2, "usage") + e.fails(t, 2, "unknown command", "frobnicate") + e.fails(t, 2, "unknown command", "list", "frobnicate") + e.fails(t, 2, "usage: parsimony list add", "list", "add") + e.fails(t, 2, "usage: parsimony member add", "member", "add", "dev@example.org") + e.fails(t, 2, "flag provided but not defined", "list", "ls", "--nope") +} + +func TestAuthAndConnectionProblems(t *testing.T) { + e := newEnv(t) + code, _, errs := e.runEnv(t, map[string]string{"PARSIMONY_URL": e.srv.URL}, "", "list", "ls") + if code != 1 || !strings.Contains(errs, "PARSIMONY_API_TOKEN is not set") { + t.Fatalf("no token: %d %q", code, errs) + } + code, _, errs = e.runEnv(t, map[string]string{"PARSIMONY_API_TOKEN": "wrong", "PARSIMONY_URL": e.srv.URL}, "", "list", "ls") + if code != 1 || !strings.Contains(errs, "invalid or missing token") { + t.Fatalf("wrong token: %d %q", code, errs) + } + code, _, errs = e.runEnv(t, map[string]string{"PARSIMONY_API_TOKEN": token, "PARSIMONY_URL": "http://127.0.0.1:1"}, "", "list", "ls") + if code != 1 || !strings.Contains(errs, "cannot reach") { + t.Fatalf("unreachable: %d %q", code, errs) + } +} + +func TestURLFlagBeatsEnvironmentAndTrailingSlashIsFine(t *testing.T) { + e := newEnv(t) + vars := map[string]string{"PARSIMONY_API_TOKEN": token, "PARSIMONY_URL": "http://127.0.0.1:1"} + code, _, errs := e.runEnv(t, vars, "", "--url", e.srv.URL+"/", "list", "ls") + if code != 0 { + t.Fatalf("--url must win over PARSIMONY_URL: %d %q", code, errs) + } + code, _, errs = e.runEnv(t, map[string]string{"PARSIMONY_API_TOKEN": token}, "", "list", "ls") + if code != 1 || !strings.Contains(errs, "cannot reach") { + t.Fatalf("default URL is the local daemon: %d %q", code, errs) + } +} + +func TestListLifecycle(t *testing.T) { + e := newEnv(t) + if out := e.ok(t, "list", "ls"); !strings.Contains(out, "No lists") { + t.Fatalf("empty: %q", out) + } + out := e.ok(t, "list", "add", "dev@example.org", "--title", "Developers") + if !strings.Contains(out, "Created dev@example.org") { + t.Fatalf("add: %q", out) + } + e.ok(t, "list", "add", "news@example.org") + out = e.ok(t, "list", "ls") + for _, want := range []string{"ID", "ADDRESS", "TITLE", "POST", "JOIN", "ARCHIVE", "dev@example.org", "Developers", "members", "open", "private", "news@example.org"} { + if !strings.Contains(out, want) { + t.Fatalf("ls lacks %q:\n%s", want, out) + } + } + e.fails(t, 1, "already exists", "list", "add", "dev@example.org") + e.fails(t, 2, "name@domain", "list", "add", "nodomain") + e.fails(t, 2, "name@domain", "list", "add", "@example.org") + e.fails(t, 1, "name and domain", "list", "add", "a+b@example.org") + + for _, ref := range []string{"dev@example.org", "DEV@Example.org", "1"} { + out = e.ok(t, "list", "show", ref) + if !strings.Contains(out, "dev@example.org") || !strings.Contains(out, "Developers") || !strings.Contains(out, "archive") { + t.Fatalf("show %s: %q", ref, out) + } + } + e.fails(t, 1, "no such list", "list", "show", "ghost@example.org") + e.fails(t, 1, "no such list", "list", "show", "99") + e.fails(t, 1, "no such list", "list", "show", "notanumber") + + out = e.ok(t, "list", "set", "dev@example.org", "--post", "moderated", "--archive", "public") + if !strings.Contains(out, "Updated dev@example.org") { + t.Fatalf("set: %q", out) + } + l, _ := e.s.FindList("dev@example.org") + if l.PostPolicy != "moderated" || l.ArchivePolicy != "public" || l.JoinPolicy != "open" || l.Title != "Developers" { + t.Fatalf("only the given fields change: %+v", l) + } + e.ok(t, "list", "set", "1", "--title", "Core devs", "--join", "closed") + l, _ = e.s.FindList("dev@example.org") + if l.Title != "Core devs" || l.JoinPolicy != "closed" || l.PostPolicy != "moderated" { + t.Fatalf("%+v", l) + } + e.fails(t, 2, "nothing to change", "list", "set", "dev@example.org") + e.fails(t, 1, "post_policy", "list", "set", "dev@example.org", "--post", "bogus") + e.fails(t, 1, "no such list", "list", "set", "ghost@example.org", "--title", "x") +} + +func TestListRemoveNeedsYes(t *testing.T) { + e := newEnv(t) + e.ok(t, "list", "add", "dev@example.org") + e.fails(t, 2, "--yes", "list", "rm", "dev@example.org") + if _, err := e.s.FindList("dev@example.org"); err != nil { + t.Fatal("without --yes nothing is deleted") + } + out := e.ok(t, "list", "rm", "dev@example.org", "--yes") + if !strings.Contains(out, "Deleted dev@example.org") { + t.Fatalf("rm: %q", out) + } + if _, err := e.s.FindList("dev@example.org"); err == nil { + t.Fatal("list must be gone") + } + e.fails(t, 1, "no such list", "list", "rm", "dev@example.org", "--yes") +} + +func TestJSONOutputIsValidAndStable(t *testing.T) { + e := newEnv(t) + e.ok(t, "list", "add", "dev@example.org", "--title", "Dev") + var lists []map[string]any + if err := json.Unmarshal([]byte(e.ok(t, "--json", "list", "ls")), &lists); err != nil || len(lists) != 1 || lists[0]["address"] != "dev@example.org" { + t.Fatalf("json ls: %v %v", err, lists) + } + var one map[string]any + if err := json.Unmarshal([]byte(e.ok(t, "--json", "list", "show", "dev@example.org")), &one); err != nil || one["title"] != "Dev" { + t.Fatalf("json show: %v %v", err, one) + } + e.s.CreateList("empty", "example.org", "E") + var ms []any + if err := json.Unmarshal([]byte(e.ok(t, "--json", "member", "ls", "empty@example.org")), &ms); err != nil || ms == nil || len(ms) != 0 { + t.Fatalf("an empty result is [] in JSON: %v %v", err, ms) + } +} + +func TestMembers(t *testing.T) { + e := newEnv(t) + e.ok(t, "list", "add", "dev@example.org") + if out := e.ok(t, "member", "ls", "dev@example.org"); !strings.Contains(out, "No members") { + t.Fatalf("empty: %q", out) + } + out := e.ok(t, "member", "add", "dev@example.org", "Alice@Example.com", "--name", "Alice") + if !strings.Contains(out, "Added alice@example.com") { + t.Fatalf("add: %q", out) + } + e.ok(t, "member", "add", "1", "bob@example.com") + out = e.ok(t, "member", "ls", "dev@example.org") + for _, want := range []string{"ADDRESS", "NAME", "STATUS", "alice@example.com", "Alice", "bob@example.com", "active"} { + if !strings.Contains(out, want) { + t.Fatalf("ls lacks %q:\n%s", want, out) + } + } + if out := e.ok(t, "member", "ls", "dev@example.org", "--emails"); out != "alice@example.com\nbob@example.com\n" { + t.Fatalf("--emails: %q", out) + } + e.fails(t, 1, "valid email", "member", "add", "dev@example.org", "not-an-address") + e.fails(t, 1, "no such list", "member", "add", "ghost@example.org", "a@b.com") + + // Bounce state is visible, and adding again re-enables. + l, _ := e.s.FindList("dev@example.org") + ms, _ := e.s.Members(l.ID) + e.s.RecordHardBounce(ms[1].ID, 3) + out = e.ok(t, "member", "ls", "dev@example.org") + if !strings.Contains(out, "active (1 bounce)") { + t.Fatalf("a member with a few bounces is still active: %s", out) + } + for i := 0; i < 3; i++ { + e.s.RecordHardBounce(ms[0].ID, 3) + } + out = e.ok(t, "member", "ls", "dev@example.org") + if !strings.Contains(out, "disabled (3 bounces)") { + t.Fatalf("bounce state: %s", out) + } + e.ok(t, "member", "add", "dev@example.org", "alice@example.com") + if out = e.ok(t, "member", "ls", "dev@example.org"); strings.Contains(out, "disabled") { + t.Fatalf("re-adding re-enables: %s", out) + } + + out = e.ok(t, "member", "rm", "dev@example.org", "bob@example.com") + if !strings.Contains(out, "Removed bob@example.com") { + t.Fatalf("rm: %q", out) + } + e.fails(t, 1, "not found", "member", "rm", "dev@example.org", "bob@example.com") + if ok, _ := e.s.IsMember(l.ID, "alice@example.com"); !ok { + t.Fatal("alice must stay") + } +} + +func TestMemberImport(t *testing.T) { + e := newEnv(t) + e.ok(t, "list", "add", "dev@example.org") + input := "# subscribers exported from Mailman\n\nalice@example.com, Alice Smith\nbob@example.com\n carol@example.com ,Carol \nnot-an-address\ndave@example.com,Dave,extra\n" + code, out, errs := e.runEnv(t, map[string]string{"PARSIMONY_API_TOKEN": token, "PARSIMONY_URL": e.srv.URL}, input, "member", "import", "dev@example.org", "-") + if code != 1 { + t.Fatalf("a failed line must make the exit code non-zero, got %d", code) + } + if !strings.Contains(out, "Imported 4") || !strings.Contains(out, "1 failed") { + t.Fatalf("summary: %q", out) + } + if !strings.Contains(errs, "line 6") || !strings.Contains(errs, "not-an-address") || !strings.Contains(errs, "valid email") { + t.Fatalf("the failing line is reported with its number: %q", errs) + } + l, _ := e.s.FindList("dev@example.org") + ms, _ := e.s.Members(l.ID) + names := map[string]string{} + for _, m := range ms { + names[m.Address] = m.DisplayName + } + if len(ms) != 4 || names["alice@example.com"] != "Alice Smith" || names["carol@example.com"] != "Carol" || names["dave@example.com"] != "Dave" { + t.Fatalf("members: %v", names) + } + + // Importing again is idempotent; a file works as well as stdin. + path := t.TempDir() + "/subs.txt" + if err := os.WriteFile(path, []byte("alice@example.com\nerin@example.com\n"), 0o600); err != nil { + t.Fatal(err) + } + out = e.ok(t, "member", "import", "dev@example.org", path) + if !strings.Contains(out, "Imported 2") || strings.Contains(out, "failed") { + t.Fatalf("file import: %q", out) + } + e.fails(t, 1, "no such file", "member", "import", "dev@example.org", "/nonexistent/file.txt") + e.fails(t, 1, "no such list", "member", "import", "ghost@example.org", path) +} + +func TestHeldQueue(t *testing.T) { + e := newEnv(t) + e.ok(t, "list", "add", "dev@example.org") + l, _ := e.s.FindList("dev@example.org") + if out := e.ok(t, "held", "ls", "dev@example.org"); !strings.Contains(out, "Nothing is held") { + t.Fatalf("empty: %q", out) + } + id1, _ := e.s.HoldMessage(l.ID, "bob@x.com", []byte("From: Bob \r\nSubject: First held\r\n\r\nbody")) + id2, _ := e.s.HoldMessage(l.ID, "eve@x.com", []byte("Subject: Second held\r\n\r\nbody")) + id3, _ := e.s.HoldMessage(l.ID, "anon@x.com", []byte("From: anon@x.com\r\n\r\nno subject here")) + out := e.ok(t, "held", "ls", "dev@example.org") + for _, want := range []string{"ID", "FROM", "SUBJECT", "SIZE", "bob@x.com", "First held", "eve@x.com", "Second held", "(no subject)"} { + if !strings.Contains(out, want) { + t.Fatalf("held ls lacks %q:\n%s", want, out) + } + } + out = e.ok(t, "held", "approve", fmt.Sprint(id1)) + if !strings.Contains(out, "Approved") || len(e.rel.released) != 1 || e.rel.released[0] != id1 { + t.Fatalf("approve: %q %v", out, e.rel.released) + } + out = e.ok(t, "held", "discard", fmt.Sprint(id2)) + if !strings.Contains(out, "Discarded") { + t.Fatalf("discard: %q", out) + } + e.ok(t, "held", "discard", fmt.Sprint(id3)) + if h, _ := e.s.ListHeld(l.ID); len(h) != 1 { // the approved one stays: the fake releaser only records it + t.Fatalf("held left: %d", len(h)) + } + e.fails(t, 1, "not found", "held", "discard", fmt.Sprint(id2)) + e.fails(t, 2, "usage: parsimony held approve", "held", "approve") + e.fails(t, 2, "not a valid id", "held", "approve", "abc") +} + +func TestArchive(t *testing.T) { + e := newEnv(t) + e.ok(t, "list", "add", "dev@example.org") + l, _ := e.s.FindList("dev@example.org") + if out := e.ok(t, "archive", "ls", "dev@example.org"); !strings.Contains(out, "archive is empty") { + t.Fatalf("empty: %q", out) + } + for i, subj := range []string{"Deploy failed", "Lunch plans", "Deploy fixed"} { + e.s.ArchiveMessage(l.ID, store.Message{MessageID: fmt.Sprintf("<%d@x>", i), Subject: subj, Sender: "Alice", + Date: time.Unix(1_700_000_000+int64(i), 0), Body: "body of " + subj}) + } + out := e.ok(t, "archive", "ls", "dev@example.org") + for _, want := range []string{"ID", "DATE", "FROM", "SUBJECT", "Deploy fixed", "Lunch plans", "Deploy failed", "3 messages"} { + if !strings.Contains(out, want) { + t.Fatalf("archive ls lacks %q:\n%s", want, out) + } + } + if strings.Index(out, "Deploy fixed") > strings.Index(out, "Deploy failed") { + t.Fatal("newest first") + } + out = e.ok(t, "archive", "ls", "dev@example.org", "--q", "deploy") + if strings.Contains(out, "Lunch") || !strings.Contains(out, "2 messages") { + t.Fatalf("search: %q", out) + } + out = e.ok(t, "archive", "ls", "dev@example.org", "--limit", "1", "--offset", "1") + if !strings.Contains(out, "Lunch plans") || strings.Contains(out, "Deploy fixed") || !strings.Contains(out, "Showing 1 of 3 messages") { + t.Fatalf("paging: %q", out) + } + if out = e.ok(t, "archive", "ls", "dev@example.org", "--q", "zzz"); !strings.Contains(out, "No messages found") { + t.Fatalf("no match: %q", out) + } + out = e.ok(t, "archive", "show", "1") + if !strings.Contains(out, "Subject: Deploy failed") || !strings.Contains(out, "body of Deploy failed") { + t.Fatalf("show: %q", out) + } + if exact := e.ok(t, "archive", "show", "1"); exact != "Subject: Deploy failed\nFrom: Alice\nDate: 2023-11-14 22:13\n\nbody of Deploy failed\n" { + t.Fatalf("show must print exactly the message, got %q", exact) + } + var shown map[string]any + if err := json.Unmarshal([]byte(e.ok(t, "--json", "archive", "show", "1")), &shown); err != nil || shown["subject"] != "Deploy failed" { + t.Fatalf("--json show must be a single JSON document: %v %v", err, shown) + } + e.fails(t, 1, "not found", "archive", "show", "99") + out = e.ok(t, "archive", "rm", "1", "--yes") + if !strings.Contains(out, "Deleted") { + t.Fatalf("rm: %q", out) + } + e.fails(t, 2, "--yes", "archive", "rm", "2") + if _, total, _ := e.s.ListMessages(l.ID, 10, 0); total != 2 { + t.Fatalf("total = %d", total) + } +} + +func TestQueueListIsCapped(t *testing.T) { + e := newEnv(t) + var items []store.NewOutbound + for i := 0; i < 105; i++ { + items = append(items, store.NewOutbound{From: "b@x.org", Rcpt: fmt.Sprintf("u%d@x.com", i)}) + } + e.s.Enqueue([]byte("x"), items) + out := e.ok(t, "queue", "ls") + if !strings.Contains(out, "Pending: 105") || !strings.Contains(out, "Showing 100 of 105 deliveries") { + t.Fatalf("queue ls:\n%.300s ... %s", out, out[max(0, len(out)-80):]) + } +} + +func TestURLWithTrailingSlashDoesNotProduceDoubleSlashes(t *testing.T) { + e := newEnv(t) + var paths []string + spy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.Path) + e.srv.Config.Handler.ServeHTTP(w, r) + })) + defer spy.Close() + vars := map[string]string{"PARSIMONY_API_TOKEN": token} + if code, _, errs := e.runEnv(t, vars, "", "--url", spy.URL+"//", "list", "ls"); code != 0 { + t.Fatalf("%d %s", code, errs) + } + if len(paths) != 1 || paths[0] != "/api/v1/lists" { + t.Fatalf("request paths: %v", paths) + } +} + +func TestQueue(t *testing.T) { + e := newEnv(t) + if out := e.ok(t, "queue", "ls"); !strings.Contains(out, "Pending: 0") || !strings.Contains(out, "queue is empty") { + t.Fatalf("empty: %q", out) + } + e.s.Enqueue([]byte("x"), []store.NewOutbound{{From: "b@x.org", Rcpt: "a@x.com"}, {From: "b@x.org", Rcpt: "b@x.com"}}) + due, _ := e.s.DueOutbox(10) + e.s.RetryOutbox(due[1].ID, time.Now().Add(time.Hour), "connection refused") + out := e.ok(t, "queue", "ls") + for _, want := range []string{"Pending: 2", "Retrying: 1", "ID", "RECIPIENT", "ATTEMPTS", "LAST ERROR", "a@x.com", "b@x.com", "connection refused"} { + if !strings.Contains(out, want) { + t.Fatalf("queue ls lacks %q:\n%s", want, out) + } + } + if strings.Index(out, "b@x.com") > strings.Index(out, "a@x.com") { + t.Fatal("failing deliveries first") + } + e.ok(t, "queue", "rm", fmt.Sprint(due[1].ID)) + e.fails(t, 1, "not found", "queue", "rm", fmt.Sprint(due[1].ID)) + if st, _ := e.s.OutboxStats(); st.Pending != 1 { + t.Fatalf("pending = %d", st.Pending) + } +} diff --git a/internal/cli/commands.go b/internal/cli/commands.go new file mode 100644 index 0000000..cf92e96 --- /dev/null +++ b/internal/cli/commands.go @@ -0,0 +1,607 @@ +package cli + +import ( + "bufio" + "encoding/json" + "flag" + "fmt" + "io" + "net/url" + "os" + "strconv" + "strings" + "time" +) + +// --- list --------------------------------------------------------------------- + +func (c *cmd) listLs(args []string) int { + if _, err := parseArgs(newFlagSet("list ls"), args); err != nil { + return c.usageError("%v", err) + } + cl, err := c.client() + if err != nil { + return c.fail(err) + } + raw, err := cl.do("GET", "/lists", nil) + if err != nil { + return c.fail(err) + } + if c.json { + return c.printJSON(raw) + } + var lists []list + if err := json.Unmarshal(raw, &lists); err != nil { + return c.fail(err) + } + if len(lists) == 0 { + fmt.Fprintln(c.io.Out, "No lists yet.") + return 0 + } + rows := [][]string{{"ID", "ADDRESS", "TITLE", "POST", "JOIN", "ARCHIVE"}} + for _, l := range lists { + rows = append(rows, []string{strconv.FormatInt(l.ID, 10), l.Address, l.Title, l.PostPolicy, l.JoinPolicy, l.ArchivePolicy}) + } + c.table(rows) + return 0 +} + +func (c *cmd) listAdd(args []string) int { + fs := newFlagSet("list add") + title := fs.String("title", "", "") + pos, err := parseArgs(fs, args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 1 { + return c.usageError("usage: parsimony list add [--title TITLE]") + } + name, domain, ok := strings.Cut(pos[0], "@") + if !ok || name == "" || domain == "" { + return c.usageError("a list address must look like name@domain") + } + cl, err := c.client() + if err != nil { + return c.fail(err) + } + raw, err := cl.do("POST", "/lists", map[string]string{"name": name, "domain": domain, "title": *title}) + if err != nil { + return c.fail(err) + } + if c.json { + return c.printJSON(raw) + } + var l list + json.Unmarshal(raw, &l) + fmt.Fprintf(c.io.Out, "Created %s (id %d)\n", l.Address, l.ID) + return 0 +} + +func (c *cmd) listShow(args []string) int { + pos, err := parseArgs(newFlagSet("list show"), args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 1 { + return c.usageError("usage: parsimony list show ") + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + if c.json { + raw, _ := json.Marshal(l) + return c.printJSON(raw) + } + c.table([][]string{ + {"id:", strconv.FormatInt(l.ID, 10)}, + {"address:", l.Address}, + {"title:", l.Title}, + {"post policy:", l.PostPolicy}, + {"join policy:", l.JoinPolicy}, + {"archive policy:", l.ArchivePolicy}, + }) + return 0 +} + +func (c *cmd) listSet(args []string) int { + fs := newFlagSet("list set") + fs.String("title", "", "") + fs.String("post", "", "") + fs.String("join", "", "") + fs.String("archive", "", "") + pos, err := parseArgs(fs, args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 1 { + return c.usageError("usage: parsimony list set [--title T] [--post P] [--join J] [--archive A]") + } + fields := map[string]string{"title": "title", "post": "post_policy", "join": "join_policy", "archive": "archive_policy"} + patch := map[string]string{} + fs.Visit(func(f *flag.Flag) { patch[fields[f.Name]] = f.Value.String() }) + if len(patch) == 0 { + return c.usageError("nothing to change: give at least one of --title, --post, --join, --archive") + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + cl, _ := c.client() + raw, err := cl.do("PATCH", fmt.Sprintf("/lists/%d", l.ID), patch) + if err != nil { + return c.fail(err) + } + if c.json { + return c.printJSON(raw) + } + fmt.Fprintf(c.io.Out, "Updated %s\n", l.Address) + return 0 +} + +func (c *cmd) listRm(args []string) int { + fs := newFlagSet("list rm") + yes := fs.Bool("yes", false, "") + pos, err := parseArgs(fs, args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 1 { + return c.usageError("usage: parsimony list rm --yes") + } + if !*yes { + return c.usageError("refusing to delete %s with its members and archive without --yes", pos[0]) + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + cl, _ := c.client() + if _, err := cl.do("DELETE", fmt.Sprintf("/lists/%d", l.ID), nil); err != nil { + return c.fail(err) + } + return c.done("Deleted " + l.Address) +} + +// done prints a success message (or a JSON ack) and returns 0. +func (c *cmd) done(msg string) int { + if c.json { + return c.printJSON(nil) + } + fmt.Fprintln(c.io.Out, msg) + return 0 +} + +// --- members -------------------------------------------------------------------- + +type member struct { + Address string `json:"address"` + DisplayName string `json:"display_name"` + Disabled bool `json:"disabled"` + BounceCount int `json:"bounce_count"` +} + +func (m member) status() string { + state := "active" + if m.Disabled { + state = "disabled" + } + if m.BounceCount > 0 { + return fmt.Sprintf("%s (%s)", state, plural(m.BounceCount, "bounce", "bounces")) + } + return state +} + +func (c *cmd) memberLs(args []string) int { + fs := newFlagSet("member ls") + emails := fs.Bool("emails", false, "") + pos, err := parseArgs(fs, args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 1 { + return c.usageError("usage: parsimony member ls [--emails]") + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + cl, _ := c.client() + raw, err := cl.do("GET", fmt.Sprintf("/lists/%d/members", l.ID), nil) + if err != nil { + return c.fail(err) + } + if c.json { + return c.printJSON(raw) + } + var ms []member + if err := json.Unmarshal(raw, &ms); err != nil { + return c.fail(err) + } + if *emails { + for _, m := range ms { + fmt.Fprintln(c.io.Out, m.Address) + } + return 0 + } + if len(ms) == 0 { + fmt.Fprintln(c.io.Out, "No members yet.") + return 0 + } + rows := [][]string{{"ADDRESS", "NAME", "STATUS"}} + for _, m := range ms { + rows = append(rows, []string{m.Address, m.DisplayName, m.status()}) + } + c.table(rows) + return 0 +} + +func (c *cmd) memberAdd(args []string) int { + fs := newFlagSet("member add") + name := fs.String("name", "", "") + pos, err := parseArgs(fs, args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 2 { + return c.usageError("usage: parsimony member add [--name NAME]") + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + raw, err := c.addMember(l.ID, pos[1], *name) + if err != nil { + return c.fail(err) + } + if c.json { + return c.printJSON(raw) + } + var m member + json.Unmarshal(raw, &m) + fmt.Fprintf(c.io.Out, "Added %s to %s\n", m.Address, l.Address) + return 0 +} + +func (c *cmd) addMember(listID int64, address, name string) (json.RawMessage, error) { + cl, err := c.client() + if err != nil { + return nil, err + } + return cl.do("POST", fmt.Sprintf("/lists/%d/members", listID), map[string]string{"address": address, "display_name": name}) +} + +func (c *cmd) memberRm(args []string) int { + pos, err := parseArgs(newFlagSet("member rm"), args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 2 { + return c.usageError("usage: parsimony member rm ") + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + cl, _ := c.client() + if _, err := cl.do("DELETE", fmt.Sprintf("/lists/%d/members/%s", l.ID, url.PathEscape(pos[1])), nil); err != nil { + return c.fail(err) + } + return c.done(fmt.Sprintf("Removed %s from %s", strings.ToLower(pos[1]), l.Address)) +} + +func (c *cmd) memberImport(args []string) int { + pos, err := parseArgs(newFlagSet("member import"), args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 2 { + return c.usageError("usage: parsimony member import ") + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + var in io.Reader = c.io.In + if pos[1] != "-" { + f, err := os.Open(pos[1]) + if err != nil { + return c.fail(err) + } + defer f.Close() + in = f + } + + imported, failed := 0, 0 + sc := bufio.NewScanner(in) + sc.Buffer(make([]byte, 64*1024), 1024*1024) + for n := 1; sc.Scan(); n++ { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + parts := strings.SplitN(line, ",", 3) + address, name := strings.TrimSpace(parts[0]), "" + if len(parts) > 1 { + name = strings.TrimSpace(parts[1]) + } + if _, err := c.addMember(l.ID, address, name); err != nil { + failed++ + fmt.Fprintf(c.io.Err, "line %d: %s: %v\n", n, line, err) + continue + } + imported++ + } + if err := sc.Err(); err != nil { + return c.fail(err) + } + msg := fmt.Sprintf("Imported %d members into %s", imported, l.Address) + if failed > 0 { + msg += fmt.Sprintf(", %d failed", failed) + } + fmt.Fprintln(c.io.Out, msg) + if failed > 0 { + return 1 + } + return 0 +} + +// --- held messages ---------------------------------------------------------------- + +func (c *cmd) heldLs(args []string) int { + pos, err := parseArgs(newFlagSet("held ls"), args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 1 { + return c.usageError("usage: parsimony held ls ") + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + cl, _ := c.client() + raw, err := cl.do("GET", fmt.Sprintf("/lists/%d/held", l.ID), nil) + if err != nil { + return c.fail(err) + } + if c.json { + return c.printJSON(raw) + } + var hs []struct { + ID int64 `json:"id"` + Sender string `json:"sender"` + Subject string `json:"subject"` + Size int `json:"size"` + CreatedAt time.Time `json:"created_at"` + } + if err := json.Unmarshal(raw, &hs); err != nil { + return c.fail(err) + } + if len(hs) == 0 { + fmt.Fprintln(c.io.Out, "Nothing is held for moderation.") + return 0 + } + rows := [][]string{{"ID", "RECEIVED", "FROM", "SUBJECT", "SIZE"}} + for _, h := range hs { + subject := h.Subject + if subject == "" { + subject = "(no subject)" + } + rows = append(rows, []string{strconv.FormatInt(h.ID, 10), formatDate(h.CreatedAt), h.Sender, subject, formatBytes(h.Size)}) + } + c.table(rows) + return 0 +} + +// byID runs an action on the numeric id given as the only argument. With needYes +// the command refuses to run without --yes. +func (c *cmd) byID(name string, args []string, needYes bool, act func(cl *client, id int64) error, done string) int { + fs := newFlagSet(name) + var yes *bool + if needYes { + yes = fs.Bool("yes", false, "") + } + pos, err := parseArgs(fs, args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 1 { + suffix := "" + if needYes { + suffix = " --yes" + } + return c.usageError("usage: parsimony %s %s", name, suffix) + } + id, ok := parseID(pos[0]) + if !ok { + return c.usageError("%q is not a valid id", pos[0]) + } + if needYes && !*yes { + return c.usageError("refusing to run %s %d without --yes", name, id) + } + cl, err := c.client() + if err != nil { + return c.fail(err) + } + if err := act(cl, id); err != nil { + return c.fail(err) + } + if done == "" { + return 0 // the action printed its own output + } + return c.done(fmt.Sprintf(done, id)) +} + +func (c *cmd) heldApprove(args []string) int { + return c.byID("held approve", args, false, func(cl *client, id int64) error { + _, err := cl.do("POST", fmt.Sprintf("/held/%d/approve", id), nil) + return err + }, "Approved held message %d: queued for delivery") +} + +func (c *cmd) heldDiscard(args []string) int { + return c.byID("held discard", args, false, func(cl *client, id int64) error { + _, err := cl.do("DELETE", fmt.Sprintf("/held/%d", id), nil) + return err + }, "Discarded held message %d") +} + +// --- archive ------------------------------------------------------------------------ + +type message struct { + ID int64 `json:"id"` + Subject string `json:"subject"` + Sender string `json:"sender"` + Date time.Time `json:"date"` + Body string `json:"body"` +} + +func plural(n int, one, many string) string { + if n == 1 { + return fmt.Sprintf("%d %s", n, one) + } + return fmt.Sprintf("%d %s", n, many) +} + +func (c *cmd) archiveLs(args []string) int { + fs := newFlagSet("archive ls") + q := fs.String("q", "", "") + limit := fs.Int("limit", 50, "") + offset := fs.Int("offset", 0, "") + pos, err := parseArgs(fs, args) + if err != nil { + return c.usageError("%v", err) + } + if len(pos) != 1 { + return c.usageError("usage: parsimony archive ls [--q TEXT] [--limit N] [--offset N]") + } + l, err := c.resolveList(pos[0]) + if err != nil { + return c.fail(err) + } + cl, _ := c.client() + query := url.Values{"limit": {strconv.Itoa(*limit)}, "offset": {strconv.Itoa(*offset)}} + if *q != "" { + query.Set("q", *q) + } + raw, err := cl.do("GET", fmt.Sprintf("/lists/%d/archive?%s", l.ID, query.Encode()), nil) + if err != nil { + return c.fail(err) + } + if c.json { + return c.printJSON(raw) + } + var page struct { + Total int `json:"total"` + Messages []message `json:"messages"` + } + if err := json.Unmarshal(raw, &page); err != nil { + return c.fail(err) + } + if page.Total == 0 { + if *q != "" { + fmt.Fprintln(c.io.Out, "No messages found.") + } else { + fmt.Fprintln(c.io.Out, "The archive is empty.") + } + return 0 + } + rows := [][]string{{"ID", "DATE", "FROM", "SUBJECT"}} + for _, m := range page.Messages { + rows = append(rows, []string{strconv.FormatInt(m.ID, 10), formatDate(m.Date), m.Sender, m.Subject}) + } + c.table(rows) + if len(page.Messages) < page.Total { + fmt.Fprintf(c.io.Out, "\nShowing %d of %s\n", len(page.Messages), plural(page.Total, "message", "messages")) + } else { + fmt.Fprintf(c.io.Out, "\n%s\n", plural(page.Total, "message", "messages")) + } + return 0 +} + +func (c *cmd) archiveShow(args []string) int { + return c.byID("archive show", args, false, func(cl *client, id int64) error { + raw, err := cl.do("GET", fmt.Sprintf("/archive/%d", id), nil) + if err != nil { + return err + } + if c.json { + c.printJSON(raw) + return nil + } + var m message + if err := json.Unmarshal(raw, &m); err != nil { + return err + } + fmt.Fprintf(c.io.Out, "Subject: %s\nFrom: %s\nDate: %s\n\n%s\n", m.Subject, m.Sender, formatDate(m.Date), m.Body) + return nil + }, "") +} + +func (c *cmd) archiveRm(args []string) int { + return c.byID("archive rm", args, true, func(cl *client, id int64) error { + _, err := cl.do("DELETE", fmt.Sprintf("/archive/%d", id), nil) + return err + }, "Deleted archived message %d") +} + +// --- queue -------------------------------------------------------------------------- + +func (c *cmd) queueLs(args []string) int { + if _, err := parseArgs(newFlagSet("queue ls"), args); err != nil { + return c.usageError("%v", err) + } + cl, err := c.client() + if err != nil { + return c.fail(err) + } + raw, err := cl.do("GET", "/queue", nil) + if err != nil { + return c.fail(err) + } + if c.json { + return c.printJSON(raw) + } + var q struct { + Pending int `json:"pending"` + Retrying int `json:"retrying"` + Oldest *time.Time `json:"oldest"` + Items []struct { + ID int64 `json:"id"` + Recipient string `json:"recipient"` + Attempts int `json:"attempts"` + LastError string `json:"last_error"` + NextAttempt time.Time `json:"next_attempt"` + } `json:"items"` + } + if err := json.Unmarshal(raw, &q); err != nil { + return c.fail(err) + } + oldest := "-" + if q.Oldest != nil { + oldest = formatDate(*q.Oldest) + } + fmt.Fprintf(c.io.Out, "Pending: %d\nRetrying: %d\nOldest: %s\n", q.Pending, q.Retrying, oldest) + if len(q.Items) == 0 { + fmt.Fprintln(c.io.Out, "\nThe queue is empty.") + return 0 + } + fmt.Fprintln(c.io.Out) + rows := [][]string{{"ID", "RECIPIENT", "ATTEMPTS", "NEXT ATTEMPT", "LAST ERROR"}} + for _, i := range q.Items { + rows = append(rows, []string{strconv.FormatInt(i.ID, 10), i.Recipient, strconv.Itoa(i.Attempts), formatDate(i.NextAttempt), i.LastError}) + } + c.table(rows) + if q.Pending > len(q.Items) { + fmt.Fprintf(c.io.Out, "\nShowing %d of %d deliveries\n", len(q.Items), q.Pending) + } + return 0 +} + +func (c *cmd) queueRm(args []string) int { + return c.byID("queue rm", args, false, func(cl *client, id int64) error { + _, err := cl.do("DELETE", fmt.Sprintf("/queue/%d", id), nil) + return err + }, "Discarded queued delivery %d") +}