OXYGENHUB
# 1ec3f008e96a oxygen / crates / oxy-core / src / repo / config.rs
9.4 KiB · Rust · last changed Sign in once per hub: oxy auth login, status and logout (closes #47) 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
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
31
    pub checkpoint_interval: u64,
32
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
33
    pub max_blob: Option<u64>,
34
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
35
    pub sparse_paths: Vec<String>,
36
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
37
    pub semantic_deps: bool,
38
}
39
40
impl Config {
41
    pub(super) fn default_for_user() -> Config {
42
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
43
        Config {
44
            repo_layer: BTreeMap::new(),
45
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
46
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
47
                .unwrap_or_else(|_| format!("{user}@localhost")),
48
            author_key: None,
49
            sign_changes: false,
50
            bookmark: "main".into(),
51
            remotes: BTreeMap::new(),
52
            remote_tokens: BTreeMap::new(),
53
            remote_cas: BTreeMap::new(),
54
            op_retention_days: 90,
55
            gc_grace_days: 14,
56
            checkpoint_interval: 256,
57
            max_blob: None,
58
            sparse_paths: Vec::new(),
59
            semantic_deps: false,
60
        }
61
    }
62
63
    /// Set a key in the repository layer, as `oxy config` does.
64
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
65
        self.apply(key, value)?;
66
        if value.is_empty() {
67
            self.repo_layer.remove(key);
68
        } else {
69
            self.repo_layer.insert(key.to_string(), value.to_string());
70
        }
71
        Ok(())
72
    }
73
74
    /// Set a key in the user file without touching any repository.
75
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
76
        Config::default_for_user().apply(key, value)?;
77
        let mut entries = read_config_file(user_path)?;
78
        if value.is_empty() {
79
            entries.remove(key);
80
        } else {
81
            entries.insert(key.to_string(), value.to_string());
82
        }
83
        if let Some(parent) = user_path.parent() {
84
            fs::create_dir_all(parent)?;
85
        }
86
        write_config_file(user_path, &entries)
87
    }
88
89
    /// Apply a key to the effective values.
90
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
91
        match key {
92
            "author.name" => self.author_name = value.into(),
93
            "author.email" => self.author_email = value.into(),
94
            "author.key" => {
95
                self.author_key = if value.is_empty() {
96
                    None
97
                } else {
98
                    Some(KeyId::from_hex(value).ok_or_else(|| {
99
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
100
                    })?)
101
                }
102
            }
103
            "core.sign" => {
104
                self.sign_changes = match value {
105
                    "change" => true,
106
                    "seal" => false,
107
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
108
                }
109
            }
110
            "workspace.bookmark" => self.bookmark = value.into(),
111
            // Read by the credential store from the user file.
112
            "auth.helper" => {}
113
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
114
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
115
            "filter.max-blob" => {
116
                self.max_blob = if value.is_empty() {
117
                    None
118
                } else {
119
                    Some(parse_size(value)?)
120
                }
121
            }
122
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
123
            "filter.paths" => {
124
                self.sparse_paths = value
125
                    .split(',')
126
                    .map(|p| {
127
                        p.trim()
128
                            .trim_start_matches("./")
129
                            .trim_matches('/')
130
                            .to_string()
131
                    })
132
                    .filter(|p| !p.is_empty())
133
                    .collect();
134
            }
135
            "core.checkpoint-interval" => {
136
                self.checkpoint_interval = value
137
                    .parse()
138
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
139
            }
140
            k if k.starts_with("remote.") => {
141
                let rest = &k["remote.".len()..];
142
                let Some((name, field)) = rest.rsplit_once('.') else {
143
                    return fail(format!("unknown configuration key {key:?}"));
144
                };
145
                if name.is_empty() || name.contains('/') {
146
                    return fail(format!("invalid remote name in {key:?}"));
147
                }
148
                let map = match field {
149
                    "url" => &mut self.remotes,
150
                    "token" => &mut self.remote_tokens,
151
                    "ca" => &mut self.remote_cas,
152
                    _ => return fail(format!("unknown configuration key {key:?}")),
153
                };
154
                if value.is_empty() {
155
                    map.remove(name);
156
                    if field == "url" {
157
                        self.remote_tokens.remove(name);
158
                        self.remote_cas.remove(name);
159
                    }
160
                } else {
161
                    map.insert(name.to_string(), value.into());
162
                }
163
            }
164
            _ => return fail(format!("unknown configuration key {key:?}")),
165
        }
166
        Ok(())
167
    }
168
169
    /// Defaults, then the user file if it exists, then the repository file.
170
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
171
        let mut c = Config::default_for_user();
172
        if let Some(u) = user_path {
173
            for (k, v) in read_config_file(u)? {
174
                let _ = c.apply(&k, &v);
175
            }
176
        }
177
        for (k, v) in read_config_file(repo_path)? {
178
            if c.apply(&k, &v).is_ok() {
179
                c.repo_layer.insert(k, v);
180
            }
181
        }
182
        Ok(c)
183
    }
184
185
    pub(super) fn save(&self, path: &Path) -> Result<()> {
186
        write_config_file(path, &self.repo_layer)
187
    }
188
189
    /// Keys explicitly set for this repository.
190
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
191
        &self.repo_layer
192
    }
193
}
194
195
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
196
pub fn parse_size(v: &str) -> Result<u64> {
197
    let v = v.trim();
198
    let (num, mult) = match v.chars().last() {
199
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
200
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
201
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
202
        _ => (v, 1),
203
    };
204
    let n: u64 = num
205
        .trim()
206
        .parse()
207
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
208
    Ok(n * mult)
209
}
210
211
/// A count of days, optionally suffixed `d`.
212
fn parse_days(v: &str) -> Result<u64> {
213
    v.trim_end_matches('d')
214
        .parse()
215
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
216
}
217
218
/// Read `key = "value"` lines; a missing file is empty.
219
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
220
    let text = match fs::read_to_string(path) {
221
        Ok(t) => t,
222
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
223
        Err(e) => return Err(e.into()),
224
    };
225
    let mut out = BTreeMap::new();
226
    for line in text.lines() {
227
        let line = line.trim();
228
        if line.is_empty() || line.starts_with('#') {
229
            continue;
230
        }
231
        let Some((k, v)) = line.split_once('=') else {
232
            continue;
233
        };
234
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
235
    }
236
    Ok(out)
237
}
238
239
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
240
    let text: String = entries
241
        .iter()
242
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
243
        .collect();
244
    write_atomic(path, text.as_bytes())
245
}