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