Lines
23.7 %
Functions
7.14 %
Branches
100 %
use clap::{Parser, Subcommand};
use cli_core::{CliListDataFindings, CliSelectColumn, CommandError, start_server};
use rpc::{ScriptCtx, Session};
use server::bootstrap::ADMIN_USER_ID;
use server::command::Argument;
use sqlx::types::Uuid;
use std::collections::HashMap;
use std::str::FromStr;
use tracing::level_filters::LevelFilter;
mod account_merge;
mod dispatch;
mod disposable;
mod eval;
mod flat;
mod references;
mod reports;
mod script;
mod ssh_key;
mod template;
mod transaction;
use dispatch::run_and_print;
use eval::{RenderMode, build_remove_ssh_key_form, escape_str, eval_print};
use flat::{AccountForms, CommodityForms, ConfigForms, TagForms, delete_tag_confirmed};
use reports::ReportsCmd;
use script::ScriptCmd;
use std::io::IsTerminal;
use template::TemplateCmd;
use transaction::TransactionCmd;
#[derive(Debug, Clone)]
struct FieldContentPair {
field: String,
content: String,
}
impl FromStr for FieldContentPair {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.splitn(2, '=').collect();
if parts.len() == 2 {
Ok(FieldContentPair {
field: parts[0].to_string(),
content: parts[1].to_string(),
})
} else {
Err("Expected format `field=content`".to_string())
#[derive(Parser, Debug)]
#[command(name = "nomisync", about = "Nomisync automation CLI")]
struct Cli {
#[arg(short = 'u', long)]
userid: Uuid,
#[arg(short = 'd', long)]
database: Option<String>,
#[arg(long)]
setopt: Option<FieldContentPair>,
loglevel: Option<LevelFilter>,
#[command(subcommand)]
cmd: Command,
#[derive(Subcommand, Debug)]
enum Command {
/// Print the software version
Version,
/// Access to accounts
Account(AccountCmd),
/// Access to transactions
Transaction(TransactionCmd),
/// Access to commodities
Commodity(CommodityCmd),
/// Access to tags
Tag(TagCmd),
/// Access to transaction templates
Template(TemplateCmd),
/// Access to scripts
Script(ScriptCmd),
/// Access to configuration
Config(ConfigCmd),
/// Access to SQL database
Sql(SqlCmd),
/// Text-rendered report charts
Reports(ReportsCmd),
/// Manage SSH public keys for remote TUI access
#[command(subcommand, name = "ssh-key")]
SshKey(SshKeyCmd),
/// Administrative reports about the stored data
Admin(AdminCmd),
enum AdminCmd {
/// List the data problems migrations recorded instead of fixing
Findings {
/// Only the findings of this kind
kind: Option<String>,
},
/// Open every stored transaction and template in the forms and save each
/// transaction unchanged. It writes: aim it at a restored copy only
#[command(name = "check-forms")]
CheckForms {
/// Confirms the database is a disposable restored copy
disposable: bool,
/// List the stored templates and declared sources that name an account or
/// commodity ambiguously or by a bare name, and check the trigger host
/// resolves no names. Read-only
#[command(name = "check-references")]
CheckReferences {
/// Directory of shipped source files (`.org`, `.nms`, `.lisp`) to scan
sources: Option<std::path::PathBuf>,
enum SshKeyCmd {
/// Register a public key for the current user
Add {
/// Path to a `.pub` OpenSSH public-key file
#[arg(
long,
conflicts_with = "public_key",
required_unless_present = "public_key"
)]
key_file: Option<String>,
/// OpenSSH `authorized_keys` line passed inline
conflicts_with = "key_file",
required_unless_present = "key_file"
public_key: Option<String>,
/// Optional human-readable label
annotation: Option<String>,
/// List all keys for the current user
List,
/// Remove a key by its SHA-256 fingerprint
Remove {
/// Fingerprint, e.g. `SHA256:abc…`
fingerprint: String,
enum AccountCmd {
/// List all accounts
/// Get the current balance and currency of an account
Balance {
account: Uuid,
#[command(flatten)]
Forms(AccountForms),
/// Merge one account into another: its splits, lots, budgets, sub-accounts
/// and tags move, and it is deleted
Merge(account_merge::MergeArgs),
enum CommodityCmd {
/// List all commodities
Forms(CommodityForms),
enum TagCmd {
/// List all tags
/// Delete a tag with every link to it
Delete {
/// Id of the tag
id: Uuid,
/// Delete without asking; required when stdin is not a terminal
yes: bool,
Forms(TagForms),
enum ConfigCmd {
/// Print the value from config; there is no get form, so it stays on `get-config`
Get {
name: String,
Forms(ConfigForms),
enum SqlCmd {
/// Raw select of SQL table
Selcol {
table: String,
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
server::telemetry::init_logging(cli.loglevel, LevelFilter::WARN)?;
if let Command::Admin(AdminCmd::CheckForms { disposable }) = &cli.cmd {
let database = cli
.database
.clone()
.or_else(|| std::env::var("DATABASE_URL").ok());
if let Err(message) = disposable::require(*disposable, database.as_deref()) {
eprintln!("Error: {message}");
std::process::exit(1);
let setopt = cli.setopt.map(|p| (p.field, p.content));
start_server(cli.database, setopt).await?;
let session_result = Session::new(ScriptCtx::new(cli.userid));
let mut session = match session_result {
Ok(s) => s,
Err(e) => {
eprintln!("Error: session init failed: {e}");
};
let outcome = dispatch_command(&mut session, cli.userid, cli.cmd).await;
match outcome {
Ok(()) => Ok(()),
Err(err) => {
eprintln!("{}", error_text(&err));
async fn dispatch_command(
session: &mut Session,
) -> Result<(), CommandError> {
match cmd {
Command::Version => eval_print(session, "(get-version)", RenderMode::Scalar).await,
Command::Account(c) => run_account(session, userid, c).await,
Command::Transaction(c) => transaction::run(session, c).await,
Command::Commodity(c) => run_commodity(session, c).await,
Command::Tag(c) => run_tag(session, c).await,
Command::Template(c) => template::run(session, c).await,
Command::Script(c) => script::run(session, c).await,
Command::Config(c) => run_config(session, c).await,
Command::Sql(c) => run_sql(c).await,
Command::Reports(c) => reports::run(session, c).await,
Command::SshKey(c) => run_ssh_key(session, c).await,
Command::Admin(c) => run_admin(c).await,
fn error_text(err: &CommandError) -> String {
match err {
CommandError::FormInvalid(_) => err.to_string(),
other => format!("Error: {other}"),
async fn run_account(
_userid: Uuid,
cmd: AccountCmd,
AccountCmd::List => eval_print(session, "(list-accounts)", RenderMode::AccountList).await,
AccountCmd::Balance { account } => {
let form = format!("(get-balances {})", escape_str(&account.to_string()));
eval_print(session, &form, RenderMode::BalanceList).await
AccountCmd::Forms(forms) => forms.run(session).await,
AccountCmd::Merge(args) => account_merge::run(session, &args).await,
async fn run_commodity(session: &mut Session, cmd: CommodityCmd) -> Result<(), CommandError> {
CommodityCmd::List => {
eval_print(session, "(list-commodities)", RenderMode::CommodityList).await
CommodityCmd::Forms(forms) => forms.run(session).await,
async fn run_tag(session: &mut Session, cmd: TagCmd) -> Result<(), CommandError> {
TagCmd::List => eval_print(session, "(list-tags)", RenderMode::TagList).await,
TagCmd::Delete { id, yes } => {
let stdin = std::io::stdin();
if !delete_tag_confirmed(session, id, yes, stdin.is_terminal(), stdin.lock()).await? {
eprintln!("Cancelled");
Ok(())
TagCmd::Forms(forms) => forms.run(session).await,
async fn run_config(session: &mut Session, cmd: ConfigCmd) -> Result<(), CommandError> {
ConfigCmd::Get { name } => {
let form = format!("(get-config {})", escape_str(&name));
eval_print(session, &form, RenderMode::ConfigValue).await
ConfigCmd::Forms(forms) => forms.run(session).await,
async fn run_sql(cmd: SqlCmd) -> Result<(), CommandError> {
SqlCmd::Selcol { field, table } => {
let mut args: HashMap<&str, Argument> = HashMap::new();
args.insert("field", Argument::String(field));
args.insert("table", Argument::String(table));
run_and_print(&CliSelectColumn, args).await
async fn run_admin(cmd: AdminCmd) -> Result<(), CommandError> {
AdminCmd::Findings { kind } => {
if let Some(kind) = kind {
args.insert("kind", Argument::String(kind));
run_and_print(&CliListDataFindings, args).await
AdminCmd::CheckForms { .. } => check_forms().await,
AdminCmd::CheckReferences { sources } => {
let admin = ADMIN_USER_ID
.parse::<Uuid>()
.map_err(|e| CommandError::Argument(format!("admin id: {e}")))?;
references::run(admin, sources.as_deref()).await
async fn check_forms() -> Result<(), CommandError> {
let report = rpc::preflight::check_forms(admin)
.await
.map_err(|e| CommandError::Command(e.to_string()))?;
report.problems.iter().for_each(|p| println!("{p}"));
println!("{}", report.summary());
match report.problems.is_empty() {
true => Ok(()),
false => Err(CommandError::Command("form preflight failed".to_string())),
async fn run_ssh_key(session: &mut Session, cmd: SshKeyCmd) -> Result<(), CommandError> {
SshKeyCmd::Add {
key_file,
public_key,
annotation,
} => ssh_key::add(session, key_file, public_key, annotation).await,
SshKeyCmd::List => eval_print(session, "(list-ssh-keys)", RenderMode::SshKeyList).await,
SshKeyCmd::Remove { fingerprint } => {
let form = build_remove_ssh_key_form(&fingerprint);
eval_print(session, &form, RenderMode::BoolSuccess).await
#[cfg(test)]
mod tests;