src/config.rs

267 lines · 7416 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)]
 73pub struct TunableValues {
 74    pub typing_notice: bool,
 75    pub typing_notice_display: bool,
 76}
 77
 78#[derive(Clone, Default, Deserialize)]
 79pub struct Tunables {
 80    pub typing_notice: Option<bool>,
 81    pub typing_notice_display: Option<bool>,
 82}
 83
 84impl Tunables {
 85    fn merge(self, other: Self) -> Self {
 86        Tunables {
 87            typing_notice: self.typing_notice.or(other.typing_notice),
 88            typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
 89        }
 90    }
 91
 92    fn values(self) -> TunableValues {
 93        TunableValues {
 94            typing_notice: self.typing_notice.unwrap_or(true),
 95            typing_notice_display: self.typing_notice.unwrap_or(true),
 96        }
 97    }
 98}
 99
100#[derive(Clone)]
101pub struct DirectoryValues {
102    pub cache: PathBuf,
103}
104
105#[derive(Clone, Default, Deserialize)]
106pub struct Directories {
107    pub cache: Option<PathBuf>,
108}
109
110impl Directories {
111    fn merge(self, other: Self) -> Self {
112        Directories { cache: self.cache.or(other.cache) }
113    }
114
115    fn values(self) -> DirectoryValues {
116        DirectoryValues {
117            cache: self
118                .cache
119                .or_else(dirs::cache_dir)
120                .expect("no dirs.cache value configured!"),
121        }
122    }
123}
124
125#[derive(Clone, Deserialize)]
126pub struct ProfileConfig {
127    pub user_id: OwnedUserId,
128    pub url: Url,
129    pub settings: Option<Tunables>,
130    pub dirs: Option<Directories>,
131}
132
133#[derive(Clone, Deserialize)]
134pub struct IambConfig {
135    pub profiles: HashMap<String, ProfileConfig>,
136    pub default_profile: Option<String>,
137    pub settings: Option<Tunables>,
138    pub dirs: Option<Directories>,
139}
140
141impl IambConfig {
142    pub fn load(config_json: &Path) -> Result<Self, ConfigError> {
143        if !config_json.is_file() {
144            usage!(
145                "Please create a configuration file at {}\n\n\
146                For more information try '--help'",
147                config_json.display(),
148            );
149        }
150
151        let file = File::open(config_json)?;
152        let reader = BufReader::new(file);
153        let config = serde_json::from_reader(reader)?;
154
155        Ok(config)
156    }
157}
158
159#[derive(Clone)]
160pub struct ApplicationSettings {
161    pub matrix_dir: PathBuf,
162    pub session_json: PathBuf,
163    pub profile_name: String,
164    pub profile: ProfileConfig,
165    pub tunables: TunableValues,
166    pub dirs: DirectoryValues,
167}
168
169impl ApplicationSettings {
170    pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
171        let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
172            usage!(
173                "No user configuration directory found;\
174                please specify one via -C.\n\n
175                For more information try '--help'"
176            );
177        });
178        config_dir.push("iamb");
179        let mut config_json = config_dir.clone();
180        config_json.push("config.json");
181
182        let IambConfig {
183            mut profiles,
184            default_profile,
185            dirs,
186            settings: global,
187        } = IambConfig::load(config_json.as_path())?;
188
189        validate_profile_names(&profiles);
190
191        let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
192            profiles.remove_entry(&profile).unwrap_or_else(|| {
193                usage!(
194                    "No configured profile with the name {:?} in {}",
195                    profile,
196                    config_json.display()
197                );
198            })
199        } else if profiles.len() == 1 {
200            profiles.into_iter().next().unwrap()
201        } else {
202            usage!(
203                "No profile specified. \
204                Please use -P or add \"default_profile\" to {}.\n\n\
205                For more information try '--help'",
206                config_json.display()
207            );
208        };
209
210        let tunables = global.unwrap_or_default();
211        let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
212        let tunables = tunables.values();
213
214        let mut profile_dir = config_dir.clone();
215        profile_dir.push("profiles");
216        profile_dir.push(profile_name.as_str());
217
218        let mut matrix_dir = profile_dir.clone();
219        matrix_dir.push("matrix");
220
221        let mut session_json = profile_dir;
222        session_json.push("session.json");
223
224        let dirs = dirs.unwrap_or_default();
225        let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
226        let dirs = dirs.values();
227
228        let settings = ApplicationSettings {
229            matrix_dir,
230            session_json,
231            profile_name,
232            profile,
233            tunables,
234            dirs,
235        };
236
237        Ok(settings)
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn test_profile_name_invalid() {
247        assert_eq!(validate_profile_name(""), false);
248        assert_eq!(validate_profile_name(" "), false);
249        assert_eq!(validate_profile_name("a b"), false);
250        assert_eq!(validate_profile_name("foo^bar"), false);
251        assert_eq!(validate_profile_name("FOO/BAR"), false);
252        assert_eq!(validate_profile_name("-b-c"), false);
253        assert_eq!(validate_profile_name("-B-c"), false);
254        assert_eq!(validate_profile_name(".b-c"), false);
255        assert_eq!(validate_profile_name(".B-c"), false);
256    }
257
258    #[test]
259    fn test_profile_name_valid() {
260        assert_eq!(validate_profile_name("foo"), true);
261        assert_eq!(validate_profile_name("FOO"), true);
262        assert_eq!(validate_profile_name("a-b-c"), true);
263        assert_eq!(validate_profile_name("a-B-c"), true);
264        assert_eq!(validate_profile_name("a.b-c"), true);
265        assert_eq!(validate_profile_name("a.B-c"), true);
266    }
267}