jujube_lib/
settings.rs

1// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::path::PathBuf;
16
17#[derive(Debug, Clone)]
18pub struct UserSettings {
19    config: config::Config,
20}
21
22#[derive(Debug, Clone)]
23pub struct RepoSettings {
24    config: config::Config,
25}
26
27impl UserSettings {
28    pub fn from_config(config: config::Config) -> Self {
29        UserSettings { config }
30    }
31
32    pub fn for_user() -> Result<Self, config::ConfigError> {
33        let mut config = config::Config::new();
34
35        if let Some(home_dir) = dirs::home_dir() {
36            config.merge(
37                config::File::from(home_dir.join(".jjconfig"))
38                    .required(false)
39                    .format(config::FileFormat::Toml),
40            )?;
41        }
42
43        Ok(UserSettings { config })
44    }
45
46    pub fn with_repo(&self, repo_path: &PathBuf) -> Result<RepoSettings, config::ConfigError> {
47        let mut config = self.config.clone();
48        config.merge(
49            config::File::from(repo_path.join("config"))
50                .required(false)
51                .format(config::FileFormat::Toml),
52        )?;
53
54        Ok(RepoSettings { config })
55    }
56
57    pub fn user_name(&self) -> String {
58        self.config.get_str("user.name").expect("no user.name set")
59    }
60
61    pub fn user_email(&self) -> String {
62        self.config
63            .get_str("user.email")
64            .expect("no user.email set")
65    }
66
67    pub fn config(&self) -> &config::Config {
68        &self.config
69    }
70}