OXYGENHUB

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

190 of 226 lines run, 38 of 60 functions · run #302 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.snapshot-retention`: days for which past operations keep their
42
    /// working copies reachable (oxygen#98); each workspace's current one is
43
    /// always kept. A file only ever in a working copy goes with it.
44
    pub snapshot_retention_days: u64,
45
    /// `snapshot.max-new-file-size`: a new, untracked file larger than this
46
    /// is left out of working-copy snapshots and named instead (oxygen#98);
47
    /// 0 takes in files of any size.
48
    pub max_new_file: u64,
49
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
50
    pub checkpoint_interval: u64,
51
    /// `push.batch-bytes`: about how many bytes of changes and their texts
52
    /// one request of a long push carries (spec §16.3).
53
    pub push_batch_bytes: u64,
54
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
55
    pub max_blob: Option<u64>,
56
    /// `filter.paths`: only these subtrees are materialized (spec §17); empty means everything.
57
    pub sparse_paths: Vec<String>,
58
    /// `hooks.semantic-deps`: run the semantic-deps hook at commit (spec §20).
59
    pub semantic_deps: bool,
60
    /// `revset.<name>`: a saved revset, used as `name()`.
61
    pub revsets: BTreeMap<String, String>,
62
    /// `storage.url`: the store the repository's objects and operation
63
    /// head are kept on (`dir://`, `s3://`, …) instead of `.oxy/objects`
64
    /// (oxygen#68).
65
    pub storage_url: Option<String>,
66
    /// `storage.cache`: the most the local cache in front of that store
67
    /// holds, in bytes.
68
    pub storage_cache: u64,
69
}
70
71
impl Config {
72
    /// Whether the repository's own file sets `key` (as against the user
73
    /// config or a default).
742×
    pub fn is_repo_set(&self, key: &str) -> bool {
752×
        self.repo_layer.contains_key(key)
762×
    }
77
782777×
    pub(super) fn default_for_user() -> Config {
792777×
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
80
        Config {
812777×
            repo_layer: BTreeMap::new(),
822777×
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
832777×
            author_email: std::env::var("OXY_AUTHOR_EMAIL")
842777×
                .unwrap_or_else(|_| format!("{user}@localhost")),
852777×
            author_key: None,
862777×
            signer_key: std::env::var("OXY_SIGNER")
872777×
                .ok()
882777×
                .and_then(|v| KeyId::from_hex(&v)),
89
            sign_changes: false,
902777×
            bookmark: "main".into(),
912777×
            remotes: BTreeMap::new(),
922777×
            remote_tokens: BTreeMap::new(),
932777×
            remote_cas: BTreeMap::new(),
942777×
            default_remote: None,
95
            git_claim: false,
96
            op_retention_days: 90,
97
            gc_grace_days: 14,
982777×
            max_new_file: 100 << 20,
99
            snapshot_retention_days: 7,
100
            checkpoint_interval: 256,
1012777×
            push_batch_bytes: 256 << 20,
1022777×
            max_blob: None,
1032777×
            sparse_paths: Vec::new(),
104
            semantic_deps: false,
1052777×
            revsets: BTreeMap::new(),
1062777×
            storage_url: None,
107
            storage_cache: DEFAULT_STORAGE_CACHE,
108
        }
1092777×
    }
110
111
    /// Set a key in the repository layer, as `oxy config` does.
112476×
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
113476×
        self.apply(key, value)?;
114476×
        if value.is_empty() {
1154×
            self.repo_layer.remove(key);
116472×
        } else {
117472×
            self.repo_layer.insert(key.to_string(), value.to_string());
118472×
        }
119476×
        Ok(())
120476×
    }
121
122
    /// Set a key in the user file without touching any repository.
123101×
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
124101×
        Config::default_for_user().apply(key, value)?;
125100×
        let mut entries = read_config_file(user_path)?;
126100×
        if value.is_empty() {
1270×
            entries.remove(key);
128100×
        } else {
129100×
            entries.insert(key.to_string(), value.to_string());
130100×
        }
