Skip to main content

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