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