Skip to main content

jj_lib/
settings.rs

1// Copyright 2020 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![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    /// String matcher expression whether to track bookmarks automatically.
67    #[serde(default)]
68    pub auto_track_bookmarks: Option<String>,
69    /// String matcher expression whether to track locally-created bookmarks
70    /// automatically.
71    #[serde(default)]
72    pub auto_track_created_bookmarks: Option<String>,
73    /// Bookmark name expression to fetch by default.
74    #[serde(default)]
75    pub fetch_bookmarks: Option<String>,
76    /// Tag name expression to fetch by default.
77    #[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/// Commit signing settings, describes how to and if to sign commits.
93#[derive(Debug, Clone)]
94pub struct SignSettings {
95    /// What to actually do, see [SignBehavior].
96    pub behavior: SignBehavior,
97    /// The email address to compare against the commit author when determining
98    /// if the existing signature is "our own" in terms of the sign behavior.
99    pub user_email: String,
100    /// The signing backend specific key, to be passed to the signing backend.
101    pub key: Option<String>,
102}
103
104impl SignSettings {
105    /// Check if a commit should be signed according to the configured behavior
106    /// and email.
107    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    // Since toml_edit::Datetime isn't the date-time type used across our code
121    // base, we accept both string and date-time types.
122    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        // It's easier to re-parse the TOML date-time expression.
126        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    /// Like [`UserSettings::from_config()`], but retains the internal state.
171    ///
172    /// This ensures that no duplicated change IDs are generated within the
173    /// current process. New `debug.randomness-seed` value is ignored.
174    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    /// Returns low-level config object.
216    ///
217    /// You should typically use `settings.get_<type>()` methods instead.
218    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    // separate from sign_settings as those two are needed in pretty different
227    // places
228    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
242/// General-purpose accessors.
243impl UserSettings {
244    /// Looks up value of the specified type `T` by `name`.
245    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    /// Looks up string value by `name`.
253    pub fn get_string(&self, name: impl ToConfigNamePath) -> Result<String, ConfigGetError> {
254        self.get(name)
255    }
256
257    /// Looks up integer value by `name`.
258    pub fn get_int(&self, name: impl ToConfigNamePath) -> Result<i64, ConfigGetError> {
259        self.get(name)
260    }
261
262    /// Looks up boolean value by `name`.
263    pub fn get_bool(&self, name: impl ToConfigNamePath) -> Result<bool, ConfigGetError> {
264        self.get(name)
265    }
266
267    /// Looks up generic value by `name`.
268    pub fn get_value(&self, name: impl ToConfigNamePath) -> Result<ConfigValue, ConfigGetError> {
269        self.config.get_value(name)
270    }
271
272    /// Looks up value by `name`, converts it by using the given function.
273    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    /// Looks up sub table by `name`.
282    ///
283    /// Use `table_keys(prefix)` and `get([prefix, key])` instead if table
284    /// values have to be converted to non-generic value type.
285    pub fn get_table(&self, name: impl ToConfigNamePath) -> Result<ConfigTable, ConfigGetError> {
286        self.config.get_table(name)
287    }
288
289    /// Returns iterator over sub table keys at `name`.
290    pub fn table_keys(&self, name: impl ToConfigNamePath) -> impl Iterator<Item = &str> {
291        self.config.table_keys(name)
292    }
293}
294
295/// This Rng uses interior mutability to allow generating random values using an
296/// immutable reference. It also fixes a specific seedable RNG for
297/// reproducibility.
298#[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    /// Creates a new RNGs. Could be made public, but we'd like to encourage all
308    /// RNGs references to point to the same RNG.
309    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/// A size in bytes optionally formatted/serialized with binary prefixes
322#[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    // A string consisting only of base 10 digits is either a valid u64 or really
381    // huge.
382    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}