Skip to content

Commit

Permalink
Added pathing utility and config handler
Browse files Browse the repository at this point in the history
  • Loading branch information
Xithrius committed Oct 14, 2021
1 parent 0ecc09d commit 5581cad
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 1 deletion.
23 changes: 23 additions & 0 deletions src/handlers/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use anyhow::{bail, Error, Result};
use serde::Deserialize;

use crate::utils::pathing::config_path;

#[derive(Deserialize)]
pub struct CompleteConfig {}

impl CompleteConfig {
pub fn new() -> Result<Self, Error> {
if let Ok(config_contents) = std::fs::read_to_string(config_path()) {
let config: CompleteConfig = toml::from_str(config_contents.as_str()).unwrap();

Ok(config)
} else {
bail!(
"Configuration not found. Create a config file at '{}', and see '{}' for an example configuration.",
config_path(),
format!("{}/blob/main/default-config.toml", env!("CARGO_PKG_REPOSITORY"))
)
}
}
}
1 change: 1 addition & 0 deletions src/handlers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod config;
14 changes: 13 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
mod handlers;
mod utils;

use crate::handlers::config::CompleteConfig;

fn main() {
println!("Hello World!");
match CompleteConfig::new() {
Ok(config) => {
println!("Hello World!");
}
Err(err) => {
println!("{}", err);
}
}
}
1 change: 1 addition & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod pathing;
46 changes: 46 additions & 0 deletions src/utils/pathing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use std::panic::panic_any;

const BINARY_NAME: &str = env!("CARGO_BIN_NAME");

pub fn config_path() -> String {
match std::env::consts::OS {
"linux" | "macos" => match std::env::var("HOME") {
Ok(env_home_path) => format!("{}/.config/{}/config.toml", env_home_path, BINARY_NAME),
Err(err) => panic_any(err),
},
"windows" => match std::env::var("APPDATA") {
Ok(appdata_path) => format!("{}\\{}\\config.toml", appdata_path, BINARY_NAME),
Err(err) => std::panic::panic_any(err),
},
_ => unimplemented!(),
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
#[cfg(target_os = "windows")]
fn test_windows_config_path() {
match std::env::var("APPDATA") {
Ok(appdata_path) => assert_eq!(
config_path(),
format!("{}\\{}\\config.toml", appdata_path, BINARY_NAME)
),
Err(err) => std::panic::panic_any(err),
}
}

#[test]
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn test_unix_config_path() {
match std::env::var("HOME") {
Ok(env_home_path) => assert_eq!(
config_path(),
format!("{}/.config/{}/config.toml", env_home_path, BINARY_NAME)
),
Err(err) => std::panic::panic_any(err),
}
}
}

0 comments on commit 5581cad

Please sign in to comment.