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