1#![expect(missing_docs)]
16
17use std::collections::HashMap;
18use std::str::FromStr;
19use std::sync::Arc;
20use std::sync::Mutex;
21
22use chrono::DateTime;
23use itertools::Itertools as _;
24use rand::prelude::*;
25use rand_chacha::ChaCha20Rng;
26use serde::Deserialize;
27
28use crate::backend::ChangeId;
29use crate::backend::Commit;
30use crate::backend::Signature;
31use crate::backend::Timestamp;
32use crate::config::ConfigGetError;
33use crate::config::ConfigGetResultExt as _;
34use crate::config::ConfigTable;
35use crate::config::ConfigValue;
36use crate::config::StackedConfig;
37use crate::config::ToConfigNamePath;
38use crate::fmt_util::binary_prefix;
39use crate::ref_name::RemoteNameBuf;
40use crate::signing::SignBehavior;
41
42#[derive(Debug, Clone)]
43pub struct UserSettings {
44 config: Arc<StackedConfig>,
45 data: Arc<UserSettingsData>,
46 rng: Arc<JJRng>,
47}
48
49#[derive(Debug)]
50struct UserSettingsData {
51 user_name: String,
52 user_email: String,
53 commit_timestamp: Option<Timestamp>,
54 operation_timestamp: Option<Timestamp>,
55 operation_hostname: String,
56 operation_username: String,
57 signing_behavior: SignBehavior,
58 signing_key: Option<String>,
59}
60
61pub type RemoteSettingsMap = HashMap<RemoteNameBuf, RemoteSettings>;
62
63#[derive(Debug, Clone, serde::Deserialize)]
64#[serde(rename_all = "kebab-case")]
65pub struct RemoteSettings {
66 #[serde(default)]
68 pub auto_track_bookmarks: Option<String>,
69 #[serde(default)]
72 pub auto_track_created_bookmarks: Option<String>,
73 #[serde(default)]
75 pub fetch_bookmarks: Option<String>,
76 #[serde(default)]
78 pub fetch_tags: Option<String>,
79}
80
81impl RemoteSettings {
82 pub fn table_from_settings(
83 settings: &UserSettings,
84 ) -> Result<RemoteSettingsMap, ConfigGetError> {
85 settings
86 .table_keys("remotes")
87 .map(|name| Ok((name.into(), settings.get(["remotes", name])?)))
88 .try_collect()
89 }
90}
91
92#[derive(Debug, Clone)]
94pub struct SignSettings {
95 pub behavior: SignBehavior,
97 pub user_email: String,
100 pub key: Option<String>,
102}
103
104impl SignSettings {
105 pub fn should_sign(&self, commit: &Commit) -> bool {
108 match self.behavior {
109 SignBehavior::Drop => false,
110 SignBehavior::Keep => {
111 commit.secure_sig.is_some() && commit.author.email == self.user_email
112 }
113 SignBehavior::Own => commit.author.email == self.user_email,
114 SignBehavior::Force => true,
115 }
116 }
117}
118
119fn to_timestamp(value: ConfigValue) -> Result<Timestamp, Box<dyn std::error::Error + Send + Sync>> {
120 if let Some(s) = value.as_str() {
123 Ok(Timestamp::from_datetime(DateTime::parse_from_rfc3339(s)?))
124 } else if let Some(d) = value.as_datetime() {
125 let s = d.to_string();
127 Ok(Timestamp::from_datetime(DateTime::parse_from_rfc3339(&s)?))
128 } else {
129 let ty = value.type_name();
130 Err(format!("invalid type: {ty}, expected a date-time").into())
131 }
132}
133
134impl UserSettings {
135 pub fn from_config(config: StackedConfig) -> Result<Self, ConfigGetError> {
136 let rng_seed = config.get::<u64>("debug.randomness-seed").optional()?;
137 Self::from_config_and_rng(config, Arc::new(JJRng::new(rng_seed)))
138 }
139
140 fn from_config_and_rng(config: StackedConfig, rng: Arc<JJRng>) -> Result<Self, ConfigGetError> {
141 let user_name = config.get("user.name")?;
142 let user_email = config.get("user.email")?;
143 let commit_timestamp = config
144 .get_value_with("debug.commit-timestamp", to_timestamp)
145 .optional()?;
146 let operation_timestamp = config
147 .get_value_with("debug.operation-timestamp", to_timestamp)
148 .optional()?;
149 let operation_hostname = config.get("operation.hostname")?;
150 let operation_username = config.get("operation.username")?;
151 let signing_behavior = config.get("signing.behavior")?;
152 let signing_key = config.get("signing.key").optional()?;
153 let data = UserSettingsData {
154 user_name,
155 user_email,
156 commit_timestamp,
157 operation_timestamp,
158 operation_hostname,
159 operation_username,
160 signing_behavior,
161 signing_key,
162 };
163 Ok(Self {
164 config: Arc::new(config),
165 data: Arc::new(data),
166 rng,
167 })
168 }
169
170 pub fn with_new_config(&self, config: StackedConfig) -> Result<Self, ConfigGetError> {
175 Self::from_config_and_rng(config, self.rng.clone())
176 }
177
178 pub fn get_rng(&self) -> Arc<JJRng> {
179 self.rng.clone()
180 }
181
182 pub fn user_name(&self) -> &str {
183 &self.data.user_name
184 }
185
186 pub fn user_email(&self) -> &str {
187 &self.data.user_email
188 }
189
190 pub fn commit_timestamp(&self) -> Option<Timestamp> {
191 self.data.commit_timestamp
192 }
193
194 pub fn operation_timestamp(&self) -> Option<Timestamp> {
195 self.data.operation_timestamp
196 }
197
198 pub fn operation_hostname(&self) -> &str {
199 &self.data.operation_hostname
200 }
201
202 pub fn operation_username(&self) -> &str {
203 &self.data.operation_username
204 }
205
206 pub fn signature(&self) -> Signature {
207 let timestamp = self.data.commit_timestamp.unwrap_or_else(Timestamp::now);
208 Signature {
209 name: self.user_name().to_owned(),
210 email: self.user_email().to_owned(),
211 timestamp,
212 }
213 }
214
215 pub fn config(&self) -> &StackedConfig {
219 &self.config
220 }
221
222 pub fn remote_settings(&self) -> Result<RemoteSettingsMap, ConfigGetError> {
223 RemoteSettings::table_from_settings(self)
224 }
225
226 pub fn signing_backend(&self) -> Result<Option<String>, ConfigGetError> {
229 let backend = self.get_string("signing.backend")?;
230 Ok((backend != "none").then_some(backend))
231 }
232
233 pub fn sign_settings(&self) -> SignSettings {
234 SignSettings {
235 behavior: self.data.signing_behavior,
236 user_email: self.data.user_email.clone(),
237 key: self.data.signing_key.clone(),
238 }
239 }
240}
241
242impl UserSettings {
244 pub fn get<'de, T: Deserialize<'de>>(
246 &self,
247 name: impl ToConfigNamePath,
248 ) -> Result<T, ConfigGetError> {
249 self.config.get(name)
250 }
251
252 pub fn get_string(&self, name: impl ToConfigNamePath) -> Result<String, ConfigGetError> {
254 self.get(name)
255 }
256
257 pub fn get_int(&self, name: impl ToConfigNamePath) -> Result<i64, ConfigGetError> {
259 self.get(name)
260 }
261
262 pub fn get_bool(&self, name: impl ToConfigNamePath) -> Result<bool, ConfigGetError> {
264 self.get(name)
265 }
266
267 pub fn get_value(&self, name: impl ToConfigNamePath) -> Result<ConfigValue, ConfigGetError> {
269 self.config.get_value(name)
270 }
271
272 pub fn get_value_with<T, E: Into<Box<dyn std::error::Error + Send + Sync>>>(
274 &self,
275 name: impl ToConfigNamePath,
276 convert: impl FnOnce(ConfigValue) -> Result<T, E>,
277 ) -> Result<T, ConfigGetError> {
278 self.config.get_value_with(name, convert)
279 }
280
281 pub fn get_table(&self, name: impl ToConfigNamePath) -> Result<ConfigTable, ConfigGetError> {
286 self.config.get_table(name)
287 }
288
289 pub fn table_keys(&self, name: impl ToConfigNamePath) -> impl Iterator<Item = &str> {
291 self.config.table_keys(name)
292 }
293}
294
295#[derive(Debug)]
299pub struct JJRng(Mutex<ChaCha20Rng>);
300impl JJRng {
301 pub fn new_change_id(&self, length: usize) -> ChangeId {
302 let mut rng = self.0.lock().unwrap();
303 let random_bytes = (0..length).map(|_| rng.random::<u8>()).collect();
304 ChangeId::new(random_bytes)
305 }
306
307 fn new(seed: Option<u64>) -> Self {
310 Self(Mutex::new(Self::internal_rng_from_seed(seed)))
311 }
312
313 fn internal_rng_from_seed(seed: Option<u64>) -> ChaCha20Rng {
314 match seed {
315 Some(seed) => ChaCha20Rng::seed_from_u64(seed),
316 None => rand::make_rng(),
317 }
318 }
319}
320
321#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
323pub struct HumanByteSize(pub u64);
324
325impl std::fmt::Display for HumanByteSize {
326 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327 let (value, prefix) = binary_prefix(self.0 as f32);
328 write!(f, "{value:.1}{prefix}B")
329 }
330}
331
332impl FromStr for HumanByteSize {
333 type Err = &'static str;
334
335 fn from_str(s: &str) -> Result<Self, Self::Err> {
336 match s.parse() {
337 Ok(bytes) => Ok(Self(bytes)),
338 Err(_) => {
339 let bytes = parse_human_byte_size(s)?;
340 Ok(Self(bytes))
341 }
342 }
343 }
344}
345
346impl TryFrom<ConfigValue> for HumanByteSize {
347 type Error = &'static str;
348
349 fn try_from(value: ConfigValue) -> Result<Self, Self::Error> {
350 if let Some(n) = value.as_integer() {
351 let n = u64::try_from(n).map_err(|_| "Integer out of range")?;
352 Ok(Self(n))
353 } else if let Some(s) = value.as_str() {
354 s.parse()
355 } else {
356 Err("Expected a positive integer or a string in '<number><unit>' form")
357 }
358 }
359}
360
361fn parse_human_byte_size(v: &str) -> Result<u64, &'static str> {
362 let digit_end = v.find(|c: char| !c.is_ascii_digit()).unwrap_or(v.len());
363 if digit_end == 0 {
364 return Err("must start with a number");
365 }
366 let (digits, trailing) = v.split_at(digit_end);
367 let exponent = match trailing.trim_start() {
368 "" | "B" => 0,
369 unit => {
370 const PREFIXES: [char; 8] = ['K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
371 let Some(prefix) = PREFIXES.iter().position(|&x| unit.starts_with(x)) else {
372 return Err("unrecognized unit prefix");
373 };
374 let ("" | "B" | "i" | "iB") = &unit[1..] else {
375 return Err("unrecognized unit");
376 };
377 prefix as u32 + 1
378 }
379 };
380 let factor = digits.parse::<u64>().unwrap_or(u64::MAX);
383 Ok(factor.saturating_mul(1024u64.saturating_pow(exponent)))
384}
385
386#[cfg(test)]
387mod tests {
388 use assert_matches::assert_matches;
389
390 use super::*;
391
392 #[test]
393 fn byte_size_parse() {
394 assert_eq!(parse_human_byte_size("0"), Ok(0));
395 assert_eq!(parse_human_byte_size("42"), Ok(42));
396 assert_eq!(parse_human_byte_size("42B"), Ok(42));
397 assert_eq!(parse_human_byte_size("42 B"), Ok(42));
398 assert_eq!(parse_human_byte_size("42K"), Ok(42 * 1024));
399 assert_eq!(parse_human_byte_size("42 K"), Ok(42 * 1024));
400 assert_eq!(parse_human_byte_size("42 KB"), Ok(42 * 1024));
401 assert_eq!(parse_human_byte_size("42 KiB"), Ok(42 * 1024));
402 assert_eq!(
403 parse_human_byte_size("42 LiB"),
404 Err("unrecognized unit prefix")
405 );
406 assert_eq!(parse_human_byte_size("42 KiC"), Err("unrecognized unit"));
407 assert_eq!(parse_human_byte_size("42 KC"), Err("unrecognized unit"));
408 assert_eq!(
409 parse_human_byte_size("KiB"),
410 Err("must start with a number")
411 );
412 assert_eq!(parse_human_byte_size(""), Err("must start with a number"));
413 }
414
415 #[test]
416 fn byte_size_from_config_value() {
417 assert_eq!(
418 HumanByteSize::try_from(ConfigValue::from(42)).unwrap(),
419 HumanByteSize(42)
420 );
421 assert_eq!(
422 HumanByteSize::try_from(ConfigValue::from("42K")).unwrap(),
423 HumanByteSize(42 * 1024)
424 );
425 assert_matches!(
426 HumanByteSize::try_from(ConfigValue::from(-1)),
427 Err("Integer out of range")
428 );
429 }
430}