Something went wrong. Try again.
Kagi Mail CLI client
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221// Package cmd wires km's cobra commands. Each command lives in its own file// as newXxxCmd(f *Factory) with its logic in runXxx(ctx, f, opts).package cmd
import ( "context" "errors" "fmt" "os" "strings"
"github.com/spf13/cobra"
"tangled.org/matilde.at/km/internal/jmap" "tangled.org/matilde.at/km/internal/mail" "tangled.org/matilde.at/km/internal/oauth" "tangled.org/matilde.at/km/internal/query" "tangled.org/matilde.at/km/internal/render")
// Version is set at build time with -ldflags "-X km/cmd.Version=…".var Version = "dev"
// Exit codes.const ( ExitOK = 0 ExitError = 1 ExitUsage = 2 ExitAuth = 4)
// ExitErr carries an exit code.type ExitErr struct { Code int Err error}
func (e *ExitErr) Error() string { return e.Err.Error() }func (e *ExitErr) Unwrap() error { return e.Err }
// usageErr marks err as a usage error (exit 2).func usageErr(err error) error { if err == nil { return nil } return &ExitErr{Code: ExitUsage, Err: err}}
// usagef is fmt.Errorf for usage errors.func usagef(format string, a ...any) error { return usageErr(fmt.Errorf(format, a...)) }
// silentErr is an error already reported to the user; it only sets the exit code.var silentErr = errors.New("")
// ExitCode maps an error to the process exit code.func ExitCode(err error) int { if err == nil { return ExitOK } var ee *ExitErr if errors.As(err, &ee) { return ee.Code } var qe *query.UsageError var fe *render.FieldsError switch { case errors.Is(err, jmap.ErrAuthRequired), errors.Is(err, oauth.ErrAuthRequired): return ExitAuth case errors.As(err, &qe), errors.As(err, &fe): return ExitUsage } msg := err.Error() if strings.HasPrefix(msg, "unknown command") || strings.HasPrefix(msg, "unknown flag") || strings.HasPrefix(msg, "unknown shorthand flag") || strings.Contains(msg, "accepts ") || strings.HasPrefix(msg, "requires at least") || strings.HasPrefix(msg, "invalid argument") { return ExitUsage } return ExitError}
// NewRootCmd builds the command tree.func NewRootCmd(f *Factory) *cobra.Command { root := &cobra.Command{ Use: "km <command> <subcommand> [flags]", Short: "Kagi Mail from the command line", Long: "Work with Kagi Mail (or any JMAP server) from the command line.", SilenceUsage: true, SilenceErrors: true, Version: Version, } root.SetIn(f.IO.In) root.SetOut(f.IO.Out) root.SetErr(f.IO.ErrOut) root.PersistentFlags().StringVar(&f.HostOverride, "host", f.HostOverride, "JMAP `host` to use (default from config, else "+"mail.kagimail.com)") root.PersistentFlags().BoolVar(&f.NoPager, "no-pager", false, "Do not pipe output through a pager") root.SetFlagErrorFunc(func(c *cobra.Command, err error) error { return usageErr(err) })
root.AddCommand( newAuthCmd(f), newAPICmd(f), newMailCmd(f), newMailboxCmd(f), newIdentityCmd(f), newDraftCmd(f), newFilterCmd(f), newVacationCmd(f), newAliasCmd(f), newConfigCmd(f), newCompletionCmd(f), searchHelp, ) return root}
func newMailCmd(f *Factory) *cobra.Command { c := &cobra.Command{ Use: "mail <command>", Short: "List, read, send and triage mail", } c.AddCommand( newMailListCmd(f), newMailSearchCmd(f), newMailViewCmd(f), newMailDownloadCmd(f), newMailSendCmd(f), newMailReplyCmd(f), newMailForwardCmd(f), newMailArchiveCmd(f), newMailDeleteCmd(f), newMailMoveCmd(f), newMailMarkCmd(f), ) return c}
// searchHelp is the `km help search` topic.var searchHelp = &cobra.Command{ Use: "search", Short: "Search query syntax", Long: `Queries for km mail list and km mail search are whitespace-separated terms,all of which must match. Quote values containing spaces; a leading - negatesa term.
from:x to:x cc:x bcc:x address or name contains x subject:x body:x subject or body contains x in:mailbox in a mailbox: role (inbox, sent, …), path (Projects/Alpha), name or id is:unread is:read read state (thread-wide in thread listings) is:flagged is:starred flagged (any message in the thread) is:draft is:answered draft, answered has:attachment has an attachment after:D before:D received after/before D: YYYY-MM-DD (local midnight) or relative 7d, 2w, 3m larger:N smaller:N size in bytes; suffixes k and m anything else full-text search
A word containing a colon that is not a qualifier must be quoted:"http://example.com".
Examples: km mail search from:alice has:attachment after:3m km mail list -m Archive -is:read subject:"weekly report"`,}
// Main runs km and returns the exit code.func Main() int { f, err := NewFactory() if err != nil { fmt.Fprintln(os.Stderr, "km:", err) return ExitError } return Run(context.Background(), f, os.Args[1:])}
// Run executes km with args (without the program name).func Run(ctx context.Context, f *Factory, args []string) int { root := NewRootCmd(f)
expanded, shell, err := expandAlias(f, root, args) if err != nil { return report(f, err) } if shell { code, err := runShellAlias(f, expanded) if err != nil { return report(f, err) } return code } if path, ok := findExtension(root, expanded); ok { code, err := runExtension(f, path, expanded[1:]) if err != nil { return report(f, err) } return code }
root.SetArgs(expanded) err = root.ExecuteContext(ctx) return report(f, err)}
func report(f *Factory, err error) int { if err == nil { return ExitOK } f.IO.StopPager() if !errors.Is(err, silentErr) && err.Error() != "" { msg := err.Error() if errors.Is(err, jmap.ErrAuthRequired) { msg = "not logged in to " + f.Host() + ": run `km auth login`" } var nf *mail.NotFoundError if errors.As(err, &nf) { msg = nf.Error() } fmt.Fprintln(f.IO.ErrOut, msg) } return ExitCode(err)}