OXYGENHUB
# c96354484bd9 oxygen / crates / oxy-core / src / repo / config.rs
13.9 KiB · Rust · last changed Grant tokens reach hubs; unsetting core.sign works 19 days 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
    /// `author.signer` (or `$OXY_SIGNER`): the key that signs and seals in
17
    /// place of `author.key`, whose identity lists it as a delegate. An
18
    /// agent sets it to its own key, so its changes carry the human as
19
    /// author and the agent's signature (spec §14.2, agent workflows §2).
20
    pub signer_key: Option<KeyId>,
21
    /// `author.signer = "keyless"`: sign with fresh keys the hub certifies
22
    /// under the agent's grant, keeping no key on disk (spec §14.7,
23
    /// oxygenhub#241).
24
    pub signer_keyless: bool,
25
    /// `keyless.hub`: the hub that certifies them (default: the default
26
    /// remote's hub).
27
    pub keyless_hub: Option<String>,
28
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
29
    /// push-time seals (`false`, the spec default).
30
    pub sign_changes: bool,
31
    pub bookmark: String,
32
    /// `remote.<name>.url`.
33
    pub remotes: BTreeMap<String, String>,
34
    /// `remote.<name>.token`: bearer token for HTTP pushes.
35
    pub remote_tokens: BTreeMap<String, String>,
36
    /// `remote.<name>.ca`: PEM file of extra roots to trust for that remote.
37
    pub remote_cas: BTreeMap<String, String>,
38
    /// `core.remote`: the remote `pull`, `fetch` and `push` use when none is
39
    /// named, for a repository whose remotes include no `origin`.
40
    pub default_remote: Option<String>,
41
    /// `git.claim`: a Git import authors the commits whose Git author email
42
    /// is this repository's identity's with its key (oxygen#97).
43
    pub git_claim: bool,
44
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
45
    pub op_retention_days: u64,
46
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
47
    pub gc_grace_days: u64,
48
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
49
    pub checkpoint_interval: u64,
50
    /// `push.batch-bytes`: about how many bytes of changes and their texts
51
    /// one request of a long push carries (spec §16.3).
52
    pub push_batch_bytes: u64,
53
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
54
    pub max_blob: Option<u64>,
55
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
56
    pub sparse_paths: Vec<String>,
57
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
58
    pub semantic_deps: bool,
59
    /// `revset.<name>`: a saved revset, used as `name()`.
60
    pub revsets: BTreeMap<String, String>,
61
    /// `storage.url`: the store the repository's objects and operation
62
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
63
    /// (oxygen#68).
64
    pub storage_url: Option<String>,
65
    /// `storage.cache`: the most the local cache in front of that store
66
    /// holds, in bytes.
67
    pub storage_cache: u64,
68
}
69
70
impl Config {
71
    /// Whether the repository's own file sets `key` (as against the user
72
    /// config or a default).
73
    pub fn is_repo_set(&self, key: &str) -> bool {
74
        self.repo_layer.contains_key(key)
75
    }
76
77
    pub(super) fn default_for_user() -> Config {
78
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
79
        Config {
80
            repo_layer: BTreeMap::new(),
81
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
82
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
83
                .unwrap_or_else(|_| format!("{user}@localhost")),
84
            author_key: None,
85
            signer_key: std::env::var("OXY_SIGNER")
86
                .ok()
87
                .and_then(|v| KeyId::from_hex(&v)),
88
            signer_keyless: std::env::var("OXY_SIGNER").is_ok_and(|v| v == "keyless"),
89
            keyless_hub: None,
90
            sign_changes: false,
91
            bookmark: "main".into(),
92
            remotes: BTreeMap::new(),
93
            remote_tokens: BTreeMap::new(),
94
            remote_cas: BTreeMap::new(),
95
            default_remote: None,
96
            git_claim: false,
97
            op_retention_days: 90,
98
            gc_grace_days: 14,
99
            checkpoint_interval: 256,
100
            push_batch_bytes: 256 << 20,
101
            max_blob: None,
102
            sparse_paths: Vec::new(),
103
            semantic_deps: false,
104
            revsets: BTreeMap::new(),
105
            storage_url: None,
106
            storage_cache: DEFAULT_STORAGE_CACHE,
107
        }
108
    }
109
110
    /// Set a key in the repository layer, as `oxy config` does.
111
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
112
        self.apply(key, value)?;
113
        if value.is_empty() {
114
            self.repo_layer.remove(key);
115
        } else {
116
            self.repo_layer.insert(key.to_string(), value.to_string());
117
        }
118
        Ok(())
119
    }
120
121
    /// Set a key in the user file without touching any repository.
122
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
123
        Config::default_for_user().apply(key, value)?;
124
        let mut entries = read_config_file(user_path)?;
125
        if value.is_empty() {
126
            entries.remove(key);
127
        } else {
128
            entries.insert(key.to_string(), value.to_string());
129
        }
130
        if let Some(parent) = user_path.parent() {
131
            fs::create_dir_all(parent)?;
132
        }
133
        write_config_file(user_path, &entries)
134
    }
135
136
    /// Apply a key to the effective values.
