OXYGENHUB

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

187 of 223 lines run, 37 of 60 functions · run #266 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
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
22
    /// push-time seals (`false`, the spec default).
23
    pub sign_changes: bool,
24
    pub bookmark: String,
25
    /// `remote.<name>.url`.
26
    pub remotes: BTreeMap<String, String>,
27
    /// `remote.<name>.token`: bearer token for HTTP pushes.
28
    pub remote_tokens: BTreeMap<String, String>,
29
    /// `remote.<name>.ca`: PEM file of extra roots to trust for that remote.
30
    pub remote_cas: BTreeMap<String, String>,
31
    /// `core.remote`: the remote `pull`, `fetch` and `push` use when none is
32
    /// named, for a repository whose remotes include no `origin`.
33
    pub default_remote: Option<String>,
34
    /// `git.claim`: a Git import authors the commits whose Git author email
35
    /// is this repository's identity's with its key (oxygen#97).
36
    pub git_claim: bool,
37
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
38
    pub op_retention_days: u64,
39
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
40
    pub gc_grace_days: u64,
41
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
42
    pub checkpoint_interval: u64,
43
    /// `push.batch-bytes`: about how many bytes of changes and their texts
44
    /// one request of a long push carries (spec §16.3).
45
    pub push_batch_bytes: u64,
46
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
47
    pub max_blob: Option<u64>,
48
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
49
    pub sparse_paths: Vec<String>,
50
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
51
    pub semantic_deps: bool,
52
    /// `revset.<name>`: a saved revset, used as `name()`.
53
    pub revsets: BTreeMap<String, String>,
54
    /// `storage.url`: the store the repository's objects and operation
55
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
56
    /// (oxygen#68).
57
    pub storage_url: Option<String>,
58
    /// `storage.cache`: the most the local cache in front of that store
59
    /// holds, in bytes.
60
    pub storage_cache: u64,
61
}
62
63
impl Config {
64
    /// Whether the repository's own file sets `key` (as against the user
65
    /// config or a default).
662×
    pub fn is_repo_set(&self, key: &str) -> bool {
672×
        self.repo_layer.contains_key(key)
682×
    }
69
702612×
    pub(super) fn default_for_user() -> Config {
712612×
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
72
        Config {
732612×
            repo_layer: BTreeMap::new(),
742612×
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
752612×
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
762612×
                .unwrap_or_else(|_| format!("{user}@localhost")),
772612×
            author_key: None,
782612×
            signer_key: std::env::var("OXY_SIGNER")
792612×
                .ok()
802612×
                .and_then(|v| KeyId::from_hex(&v)),
81
            sign_changes: false,
822612×
            bookmark: "main".into(),
832612×
            remotes: BTreeMap::new(),
842612×
            remote_tokens: BTreeMap::new(),
852612×
            remote_cas: BTreeMap::new(),
862612×
            default_remote: None,
87
            git_claim: false,
88
            op_retention_days: 90,
89
            gc_grace_days: 14,
90
            checkpoint_interval: 256,
912612×
            push_batch_bytes: 256 << 20,
922612×
            max_blob: None,
932612×
            sparse_paths: Vec::new(),
94
            semantic_deps: false,
952612×
            revsets: BTreeMap::new(),
962612×
            storage_url: None,
97
            storage_cache: DEFAULT_STORAGE_CACHE,
98
        }
992612×
    }
100
101
    /// Set a key in the repository layer, as `oxy config` does.
102449×
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
103449×
        self.apply(key, value)?;
104449×
        if value.is_empty() {
1052×
            self.repo_layer.remove(key);
106447×
        } else {
107447×
            self.repo_layer.insert(key.to_string(), value.to_string());
108447×
        }
109449×
        Ok(())
110449×
    }
111
112
    /// Set a key in the user file without touching any repository.
11391×
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
11491×
        Config::default_for_user().apply(key, value)?;
11590×
        let mut entries = read_config_file(user_path)?;
11690×
        if value.is_empty() {
1170×
            entries.remove(key);
11890×
        } else {
11990×
            entries.insert(key.to_string(), value.to_string());
12090×
        }
12190×
        if let Some(parent) = user_path.parent() {
12290×
            fs::create_dir_all(parent)?;
1230×
        }
12490×
        write_config_file(user_path, &entries)
12591×
    }
126
127
    /// Apply a key to the effective values.
1281486×
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
1293×
        match key {
1301486×
            "author.name" => self.author_name = value.into(),
1311240×
            "author.email" => self.author_email = value.into(),
132994×
            "author.key" => {
133248×
                self.author_key = if value.is_empty() {
1340×
                    None
135
                } else {
136248×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1370×
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
1380×
                    })?)
139
                }
140
            }
141746×
            "author.signer" => {
1423×
                self.signer_key = if value.is_empty() {
1430×
                    None
144
                } else {
1453×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1460×
                        RepoError::Msg("author.signer must be a 64-character hex KeyId".into())
1470×
                    })?)
148
                }
149
            }
150743×
            "core.sign" => {
15183×
                self.sign_changes = match value {
15283×
                    "change" => true,
1537×
                    "seal" => false,
1540×
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
155
                }
156
            }
157660×
            "workspace.bookmark" => self.bookmark = value.into(),
158
            // Read by the credential store from the user file.
159656×
            "auth.helper" => {}
160656×
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
161644×
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
162644×
            "filter.max-blob" => {
1635×
                self.max_blob = if value.is_empty() {
1640×
                    None
165
                } else {
1665×
                    Some(parse_size(value)?)
167
                }
168
            }
