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}
70
71impl RemoteSettings {
72    pub fn table_from_settings(
73        settings: &UserSettings,
74    ) -> Result<RemoteSettingsMap, ConfigGetError> {
75        settings
76            .table_keys("remotes")
77            .map(|name| Ok((name.into(), settings.get(["remotes", name])?)))
78            .try_collect()
79    }
80}
81
82/// Commit signing settings, describes how to and if to sign commits.
83#[derive(Debug, Clone)]
84pub struct SignSettings {
85    /// What to actually do, see [SignBehavior].
86    pub behavior: SignBehavior,
87    /// The email address to compare against the commit author when determining
88    /// if the existing signature is "our own" in terms of the sign behavior.
89    pub user_email: String,
90    /// The signing backend specific key, to be passed to the signing backend.
91    pub key: Option<String>,
92}
93
94impl SignSettings {
95    /// Check if a commit should be signed according to the configured behavior
96    /// and email.
97    pub fn should_sign(&self, commit: &Commit) -> bool {
98        match self.behavior {
99            SignBehavior::Drop => false,
100            SignBehavior::Keep => {
101                commit.secure_sig.is_some() && commit.author.email == self.user_email
102            }
103            SignBehavior::Own => commit.author.email == self.user_email,
104            SignBehavior::Force => true,
105        }
106    }
107}
108
109fn to_timestamp(value: ConfigValue) -> Result<Timestamp, Box<dyn std::error::Error + Send + Sync>> {
110    // Since toml_edit::Datetime isn't the date-time type used across our code
111    // base, we accept both string and date-time types.
112    if let Some(s) = value.as_str() {
113        Ok(Timestamp::from_datetime(DateTime::parse_from_rfc3339(s)?))
114    } else if let Some(d) = value.as_datetime() {
115        // It's easier to re-parse the TOML date-time expression.
116        let s = d.to_string();
117        Ok(Timestamp::from_datetime(DateTime::parse_from_rfc3339(&s)?))
118    } else {
119        let ty = value.type_name();
120        Err(format!("invalid type: {ty}, expected a date-time").into())
121    }
122}
123
124impl UserSettings {
125    pub fn from_config(config: StackedConfig) -> Result<Self, ConfigGetError> {
126        let rng_seed = config.get::<u64>("debug.randomness-seed").optional()?;
127        Self::from_config_and_rng(config, Arc::new(JJRng::new(rng_seed)))
128    }
129
130    fn from_config_and_rng(config: StackedConfig, rng: Arc<JJRng>) -> Result<Self, ConfigGetError> {
131        let user_name = config.get("user.name")?;
132        let user_email = config.get("user.email")?;
133        let commit_timestamp = config
134            .get_value_with("debug.commit-timestamp", to_timestamp)
135            .optional()?;
136        let operation_timestamp = config
137            .get_value_with("debug.operation-timestamp", to_timestamp)
138            .optional()?;
139        let operation_hostname = config.get("operation.hostname")?;
140        let operation_username = config.get("operation.username")?;
141        let signing_behavior = config.get("signing.behavior")?;
142        let signing_key = config.get("signing.key").optional()?;
143        let data = UserSettingsData {
144            user_name,
145            user_email,
146            commit_timestamp,
147            operation_timestamp,
148            operation_hostname,
149            operation_username,
150            signing_behavior,
151            signing_key,
152        };
153        Ok(Self {
154            config: Arc::new(config),
155            data: Arc::new(data),
156            rng,
157        })
158    }
159
160    /// Like [`UserSettings::from_config()`], but retains the internal state.
161    ///
162    /// This ensures that no duplicated change IDs are generated within the
163    /// current process. New `debug.randomness-seed` value is ignored.
164    pub fn with_new_config(&self, config: StackedConfig) -> Result<Self, ConfigGetError> {
165        Self::from_config_and_rng(config, self.rng.clone())
166    }
167
168    pub fn get_rng(&self) -> Arc<JJRng> {
169        self.rng.clone()
170    }
171
172    pub fn user_name(&self) -> &str {
173        &self.data.user_name
174    }
175
176    // Must not be changed to avoid git pushing older commits with no set name
177    pub const USER_NAME_PLACEHOLDER: &str = "(no name configured)";
178
179    pub fn user_email(&self) -> &str {
180        &self.data.user_email
181    }
182
183    // Must not be changed to avoid git pushing older commits with no set email
184    // address
185    pub const USER_EMAIL_PLACEHOLDER: &str = "(no email configured)";
186
187    pub fn commit_timestamp(&self) -> Option<Timestamp> {
188        self.data.commit_timestamp
189    }
190
191    pub fn operation_timestamp(&self) -> Option<Timestamp> {
192        self.data.operation_timestamp
193    }
194
195    pub fn operation_hostname(&self) -> &str {
196        &self.data.operation_hostname
197    }
198
199    pub fn operation_username(&self) -> &str {
200        &self.data.operation_username
201    }
202
203    pub fn signature(&self) -> Signature {
204        let timestamp = self.data.commit_timestamp.unwrap_or_else(Timestamp::now);
205        Signature {
206            name: self.user_name().to_owned(),
207            email: self.user_email().to_owned(),
208            timestamp,
209        }
210    }
211
212    /// Returns low-level config object.
213    ///
214    /// You should typically use `settings.get_<type>()` methods instead.
215    pub fn config(&self) -> &StackedConfig {
216        &self.config
217    }
218
219    pub fn remote_settings(&self) -> Result<RemoteSettingsMap, ConfigGetError> {
220        RemoteSettings::table_from_settings(self)
221    }
222
223    // separate from sign_settings as those two are needed in pretty different
224    // places
225    pub fn signing_backend(&self) -> Result<Option<String>, ConfigGetError> {
226        let backend = self.get_string("signing.backend")?;
227        Ok((backend != "none").then_some(backend))
228    }
229
230    pub fn sign_settings(&self) -> SignSettings {
231        SignSettings {
232            behavior: self.data.signing_behavior,
233            user_email: self.data.user_email.clone(),
234            key: self.data.signing_key.clone(),
235        }
236    }
237}
238
239/// General-purpose accessors.
240impl UserSettings {
241    /// Looks up value of the specified type `T` by `name`.
242    pub fn get<'de, T: Deserialize<'de>>(
243        &self,
244        name: impl ToConfigNamePath,
245    ) -> Result<T, ConfigGetError> {
246        self.config.get(name)
247    }
248
249    /// Looks up string value by `name`.
250    pub fn get_string(&self, name: impl ToConfigNamePath) -> Result<String, ConfigGetError> {
251        self.get(name)
252    }
253
254    /// Looks up integer value by `name`.
255    pub fn get_int(&self, name: impl ToConfigNamePath) -> Result<i64, ConfigGetError> {
256        self.get(name)
257    }
258
259    /// Looks up boolean value by `name`.
260    pub fn get_bool(&self, name: impl ToConfigNamePath) -> Result<bool, ConfigGetError> {
261        self.get(name)
262    }
263
264    /// Looks up generic value by `name`.
265    pub fn get_value(&self, name: impl ToConfigNamePath) -> Result<ConfigValue, ConfigGetError> {
266        self.config.get_value(name)
267    }
268
269    /// Looks up value by `name`, converts it by using the given function.
270    pub fn get_value_with<T, E: Into<Box<dyn std::error::Error + Send + Sync>>>(
271        &self,
272        name: impl ToConfigNamePath,
273        convert: impl FnOnce(ConfigValue) -> Result<T, E>,
274    ) -> Result<T, ConfigGetError> {
275        self.config.get_value_with(name, convert)
276    }
277
278    /// Looks up sub table by `name`.
279    ///
280    /// Use `table_keys(prefix)` and `get([prefix, key])` instead if table
281    /// values have to be converted to non-generic value type.
282    pub fn get_table(&self, name: impl ToConfigNamePath) -> Result<ConfigTable, ConfigGetError> {
283        self.config.get_table(name)
284    }
285
286    /// Returns iterator over sub table keys at `name`.
287    pub fn table_keys(&self, name: impl ToConfigNamePath) -> impl Iterator<Item = &str> {
288        self.config.table_keys(name)
289    }
290}
291
292/// This Rng uses interior mutability to allow generating random values using an
293/// immutable reference. It also fixes a specific seedable RNG for
294/// reproducibility.
295#[derive(Debug)]
296pub struct JJRng(Mutex<ChaCha20Rng>);
297impl JJRng {
298    pub fn new_change_id(&self, length: usize) -> ChangeId {
299        let mut rng = self.0.lock().unwrap();
300        let random_bytes = (0..length).map(|_| rng.random::<u8>()).collect();
301        ChangeId::new(random_bytes)
302    }
303
304    /// Creates a new RNGs. Could be made public, but we'd like to encourage all
305    /// RNGs references to point to the same RNG.
306    fn new(seed: Option<u64>) -> Self {
307        Self(Mutex::new(Self::internal_rng_from_seed(seed)))
308    }
309
310    fn internal_rng_from_seed(seed: Option<u64>) -> ChaCha20Rng {
311        match seed {
312            Some(seed) => ChaCha20Rng::seed_from_u64(seed),
313            None => ChaCha20Rng::from_os_rng(),
314        }
315    }
316}
317
318/// A size in bytes optionally formatted/serialized with binary prefixes
319#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
320pub struct HumanByteSize(pub u64);
321
322impl std::fmt::Display for HumanByteSize {
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        let (value, prefix) = binary_prefix(self.0 as f32);
325        write!(f, "{value:.1}{prefix}B")
326    }
327}
328
329impl FromStr for HumanByteSize {
330    type Err = &'static str;
331
332    fn from_str(s: &str) -> Result<Self, Self::Err> {
333        match s.parse() {
334            Ok(bytes) => Ok(Self(bytes)),
335            Err(_) => {
336                let bytes = parse_human_byte_size(s)?;
337                Ok(Self(bytes))
338            }
339        }
340    }
341}
342
343impl TryFrom<ConfigValue> for HumanByteSize {
344    type Error = &'static str;
345
346    fn try_from(value: ConfigValue) -> Result<Self, Self::Error> {
347        if let Some(n) = value.as_integer() {
348            let n = u64::try_from(n).map_err(|_| "Integer out of range")?;
349            Ok(Self(n))
350        } else if let Some(s) = value.as_str() {
351            s.parse()
352        } else {
353            Err("Expected a positive integer or a string in '<number><unit>' form")
354        }
355    }
356}
357
358fn parse_human_byte_size(v: &str) -> Result<u64, &'static str> {
359    let digit_end = v.find(|c: char| !c.is_ascii_digit()).unwrap_or(v.len());
360    if digit_end == 0 {
361        return Err("must start with a number");
362    }
363    let (digits, trailing) = v.split_at(digit_end);
364    let exponent = match trailing.trim_start() {
365        "" | "B" => 0,
366        unit => {
367            const PREFIXES: [char; 8] = ['K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
368            let Some(prefix) = PREFIXES.iter().position(|&x| unit.starts_with(x)) else {
369                return Err("unrecognized unit prefix");
370            };
371            let ("" | "B" | "i" | "iB") = &unit[1..] else {
372                return Err("unrecognized unit");
373            };
374            prefix as u32 + 1
375        }
376    };
377    // A string consisting only of base 10 digits is either a valid u64 or really
378    // huge.
379    let factor = digits.parse::<u64>().unwrap_or(u64::MAX);
380    Ok(factor.saturating_mul(1024u64.saturating_pow(exponent)))
381}
382
383#[cfg(test)]
384mod tests {
385    use assert_matches::assert_matches;
386
387    use super::*;
388
389    #[test]
390    fn byte_size_parse() {
391        assert_eq!(parse_human_byte_size("0"), Ok(0));
392        assert_eq!(parse_human_byte_size("42"), Ok(42));
393        assert_eq!(parse_human_byte_size("42B"), Ok(42));
394        assert_eq!(parse_human_byte_size("42 B"), Ok(42));
395        assert_eq!(parse_human_byte_size("42K"), Ok(42 * 1024));
396        assert_eq!(parse_human_byte_size("42 K"), Ok(42 * 1024));
397        assert_eq!(parse_human_byte_size("42 KB"), Ok(42 * 1024));
398        assert_eq!(parse_human_byte_size("42 KiB"), Ok(42 * 1024));
399        assert_eq!(
400            parse_human_byte_size("42 LiB"),
401            Err("unrecognized unit prefix")
402        );
403        assert_eq!(parse_human_byte_size("42 KiC"), Err("unrecognized unit"));
404        assert_eq!(parse_human_byte_size("42 KC"), Err("unrecognized unit"));
405        assert_eq!(
406            parse_human_byte_size("KiB"),
407            Err("must start with a number")
408        );
409        assert_eq!(parse_human_byte_size(""), Err("must start with a number"));
410    }
411
412    #[test]
413    fn byte_size_from_config_value() {
414        assert_eq!(
415            HumanByteSize::try_from(ConfigValue::from(42)).unwrap(),
416            HumanByteSize(42)
417        );
418        assert_eq!(
419            HumanByteSize::try_from(ConfigValue::from("42K")).unwrap(),
420            HumanByteSize(42 * 1024)
421        );
422        assert_matches!(
423            HumanByteSize::try_from(ConfigValue::from(-1)),
424            Err("Integer out of range")
425        );
426    }
427}