OXYGENHUB
# e8b4e156f2fa oxygen / crates / oxy-core / src / repo / config.rs
7.0 KiB · Rust · last changed Garbage collection: operation-log retention, pruning with grace period, pack rewriting; oxy gc --now 1 month ago source blame history raw
1
//! Layered configuration: defaults, the user file, the repository file.
2
3
use super::*;
4
5
/// Effective settings: defaults, then the user file (`~/.config/oxy/config.toml`,
6
/// spec §19), then the repository file (`.oxy/config`). Both files are
7
/// `key = "value"` lines. `save` writes only the repository layer.
8
#[derive(Clone, Debug, PartialEq, Eq)]
9
pub struct Config {
10
    /// Keys set in the repository file (or via `set`), written by `save`.
11
    repo_layer: BTreeMap<String, String>,
12
    pub author_name: String,
13
    pub author_email: String,
14
    /// The KeyId of the author's identity, once `create_identity` has run.
15
    pub author_key: Option<KeyId>,
16
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
17
    /// push-time seals (`false`, the spec default).
18
    pub sign_changes: bool,
19
    pub bookmark: String,
20
    /// `remote.<name>.url`.
21
    pub remotes: BTreeMap<String, String>,
22
    /// `remote.<name>.token`: bearer token for HTTP pushes.
23
    pub remote_tokens: BTreeMap<String, String>,
24
    /// `remote.<name>.ca`: PEM file of extra roots to trust for that remote.
25
    pub remote_cas: BTreeMap<String, String>,
26
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
27
    pub op_retention_days: u64,
28
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
29
    pub gc_grace_days: u64,
30
}
31
32
impl Config {
33
    pub(super) fn default_for_user() -> Config {
34
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
35
        Config {
36
            repo_layer: BTreeMap::new(),
37
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
38
            author_email: std::env::var("OXY_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{user}@localhost")),
39
            author_key: None,
40
            sign_changes: false,
41
            bookmark: "main".into(),
42
            remotes: BTreeMap::new(),
43
            remote_tokens: BTreeMap::new(),
44
            remote_cas: BTreeMap::new(),
45
            op_retention_days: 90,
46
            gc_grace_days: 14,
47
        }
48
    }
49
50
    /// Set a key in the repository layer, as `oxy config` does.
51
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
52
        self.apply(key, value)?;
53
        if value.is_empty() {
54
            self.repo_layer.remove(key);
55
        } else {
56
            self.repo_layer.insert(key.to_string(), value.to_string());
57
        }
58
        Ok(())
59
    }
60
61
    /// Set a key in the user file without touching any repository.
62
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
63
        Config::default_for_user().apply(key, value)?;
64
        let mut entries = read_config_file(user_path)?;
65
        if value.is_empty() {
66
            entries.remove(key);
67
        } else {
68
            entries.insert(key.to_string(), value.to_string());
69
        }
70
        if let Some(parent) = user_path.parent() {
71
            fs::create_dir_all(parent)?;
72
        }
73
        write_config_file(user_path, &entries)
74
    }
75
76
    /// Apply a key to the effective values.
77
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
78
        match key {
79
            "author.name" => self.author_name = value.into(),
80
            "author.email" => self.author_email = value.into(),
81
            "author.key" => {
82
                self.author_key = if value.is_empty() {
83
                    None
84
                } else {
85
                    Some(KeyId::from_hex(value).ok_or_else(|| RepoError::Msg("author.key must be a 64-character hex KeyId".into()))?)
86
                }
87
            }
88
            "core.sign" => {
89
                self.sign_changes = match value {
90
                    "change" => true,
91
                    "seal" => false,
92
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
93
                }
94
            }
95
            "workspace.bookmark" => self.bookmark = value.into(),
96
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
97
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
98
            k if k.starts_with("remote.") => {
99
                let rest = &k["remote.".len()..];
100
                let Some((name, field)) = rest.rsplit_once('.') else {
101
                    return fail(format!("unknown configuration key {key:?}"));
102
                };
103
                if name.is_empty() || name.contains('/') {
104
                    return fail(format!("invalid remote name in {key:?}"));
105
                }
106
                let map = match field {
107
                    "url" => &mut self.remotes,
108
                    "token" => &mut self.remote_tokens,
109
                    "ca" => &mut self.remote_cas,
110
                    _ => return fail(format!("unknown configuration key {key:?}")),
111
                };
112
                if value.is_empty() {
113
                    map.remove(name);
114
                    if field == "url" {
115
                        self.remote_tokens.remove(name);
116
                        self.remote_cas.remove(name);
117
                    }
118
                } else {
119
                    map.insert(name.to_string(), value.into());
120
                }
121
            }
122
            _ => return fail(format!("unknown configuration key {key:?}")),
123
        }
124
        Ok(())
125
    }
126
127
    /// Defaults, then the user file if it exists, then the repository file.
128
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
129
        let mut c = Config::default_for_user();
130
        if let Some(u) = user_path {
131
            for (k, v) in read_config_file(u)? {
132
                let _ = c.apply(&k, &v);
133
            }
134
        }
135
        for (k, v) in read_config_file(repo_path)? {
136
            if c.apply(&k, &v).is_ok() {
137
                c.repo_layer.insert(k, v);
138
            }
139
        }
140
        Ok(c)
141
    }
142
143
    pub(super) fn save(&self, path: &Path) -> Result<()> {
144
        write_config_file(path, &self.repo_layer)
145
    }
146
147
    /// Keys explicitly set for this repository.
148
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
149
        &self.repo_layer
150
    }
151
}
152
153
/// A count of days, optionally suffixed `d`.
154
fn parse_days(v: &str) -> Result<u64> {
155
    v.trim_end_matches('d').parse().map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
156
}
157
158
/// Read `key = "value"` lines; a missing file is empty.
159
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
160
    let text = match fs::read_to_string(path) {
161
        Ok(t) => t,
162
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
163
        Err(e) => return Err(e.into()),
164
    };
165
    let mut out = BTreeMap::new();
166
    for line in text.lines() {
167
        let line = line.trim();
168
        if line.is_empty() || line.starts_with('#') {
169
            continue;
170
        }
171
        let Some((k, v)) = line.split_once('=') else { continue };
172
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
173
    }
174
    Ok(out)
175
}
176
177
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
178
    let text: String = entries.iter().map(|(k, v)| format!("{k} = \"{v}\"\n")).collect();
179
    write_atomic(path, text.as_bytes())
180
}
181