OXYGENHUB

Coverage / crates/oxy-core/src/repo/config.rs 84.3%

209 of 248 lines run, 41 of 70 functions · run #394 on proposal/151 · run missed

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
    /// `author.for` (oxygen#82): in a keyless agent's home, the account it
29
    /// acts for; the home then authors as that person's newest identity,
30
    /// which the hub names with each certificate, rather than a pinned
31
    /// `author.key` that goes stale with every rotation.
32
    pub author_for: Option<String>,
33
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
34
    /// push-time seals (`false`, the spec default).
35
    pub sign_changes: bool,
36
    pub bookmark: String,
37
    /// `remote.<name>.url`.
38
    pub remotes: BTreeMap<String, String>,
39
    /// `remote.<name>.token`: bearer token for HTTP pushes.
40
    pub remote_tokens: BTreeMap<String, String>,
41
    /// `remote.<name>.ca`: PEM file of extra roots to trust for that remote.
42
    pub remote_cas: BTreeMap<String, String>,
43
    /// `core.remote`: the remote `pull`, `fetch` and `push` use when none is
44
    /// named, for a repository whose remotes include no `origin`.
45
    pub default_remote: Option<String>,
46
    /// `git.claim`: a Git import authors the commits whose Git author email
47
    /// is this repository's identity's with its key (oxygen#97).
48
    pub git_claim: bool,
49
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
50
    pub op_retention_days: u64,
51
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
52
    pub gc_grace_days: u64,
53
    /// `core.snapshot-retention`: days for which past operations keep their
54
    /// working copies reachable (oxygen#98); each workspace's current one is
55
    /// always kept. A file only ever in a working copy goes with it.
56
    pub snapshot_retention_days: u64,
57
    /// `snapshot.max-new-file-size`: a new, untracked file larger than this
58
    /// is left out of working-copy snapshots and named instead (oxygen#98);
59
    /// 0 takes in files of any size.
60
    pub max_new_file: u64,
61
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
62
    pub checkpoint_interval: u64,
63
    /// `push.batch-bytes`: about how many bytes of changes and their texts
64
    /// one request of a long push carries (spec §16.3).
65
    pub push_batch_bytes: u64,
66
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
67
    pub max_blob: Option<u64>,
68
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
69
    pub sparse_paths: Vec<String>,
70
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
71
    pub semantic_deps: bool,
72
    /// `revset.<name>`: a saved revset, used as `name()`.
73
    pub revsets: BTreeMap<String, String>,
74
    /// `storage.url`: the store the repository's objects and operation
75
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
76
    /// (oxygen#68).
77
    pub storage_url: Option<String>,
78
    /// `storage.cache`: the most the local cache in front of that store
79
    /// holds, in bytes.
80
    pub storage_cache: u64,
81
}
82
83
impl Config {
84
    /// Whether the repository's own file sets `key` (as against the user
85
    /// config or a default).
862×
    pub fn is_repo_set(&self, key: &str) -> bool {
872×
        self.repo_layer.contains_key(key)
882×
    }
89
903294×
    pub(super) fn default_for_user() -> Config {
913294×
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
92
        Config {
933294×
            repo_layer: BTreeMap::new(),
943294×
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
953294×
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
963294×
                .unwrap_or_else(|_| format!("{user}@localhost")),
973294×
            author_key: None,
983294×
            signer_key: std::env::var("OXY_SIGNER")
993294×
                .ok()
1003294×
                .and_then(|v| KeyId::from_hex(&v)),
1013294×
            signer_keyless: std::env::var("OXY_SIGNER").is_ok_and(|v| v == "keyless"),
1023294×
            keyless_hub: None,
1033294×
            author_for: None,
104
            sign_changes: false,
1053294×
            bookmark: "main".into(),
1063294×
            remotes: BTreeMap::new(),
1073294×
            remote_tokens: BTreeMap::new(),
1083294×
            remote_cas: BTreeMap::new(),
1093294×
            default_remote: None,
110
            git_claim: false,
111
            op_retention_days: 90,
112
            gc_grace_days: 14,
1133294×
            max_new_file: 100 << 20,
114
            snapshot_retention_days: 7,
115
            checkpoint_interval: 256,
116
            // Well under the 100 MB a proxy in front of a hub may take
117
            // (oxygen#133).
1183294×
            push_batch_bytes: 64 << 20,
1193294×
            max_blob: None,
1203294×
            sparse_paths: Vec::new(),
121
            semantic_deps: false,
1223294×
            revsets: BTreeMap::new(),
1233294×
            storage_url: None,
124
            storage_cache: DEFAULT_STORAGE_CACHE,
125
        }
1263294×
    }
127
128
    /// Set a key in the repository layer, as `oxy config` does.
129532×
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
130532×
        self.apply(key, value)?;
131532×
        if value.is_empty() {
1324×
            self.repo_layer.remove(key);
133528×
        } else {
134528×
            self.repo_layer.insert(key.to_string(), value.to_string());
135528×
        }
136532×
        Ok(())
137532×
    }
