use std::sync::Mutex;
use colored::Colorize;
use serde_json::json;
use vela_protocol::cli_style as style;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
Usage,
NotFound,
Custody,
Exists,
Domain,
#[allow(dead_code)] Internal,
}
impl ErrorKind {
pub fn exit_code(self) -> i32 {
match self {
Self::Domain | Self::Internal => 1,
Self::Usage => 2,
Self::NotFound => 3,
Self::Custody => 4,
Self::Exists => 5,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Usage => "usage",
Self::NotFound => "not_found",
Self::Custody => "custody_refused",
Self::Exists => "already_exists",
Self::Domain => "domain",
Self::Internal => "internal",
}
}
}
struct Mode {
command: String,
json: bool,
}
static MODE: Mutex<Option<Mode>> = Mutex::new(None);
static QUIET: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn set_mode(command: &str, json: bool) {
*MODE.lock().unwrap() = Some(Mode {
command: command.to_string(),
json,
});
}
pub fn set_quiet(quiet: bool) {
QUIET.store(quiet, std::sync::atomic::Ordering::Relaxed);
}
fn mode() -> (String, bool) {
MODE.lock()
.unwrap()
.as_ref()
.map(|m| (m.command.clone(), m.json))
.unwrap_or_else(|| (String::new(), false))
}
fn advice_enabled() -> bool {
if QUIET.load(std::sync::atomic::Ordering::Relaxed) {
return false;
}
let (v, _) = crate::config::settings::resolve("ui.advice", None);
v != "0" && v != "off"
}
pub fn is_interactive() -> bool {
use std::io::IsTerminal;
std::env::var_os("VELA_NO_INPUT").is_none()
&& std::io::stdin().is_terminal()
&& std::io::stdout().is_terminal()
}
pub fn ensure_can_prompt(what: &str, hint: &str) {
if !is_interactive() {
fail_with(
ErrorKind::Usage,
&format!("refusing to prompt for {what}: not an interactive terminal"),
Some(hint),
);
}
}
pub fn fail_with(kind: ErrorKind, message: &str, hint: Option<&str>) -> ! {
let (command, json) = mode();
if json {
let payload = json!({
"ok": false,
"command": if command.is_empty() { serde_json::Value::Null } else { json!(command) },
"error": {
"kind": kind.as_str(),
"message": message,
"hint": hint,
},
});
println!(
"{}",
serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".into())
);
} else {
let message = crate::cli::safe_text::multiline(message);
eprintln!("{} {message}", style::err_prefix());
if let Some(hint) = hint
&& advice_enabled()
{
eprintln!(" hint: {}", crate::cli::safe_text::inline(hint));
}
}
std::process::exit(kind.exit_code());
}
pub fn fail_unchanged(kind: ErrorKind, message: &str, operation_id: &str, next_command: &str) -> ! {
let (command, json) = mode();
if json {
let payload = json!({
"ok": false,
"command": if command.is_empty() { serde_json::Value::Null } else { json!(command) },
"request_id": operation_id,
"operation_id": operation_id,
"changed": false,
"retained": {
"request_id": operation_id,
"transaction_marker": false,
},
"next": next_command,
"error": {
"kind": kind.as_str(),
"message": message,
"hint": next_command,
},
});
println!(
"{}",
serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".into())
);
} else {
let message = crate::cli::safe_text::multiline(message);
eprintln!("{} {message}", style::err_prefix());
eprintln!(
" {:<16} canonical Vela state, Git refs, index, and worktree",
style::dim("unchanged")
);
eprintln!(
" {:<16} {} (request only; no transaction marker)",
style::dim("retained"),
crate::cli::safe_text::inline(operation_id)
);
eprintln!(
" {:<16} {}",
style::dim("next"),
crate::cli::safe_text::inline(next_command)
);
}
std::process::exit(kind.exit_code());
}
pub fn header(command: &str, subject: &str, note: Option<&str>) {
println!();
let command = crate::cli::safe_text::inline(command);
let subject = crate::cli::safe_text::inline(subject);
let mut line = format!("VELA · {command}");
if !subject.is_empty() {
line.push_str(&format!(" · {subject}"));
}
if let Some(note) = note {
line.push_str(&format!(" ({})", crate::cli::safe_text::inline(note)));
}
println!(" {}", line.to_uppercase().dimmed());
println!(" {}", style::tick_row(60));
}
pub fn resolve_frontier(explicit: Option<std::path::PathBuf>) -> std::path::PathBuf {
if let Some(path) = explicit {
return path;
}
let Ok(mut cur) = std::env::current_dir() else {
fail_with(
ErrorKind::Usage,
"cannot resolve the current directory",
None,
);
};
let started = cur.clone();
loop {
let store = cur.join(".vela");
if store.is_dir()
&& (store.join("events").is_dir()
|| store.join("proposals").is_dir()
|| store.join("genesis.json").is_file())
{
return cur;
}
if !cur.pop() {
fail_with(
ErrorKind::NotFound,
&format!(
"no frontier found from {} up to the filesystem root",
started.display()
),
Some("run `vela init` to create one here, or pass a path: `vela status <dir>`"),
);
}
}
}
pub fn resolve_frontier_with_id(
frontier: Option<std::path::PathBuf>,
id: Option<String>,
id_prefixes: &[&str],
) -> (std::path::PathBuf, Option<String>) {
if let Some(first) = &frontier {
let s = first.display().to_string();
if id.is_none() && id_prefixes.iter().any(|p| s.starts_with(p)) && !first.exists() {
return (resolve_frontier(None), Some(s));
}
}
(resolve_frontier(frontier), id)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exit_codes_follow_the_contract() {
assert_eq!(ErrorKind::Domain.exit_code(), 1);
assert_eq!(ErrorKind::Usage.exit_code(), 2);
assert_eq!(ErrorKind::NotFound.exit_code(), 3);
assert_eq!(ErrorKind::Custody.exit_code(), 4);
assert_eq!(ErrorKind::Exists.exit_code(), 5);
}
#[test]
fn mode_roundtrip() {
set_mode("status", true);
assert!(mode().1);
set_mode("status", false);
assert!(!mode().1);
}
}