// Package cli implements chatline's commands. package cli import ( "context" "errors" "fmt" "io" "log/slog" "net/http" "os" "os/signal" "strings" "syscall" "time" "github.com/spf13/cobra" "golang.org/x/term" "tangled.org/beardic.us/chatline/internal/api" "tangled.org/beardic.us/chatline/internal/config" "tangled.org/beardic.us/chatline/internal/output" ) // BuildInfo is set from main via -ldflags. type BuildInfo struct { Version string Commit string ChattoVersion string } // App carries dependencies shared by all commands. Tests construct it directly. type App struct { Build BuildInfo Stdin io.Reader Stdout io.Writer Stderr io.Writer Env config.Env // StdinIsTTY reports whether stdin is an interactive terminal. StdinIsTTY func() bool // ReadSecret reads a line from the terminal without echo. ReadSecret func() (string, error) // HTTP is used for all server traffic; nil means a default client. HTTP *http.Client Now func() time.Time // Ctx is the base context; nil means context.Background(). Tests cancel it // to stop long-running commands such as listen. Ctx context.Context overrides config.Overrides format string quiet bool logFile string log *slog.Logger closers []io.Closer cfg *config.Config client *api.Client } // NewApp returns an App wired to the real process environment. func NewApp(b BuildInfo) *App { return &App{ Build: b, Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, Env: os.Getenv, StdinIsTTY: func() bool { return term.IsTerminal(int(os.Stdin.Fd())) }, ReadSecret: func() (string, error) { b, err := term.ReadPassword(int(os.Stdin.Fd())) return string(b), err }, Now: time.Now, } } // Run executes the CLI with args and returns the process exit code. func (a *App) Run(args []string) int { root := a.rootCmd() root.SetArgs(args) root.SetIn(a.Stdin) root.SetOut(a.Stdout) root.SetErr(a.Stderr) base := a.Ctx if base == nil { base = context.Background() } ctx, stop := signal.NotifyContext(base, os.Interrupt, syscall.SIGTERM) defer stop() err := root.ExecuteContext(ctx) for _, c := range a.closers { c.Close() } if err == nil { return output.ExitOK } if errors.Is(err, errInterrupted) { return output.ExitOK } var ec exitCode if errors.As(err, &ec) { return int(ec) } return output.WriteError(a.Stderr, a.format, err) } var errInterrupted = errors.New("interrupted") // Command returns the root command without running it. tools/gen-docs walks // it to write the command reference. func (a *App) Command() *cobra.Command { return a.rootCmd() } func (a *App) rootCmd() *cobra.Command { root := &cobra.Command{ Use: "chatline", Short: "A command-line client for Chatto that connects agents and scripts", Long: `A command-line client for Chatto. Connect agents and scripts with a single binary. Start with "chatline init", then check the bot's permissions with "chatline auth status". Text output is line-oriented, and --format json prints JSON lines. Status lines go to stderr. An error is one line on stderr, "error: : ", and sets the exit status: 0 success 1 server error or network failure 2 invalid or revoked key 3 missing or invalid config, or no key 4 bad flags or arguments 5 timed out 6 permission denied 7 room, user or message not found`, SilenceErrors: true, SilenceUsage: true, Version: a.versionString(), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { if a.format != "text" && a.format != "json" { return output.Usage("bad_format", "--format must be text or json") } return nil }, } root.SetVersionTemplate("{{.Version}}\n") root.Flags().BoolP("version", "v", false, "print version information") pf := root.PersistentFlags() pf.StringVar(&a.overrides.ConfigPath, "config", "", "config file (default ~/.config/chatline/config.json, or $CHATLINE_CONFIG)") pf.StringVar(&a.overrides.ServerURL, "server", "", "Chatto server URL (or $CHATLINE_SERVER)") pf.StringVar(&a.overrides.KeyFile, "key-file", "", "read the bot API key from this file (or $CHATLINE_API_KEY_FILE)") pf.StringVar(&a.overrides.StateDir, "state-dir", "", "directory for resume state (default ~/.local/state/chatline/PROFILE, named after the config file, or $CHATLINE_STATE_DIR)") pf.StringVar(&a.format, "format", "text", `output format: "text" or "json"`) pf.BoolVarP(&a.quiet, "quiet", "q", false, "suppress status lines on stderr") pf.StringVar(&a.logFile, "log-file", "", "also append logs to this file (or $CHATLINE_LOG_FILE)") root.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error { return output.Usage("bad_flag", "%v", err) }) root.AddCommand( a.initCmd(), a.authCmd(), a.roomsCmd(), a.usersCmd(), a.sendCmd(), a.readCmd(), a.runCmd(), a.reactCmd(), a.permalinkCmd(), a.downloadCmd(), a.profileCmd(), a.botCmd(), a.listenCmd(), a.askCmd(), a.channelCmd(), a.serveCmd(), a.searchCmd(), a.bootstrapCmd(), a.skillCmd(), a.versionCmd(), ) for _, c := range root.Commands() { wrapArgs(c) } return root } // wrapArgs turns cobra's positional-argument errors into usage errors. func wrapArgs(c *cobra.Command) { if c.Args != nil { orig := c.Args c.Args = func(cmd *cobra.Command, args []string) error { if err := orig(cmd, args); err != nil { return output.Usage("bad_args", "%v", err) } return nil } } for _, sub := range c.Commands() { wrapArgs(sub) } } func (a *App) versionString() string { v := a.Build.Version if v == "" { v = "dev" } return fmt.Sprintf("chatline %s (commit %s, built for Chatto %s)", v, a.Build.Commit, a.Build.ChattoVersion) } func (a *App) versionCmd() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Print version information", Args: cobra.NoArgs, Long: `Print the chatline version, the commit it was built from, and the Chatto version it was built against. "chatline --version" prints the same line. With --format json, the fields are "version", "commit", and "chatto_version".`, Example: ` chatline version chatline version --format json`, RunE: func(cmd *cobra.Command, args []string) error { if a.json() { return a.printer().JSONLine(map[string]string{"version": a.Build.Version, "commit": a.Build.Commit, "chatto_version": a.Build.ChattoVersion}) } fmt.Fprintln(a.Stdout, a.versionString()) return nil }, } } func (a *App) json() bool { return a.format == "json" } func (a *App) printer() *output.Printer { return &output.Printer{W: a.Stdout, JSON: a.json()} } // status prints a status line on stderr unless --quiet. func (a *App) status(format string, args ...any) { if !a.quiet { fmt.Fprintf(a.Stderr, format+"\n", args...) } } func (a *App) warn(format string, args ...any) { fmt.Fprintf(a.Stderr, "warning: "+format+"\n", args...) } // config loads the configuration once. func (a *App) config() (*config.Config, error) { if a.cfg != nil { return a.cfg, nil } cfg, err := config.Load(a.overrides, a.Env) if err != nil { return nil, err } for _, w := range cfg.Warnings { a.warn("%s", w) } a.cfg = cfg return cfg, nil } // api returns an authenticated client, requiring a server URL and key. func (a *App) api() (*api.Client, error) { if a.client != nil { return a.client, nil } cfg, err := a.config() if err != nil { return nil, err } if err := cfg.Require(); err != nil { return nil, err } a.client = api.New(cfg.ServerURL, cfg.APIKey, a.HTTP) return a.client, nil } // readBody returns the message body from -m, --message-file or stdin. func (a *App) readBody(msg, file string, allowEmpty bool) (string, error) { var body string switch { case msg != "" && file != "": return "", output.Usage("bad_flag", "use only one of --message and --message-file") case msg != "": body = msg case file != "": data, err := os.ReadFile(file) if err != nil { return "", output.Usage("file_unreadable", "%v", err) } body = string(data) case !a.StdinIsTTY(): data, err := io.ReadAll(a.Stdin) if err != nil { return "", err } body = string(data) } body = strings.TrimSuffix(strings.TrimSuffix(body, "\n"), "\r") if body == "" && !allowEmpty { return "", output.Usage("no_message", "no message: pass --message, --message-file, or pipe text on stdin") } return body, nil }