131100×
        if let Some(parent) = user_path.parent() {
132100×
            fs::create_dir_all(parent)?;
1330×
        }
134100×
        write_config_file(user_path, &entries)
135101×
    }
136
137
    /// Apply a key to the effective values.
1381575×
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
1393×
        match key {
1401575×
            "author.name" => self.author_name = value.into(),
1411312×
            "author.email" => self.author_email = value.into(),
1421049×
            "author.key" => {
143265×
                self.author_key = if value.is_empty() {
1440×
                    None
145
                } else {
146265×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1470×
                        RepoError::Msg("author.key must be a 64-character hex KeyId".into())
1480×
                    })?)
149
                }
150
            }
151784×
            "author.signer" => {
1525×
                self.signer_key = if value.is_empty() {
1530×
                    None
154
                } else {
1555×
                    Some(KeyId::from_hex(value).ok_or_else(|| {
1560×
                        RepoError::Msg("author.signer must be a 64-character hex KeyId".into())
1570×
                    })?)
158
                }
159
            }
160779×
            "core.sign" => {
16187×
                self.sign_changes = match value {
16287×
                    "change" => true,
1637×
                    "seal" => false,
1640×
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
165
                }
166
            }
167692×
            "workspace.bookmark" => self.bookmark = value.into(),
168
            // Read by the credential store from the user file.
169688×
            "auth.helper" => {}
170688×
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
171676×
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
172676×
            "snapshot.max-new-file-size" => self.max_new_file = parse_size(value)?,
173676×
            "core.snapshot-retention" => self.snapshot_retention_days = parse_days(value)?,
174676×
            "filter.max-blob" => {
1755×
                self.max_blob = if value.is_empty() {
1760×
                    None
177
                } else {
1785×
                    Some(parse_size(value)?)
179
                }
180
            }
181671×
            "storage.url" => {
1825×
                self.storage_url = (!value.is_empty()).then(|| value.to_string());
183
            }
184666×
            "storage.cache" => {
1850×
                self.storage_cache = if value.is_empty() {
1860×
                    DEFAULT_STORAGE_CACHE
187
                } else {
1880×
                    parse_size(value)?
189
                }
190
            }
191666×
            "core.remote" => {
1921×
                self.default_remote = (!value.is_empty()).then(|| value.to_string());
193
            }
194665×
            "hooks.semantic-deps" => self.semantic_deps = matches!(value, "true" | "1" | "yes"),
195664×
            "git.claim" => self.git_claim = matches!(value, "true" | "1" | "yes"),
196662×
            "filter.paths" => {
1973×
                self.sparse_paths = value
1983×
                    .split(',')
1994×
                    .map(|p| {
2004×
                        p.trim()
2014×
                            .trim_start_matches("./")
2024×
                            .trim_matches('/')
2034×
                            .to_string()
2044×
                    })
2054×
                    .filter(|p| !p.is_empty())
2063×
                    .collect();
207
            }
208659×
            "core.checkpoint-interval" => {
2093×
                self.checkpoint_interval = value
2103×
                    .parse()
2113×
                    .map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
212
            }
213656×
            "push.batch-bytes" => {
2141×
                self.push_batch_bytes = value.parse().ok().filter(|n| *n > 0).ok_or_else(|| {
2150×
                    RepoError::Msg(format!("expected a number of bytes, got {value:?}"))
2160×
                })?;
217
            }
218655×
            k if k.starts_with("remote.") => {
219652×
                let rest = &k["remote.".len()..];
220652×
                let Some((name, field)) = rest.rsplit_once('.') else {
2210×
                    return fail(format!("unknown configuration key {key:?}"));
222
                };
223652×
                if name.is_empty() || name.contains('/') {
2240×
                    return fail(format!("invalid remote name in {key:?}"));
225652×
                }
226652×
                let map = match field {
227652×
                    "url" => &mut self.remotes,
22814×
                    "token" => &mut self.remote_tokens,
2294×
                    "ca" => &mut self.remote_cas,
2300×
                    _ => return fail(format!("unknown configuration key {key:?}")),
231
                };
232652×
                if value.is_empty() {
2334×
                    map.remove(name);
2344×
                    if field == "url" {
2353×
                        self.remote_tokens.remove(name);
2363×
                        self.remote_cas.remove(name);
2373×
                    }
238648×
                } else {
239648×
                    map.insert(name.to_string(), value.into());
240648×
                }
241
            }