137
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
138
        match key {
139
            "author.name" => self.author_name = value.into(),
140
            "author.email" => self.author_email = value.into(),
141
            "author.key" => {
142
                self.author_key = if value.is_empty() {
143
                    None
144
                } else {
145
                    Some(KeyId::from_hex(value).ok_or_else(|| {
146
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
147
                    })?)
148
                }
149
            }
150
            "author.signer" => {
151
                self.signer_keyless = value == "keyless";
152
                self.signer_key = if value.is_empty() || self.signer_keyless {
153
                    None
154
                } else {
155
                    Some(KeyId::from_hex(value).ok_or_else(|| {
156
                        RepoError::Msg(
157
                            "author.signer must be a 64-character hex KeyId, or \"keyless\"".into(),
158
                        )
159
                    })?)
160
                }
161
            }
162
            "core.sign" => {
163
                self.sign_changes = match value {
164
                    "change" => true,
165
                    // Empty: unset, the default.
166
                    "seal" | "" => false,
167
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
168
                }
169
            }
170
            "workspace.bookmark" => self.bookmark = value.into(),
171
            "keyless.hub" => self.keyless_hub = (!value.is_empty()).then(|| value.to_string()),
172
            // Read by the credential store from the user file.
173
            "auth.helper" => {}
174
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
175
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
176
            "filter.max-blob" => {
177
                self.max_blob = if value.is_empty() {
178
                    None
179
                } else {
180
                    Some(parse_size(value)?)
181
                }
182
            }
183
            "storage.url" => {
184
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
185
            }
186
            "storage.cache" => {
187
                self.storage_cache = if value.is_empty() {
188
                    DEFAULT_STORAGE_CACHE
189
                } else {
190
                    parse_size(value)?
191
                }
192
            }
193
            "core.remote" => {
194
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
195
            }
196
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
197
            "git.claim" => self.git_claim = matches!(value, "true" | "1" | "yes"),
198
            "filter.paths" => {
199
                self.sparse_paths = value
200
                    .split(',')
201
                    .map(|p| {
202
                        p.trim()
203
                            .trim_start_matches("./")
204
                            .trim_matches('/')
205
                            .to_string()
206
                    })
207
                    .filter(|p| !p.is_empty())
208
                    .collect();
209
            }
210
            "core.checkpoint-interval" => {
211
                self.checkpoint_interval = value
212
                    .parse()
213
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
214
            }
215
            "push.batch-bytes" => {
216
                self.push_batch_bytes = value.parse().ok().filter(|n| *n > 0).ok_or_else(|| {
217
                    RepoError::Msg(format!("expected a number of bytes, got {value:?}"))
218
                })?;
219
            }
220
            k if k.starts_with("remote.") => {
221
                let rest = &k["remote.".len()..];
222
                let Some((name, field)) = rest.rsplit_once('.') else {
223
                    return fail(format!("unknown configuration key {key:?}"));
224
                };
225
                if name.is_empty() || name.contains('/') {
226
                    return fail(format!("invalid remote name in {key:?}"));
227
                }
228
                let map = match field {
229
                    "url" => &mut self.remotes,
230
                    "token" => &mut self.remote_tokens,
231
                    "ca" => &mut self.remote_cas,
232
                    _ => return fail(format!("unknown configuration key {key:?}")),
233
                };
234
                if value.is_empty() {
235
                    map.remove(name);
236
                    if field == "url" {
237
                        self.remote_tokens.remove(name);
238
                        self.remote_cas.remove(name);
239
                    }
240
                } else {
241
                    map.insert(name.to_string(), value.into());
242
                }
243
            }
244
            k if k.starts_with("revset.") => {
245
                let name = &k["revset.".len()..];
246
                if name.is_empty()
247
                    || !name
248
                        .chars()
249
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
250
                {
251
                    return fail(format!(
252
                        "a revset's name is letters, digits, _ and -: {key:?}"
253
                    ));
254
                }
255
                if value.is_empty() {
256
                    self.revsets.remove(name);
257
                } else {
258
                    crate::revset::parse(value)
259
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
260
                    self.revsets.insert(name.to_string(), value.into());
261
                }
262
            }
263
            _ => return fail(format!("unknown configuration key {key:?}")),
264
        }
265
        Ok(())
266
    }
267
268
    /// Defaults, then the user file if it exists, then the repository file.
269
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
270
        let mut c = Config::default_for_user();
271
        if let Some(u) = user_path {
272
            for (k, v) in read_config_file(u)? {
273
                let _ = c.apply(&k, &v);
274
            }
275
        }
276
        for (k, v) in read_config_file(repo_path)? {
277
            if c.apply(&k, &v).is_ok() {
278
                c.repo_layer.insert(k, v);
279
            }
280
        }
281
        Ok(c)
282
    }
283
284
    pub(super) fn save(&self, path: &Path) -> Result<()> {
285
        write_config_file(path, &self.repo_layer)
286
    }
287
288
    /// Keys explicitly set for this repository.
289
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
290
        &self.repo_layer
291
    }
292
}
293
294
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
295
/// `storage.cache` when unset: 2 GiB.
296
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
297
298
pub fn parse_size(v: &str) -> Result<u64> {
299
    let v = v.trim();
300
    let (num, mult) = match v.chars().last() {
301
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
302
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
303
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
304
        _ => (v, 1),
305
    };
306
    let n: u64 = num
307
        .trim()
308
        .parse()
309
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
310
    Ok(n * mult)
311
}
312
313
/// A count of days, optionally suffixed `d`.
314
fn parse_days(v: &str) -> Result<u64> {
315
    v.trim_end_matches('d')
316
        .parse()
317
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
318
}
319
320
/// Read `key = "value"` lines; a missing file is empty.
321
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
322
    let text = match fs::read_to_string(path) {
323
        Ok(t) => t,
324
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
325
        Err(e) => return Err(e.into()),
326
    };
327
    let mut out = BTreeMap::new();
328
    for line in text.lines() {
329
        let line = line.trim();
330
        if line.is_empty() || line.starts_with('#') {
331
            continue;
332
        }
333
        let Some((k, v)) = line.split_once('=') else {
334
            continue;
335
        };
336
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
337
    }
338
    Ok(out)
339
}
340
341
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
342
    let text: String = entries
343
        .iter()
344
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
345
        .collect();
346
    write_atomic(path, text.as_bytes())
347
}