OXYGENHUB
# b3c5a59a875a oxygen / crates / oxy-core / src / repo / config.rs
8.2 KiB · Rust · last changed Lazy blobs: clone --max-blob / filter.max-blob, absent-blob registry fetched on first read, objects endpoint (spec 0.6e) 1 month ago source blame history raw
98286406 Andy McCall ↶ 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
    /// `core.sign`: sign every change at commit (`true`) or leave signing to
17
    /// push-time seals (`false`, the spec default).
18
    pub sign_changes: bool,
19
    pub bookmark: String,
20
    /// `remote.<name>.url`.
21
    pub remotes: BTreeMap<String, String>,
22
    /// `remote.<name>.token`: bearer token for HTTP pushes.
23
    pub remote_tokens: BTreeMap<String, String>,
2b5ee371 Andy McCall ↶ 24
    /// `remote.<name>.ca`: PEM file of extra roots to trust for that remote.
25
    pub remote_cas: BTreeMap<String, String>,
ba160f60 Andy McCall ↶ 26
    /// `core.op-retention`: days for which operations keep their states reachable (spec §12.1, §21).
27
    pub op_retention_days: u64,
28
    /// `core.gc-grace`: days an unreachable object survives, protecting concurrent writers (spec §21).
29
    pub gc_grace_days: u64,
252e8cb2 Andy McCall ↶ 30
    /// `core.checkpoint-interval`: changes between automatic checkpoints (spec §11).
31
    pub checkpoint_interval: u64,
b3c5a59a Andy McCall ↶ 32
    /// `filter.max-blob`: blobs larger than this many bytes are fetched lazily (spec §17).
33
    pub max_blob: Option<u64>,
98286406 Andy McCall ↶ 34
}
35
36
impl Config {
37
    pub(super) fn default_for_user() -> Config {
38
        let user = std::env::var("USER").unwrap_or_else(|_| "unknown".into());
39
        Config {
40
            repo_layer: BTreeMap::new(),
41
            author_name: std::env::var("OXY_AUTHOR_NAME").unwrap_or_else(|_| user.clone()),
42
            author_email: std::env::var("OXY_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{user}@localhost")),
43
            author_key: None,
44
            sign_changes: false,
45
            bookmark: "main".into(),
46
            remotes: BTreeMap::new(),
47
            remote_tokens: BTreeMap::new(),
2b5ee371 Andy McCall ↶ 48
            remote_cas: BTreeMap::new(),
ba160f60 Andy McCall ↶ 49
            op_retention_days: 90,
50
            gc_grace_days: 14,
252e8cb2 Andy McCall ↶ 51
            checkpoint_interval: 256,
b3c5a59a Andy McCall ↶ 52
            max_blob: None,
98286406 Andy McCall ↶ 53
        }
54
    }
55
56
    /// Set a key in the repository layer, as `oxy config` does.
57
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
58
        self.apply(key, value)?;
59
        if value.is_empty() {
60
            self.repo_layer.remove(key);
61
        } else {
62
            self.repo_layer.insert(key.to_string(), value.to_string());
63
        }
64
        Ok(())
65
    }
66
67
    /// Set a key in the user file without touching any repository.
68
    pub fn set_user(user_path: &Path, key: &str, value: &str) -> Result<()> {
69
        Config::default_for_user().apply(key, value)?;
70
        let mut entries = read_config_file(user_path)?;
71
        if value.is_empty() {
72
            entries.remove(key);
73
        } else {
74
            entries.insert(key.to_string(), value.to_string());
75
        }
76
        if let Some(parent) = user_path.parent() {
77
            fs::create_dir_all(parent)?;
78
        }
79
        write_config_file(user_path, &entries)
80
    }
81
82
    /// Apply a key to the effective values.
