|
| 1 | +use crate::args::template_completer; |
| 2 | +use crate::args::{Cli, CliConfig}; |
| 3 | +use crate::output::{self, OutputLevel}; |
| 4 | +use crate::templates::TemplateStore; |
| 5 | +use anyhow::Result; |
| 6 | +use clap::{Args, Subcommand}; |
| 7 | +use clap_complete::engine::ArgValueCompleter; |
| 8 | + |
| 9 | +#[derive(Args)] |
| 10 | +pub struct TemplatesArgs { |
| 11 | + #[command(subcommand)] |
| 12 | + pub action: TemplateAction, |
| 13 | +} |
| 14 | + |
| 15 | +#[derive(Subcommand)] |
| 16 | +pub enum TemplateAction { |
| 17 | + /// List all templates |
| 18 | + List, |
| 19 | + /// Show a specific template's details |
| 20 | + Show { |
| 21 | + /// Template name |
| 22 | + #[arg(value_name = "NAME", add = ArgValueCompleter::new(template_completer))] |
| 23 | + name: String, |
| 24 | + }, |
| 25 | + /// Remove a template file |
| 26 | + Remove { |
| 27 | + /// Template name to delete |
| 28 | + #[arg(value_name = "NAME", add = ArgValueCompleter::new(template_completer))] |
| 29 | + name: String, |
| 30 | + }, |
| 31 | + /// Edit a template file in $EDITOR |
| 32 | + Edit { |
| 33 | + /// Template name to edit |
| 34 | + #[arg(value_name = "NAME", add = ArgValueCompleter::new(template_completer))] |
| 35 | + name: String, |
| 36 | + }, |
| 37 | + /// Create a new template |
| 38 | + Create { |
| 39 | + /// Template name |
| 40 | + name: String, |
| 41 | + /// User prompt (use quotes if contains spaces) |
| 42 | + #[arg(long, short = 'u')] |
| 43 | + user_prompt: String, |
| 44 | + /// Optional system prompt |
| 45 | + #[arg(long, short = 's')] |
| 46 | + system_prompt: Option<String>, |
| 47 | + /// Optional description |
| 48 | + #[arg(long, short = 'd')] |
| 49 | + description: Option<String>, |
| 50 | + /// Default placeholder values in key=value format. Can be repeated. |
| 51 | + #[arg(long = "default", value_parser = parse_default_kv)] |
| 52 | + defaults: Vec<(String, String)>, |
| 53 | + /// Overwrite if template already exists |
| 54 | + #[arg(long, short = 'f')] |
| 55 | + force: bool, |
| 56 | + }, |
| 57 | +} |
| 58 | + |
| 59 | +impl TemplatesArgs { |
| 60 | + pub async fn run( |
| 61 | + &self, |
| 62 | + output_level: OutputLevel, |
| 63 | + cli_config: &CliConfig, |
| 64 | + _cli: &Cli, |
| 65 | + ) -> Result<()> { |
| 66 | + let mut store = TemplateStore::new(&cli_config.config_base_path); |
| 67 | + store.load()?; |
| 68 | + |
| 69 | + match &self.action { |
| 70 | + TemplateAction::List => { |
| 71 | + let names = store.list(); |
| 72 | + if names.is_empty() { |
| 73 | + output::note("No templates found.", output_level); |
| 74 | + } else { |
| 75 | + output::heading("Available templates:", output_level); |
| 76 | + for name in names { |
| 77 | + output::note(&format!(" - {name}"), output_level); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + TemplateAction::Show { name } => { |
| 82 | + if let Some(tpl) = store.get(name) { |
| 83 | + output::heading(&format!("Template: {name}"), output_level); |
| 84 | + if let Some(desc) = &tpl.description { |
| 85 | + output::note(&format!("Description: {desc}"), output_level); |
| 86 | + } |
| 87 | + if let Some(sys) = &tpl.system_prompt { |
| 88 | + output::note("System Prompt:", output_level); |
| 89 | + output::note(sys, output_level); |
| 90 | + } |
| 91 | + |
| 92 | + if let Some(user) = &tpl.user_prompt { |
| 93 | + output::note("User Prompt:", output_level); |
| 94 | + output::note(user, output_level); |
| 95 | + } |
| 96 | + |
| 97 | + if !tpl.defaults.is_empty() { |
| 98 | + output::note("\nDefaults:", output_level); |
| 99 | + for (k, v) in &tpl.defaults { |
| 100 | + output::note(&format!(" {k} = {v}"), output_level); |
| 101 | + } |
| 102 | + } |
| 103 | + } else { |
| 104 | + output::error(&format!("Template '{name}' not found."), output_level); |
| 105 | + } |
| 106 | + } |
| 107 | + TemplateAction::Remove { name } => match store.delete(name) { |
| 108 | + Ok(true) => output::success(&format!("Removed template '{name}'."), output_level), |
| 109 | + Ok(false) => { |
| 110 | + output::warning(&format!("Template '{name}' not found."), output_level) |
| 111 | + } |
| 112 | + Err(e) => output::error( |
| 113 | + &format!("Failed to delete template '{name}': {e}"), |
| 114 | + output_level, |
| 115 | + ), |
| 116 | + }, |
| 117 | + TemplateAction::Edit { name } => { |
| 118 | + use std::env; |
| 119 | + use std::process::Command; |
| 120 | + use std::process::Stdio; |
| 121 | + |
| 122 | + if !store.contains(name) { |
| 123 | + output::error(&format!("Template '{name}' not found."), output_level); |
| 124 | + return Ok(()); |
| 125 | + } |
| 126 | + |
| 127 | + let file_path = store.templates_dir().join(format!("{name}.toml")); |
| 128 | + let editor = env::var("EDITOR").unwrap_or_else(|_| "nvim".to_string()); |
| 129 | + |
| 130 | + let status = Command::new(&editor) |
| 131 | + .arg(&file_path) |
| 132 | + .stdin(Stdio::inherit()) |
| 133 | + .stdout(Stdio::inherit()) |
| 134 | + .stderr(Stdio::inherit()) |
| 135 | + .status(); |
| 136 | + |
| 137 | + match status { |
| 138 | + Ok(s) if s.success() => { |
| 139 | + // Reload the store to refresh in-memory state |
| 140 | + if let Err(e) = store.load() { |
| 141 | + output::warning( |
| 142 | + &format!("Edited, but failed to reload templates: {e}"), |
| 143 | + output_level, |
| 144 | + ); |
| 145 | + } else { |
| 146 | + output::success(&format!("Edited template '{name}'."), output_level); |
| 147 | + } |
| 148 | + } |
| 149 | + Ok(s) => { |
| 150 | + output::error(&format!("Editor exited with status: {s}"), output_level); |
| 151 | + } |
| 152 | + Err(e) => { |
| 153 | + output::error(&format!("Failed to launch editor: {e}"), output_level); |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + TemplateAction::Create { |
| 158 | + name, |
| 159 | + user_prompt, |
| 160 | + system_prompt, |
| 161 | + description, |
| 162 | + defaults, |
| 163 | + force, |
| 164 | + } => { |
| 165 | + // Check if already exists |
| 166 | + if store.contains(name) && !*force { |
| 167 | + output::warning( |
| 168 | + &format!("Template '{name}' already exists. Use --force to overwrite."), |
| 169 | + output_level, |
| 170 | + ); |
| 171 | + return Ok(()); |
| 172 | + } |
| 173 | + |
| 174 | + let mut template = |
| 175 | + crate::templates::Template::new(name.clone(), user_prompt.clone()); |
| 176 | + template.system_prompt = system_prompt.clone(); |
| 177 | + template.description = description.clone(); |
| 178 | + // Insert defaults |
| 179 | + for (k, v) in defaults { |
| 180 | + template.defaults.insert(k.clone(), v.clone()); |
| 181 | + } |
| 182 | + |
| 183 | + match store.save(&template) { |
| 184 | + Ok(_) => output::success(&format!("Saved template '{name}'."), output_level), |
| 185 | + Err(e) => output::error( |
| 186 | + &format!("Failed to save template '{name}': {e}"), |
| 187 | + output_level, |
| 188 | + ), |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + Ok(()) |
| 194 | + } |
| 195 | +} |
| 196 | + |
| 197 | +fn parse_default_kv(s: &str) -> std::result::Result<(String, String), String> { |
| 198 | + if let Some((k, v)) = s.split_once('=') { |
| 199 | + if k.trim().is_empty() { |
| 200 | + return Err("Key cannot be empty".into()); |
| 201 | + } |
| 202 | + Ok((k.trim().to_string(), v.trim().to_string())) |
| 203 | + } else { |
| 204 | + Err("Expected key=value format".into()) |
| 205 | + } |
| 206 | +} |
0 commit comments