summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: ddd856e75461274428b345855a18e733a446700d (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
mod cli;
mod client;
mod config;
mod repl;

use std::process::exit;
use std::sync::Arc;

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

use anyhow::{anyhow, Result};
use clap::Parser;
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!("Uknown role '{name}'"))?,
        ),
        None => None,
    };
    let client = ChatGptClient::init(config.clone())?;
    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 output = client.acquire(input, role.map(|v| v.prompt))?;
    println!("{}", output.trim());
    Config::save_message(file.as_mut(), input, &output);
    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)
}