mod config;
mod daemon;
mod effects;
mod hooks;
mod lock;
mod notify;
mod report;
#[cfg(test)]
mod scratch;
mod tui;
mod wait;
use std::fmt;
use std::io::{self, IsTerminal};
use std::path::PathBuf;
use std::process::ExitCode;
use blubat_core::{Paths, Snapshot};
use clap::{CommandFactory, Parser, Subcommand};
use report::Format;
#[derive(Debug, Parser)]
#[command(name = "blubat", version, about)]
struct Cli {
#[command(subcommand)]
command: Option<Command>,
#[arg(long, global = true, value_name = "PATH")]
config: Option<PathBuf>,
#[arg(long, global = true, value_name = "PATH")]
state_dir: Option<PathBuf>,
}
#[derive(Debug, Subcommand)]
enum Command {
List {
#[arg(long)]
json: bool,
#[arg(long, short)]
all: bool,
},
Status {
#[arg(long, short)]
device: Option<String>,
#[arg(long, conflicts_with = "number")]
json: bool,
#[arg(long, short)]
number: bool,
},
Wait(wait::Args),
Config {
#[command(subcommand)]
command: config::Command,
},
Daemon {
#[command(subcommand)]
command: daemon::Command,
},
NotifyTest,
}
#[derive(Debug, PartialEq, Eq)]
enum Failure {
NoDevice(String),
Error(String),
}
impl Failure {
const ERROR: u8 = 1;
const NO_DEVICE: u8 = 3;
fn code(&self) -> u8 {
match self {
Failure::NoDevice(_) => Self::NO_DEVICE,
Failure::Error(_) => Self::ERROR,
}
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Failure::NoDevice(message) | Failure::Error(message) => f.write_str(message),
}
}
}
impl From<blubat_core::Error> for Failure {
fn from(error: blubat_core::Error) -> Self {
Failure::Error(error.to_string())
}
}
fn main() -> ExitCode {
match Cli::try_parse() {
Ok(cli) => run(cli).map_or_else(fail, |()| ExitCode::SUCCESS),
Err(usage) => {
let _ = usage.print();
if usage.use_stderr() {
ExitCode::from(Failure::ERROR)
} else {
ExitCode::SUCCESS
}
}
}
}
fn run(cli: Cli) -> Result<(), Failure> {
let files = || paths(cli.config.clone(), cli.state_dir.clone());
match cli.command {
Some(Command::List { json, all }) => report::list(&reading(), json, all),
Some(Command::Status {
device,
json,
number,
}) => report::status(&reading(), device.as_deref(), Format::of(json, number)),
Some(Command::Wait(args)) => wait::run(&args, &files()?),
Some(Command::Config { command }) => config::run(&command, &files()?),
Some(Command::Daemon { command }) => daemon::run(&command, &files()?),
Some(Command::NotifyTest) => notify::run(&files()?),
None if io::stdout().is_terminal() => tui::run(&files()?),
None => offer_the_commands(),
}
}
fn paths(config: Option<PathBuf>, state_dir: Option<PathBuf>) -> Result<Paths, Failure> {
let mut paths = Paths::resolve()?;
if let Some(path) = config {
paths = paths.with_config_file(path);
}
if let Some(dir) = state_dir {
paths = paths.with_state_dir(dir);
}
Ok(paths)
}
fn offer_the_commands() -> Result<(), Failure> {
Cli::command().print_help()?;
println!("\nRun `blubat list` for a reading, or `blubat` in a terminal for the dashboard.");
Ok(())
}
fn reading() -> Snapshot {
let snapshot = blubat_core::snapshot();
if snapshot.degraded {
eprintln!("blubat: warning: a source could not be read, so this is its last good answer");
}
for warning in &snapshot.warnings {
eprintln!("blubat: warning: {warning}");
}
snapshot
}
impl From<io::Error> for Failure {
fn from(error: io::Error) -> Self {
Failure::Error(error.to_string())
}
}
fn fail(failure: Failure) -> ExitCode {
eprintln!("blubat: {failure}");
ExitCode::from(failure.code())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_cli_definition_is_well_formed() {
Cli::command().debug_assert();
}
#[test]
fn exit_codes_match_the_documented_contract() {
assert_eq!(Failure::NoDevice("nothing".to_string()).code(), 3);
assert_eq!(Failure::Error("broke".to_string()).code(), 1);
}
#[test]
fn a_core_error_is_an_error_exit_carrying_its_message() {
let failure = Failure::from(blubat_core::Error::Command(
"no system_profiler".to_string(),
));
assert_eq!(failure.code(), 1);
assert_eq!(failure.to_string(), "no system_profiler");
}
}