1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
use std::collections::HashMap; use std::env::{self, VarError}; use std::iter::Iterator; use std::path::{Path, PathBuf}; use std::str::FromStr; use promptly::prompt; use serde::{Deserialize, Serialize}; use crate::{FhttpError, Result, Config, ResponseStore}; pub use profile_variable::ProfileVariable; use crate::path_utils::get_dependency_path; mod profile_variable; pub struct Profiles; impl Profiles { pub fn parse(path: &Path) -> Result<HashMap<String, Profile>> { let content = std::fs::read_to_string(&path) .map_err(|_| FhttpError::new(format!("Error opening file {}", path.to_str().unwrap())))?; let profiles = serde_json::from_str::<HashMap<String, _Profile>>(&content) .map_err(|_| FhttpError::new(format!("error reading profile from {}", path.to_str().unwrap())))?; let ret = profiles.into_iter() .map(|(key, value)| { let profile = Profile::new(path, value.variables); (key, profile) }) .collect::<HashMap<String, Profile>>(); Ok(ret) } } #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] struct _Profile { pub variables: HashMap<String, ProfileVariable>, } #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] pub struct Profile { source_path: PathBuf, variables: HashMap<String, ProfileVariable>, } impl Profile { pub fn empty<T: Into<PathBuf>>(source_path: T) -> Self { Profile { source_path: source_path.into(), variables: HashMap::new(), } } pub fn new<T: Into<PathBuf>>( source_path: T, variables: HashMap<String, ProfileVariable>, ) -> Self { Profile { source_path: source_path.into(), variables, } } pub fn defined_through_request<K: Into<String>>( &self, key: K ) -> Option<PathBuf> { let key = key.into(); match self.variables.contains_key(&key) { true => match self.variables.get(&key) { Some(ProfileVariable::Request { request }) => Some(PathBuf::from_str(request).unwrap()), _ => None }, false => None } } pub fn get<'a, K: Into<&'a str>>( &self, key: K, config: &Config, response_store: &ResponseStore, ) -> Result<String> { let key = key.into(); match self.variables.get(key) { Some(ProfileVariable::Request { request }) => Ok(response_store.get(&get_dependency_path(&self.source_path, request))), Some(var) => var.get(), None => get_from_environment(&key, config) } } pub fn source_path(&self) -> &Path { &self.source_path } pub fn variables(&self) -> Vec<&ProfileVariable> { self.variables.values().collect() } pub fn override_with( &mut self, other: Profile ) { for (key, value) in other.variables { self.variables.insert(key, value); } } } fn get_from_environment( key: &str, config: &Config ) -> Result<String> { match env::var(&key) { Ok(value) => Ok(value), Err(VarError::NotUnicode(_)) => Err(FhttpError::new(format!("environment variable {} is not unicode!", key))), Err(VarError::NotPresent) => match config.prompt_missing_env_vars { true => { let value = prompt::<String, _>(&key).unwrap(); env::set_var(&key, &value); Ok(value) }, false => Err(FhttpError::new(format!("missing environment variable {}", key))) } } } #[cfg(test)] mod test { use std::env; use maplit::hashmap; use crate::test_utils::root; use crate::profiles::ProfileVariable; use super::*; #[test] fn should_load_profiles() -> Result<()> { let path = root() .join("resources/test/profiles/profile1.json"); let profiles = Profiles::parse(&path)?; assert_eq!( profiles, hashmap!{ "development".into() => Profile { source_path: root().join("resources/test/profiles/profile1.json"), variables: hashmap!{}, }, "testing".into() => Profile { source_path: root().join("resources/test/profiles/profile1.json"), variables: hashmap!{ "var1".into() => ProfileVariable::StringValue("value1".into()) }, } } ); Ok(()) } #[test] fn get_should_get_variables() -> Result<()> { let profile = Profile { source_path: env::current_dir().unwrap(), variables: hashmap! { "a".into() => ProfileVariable::StringValue("b".into()) }, }; assert_eq!( profile.get("a", &Config::default(), &ResponseStore::new())?, String::from("b") ); Ok(()) } #[test] fn get_should_default_to_env_vars() -> Result<()> { env::set_var("a", "A"); let profile = Profile { source_path: env::current_dir().unwrap(), variables: HashMap::new(), }; assert_eq!( profile.get("a", &Config::default(), &ResponseStore::new())?, String::from("A") ); Ok(()) } #[test] fn override_with_should_merge() -> Result<()> { let config = Config::default(); let response_store = ResponseStore::new(); let mut default = Profile::new( env::current_dir().unwrap(), hashmap! { String::from("a") => ProfileVariable::StringValue(String::from("A")), String::from("b") => ProfileVariable::StringValue(String::from("B")) } ); let local = Profile::new( env::current_dir().unwrap(), hashmap! { String::from("b") => ProfileVariable::StringValue(String::from("BBB")), String::from("c") => ProfileVariable::StringValue(String::from("CCC")), } ); default.override_with(local); assert_eq!(default.get("a", &config, &response_store)?, "A"); assert_eq!(default.get("b", &config, &response_store)?, "BBB"); assert_eq!(default.get("c", &config, &response_store)?, "CCC"); Ok(()) } }