use anyhow::{Context, Result};
use clap::Parser;
use is_terminal::IsTerminal;
use std::io::{stdin, Read};
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
#[clap(short, long)]
pub model: Option<String>,
#[clap(long)]
pub prompt: Option<String>,
#[clap(short, long)]
pub role: Option<String>,
#[clap(short = 's', long)]
pub session: Option<Option<String>>,
#[clap(long)]
pub empty_session: bool,
#[clap(long)]
pub save_session: bool,
#[clap(short = 'a', long)]
pub agent: Option<String>,
#[clap(long, value_names = ["NAME", "VALUE"], num_args = 2)]
pub agent_variable: Vec<String>,
#[clap(long)]
pub rag: Option<String>,
#[clap(long)]
pub rebuild_rag: bool,
#[clap(long = "macro", value_name = "MACRO")]
pub macro_name: Option<String>,
#[clap(long, value_name = "ADDRESS")]
pub serve: Option<Option<String>>,
#[clap(short = 'e', long)]
pub execute: bool,
#[clap(short = 'c', long)]
pub code: bool,
#[clap(short = 'f', long, value_name = "FILE")]
pub file: Vec<String>,
#[clap(short = 'S', long)]
pub no_stream: bool,
#[clap(long)]
pub dry_run: bool,
#[clap(long)]
pub info: bool,
#[clap(long)]
pub sync_models: bool,
#[clap(long)]
pub list_models: bool,
#[clap(long)]
pub list_roles: bool,
#[clap(long)]
pub list_sessions: bool,
#[clap(long)]
pub list_agents: bool,
#[clap(long)]
pub list_rags: bool,
#[clap(long)]
pub list_macros: bool,
#[clap(trailing_var_arg = true)]
text: Vec<String>,
}
impl Cli {
pub fn text(&self) -> Result<Option<String>> {
let mut stdin_text = String::new();
if !stdin().is_terminal() {
let _ = stdin()
.read_to_string(&mut stdin_text)
.context("Invalid stdin pipe")?;
};
match self.text.is_empty() {
true => {
if stdin_text.is_empty() {
Ok(None)
} else {
Ok(Some(stdin_text))
}
}
false => {
if self.macro_name.is_some() {
let text = self
.text
.iter()
.map(|v| shell_words::quote(v))
.collect::<Vec<_>>()
.join(" ");
if stdin_text.is_empty() {
Ok(Some(text))
} else {
Ok(Some(format!("{text} -- {stdin_text}")))
}
} else {
let text = self.text.join(" ");
if stdin_text.is_empty() {
Ok(Some(text))
} else {
Ok(Some(format!("{text}\n{stdin_text}")))
}
}
}
}
}
}