use std::ffi::OsString;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::Command as Process;
use blubat_core::{Config, Device, Paths};
use toml_edit::{Array, DocumentMut, Item, Table, value};
use crate::{Failure, reading};
#[derive(Debug, clap::Subcommand)]
pub enum Command {
Path,
Edit,
Validate,
}
pub fn run(command: &Command, paths: &Paths) -> Result<(), Failure> {
let path = paths.config_file();
match command {
Command::Path => {
println!("{}", path.display());
Ok(())
}
Command::Edit => edit(path, &editor(|name| std::env::var(name).ok())?),
Command::Validate => validate(path, &mut io::stdout(), || reading().devices),
}
}
pub fn save_hidden(path: &Path, hidden: &[String]) -> Result<(), String> {
document(path)
.and_then(|mut document| {
set_hidden(&mut document, hidden)?;
write_atomically(path, &document.to_string())
})
.map_err(|problem| format!("{}: {problem}", path.display()))
}
fn document(path: &Path) -> Result<DocumentMut, String> {
match fs::read_to_string(path) {
Ok(written) => written
.parse()
.map_err(|error: toml_edit::TomlError| format!("{error}, so the hide was not written")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(DocumentMut::new()),
Err(error) => Err(error.to_string()),
}
}
fn set_hidden(document: &mut DocumentMut, hidden: &[String]) -> Result<(), String> {
document
.entry("dashboard")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or_else(|| String::from("[dashboard] is not a table"))
.map(|dashboard| {
dashboard.insert(
"hidden",
value(hidden.iter().map(String::as_str).collect::<Array>()),
);
})
}
fn write_atomically(path: &Path, contents: &str) -> Result<(), String> {
let mut partial = OsString::from(path);
partial.push(".partial");
let partial = PathBuf::from(partial);
let written = path
.parent()
.map_or(Ok(()), fs::create_dir_all)
.and_then(|()| fs::write(&partial, contents))
.and_then(|()| fs::rename(&partial, path));
if written.is_err() {
let _ = fs::remove_file(&partial);
}
written.map_err(|error| error.to_string())
}
fn editor(variable: impl Fn(&str) -> Option<String>) -> Result<String, Failure> {
["EDITOR", "VISUAL"]
.into_iter()
.filter_map(variable)
.find(|editor| !editor.trim().is_empty())
.ok_or_else(|| {
Failure::Error("set $EDITOR to the editor blubat should open the config in".to_string())
})
}
fn edit(path: &Path, editor: &str) -> Result<(), Failure> {
let (program, arguments) = split(editor);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|error| Failure::Error(format!("{}: {error}", parent.display())))?;
}
Process::new(program)
.args(arguments)
.arg(path)
.status()
.map_err(|error| Failure::Error(format!("{editor}: {error}")))
.and_then(|status| {
status
.success()
.then_some(())
.ok_or_else(|| Failure::Error(format!("{editor} exited with {status}")))
})
}
fn split(editor: &str) -> (&str, Vec<&str>) {
let mut words = editor.split_whitespace();
(words.next().unwrap_or(editor), words.collect())
}
fn validate(
path: &Path,
out: &mut impl Write,
devices: impl Fn() -> Vec<Device>,
) -> Result<(), Failure> {
let Some(config) = Config::read(path)? else {
writeln!(
out,
"{}: no config file, blubat runs on built-in defaults",
path.display()
)?;
return Ok(());
};
if !config.devices.is_empty() {
for pattern in config.unmatched(&devices()) {
writeln!(
out,
"warning: [[device]] match = \"{pattern}\" matches no device blubat can see"
)?;
}
}
let problems: String = config
.problems()
.iter()
.map(|problem| format!("\n {problem}"))
.collect();
if problems.is_empty() {
writeln!(out, "{}: ok", path.display())?;
Ok(())
} else {
Err(Failure::Error(format!("{}{problems}", path.display())))
}
}
#[cfg(test)]
mod tests {
use blubat_core::{Address, ChargeState, Levels, Source, Timestamp};
use crate::scratch::Scratch;
use super::*;
fn trackpad() -> Device {
Device {
address: Address::parse("30-82-16-f2-24-90").expect("valid address"),
name: "Paul\u{2019}s Magic Trackpad".to_string(),
kind: None,
transport: None,
levels: Levels {
main: Some(42),
..Levels::default()
},
charge: ChargeState::Unknown,
source: Source::IoKit,
connected: true,
read_at: Timestamp::from_unix(0),
}
}
fn check(path: &Path, devices: Vec<Device>) -> (Result<(), Failure>, String) {
let mut printed = Vec::new();
let outcome = validate(path, &mut printed, || devices.clone());
(outcome, String::from_utf8(printed).expect("utf8 output"))
}
#[test]
fn no_config_file_is_a_pass_that_says_so() {
let scratch = Scratch::new();
let (outcome, printed) = check(&scratch.config_file(), Vec::new());
assert_eq!(outcome, Ok(()));
assert!(printed.contains("no config file"), "{printed}");
assert!(!scratch.config_file().exists(), "checking created nothing");
}
#[test]
fn a_usable_file_passes() {
let scratch = Scratch::new();
let path =
scratch.write_config("[defaults]\nlow = 25\n\n[notifications]\nsound = \"Ping\"\n");
let (outcome, printed) = check(&path, Vec::new());
assert_eq!(outcome, Ok(()));
assert!(printed.contains("ok"), "{printed}");
}
#[test]
fn a_malformed_file_fails_with_the_line_it_is_on() {
let scratch = Scratch::new();
let path = scratch.write_config("[defaults]\nlow = 20\ncritical = \"ten\"\n");
let (outcome, printed) = check(&path, Vec::new());
let message = outcome
.expect_err("a string threshold is not a number")
.to_string();
assert!(message.contains("line 3"), "{message}");
assert!(message.contains(&path.display().to_string()), "{message}");
assert!(printed.is_empty(), "{printed}");
}
#[test]
fn an_unknown_key_fails_rather_than_being_ignored() {
let scratch = Scratch::new();
let path = scratch.write_config("[defaults]\nlwo = 20\n");
assert!(check(&path, Vec::new()).0.is_err());
}
#[test]
fn thresholds_that_cannot_hold_fail_with_every_problem_listed() {
let scratch = Scratch::new();
let path = scratch.write_config("[defaults]\nlow = 20\nhigh = 15\n");
let message = check(&path, Vec::new())
.0
.expect_err("low is above high")
.to_string();
assert!(
message.contains("low (20) must be below high (15)"),
"{message}"
);
}
#[test]
fn a_block_matching_nothing_warns_without_failing() {
let scratch = Scratch::new();
let path = scratch.write_config("[[device]]\nmatch = \"trackpad\"\nlow = 25\n");
let (matched, quiet) = check(&path, vec![trackpad()]);
let (unmatched, warned) = check(&path, Vec::new());
assert_eq!(matched, Ok(()));
assert!(!quiet.contains("warning"), "{quiet}");
assert_eq!(unmatched, Ok(()), "a device may simply be switched off");
assert!(warned.contains("warning"), "{warned}");
assert!(warned.contains("trackpad"), "{warned}");
}
#[test]
fn hiding_a_device_writes_the_table_and_nothing_else_in_the_file() {
let scratch = Scratch::new();
let written = "# my thresholds\n[defaults]\nlow = 25\n\n\
[[device]]\nmatch = \"trackpad\"\nlow = 30\n\n\
[[hook]]\nevent = \"low_battery\"\ncommand = \"nag\" # shouts\n\n\
[[hook]]\nevent = \"charged\"\ncommand = \"unplug\"\n\n\
[experimental]\nnothing_blubat_knows = true\n\n\
[dashboard]\nhidden = [\"MX Master\"] # for now\nsort = \"name\"\n";
let path = scratch.write_config(written);
assert_eq!(
save_hidden(&path, &["MX Master".to_string(), "30-82-16".to_string()]),
Ok(())
);
assert_eq!(
fs::read_to_string(&path).expect("a written config"),
written.replace(
"hidden = [\"MX Master\"] # for now",
"hidden = [\"MX Master\", \"30-82-16\"]"
),
"the comments, the order and every other table survive the hide"
);
}
#[test]
fn a_dashboard_that_is_not_a_table_is_reported_rather_than_replaced() {
let scratch = Scratch::new();
let path = scratch.write_config("dashboard = 5\n");
let problem = save_hidden(&path, &["30-82-16".to_string()])
.expect_err("there is nowhere to put the list");
assert!(problem.contains("[dashboard] is not a table"), "{problem}");
assert_eq!(
fs::read_to_string(&path).expect("still there"),
"dashboard = 5\n"
);
}
#[test]
fn hiding_the_first_device_creates_a_file_holding_that_table_alone() {
let scratch = Scratch::new();
let path = scratch.config_file();
assert_eq!(save_hidden(&path, &["30-82-16".to_string()]), Ok(()));
assert_eq!(
fs::read_to_string(&path).expect("a written config"),
"[dashboard]\nhidden = [\"30-82-16\"]\n"
);
assert_eq!(
Config::load(&path).expect("blubat reads back what it wrote"),
Config {
dashboard: blubat_core::Dashboard {
hidden: vec!["30-82-16".to_string()],
..blubat_core::Dashboard::default()
},
..Config::default()
}
);
}
#[test]
fn showing_the_last_device_again_leaves_the_list_empty_rather_than_absent() {
let scratch = Scratch::new();
let path = scratch.write_config("[dashboard]\nhidden = [\"30-82-16\"]\n");
assert_eq!(save_hidden(&path, &[]), Ok(()));
assert_eq!(
fs::read_to_string(&path).expect("a written config"),
"[dashboard]\nhidden = []\n"
);
}
#[test]
fn a_file_that_will_not_parse_is_reported_rather_than_overwritten() {
let scratch = Scratch::new();
let path = scratch.write_config("[defaults\nlow = 25\n");
let problem = save_hidden(&path, &["30-82-16".to_string()])
.expect_err("an unclosed table header is not TOML");
assert!(problem.contains(&path.display().to_string()), "{problem}");
assert_eq!(
fs::read_to_string(&path).expect("still there"),
"[defaults\nlow = 25\n",
"a file blubat cannot read is a file it will not rewrite"
);
}
#[test]
fn the_editor_is_the_first_of_the_two_variables_that_names_one() {
let set = |variables: [(&'static str, &'static str); 2]| {
move |name: &str| {
variables
.iter()
.find(|(key, _)| *key == name)
.map(|(_, value)| (*value).to_string())
.filter(|value| !value.is_empty())
}
};
assert_eq!(
editor(set([("EDITOR", "vim"), ("VISUAL", "")])),
Ok("vim".to_string())
);
assert_eq!(
editor(set([("EDITOR", ""), ("VISUAL", "code -w")])),
Ok("code -w".to_string())
);
assert_eq!(
editor(set([("EDITOR", "vim"), ("VISUAL", "code -w")])),
Ok("vim".to_string()),
"EDITOR is asked first"
);
assert_eq!(
editor(set([("EDITOR", " "), ("VISUAL", "code -w")])),
Ok("code -w".to_string()),
"a variable set to nothing but spaces names no editor"
);
assert!(
editor(|_| None)
.expect_err("nothing to open it in")
.to_string()
.contains("set $EDITOR")
);
}
#[test]
fn an_editor_setting_splits_into_a_program_and_its_arguments() {
assert_eq!(split("vim"), ("vim", Vec::new()));
assert_eq!(split("code -w"), ("code", vec!["-w"]));
assert_eq!(split(" emacsclient -nw "), ("emacsclient", vec!["-nw"]));
}
#[test]
fn editing_makes_room_for_the_file_without_creating_it() {
let scratch = Scratch::new();
let path = scratch.config_file();
assert_eq!(edit(&path, "/usr/bin/true"), Ok(()));
assert!(path.parent().expect("a parent").is_dir(), "nowhere to save");
assert!(
!path.exists(),
"an editor that saved nothing leaves nothing"
);
}
#[test]
fn an_editor_that_fails_is_reported() {
let scratch = Scratch::new();
let failed = edit(&scratch.config_file(), "/usr/bin/false")
.expect_err("a non zero exit is a failure");
let missing = edit(&scratch.config_file(), "/nonexistent-editor")
.expect_err("an editor that is not there is a failure");
assert!(failed.to_string().contains("exited"), "{failed}");
assert!(matches!(missing, Failure::Error(_)));
}
}