OXYGENHUB

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

210 of 249 lines run, 41 of 70 functions · run #426 on main · 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
    /// `git.colocate`: keep a `.git` beside `.oxy` with the current
50
    /// bookmark exported after every operation, so editors' Git features
51
    /// work on an Oxygen checkout (one way: oxy to Git).
52
    pub git_colocate: bool,
53
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
54
    pub op_retention_days: u64,
55
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
56
    pub gc_grace_days: u64,
57
    /// `core.snapshot-retention`: days for which past operations keep their
58
    /// working copies reachable (oxygen#98); each workspace's current one is
59
    /// always kept. A file only ever in a working copy goes with it.
60
    pub snapshot_retention_days: u64,
61
    /// `snapshot.max-new-file-size`: a new, untracked file larger than this
62
    /// is left out of working-copy snapshots and named instead (oxygen#98);
63
    /// 0 takes in files of any size.
64
    pub max_new_file: u64,
65
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
66
    pub checkpoint_interval: u64,
67
    /// `push.batch-bytes`: about how many bytes of changes and their texts
68
    /// one request of a long push carries (spec §16.3).
69
    pub push_batch_bytes: u64,
70
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
71
    pub max_blob: Option<u64>,
72
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
73
    pub sparse_paths: Vec<String>,
74
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
75
    pub semantic_deps: bool,
76
    /// `revset.<name>`: a saved revset, used as `name()`.
77
    pub revsets: BTreeMap<String, String>,
78
    /// `storage.url`: the store the repository's objects and operation
79
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
80
    /// (oxygen#68).
81
    pub storage_url: Option<String>,
82
    /// `storage.cache`: the most the local cache in front of that store
83
    /// holds, in bytes.
84
    pub storage_cache: u64,
85
}
86
87
impl Config {
88
    /// Whether the repository's own file sets `key` (as against the user
89
    /// config or a default).
904×
    pub fn is_repo_set(&self, key: &str) -> bool {
914×
        self.repo_layer.contains_key(key)
924×
    }
93
943590×
    pub(super) fn default_for_user() -> Config {
953590×
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
96
        Config {
973590×
            repo_layer: BTreeMap::new(),
983590×
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
993590×
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
1003590×
                .unwrap_or_else(|_| format!("{user}@localhost")),
1013590×
            author_key: None,
1023590×
            signer_key: std::env::var("OXY_SIGNER")
1033590×
                .ok()
1043590×
                .and_then(|v| KeyId::from_hex(&v)),
1053590×
            signer_keyless: std::env::var("OXY_SIGNER").is_ok_and(|v| v == "keyless"),
1063590×
            keyless_hub: None,
1073590×
            author_for: None,
108
            sign_changes: false,
1093590×
            bookmark: "main".into(),
1103590×
            remotes: BTreeMap::new(),
1113590×
            remote_tokens: BTreeMap::new(),
1123590×
            remote_cas: BTreeMap::new(),
1133590×
            default_remote: None,
114
            git_claim: false,
115
            git_colocate: false,
116
            op_retention_days: 90,
117
            gc_grace_days: 14,
1183590×
            max_new_file: 100 << 20,
119
            snapshot_retention_days: 7,
120
            checkpoint_interval: 256,
121
            // Well under the 100 MB a proxy in front of a hub may take
122
            // (oxygen#133).
1233590×
            push_batch_bytes: 64 << 20,
1243590×
            max_blob: None,
1253590×
            sparse_paths: Vec::new(),
126
            semantic_deps: false,
1273590×
            revsets: BTreeMap::new(),
1283590×
            storage_url: None,
129
            storage_cache: DEFAULT_STORAGE_CACHE,
130
        }
1313590×
    }
132
133
    /// Set a key in the repository layer, as `oxy config` does.
134546×
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
135546×
        self.apply(key, value)?;
136546×
        if value.is_empty() {
1374×
            self.repo_layer.remove(key);
138542×
        } else {
139542×
            self.repo_layer.insert(key.to_string(), value.to_string());
140542×
        }
141546×
        Ok(())
142546×
    }
143
144
    /// Set a key in the user file without touching any repository.
145225×
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
146225×
        Config::default_for_user().apply(key, value)?;
147224×
        let mut entries = read_config_file(user_path)?;
148224×
        if value.is_empty() {
1490×
            entries.remove(key);
150224×
        } else {
151224×
            entries.insert(key.to_string(), value.to_string());
152224×
        }
