1use clap::{Parser, Subcommand};
2use cli_core::{CliListDataFindings, CliSelectColumn, CommandError, start_server};
3use rpc::{ScriptCtx, Session};
4use server::bootstrap::ADMIN_USER_ID;
5use server::command::Argument;
6use sqlx::types::Uuid;
7use std::collections::HashMap;
8use std::str::FromStr;
9use tracing::level_filters::LevelFilter;
10
11mod account_merge;
12mod dispatch;
13mod disposable;
14mod eval;
15mod flat;
16mod references;
17mod reports;
18mod script;
19mod ssh_key;
20mod template;
21mod transaction;
22
23use dispatch::run_and_print;
24use eval::{RenderMode, build_remove_ssh_key_form, escape_str, eval_print};
25use flat::{AccountForms, CommodityForms, ConfigForms, TagForms, delete_tag_confirmed};
26use reports::ReportsCmd;
27use script::ScriptCmd;
28use std::io::IsTerminal;
29use template::TemplateCmd;
30use transaction::TransactionCmd;
31
32#[derive(Debug, Clone)]
33struct FieldContentPair {
34 field: String,
35 content: String,
36}
37
38impl FromStr for FieldContentPair {
39 type Err = String;
40
41 fn from_str(s: &str) -> Result<Self, Self::Err> {
42 let parts: Vec<&str> = s.splitn(2, '=').collect();
43 if parts.len() == 2 {
44 Ok(FieldContentPair {
45 field: parts[0].to_string(),
46 content: parts[1].to_string(),
47 })
48 } else {
49 Err("Expected format `field=content`".to_string())
50 }
51 }
52}
53
54#[derive(Parser, Debug)]
55#[command(name = "nomisync", about = "Nomisync automation CLI")]
56struct Cli {
57 #[arg(short = 'u', long)]
58 userid: Uuid,
59
60 #[arg(short = 'd', long)]
61 database: Option<String>,
62
63 #[arg(long)]
64 setopt: Option<FieldContentPair>,
65
66 #[arg(long)]
67 loglevel: Option<LevelFilter>,
68
69 #[command(subcommand)]
70 cmd: Command,
71}
72
73#[derive(Subcommand, Debug)]
74enum Command {
75 Version,
77
78 #[command(subcommand)]
80 Account(AccountCmd),
81
82 #[command(subcommand)]
84 Transaction(TransactionCmd),
85
86 #[command(subcommand)]
88 Commodity(CommodityCmd),
89
90 #[command(subcommand)]
92 Tag(TagCmd),
93
94 #[command(subcommand)]
96 Template(TemplateCmd),
97
98 #[command(subcommand)]
100 Script(ScriptCmd),
101
102 #[command(subcommand)]
104 Config(ConfigCmd),
105
106 #[command(subcommand)]
108 Sql(SqlCmd),
109
110 #[command(subcommand)]
112 Reports(ReportsCmd),
113
114 #[command(subcommand, name = "ssh-key")]
116 SshKey(SshKeyCmd),
117
118 #[command(subcommand)]
120 Admin(AdminCmd),
121}
122
123#[derive(Subcommand, Debug)]
124enum AdminCmd {
125 Findings {
127 #[arg(long)]
129 kind: Option<String>,
130 },
131 #[command(name = "check-forms")]
134 CheckForms {
135 #[arg(long)]
137 disposable: bool,
138 },
139 #[command(name = "check-references")]
143 CheckReferences {
144 #[arg(long)]
146 sources: Option<std::path::PathBuf>,
147 },
148}
149
150#[derive(Subcommand, Debug)]
151enum SshKeyCmd {
152 Add {
154 #[arg(
156 long,
157 conflicts_with = "public_key",
158 required_unless_present = "public_key"
159 )]
160 key_file: Option<String>,
161 #[arg(
163 long,
164 conflicts_with = "key_file",
165 required_unless_present = "key_file"
166 )]
167 public_key: Option<String>,
168 #[arg(long)]
170 annotation: Option<String>,
171 },
172 List,
174 Remove {
176 #[arg(long)]
178 fingerprint: String,
179 },
180}
181
182#[derive(Subcommand, Debug)]
183enum AccountCmd {
184 List,
186 Balance {
188 #[arg(long)]
189 account: Uuid,
190 },
191 #[command(flatten)]
192 Forms(AccountForms),
193 Merge(account_merge::MergeArgs),
196}
197
198#[derive(Subcommand, Debug)]
199enum CommodityCmd {
200 List,
202 #[command(flatten)]
203 Forms(CommodityForms),
204}
205
206#[derive(Subcommand, Debug)]
207enum TagCmd {
208 List,
210 Delete {
212 id: Uuid,
214 #[arg(long)]
216 yes: bool,
217 },
218 #[command(flatten)]
219 Forms(TagForms),
220}
221
222#[derive(Subcommand, Debug)]
223enum ConfigCmd {
224 Get {
226 #[arg(long)]
227 name: String,
228 },
229 #[command(flatten)]
230 Forms(ConfigForms),
231}
232
233#[derive(Subcommand, Debug)]
234enum SqlCmd {
235 Selcol {
237 #[arg(long)]
238 field: String,
239 #[arg(long)]
240 table: String,
241 },
242}
243
244#[tokio::main]
245async fn main() -> anyhow::Result<()> {
246 let cli = Cli::parse();
247
248 server::telemetry::init_logging(cli.loglevel, LevelFilter::WARN)?;
249
250 if let Command::Admin(AdminCmd::CheckForms { disposable }) = &cli.cmd {
251 let database = cli
252 .database
253 .clone()
254 .or_else(|| std::env::var("DATABASE_URL").ok());
255 if let Err(message) = disposable::require(*disposable, database.as_deref()) {
256 eprintln!("Error: {message}");
257 std::process::exit(1);
258 }
259 }
260
261 let setopt = cli.setopt.map(|p| (p.field, p.content));
262 start_server(cli.database, setopt).await?;
263
264 let session_result = Session::new(ScriptCtx::new(cli.userid));
265 let mut session = match session_result {
266 Ok(s) => s,
267 Err(e) => {
268 eprintln!("Error: session init failed: {e}");
269 std::process::exit(1);
270 }
271 };
272
273 let outcome = dispatch_command(&mut session, cli.userid, cli.cmd).await;
274 match outcome {
275 Ok(()) => Ok(()),
276 Err(err) => {
277 eprintln!("{}", error_text(&err));
278 std::process::exit(1);
279 }
280 }
281}
282
283async fn dispatch_command(
284 session: &mut Session,
285 userid: Uuid,
286 cmd: Command,
287) -> Result<(), CommandError> {
288 match cmd {
289 Command::Version => eval_print(session, "(get-version)", RenderMode::Scalar).await,
290 Command::Account(c) => run_account(session, userid, c).await,
291 Command::Transaction(c) => transaction::run(session, c).await,
292 Command::Commodity(c) => run_commodity(session, c).await,
293 Command::Tag(c) => run_tag(session, c).await,
294 Command::Template(c) => template::run(session, c).await,
295 Command::Script(c) => script::run(session, c).await,
296 Command::Config(c) => run_config(session, c).await,
297 Command::Sql(c) => run_sql(c).await,
298 Command::Reports(c) => reports::run(session, c).await,
299 Command::SshKey(c) => run_ssh_key(session, c).await,
300 Command::Admin(c) => run_admin(c).await,
301 }
302}
303
304fn error_text(err: &CommandError) -> String {
305 match err {
306 CommandError::FormInvalid(_) => err.to_string(),
307 other => format!("Error: {other}"),
308 }
309}
310
311async fn run_account(
312 session: &mut Session,
313 _userid: Uuid,
314 cmd: AccountCmd,
315) -> Result<(), CommandError> {
316 match cmd {
317 AccountCmd::List => eval_print(session, "(list-accounts)", RenderMode::AccountList).await,
318 AccountCmd::Balance { account } => {
319 let form = format!("(get-balances {})", escape_str(&account.to_string()));
320 eval_print(session, &form, RenderMode::BalanceList).await
321 }
322 AccountCmd::Forms(forms) => forms.run(session).await,
323 AccountCmd::Merge(args) => account_merge::run(session, &args).await,
324 }
325}
326
327async fn run_commodity(session: &mut Session, cmd: CommodityCmd) -> Result<(), CommandError> {
328 match cmd {
329 CommodityCmd::List => {
330 eval_print(session, "(list-commodities)", RenderMode::CommodityList).await
331 }
332 CommodityCmd::Forms(forms) => forms.run(session).await,
333 }
334}
335
336async fn run_tag(session: &mut Session, cmd: TagCmd) -> Result<(), CommandError> {
337 match cmd {
338 TagCmd::List => eval_print(session, "(list-tags)", RenderMode::TagList).await,
339 TagCmd::Delete { id, yes } => {
340 let stdin = std::io::stdin();
341 if !delete_tag_confirmed(session, id, yes, stdin.is_terminal(), stdin.lock()).await? {
342 eprintln!("Cancelled");
343 }
344 Ok(())
345 }
346 TagCmd::Forms(forms) => forms.run(session).await,
347 }
348}
349
350async fn run_config(session: &mut Session, cmd: ConfigCmd) -> Result<(), CommandError> {
351 match cmd {
352 ConfigCmd::Get { name } => {
353 let form = format!("(get-config {})", escape_str(&name));
354 eval_print(session, &form, RenderMode::ConfigValue).await
355 }
356 ConfigCmd::Forms(forms) => forms.run(session).await,
357 }
358}
359
360async fn run_sql(cmd: SqlCmd) -> Result<(), CommandError> {
361 match cmd {
362 SqlCmd::Selcol { field, table } => {
363 let mut args: HashMap<&str, Argument> = HashMap::new();
364 args.insert("field", Argument::String(field));
365 args.insert("table", Argument::String(table));
366 run_and_print(&CliSelectColumn, args).await
367 }
368 }
369}
370
371async fn run_admin(cmd: AdminCmd) -> Result<(), CommandError> {
372 match cmd {
373 AdminCmd::Findings { kind } => {
374 let mut args: HashMap<&str, Argument> = HashMap::new();
375 if let Some(kind) = kind {
376 args.insert("kind", Argument::String(kind));
377 }
378 run_and_print(&CliListDataFindings, args).await
379 }
380 AdminCmd::CheckForms { .. } => check_forms().await,
381 AdminCmd::CheckReferences { sources } => {
382 let admin = ADMIN_USER_ID
383 .parse::<Uuid>()
384 .map_err(|e| CommandError::Argument(format!("admin id: {e}")))?;
385 references::run(admin, sources.as_deref()).await
386 }
387 }
388}
389
390async fn check_forms() -> Result<(), CommandError> {
391 let admin = ADMIN_USER_ID
392 .parse::<Uuid>()
393 .map_err(|e| CommandError::Argument(format!("admin id: {e}")))?;
394 let report = rpc::preflight::check_forms(admin)
395 .await
396 .map_err(|e| CommandError::Command(e.to_string()))?;
397 report.problems.iter().for_each(|p| println!("{p}"));
398 println!("{}", report.summary());
399 match report.problems.is_empty() {
400 true => Ok(()),
401 false => Err(CommandError::Command("form preflight failed".to_string())),
402 }
403}
404
405async fn run_ssh_key(session: &mut Session, cmd: SshKeyCmd) -> Result<(), CommandError> {
406 match cmd {
407 SshKeyCmd::Add {
408 key_file,
409 public_key,
410 annotation,
411 } => ssh_key::add(session, key_file, public_key, annotation).await,
412 SshKeyCmd::List => eval_print(session, "(list-ssh-keys)", RenderMode::SshKeyList).await,
413 SshKeyCmd::Remove { fingerprint } => {
414 let form = build_remove_ssh_key_form(&fingerprint);
415 eval_print(session, &form, RenderMode::BoolSuccess).await
416 }
417 }
418}
419
420#[cfg(test)]
421mod tests;