OXYGENHUB

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

186 of 222 lines run, 37 of 60 functions · run #263 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
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
35
    pub op_retention_days: u64,
36
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
37
    pub gc_grace_days: u64,
38
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
39
    pub checkpoint_interval: u64,
40
    /// `push.batch-bytes`: about how many bytes of changes and their texts
41
    /// one request of a long push carries (spec §16.3).
42
    pub push_batch_bytes: u64,
43
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
44
    pub max_blob: Option<u64>,
45
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
46
    pub sparse_paths: Vec<String>,
47
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
48
    pub semantic_deps: bool,
49
    /// `revset.<name>`: a saved revset, used as `name()`.
50
    pub revsets: BTreeMap<String, String>,
51
    /// `storage.url`: the store the repository's objects and operation
52
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
53
    /// (oxygen#68).
54
    pub storage_url: Option<String>,
55
    /// `storage.cache`: the most the local cache in front of that store
56
    /// holds, in bytes.
57
    pub storage_cache: u64,
58
}
59
60
impl Config {
61
    /// Whether the repository's own file sets `key` (as against the user
62
    /// config or a default).
632×
    pub fn is_repo_set(&self, key: &str) -> bool {
642×
        self.repo_layer.contains_key(key)
652×
    }
66
672625×
    pub(super) fn default_for_user() -> Config {
682625×
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
69
        Config {
702625×
            repo_layer: BTreeMap::new(),
712625×
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
722625×
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
732625×
                .unwrap_or_else(|_| format!("{user}@localhost")),
742625×
            author_key: None,
752625×
            signer_key: std::env::var("OXY_SIGNER")
762625×
                .ok()
772625×
                .and_then(|v| KeyId::from_hex(&v)),
78
            sign_changes: false,
792625×
            bookmark: "main".into(),
802625×
            remotes: BTreeMap::new(),
812625×
            remote_tokens: BTreeMap::new(),
822625×
            remote_cas: BTreeMap::new(),
832625×
            default_remote: None,
84
            op_retention_days: 90,
85
            gc_grace_days: 14,
86
            checkpoint_interval: 256,
872625×
            push_batch_bytes: 256 << 20,
882625×
            max_blob: None,
892625×
            sparse_paths: Vec::new(),
90
            semantic_deps: false,
912625×
            revsets: BTreeMap::new(),
922625×
            storage_url: None,
93
            storage_cache: DEFAULT_STORAGE_CACHE,
94
        }
952625×
    }
96
97
    /// Set a key in the repository layer, as `oxy config` does.
98448×
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
99448×
        self.apply(key, value)?;
100448×
        if value.is_empty() {
1012×
            self.repo_layer.remove(key);
102446×
        } else {
103446×
            self.repo_layer.insert(key.to_string(), value.to_string());
104446×
        }
105448×
        Ok(())
106448×
    }
107
108
    /// Set a key in the user file without touching any repository.
10991×
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
11091×
        Config::default_for_user().apply(key, value)?;
11190×
        let mut entries = read_config_file(user_path)?;
11290×
        if value.is_empty() {
1130×
            entries.remove(key);
11490×
        } else {
11590×
            entries.insert(key.to_string(), value.to_string());
11690×
        }
11790×
        if let Some(parent) = user_path.parent() {
11890×
            fs::create_dir_all(parent)?;
1190×
        }
12090×
        write_config_file(user_path, &entries)
12191×
    }
122
123
    /// Apply a key to the effective values.
1241481×
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
1253×
        match key {
1261481×
            "author.name" => self.author_name = value.into(),
1271237×
            "author.email" => self.author_email = value.into(),
128993×
            "author.key" => {
129246×
                self.author_key = if value.is_empty() {
1300×
                    None
131
                } else {
132246×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1330×
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
1340×
                    })?)
135
                }
136
            }
137747×
            "author.signer" => {
1383×
                self.signer_key = if value.is_empty() {
1390×
                    None
140
                } else {
1413×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1420×
                        RepoError::Msg("author.signer must be a 64-character hex KeyId".into())
1430×
                    })?)
144
                }
145
            }
146744×
            "core.sign" => {
14783×
                self.sign_changes = match value {
14883×
                    "change" => true,
1497×
                    "seal" => false,
1500×
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
151
                }
152
            }
153661×
            "workspace.bookmark" => self.bookmark = value.into(),
154
            // Read by the credential store from the user file.
155657×
            "auth.helper" => {}
156657×
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
157645×
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
158645×
            "filter.max-blob" => {
1595×
                self.max_blob = if value.is_empty() {
1600×
                    None
161
                } else {
1625×
                    Some(parse_size(value)?)
163
                }
164
            }
165640×
            "storage.url" => {
1665×
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
167
            }
168635×
            "storage.cache" => {
1690×
                self.storage_cache = if value.is_empty() {
1700×
                    DEFAULT_STORAGE_CACHE
171
                } else {
1720×
                    parse_size(value)?
173
                }
174
            }
175635×
            "core.remote" => {
1761×
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
177
            }
