aboutsummaryrefslogtreecommitdiff
path: root/crates/iam/src/util.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--crates/iam/src/util.rs88
1 files changed, 88 insertions, 0 deletions
diff --git a/crates/iam/src/util.rs b/crates/iam/src/util.rs
new file mode 100644
index 0000000..01ce851
--- /dev/null
+++ b/crates/iam/src/util.rs
@@ -0,0 +1,88 @@
+use crate::{
+ api::{CliError, Config, ConfigProfile},
+ CONFIG_DIR_NAME, CONFIG_PROFILE_FILE, ISSUE_TRACKER_LOC,
+};
+use anyhow::{anyhow, Context};
+use colored::Colorize;
+use home::home_dir;
+use secd::Secd;
+use std::{
+ env::var,
+ error::Error,
+ fs::{self, File},
+ io::{self, Read},
+ path::PathBuf,
+ result,
+ str::FromStr,
+};
+use thiserror;
+
+pub type Result<T> = anyhow::Result<T>;
+
+macro_rules! err {
+ ($($tt:tt)*) => { Err(Box::<dyn Error>::from(format!($($tt)*))) }
+}
+pub(crate) use err;
+
+#[derive(Debug, thiserror::Error)]
+pub enum InternalError {
+ #[error(
+ "Cannot read {0} profile from {1}. Initialize a default iam store with `iam admin init`"
+ )]
+ CannotReadProfile(String, String),
+}
+
+pub fn get_config_dir() -> PathBuf {
+ let xdg_dir = var("XDG_CONFIG_HOME").map(|s| PathBuf::from_str(&s).unwrap());
+ let mut home_dir = home_dir().expect(&format!(
+ "Could not find home directory. This should not be possible, please file a bug at {}",
+ ISSUE_TRACKER_LOC
+ ));
+
+ match xdg_dir {
+ Ok(mut d) => {
+ d.push(format!(".{}", CONFIG_DIR_NAME));
+ d
+ }
+ Err(_) => {
+ home_dir.push(".config");
+ home_dir.push(CONFIG_DIR_NAME);
+ home_dir
+ }
+ }
+}
+
+pub fn get_config_profile() -> PathBuf {
+ let mut config_dir = get_config_dir();
+ config_dir.push(CONFIG_PROFILE_FILE);
+ config_dir
+}
+
+pub fn read_config(profile_name: Option<String>) -> Result<ConfigProfile> {
+ let profile_path = get_config_profile();
+ let profile_name = profile_name.unwrap_or("default".into());
+
+ let bytes = fs::read(profile_path.clone())?;
+ let config: Config = toml::from_slice(&bytes)?;
+
+ let mut cfg = config
+ .profile
+ .into_iter()
+ .filter(|p| p.name == profile_name)
+ .last()
+ .ok_or(anyhow!(
+ "cannot read configuration file when calling read_config"
+ ))?;
+
+ if let Some(path) = cfg.email_template_login {
+ let buf = fs::read_to_string(path)?;
+ cfg.email_template_login = Some(buf);
+ }
+
+ if let Some(path) = cfg.email_template_signup {
+ let buf = fs::read_to_string(path)?;
+ cfg.email_template_signup = Some(buf);
+ }
+
+ Ok(cfg)
+}