2423×
            k if k.starts_with("revset.") => {
2433×
                let name = &k["revset.".len()..];
2443×
                if name.is_empty()
2453×
                    || !name
2463×
                        .chars()
24711×
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
248
                {
2490×
                    return fail(format!(
250
                        "a revset's name is letters, digits, _ and -: {key:?}"
251
                    ));
2523×
                }
2533×
                if value.is_empty() {
2540×
                    self.revsets.remove(name);
2550×
                } else {
2563×
                    crate::revset::parse(value)
2573×
                        .map_err(|e| RepoError::Msg(format!("{key} = {value:?}: {e}")))?;
2582×
                    self.revsets.insert(name.to_string(), value.into());
259
                }
260
            }
2610×
            _ => return fail(format!("unknown configuration key {key:?}")),
262
        }
2631574×
        Ok(())
2641575×
    }
265
266
    /// Defaults, then the user file if it exists, then the repository file.
2672676×
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
2682676×
        let mut c = Config::default_for_user();
2692676×
        if let Some(u) = user_path {
2702676×
            for (k, v) in read_config_file(u)? {
271322×
                let _ = c.apply(&k, &v);
272322×
            }
2730×
        }
2742676×
        for (k, v) in read_config_file(repo_path)? {
275676×
            if c.apply(&k, &v).is_ok() {
276676×
                c.repo_layer.insert(k, v);
277676×
            }
278
        }
2792676×
        Ok(c)
2802676×
    }
281
282897×
    pub(super) fn save(&self, path: &Path) -> Result<()> {
283897×
        write_config_file(path, &self.repo_layer)
284897×
    }
285
286
    /// Keys explicitly set for this repository.
28720×
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
28820×
        &self.repo_layer
28920×
    }
290
}
291
292
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
293
/// `storage.cache` when unset: 2 GiB.
294
pub const DEFAULT_STORAGE_CACHE: u64 = 2 << 30;
295
2967×
pub fn parse_size(v: &str) -> Result<u64> {
2977×
    let v = v.trim();
2987×
    let (num, mult) = match v.chars().last() {
2991×
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
3001×
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
3010×
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
3025×
        _ => (v, 1),
303
    };
3047×
    let n: u64 = num
3057×
        .trim()
3067×
        .parse()
3077×
        .map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
3086×
    Ok(n * mult)
3097×
}
310
311
/// A count of days, optionally suffixed `d`.
31212×
fn parse_days(v: &str) -> Result<u64> {
31312×
    v.trim_end_matches('d')
31412×
        .parse()
31512×
        .map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
31612×
}
317
318
/// Read `key = "value"` lines; a missing file is empty.
3195946×
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
3205946×
    let text = match fs::read_to_string(path) {
3212340×
        Ok(t) => t,
3223606×
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
3230×
        Err(e) => return Err(e.into()),
324
    };
3252340×
    let mut out = BTreeMap::new();
3262340×
    for line in text.lines() {
3271233×
        let line = line.trim();
3281233×
        if line.is_empty() || line.starts_with('#') {
3290×
            continue;
3301233×
        }
3311233×
        let Some((k, v)) = line.split_once('=') else {
3320×
            continue;
333
        };
3341233×
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
335
    }
3362340×
    Ok(out)
3375946×
}
338
339997×
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
340997×
    let text: String = entries
341997×
        .iter()
342997×
        .map(|(k, v)| format!("{k} = \"{v}\"\n"))
343997×
        .collect();
344997×
    write_atomic(path, text.as_bytes())
345997×
}