138
139
    /// Set a key in the user file without touching any repository.
140200×
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
141200×
        Config::default_for_user().apply(key, value)?;
142199×
        let mut entries = read_config_file(user_path)?;
143199×
        if value.is_empty() {
1440×
            entries.remove(key);
145199×
        } else {
146199×
            entries.insert(key.to_string(), value.to_string());
147199×
        }
148199×
        if let Some(parent) = user_path.parent() {
149199×
            fs::create_dir_all(parent)?;
1500×
        }
151199×
        write_config_file(user_path, &entries)
152200×
    }
153
154
    /// Apply a key to the effective values.
1551997×
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
1563×
        match key {
1571997×
            "author.name" => self.author_name = value.into(),
1581653×
            "author.email" => self.author_email = value.into(),
1591309×
            "author.key" => {
160356×
                self.author_key = if value.is_empty() {
1610×
                    None
162
                } else {
163356×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1640×
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
1650×
                    })?)
166
                }
167
            }
168953×
            "author.signer" => {
16923×
                self.signer_keyless = value == "keyless";
17023×
                self.signer_key = if value.is_empty() || self.signer_keyless {
1712×
                    None
172
                } else {
17321×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1740×
                        RepoError::Msg(
1750×
                            "author.signer must be a 64-character hex KeyId, or \"keyless\"".into(),
1760×
                        )
1770×
                    })?)
178
                }
179
            }
180930×
            "core.sign" => {
18195×
                self.sign_changes = match value {
18295×
                    "change" => true,
183
                    // Empty: unset, the default.
1847×
                    "seal" | "" => false,
1850×
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
186
                }
187
            }
188835×
            "workspace.bookmark" => self.bookmark = value.into(),
189831×
            "keyless.hub" => self.keyless_hub = (!value.is_empty()).then(|| value.to_string()),
190831×
            "author.for" => self.author_for = (!value.is_empty()).then(|| value.to_string()),
191
            // Read by the credential store from the user file.
192829×
            "auth.helper" => {}
193829×
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
194817×
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
195817×
            "snapshot.max-new-file-size" => self.max_new_file = parse_size(value)?,
196817×
            "core.snapshot-retention" => self.snapshot_retention_days = parse_days(value)?,
197817×
            "filter.max-blob" => {
1986×
                self.max_blob = if value.is_empty() {
1990×
                    None
200
                } else {
2016×
                    Some(parse_size(value)?)
202
                }
203
            }
204811×
            "storage.url" => {
2055×
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
206
            }
207806×
            "storage.cache" => {
2080×
                self.storage_cache = if value.is_empty() {
2090×
                    DEFAULT_STORAGE_CACHE
210
                } else {
2110×
                    parse_size(value)?
212
                }
213
            }
214806×
            "core.remote" => {
2151×
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
216
            }
217805×
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
218804×
            "git.claim" => self.git_claim = matches!(value, "true" | "1" | "yes"),
219802×
            "filter.paths" => {
2203×
                self.sparse_paths = value
2213×
                    .split(',')
2224×
                    .map(|p| {
2234×
                        p.trim()
2244×
                            .trim_start_matches("./")
2254×
                            .trim_matches('/')
2264×
                            .to_string()
2274×
                    })
2284×
                    .filter(|p| !p.is_empty())
2293×
                    .collect();
230
            }
231799×
            "core.checkpoint-interval" => {
2323×
                self.checkpoint_interval = value
2333×
                    .parse()
2343×
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
235
            }
236796×
            "push.batch-bytes" => {
2372×
                self.push_batch_bytes = value.parse().ok().filter(|n| *n > 0).ok_or_else(|| {
2380×
                    RepoError::Msg(format!("expected a number of bytes, got {value:?}"))
2390×
                })?;
240
            }
