src/config.rs

203 lines · 5783 bytes

  1use std::collections::HashMap;
  2use std::fs::File;
  3use std::io::BufReader;
  4use std::path::{Path, PathBuf};
  5use std::process;
  6
  7use clap::Parser;
  8use matrix_sdk::ruma::OwnedUserId;
  9use serde::Deserialize;
 10use url::Url;
 11
 12macro_rules! usage {
 13    ( $($args: tt)* ) => {
 14        println!($($args)*);
 15        process::exit(2);
 16    }
 17}
 18
 19fn is_profile_char(c: char) -> bool {
 20    c.is_ascii_alphanumeric() || c == '.' || c == '-'
 21}
 22
 23fn validate_profile_name(name: &str) -> bool {
 24    if name.is_empty() {
 25        return false;
 26    }
 27
 28    let mut chars = name.chars();
 29
 30    if !chars.next().map_or(false, |c| c.is_ascii_alphanumeric()) {
 31        return false;
 32    }
 33
 34    name.chars().all(is_profile_char)
 35}
 36
 37fn validate_profile_names(names: &HashMap<String, ProfileConfig>) {
 38    for name in names.keys() {
 39        if validate_profile_name(name.as_str()) {
 40            continue;
 41        }
 42
 43        usage!(
 44            "{:?} is not a valid profile name.\n\n\
 45            Profile names can only contain the characters \
 46            a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.",
 47            name
 48        );
 49    }
 50}
 51
 52#[derive(Parser)]
 53#[clap(version, about, long_about = None)]
 54#[clap(propagate_version = true)]
 55pub struct Iamb {
 56    #[clap(short = 'P', long, value_parser)]
 57    pub profile: Option<String>,
 58
 59    #[clap(short = 'C', long, value_parser)]
 60    pub config_directory: Option<PathBuf>,
 61}
 62
 63#[derive(thiserror::Error, Debug)]
 64pub enum ConfigError {
 65    #[error("Error reading configuration file: {0}")]
 66    IO(#[from] std::io::Error),
 67
 68    #[error("Error loading configuration file: {0}")]
 69    Invalid(#[from] serde_json::Error),
 70}
 71
 72#[derive(Clone, Deserialize)]
 73pub struct ProfileConfig {
 74    pub user_id: OwnedUserId,
 75    pub url: Url,
 76}
 77
 78#[derive(Clone, Deserialize)]
 79pub struct IambConfig {
 80    pub profiles: HashMap<String, ProfileConfig>,
 81    pub default_profile: Option<String>,
 82    pub cache: Option<PathBuf>,
 83}
 84
 85impl IambConfig {
 86    pub fn load(config_json: &Path) -> Result<Self, ConfigError> {
 87        if !config_json.is_file() {
 88            usage!(
 89                "Please create a configuration file at {}\n\n\
 90                For more information try '--help'",
 91                config_json.display(),
 92            );
 93        }
 94
 95        let file = File::open(config_json)?;
 96        let reader = BufReader::new(file);
 97        let config = serde_json::from_reader(reader)?;
 98
 99        Ok(config)
100    }
101}
102
103#[derive(Clone)]
104pub struct ApplicationSettings {
105    pub matrix_dir: PathBuf,
106    pub cache_dir: PathBuf,
107    pub session_json: PathBuf,
108    pub profile_name: String,
109    pub profile: ProfileConfig,
110}
111
112impl ApplicationSettings {
113    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
114        let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
115            usage!(
116                "No user configuration directory found;\
117                please specify one via -C.\n\n
118                For more information try '--help'"
119            );
120        });
121        config_dir.push("iamb");
122        let mut config_json = config_dir.clone();
123        config_json.push("config.json");
124
125        let IambConfig { mut profiles, default_profile, cache } =
126            IambConfig::load(config_json.as_path())?;
127
128        validate_profile_names(&profiles);
129
130        let (profile_name, profile) = if let Some(profile) = cli.profile.or(default_profile) {
131            profiles.remove_entry(&profile).unwrap_or_else(|| {
132                usage!(
133                    "No configured profile with the name {:?} in {}",
134                    profile,
135                    config_json.display()
136                );
137            })
138        } else if profiles.len() == 1 {
139            profiles.into_iter().next().unwrap()
140        } else {
141            usage!(
142                "No profile specified. \
143                Please use -P or add \"default_profile\" to {}.\n\n\
144                For more information try '--help'",
145                config_json.display()
146            );
147        };
148
149        let mut profile_dir = config_dir.clone();
150        profile_dir.push("profiles");
151        profile_dir.push(profile_name.as_str());
152
153        let mut matrix_dir = profile_dir.clone();
154        matrix_dir.push("matrix");
155
156        let mut session_json = profile_dir;
157        session_json.push("session.json");
158
159        let cache_dir = cache.unwrap_or_else(|| {
160            let mut cache = dirs::cache_dir().expect("no user cache directory");
161            cache.push("iamb");
162            cache
163        });
164
165        let settings = ApplicationSettings {
166            matrix_dir,
167            cache_dir,
168            session_json,
169            profile_name,
170            profile,
171        };
172
173        Ok(settings)
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn test_profile_name_invalid() {
183        assert_eq!(validate_profile_name(""), false);
184        assert_eq!(validate_profile_name(" "), false);
185        assert_eq!(validate_profile_name("a b"), false);
186        assert_eq!(validate_profile_name("foo^bar"), false);
187        assert_eq!(validate_profile_name("FOO/BAR"), false);
188        assert_eq!(validate_profile_name("-b-c"), false);
189        assert_eq!(validate_profile_name("-B-c"), false);
190        assert_eq!(validate_profile_name(".b-c"), false);
191        assert_eq!(validate_profile_name(".B-c"), false);
192    }
193
194    #[test]
195    fn test_profile_name_valid() {
196        assert_eq!(validate_profile_name("foo"), true);
197        assert_eq!(validate_profile_name("FOO"), true);
198        assert_eq!(validate_profile_name("a-b-c"), true);
199        assert_eq!(validate_profile_name("a-B-c"), true);
200        assert_eq!(validate_profile_name("a.b-c"), true);
201        assert_eq!(validate_profile_name("a.B-c"), true);
202    }
203}