1use clap::{Args, Subcommand};
4use cli_core::CommandError;
5use cli_core::template as ops;
6use rpc::Session;
7use sqlx::types::Uuid;
8use std::io::{BufRead, IsTerminal, Read};
9use std::path::{Path, PathBuf};
10
11use crate::eval::{RenderMode, build_delete_template_form, eval_print};
12use crate::transaction::confirmed;
13
14fn unreadable(what: &str, e: std::io::Error) -> CommandError {
15 CommandError::Argument(format!("reading the source from {what}: {e}"))
16}
17
18fn read_stdin(mut stdin: impl Read) -> Result<String, CommandError> {
19 let mut text = String::new();
20 stdin
21 .read_to_string(&mut text)
22 .map_err(|e| unreadable("standard input", e))?;
23 Ok(text)
24}
25
26pub fn read_path(path: &Path, stdin: impl Read) -> Result<String, CommandError> {
31 match path.as_os_str() == "-" {
32 true => read_stdin(stdin),
33 false => {
34 std::fs::read_to_string(path).map_err(|e| unreadable(&path.display().to_string(), e))
35 }
36 }
37}
38
39#[derive(Args, Debug, Default)]
41pub struct SourceArgs {
42 #[arg(long, value_name = "PATH", conflicts_with = "source")]
44 source_file: Option<PathBuf>,
45 #[arg(long, value_name = "TEXT", conflicts_with = "source_file")]
47 source: Option<String>,
48}
49
50impl SourceArgs {
51 pub fn read(&self, stdin: impl Read) -> Result<Option<String>, CommandError> {
56 match (&self.source_file, &self.source) {
57 (Some(path), _) => read_path(path, stdin).map(Some),
58 (None, Some(text)) if text == "-" => read_stdin(stdin).map(Some),
59 (None, source) => Ok(source.clone()),
60 }
61 }
62
63 fn required(&self, stdin: impl Read) -> Result<String, CommandError> {
64 self.read(stdin)?.ok_or_else(|| {
65 CommandError::Argument("one of --source-file or --source is required".to_string())
66 })
67 }
68}
69
70#[derive(Subcommand, Debug)]
71pub enum TemplateCmd {
72 List,
74 Create {
76 #[arg(long)]
77 name: Option<String>,
78 #[command(flatten)]
79 source: SourceArgs,
80 },
81 Edit {
83 id: Uuid,
85 #[arg(long)]
86 name: Option<String>,
87 #[command(flatten)]
88 source: SourceArgs,
89 },
90 Delete {
92 id: Uuid,
94 #[arg(long)]
96 yes: bool,
97 },
98 Test {
100 #[arg(conflicts_with_all = ["source_file", "source"])]
102 id: Option<Uuid>,
103 #[command(flatten)]
104 source: SourceArgs,
105 },
106}
107
108pub async fn delete_template_confirmed(
110 session: &mut Session,
111 id: Uuid,
112 yes: bool,
113 interactive: bool,
114 input: impl BufRead,
115) -> Result<bool, CommandError> {
116 let question = format!("Delete template {id}?");
117 if !confirmed(&question, yes, interactive, input)? {
118 return Ok(false);
119 }
120 let form = build_delete_template_form(&id.to_string());
121 eval_print(session, &form, RenderMode::BoolSuccess).await?;
122 Ok(true)
123}
124
125async fn tested_source(
126 session: &mut Session,
127 id: Option<Uuid>,
128 source: &SourceArgs,
129) -> Result<String, CommandError> {
130 match id {
131 Some(id) => ops::stored_source(session, &id.to_string()).await,
132 None => source.required(std::io::stdin().lock()),
133 }
134}
135
136pub async fn run(session: &mut Session, cmd: TemplateCmd) -> Result<(), CommandError> {
137 match cmd {
138 TemplateCmd::List => ops::list(session)
139 .await?
140 .iter()
141 .for_each(|l| println!("{l}")),
142 TemplateCmd::Create { name, source } => {
143 let source = source.required(std::io::stdin().lock())?;
144 println!("{}", ops::create(session, name.as_deref(), &source).await?);
145 }
146 TemplateCmd::Edit { id, name, source } => {
147 let source = source.read(std::io::stdin().lock())?;
148 let id = id.to_string();
149 println!(
150 "{}",
151 ops::edit(session, &id, name.as_deref(), source.as_deref()).await?
152 );
153 }
154 TemplateCmd::Delete { id, yes } => {
155 let stdin = std::io::stdin();
156 if !delete_template_confirmed(session, id, yes, stdin.is_terminal(), stdin.lock())
157 .await?
158 {
159 eprintln!("Cancelled");
160 }
161 }
162 TemplateCmd::Test { id, source } => {
163 let source = tested_source(session, id, &source).await?;
164 ops::test(session, &source)
165 .await?
166 .iter()
167 .for_each(|l| println!("{l}"));
168 }
169 }
170 Ok(())
171}
172
173#[cfg(test)]
174mod tests;