From 06b5606f13592b669212a97fb5ea3367d7f0fa21 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Sun, 17 Jan 2021 08:05:43 +0200 Subject: feat: add a default configuration file The ~/.config/obnam/obnam.yaml file will be used as the configuration file by default. The ~/.config directory can be overridden by setting the XDG variable (XDG_CONFIG_HOME), or the whole file can be overridden with the --config option to obnam. --- Cargo.toml | 1 + src/bin/obnam.rs | 18 ++++++++++++++++-- src/client.rs | 4 +++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e8bbd91..747deb0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ edition = "2018" anyhow = "1" bytes = "0.5" chrono = "0.4" +dirs = "3" indicatif = "0.15" libc = "0.2" log = "0.4" diff --git a/src/bin/obnam.rs b/src/bin/obnam.rs index 1e09168..e9f30ca 100644 --- a/src/bin/obnam.rs +++ b/src/bin/obnam.rs @@ -10,7 +10,11 @@ const BUFFER_SIZE: usize = 1024 * 1024; fn main() -> anyhow::Result<()> { let opt = Opt::from_args(); - let config = ClientConfig::read_config(&opt.config)?; + let config_file = match opt.config { + None => default_config(), + Some(ref path) => path.to_path_buf(), + }; + let config = ClientConfig::read_config(&config_file)?; if let Some(ref log) = config.log { setup_logging(&log)?; } @@ -37,11 +41,21 @@ fn main() -> anyhow::Result<()> { Ok(()) } +fn default_config() -> PathBuf { + if let Some(path) = dirs::config_dir() { + path.join("obnam").join("obnam.yaml") + } else if let Some(path) = dirs::home_dir() { + path.join(".config").join("obnam").join("obnam.yaml") + } else { + panic!("can't find config dir or home dir"); + } +} + #[derive(Debug, StructOpt)] #[structopt(name = "obnam-backup", about = "Simplistic backup client")] struct Opt { #[structopt(long, short, parse(from_os_str))] - config: PathBuf, + config: Option, #[structopt(subcommand)] cmd: Command, diff --git a/src/client.rs b/src/client.rs index 4526830..23df540 100644 --- a/src/client.rs +++ b/src/client.rs @@ -9,6 +9,7 @@ use crate::fsentry::{FilesystemEntry, FilesystemKind}; use crate::generation::{FinishedGeneration, LocalGeneration}; use crate::genlist::GenerationList; +use anyhow::Context; use chrono::{DateTime, Local}; use log::{debug, error, info, trace}; use reqwest::blocking::Client; @@ -28,7 +29,8 @@ pub struct ClientConfig { impl ClientConfig { pub fn read_config(filename: &Path) -> anyhow::Result { trace!("read_config: filename={:?}", filename); - let config = std::fs::read_to_string(filename)?; + let config = std::fs::read_to_string(filename) + .with_context(|| format!("reading configuration file {}", filename.display()))?; let config = serde_yaml::from_str(&config)?; Ok(config) } -- cgit v1.2.1