178634×
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
179633×
            "filter.paths" => {
1803×
                self.sparse_paths = value
1813×
                    .split(',')
1824×
                    .map(|p| {
1834×
                        p.trim()
1844×
                            .trim_start_matches("./")
1854×
                            .trim_matches('/')
1864×
                            .to_string()
1874×
                    })
1884×
                    .filter(|p| !p.is_empty())
1893×
                    .collect();
190
            }
191630×
            "core.checkpoint-interval" => {
1923×
                self.checkpoint_interval = value
1933×
                    .parse()
1943×
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
195
            }
196627×
            "push.batch-bytes" => {
1971×
                self.push_batch_bytes = value.parse().ok().filter(|n| *n > 0).ok_or_else(|| {
1980×
                    RepoError::Msg(format!("expected a number of bytes, got {value:?}"))
1990×
                })?;
200
            }
201626×
            k if k.starts_with("remote.") => {
202623×
                let rest = &k["remote.".len()..];
203623×
                let Some((name, field)) = rest.rsplit_once('.') else {
2040×
                    return fail(format!("unknown configuration key {key:?}"));
205
                };
206623×
                if name.is_empty() || name.contains('/') {
2070×
                    return fail(format!("invalid remote name in {key:?}"));
208623×
                }
209623×
                let map = match field {
210623×
                    "url" => &mut self.remotes,
21110×
                    "token" => &mut self.remote_tokens,
2124×
                    "ca" => &mut self.remote_cas,
2130×
                    _ => return fail(format!("unknown configuration key {key:?}")),
214
                };
215623×
                if value.is_empty() {
2162×
                    map.remove(name);
2172×
                    if field == "url" {
2182×
                        self.remote_tokens.remove(name);
2192×
                        self.remote_cas.remove(name);
2202×
                    }
221621×
                } else {
222621×
                    map.insert(name.to_string(), value.into());
223621×
                }
224
            }
2253×
            k if k.starts_with("revset.") => {
2263×
                let name = &k["revset.".len()..];
2273×
                if name.is_empty()
2283×
                    || !name
2293×
                        .chars()
23011×
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
231
                {
2320×
                    return fail(format!(
233
                        "a revset's name is letters, digits, _ and -: {key:?}"
234
                    ));
2353×
                }
2363×
                if value.is_empty() {
2370×
                    self.revsets.remove(name);
2380×
                } else {
2393×
                    crate::revset::parse(value)
2403×
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
2412×
                    self.revsets.insert(name.to_string(), value.into());
242
                }
243
            }
2440×
            _ => return fail(format!("unknown configuration key {key:?}")),
245
        }
2461480×
        Ok(())
2471481×
    }
248
249
    /// Defaults, then the user file if it exists, then the repository file.
2502534×
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
2512534×
        let mut c = Config::default_for_user();
2522534×
        if let Some(u) = user_path {
2532534×
            for (k, v) in read_config_file(u)? {
254294×
                let _ = c.apply(&k, &v);
255294×
            }
2560×
        }
2572534×
        for (k, v) in read_config_file(repo_path)? {
258648×
            if c.apply(&k, &v).is_ok() {
259648×
                c.repo_layer.insert(k, v);
260648×
            }
261
        }
2622534×
        Ok(c)
2632534×
    }
264
265850×
    pub(super) fn save(&self, path: &Path) -> Result<()> {
266850×
        write_config_file(path, &self.repo_layer)
267850×
    }
268
269
    /// Keys explicitly set for this repository.
27015×
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
27115×
        &self.repo_layer
27215×
    }
273
}
274
275
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
276
/// `storage.cache` when unset: 2 GiB.
277
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
278
2797×
pub fn parse_size(v: &str) -> Result<u64> {
2807×
    let v = v.trim();
2817×
    let (num, mult) = match v.chars().last() {
2821×
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
2831×
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
2840×
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
2855×
        _ => (v, 1),
286
    };
2877×
    let n: u64 = num
2887×
        .trim()
2897×
        .parse()
2907×
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
2916×
    Ok(n * mult)
2927×
}
293
294
/// A count of days, optionally suffixed `d`.
29512×
fn parse_days(v: &str) -> Result<u64> {
29612×
    v.trim_end_matches('d')
29712×
        .parse()
29812×
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
29912×
}
300
301
/// Read `key = "value"` lines; a missing file is empty.
3025601×
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
3035601×
    let text = match fs::read_to_string(path) {
3042204×
        Ok(t) => t,
3053397×
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
3060×
        Err(e) => return Err(e.into()),
307
    };
3082204×
    let mut out = BTreeMap::new();
3092204×
    for line in text.lines() {
3101146×
        let line = line.trim();
3111146×
        if line.is_empty() || line.starts_with('#') {
3120×
            continue;
3131146×
        }
3141146×
        let Some((k, v)) = line.split_once('=') else {
3150×
            continue;
316
        };
3171146×
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
318
    }
3192204×
    Ok(out)
3205601×
}
321
322940×
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
323940×
    let text: String = entries
324940×
        .iter()
325940×
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
326940×
        .collect();
327940×
    write_atomic(path, text.as_bytes())
328940×
}