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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::env;
use std::path::Path;

use chrono::DateTime;

use crate::backend::{Signature, Timestamp};

#[derive(Debug, Clone, Default)]
pub struct UserSettings {
    config: config::Config,
    timestamp: Option<Timestamp>,
}

#[derive(Debug, Clone)]
pub struct RepoSettings {
    _config: config::Config,
}

const TOO_MUCH_CONFIG_ERROR: &str =
    "Both `$HOME/.jjconfig` and `$XDG_CONFIG_HOME/jj/config.toml` were found, please remove one.";

impl UserSettings {
    pub fn from_config(config: config::Config) -> Self {
        let timestamp = match config.get_str("user.timestamp") {
            Ok(timestamp_str) => match DateTime::parse_from_rfc3339(&timestamp_str) {
                Ok(datetime) => Some(Timestamp::from_datetime(datetime)),
                Err(_) => None,
            },
            Err(_) => None,
        };
        UserSettings { config, timestamp }
    }

    pub fn for_user() -> Result<Self, config::ConfigError> {
        let mut config = config::Config::new();

        let loaded_from_config_dir = match dirs::config_dir() {
            None => false,
            Some(config_dir) => {
                let p = config_dir.join("jj/config.toml");
                let exists = p.exists();
                config.merge(
                    config::File::from(p)
                        .required(false)
                        .format(config::FileFormat::Toml),
                )?;
                exists
            }
        };

        if let Some(home_dir) = dirs::home_dir() {
            let p = home_dir.join(".jjconfig");
            // we already loaded from the new location, prevent user confusion and make them
            // remove the old one:
            if loaded_from_config_dir && p.exists() {
                return Err(config::ConfigError::Message(
                    TOO_MUCH_CONFIG_ERROR.to_string(),
                ));
            }
            config.merge(
                config::File::from(p)
                    .required(false)
                    .format(config::FileFormat::Toml),
            )?;
        }

        let mut env_config = config::Config::new();
        if let Ok(value) = env::var("JJ_USER") {
            env_config.set("user.name", value)?;
        }
        if let Ok(value) = env::var("JJ_EMAIL") {
            env_config.set("user.email", value)?;
        }
        if let Ok(value) = env::var("JJ_TIMESTAMP") {
            env_config.set("user.timestamp", value)?;
        }
        config.merge(env_config)?;

        Ok(Self::from_config(config))
    }

    pub fn with_repo(&self, repo_path: &Path) -> Result<RepoSettings, config::ConfigError> {
        let mut config = self.config.clone();
        config.merge(
            config::File::from(repo_path.join("config"))
                .required(false)
                .format(config::FileFormat::Toml),
        )?;

        Ok(RepoSettings { _config: config })
    }

    pub fn user_name(&self) -> String {
        self.config
            .get_str("user.name")
            .unwrap_or_else(|_| "(no name configured)".to_string())
    }

    pub fn user_email(&self) -> String {
        self.config
            .get_str("user.email")
            .unwrap_or_else(|_| "(no email configured)".to_string())
    }

    pub fn signature(&self) -> Signature {
        let timestamp = self.timestamp.clone().unwrap_or_else(Timestamp::now);
        Signature {
            name: self.user_name(),
            email: self.user_email(),
            timestamp,
        }
    }

    pub fn config(&self) -> &config::Config {
        &self.config
    }
}