OXYGENHUB

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

170 of 207 lines run, 34 of 52 functions · run #251 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.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
32
    pub op_retention_days: u64,
33
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
34
    pub gc_grace_days: u64,
35
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
36
    pub checkpoint_interval: u64,
37
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
38
    pub max_blob: Option<u64>,
39
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
40
    pub sparse_paths: Vec<String>,
41
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
42
    pub semantic_deps: bool,
43
    /// `revset.<name>`: a saved revset, used as `name()`.
44
    pub revsets: BTreeMap<String, String>,
45
    /// `storage.url`: the store the repository's objects and operation
46
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
47
    /// (oxygen#68).
48
    pub storage_url: Option<String>,
49
    /// `storage.cache`: the most the local cache in front of that store
50
    /// holds, in bytes.
51
    pub storage_cache: u64,
52
}
53
54
impl Config {
552494×
    pub(super) fn default_for_user() -> Config {
562494×
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
57
        Config {
582494×
            repo_layer: BTreeMap::new(),
592494×
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
602494×
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
612494×
                .unwrap_or_else(|_| format!("{user}@localhost")),
622494×
            author_key: None,
632494×
            signer_key: std::env::var("OXY_SIGNER")
642494×
                .ok()
652494×
                .and_then(|v| KeyId::from_hex(&v)),
66
            sign_changes: false,
672494×
            bookmark: "main".into(),
682494×
            remotes: BTreeMap::new(),
692494×
            remote_tokens: BTreeMap::new(),
702494×
            remote_cas: BTreeMap::new(),
71
            op_retention_days: 90,
72
            gc_grace_days: 14,
73
            checkpoint_interval: 256,
742494×
            max_blob: None,
752494×
            sparse_paths: Vec::new(),
76
            semantic_deps: false,
772494×
            revsets: BTreeMap::new(),
782494×
            storage_url: None,
79
            storage_cache: DEFAULT_STORAGE_CACHE,
80
        }
812494×
    }
82
83
    /// Set a key in the repository layer, as `oxy config` does.
84428×
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
85428×
        self.apply(key, value)?;
86428×
        if value.is_empty() {
871×
            self.repo_layer.remove(key);
88427×
        } else {
89427×
            self.repo_layer.insert(key.to_string(), value.to_string());
90427×
        }
91428×
        Ok(())
92428×
    }
93
94
    /// Set a key in the user file without touching any repository.
9591×
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
9691×
        Config::default_for_user().apply(key, value)?;
9790×
        let mut entries = read_config_file(user_path)?;
9890×
        if value.is_empty() {
990×
            entries.remove(key);
10090×
        } else {
10190×
            entries.insert(key.to_string(), value.to_string());
10290×
        }
10390×
        if let Some(parent) = user_path.parent() {
10490×
            fs::create_dir_all(parent)?;
1050×
        }
10690×
        write_config_file(user_path, &entries)
10791×
    }
108
109
    /// Apply a key to the effective values.
1101433×
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
1113×
        match key {
1121433×
            "author.name" => self.author_name = value.into(),
1131189×
            "author.email" => self.author_email = value.into(),
114945×
            "author.key" => {
115245×
                self.author_key = if value.is_empty() {
1160×
                    None
117
                } else {
118245×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1190×
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
1200×
                    })?)
121
                }
122
            }
123700×
            "author.signer" => {
1243×
                self.signer_key = if value.is_empty() {
1250×
                    None
126
                } else {
1273×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1280×
                        RepoError::Msg("author.signer must be a 64-character hex KeyId".into())
1290×
                    })?)
130
                }
131
            }
132697×
            "core.sign" => {
13383×
                self.sign_changes = match value {
13483×
                    "change" => true,
1357×
                    "seal" => false,
1360×
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
137
                }
138
            }
139614×
            "workspace.bookmark" => self.bookmark = value.into(),
140
            // Read by the credential store from the user file.
141610×
            "auth.helper" => {}
142610×
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
143598×
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
144598×
            "filter.max-blob" => {
1455×
                self.max_blob = if value.is_empty() {
1460×
                    None
147
                } else {
1485×
                    Some(parse_size(value)?)
149
                }
150
            }
151593×
            "storage.url" => {
1525×
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
153
            }
154588×
            "storage.cache" => {
1550×
                self.storage_cache = if value.is_empty() {
1560×
                    DEFAULT_STORAGE_CACHE
157
                } else {
1580×
                    parse_size(value)?
159
                }
160
            }