241794×
            k if k.starts_with("remote.") => {
242791×
                let rest = &k["remote.".len()..];
243791×
                let Some((name, field)) = rest.rsplit_once('.') else {
2440×
                    return fail(format!("unknown configuration key {key:?}"));
245
                };
246791×
                if name.is_empty() || name.contains('/') {
2470×
                    return fail(format!("invalid remote name in {key:?}"));
248791×
                }
249791×
                let map = match field {
250791×
                    "url" => &mut self.remotes,
25114×
                    "token" => &mut self.remote_tokens,
2524×
                    "ca" => &mut self.remote_cas,
2530×
                    _ => return fail(format!("unknown configuration key {key:?}")),
254
                };
255791×
                if value.is_empty() {
2564×
                    map.remove(name);
2574×
                    if field == "url" {
2583×
                        self.remote_tokens.remove(name);
2593×
                        self.remote_cas.remove(name);
2603×
                    }
261787×
                } else {
262787×
                    map.insert(name.to_string(), value.into());
263787×
                }
264
            }
2653×
            k if k.starts_with("revset.") => {
2663×
                let name = &k["revset.".len()..];
2673×
                if name.is_empty()
2683×
                    || !name
2693×
                        .chars()
27011×
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
271
                {
2720×
                    return fail(format!(
273
                        "a revset's name is letters, digits, _ and -: {key:?}"
274
                    ));
2753×
                }
2763×
                if value.is_empty() {
2770×
                    self.revsets.remove(name);
2780×
                } else {
2793×
                    crate::revset::parse(value)
2803×
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
2812×
                    self.revsets.insert(name.to_string(), value.into());
282
                }
283
            }
2840×
            _ => return fail(format!("unknown configuration key {key:?}")),
285
        }
2861996×
        Ok(())
2871997×
    }
288
289
    /// Defaults, then the user file if it exists, then the repository file.
2903094×
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
2913094×
        let mut c = Config::default_for_user();
2923094×
        if let Some(u) = user_path {
2933094×
            for (k, v) in read_config_file(u)? {
294480×
                let _ = c.apply(&k, &v);
295480×
            }
2960×
        }
2973094×
        for (k, v) in read_config_file(repo_path)? {
298785×
            if c.apply(&k, &v).is_ok() {
299785×
                c.repo_layer.insert(k, v);
300785×
            }
301
        }
302
        // author.for (oxygen#82): the identity the hub last named as the
303
        // person's newest, kept in the home; a repository's own
304
        // author.key pin still wins.
3053094×
        if c.author_for.is_some() && !c.repo_layer.contains_key("author.key") {
3061×
            if let Some(k) = user_path
3071×
                .and_then(Path::parent)
3081×
                .and_then(|home| fs::read_to_string(home.join("keys").join(AUTHOR_FOR_FILE)).ok())
3091×
                .and_then(|s| KeyId::from_hex(s.trim()))
3101×
            {
3111×
                c.author_key = Some(k);
3121×
            }
3133093×
        }
3143094×
        Ok(c)
3153094×
    }
316
3171029×
    pub(super) fn save(&self, path: &Path) -> Result<()> {
3181029×
        write_config_file(path, &self.repo_layer)
3191029×
    }
320
321
    /// Keys explicitly set for this repository.
32222×
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
32322×
        &self.repo_layer
32422×
    }
325
}
326
327
/// In a home's `keys/`: the key of the identity `author.for` follows,
328
/// as the hub last named it (oxygen#82).
329
pub const AUTHOR_FOR_FILE: &str = "author.for";
330
331
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
332
/// `storage.cache` when unset: 2 GiB.
333
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
334
3358×
pub fn parse_size(v: &str) -> Result<u64> {
3368×
    let v = v.trim();
3378×
    let (num, mult) = match v.chars().last() {
3381×
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
3391×
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
3400×
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
3416×
        _ => (v, 1),
342
    };
3438×
    let n: u64 = num
3448×
        .trim()
3458×
        .parse()
3468×
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
3477×
    Ok(n * mult)
3488×
}
349
350
/// A count of days, optionally suffixed `d`.
35112×
fn parse_days(v: &str) -> Result<u64> {
35212×
    v.trim_end_matches('d')
35312×
        .parse()
35412×
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
35512×
}
356
357
/// Read `key = "value"` lines; a missing file is empty.
3586954×
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
3596954×
    let text = match fs::read_to_string(path) {
3602798×
        Ok(t) => t,
3614156×
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
3620×
        Err(e) => return Err(e.into()),
363
    };
3642798×
    let mut out = BTreeMap::new();
3652798×
    for line in text.lines() {
3661653×
        let line = line.trim();
3671653×
        if line.is_empty() || line.starts_with('#') {
3680×
            continue;
3691653×
        }
3701653×
        let Some((k, v)) = line.split_once('=') else {
3710×
            continue;
372
        };
3731653×
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
374
    }
3752798×
    Ok(out)
3766954×
}
377
3781228×
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
3791228×
    let text: String = entries
3801228×
        .iter()
3811228×
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
3821228×
        .collect();
3831228×
    write_atomic(path, text.as_bytes())
3841228×
}