1
//! `template` subcommands: list, create, edit, delete and test of template sources.
2

            
3
use clap::{Args, Subcommand};
4
use cli_core::CommandError;
5
use cli_core::template as ops;
6
use rpc::Session;
7
use sqlx::types::Uuid;
8
use std::io::{BufRead, IsTerminal, Read};
9
use std::path::{Path, PathBuf};
10

            
11
use crate::eval::{RenderMode, build_delete_template_form, eval_print};
12
use crate::transaction::confirmed;
13

            
14
1
fn unreadable(what: &str, e: std::io::Error) -> CommandError {
15
1
    CommandError::Argument(format!("reading the source from {what}: {e}"))
16
1
}
17

            
18
2
fn read_stdin(mut stdin: impl Read) -> Result<String, CommandError> {
19
2
    let mut text = String::new();
20
2
    stdin
21
2
        .read_to_string(&mut text)
22
        .map_err(|e| unreadable("standard input", e))?;
23
2
    Ok(text)
24
2
}
25

            
26
/// The text of the file at `path`, or of standard input for `-`.
27
///
28
/// # Errors
29
/// [`CommandError::Argument`] for an unreadable file or standard input.
30
5
pub fn read_path(path: &Path, stdin: impl Read) -> Result<String, CommandError> {
31
5
    match path.as_os_str() == "-" {
32
1
        true => read_stdin(stdin),
33
        false => {
34
4
            std::fs::read_to_string(path).map_err(|e| unreadable(&path.display().to_string(), e))
35
        }
36
    }
37
5
}
38

            
39
/// Where a template source comes from.
40
#[derive(Args, Debug, Default)]
41
pub struct SourceArgs {
42
    /// File holding the source; `-` reads standard input
43
    #[arg(long, value_name = "PATH", conflicts_with = "source")]
44
    source_file: Option<PathBuf>,
45
    /// The source text; `-` reads standard input
46
    #[arg(long, value_name = "TEXT", conflicts_with = "source_file")]
47
    source: Option<String>,
48
}
49

            
50
impl SourceArgs {
51
    /// The given source, or `None` when neither option was used.
52
    ///
53
    /// # Errors
54
    /// [`CommandError::Argument`] for an unreadable file or standard input.
55
7
    pub fn read(&self, stdin: impl Read) -> Result<Option<String>, CommandError> {
56
7
        match (&self.source_file, &self.source) {
57
3
            (Some(path), _) => read_path(path, stdin).map(Some),
58
2
            (None, Some(text)) if text == "-" => read_stdin(stdin).map(Some),
59
3
            (None, source) => Ok(source.clone()),
60
        }
61
7
    }
62

            
63
1
    fn required(&self, stdin: impl Read) -> Result<String, CommandError> {
64
1
        self.read(stdin)?.ok_or_else(|| {
65
1
            CommandError::Argument("one of --source-file or --source is required".to_string())
66
1
        })
67
1
    }
68
}
69

            
70
#[derive(Subcommand, Debug)]
71
pub enum TemplateCmd {
72
    /// List the templates: id and name
73
    List,
74
    /// Create a template from a source
75
    Create {
76
        #[arg(long)]
77
        name: Option<String>,
78
        #[command(flatten)]
79
        source: SourceArgs,
80
    },
81
    /// Edit a template; omitted fields stay as stored
82
    Edit {
83
        /// Id of the template
84
        id: Uuid,
85
        #[arg(long)]
86
        name: Option<String>,
87
        #[command(flatten)]
88
        source: SourceArgs,
89
    },
90
    /// Delete a template
91
    Delete {
92
        /// Id of the template
93
        id: Uuid,
94
        /// Delete without asking; required when stdin is not a terminal
95
        #[arg(long)]
96
        yes: bool,
97
    },
98
    /// Show the draft a source renders to, saving nothing
99
    Test {
100
        /// Test the stored source of this template
101
        #[arg(conflicts_with_all = ["source_file", "source"])]
102
        id: Option<Uuid>,
103
        #[command(flatten)]
104
        source: SourceArgs,
105
    },
106
}
107

            
108
/// Deletes the template unless the answer declines; returns whether it was deleted.
109
4
pub async fn delete_template_confirmed(
110
4
    session: &mut Session,
111
4
    id: Uuid,
112
4
    yes: bool,
113
4
    interactive: bool,
114
4
    input: impl BufRead,
115
4
) -> Result<bool, CommandError> {
116
4
    let question = format!("Delete template {id}?");
117
4
    if !confirmed(&question, yes, interactive, input)? {
118
1
        return Ok(false);
119
2
    }
120
2
    let form = build_delete_template_form(&id.to_string());
121
2
    eval_print(session, &form, RenderMode::BoolSuccess).await?;
122
2
    Ok(true)
123
4
}
124

            
125
async 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

            
136
pub 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)]
174
mod tests;