153224×
        if let Some(parent) = user_path.parent() {
154224×
            fs::create_dir_all(parent)?;
1550×
        }
156224×
        write_config_file(user_path, &entries)
157225×
    }
158
159
    /// Apply a key to the effective values.
1602625×
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
1613×
        match key {
1622625×
            "author.name" => self.author_name = value.into(),
1632135×
            "author.email" => self.author_email = value.into(),
1641645×
            "author.key" => {
165509×
                self.author_key = if value.is_empty() {
1660×
                    None
167
                } else {
168509×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1690×
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
1700×
                    })?)
171
                }
172
            }
1731136×
            "author.signer" => {
17423×
                self.signer_keyless = value == "keyless";
17523×
                self.signer_key = if value.is_empty() || self.signer_keyless {
1762×
                    None
177
                } else {
17821×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1790×
                        RepoError::Msg(
1800×
                            "author.signer must be a 64-character hex KeyId, or \"keyless\"".into(),
1810×
                        )
1820×
                    })?)
183
                }
184
            }
1851113×
            "core.sign" => {
186153×
                self.sign_changes = match value {
187153×
                    "change" => true,
188
                    // Empty: unset, the default.
1897×
                    "seal" | "" => false,
1900×
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
191
                }
192
            }
193960×
            "workspace.bookmark" => self.bookmark = value.into(),
194956×
            "keyless.hub" => self.keyless_hub = (!value.is_empty()).then(|| value.to_string()),
195956×
            "author.for" => self.author_for = (!value.is_empty()).then(|| value.to_string()),
196
            // Read by the credential store from the user file.
197954×
            "auth.helper" => {}
198954×
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
199942×
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
200942×
            "snapshot.max-new-file-size" => self.max_new_file = parse_size(value)?,
201942×
            "core.snapshot-retention" => self.snapshot_retention_days = parse_days(value)?,
202942×
            "filter.max-blob" => {
2036×
                self.max_blob = if value.is_empty() {
2040×
                    None
205
                } else {
2066×
                    Some(parse_size(value)?)
207
                }
208
            }
209936×
            "storage.url" => {
2105×
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
211
            }
212931×
            "storage.cache" => {
2130×
                self.storage_cache = if value.is_empty() {
2140×
                    DEFAULT_STORAGE_CACHE
215
                } else {
2160×
                    parse_size(value)?
217
                }
218
            }
219931×
            "core.remote" => {
2201×
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
221
            }
222930×
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
223929×
            "git.claim" => self.git_claim = matches!(value, "true" | "1" | "yes"),
224927×
            "git.colocate" => self.git_colocate = matches!(value, "true" | "1" | "yes"),
225916×
            "filter.paths" => {
2263×
                self.sparse_paths = value
2273×
                    .split(',')
2284×
                    .map(|p| {
2294×
                        p.trim()
2304×
                            .trim_start_matches("./")
2314×
                            .trim_matches('/')
2324×
                            .to_string()
2334×
                    })
2344×
                    .filter(|p| !p.is_empty())
2353×
                    .collect();
236
            }
237913×
            "core.checkpoint-interval" => {
2383×
                self.checkpoint_interval = value
2393×
                    .parse()
2403×
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
241
            }
242910×
            "push.batch-bytes" => {
2432×
                self.push_batch_bytes = value.parse().ok().filter(|n| *n > 0).ok_or_else(|| {
2440×
                    RepoError::Msg(format!("expected a number of bytes, got {value:?}"))
2450×
                })?;
246
            }
247908×
            k if k.starts_with("remote.") => {
248905×
                let rest = &k["remote.".len()..];
249905×
                let Some((name, field)) = rest.rsplit_once('.') else {
2500×
                    return fail(format!("unknown configuration key {key:?}"));
251
                };
252905×
                if name.is_empty() || name.contains('/') {
2530×
                    return fail(format!("invalid remote name in {key:?}"));
254905×
                }
255905×
                let map = match field {
256905×
                    "url" => &mut self.remotes,
25716×
                    "token" => &mut self.remote_tokens,
2584×
                    "ca" => &mut self.remote_cas,
2590×
                    _ => return fail(format!("unknown configuration key {key:?}")),
260
                };
261905×
                if value.is_empty() {
2624×
                    map.remove(name);
2634×
                    if field == "url" {
2643×
                        self.remote_tokens.remove(name);
2653×
                        self.remote_cas.remove(name);
2663×
                    }
267901×
                } else {
268901×
                    map.insert(name.to_string(), value.into());
269901×
                }
270
            }
