use crate::error::{Failure, Result};
use std::collections::BTreeMap;
use std::io::Write as _;
use std::path::Path;
pub type Stored = BTreeMap<String, String>;
pub fn load(file: &Path) -> Result<Stored> {
let text = match std::fs::read_to_string(file) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Stored::new()),
Err(error) => {
return Err(Failure::config(
"config.unreadable",
format!("the settings file at {} could not be read", file.display()),
)
.with_detail("detail", file.display().to_string())
.with_hint("check that the file is readable by this user")
.with_cause(error.to_string()))
}
};
toml::from_str(&text).map_err(|error| {
Failure::config(
"config.malformed",
format!(
"the settings file at {} is not readable as stored settings",
file.display()
),
)
.with_detail("detail", file.display().to_string())
.with_hint("run `config doctor` to see what is wrong, or remove the file to start over")
.with_cause(error.to_string())
})
}
pub fn store(file: &Path, name: &str, raw: &str) -> Result<()> {
let mut settings = load(file)?;
settings.insert(name.to_owned(), raw.to_owned());
write_all(file, &settings)
}
pub fn remove(file: &Path, name: &str) -> Result<bool> {
let mut settings = load(file)?;
let existed = settings.remove(name).is_some();
if existed {
write_all(file, &settings)?;
}
Ok(existed)
}
fn write_all(file: &Path, settings: &Stored) -> Result<()> {
let directory = file.parent().unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(directory).map_err(|error| {
Failure::config(
"config.directory_not_writable",
format!(
"the settings directory at {} could not be created",
directory.display()
),
)
.with_detail("detail", directory.display().to_string())
.with_hint("check that this user may write there")
.with_cause(error.to_string())
})?;
let text = toml::to_string(settings).map_err(|error| {
Failure::config(
"config.not_serialisable",
"the settings could not be written out",
)
.with_cause(error.to_string())
})?;
let mut handle = tempfile::NamedTempFile::new_in(directory).map_err(|error| {
Failure::config(
"config.not_writable",
format!(
"no temporary file could be created in {}",
directory.display()
),
)
.with_detail("detail", directory.display().to_string())
.with_hint("check that this user may write there")
.with_cause(error.to_string())
})?;
handle
.write_all(text.as_bytes())
.and_then(|()| handle.as_file().sync_all())
.map_err(|error| {
Failure::config("config.not_writable", "the settings could not be written")
.with_detail("detail", file.display().to_string())
.with_cause(error.to_string())
})?;
restrict(handle.path())?;
handle.persist(file).map_err(|error| {
Failure::config(
"config.not_writable",
format!("the settings could not be moved into {}", file.display()),
)
.with_detail("detail", file.display().to_string())
.with_cause(error.to_string())
})?;
Ok(())
}
#[cfg(unix)]
pub const OWNER_ONLY: u32 = 0o600;
#[cfg(unix)]
fn restrict(file: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(file, std::fs::Permissions::from_mode(OWNER_ONLY)).map_err(|error| {
Failure::config(
"config.permission_not_applied",
"the settings file could not be narrowed to its owner",
)
.with_hint("the product refuses to store a setting it cannot protect")
.with_cause(error.to_string())
})
}
#[cfg(not(unix))]
fn restrict(file: &Path) -> Result<()> {
crate::i18n::report::permissions_unavailable_settings(&file.display().to_string());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch() -> tempfile::TempDir {
tempfile::tempdir().expect("scratch directory")
}
#[test]
fn an_absent_file_means_nothing_was_ever_stored() {
let dir = scratch();
let settings = load(&dir.path().join("config.toml")).expect("absence is not a failure");
assert!(settings.is_empty());
}
#[test]
fn a_stored_value_survives_a_round_trip() {
let dir = scratch();
let file = dir.path().join("config.toml");
store(&file, "output.format", "ndjson").expect("writes");
let settings = load(&file).expect("reads");
assert_eq!(
settings.get("output.format").map(String::as_str),
Some("ndjson")
);
}
#[test]
fn writing_one_setting_leaves_the_others_untouched() {
let dir = scratch();
let file = dir.path().join("config.toml");
store(&file, "output.format", "tsv").expect("writes");
store(&file, "limits.retries", "5").expect("writes");
let settings = load(&file).expect("reads");
assert_eq!(
settings.get("output.format").map(String::as_str),
Some("tsv")
);
assert_eq!(
settings.get("limits.retries").map(String::as_str),
Some("5")
);
}
#[test]
fn removing_reports_whether_anything_was_stored() {
let dir = scratch();
let file = dir.path().join("config.toml");
store(&file, "log.to_file", "true").expect("writes");
assert!(remove(&file, "log.to_file").expect("removes"));
assert!(!remove(&file, "log.to_file").expect("nothing left"));
}
#[test]
fn the_write_leaves_no_leftover_beside_the_target() {
let dir = scratch();
let file = dir.path().join("config.toml");
store(&file, "output.format", "json").expect("writes");
let entries: Vec<_> = std::fs::read_dir(dir.path())
.expect("listing")
.filter_map(std::result::Result::ok)
.map(|entry| entry.file_name())
.collect();
assert_eq!(
entries.len(),
1,
"a half written file was left behind: {entries:?}"
);
}
#[cfg(unix)]
#[test]
fn the_stored_file_is_readable_by_its_owner_alone() {
use std::os::unix::fs::PermissionsExt as _;
let dir = scratch();
let file = dir.path().join("config.toml");
store(&file, "conn.default", "production").expect("writes");
let mode = std::fs::metadata(&file)
.expect("metadata")
.permissions()
.mode();
assert_eq!(mode & 0o777, OWNER_ONLY, "the file is open to other users");
}
#[test]
fn a_file_that_does_not_parse_is_reported_rather_than_ignored() {
let dir = scratch();
let file = dir.path().join("config.toml");
std::fs::write(&file, "this is not settings at all\n").expect("writes");
let failure = load(&file).expect_err("must report");
assert_eq!(failure.code(), "config.malformed");
}
}