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