169639×
            "storage.url" => {
1705×
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
171
            }
172634×
            "storage.cache" => {
1730×
                self.storage_cache = if value.is_empty() {
1740×
                    DEFAULT_STORAGE_CACHE
175
                } else {
1760×
                    parse_size(value)?
177
                }
178
            }
179634×
            "core.remote" => {
1801×
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
181
            }
182633×
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
183632×
            "git.claim" => self.git_claim = matches!(value, "true" | "1" | "yes"),
184630×
            "filter.paths" => {
1853×
                self.sparse_paths = value
1863×
                    .split(',')
1874×
                    .map(|p| {
1884×
                        p.trim()
1894×
                            .trim_start_matches("./")
1904×
                            .trim_matches('/')
1914×
                            .to_string()
1924×
                    })
1934×
                    .filter(|p| !p.is_empty())
1943×
                    .collect();
195
            }
196627×
            "core.checkpoint-interval" => {
1973×
                self.checkpoint_interval = value
1983×
                    .parse()
1993×
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
200
            }
201624×
            "push.batch-bytes" => {
2021×
                self.push_batch_bytes = value.parse().ok().filter(|n| *n > 0).ok_or_else(|| {
2030×
                    RepoError::Msg(format!("expected a number of bytes, got {value:?}"))
2040×
                })?;
205
            }
206623×
            k if k.starts_with("remote.") => {
207620×
                let rest = &k["remote.".len()..];
208620×
                let Some((name, field)) = rest.rsplit_once('.') else {
2090×
                    return fail(format!("unknown configuration key {key:?}"));
210
                };
211620×
                if name.is_empty() || name.contains('/') {
2120×
                    return fail(format!("invalid remote name in {key:?}"));
213620×
                }
214620×
                let map = match field {
215620×
                    "url" => &mut self.remotes,
21610×
                    "token" => &mut self.remote_tokens,
2174×
                    "ca" => &mut self.remote_cas,
2180×
                    _ => return fail(format!("unknown configuration key {key:?}")),
219
                };
220620×
                if value.is_empty() {
2212×
                    map.remove(name);
2222×
                    if field == "url" {
2232×
                        self.remote_tokens.remove(name);
2242×
                        self.remote_cas.remove(name);
2252×
                    }
226618×
                } else {
227618×
                    map.insert(name.to_string(), value.into());
228618×
                }
229
            }
2303×
            k if k.starts_with("revset.") => {
2313×
                let name = &k["revset.".len()..];
2323×
                if name.is_empty()
2333×
                    || !name
2343×
                        .chars()
23511×
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
236
                {
2370×
                    return fail(format!(
238
                        "a revset's name is letters, digits, _ and -: {key:?}"
239
                    ));
2403×
                }
2413×
                if value.is_empty() {
2420×
                    self.revsets.remove(name);
2430×
                } else {
2443×
                    crate::revset::parse(value)
2453×
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
2462×
                    self.revsets.insert(name.to_string(), value.into());
247
                }
248
            }
2490×
            _ => return fail(format!("unknown configuration key {key:?}")),
250
        }
2511485×
        Ok(())
2521486×
    }
253
254
    /// Defaults, then the user file if it exists, then the repository file.
2552521×
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
2562521×
        let mut c = Config::default_for_user();
2572521×
        if let Some(u) = user_path {
2582521×
            for (k, v) in read_config_file(u)? {
259294×
                let _ = c.apply(&k, &v);
260294×
            }
2610×
        }
2622521×
        for (k, v) in read_config_file(repo_path)? {
263652×
            if c.apply(&k, &v).is_ok() {
264652×
                c.repo_layer.insert(k, v);
265652×
            }
266
        }
2672521×
        Ok(c)
2682521×
    }
269
270847×
    pub(super) fn save(&self, path: &Path) -> Result<()> {
271847×
        write_config_file(path, &self.repo_layer)
272847×
    }
273
274
    /// Keys explicitly set for this repository.
27515×
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
27615×
        &self.repo_layer
27715×
    }
278
}
279
280
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
281
/// `storage.cache` when unset: 2 GiB.
282
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
283
2847×
pub fn parse_size(v: &str) -> Result<u64> {
2857×
    let v = v.trim();
2867×
    let (num, mult) = match v.chars().last() {
2871×
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
2881×
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
2890×
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
2905×
        _ => (v, 1),
291
    };
2927×
    let n: u64 = num
2937×
        .trim()
2947×
        .parse()
2957×
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
2966×
    Ok(n * mult)
2977×
}
298
299
/// A count of days, optionally suffixed `d`.
30012×
fn parse_days(v: &str) -> Result<u64> {
30112×
    v.trim_end_matches('d')
30212×
        .parse()
30312×
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
30412×
}
305
306
/// Read `key = "value"` lines; a missing file is empty.
3075575×
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
3085575×
    let text = match fs::read_to_string(path) {
3092193×
        Ok(t) => t,
3103382×
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
3110×
        Err(e) => return Err(e.into()),
312
    };
3132193×
    let mut out = BTreeMap::new();
3142193×
    for line in text.lines() {
3151150×
        let line = line.trim();
3161150×
        if line.is_empty() || line.starts_with('#') {
3170×
            continue;
3181150×
        }
3191150×
        let Some((k, v)) = line.split_once('=') else {
3200×
            continue;
321
        };
3221150×
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
323
    }
3242193×
    Ok(out)
3255575×
}
326
327937×
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
328937×
    let text: String = entries
329937×
        .iter()
330937×
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
331937×
        .collect();
332937×
    write_atomic(path, text.as_bytes())
333937×
}