// 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 archive import add the messages of an mbox file (Mailman export); safe to repeat, threads are rebuilt 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, "import": c.archiveImport}, "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}, upload: &http.Client{}, // big files: no overall timeout } 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 // ordinary requests, with a timeout upload *http.Client // streaming uploads, without one } type apiError struct { status int message string } func (e *apiError) Error() string { return e.message } // do sends a JSON 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 ctype := "" if body != nil { b, err := json.Marshal(body) if err != nil { return nil, err } rd, ctype = bytes.NewReader(b), "application/json" } return cl.send(cl.http, method, path, rd, ctype) } // uploadTo streams r as the body of a POST, with no overall timeout. func (cl *client) uploadTo(path string, r io.Reader, contentType string) (json.RawMessage, error) { return cl.send(cl.upload, "POST", path, r, contentType) } func (cl *client) send(hc *http.Client, method, path string, rd io.Reader, contentType string) (json.RawMessage, error) { 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 contentType != "" { req.Header.Set("Content-Type", contentType) } resp, err := hc.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)) }