2713×
            k if k.starts_with("revset.") => {
2723×
                let name = &k["revset.".len()..];
2733×
                if name.is_empty()
2743×
                    || !name
2753×
                        .chars()
27611×
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
277
                {
2780×
                    return fail(format!(
279
                        "a revset's name is letters, digits, _ and -: {key:?}"
280
                    ));
2813×
                }
2823×
                if value.is_empty() {
2830×
                    self.revsets.remove(name);
2840×
                } else {
2853×
                    crate::revset::parse(value)
2863×
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
2872×
                    self.revsets.insert(name.to_string(), value.into());
288
                }
289
            }
2900×
            _ => return fail(format!("unknown configuration key {key:?}")),
291
        }
2922624×
        Ok(())
2932625×
    }
294
295
    /// Defaults, then the user file if it exists, then the repository file.
2963365×
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
2973365×
        let mut c = Config::default_for_user();
2983365×
        if let Some(u) = user_path {
2993365×
            for (k, v) in read_config_file(u)? {
300942×
                let _ = c.apply(&k, &v);
301942×
            }
3020×
        }
3033365×
        for (k, v) in read_config_file(repo_path)? {
304912×
            if c.apply(&k, &v).is_ok() {
305912×
                c.repo_layer.insert(k, v);
306912×
            }
307
        }
308
        // author.for (oxygen#82): the identity the hub last named as the
309
        // person's newest, kept in the home; a repository's own
310
        // author.key pin still wins.
3113365×
        if c.author_for.is_some() && !c.repo_layer.contains_key("author.key") {
3121×
            if let Some(k) = user_path
3131×
                .and_then(Path::parent)
3141×
                .and_then(|home| fs::read_to_string(home.join("keys").join(AUTHOR_FOR_FILE)).ok())
3151×
                .and_then(|s| KeyId::from_hex(s.trim()))
3161×
            {
3171×
                c.author_key = Some(k);
3181×
            }
3193364×
        }
3203365×
        Ok(c)
3213365×
    }
322
3231061×
    pub(super) fn save(&self, path: &Path) -> Result<()> {
3241061×
        write_config_file(path, &self.repo_layer)
3251061×
    }
326
327
    /// Keys explicitly set for this repository.
32825×
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
32925×
        &self.repo_layer
33025×
    }
331
}
332
333
/// In a home's `keys/`: the key of the identity `author.for` follows,
334
/// as the hub last named it (oxygen#82).
335
pub const AUTHOR_FOR_FILE: &str = "author.for";
336
337
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
338
/// `storage.cache` when unset: 2 GiB.
339
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
340
3418×
pub fn parse_size(v: &str) -> Result<u64> {
3428×
    let v = v.trim();
3438×
    let (num, mult) = match v.chars().last() {
3441×
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
3451×
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
3460×
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
3476×
        _ => (v, 1),
348
    };
3498×
    let n: u64 = num
3508×
        .trim()
3518×
        .parse()
3528×
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
3537×
    Ok(n * mult)
3548×
}
355
356
/// A count of days, optionally suffixed `d`.
35712×
fn parse_days(v: &str) -> Result<u64> {
35812×
    v.trim_end_matches('d')
35912×
        .parse()
36012×
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
36112×
}
362
363
/// Read `key = "value"` lines; a missing file is empty.
3647542×
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
3657542×
    let text = match fs::read_to_string(path) {
3663208×
        Ok(t) => t,
3674334×
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
3680×
        Err(e) => return Err(e.into()),
369
    };
3703208×
    let mut out = BTreeMap::new();
3713208×
    for line in text.lines() {
3722294×
        let line = line.trim();
3732294×
        if line.is_empty() || line.starts_with('#') {
3740×
            continue;
3752294×
        }
3762294×
        let Some((k, v)) = line.split_once('=') else {
3770×
            continue;
378
        };
3792294×
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
380
    }
3813208×
    Ok(out)
3827542×
}
383
3841285×
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
3851285×
    let text: String = entries
3861285×
        .iter()
3871285×
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
3881285×
        .collect();
3891285×
    write_atomic(path, text.as_bytes())
3901285×
}