dotfiles_core/settings.rs
1// Copyright (c) 2021-2022 Miguel Barreto and others
2//
3// Permission is hereby granted, free of charge, to any person obtaining
4// a copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to
8// permit persons to whom the Software is furnished to do so, subject to
9// the following conditions:
10//
11// The above copyright notice and this permission notice shall be
12// included in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22//! This module contains the definition of a setting and code to parse them.
23
24extern crate strict_yaml_rust;
25
26use std::collections::HashMap;
27
28use strict_yaml_rust::StrictYaml;
29
30use crate::{
31 error::DotfilesError,
32 yaml_util::{parse_as_boolean, parse_as_integer, parse_as_string},
33};
34
35/// The Settings object is a hashmap of option names to a default value
36pub type Settings = HashMap<String, Setting>;
37
38/// Represents a value for a setting
39#[derive(Eq, PartialEq, Clone, Debug)]
40pub enum Setting {
41 /// A boolean value for a setting
42 Boolean(bool),
43 /// A string value for a setting
44 String(String),
45 /// An Integer value for a setting
46 Integer(i64),
47}
48
49/// Returns a Settings object from an array as a bit of syntactic sugar
50pub fn initialize_settings_object(settings: &[(String, Setting)]) -> Settings {
51 let settings_object: Settings = settings
52 .iter()
53 .map(|(name, setting)| (name.clone(), setting.clone()))
54 .collect();
55 settings_object
56}
57
58/// Parse a setting from StrictYaml given a particular setting type.
59pub fn parse_setting(setting_type: &Setting, yaml: &StrictYaml) -> Result<Setting, DotfilesError> {
60 match setting_type {
61 Setting::String(_) => Ok(Setting::String(parse_as_string(yaml)?)),
62 Setting::Boolean(_) => Ok(Setting::Boolean(parse_as_boolean(yaml)?)),
63 Setting::Integer(_) => Ok(Setting::Integer(parse_as_integer(yaml)?)),
64 }
65}