161588×
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
162587×
            "filter.paths" => {
1633×
                self.sparse_paths = value
1643×
                    .split(',')
1654×
                    .map(|p| {
1664×
                        p.trim()
1674×
                            .trim_start_matches("./")
1684×
                            .trim_matches('/')
1694×
                            .to_string()
1704×
                    })
1714×
                    .filter(|p| !p.is_empty())
1723×
                    .collect();
173
            }
174584×
            "core.checkpoint-interval" => {
1753×
                self.checkpoint_interval = value
1763×
                    .parse()
1773×
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
178
            }
179581×
            k if k.starts_with("remote.") => {
180578×
                let rest = &k["remote.".len()..];
181578×
                let Some((name, field)) = rest.rsplit_once('.') else {
1820×
                    return fail(format!("unknown configuration key {key:?}"));
183
                };
184578×
                if name.is_empty() || name.contains('/') {
1850×
                    return fail(format!("invalid remote name in {key:?}"));
186578×
                }
187578×
                let map = match field {
188578×
                    "url" => &mut self.remotes,
18910×
                    "token" => &mut self.remote_tokens,
1904×
                    "ca" => &mut self.remote_cas,
1910×
                    _ => return fail(format!("unknown configuration key {key:?}")),
192
                };
193578×
                if value.is_empty() {
1941×
                    map.remove(name);
1951×
                    if field == "url" {
1961×
                        self.remote_tokens.remove(name);
1971×
                        self.remote_cas.remove(name);
1981×
                    }
199577×
                } else {
200577×
                    map.insert(name.to_string(), value.into());
201577×
                }
202
            }
2033×
            k if k.starts_with("revset.") => {
2043×
                let name = &k["revset.".len()..];
2053×
                if name.is_empty()
2063×
                    || !name
2073×
                        .chars()
20811×
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
209
                {
2100×
                    return fail(format!(
211
                        "a revset's name is letters, digits, _ and -: {key:?}"
212
                    ));
2133×
                }
2143×
                if value.is_empty() {
2150×
                    self.revsets.remove(name);
2160×
                } else {
2173×
                    crate::revset::parse(value)
2183×
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
2192×
                    self.revsets.insert(name.to_string(), value.into());
220
                }
221
            }
2220×
            _ => return fail(format!("unknown configuration key {key:?}")),
223
        }
2241432×
        Ok(())
2251433×
    }
226
227
    /// Defaults, then the user file if it exists, then the repository file.
2282403×
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
2292403×
        let mut c = Config::default_for_user();
2302403×
        if let Some(u) = user_path {
2312403×
            for (k, v) in read_config_file(u)? {
232294×
                let _ = c.apply(&k, &v);
233294×
            }
2340×
        }
2352403×
        for (k, v) in read_config_file(repo_path)? {
236620×
            if c.apply(&k, &v).is_ok() {
237620×
                c.repo_layer.insert(k, v);
238620×
            }
239
        }
2402403×
        Ok(c)
2412403×
    }
242
243804×
    pub(super) fn save(&self, path: &Path) -> Result<()> {
244804×
        write_config_file(path, &self.repo_layer)
245804×
    }
246
247
    /// Keys explicitly set for this repository.
24815×
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
24915×
        &self.repo_layer
25015×
    }
251
}
252
253
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
254
/// `storage.cache` when unset: 2 GiB.
255
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
256
2577×
pub fn parse_size(v: &str) -> Result<u64> {
2587×
    let v = v.trim();
2597×
    let (num, mult) = match v.chars().last() {
2601×
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
2611×
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
2620×
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
2635×
        _ => (v, 1),
264
    };
2657×
    let n: u64 = num
2667×
        .trim()
2677×
        .parse()
2687×
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
2696×
    Ok(n * mult)
2707×
}
271
272
/// A count of days, optionally suffixed `d`.
27312×
fn parse_days(v: &str) -> Result<u64> {
27412×
    v.trim_end_matches('d')
27512×
        .parse()
27612×
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
27712×
}
278
279
/// Read `key = "value"` lines; a missing file is empty.
2805339×
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
2815339×
    let text = match fs::read_to_string(path) {
2822104×
        Ok(t) => t,
2833235×
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
2840×
        Err(e) => return Err(e.into()),
285
    };
2862104×
    let mut out = BTreeMap::new();
2872104×
    for line in text.lines() {
2881118×
        let line = line.trim();
2891118×
        if line.is_empty() || line.starts_with('#') {
2900×
            continue;
2911118×
        }
2921118×
        let Some((k, v)) = line.split_once('=') else {
2930×
            continue;
294
        };
2951118×
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
296
    }
2972104×
    Ok(out)
2985339×
}
299
300894×
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
301894×
    let text: String = entries
302894×
        .iter()
303894×
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
304894×
        .collect();
305894×
    write_atomic(path, text.as_bytes())
306894×
}