83
    pub(super) fn apply(&mut self, key: &str, value: &str) -> Result<()> {
84
        match key {
85
            "author.name" => self.author_name = value.into(),
86
            "author.email" => self.author_email = value.into(),
87
            "author.key" => {
88
                self.author_key = if value.is_empty() {
89
                    None
90
                } else {
91
                    Some(KeyId::from_hex(value).ok_or_else(|| RepoError::Msg("author.key must be a 64-character hex KeyId".into()))?)
92
                }
93
            }
94
            "core.sign" => {
95
                self.sign_changes = match value {
96
                    "change" => true,
97
                    "seal" => false,
98
                    _ => return fail("core.sign must be \"change\" or \"seal\""),
99
                }
100
            }
101
            "workspace.bookmark" => self.bookmark = value.into(),
ba160f60 Andy McCall ↶ 102
            "core.op-retention" => self.op_retention_days = parse_days(value)?,
103
            "core.gc-grace" => self.gc_grace_days = parse_days(value)?,
b3c5a59a Andy McCall ↶ 104
            "filter.max-blob" => self.max_blob = if value.is_empty() { None } else { Some(parse_size(value)?) },
252e8cb2 Andy McCall ↶ 105
            "core.checkpoint-interval" => {
106
                self.checkpoint_interval = value.parse().map_err(|_| RepoError::Msg(format!("expected a number, got {value:?}")))?;
107
            }
2b5ee371 Andy McCall ↶ 108
            k if k.starts_with("remote.") => {
109
                let rest = &k["remote.".len()..];
110
                let Some((name, field)) = rest.rsplit_once('.') else {
111
                    return fail(format!("unknown configuration key {key:?}"));
98286406 Andy McCall ↶ 112
                };
113
                if name.is_empty() || name.contains('/') {
114
                    return fail(format!("invalid remote name in {key:?}"));
115
                }
2b5ee371 Andy McCall ↶ 116
                let map = match field {
117
                    "url" => &mut self.remotes,
118
                    "token" => &mut self.remote_tokens,
119
                    "ca" => &mut self.remote_cas,
120
                    _ => return fail(format!("unknown configuration key {key:?}")),
121
                };
98286406 Andy McCall ↶ 122
                if value.is_empty() {
123
                    map.remove(name);
2b5ee371 Andy McCall ↶ 124
                    if field == "url" {
98286406 Andy McCall ↶ 125
                        self.remote_tokens.remove(name);
2b5ee371 Andy McCall ↶ 126
                        self.remote_cas.remove(name);
98286406 Andy McCall ↶ 127
                    }
128
                } else {
129
                    map.insert(name.to_string(), value.into());
130
                }
131
            }
132
            _ => return fail(format!("unknown configuration key {key:?}")),
133
        }
134
        Ok(())
135
    }
136
137
    /// Defaults, then the user file if it exists, then the repository file.
138
    pub(super) fn load(user_path: Option<&Path>, repo_path: &Path) -> Result<Config> {
139
        let mut c = Config::default_for_user();
140
        if let Some(u) = user_path {
141
            for (k, v) in read_config_file(u)? {
142
                let _ = c.apply(&k, &v);
143
            }
144
        }
145
        for (k, v) in read_config_file(repo_path)? {
146
            if c.apply(&k, &v).is_ok() {
147
                c.repo_layer.insert(k, v);
148
            }
149
        }
150
        Ok(c)
151
    }
152
153
    pub(super) fn save(&self, path: &Path) -> Result<()> {
154
        write_config_file(path, &self.repo_layer)
155
    }
156
157
    /// Keys explicitly set for this repository.
158
    pub fn repo_layer(&self) -> &BTreeMap<String, String> {
159
        &self.repo_layer
160
    }
161
}
162
b3c5a59a Andy McCall ↶ 163
/// A byte count with an optional `K`, `M`, or `G` suffix (binary units).
164
pub fn parse_size(v: &str) -> Result<u64> {
165
    let v = v.trim();
166
    let (num, mult) = match v.chars().last() {
167
        Some('K' | 'k') => (&v[..v.len() - 1], 1u64 << 10),
168
        Some('M' | 'm') => (&v[..v.len() - 1], 1u64 << 20),
169
        Some('G' | 'g') => (&v[..v.len() - 1], 1u64 << 30),
170
        _ => (v, 1),
171
    };
172
    let n: u64 = num.trim().parse().map_err(|_| RepoError::Msg(format!("expected a size like 1M, got {v:?}")))?;
173
    Ok(n * mult)
174
}
175
ba160f60 Andy McCall ↶ 176
/// A count of days, optionally suffixed `d`.
177
fn parse_days(v: &str) -> Result<u64> {
178
    v.trim_end_matches('d').parse().map_err(|_| RepoError::Msg(format!("expected a number of days, got {v:?}")))
179
}
180
98286406 Andy McCall ↶ 181
/// Read `key = "value"` lines; a missing file is empty.
182
pub fn read_config_file(path: &Path) -> Result<BTreeMap<String, String>> {
183
    let text = match fs::read_to_string(path) {
184
        Ok(t) => t,
185
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
186
        Err(e) => return Err(e.into()),
187
    };
188
    let mut out = BTreeMap::new();
189
    for line in text.lines() {
190
        let line = line.trim();
191
        if line.is_empty() || line.starts_with('#') {
192
            continue;
193
        }
194
        let Some((k, v)) = line.split_once('=') else { continue };
195
        out.insert(k.trim().to_string(), v.trim().trim_matches('"').to_string());
196
    }
197
    Ok(out)
198
}
199
200
fn write_config_file(path: &Path, entries: &BTreeMap<String, String>) -> Result<()> {
201
    let text: String = entries.iter().map(|(k, v)| format!("{k} = \"{v}\"\n")).collect();
202
    write_atomic(path, text.as_bytes())
203
}
204