-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathconfig.rs
More file actions
2079 lines (1916 loc) · 71.3 KB
/
Copy pathconfig.rs
File metadata and controls
2079 lines (1916 loc) · 71.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::env;
use std::env::split_paths;
use std::fmt;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Mutex;
use etcetera::BaseStrategy as _;
use itertools::Itertools as _;
use jj_lib::config::ConfigFile;
use jj_lib::config::ConfigGetError;
use jj_lib::config::ConfigLayer;
use jj_lib::config::ConfigLoadError;
use jj_lib::config::ConfigMigrationRule;
use jj_lib::config::ConfigNamePathBuf;
use jj_lib::config::ConfigResolutionContext;
use jj_lib::config::ConfigSource;
use jj_lib::config::ConfigValue;
use jj_lib::config::StackedConfig;
use jj_lib::dsl_util::AliasDeclarationParser;
use jj_lib::dsl_util::AliasesMap;
use jj_lib::secure_config::LoadedSecureConfig;
use jj_lib::secure_config::SecureConfig;
use rand::SeedableRng as _;
use rand_chacha::ChaCha20Rng;
use regex::Captures;
use regex::Regex;
use serde::Serialize as _;
use tracing::instrument;
use crate::command_error::CommandError;
use crate::command_error::config_error;
use crate::command_error::config_error_with_message;
use crate::command_error::user_error;
use crate::ui::Ui;
// TODO(#879): Consider generating entire schema dynamically vs. static file.
pub const CONFIG_SCHEMA: &str = include_str!("config-schema.json");
const REPO_CONFIG_DIR: &str = "repos";
const WORKSPACE_CONFIG_DIR: &str = "workspaces";
/// Parses a TOML value expression. Interprets the given value as string if it
/// can't be parsed and doesn't look like a TOML expression.
pub fn parse_value_or_bare_string(value_str: &str) -> Result<ConfigValue, toml_edit::TomlError> {
match value_str.parse() {
Ok(value) => Ok(value),
Err(_) if is_bare_string(value_str) => Ok(value_str.into()),
Err(err) => Err(err),
}
}
fn is_bare_string(value_str: &str) -> bool {
// leading whitespace isn't ignored when parsing TOML value expression, but
// "\n[]" doesn't look like a bare string.
let trimmed = value_str.trim_ascii().as_bytes();
if let (Some(&first), Some(&last)) = (trimmed.first(), trimmed.last()) {
// string, array, or table constructs?
!matches!(first, b'"' | b'\'' | b'[' | b'{') && !matches!(last, b'"' | b'\'' | b']' | b'}')
} else {
true // empty or whitespace only
}
}
/// Converts [`ConfigValue`] (or [`toml_edit::Value`]) to [`toml::Value`] which
/// implements [`serde::Serialize`].
pub fn to_serializable_value(value: ConfigValue) -> toml::Value {
match value {
ConfigValue::String(v) => toml::Value::String(v.into_value()),
ConfigValue::Integer(v) => toml::Value::Integer(v.into_value()),
ConfigValue::Float(v) => toml::Value::Float(v.into_value()),
ConfigValue::Boolean(v) => toml::Value::Boolean(v.into_value()),
ConfigValue::Datetime(v) => toml::Value::Datetime(v.into_value()),
ConfigValue::Array(array) => {
let array = array.into_iter().map(to_serializable_value).collect();
toml::Value::Array(array)
}
ConfigValue::InlineTable(table) => {
let table = table
.into_iter()
.map(|(k, v)| (k, to_serializable_value(v)))
.collect();
toml::Value::Table(table)
}
}
}
/// Configuration variable with its source information.
#[derive(Clone, Debug, serde::Serialize)]
pub struct AnnotatedValue {
/// Dotted name path to the configuration variable.
#[serde(serialize_with = "serialize_name")]
pub name: ConfigNamePathBuf,
/// Configuration value.
#[serde(serialize_with = "serialize_value")]
pub value: ConfigValue,
/// Source of the configuration value.
#[serde(serialize_with = "serialize_source")]
pub source: ConfigSource,
/// Path to the source file, if available.
pub path: Option<PathBuf>,
/// True if this value is overridden in higher precedence layers.
pub is_overridden: bool,
}
fn serialize_name<S>(name: &ConfigNamePathBuf, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
name.to_string().serialize(serializer)
}
fn serialize_value<S>(value: &ConfigValue, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
to_serializable_value(value.clone()).serialize(serializer)
}
fn serialize_source<S>(source: &ConfigSource, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
source.to_string().serialize(serializer)
}
/// Collects values under the given `filter_prefix` name recursively, from all
/// layers.
pub fn resolved_config_values(
stacked_config: &StackedConfig,
filter_prefix: &ConfigNamePathBuf,
) -> Vec<AnnotatedValue> {
// Collect annotated values in reverse order and mark each value shadowed by
// value or table in upper layers.
let mut config_vals = vec![];
let mut upper_value_names = BTreeSet::new();
for layer in stacked_config.layers().iter().rev() {
let top_item = match layer.look_up_item(filter_prefix) {
Ok(Some(item)) => item,
Ok(None) => continue, // parent is a table, but no value found
Err(_) => {
// parent is not a table, shadows lower layers
upper_value_names.insert(filter_prefix.clone());
continue;
}
};
let mut config_stack = vec![(filter_prefix.clone(), top_item, false)];
while let Some((name, item, is_parent_overridden)) = config_stack.pop() {
// Cannot retain inline table formatting because inner values may be
// overridden independently.
if let Some(table) = item.as_table_like() {
// current table and children may be shadowed by value in upper layer
let is_overridden = is_parent_overridden || upper_value_names.contains(&name);
for (k, v) in table.iter() {
let mut sub_name = name.clone();
sub_name.push(k);
config_stack.push((sub_name, v, is_overridden)); // in reverse order
}
} else {
// current value may be shadowed by value or table in upper layer
let maybe_child = upper_value_names
.range(&name..)
.next()
.filter(|next| next.starts_with(&name));
let is_overridden = is_parent_overridden || maybe_child.is_some();
if maybe_child != Some(&name) {
upper_value_names.insert(name.clone());
}
let value = item
.clone()
.into_value()
.expect("Item::None should not exist in table");
config_vals.push(AnnotatedValue {
name,
value,
source: layer.source,
path: layer.path.clone(),
is_overridden,
});
}
}
}
config_vals.reverse();
config_vals
}
/// Newtype for unprocessed (or unresolved) [`StackedConfig`].
///
/// This doesn't provide any strict guarantee about the underlying config
/// object. It just requires an explicit cast to access to the config object.
#[derive(Clone, Debug)]
pub struct RawConfig(StackedConfig);
impl AsRef<StackedConfig> for RawConfig {
fn as_ref(&self) -> &StackedConfig {
&self.0
}
}
impl AsMut<StackedConfig> for RawConfig {
fn as_mut(&mut self) -> &mut StackedConfig {
&mut self.0
}
}
#[derive(Clone, Debug)]
enum ConfigPathState {
New,
Exists,
}
/// A ConfigPath can be in one of two states:
///
/// - exists(): a config file exists at the path
/// - !exists(): a config file doesn't exist here, but a new file _can_ be
/// created at this path
#[derive(Clone, Debug)]
struct ConfigPath {
path: PathBuf,
state: ConfigPathState,
}
impl ConfigPath {
fn new(path: PathBuf) -> Self {
use ConfigPathState::*;
Self {
state: if path.exists() { Exists } else { New },
path,
}
}
fn as_path(&self) -> &Path {
&self.path
}
fn exists(&self) -> bool {
match self.state {
ConfigPathState::Exists => true,
ConfigPathState::New => false,
}
}
}
/// Like std::fs::create_dir_all but creates new directories to be accessible to
/// the user only on Unix (chmod 700).
fn create_dir_all(path: &Path) -> std::io::Result<()> {
let mut dir = std::fs::DirBuilder::new();
dir.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
dir.mode(0o700);
}
dir.create(path)
}
// The struct exists so that we can mock certain global values in unit tests.
#[derive(Clone, Default, Debug)]
struct UnresolvedConfigEnv {
user_config_dir: Option<PathBuf>,
home_dir: Option<PathBuf>,
jj_config: Option<String>,
system_config_dir: Option<PathBuf>,
}
impl UnresolvedConfigEnv {
fn root_config_dir(&self) -> Option<PathBuf> {
self.user_config_dir.as_deref().map(|c| c.join("jj"))
}
fn resolve_user(self) -> Vec<ConfigPath> {
if let Some(paths) = self.jj_config {
return split_paths(&paths)
.filter(|path| !path.as_os_str().is_empty())
.map(ConfigPath::new)
.collect();
}
let mut paths = vec![];
let home_config_path = self.home_dir.map(|mut home_dir| {
home_dir.push(".jjconfig.toml");
ConfigPath::new(home_dir)
});
let platform_config_path = self.user_config_dir.clone().map(|mut config_dir| {
config_dir.push("jj");
config_dir.push("config.toml");
ConfigPath::new(config_dir)
});
let platform_config_dir = self.user_config_dir.map(|mut config_dir| {
config_dir.push("jj");
config_dir.push("conf.d");
ConfigPath::new(config_dir)
});
if let Some(path) = home_config_path
&& (path.exists() || platform_config_path.is_none())
{
paths.push(path);
}
// This should be the default config created if there's
// no user config and `jj config edit` is executed.
if let Some(path) = platform_config_path {
paths.push(path);
}
if let Some(path) = platform_config_dir
&& path.exists()
{
paths.push(path);
}
paths
}
fn resolve_system(&self) -> Vec<ConfigPath> {
if let Some(path) = self.system_config_dir.as_ref()
&& self.jj_config.is_none()
{
[path.join("jj/config.toml"), path.join("jj/conf.d")]
.into_iter()
.map(ConfigPath::new)
.collect()
} else {
Vec::new()
}
}
}
#[derive(Clone, Debug)]
pub struct ConfigEnv {
home_dir: Option<PathBuf>,
root_config_dir: Option<PathBuf>,
repo_path: Option<PathBuf>,
workspace_path: Option<PathBuf>,
system_config_paths: Vec<ConfigPath>,
user_config_paths: Vec<ConfigPath>,
repo_config: Option<SecureConfig>,
workspace_config: Option<SecureConfig>,
command: Option<String>,
hostname: Option<String>,
environment: HashMap<String, String>,
rng: Arc<Mutex<ChaCha20Rng>>,
}
impl ConfigEnv {
/// Initializes configuration loader based on environment variables.
pub fn from_environment() -> Self {
let user_config_dir = etcetera::choose_base_strategy()
.ok()
.map(|s| s.config_dir());
// Canonicalize home as we do canonicalize cwd in CliRunner. $HOME might
// point to symlink.
let home_dir = etcetera::home_dir()
.ok()
.map(|d| dunce::canonicalize(&d).unwrap_or(d));
let system_config_dir = if cfg!(unix) {
Some("/etc".into())
} else {
None
};
let env = UnresolvedConfigEnv {
user_config_dir,
home_dir: home_dir.clone(),
jj_config: env::var("JJ_CONFIG").ok(),
system_config_dir,
};
let environment = env::vars_os()
.filter_map(|(k, v)| {
// Silently ignore non-Unicode environment variables. Don't panic like vars()
let k = k.into_string().ok()?;
let v = v.into_string().ok()?;
Some((k, v))
})
.collect();
Self {
home_dir,
root_config_dir: env.root_config_dir(),
repo_path: None,
workspace_path: None,
system_config_paths: env.resolve_system(),
user_config_paths: env.resolve_user(),
repo_config: None,
workspace_config: None,
command: None,
hostname: whoami::hostname().ok(),
environment,
// We would ideally use JjRng, but that requires the seed from the
// config, which requires the config to be loaded.
rng: Arc::new(Mutex::new(
if let Ok(Ok(value)) = env::var("JJ_RANDOMNESS_SEED").map(|s| s.parse::<u64>()) {
ChaCha20Rng::seed_from_u64(value)
} else {
rand::make_rng()
},
)),
}
}
pub fn set_command_name(&mut self, command: String) {
self.command = Some(command);
}
/// Loads system-wide config files into the given `config`. The old
/// system-config layers will be replaced if any.
#[instrument]
pub fn reload_system_config(&self, config: &mut RawConfig) -> Result<(), ConfigLoadError> {
config.as_mut().remove_layers(ConfigSource::System);
for path in self.existing_system_config_paths() {
if path.is_dir() {
config.as_mut().load_dir(ConfigSource::System, path)?;
} else {
config.as_mut().load_file(ConfigSource::System, path)?;
}
}
Ok(())
}
pub fn existing_system_config_paths(&self) -> impl Iterator<Item = &Path> {
self.system_config_paths
.iter()
.filter(|p| p.exists())
.map(ConfigPath::as_path)
}
fn load_secure_config(
&self,
ui: &Ui,
config: Option<&SecureConfig>,
kind: &str,
force: bool,
) -> Result<Option<LoadedSecureConfig>, CommandError> {
Ok(match (config, self.root_config_dir.as_ref()) {
(Some(config), Some(root_config_dir)) => {
let mut guard = self.rng.lock().unwrap();
let loaded_config = if force {
config.load_config(&mut guard, &root_config_dir.join(kind))
} else {
config.maybe_load_config(&mut guard, &root_config_dir.join(kind))
}?;
for warning in &loaded_config.warnings {
writeln!(ui.warning_default(), "{warning}")?;
}
Some(loaded_config)
}
_ => None,
})
}
/// Returns the paths to the user-specific config files or directories.
pub fn user_config_paths(&self) -> impl Iterator<Item = &Path> {
self.user_config_paths.iter().map(ConfigPath::as_path)
}
/// Returns the paths to the existing user-specific config files or
/// directories.
pub fn existing_user_config_paths(&self) -> impl Iterator<Item = &Path> {
self.user_config_paths
.iter()
.filter(|p| p.exists())
.map(ConfigPath::as_path)
}
/// Returns user configuration files for modification. Instantiates one if
/// `config` has no user configuration layers.
///
/// The parent directory for the new file may be created by this function.
/// If the user configuration path is unknown, this function returns an
/// empty `Vec`.
pub fn user_config_files(&self, config: &RawConfig) -> Result<Vec<ConfigFile>, CommandError> {
config_files_for(config, ConfigSource::User, || {
Ok(self.new_user_config_file()?)
})
}
fn new_user_config_file(&self) -> Result<Option<ConfigFile>, ConfigLoadError> {
self.user_config_paths()
.next()
.map(|path| {
// No need to propagate io::Error here. If the directory
// couldn't be created, file.save() would fail later.
if let Some(dir) = path.parent() {
create_dir_all(dir).ok();
}
// The path doesn't usually exist, but we shouldn't overwrite it
// with an empty config if it did exist.
ConfigFile::load_or_empty(ConfigSource::User, path)
})
.transpose()
}
/// Loads user-specific config files into the given `config`. The old
/// user-config layers will be replaced if any.
#[instrument]
pub fn reload_user_config(&self, config: &mut RawConfig) -> Result<(), ConfigLoadError> {
config.as_mut().remove_layers(ConfigSource::User);
for path in self.existing_user_config_paths() {
if path.is_dir() {
config.as_mut().load_dir(ConfigSource::User, path)?;
} else {
config.as_mut().load_file(ConfigSource::User, path)?;
}
}
Ok(())
}
/// Sets the directory where the repo-specific config file is stored. The
/// path is usually `$REPO/.jj/repo`.
pub fn reset_repo_path(&mut self, path: &Path) {
self.repo_config = Some(SecureConfig::new_repo(path.to_path_buf()));
self.repo_path = Some(path.to_owned());
}
/// Returns a path to the existing repo-specific config file.
fn maybe_repo_config_path(&self, ui: &Ui) -> Result<Option<PathBuf>, CommandError> {
Ok(self
.load_secure_config(ui, self.repo_config.as_ref(), REPO_CONFIG_DIR, false)?
.and_then(|c| c.config_file))
}
/// Returns a path to the existing repo-specific config file.
/// If the config file does not exist, will create a new config ID and
/// create a new directory for this.
pub fn repo_config_path(&self, ui: &Ui) -> Result<Option<PathBuf>, CommandError> {
Ok(self
.load_secure_config(ui, self.repo_config.as_ref(), REPO_CONFIG_DIR, true)?
.and_then(|c| c.config_file))
}
/// Returns the directory under which all repo-specific config
/// subdirectories (one per config ID) are stored.
pub fn repo_configs_root_dir(&self) -> Option<PathBuf> {
self.root_config_dir
.as_ref()
.map(|dir| dir.join(REPO_CONFIG_DIR))
}
/// Returns repo configuration files for modification. Instantiates one if
/// `config` has no repo configuration layers.
///
/// If the repo path is unknown, this function returns an empty `Vec`. Since
/// the repo config path cannot be a directory, the returned `Vec` should
/// have at most one config file.
pub fn repo_config_files(
&self,
ui: &Ui,
config: &RawConfig,
) -> Result<Vec<ConfigFile>, CommandError> {
config_files_for(config, ConfigSource::Repo, || self.new_repo_config_file(ui))
}
fn new_repo_config_file(&self, ui: &Ui) -> Result<Option<ConfigFile>, CommandError> {
Ok(self
.repo_config_path(ui)?
// The path doesn't usually exist, but we shouldn't overwrite it
// with an empty config if it did exist.
.map(|path| ConfigFile::load_or_empty(ConfigSource::Repo, path))
.transpose()?)
}
/// Loads repo-specific config file into the given `config`. The old
/// repo-config layer will be replaced if any.
#[instrument(skip(ui))]
pub fn reload_repo_config(&self, ui: &Ui, config: &mut RawConfig) -> Result<(), CommandError> {
config.as_mut().remove_layers(ConfigSource::Repo);
if let Some(path) = self.maybe_repo_config_path(ui)?
&& path.exists()
{
config.as_mut().load_file(ConfigSource::Repo, path)?;
}
Ok(())
}
/// Sets the directory where the workspace-specific config file is stored.
pub fn reset_workspace_path(&mut self, path: &Path) {
self.workspace_config = Some(SecureConfig::new_workspace(path.join(".jj")));
self.workspace_path = Some(path.to_owned());
}
/// Returns a path to the workspace-specific config file, if it exists.
fn maybe_workspace_config_path(&self, ui: &Ui) -> Result<Option<PathBuf>, CommandError> {
Ok(self
.load_secure_config(
ui,
self.workspace_config.as_ref(),
WORKSPACE_CONFIG_DIR,
false,
)?
.and_then(|c| c.config_file))
}
/// Returns a path to the existing workspace-specific config file.
/// If the config file does not exist, will create a new config ID and
/// create a new directory for this.
pub fn workspace_config_path(&self, ui: &Ui) -> Result<Option<PathBuf>, CommandError> {
Ok(self
.load_secure_config(
ui,
self.workspace_config.as_ref(),
WORKSPACE_CONFIG_DIR,
true,
)?
.and_then(|c| c.config_file))
}
/// Returns workspace configuration files for modification. Instantiates one
/// if `config` has no workspace configuration layers.
///
/// If the workspace path is unknown, this function returns an empty `Vec`.
/// Since the workspace config path cannot be a directory, the returned
/// `Vec` should have at most one config file.
pub fn workspace_config_files(
&self,
ui: &Ui,
config: &RawConfig,
) -> Result<Vec<ConfigFile>, CommandError> {
config_files_for(config, ConfigSource::Workspace, || {
self.new_workspace_config_file(ui)
})
}
fn new_workspace_config_file(&self, ui: &Ui) -> Result<Option<ConfigFile>, CommandError> {
Ok(self
.workspace_config_path(ui)?
.map(|path| ConfigFile::load_or_empty(ConfigSource::Workspace, path))
.transpose()?)
}
/// Loads workspace-specific config file into the given `config`. The old
/// workspace-config layer will be replaced if any.
#[instrument(skip(ui))]
pub fn reload_workspace_config(
&self,
ui: &Ui,
config: &mut RawConfig,
) -> Result<(), CommandError> {
config.as_mut().remove_layers(ConfigSource::Workspace);
if let Some(path) = self.maybe_workspace_config_path(ui)?
&& path.exists()
{
config.as_mut().load_file(ConfigSource::Workspace, path)?;
}
Ok(())
}
/// Returns the configuration file at the specified `path` for modification.
///
/// Validates that the path is a recognized Jujutsu configuration location
/// (such as a loaded layer, a user config path or file in `conf.d/`,
/// or a repo/workspace config path). If the file is already loaded in
/// `config`, its existing [`ConfigFile`] representation is reused;
/// otherwise, a new [`ConfigFile`] is initialized.
pub fn resolve_file_to_edit(
&self,
ui: &Ui,
config: &RawConfig,
path: &Path,
) -> Result<ConfigFile, CommandError> {
let canonical_path = dunce::canonicalize(path).ok();
let matches_path = |p: &Path| p == path || Some(p) == canonical_path.as_deref();
// 1. Check if it matches an already loaded layer (user, system, repo,
// workspace, --config-file, JJ_CONFIG, etc.)
for layer in config.as_ref().layers() {
if let Some(layer_path) = layer.path.as_ref()
&& matches_path(layer_path)
&& let Ok(file) = ConfigFile::from_layer(layer.clone())
{
return Ok(file);
}
}
// 2. Check repo config path (even if not yet created on disk)
if let Ok(Some(repo_path)) = self.repo_config_path(ui)
&& matches_path(&repo_path)
{
if let Some(parent) = path.parent() {
create_dir_all(parent).ok();
}
return Ok(ConfigFile::load_or_empty(ConfigSource::Repo, path)?);
}
// 3. Check workspace config path (even if not yet created on disk)
if let Ok(Some(workspace_path)) = self.workspace_config_path(ui)
&& matches_path(&workspace_path)
{
if let Some(parent) = path.parent() {
create_dir_all(parent).ok();
}
return Ok(ConfigFile::load_or_empty(ConfigSource::Workspace, path)?);
}
// 4. Check user config paths (e.g. ~/.config/jj/config.toml,
// ~/.jjconfig.toml, or files in conf.d)
for user_path in self.user_config_paths() {
if matches_path(user_path) || is_file_in_config_dir(path, user_path) {
if let Some(parent) = path.parent() {
create_dir_all(parent).ok();
}
return Ok(ConfigFile::load_or_empty(ConfigSource::User, path)?);
}
}
Err(user_error(format!(
"Configuration file '{}' is not a valid jj configuration file location",
path.display()
))
.hinted(
"Valid config locations include user configs (`~/.config/jj/config.toml` or \
`conf.d/*.toml`), repo/workspace configs, or files loaded with the global flag \
`--config-file <PATH>`.",
))
}
/// Resolves conditional scopes within the current environment. Returns new
/// resolved config.
pub fn resolve_config(&self, config: &RawConfig) -> Result<StackedConfig, ConfigGetError> {
let context = ConfigResolutionContext {
home_dir: self.home_dir.as_deref(),
repo_path: self.repo_path.as_deref(),
workspace_path: self.workspace_path.as_deref(),
command: self.command.as_deref(),
hostname: self.hostname.as_deref().unwrap_or(""),
environment: &self.environment,
};
jj_lib::config::resolve(config.as_ref(), &context)
}
}
/// Similar to [`ConfigEnv::repo_config_files()`], but doesn't attempt to
/// initialize new config ID and its storage directory.
pub fn existing_repo_config_file(config: &RawConfig) -> Option<ConfigFile> {
// There should be at most one repo-level config file.
config
.as_ref()
.layers_for(ConfigSource::Repo)
.iter()
.find_map(|layer| ConfigFile::from_layer(layer.clone()).ok())
}
fn config_files_for(
config: &RawConfig,
source: ConfigSource,
new_file: impl FnOnce() -> Result<Option<ConfigFile>, CommandError>,
) -> Result<Vec<ConfigFile>, CommandError> {
let mut files = config
.as_ref()
.layers_for(source)
.iter()
.filter_map(|layer| ConfigFile::from_layer(layer.clone()).ok())
.collect_vec();
if files.is_empty() {
files.extend(new_file()?);
}
Ok(files)
}
fn is_file_in_config_dir(file_path: &Path, dir_path: &Path) -> bool {
if file_path.extension() != Some("toml".as_ref()) {
return false;
}
if dir_path.is_file() {
return false;
}
let Some(parent) = file_path.parent() else {
return false;
};
if parent == dir_path {
return true;
}
dunce::canonicalize(parent).ok().as_deref() == Some(dir_path)
}
/// Initializes stacked config with the given `default_layers` and infallible
/// sources.
///
/// Sources from the lowest precedence:
/// 1. Default
/// 2. System config
/// 3. Base environment variables
/// 4. [User configs](https://docs.jj-vcs.dev/latest/config/)
/// 5. Repo config
/// 6. Workspace config
/// 7. Override environment variables
/// 8. Command-line arguments `--config` and `--config-file`
///
/// This function sets up 1, 3, and 7.
pub fn config_from_environment(default_layers: impl IntoIterator<Item = ConfigLayer>) -> RawConfig {
let mut config = StackedConfig::with_defaults();
config.extend_layers(default_layers);
config.add_layer(env_base_layer());
config.add_layer(env_overrides_layer());
RawConfig(config)
}
const OP_HOSTNAME: &str = "operation.hostname";
const OP_USERNAME: &str = "operation.username";
/// Environment variables that should be overridden by config values
fn env_base_layer() -> ConfigLayer {
let mut layer = ConfigLayer::empty(ConfigSource::EnvBase);
if let Ok(value) =
whoami::hostname().inspect_err(|err| tracing::warn!(?err, "failed to get hostname"))
{
layer.set_value(OP_HOSTNAME, value).unwrap();
}
if let Ok(value) =
whoami::username().inspect_err(|err| tracing::warn!(?err, "failed to get username"))
{
layer.set_value(OP_USERNAME, value).unwrap();
} else if let Ok(value) = env::var("USER") {
// On Unix, $USER is set by login(1). Use it as a fallback because
// getpwuid() of musl libc appears not (fully?) supporting nsswitch.
layer.set_value(OP_USERNAME, value).unwrap();
}
if !env::var("NO_COLOR").unwrap_or_default().is_empty() {
// "User-level configuration files and per-instance command-line arguments
// should override $NO_COLOR." https://no-color.org/
layer.set_value("ui.color", "never").unwrap();
}
if let Ok(value) = env::var("VISUAL") {
layer.set_value("ui.editor", value).unwrap();
} else if let Ok(value) = env::var("EDITOR") {
layer.set_value("ui.editor", value).unwrap();
}
// Intentionally NOT respecting $PAGER here as it often creates a bad
// out-of-the-box experience for users, see http://github.com/jj-vcs/jj/issues/3502.
layer
}
pub fn default_config_layers() -> Vec<ConfigLayer> {
// Syntax error in default config isn't a user error. That's why defaults are
// loaded by separate builder.
let parse = |text: &'static str| ConfigLayer::parse(ConfigSource::Default, text).unwrap();
let mut layers = vec![
parse(include_str!("config/colors.toml")),
parse(include_str!("config/hints.toml")),
parse(include_str!("config/merge_tools.toml")),
parse(include_str!("config/misc.toml")),
parse(include_str!("config/revsets.toml")),
parse(include_str!("config/templates.toml")),
];
if cfg!(unix) {
layers.push(parse(include_str!("config/unix.toml")));
}
if cfg!(windows) {
layers.push(parse(include_str!("config/windows.toml")));
}
layers
}
/// Environment variables that override config values
fn env_overrides_layer() -> ConfigLayer {
let mut layer = ConfigLayer::empty(ConfigSource::EnvOverrides);
if let Ok(value) = env::var("JJ_USER") {
layer.set_value("user.name", value).unwrap();
}
if let Ok(value) = env::var("JJ_EMAIL") {
layer.set_value("user.email", value).unwrap();
}
if let Ok(value) = env::var("JJ_TIMESTAMP") {
layer.set_value("debug.commit-timestamp", value).unwrap();
}
if let Ok(Ok(value)) = env::var("JJ_RANDOMNESS_SEED").map(|s| s.parse::<i64>()) {
layer.set_value("debug.randomness-seed", value).unwrap();
}
if let Ok(value) = env::var("JJ_OP_TIMESTAMP") {
layer.set_value("debug.operation-timestamp", value).unwrap();
}
if let Ok(value) = env::var("JJ_OP_HOSTNAME") {
layer.set_value(OP_HOSTNAME, value).unwrap();
}
if let Ok(value) = env::var("JJ_OP_USERNAME") {
layer.set_value(OP_USERNAME, value).unwrap();
}
if let Ok(value) = env::var("JJ_EDITOR") {
layer.set_value("ui.editor", value).unwrap();
}
if let Ok(value) = env::var("JJ_PAGER") {
layer.set_value("ui.pager", value).unwrap();
}
layer
}
/// Configuration source/data type provided as command-line argument.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ConfigArgKind {
/// `--config=NAME=VALUE`
Item,
/// `--config-file=PATH`
File,
}
/// Parses `--config*` arguments.
pub fn parse_config_args(
toml_strs: &[(ConfigArgKind, &str)],
) -> Result<Vec<ConfigLayer>, CommandError> {
let source = ConfigSource::CommandArg;
let mut layers = Vec::new();
for (kind, chunk) in &toml_strs.iter().chunk_by(|&(kind, _)| kind) {
match kind {
ConfigArgKind::Item => {
let mut layer = ConfigLayer::empty(source);
for (_, item) in chunk {
let (name, value) = parse_config_arg_item(item)?;
// Can fail depending on the argument order, but that
// wouldn't matter in practice.
layer.set_value(name, value).map_err(|err| {
config_error_with_message("--config argument cannot be set", err)
})?;
}
layers.push(layer);
}
ConfigArgKind::File => {
for (_, path) in chunk {
layers.push(ConfigLayer::load_from_file(source, path.into())?);
}
}
}
}
Ok(layers)
}
/// Parses `NAME=VALUE` string.
fn parse_config_arg_item(item_str: &str) -> Result<(ConfigNamePathBuf, ConfigValue), CommandError> {
// split NAME=VALUE at the first parsable position
let split_candidates = item_str.as_bytes().iter().positions(|&b| b == b'=');
let Some((name, value_str)) = split_candidates
.map(|p| (&item_str[..p], &item_str[p + 1..]))
.map(|(name, value)| name.parse().map(|name| (name, value)))
.find_or_last(Result::is_ok)
.transpose()
.map_err(|err| config_error_with_message("--config name cannot be parsed", err))?
else {
return Err(config_error("--config must be specified as NAME=VALUE"));
};
let value = parse_value_or_bare_string(value_str)
.map_err(|err| config_error_with_message("--config value cannot be parsed", err))?;
Ok((name, value))
}
/// List of rules to migrate deprecated config variables.
pub fn default_config_migrations() -> Vec<ConfigMigrationRule> {
vec![]
}
/// Command name and arguments specified by config.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)]
#[serde(untagged)]
pub enum CommandNameAndArgs {
String(String),
Vec(NonEmptyCommandArgsVec),
Structured {
env: HashMap<String, String>,
command: NonEmptyCommandArgsVec,
},
}
impl CommandNameAndArgs {
/// Returns command name without arguments.
pub fn split_name(&self) -> Cow<'_, str> {
let (name, _) = self.split_name_and_args();
name
}
/// Returns command name and arguments.
///
/// The command name may be an empty string (as well as each argument.)
pub fn split_name_and_args(&self) -> (Cow<'_, str>, Cow<'_, [String]>) {
match self {
Self::String(s) => {
if s.contains('"') || s.contains('\'') {
let mut parts = shlex::Shlex::new(s);
let res = (
parts.next().unwrap_or_default().into(),
parts.by_ref().collect(),
);
if !parts.had_error {