Lines
55.56 %
Functions
26.09 %
Branches
100 %
//! `template` subcommands: list, create, edit, delete and test of template sources.
use clap::{Args, Subcommand};
use cli_core::CommandError;
use cli_core::template as ops;
use rpc::Session;
use sqlx::types::Uuid;
use std::io::{BufRead, IsTerminal, Read};
use std::path::{Path, PathBuf};
use crate::eval::{RenderMode, build_delete_template_form, eval_print};
use crate::transaction::confirmed;
fn unreadable(what: &str, e: std::io::Error) -> CommandError {
CommandError::Argument(format!("reading the source from {what}: {e}"))
}
fn read_stdin(mut stdin: impl Read) -> Result<String, CommandError> {
let mut text = String::new();
stdin
.read_to_string(&mut text)
.map_err(|e| unreadable("standard input", e))?;
Ok(text)
/// The text of the file at `path`, or of standard input for `-`.
///
/// # Errors
/// [`CommandError::Argument`] for an unreadable file or standard input.
pub fn read_path(path: &Path, stdin: impl Read) -> Result<String, CommandError> {
match path.as_os_str() == "-" {
true => read_stdin(stdin),
false => {
std::fs::read_to_string(path).map_err(|e| unreadable(&path.display().to_string(), e))
/// Where a template source comes from.
#[derive(Args, Debug, Default)]
pub struct SourceArgs {
/// File holding the source; `-` reads standard input
#[arg(long, value_name = "PATH", conflicts_with = "source")]
source_file: Option<PathBuf>,
/// The source text; `-` reads standard input
#[arg(long, value_name = "TEXT", conflicts_with = "source_file")]
source: Option<String>,
impl SourceArgs {
/// The given source, or `None` when neither option was used.
pub fn read(&self, stdin: impl Read) -> Result<Option<String>, CommandError> {
match (&self.source_file, &self.source) {
(Some(path), _) => read_path(path, stdin).map(Some),
(None, Some(text)) if text == "-" => read_stdin(stdin).map(Some),
(None, source) => Ok(source.clone()),
fn required(&self, stdin: impl Read) -> Result<String, CommandError> {
self.read(stdin)?.ok_or_else(|| {
CommandError::Argument("one of --source-file or --source is required".to_string())
})
#[derive(Subcommand, Debug)]
pub enum TemplateCmd {
/// List the templates: id and name
List,
/// Create a template from a source
Create {
#[arg(long)]
name: Option<String>,
#[command(flatten)]
source: SourceArgs,
},
/// Edit a template; omitted fields stay as stored
Edit {
/// Id of the template
id: Uuid,
/// Delete a template
Delete {
/// Delete without asking; required when stdin is not a terminal
yes: bool,
/// Show the draft a source renders to, saving nothing
Test {
/// Test the stored source of this template
#[arg(conflicts_with_all = ["source_file", "source"])]
id: Option<Uuid>,
/// Deletes the template unless the answer declines; returns whether it was deleted.
pub async fn delete_template_confirmed(
session: &mut Session,
interactive: bool,
input: impl BufRead,
) -> Result<bool, CommandError> {
let question = format!("Delete template {id}?");
if !confirmed(&question, yes, interactive, input)? {
return Ok(false);
let form = build_delete_template_form(&id.to_string());
eval_print(session, &form, RenderMode::BoolSuccess).await?;
Ok(true)
async fn tested_source(
source: &SourceArgs,
) -> Result<String, CommandError> {
match id {
Some(id) => ops::stored_source(session, &id.to_string()).await,
None => source.required(std::io::stdin().lock()),
pub async fn run(session: &mut Session, cmd: TemplateCmd) -> Result<(), CommandError> {
match cmd {
TemplateCmd::List => ops::list(session)
.await?
.iter()
.for_each(|l| println!("{l}")),
TemplateCmd::Create { name, source } => {
let source = source.required(std::io::stdin().lock())?;
println!("{}", ops::create(session, name.as_deref(), &source).await?);
TemplateCmd::Edit { id, name, source } => {
let source = source.read(std::io::stdin().lock())?;
let id = id.to_string();
println!(
"{}",
ops::edit(session, &id, name.as_deref(), source.as_deref()).await?
);
TemplateCmd::Delete { id, yes } => {
let stdin = std::io::stdin();
if !delete_template_confirmed(session, id, yes, stdin.is_terminal(), stdin.lock())
{
eprintln!("Cancelled");
TemplateCmd::Test { id, source } => {
let source = tested_source(session, id, &source).await?;
ops::test(session, &source)
.for_each(|l| println!("{l}"));
Ok(())
#[cfg(test)]
mod tests;