summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 8dfa2fd094913f1b01cc6ff9701944173f8198c0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
mod cli;
mod client;
mod config;
mod render;
mod repl;
mod term;
mod utils;

use std::io::{stdin, Read};
use std::sync::Arc;
use std::{io::stdout, process::exit};

use cli::Cli;
use client::ChatGptClient;
use config::{Config, Role};
use is_terminal::IsTerminal;

use anyhow::{anyhow, Result};
use clap::Parser;
use render::MarkdownRender;
use repl::{Repl, ReplCmdHandler};

fn main() {
    if let Err(err) = start() {
        eprintln!("error: {err}");
        exit(1);
    }
}

fn start() -> Result<()> {
    let cli = Cli::parse();
    let text = cli.text();
    let config = Arc::new(Config::init(text.is_none())?);
    if cli.list_roles {
        config.roles.iter().for_each(|v| println!("{}", v.name));
        exit(0);
    }
    let role = match &cli.role {
        Some(name) => Some(
            config
                .find_role(name)
                .ok_or_else(|| anyhow!("Unknown role '{name}'"))?,
        ),
        None => None,
    };
    let client = ChatGptClient::init(config.clone())?;
    if atty::isnt(atty::Stream::Stdin) {
        let mut text = String::new();
        stdin().read_to_string(&mut text)?;
        start_directive(client, config, role, &text)
    } else {
        match text {
            Some(text) => start_directive(client, config, role, &text),
            None => start_interactive(client, config, role),
        }
    }
}

fn start_directive(
    client: ChatGptClient,
    config: Arc<Config>,
    role: Option<Role>,
    input: &str,
) -> Result<()> {
    let mut file = config.open_message_file()?;
    let prompt = role.as_ref().map(|v| v.prompt.to_string());
    let role_name = role.as_ref().map(|v| v.name.to_string());
    let output = client.acquire(input, prompt)?;
    let output = output.trim();
    if !config.no_highlight && stdout().is_terminal() {
        let markdown_render = MarkdownRender::init()?;
        markdown_render.print(output)?;
    } else {
        println!("{output}");
    }

    Config::save_message(file.as_mut(), input, output, &role_name);
    Ok(())
}

fn start_interactive(client: ChatGptClient, config: Arc<Config>, role: Option<Role>) -> Result<()> {
    let mut repl = Repl::init(config.clone())?;
    let handler = ReplCmdHandler::init(client, config, role)?;
    repl.run(handler)
}