-
Notifications
You must be signed in to change notification settings - Fork 968
Expand file tree
/
Copy pathcli_util.rs
More file actions
4518 lines (4163 loc) · 169 KB
/
cli_util.rs
File metadata and controls
4518 lines (4163 loc) · 169 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::cell::OnceCell;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::ffi::OsString;
use std::fmt;
use std::fmt::Debug;
use std::io;
use std::io::Write as _;
use std::mem;
use std::path::Path;
use std::path::PathBuf;
use std::pin::Pin;
use std::rc::Rc;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::SystemTime;
use bstr::ByteVec as _;
use chrono::TimeZone as _;
use clap::ArgAction;
use clap::ArgMatches;
use clap::Command;
use clap::FromArgMatches as _;
use clap::builder::MapValueParser;
use clap::builder::NonEmptyStringValueParser;
use clap::builder::TypedValueParser as _;
use clap::builder::ValueParserFactory;
use clap::error::ContextKind;
use clap::error::ContextValue;
use clap_complete::ArgValueCandidates;
use clap_complete::ArgValueCompleter;
use indexmap::IndexMap;
use indexmap::IndexSet;
use indoc::indoc;
use indoc::writedoc;
use itertools::Itertools as _;
use jj_lib::backend::BackendResult;
use jj_lib::backend::ChangeId;
use jj_lib::backend::CommitId;
use jj_lib::backend::TreeValue;
use jj_lib::commit::Commit;
use jj_lib::config::ConfigGetError;
use jj_lib::config::ConfigGetResultExt as _;
use jj_lib::config::ConfigLayer;
use jj_lib::config::ConfigMigrationRule;
use jj_lib::config::ConfigNamePathBuf;
use jj_lib::config::ConfigSource;
use jj_lib::config::ConfigValue;
use jj_lib::config::StackedConfig;
use jj_lib::conflicts::ConflictMarkerStyle;
use jj_lib::fileset;
use jj_lib::fileset::FilesetAliasesMap;
use jj_lib::fileset::FilesetDiagnostics;
use jj_lib::fileset::FilesetExpression;
use jj_lib::fileset::FilesetParseContext;
use jj_lib::gitignore::GitIgnoreError;
use jj_lib::gitignore::GitIgnoreFile;
use jj_lib::id_prefix::IdPrefixContext;
use jj_lib::lock::FileLock;
use jj_lib::matchers::Matcher;
use jj_lib::matchers::NothingMatcher;
use jj_lib::merge::Diff;
use jj_lib::merge::MergedTreeValue;
use jj_lib::merged_tree::MergedTree;
use jj_lib::object_id::ObjectId as _;
use jj_lib::op_heads_store;
use jj_lib::op_store::OpStoreError;
use jj_lib::op_store::OperationId;
use jj_lib::op_store::RefTarget;
use jj_lib::op_walk;
use jj_lib::op_walk::OpsetEvaluationError;
use jj_lib::operation::Operation;
use jj_lib::ref_name::RefName;
use jj_lib::ref_name::RefNameBuf;
use jj_lib::ref_name::RemoteName;
use jj_lib::ref_name::RemoteRefSymbol;
use jj_lib::ref_name::WorkspaceName;
use jj_lib::ref_name::WorkspaceNameBuf;
use jj_lib::repo::CheckOutCommitError;
use jj_lib::repo::EditCommitError;
use jj_lib::repo::MutableRepo;
use jj_lib::repo::ReadonlyRepo;
use jj_lib::repo::Repo;
use jj_lib::repo::RepoLoader;
use jj_lib::repo::StoreFactories;
use jj_lib::repo::StoreLoadError;
use jj_lib::repo::merge_factories_map;
use jj_lib::repo_path::RepoPath;
use jj_lib::repo_path::RepoPathBuf;
use jj_lib::repo_path::RepoPathUiConverter;
use jj_lib::repo_path::UiPathParseError;
use jj_lib::revset;
use jj_lib::revset::ResolvedRevsetExpression;
use jj_lib::revset::RevsetAliasesMap;
use jj_lib::revset::RevsetDiagnostics;
use jj_lib::revset::RevsetExpression;
use jj_lib::revset::RevsetExtensions;
use jj_lib::revset::RevsetFilterPredicate;
use jj_lib::revset::RevsetFunction;
use jj_lib::revset::RevsetIteratorExt as _;
use jj_lib::revset::RevsetParseContext;
use jj_lib::revset::RevsetWorkspaceContext;
use jj_lib::revset::SymbolResolverExtension;
use jj_lib::revset::UserRevsetExpression;
use jj_lib::rewrite::restore_tree;
use jj_lib::settings::HumanByteSize;
use jj_lib::settings::UserSettings;
use jj_lib::store::Store;
use jj_lib::str_util::StringExpression;
use jj_lib::str_util::StringMatcher;
use jj_lib::str_util::StringPattern;
use jj_lib::transaction::Transaction;
use jj_lib::working_copy;
use jj_lib::working_copy::CheckoutStats;
use jj_lib::working_copy::LockedWorkingCopy;
use jj_lib::working_copy::SnapshotOptions;
use jj_lib::working_copy::SnapshotStats;
use jj_lib::working_copy::UntrackedReason;
use jj_lib::working_copy::WorkingCopy;
use jj_lib::working_copy::WorkingCopyFactory;
use jj_lib::working_copy::WorkingCopyFreshness;
use jj_lib::workspace::DefaultWorkspaceLoaderFactory;
use jj_lib::workspace::LockedWorkspace;
use jj_lib::workspace::WorkingCopyFactories;
use jj_lib::workspace::Workspace;
use jj_lib::workspace::WorkspaceLoadError;
use jj_lib::workspace::WorkspaceLoader;
use jj_lib::workspace::WorkspaceLoaderFactory;
use jj_lib::workspace::default_working_copy_factories;
use jj_lib::workspace::get_working_copy_factory;
use pollster::FutureExt as _;
use tracing::instrument;
use tracing_chrome::ChromeLayerBuilder;
use tracing_subscriber::prelude::*;
use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::command_error::config_error_with_message;
use crate::command_error::handle_command_result;
use crate::command_error::internal_error;
use crate::command_error::internal_error_with_message;
use crate::command_error::print_error_sources;
use crate::command_error::print_parse_diagnostics;
use crate::command_error::user_error;
use crate::command_error::user_error_with_message;
use crate::commit_templater::CommitTemplateLanguage;
use crate::commit_templater::CommitTemplateLanguageExtension;
use crate::complete;
use crate::config::ConfigArgKind;
use crate::config::ConfigEnv;
use crate::config::RawConfig;
use crate::config::config_from_environment;
use crate::config::load_aliases_map;
use crate::config::parse_config_args;
use crate::description_util::TextEditor;
use crate::diff_util;
use crate::diff_util::DiffFormat;
use crate::diff_util::DiffFormatArgs;
use crate::diff_util::DiffRenderer;
use crate::formatter::FormatRecorder;
use crate::formatter::Formatter;
use crate::formatter::FormatterExt as _;
use crate::merge_tools::DiffEditor;
use crate::merge_tools::MergeEditor;
use crate::merge_tools::MergeToolConfigError;
use crate::operation_templater::OperationTemplateLanguage;
use crate::operation_templater::OperationTemplateLanguageExtension;
use crate::revset_util;
use crate::revset_util::RevsetExpressionEvaluator;
use crate::revset_util::parse_union_name_patterns;
use crate::template_builder;
use crate::template_builder::TemplateLanguage;
use crate::template_parser::TemplateAliasesMap;
use crate::template_parser::TemplateDiagnostics;
use crate::templater::TemplateRenderer;
use crate::templater::WrapTemplateProperty;
use crate::text_util;
use crate::ui::ColorChoice;
use crate::ui::Ui;
const SHORT_CHANGE_ID_TEMPLATE_TEXT: &str = "format_short_change_id_with_change_offset(self)";
#[derive(Clone)]
struct ChromeTracingFlushGuard {
_inner: Option<Rc<tracing_chrome::FlushGuard>>,
}
impl Debug for ChromeTracingFlushGuard {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let Self { _inner } = self;
f.debug_struct("ChromeTracingFlushGuard")
.finish_non_exhaustive()
}
}
/// Handle to initialize or change tracing subscription.
#[derive(Clone, Debug)]
pub struct TracingSubscription {
reload_log_filter: tracing_subscriber::reload::Handle<
tracing_subscriber::EnvFilter,
tracing_subscriber::Registry,
>,
_chrome_tracing_flush_guard: ChromeTracingFlushGuard,
}
impl TracingSubscription {
const ENV_VAR_NAME: &str = "JJ_LOG";
/// Initializes tracing with the default configuration. This should be
/// called as early as possible.
pub fn init() -> Self {
let filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(tracing::metadata::LevelFilter::ERROR.into())
.with_env_var(Self::ENV_VAR_NAME)
.from_env_lossy();
let (filter, reload_log_filter) = tracing_subscriber::reload::Layer::new(filter);
let (chrome_tracing_layer, chrome_tracing_flush_guard) = match std::env::var("JJ_TRACE") {
Ok(filename) => {
let filename = if filename.is_empty() {
format!(
"jj-trace-{}.json",
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs(),
)
} else {
filename
};
let include_args = std::env::var("JJ_TRACE_INCLUDE_ARGS").is_ok();
let (layer, guard) = ChromeLayerBuilder::new()
.file(filename)
.include_args(include_args)
.build();
(
Some(layer),
ChromeTracingFlushGuard {
_inner: Some(Rc::new(guard)),
},
)
}
Err(_) => (None, ChromeTracingFlushGuard { _inner: None }),
};
tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::Layer::default()
.with_writer(std::io::stderr)
.with_filter(filter),
)
.with(chrome_tracing_layer)
.init();
Self {
reload_log_filter,
_chrome_tracing_flush_guard: chrome_tracing_flush_guard,
}
}
pub fn enable_debug_logging(&self) -> Result<(), CommandError> {
self.reload_log_filter
.modify(|filter| {
// The default is INFO.
// jj-lib and jj-cli are whitelisted for DEBUG logging.
// This ensures that other crates' logging doesn't show up by default.
*filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(tracing::metadata::LevelFilter::INFO.into())
.with_env_var(Self::ENV_VAR_NAME)
.from_env_lossy()
.add_directive("jj_lib=debug".parse().unwrap())
.add_directive("jj_cli=debug".parse().unwrap());
})
.map_err(|err| internal_error_with_message("failed to enable debug logging", err))?;
tracing::info!("debug logging enabled");
Ok(())
}
}
#[derive(Clone)]
pub struct CommandHelper {
data: Rc<CommandHelperData>,
}
struct CommandHelperData {
app: Command,
cwd: PathBuf,
string_args: Vec<String>,
matches: ArgMatches,
global_args: GlobalArgs,
config_env: ConfigEnv,
config_migrations: Vec<ConfigMigrationRule>,
raw_config: RawConfig,
settings: UserSettings,
revset_extensions: Arc<RevsetExtensions>,
commit_template_extensions: Vec<Arc<dyn CommitTemplateLanguageExtension>>,
operation_template_extensions: Vec<Arc<dyn OperationTemplateLanguageExtension>>,
maybe_workspace_loader: Result<Box<dyn WorkspaceLoader>, CommandError>,
store_factories: StoreFactories,
working_copy_factories: WorkingCopyFactories,
workspace_loader_factory: Box<dyn WorkspaceLoaderFactory>,
}
impl CommandHelper {
pub fn app(&self) -> &Command {
&self.data.app
}
/// Canonical form of the current working directory path.
///
/// A loaded `Workspace::workspace_root()` also returns a canonical path, so
/// relative paths can be easily computed from these paths.
pub fn cwd(&self) -> &Path {
&self.data.cwd
}
pub fn string_args(&self) -> &Vec<String> {
&self.data.string_args
}
pub fn matches(&self) -> &ArgMatches {
&self.data.matches
}
pub fn global_args(&self) -> &GlobalArgs {
&self.data.global_args
}
pub fn config_env(&self) -> &ConfigEnv {
&self.data.config_env
}
/// Unprocessed (or unresolved) configuration data.
///
/// Use this only if the unmodified config data is needed. For example, `jj
/// config set` should use this to write updated data back to file.
pub fn raw_config(&self) -> &RawConfig {
&self.data.raw_config
}
/// Settings for the current command and workspace.
///
/// This may be different from the settings for new workspace created by
/// e.g. `jj git init`. There may be conditional variables and repo config
/// loaded for the cwd workspace.
pub fn settings(&self) -> &UserSettings {
&self.data.settings
}
/// Resolves configuration for new workspace located at the specified path.
pub fn settings_for_new_workspace(
&self,
ui: &Ui,
workspace_root: &Path,
) -> Result<(UserSettings, ConfigEnv), CommandError> {
let mut config_env = self.data.config_env.clone();
let mut raw_config = self.data.raw_config.clone();
let repo_path = workspace_root.join(".jj").join("repo");
config_env.reset_repo_path(&repo_path);
config_env.reload_repo_config(ui, &mut raw_config)?;
config_env.reset_workspace_path(workspace_root);
config_env.reload_workspace_config(ui, &mut raw_config)?;
let mut config = config_env.resolve_config(&raw_config)?;
// No migration messages here, which would usually be emitted before.
jj_lib::config::migrate(&mut config, &self.data.config_migrations)?;
Ok((self.data.settings.with_new_config(config)?, config_env))
}
/// Loads text editor from the settings.
pub fn text_editor(&self) -> Result<TextEditor, ConfigGetError> {
TextEditor::from_settings(self.settings())
}
pub fn revset_extensions(&self) -> &Arc<RevsetExtensions> {
&self.data.revset_extensions
}
/// Parses template of the given language into evaluation tree.
///
/// This function also loads template aliases from the settings. Use
/// `WorkspaceCommandHelper::parse_template()` if you've already
/// instantiated the workspace helper.
pub fn parse_template<'a, C, L>(
&self,
ui: &Ui,
language: &L,
template_text: &str,
) -> Result<TemplateRenderer<'a, C>, CommandError>
where
C: Clone + 'a,
L: TemplateLanguage<'a> + ?Sized,
L::Property: WrapTemplateProperty<'a, C>,
{
let mut diagnostics = TemplateDiagnostics::new();
let aliases = load_template_aliases(ui, self.settings().config())?;
let template =
template_builder::parse(language, &mut diagnostics, template_text, &aliases)?;
print_parse_diagnostics(ui, "In template expression", &diagnostics)?;
Ok(template)
}
pub fn workspace_loader(&self) -> Result<&dyn WorkspaceLoader, CommandError> {
self.data
.maybe_workspace_loader
.as_deref()
.map_err(Clone::clone)
}
fn new_workspace_loader_at(
&self,
workspace_root: &Path,
) -> Result<Box<dyn WorkspaceLoader>, CommandError> {
self.data
.workspace_loader_factory
.create(workspace_root)
.map_err(|err| map_workspace_load_error(err, None))
}
/// Loads workspace and repo, then snapshots the working copy if allowed.
#[instrument(skip(self, ui))]
pub fn workspace_helper(&self, ui: &Ui) -> Result<WorkspaceCommandHelper, CommandError> {
let (workspace_command, stats) = self.workspace_helper_with_stats(ui)?;
print_snapshot_stats(ui, &stats, workspace_command.env().path_converter())?;
Ok(workspace_command)
}
/// Loads workspace and repo, then snapshots the working copy if allowed and
/// returns the SnapshotStats.
///
/// Note that unless you have a good reason not to do so, you should always
/// call [`print_snapshot_stats`] with the [`SnapshotStats`] returned by
/// this function to present possible untracked files to the user.
#[instrument(skip(self, ui))]
pub fn workspace_helper_with_stats(
&self,
ui: &Ui,
) -> Result<(WorkspaceCommandHelper, SnapshotStats), CommandError> {
let mut workspace_command = self.workspace_helper_no_snapshot(ui)?;
let (workspace_command, stats) = match workspace_command.maybe_snapshot_impl(ui).block_on()
{
Ok(stats) => (workspace_command, stats),
Err(SnapshotWorkingCopyError::Command(err)) => return Err(err),
Err(SnapshotWorkingCopyError::StaleWorkingCopy(err)) => {
let auto_update_stale = self.settings().get_bool("snapshot.auto-update-stale")?;
if !auto_update_stale {
return Err(err);
}
// We detected the working copy was stale and the client is configured to
// auto-update-stale, so let's do that now. We need to do it up here, not at a
// lower level (e.g. inside snapshot_working_copy()) to avoid recursive locking
// of the working copy.
self.recover_stale_working_copy(ui).block_on()?
}
};
Ok((workspace_command, stats))
}
/// Loads workspace and repo, but never snapshots the working copy. Most
/// commands should use `workspace_helper()` instead.
#[instrument(skip(self, ui))]
pub fn workspace_helper_no_snapshot(
&self,
ui: &Ui,
) -> Result<WorkspaceCommandHelper, CommandError> {
let workspace = self.load_workspace()?;
let op_head = self.resolve_operation(ui, workspace.repo_loader())?;
let repo = workspace.repo_loader().load_at(&op_head).block_on()?;
let mut env = self.workspace_environment(ui, &workspace)?;
if let Err(err) =
revset_util::try_resolve_trunk_alias(repo.as_ref(), &env.revset_parse_context())
{
// The fallback can be builtin_trunk() if we're willing to support
// inferred trunk forever. (#7990)
let fallback = "root()";
writeln!(
ui.warning_default(),
"Failed to resolve `revset-aliases.trunk()`: {err}"
)?;
writeln!(
ui.warning_no_heading(),
"The `trunk()` alias is temporarily set to `{fallback}`."
)?;
writeln!(
ui.hint_default(),
"Use `jj config edit --repo` to adjust the `trunk()` alias."
)?;
env.revset_aliases_map
.insert("trunk()", fallback)
.expect("valid syntax");
env.reload_revset_expressions(ui)?;
}
WorkspaceCommandHelper::new(ui, workspace, repo, env, self.is_at_head_operation())
}
pub fn get_working_copy_factory(&self) -> Result<&dyn WorkingCopyFactory, CommandError> {
let loader = self.workspace_loader()?;
// We convert StoreLoadError -> WorkspaceLoadError -> CommandError
let factory: Result<_, WorkspaceLoadError> =
get_working_copy_factory(loader, &self.data.working_copy_factories)
.map_err(|e| e.into());
let factory = factory.map_err(|err| {
map_workspace_load_error(err, self.data.global_args.repository.as_deref())
})?;
Ok(factory)
}
/// Loads workspace for the current command.
#[instrument(skip_all)]
pub fn load_workspace(&self) -> Result<Workspace, CommandError> {
let loader = self.workspace_loader()?;
loader
.load(
&self.data.settings,
&self.data.store_factories,
&self.data.working_copy_factories,
)
.map_err(|err| {
map_workspace_load_error(err, self.data.global_args.repository.as_deref())
})
}
/// Loads workspace located at the specified path.
#[instrument(skip(self, settings))]
pub fn load_workspace_at(
&self,
workspace_root: &Path,
settings: &UserSettings,
) -> Result<Workspace, CommandError> {
let loader = self.new_workspace_loader_at(workspace_root)?;
loader
.load(
settings,
&self.data.store_factories,
&self.data.working_copy_factories,
)
.map_err(|err| map_workspace_load_error(err, None))
}
/// Note that unless you have a good reason not to do so, you should always
/// call [`print_snapshot_stats`] with the [`SnapshotStats`] returned by
/// this function to present possible untracked files to the user.
pub async fn recover_stale_working_copy(
&self,
ui: &Ui,
) -> Result<(WorkspaceCommandHelper, SnapshotStats), CommandError> {
let workspace = self.load_workspace()?;
let op_id = workspace.working_copy().operation_id();
match workspace.repo_loader().load_operation(op_id).await {
Ok(op) => {
let repo = workspace.repo_loader().load_at(&op).await?;
let mut workspace_command = self.for_workable_repo(ui, workspace, repo)?;
workspace_command.check_working_copy_writable()?;
// Snapshot the current working copy on top of the last known working-copy
// operation, then merge the divergent operations. The wc_commit_id of the
// merged repo wouldn't change because the old one wins, but it's probably
// fine if we picked the new wc_commit_id.
let stale_stats = workspace_command
.snapshot_working_copy(ui)
.await
.map_err(|err| err.into_command_error())?;
let wc_commit_id = workspace_command.get_wc_commit_id().unwrap();
let repo = workspace_command.repo().clone();
let stale_wc_commit = repo.store().get_commit_async(wc_commit_id).await?;
let mut workspace_command = self.workspace_helper_no_snapshot(ui)?;
let repo = workspace_command.repo().clone();
let (mut locked_ws, desired_wc_commit) =
workspace_command.unchecked_start_working_copy_mutation()?;
match WorkingCopyFreshness::check_stale(
locked_ws.locked_wc(),
&desired_wc_commit,
&repo,
)
.await?
{
WorkingCopyFreshness::Fresh | WorkingCopyFreshness::Updated(_) => {
drop(locked_ws);
writeln!(
ui.status(),
"Attempted recovery, but the working copy is not stale"
)?;
}
WorkingCopyFreshness::WorkingCopyStale
| WorkingCopyFreshness::SiblingOperation => {
let stats = update_stale_working_copy(
locked_ws,
repo.op_id().clone(),
&stale_wc_commit,
&desired_wc_commit,
)
.await?;
workspace_command.print_updated_working_copy_stats(
ui,
Some(&stale_wc_commit),
&desired_wc_commit,
&stats,
)?;
writeln!(
ui.status(),
"Updated working copy to fresh commit {}",
short_commit_hash(desired_wc_commit.id())
)?;
}
}
// There may be Git refs to import, so snapshot again. Git HEAD
// will also be imported if it was updated after the working
// copy became stale. The result wouldn't be ideal, but there
// should be no data loss at least.
let fresh_stats = workspace_command
.maybe_snapshot_impl(ui)
.await
.map_err(|err| err.into_command_error())?;
let merged_stats = {
let SnapshotStats {
mut untracked_paths,
} = stale_stats;
untracked_paths.extend(fresh_stats.untracked_paths);
SnapshotStats { untracked_paths }
};
Ok((workspace_command, merged_stats))
}
Err(e @ OpStoreError::ObjectNotFound { .. }) => {
writeln!(
ui.status(),
"Failed to read working copy's current operation; attempting recovery. Error \
message from read attempt: {e}"
)?;
let mut workspace_command = self.workspace_helper_no_snapshot(ui)?;
let stats = workspace_command
.create_and_check_out_recovery_commit(ui)
.await?;
Ok((workspace_command, stats))
}
Err(e) => Err(e.into()),
}
}
/// Loads command environment for the given `workspace`.
pub fn workspace_environment(
&self,
ui: &Ui,
workspace: &Workspace,
) -> Result<WorkspaceCommandEnvironment, CommandError> {
WorkspaceCommandEnvironment::new(ui, self, workspace)
}
/// Returns true if the working copy to be loaded is writable, and therefore
/// should usually be snapshotted.
pub fn is_working_copy_writable(&self) -> bool {
self.is_at_head_operation() && !self.data.global_args.ignore_working_copy
}
/// Returns true if the current operation is considered to be the head.
pub fn is_at_head_operation(&self) -> bool {
// TODO: should we accept --at-op=<head_id> as the head op? or should we
// make --at-op=@ imply --ignore-working-copy (i.e. not at the head.)
matches!(
self.data.global_args.at_operation.as_deref(),
None | Some("@")
)
}
/// Resolves the current operation from the command-line argument.
///
/// If no `--at-operation` is specified, the head operations will be
/// loaded. If there are multiple heads, they'll be merged.
#[instrument(skip_all)]
pub fn resolve_operation(
&self,
ui: &Ui,
repo_loader: &RepoLoader,
) -> Result<Operation, CommandError> {
if let Some(op_str) = &self.data.global_args.at_operation {
Ok(op_walk::resolve_op_for_load(repo_loader, op_str).block_on()?)
} else {
op_heads_store::resolve_op_heads(
repo_loader.op_heads_store().as_ref(),
repo_loader.op_store(),
async |op_heads| {
writeln!(
ui.status(),
"Concurrent modification detected, resolving automatically.",
)?;
let base_repo = repo_loader.load_at(&op_heads[0]).block_on()?;
// TODO: It may be helpful to print each operation we're merging here
let mut tx = start_repo_transaction(&base_repo, &self.data.string_args);
for other_op_head in op_heads.into_iter().skip(1) {
tx.merge_operation(other_op_head).await?;
let num_rebased = tx.repo_mut().rebase_descendants().await?;
if num_rebased > 0 {
writeln!(
ui.status(),
"Rebased {num_rebased} descendant commits onto commits rewritten \
by other operation"
)?;
}
}
Ok(tx
.write("reconcile divergent operations")
.await?
.leave_unpublished()
.operation()
.clone())
},
)
.block_on()
}
}
/// Creates helper for the repo whose view is supposed to be in sync with
/// the working copy. If `--ignore-working-copy` is not specified, the
/// returned helper will attempt to update the working copy.
#[instrument(skip_all)]
pub fn for_workable_repo(
&self,
ui: &Ui,
workspace: Workspace,
repo: Arc<ReadonlyRepo>,
) -> Result<WorkspaceCommandHelper, CommandError> {
let env = self.workspace_environment(ui, &workspace)?;
let loaded_at_head = true;
WorkspaceCommandHelper::new(ui, workspace, repo, env, loaded_at_head)
}
}
/// A ReadonlyRepo along with user-config-dependent derived data. The derived
/// data is lazily loaded.
struct ReadonlyUserRepo {
repo: Arc<ReadonlyRepo>,
id_prefix_context: OnceCell<IdPrefixContext>,
}
impl ReadonlyUserRepo {
fn new(repo: Arc<ReadonlyRepo>) -> Self {
Self {
repo,
id_prefix_context: OnceCell::new(),
}
}
}
/// A advanceable bookmark to satisfy the "advance-bookmarks" feature.
///
/// This is a helper for `WorkspaceCommandTransaction`. It provides a
/// type-safe way to separate the work of checking whether a bookmark
/// can be advanced and actually advancing it. Advancing the bookmark
/// never fails, but can't be done until the new `CommitId` is
/// available. Splitting the work in this way also allows us to
/// identify eligible bookmarks without actually moving them and
/// return config errors to the user early.
pub struct AdvanceableBookmark {
name: RefNameBuf,
old_commit_id: CommitId,
}
/// Parses advance-bookmarks settings into matcher.
///
/// Settings are configured in the jj config.toml as lists of string matcher
/// expressions for enabled and disabled bookmarks. Example:
/// ```toml
/// [experimental-advance-branches]
/// # Enable the feature for all branches except "main".
/// enabled-branches = ["*"]
/// disabled-branches = ["main"]
/// ```
fn load_advance_bookmarks_matcher(
ui: &Ui,
settings: &UserSettings,
) -> Result<Option<StringMatcher>, CommandError> {
let get_setting = |setting_key: &str| -> Result<Vec<String>, _> {
let name = ConfigNamePathBuf::from_iter(["experimental-advance-branches", setting_key]);
settings.get(&name)
};
// TODO: When we stabilize this feature, enabled/disabled patterns can be
// combined into a single matcher expression.
let enabled_names = get_setting("enabled-branches")?;
let disabled_names = get_setting("disabled-branches")?;
let enabled_expr = parse_union_name_patterns(ui, &enabled_names)?;
let disabled_expr = parse_union_name_patterns(ui, &disabled_names)?;
if enabled_names.is_empty() {
Ok(None)
} else {
let expr = enabled_expr.intersection(disabled_expr.negated());
Ok(Some(expr.to_matcher()))
}
}
/// Metadata and configuration loaded for a specific workspace.
pub struct WorkspaceCommandEnvironment {
command: CommandHelper,
settings: UserSettings,
fileset_aliases_map: FilesetAliasesMap,
revset_aliases_map: RevsetAliasesMap,
template_aliases_map: TemplateAliasesMap,
default_ignored_remote: Option<&'static RemoteName>,
revsets_use_glob_by_default: bool,
path_converter: RepoPathUiConverter,
workspace_name: WorkspaceNameBuf,
immutable_heads_expression: Arc<UserRevsetExpression>,
short_prefixes_expression: Option<Arc<UserRevsetExpression>>,
conflict_marker_style: ConflictMarkerStyle,
}
impl WorkspaceCommandEnvironment {
#[instrument(skip_all)]
fn new(ui: &Ui, command: &CommandHelper, workspace: &Workspace) -> Result<Self, CommandError> {
let settings = workspace.settings();
let fileset_aliases_map = load_fileset_aliases(ui, settings.config())?;
let revset_aliases_map = load_revset_aliases(ui, settings.config())?;
let template_aliases_map = load_template_aliases(ui, settings.config())?;
let default_ignored_remote = default_ignored_remote_name(workspace.repo_loader().store());
let path_converter = RepoPathUiConverter::Fs {
cwd: command.cwd().to_owned(),
base: workspace.workspace_root().to_owned(),
};
let mut env = Self {
command: command.clone(),
settings: settings.clone(),
fileset_aliases_map,
revset_aliases_map,
template_aliases_map,
default_ignored_remote,
revsets_use_glob_by_default: settings.get("ui.revsets-use-glob-by-default")?,
path_converter,
workspace_name: workspace.workspace_name().to_owned(),
immutable_heads_expression: RevsetExpression::root(),
short_prefixes_expression: None,
conflict_marker_style: settings.get("ui.conflict-marker-style")?,
};
env.reload_revset_expressions(ui)?;
Ok(env)
}
pub(crate) fn path_converter(&self) -> &RepoPathUiConverter {
&self.path_converter
}
pub fn workspace_name(&self) -> &WorkspaceName {
&self.workspace_name
}
/// Parsing context for fileset expressions specified by command arguments.
pub(crate) fn fileset_parse_context(&self) -> FilesetParseContext<'_> {
FilesetParseContext {
aliases_map: &self.fileset_aliases_map,
path_converter: &self.path_converter,
}
}
/// Parsing context for fileset expressions loaded from config files.
pub(crate) fn fileset_parse_context_for_config(&self) -> FilesetParseContext<'_> {
// TODO: bump MSRV to 1.91.0 to leverage const PathBuf::new()
static ROOT_PATH_CONVERTER: LazyLock<RepoPathUiConverter> =
LazyLock::new(|| RepoPathUiConverter::Fs {
cwd: PathBuf::new(),
base: PathBuf::new(),
});
FilesetParseContext {
aliases_map: &self.fileset_aliases_map,
path_converter: &ROOT_PATH_CONVERTER,
}
}
pub(crate) fn revset_parse_context(&self) -> RevsetParseContext<'_> {
let workspace_context = RevsetWorkspaceContext {
path_converter: &self.path_converter,
workspace_name: &self.workspace_name,
};
let now = if let Some(timestamp) = self.settings.commit_timestamp() {
chrono::Local
.timestamp_millis_opt(timestamp.timestamp.0)
.unwrap()
} else {
chrono::Local::now()
};
RevsetParseContext {
aliases_map: &self.revset_aliases_map,
local_variables: HashMap::new(),
user_email: self.settings.user_email(),
date_pattern_context: now.into(),
default_ignored_remote: self.default_ignored_remote,
fileset_aliases_map: &self.fileset_aliases_map,
use_glob_by_default: self.revsets_use_glob_by_default,
extensions: self.command.revset_extensions(),
workspace: Some(workspace_context),
}
}
/// Creates fresh new context which manages cache of short commit/change ID
/// prefixes. New context should be created per repo view (or operation.)
pub fn new_id_prefix_context(&self) -> IdPrefixContext {
let context = IdPrefixContext::new(self.command.revset_extensions().clone());
match &self.short_prefixes_expression {
None => context,
Some(expression) => context.disambiguate_within(expression.clone()),
}
}
/// Updates parsed revset expressions.
fn reload_revset_expressions(&mut self, ui: &Ui) -> Result<(), CommandError> {
self.immutable_heads_expression = self.load_immutable_heads_expression(ui)?;
self.short_prefixes_expression = self.load_short_prefixes_expression(ui)?;
Ok(())
}
/// User-configured expression defining the immutable set.
pub fn immutable_expression(&self) -> Arc<UserRevsetExpression> {
// Negated ancestors expression `~::(<heads> | root())` is slightly
// easier to optimize than negated union `~(::<heads> | root())`.
self.immutable_heads_expression.ancestors()
}
/// User-configured expression defining the heads of the immutable set.
pub fn immutable_heads_expression(&self) -> &Arc<UserRevsetExpression> {
&self.immutable_heads_expression
}
/// User-configured conflict marker style for materializing conflicts
pub fn conflict_marker_style(&self) -> ConflictMarkerStyle {
self.conflict_marker_style
}
fn load_immutable_heads_expression(
&self,
ui: &Ui,
) -> Result<Arc<UserRevsetExpression>, CommandError> {
let mut diagnostics = RevsetDiagnostics::new();
let expression = revset_util::parse_immutable_heads_expression(
&mut diagnostics,
&self.revset_parse_context(),
)
.map_err(|e| config_error_with_message("Invalid `revset-aliases.immutable_heads()`", e))?;
print_parse_diagnostics(ui, "In `revset-aliases.immutable_heads()`", &diagnostics)?;
Ok(expression)
}
fn load_short_prefixes_expression(
&self,
ui: &Ui,
) -> Result<Option<Arc<UserRevsetExpression>>, CommandError> {
let revset_string = self
.settings
.get_string("revsets.short-prefixes")
.optional()?
.map_or_else(|| self.settings.get_string("revsets.log"), Ok)?;
if revset_string.is_empty() {
Ok(None)
} else {
let mut diagnostics = RevsetDiagnostics::new();
let expression = revset::parse(
&mut diagnostics,
&revset_string,
&self.revset_parse_context(),
)
.map_err(|err| config_error_with_message("Invalid `revsets.short-prefixes`", err))?;
print_parse_diagnostics(ui, "In `revsets.short-prefixes`", &diagnostics)?;
Ok(Some(expression))
}
}
/// Returns first immutable commit.
fn find_immutable_commit(
&self,
repo: &dyn Repo,
to_rewrite_expr: &Arc<ResolvedRevsetExpression>,
) -> Result<Option<CommitId>, CommandError> {
let immutable_expression = if self.command.global_args().ignore_immutable {
UserRevsetExpression::root()
} else {
self.immutable_expression()
};
// Not using self.id_prefix_context() because the disambiguation data