-
Notifications
You must be signed in to change notification settings - Fork 349
/
cli_util.rs
3048 lines (2813 loc) · 115 KB
/
cli_util.rs
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 core::fmt;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashSet};
use std::env::{self, ArgsOs, VarError};
use std::ffi::OsString;
use std::fmt::Debug;
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::rc::Rc;
use std::str::FromStr;
use std::sync::Arc;
use std::time::SystemTime;
use std::{fs, mem, str};
use bstr::ByteVec as _;
use chrono::TimeZone;
use clap::builder::{
MapValueParser, NonEmptyStringValueParser, TypedValueParser, ValueParserFactory,
};
use clap::error::{ContextKind, ContextValue};
use clap::{ArgAction, ArgMatches, Command, FromArgMatches};
use indexmap::{IndexMap, IndexSet};
use itertools::Itertools;
use jj_lib::backend::{ChangeId, CommitId, MergedTreeId, TreeValue};
use jj_lib::commit::Commit;
use jj_lib::fileset::FilesetExpression;
use jj_lib::git_backend::GitBackend;
use jj_lib::gitignore::{GitIgnoreError, GitIgnoreFile};
use jj_lib::hex_util::to_reverse_hex;
use jj_lib::id_prefix::IdPrefixContext;
use jj_lib::matchers::Matcher;
use jj_lib::merge::MergedTreeValue;
use jj_lib::merged_tree::MergedTree;
use jj_lib::object_id::ObjectId;
use jj_lib::op_store::{OpStoreError, OperationId, RefTarget, WorkspaceId};
use jj_lib::op_walk::OpsetEvaluationError;
use jj_lib::operation::Operation;
use jj_lib::repo::{
merge_factories_map, CheckOutCommitError, EditCommitError, MutableRepo, ReadonlyRepo, Repo,
RepoLoader, StoreFactories, StoreLoadError,
};
use jj_lib::repo_path::{RepoPath, RepoPathBuf, RepoPathUiConverter, UiPathParseError};
use jj_lib::revset::{
RevsetAliasesMap, RevsetExpression, RevsetExtensions, RevsetFilterPredicate, RevsetFunction,
RevsetIteratorExt, RevsetModifier, RevsetParseContext, RevsetWorkspaceContext,
SymbolResolverExtension,
};
use jj_lib::rewrite::restore_tree;
use jj_lib::settings::{ConfigResultExt as _, UserSettings};
use jj_lib::signing::SignInitError;
use jj_lib::str_util::StringPattern;
use jj_lib::transaction::Transaction;
use jj_lib::view::View;
use jj_lib::working_copy::{
CheckoutStats, LockedWorkingCopy, SnapshotOptions, WorkingCopy, WorkingCopyFactory,
};
use jj_lib::workspace::{
default_working_copy_factories, LockedWorkspace, WorkingCopyFactories, Workspace,
WorkspaceLoadError, WorkspaceLoader,
};
use jj_lib::{dag_walk, fileset, git, op_heads_store, op_walk, revset};
use once_cell::unsync::OnceCell;
use tracing::instrument;
use tracing_chrome::ChromeLayerBuilder;
use tracing_subscriber::prelude::*;
use crate::command_error::{
cli_error, config_error_with_message, handle_command_result, internal_error,
internal_error_with_message, user_error, user_error_with_hint, user_error_with_message,
CommandError,
};
use crate::commit_templater::{CommitTemplateLanguage, CommitTemplateLanguageExtension};
use crate::config::{
new_config_path, AnnotatedValue, CommandNameAndArgs, ConfigNamePathBuf, ConfigSource,
LayeredConfigs,
};
use crate::diff_util::{self, DiffFormat, DiffFormatArgs, DiffRenderer};
use crate::formatter::{FormatRecorder, Formatter, PlainTextFormatter};
use crate::git_util::{
is_colocated_git_workspace, print_failed_git_export, print_git_import_stats,
};
use crate::merge_tools::{DiffEditor, MergeEditor, MergeToolConfigError};
use crate::operation_templater::OperationTemplateLanguageExtension;
use crate::revset_util::RevsetExpressionEvaluator;
use crate::template_builder::TemplateLanguage;
use crate::template_parser::TemplateAliasesMap;
use crate::templater::{PropertyPlaceholder, TemplateRenderer};
use crate::ui::{ColorChoice, Ui};
use crate::{revset_util, template_builder, text_util};
#[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 {
/// 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())
.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();
TracingSubscription {
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| {
*filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(tracing::metadata::LevelFilter::DEBUG.into())
.from_env_lossy()
})
.map_err(|err| internal_error_with_message("failed to enable debug logging", err))?;
tracing::info!("debug logging enabled");
Ok(())
}
}
pub struct CommandHelper {
app: Command,
cwd: PathBuf,
string_args: Vec<String>,
matches: ArgMatches,
global_args: GlobalArgs,
settings: UserSettings,
layered_configs: LayeredConfigs,
revset_extensions: Arc<RevsetExtensions>,
commit_template_extensions: Vec<Arc<dyn CommitTemplateLanguageExtension>>,
operation_template_extensions: Vec<Arc<dyn OperationTemplateLanguageExtension>>,
maybe_workspace_loader: Result<WorkspaceLoader, CommandError>,
store_factories: StoreFactories,
working_copy_factories: WorkingCopyFactories,
}
impl CommandHelper {
pub fn app(&self) -> &Command {
&self.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.cwd
}
pub fn string_args(&self) -> &Vec<String> {
&self.string_args
}
pub fn matches(&self) -> &ArgMatches {
&self.matches
}
pub fn global_args(&self) -> &GlobalArgs {
&self.global_args
}
pub fn settings(&self) -> &UserSettings {
&self.settings
}
pub fn resolved_config_values(
&self,
prefix: &ConfigNamePathBuf,
) -> Result<Vec<AnnotatedValue>, crate::config::ConfigError> {
self.layered_configs.resolved_config_values(prefix)
}
pub fn revset_extensions(&self) -> &Arc<RevsetExtensions> {
&self.revset_extensions
}
/// Loads template aliases from the configs.
///
/// For most commands that depend on a loaded repo, you should use
/// `WorkspaceCommandHelper::template_aliases_map()` instead.
fn load_template_aliases(&self, ui: &Ui) -> Result<TemplateAliasesMap, CommandError> {
load_template_aliases(ui, &self.layered_configs)
}
/// 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: Clone + 'a, L: TemplateLanguage<'a> + ?Sized>(
&self,
ui: &Ui,
language: &L,
template_text: &str,
wrap_self: impl Fn(PropertyPlaceholder<C>) -> L::Property,
) -> Result<TemplateRenderer<'a, C>, CommandError> {
let aliases = self.load_template_aliases(ui)?;
Ok(template_builder::parse(
language,
template_text,
&aliases,
wrap_self,
)?)
}
pub fn operation_template_extensions(&self) -> &[Arc<dyn OperationTemplateLanguageExtension>] {
&self.operation_template_extensions
}
pub fn workspace_loader(&self) -> Result<&WorkspaceLoader, CommandError> {
self.maybe_workspace_loader.as_ref().map_err(Clone::clone)
}
/// Loads workspace and repo, then snapshots the working copy if allowed.
#[instrument(skip(self, ui))]
pub fn workspace_helper(&self, ui: &mut Ui) -> Result<WorkspaceCommandHelper, CommandError> {
let mut workspace_command = self.workspace_helper_no_snapshot(ui)?;
workspace_command.maybe_snapshot(ui)?;
Ok(workspace_command)
}
/// 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: &mut 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)?;
WorkspaceCommandHelper::new(ui, self, workspace, repo, 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> = loader
.get_working_copy_factory(&self.working_copy_factories)
.map_err(|e| e.into());
let factory = factory
.map_err(|err| map_workspace_load_error(err, self.global_args.repository.as_deref()))?;
Ok(factory)
}
#[instrument(skip_all)]
pub fn load_workspace(&self) -> Result<Workspace, CommandError> {
let loader = self.workspace_loader()?;
loader
.load(
&self.settings,
&self.store_factories,
&self.working_copy_factories,
)
.map_err(|err| map_workspace_load_error(err, self.global_args.repository.as_deref()))
}
/// 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.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-workign-copy (i.e. not at the head.)
matches!(self.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: &mut Ui,
repo_loader: &RepoLoader,
) -> Result<Operation, CommandError> {
if let Some(op_str) = &self.global_args.at_operation {
Ok(op_walk::resolve_op_for_load(repo_loader, op_str)?)
} else {
op_heads_store::resolve_op_heads(
repo_loader.op_heads_store().as_ref(),
repo_loader.op_store(),
|op_heads| {
writeln!(
ui.status(),
"Concurrent modification detected, resolving automatically.",
)?;
let base_repo = repo_loader.load_at(&op_heads[0])?;
// TODO: It may be helpful to print each operation we're merging here
let mut tx =
start_repo_transaction(&base_repo, &self.settings, &self.string_args);
for other_op_head in op_heads.into_iter().skip(1) {
tx.merge_operation(other_op_head)?;
let num_rebased = tx.mut_repo().rebase_descendants(&self.settings)?;
if num_rebased > 0 {
writeln!(
ui.status(),
"Rebased {num_rebased} descendant commits onto commits rewritten \
by other operation"
)?;
}
}
Ok(tx
.write("resolve concurrent operations")
.leave_unpublished()
.operation()
.clone())
},
)
}
}
/// 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: &mut Ui,
workspace: Workspace,
repo: Arc<ReadonlyRepo>,
) -> Result<WorkspaceCommandHelper, CommandError> {
let loaded_at_head = true;
WorkspaceCommandHelper::new(ui, self, workspace, repo, loaded_at_head)
}
/// Creates helper for the repo whose view might be out of sync with
/// the working copy. Therefore, the working copy should not be updated.
#[instrument(skip_all)]
pub fn for_temporary_repo(
&self,
ui: &mut Ui,
workspace: Workspace,
repo: Arc<ReadonlyRepo>,
) -> Result<WorkspaceCommandHelper, CommandError> {
let loaded_at_head = false;
WorkspaceCommandHelper::new(ui, self, workspace, repo, 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(),
}
}
pub fn git_backend(&self) -> Option<&GitBackend> {
self.repo.store().backend_impl().downcast_ref()
}
}
/// A branch that should be advanced to satisfy the "advance-branches" feature.
/// This is a helper for `WorkspaceCommandTransaction`. It provides a type-safe
/// way to separate the work of checking whether a branch can be advanced and
/// actually advancing it. Advancing the branch 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 branches without actually moving them and
/// return config errors to the user early.
pub struct AdvanceableBranch {
name: String,
old_commit_id: CommitId,
}
/// Helper for parsing and evaluating settings for the advance-branches feature.
/// Settings are configured in the jj config.toml as lists of [`StringPattern`]s
/// for enabled and disabled branches. Example:
/// ```toml
/// [experimental-advance-branches]
/// # Enable the feature for all branches except "main".
/// enabled-branches = ["glob:*"]
/// disabled-branches = ["main"]
/// ```
struct AdvanceBranchesSettings {
enabled_branches: Vec<StringPattern>,
disabled_branches: Vec<StringPattern>,
}
impl AdvanceBranchesSettings {
fn from_config(config: &config::Config) -> Result<Self, CommandError> {
let get_setting = |setting_key| {
let setting = format!("experimental-advance-branches.{setting_key}");
match config.get::<Vec<String>>(&setting).optional()? {
Some(patterns) => patterns
.into_iter()
.map(|s| {
StringPattern::parse(&s).map_err(|e| {
config_error_with_message(
format!("Error parsing '{s}' for {setting}"),
e,
)
})
})
.collect(),
None => Ok(Vec::new()),
}
};
Ok(Self {
enabled_branches: get_setting("enabled-branches")?,
disabled_branches: get_setting("disabled-branches")?,
})
}
/// Returns true if the advance-branches feature is enabled for
/// `branch_name`.
fn branch_is_eligible(&self, branch_name: &str) -> bool {
if self
.disabled_branches
.iter()
.any(|d| d.matches(branch_name))
{
return false;
}
self.enabled_branches.iter().any(|e| e.matches(branch_name))
}
/// Returns true if the config includes at least one "enabled-branches"
/// pattern.
fn feature_enabled(&self) -> bool {
!self.enabled_branches.is_empty()
}
}
/// Provides utilities for writing a command that works on a [`Workspace`]
/// (which most commands do).
pub struct WorkspaceCommandHelper {
string_args: Vec<String>,
global_args: GlobalArgs,
settings: UserSettings,
workspace: Workspace,
user_repo: ReadonlyUserRepo,
revset_extensions: Arc<RevsetExtensions>,
// TODO: Parsed template can be cached if it doesn't capture 'repo lifetime
commit_summary_template_text: String,
commit_template_extensions: Vec<Arc<dyn CommitTemplateLanguageExtension>>,
revset_aliases_map: RevsetAliasesMap,
template_aliases_map: TemplateAliasesMap,
may_update_working_copy: bool,
working_copy_shared_with_git: bool,
path_converter: RepoPathUiConverter,
}
impl WorkspaceCommandHelper {
#[instrument(skip_all)]
fn new(
ui: &mut Ui,
command: &CommandHelper,
workspace: Workspace,
repo: Arc<ReadonlyRepo>,
loaded_at_head: bool,
) -> Result<Self, CommandError> {
let settings = command.settings.clone();
let commit_summary_template_text =
settings.config().get_string("templates.commit_summary")?;
let revset_aliases_map = revset_util::load_revset_aliases(ui, &command.layered_configs)?;
let template_aliases_map = command.load_template_aliases(ui)?;
let may_update_working_copy = loaded_at_head && !command.global_args.ignore_working_copy;
let working_copy_shared_with_git = is_colocated_git_workspace(&workspace, &repo);
let path_converter = RepoPathUiConverter::Fs {
cwd: command.cwd.clone(),
base: workspace.workspace_root().clone(),
};
let helper = Self {
string_args: command.string_args.clone(),
global_args: command.global_args.clone(),
settings,
workspace,
user_repo: ReadonlyUserRepo::new(repo),
revset_extensions: command.revset_extensions.clone(),
commit_summary_template_text,
commit_template_extensions: command.commit_template_extensions.clone(),
revset_aliases_map,
template_aliases_map,
may_update_working_copy,
working_copy_shared_with_git,
path_converter,
};
// Parse commit_summary template (and short-prefixes revset) early to
// report error before starting mutable operation.
helper.parse_commit_template(&helper.commit_summary_template_text)?;
Ok(helper)
}
pub fn git_backend(&self) -> Option<&GitBackend> {
self.user_repo.git_backend()
}
pub fn check_working_copy_writable(&self) -> Result<(), CommandError> {
if self.may_update_working_copy {
Ok(())
} else {
let hint = if self.global_args.ignore_working_copy {
"Don't use --ignore-working-copy."
} else {
"Don't use --at-op."
};
Err(user_error_with_hint(
"This command must be able to update the working copy.",
hint,
))
}
}
/// Snapshot the working copy if allowed, and import Git refs if the working
/// copy is collocated with Git.
#[instrument(skip_all)]
pub fn maybe_snapshot(&mut self, ui: &mut Ui) -> Result<(), CommandError> {
if self.may_update_working_copy {
if self.working_copy_shared_with_git {
self.import_git_head(ui)?;
}
// Because the Git refs (except HEAD) aren't imported yet, the ref
// pointing to the new working-copy commit might not be exported.
// In that situation, the ref would be conflicted anyway, so export
// failure is okay.
self.snapshot_working_copy(ui)?;
// import_git_refs() can rebase the working-copy commit.
if self.working_copy_shared_with_git {
self.import_git_refs(ui)?;
}
}
Ok(())
}
/// Imports new HEAD from the colocated Git repo.
///
/// If the Git HEAD has changed, this function checks out the new Git HEAD.
/// The old working-copy commit will be abandoned if it's discardable. The
/// working-copy state will be reset to point to the new Git HEAD. The
/// working-copy contents won't be updated.
#[instrument(skip_all)]
fn import_git_head(&mut self, ui: &mut Ui) -> Result<(), CommandError> {
assert!(self.may_update_working_copy);
let mut tx = self.start_transaction();
git::import_head(tx.mut_repo())?;
if !tx.mut_repo().has_changes() {
return Ok(());
}
// TODO: There are various ways to get duplicated working-copy
// commits. Some of them could be mitigated by checking the working-copy
// operation id after acquiring the lock, but that isn't enough.
//
// - moved HEAD was observed by multiple jj processes, and new working-copy
// commits are created concurrently.
// - new HEAD was exported by jj, but the operation isn't committed yet.
// - new HEAD was exported by jj, but the new working-copy commit isn't checked
// out yet.
let mut tx = tx.into_inner();
let old_git_head = self.repo().view().git_head().clone();
let new_git_head = tx.mut_repo().view().git_head().clone();
if let Some(new_git_head_id) = new_git_head.as_normal() {
let workspace_id = self.workspace_id().to_owned();
let new_git_head_commit = tx.mut_repo().store().get_commit(new_git_head_id)?;
tx.mut_repo()
.check_out(workspace_id, &self.settings, &new_git_head_commit)?;
let mut locked_ws = self.workspace.start_working_copy_mutation()?;
// The working copy was presumably updated by the git command that updated
// HEAD, so we just need to reset our working copy
// state to it without updating working copy files.
locked_ws.locked_wc().reset(&new_git_head_commit)?;
tx.mut_repo().rebase_descendants(&self.settings)?;
self.user_repo = ReadonlyUserRepo::new(tx.commit("import git head"));
locked_ws.finish(self.user_repo.repo.op_id().clone())?;
if old_git_head.is_present() {
writeln!(
ui.status(),
"Reset the working copy parent to the new Git HEAD."
)?;
} else {
// Don't print verbose message on initial checkout.
}
} else {
// Unlikely, but the HEAD ref got deleted by git?
self.finish_transaction(ui, tx, "import git head")?;
}
Ok(())
}
/// Imports branches and tags from the underlying Git repo, abandons old
/// branches.
///
/// If the working-copy branch is rebased, and if update is allowed, the new
/// working-copy commit will be checked out.
///
/// This function does not import the Git HEAD, but the HEAD may be reset to
/// the working copy parent if the repository is colocated.
#[instrument(skip_all)]
fn import_git_refs(&mut self, ui: &mut Ui) -> Result<(), CommandError> {
let git_settings = self.settings.git_settings();
let mut tx = self.start_transaction();
// Automated import shouldn't fail because of reserved remote name.
let stats = git::import_some_refs(tx.mut_repo(), &git_settings, |ref_name| {
!git::is_reserved_git_remote_ref(ref_name)
})?;
if !tx.mut_repo().has_changes() {
return Ok(());
}
print_git_import_stats(ui, tx.repo(), &stats, false)?;
let mut tx = tx.into_inner();
// Rebase here to show slightly different status message.
let num_rebased = tx.mut_repo().rebase_descendants(&self.settings)?;
if num_rebased > 0 {
writeln!(
ui.status(),
"Rebased {num_rebased} descendant commits off of commits rewritten from git"
)?;
}
self.finish_transaction(ui, tx, "import git refs")?;
writeln!(
ui.status(),
"Done importing changes from the underlying Git repo."
)?;
Ok(())
}
pub fn repo(&self) -> &Arc<ReadonlyRepo> {
&self.user_repo.repo
}
pub fn working_copy(&self) -> &dyn WorkingCopy {
self.workspace.working_copy()
}
pub fn unchecked_start_working_copy_mutation(
&mut self,
) -> Result<(LockedWorkspace, Commit), CommandError> {
self.check_working_copy_writable()?;
let wc_commit = if let Some(wc_commit_id) = self.get_wc_commit_id() {
self.repo().store().get_commit(wc_commit_id)?
} else {
return Err(user_error("Nothing checked out in this workspace"));
};
let locked_ws = self.workspace.start_working_copy_mutation()?;
Ok((locked_ws, wc_commit))
}
pub fn start_working_copy_mutation(
&mut self,
) -> Result<(LockedWorkspace, Commit), CommandError> {
let (mut locked_ws, wc_commit) = self.unchecked_start_working_copy_mutation()?;
if wc_commit.tree_id() != locked_ws.locked_wc().old_tree_id() {
return Err(user_error("Concurrent working copy operation. Try again."));
}
Ok((locked_ws, wc_commit))
}
pub fn workspace_root(&self) -> &PathBuf {
self.workspace.workspace_root()
}
pub fn workspace_id(&self) -> &WorkspaceId {
self.workspace.workspace_id()
}
pub fn get_wc_commit_id(&self) -> Option<&CommitId> {
self.repo().view().get_wc_commit_id(self.workspace_id())
}
pub fn working_copy_shared_with_git(&self) -> bool {
self.working_copy_shared_with_git
}
pub fn format_file_path(&self, file: &RepoPath) -> String {
self.path_converter.format_file_path(file)
}
/// Parses a path relative to cwd into a RepoPath, which is relative to the
/// workspace root.
pub fn parse_file_path(&self, input: &str) -> Result<RepoPathBuf, UiPathParseError> {
self.path_converter.parse_file_path(input)
}
/// Parses the given strings as file patterns.
pub fn parse_file_patterns(
&self,
values: &[String],
) -> Result<FilesetExpression, CommandError> {
// TODO: This function might be superseded by parse_union_filesets(),
// but it would be weird if parse_union_*() had a special case for the
// empty arguments.
if values.is_empty() {
Ok(FilesetExpression::all())
} else if self.settings.config().get_bool("ui.allow-filesets")? {
self.parse_union_filesets(values)
} else {
let expressions = values
.iter()
.map(|v| self.parse_file_path(v))
.map_ok(FilesetExpression::prefix_path)
.try_collect()?;
Ok(FilesetExpression::union_all(expressions))
}
}
/// Parses the given fileset expressions and concatenates them all.
pub fn parse_union_filesets(
&self,
file_args: &[String], // TODO: introduce FileArg newtype?
) -> Result<FilesetExpression, CommandError> {
let expressions: Vec<_> = file_args
.iter()
.map(|arg| fileset::parse_maybe_bare(arg, &self.path_converter))
.try_collect()?;
Ok(FilesetExpression::union_all(expressions))
}
pub(crate) fn path_converter(&self) -> &RepoPathUiConverter {
&self.path_converter
}
#[instrument(skip_all)]
pub fn base_ignores(&self) -> Result<Arc<GitIgnoreFile>, GitIgnoreError> {
fn get_excludes_file_path(config: &gix::config::File) -> Option<PathBuf> {
// TODO: maybe use path() and interpolate(), which can process non-utf-8
// path on Unix.
if let Some(value) = config.string("core.excludesFile") {
str::from_utf8(&value)
.ok()
.map(crate::git_util::expand_git_path)
} else {
xdg_config_home().ok().map(|x| x.join("git").join("ignore"))
}
}
fn xdg_config_home() -> Result<PathBuf, VarError> {
if let Ok(x) = std::env::var("XDG_CONFIG_HOME") {
if !x.is_empty() {
return Ok(PathBuf::from(x));
}
}
std::env::var("HOME").map(|x| Path::new(&x).join(".config"))
}
let mut git_ignores = GitIgnoreFile::empty();
if let Some(git_backend) = self.git_backend() {
let git_repo = git_backend.git_repo();
if let Some(excludes_file_path) = get_excludes_file_path(&git_repo.config_snapshot()) {
git_ignores = git_ignores.chain_with_file("", excludes_file_path)?;
}
git_ignores = git_ignores
.chain_with_file("", git_backend.git_repo_path().join("info").join("exclude"))?;
} else if let Ok(git_config) = gix::config::File::from_globals() {
if let Some(excludes_file_path) = get_excludes_file_path(&git_config) {
git_ignores = git_ignores.chain_with_file("", excludes_file_path)?;
}
}
Ok(git_ignores)
}
/// Creates textual diff renderer of the specified `formats`.
pub fn diff_renderer(&self, formats: Vec<DiffFormat>) -> DiffRenderer<'_> {
DiffRenderer::new(self.repo().as_ref(), &self.path_converter, formats)
}
/// Loads textual diff renderer from the settings and command arguments.
pub fn diff_renderer_for(
&self,
args: &DiffFormatArgs,
) -> Result<DiffRenderer<'_>, CommandError> {
let formats = diff_util::diff_formats_for(&self.settings, args)?;
Ok(self.diff_renderer(formats))
}
/// Loads textual diff renderer from the settings and log-like command
/// arguments. Returns `Ok(None)` if there are no command arguments that
/// enable patch output.
pub fn diff_renderer_for_log(
&self,
args: &DiffFormatArgs,
patch: bool,
) -> Result<Option<DiffRenderer<'_>>, CommandError> {
let formats = diff_util::diff_formats_for_log(&self.settings, args, patch)?;
Ok((!formats.is_empty()).then(|| self.diff_renderer(formats)))
}
/// Loads diff editor from the settings.
///
/// If the `tool_name` isn't specified, the default editor will be returned.
pub fn diff_editor(
&self,
ui: &Ui,
tool_name: Option<&str>,
) -> Result<DiffEditor, CommandError> {
let base_ignores = self.base_ignores()?;
if let Some(name) = tool_name {
Ok(DiffEditor::with_name(name, &self.settings, base_ignores)?)
} else {
Ok(DiffEditor::from_settings(ui, &self.settings, base_ignores)?)
}
}
/// Conditionally loads diff editor from the settings.
///
/// If the `tool_name` is specified, interactive session is implied.
pub fn diff_selector(
&self,
ui: &Ui,
tool_name: Option<&str>,
force_interactive: bool,
) -> Result<DiffSelector, CommandError> {
if tool_name.is_some() || force_interactive {
Ok(DiffSelector::Interactive(self.diff_editor(ui, tool_name)?))
} else {
Ok(DiffSelector::NonInteractive)
}
}
/// Loads 3-way merge editor from the settings.
///
/// If the `tool_name` isn't specified, the default editor will be returned.
pub fn merge_editor(
&self,
ui: &Ui,
tool_name: Option<&str>,
) -> Result<MergeEditor, MergeToolConfigError> {
if let Some(name) = tool_name {
MergeEditor::with_name(name, &self.settings)
} else {
MergeEditor::from_settings(ui, &self.settings)
}
}
pub fn resolve_single_op(&self, op_str: &str) -> Result<Operation, OpsetEvaluationError> {
op_walk::resolve_op_with_repo(self.repo(), op_str)
}
/// Resolve a revset to a single revision. Return an error if the revset is
/// empty or has multiple revisions.
pub fn resolve_single_rev(&self, revision_arg: &RevisionArg) -> Result<Commit, CommandError> {
let expression = self.parse_revset(revision_arg)?;
let should_hint_about_all_prefix = false;
revset_util::evaluate_revset_to_single_commit(
revision_arg.as_ref(),
&expression,
|| self.commit_summary_template(),
should_hint_about_all_prefix,
)
}
/// Evaluates revset expressions to non-empty set of commits. The returned
/// set preserves the order of the input expressions.
///
/// If an input expression is prefixed with `all:`, it may be evaluated to
/// any number of revisions (including 0.)
pub fn resolve_some_revsets_default_single(
&self,
revision_args: &[RevisionArg],
) -> Result<IndexSet<Commit>, CommandError> {
let mut all_commits = IndexSet::new();
for revision_arg in revision_args {
let (expression, modifier) = self.parse_revset_with_modifier(revision_arg)?;
let all = match modifier {
Some(RevsetModifier::All) => true,
None => self
.settings
.config()
.get_bool("ui.always-allow-large-revsets")?,
};
if all {
for commit in expression.evaluate_to_commits()? {
all_commits.insert(commit?);
}
} else {
let should_hint_about_all_prefix = true;
let commit = revset_util::evaluate_revset_to_single_commit(
revision_arg.as_ref(),
&expression,
|| self.commit_summary_template(),
should_hint_about_all_prefix,
)?;
let commit_hash = short_commit_hash(commit.id());
if !all_commits.insert(commit) {
return Err(user_error(format!(
r#"More than one revset resolved to revision {commit_hash}"#,
)));
}
}
}
if all_commits.is_empty() {
Err(user_error("Empty revision set"))
} else {
Ok(all_commits)
}
}
pub fn parse_revset(
&self,
revision_arg: &RevisionArg,
) -> Result<RevsetExpressionEvaluator<'_>, CommandError> {
let (expression, modifier) = self.parse_revset_with_modifier(revision_arg)?;
// Whether the caller accepts multiple revisions or not, "all:" should
// be valid. For example, "all:@" is a valid single-rev expression.
let (None | Some(RevsetModifier::All)) = modifier;
Ok(expression)
}
fn parse_revset_with_modifier(
&self,
revision_arg: &RevisionArg,
) -> Result<(RevsetExpressionEvaluator<'_>, Option<RevsetModifier>), CommandError> {
let context = self.revset_parse_context();
let (expression, modifier) = revset::parse_with_modifier(revision_arg.as_ref(), &context)?;
Ok((self.attach_revset_evaluator(expression)?, modifier))
}
/// Parses the given revset expressions and concatenates them all.
pub fn parse_union_revsets(
&self,
revision_args: &[RevisionArg],
) -> Result<RevsetExpressionEvaluator<'_>, CommandError> {