Something went wrong. Try again.
A command-line bot client for Chatto. beardicus.tngl.io/chatline
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283// 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. Statuslines go to stderr. An error is one line on stderr, "error: <code>: <detail>",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 Chattoversion 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}