-
Notifications
You must be signed in to change notification settings - Fork 403
/
Copy pathcommands.rs
4539 lines (4338 loc) · 173 KB
/
commands.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 2020 Google LLC
//
// 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.
extern crate chrono;
extern crate clap;
extern crate clap_mangen;
extern crate config;
use std::collections::{HashMap, HashSet, VecDeque};
use std::ffi::OsString;
use std::fmt::Debug;
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Instant;
use std::{fs, io};
use clap::{crate_version, Arg, ArgMatches, Command};
use criterion::Criterion;
use git2::{Oid, Repository};
use itertools::Itertools;
use jujutsu_lib::backend::{BackendError, CommitId, Timestamp, TreeId, TreeValue};
use jujutsu_lib::commit::Commit;
use jujutsu_lib::commit_builder::CommitBuilder;
use jujutsu_lib::dag_walk::topo_order_reverse;
use jujutsu_lib::diff::{Diff, DiffHunk};
use jujutsu_lib::files::DiffLine;
use jujutsu_lib::git::{GitExportError, GitFetchError, GitImportError, GitRefUpdate};
use jujutsu_lib::index::HexPrefix;
use jujutsu_lib::matchers::{EverythingMatcher, Matcher, PrefixMatcher};
use jujutsu_lib::op_heads_store::OpHeadsStore;
use jujutsu_lib::op_store::{OpStore, OpStoreError, OperationId, RefTarget, WorkspaceId};
use jujutsu_lib::operation::Operation;
use jujutsu_lib::refs::{classify_branch_push_action, BranchPushAction};
use jujutsu_lib::repo::{MutableRepo, ReadonlyRepo, RepoRef};
use jujutsu_lib::repo_path::RepoPath;
use jujutsu_lib::revset::{RevsetError, RevsetExpression, RevsetParseError};
use jujutsu_lib::revset_graph_iterator::RevsetGraphEdgeType;
use jujutsu_lib::rewrite::{back_out_commit, merge_commit_trees, rebase_commit, DescendantRebaser};
use jujutsu_lib::settings::UserSettings;
use jujutsu_lib::store::Store;
use jujutsu_lib::transaction::Transaction;
use jujutsu_lib::tree::{merge_trees, TreeDiffIterator};
use jujutsu_lib::working_copy::{CheckoutStats, ResetError, WorkingCopy};
use jujutsu_lib::workspace::{Workspace, WorkspaceInitError, WorkspaceLoadError};
use jujutsu_lib::{conflicts, dag_walk, diff, files, git, revset, tree};
use maplit::{hashmap, hashset};
use pest::Parser;
use self::chrono::{FixedOffset, TimeZone, Utc};
use crate::commands::CommandError::UserError;
use crate::diff_edit::DiffEditError;
use crate::formatter::Formatter;
use crate::graphlog::{AsciiGraphDrawer, Edge};
use crate::template_parser::TemplateParser;
use crate::templater::Template;
use crate::ui::{FilePathParseError, Ui};
enum CommandError {
UserError(String),
BrokenPipe,
InternalError(String),
}
impl From<std::io::Error> for CommandError {
fn from(err: std::io::Error) -> Self {
if err.kind() == std::io::ErrorKind::BrokenPipe {
CommandError::BrokenPipe
} else {
// TODO: Record the error as a chained cause
CommandError::InternalError(format!("I/O error: {}", err))
}
}
}
impl From<BackendError> for CommandError {
fn from(err: BackendError) -> Self {
CommandError::UserError(format!("Unexpected error from store: {}", err))
}
}
impl From<WorkspaceInitError> for CommandError {
fn from(_: WorkspaceInitError) -> Self {
CommandError::UserError("The target repo already exists".to_string())
}
}
impl From<ResetError> for CommandError {
fn from(_: ResetError) -> Self {
CommandError::InternalError("Failed to reset the working copy".to_string())
}
}
impl From<DiffEditError> for CommandError {
fn from(err: DiffEditError) -> Self {
CommandError::UserError(format!("Failed to edit diff: {}", err))
}
}
impl From<git2::Error> for CommandError {
fn from(err: git2::Error) -> Self {
CommandError::UserError(format!("Git operation failed: {}", err))
}
}
impl From<GitImportError> for CommandError {
fn from(err: GitImportError) -> Self {
CommandError::InternalError(format!(
"Failed to import refs from underlying Git repo: {}",
err
))
}
}
impl From<GitExportError> for CommandError {
fn from(err: GitExportError) -> Self {
match err {
GitExportError::ConflictedBranch(branch_name) => CommandError::UserError(format!(
"Cannot export conflicted branch '{}'",
branch_name
)),
GitExportError::InternalGitError(err) => CommandError::InternalError(format!(
"Failed to export refs to underlying Git repo: {}",
err
)),
}
}
}
impl From<RevsetParseError> for CommandError {
fn from(err: RevsetParseError) -> Self {
CommandError::UserError(format!("Failed to parse revset: {}", err))
}
}
impl From<RevsetError> for CommandError {
fn from(err: RevsetError) -> Self {
CommandError::UserError(format!("{}", err))
}
}
impl From<FilePathParseError> for CommandError {
fn from(err: FilePathParseError) -> Self {
match err {
FilePathParseError::InputNotInRepo(input) => {
CommandError::UserError(format!("Path \"{}\" is not in the repo", input))
}
}
}
}
struct CommandHelper {
string_args: Vec<String>,
root_args: ArgMatches,
}
impl CommandHelper {
fn new(string_args: Vec<String>, root_args: ArgMatches) -> Self {
Self {
string_args,
root_args,
}
}
fn root_args(&self) -> &ArgMatches {
&self.root_args
}
fn workspace_helper(&self, ui: &Ui) -> Result<WorkspaceCommandHelper, CommandError> {
let wc_path_str = self.root_args.value_of("repository").unwrap();
let wc_path = ui.cwd().join(wc_path_str);
let workspace = match Workspace::load(ui.settings(), wc_path) {
Ok(workspace) => workspace,
Err(WorkspaceLoadError::NoWorkspaceHere(wc_path)) => {
let mut message = format!("There is no jj repo in \"{}\"", wc_path_str);
let git_dir = wc_path.join(".git");
if git_dir.is_dir() {
// TODO: Make this hint separate from the error, so the caller can format
// it differently.
message += "
It looks like this is a git repo. You can create a jj repo backed by it by running this:
jj init --git-repo=.";
}
return Err(CommandError::UserError(message));
}
Err(WorkspaceLoadError::RepoDoesNotExist(repo_dir)) => {
return Err(CommandError::UserError(format!(
"The repository directory at {} is missing. Was it moved?",
repo_dir.to_str().unwrap()
)));
}
};
let repo_loader = workspace.repo_loader();
let op_str = self.root_args.value_of("at_op").unwrap();
let repo = if op_str == "@" {
repo_loader.load_at_head()
} else {
let op = resolve_single_op_from_store(
repo_loader.op_store(),
repo_loader.op_heads_store(),
op_str,
)?;
repo_loader.load_at(&op)
};
self.for_loaded_repo(ui, workspace, repo)
}
fn for_loaded_repo(
&self,
ui: &Ui,
workspace: Workspace,
repo: Arc<ReadonlyRepo>,
) -> Result<WorkspaceCommandHelper, CommandError> {
WorkspaceCommandHelper::for_loaded_repo(
ui,
workspace,
self.string_args.clone(),
&self.root_args,
repo,
)
}
}
// Provides utilities for writing a command that works on a workspace (like most
// commands do).
struct WorkspaceCommandHelper {
string_args: Vec<String>,
settings: UserSettings,
workspace: Workspace,
repo: Arc<ReadonlyRepo>,
may_update_working_copy: bool,
working_copy_shared_with_git: bool,
working_copy_committed: bool,
// Whether to rebase descendants when the transaction finishes. This should generally be true
// for commands that rewrite commits.
rebase_descendants: bool,
}
impl WorkspaceCommandHelper {
fn for_loaded_repo(
ui: &Ui,
workspace: Workspace,
string_args: Vec<String>,
root_args: &ArgMatches,
repo: Arc<ReadonlyRepo>,
) -> Result<Self, CommandError> {
let loaded_at_head = root_args.value_of("at_op").unwrap() == "@";
let may_update_working_copy =
loaded_at_head && !root_args.is_present("no_commit_working_copy");
let mut working_copy_shared_with_git = false;
let maybe_git_repo = repo.store().git_repo();
if let Some(git_repo) = &maybe_git_repo {
working_copy_shared_with_git =
git_repo.workdir() == Some(workspace.workspace_root().as_path());
}
let mut helper = Self {
string_args,
settings: ui.settings().clone(),
workspace,
repo,
may_update_working_copy,
working_copy_shared_with_git,
working_copy_committed: false,
rebase_descendants: true,
};
if working_copy_shared_with_git && may_update_working_copy {
helper.import_git_refs_and_head(maybe_git_repo.as_ref().unwrap())?;
}
Ok(helper)
}
fn import_git_refs_and_head(&mut self, git_repo: &Repository) -> Result<(), CommandError> {
let mut tx = self.start_transaction("import git refs");
git::import_refs(tx.mut_repo(), git_repo)?;
if tx.mut_repo().has_changes() {
let old_git_head = self.repo.view().git_head();
let new_git_head = tx.mut_repo().view().git_head();
// If the Git HEAD has changed, abandon our old checkout and check out the new
// Git HEAD.
if new_git_head != old_git_head && new_git_head.is_some() {
let workspace_id = self.workspace.workspace_id();
let mut locked_working_copy = self.workspace.working_copy_mut().start_mutation();
if let Some(old_checkout) = self.repo.view().get_checkout(&workspace_id) {
tx.mut_repo().record_abandoned_commit(old_checkout.clone());
}
let new_checkout = self
.repo
.store()
.get_commit(new_git_head.as_ref().unwrap())?;
tx.mut_repo()
.check_out(workspace_id, &self.settings, &new_checkout);
// 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_working_copy.reset(&new_checkout.tree())?;
tx.mut_repo().rebase_descendants(&self.settings);
self.repo = tx.commit();
locked_working_copy.finish(self.repo.op_id().clone());
} else {
self.repo = tx.commit();
}
}
Ok(())
}
fn export_head_to_git(&self, mut_repo: &mut MutableRepo) -> Result<(), CommandError> {
let git_repo = mut_repo.store().git_repo().unwrap();
let current_git_head_ref = git_repo.find_reference("HEAD").unwrap();
let current_git_commit_id = current_git_head_ref
.peel_to_commit()
.ok()
.map(|commit| commit.id());
if let Some(checkout_id) = mut_repo.view().get_checkout(&self.workspace_id()) {
let first_parent_id =
mut_repo.index().entry_by_id(checkout_id).unwrap().parents()[0].commit_id();
if first_parent_id != *mut_repo.store().root_commit_id() {
if let Some(current_git_commit_id) = current_git_commit_id {
git_repo.set_head_detached(current_git_commit_id)?;
}
let new_git_commit_id = Oid::from_bytes(first_parent_id.as_bytes()).unwrap();
let new_git_commit = git_repo.find_commit(new_git_commit_id)?;
git_repo.reset(new_git_commit.as_object(), git2::ResetType::Mixed, None)?;
mut_repo.set_git_head(first_parent_id);
}
} else {
// The workspace was removed (maybe the user undid the
// initialization of the workspace?), which is weird,
// but we should probably just not do anything else here.
// Except maybe print a note about it?
}
Ok(())
}
fn rebase_descendants(mut self, value: bool) -> Self {
self.rebase_descendants = value;
self
}
fn repo(&self) -> &Arc<ReadonlyRepo> {
&self.repo
}
fn repo_mut(&mut self) -> &mut Arc<ReadonlyRepo> {
&mut self.repo
}
fn working_copy(&self) -> &WorkingCopy {
self.workspace.working_copy()
}
fn working_copy_mut(&mut self) -> &mut WorkingCopy {
self.workspace.working_copy_mut()
}
fn workspace_root(&self) -> &PathBuf {
self.workspace.workspace_root()
}
fn workspace_id(&self) -> WorkspaceId {
self.workspace.workspace_id()
}
fn working_copy_shared_with_git(&self) -> bool {
self.working_copy_shared_with_git
}
fn resolve_revision_arg(
&mut self,
ui: &mut Ui,
args: &ArgMatches,
) -> Result<Commit, CommandError> {
self.resolve_single_rev(ui, args.value_of("revision").unwrap())
}
fn resolve_single_rev(
&mut self,
ui: &mut Ui,
revision_str: &str,
) -> Result<Commit, CommandError> {
let revset_expression = self.parse_revset(ui, revision_str)?;
let revset =
revset_expression.evaluate(self.repo.as_repo_ref(), Some(&self.workspace_id()))?;
let mut iter = revset.iter().commits(self.repo.store());
match iter.next() {
None => Err(CommandError::UserError(format!(
"Revset \"{}\" didn't resolve to any revisions",
revision_str
))),
Some(commit) => {
if iter.next().is_some() {
return Err(CommandError::UserError(format!(
"Revset \"{}\" resolved to more than one revision",
revision_str
)));
} else {
Ok(commit?)
}
}
}
}
fn resolve_revset(
&mut self,
ui: &mut Ui,
revision_str: &str,
) -> Result<Vec<Commit>, CommandError> {
let revset_expression = self.parse_revset(ui, revision_str)?;
let revset =
revset_expression.evaluate(self.repo.as_repo_ref(), Some(&self.workspace_id()))?;
Ok(revset
.iter()
.commits(self.repo.store())
.map(Result::unwrap)
.collect())
}
fn parse_revset(
&mut self,
ui: &mut Ui,
revision_str: &str,
) -> Result<Rc<RevsetExpression>, CommandError> {
let expression = revset::parse(revision_str)?;
// If the revset is exactly "@", then we need to commit the working copy. If
// it's another symbol, then we don't. If it's more complex, then we do
// (just to be safe). TODO: Maybe make this smarter. How do we generally
// figure out if a revset needs to commit the working copy? For example,
// "@-" should perhaps not result in a new working copy commit, but
// "@--" should. "foo++" is probably also should, since we would
// otherwise need to evaluate the revset and see if "foo::" includes the
// parent of the current checkout. Other interesting cases include some kind of
// reference pointing to the working copy commit. If it's a
// type of reference that would get updated when the commit gets rewritten, then
// we probably should create a new working copy commit.
let mentions_checkout = match expression.as_ref() {
RevsetExpression::Symbol(name) => name == "@",
_ => true,
};
if mentions_checkout && !self.working_copy_committed {
self.maybe_commit_working_copy(ui)?;
}
Ok(expression)
}
fn check_rewriteable(&self, commit: &Commit) -> Result<(), CommandError> {
if commit.id() == self.repo.store().root_commit_id() {
return Err(CommandError::UserError(
"Cannot rewrite the root commit".to_string(),
));
}
Ok(())
}
fn check_non_empty(&self, commits: &[Commit]) -> Result<(), CommandError> {
if commits.is_empty() {
return Err(CommandError::UserError("Empty revision set".to_string()));
}
Ok(())
}
fn commit_working_copy(&mut self, ui: &mut Ui) -> Result<(), CommandError> {
if !self.may_update_working_copy {
return Err(UserError(
"Refusing to update working copy (maybe because you're using --at-op)".to_string(),
));
}
self.maybe_commit_working_copy(ui)?;
Ok(())
}
fn maybe_commit_working_copy(&mut self, ui: &mut Ui) -> Result<(), CommandError> {
if !self.may_update_working_copy {
return Ok(());
}
let repo = self.repo.clone();
let workspace_id = self.workspace_id();
let checkout_id = match repo.view().get_checkout(&self.workspace_id()) {
Some(checkout_id) => checkout_id.clone(),
None => {
// If the workspace has been deleted, it's unclear what to do, so we just skip
// committing the working copy.
return Ok(());
}
};
let mut locked_wc = self.workspace.working_copy_mut().start_mutation();
// Check if the working copy commit matches the repo's view. It's fine if it
// doesn't, but we'll need to reload the repo so the new commit is
// in the index and view, and so we don't cause unnecessary
// divergence.
let checkout_commit = repo.store().get_commit(&checkout_id).unwrap();
let wc_tree_id = locked_wc.old_tree_id().clone();
if *checkout_commit.tree_id() != wc_tree_id {
let wc_operation_data = self
.repo
.op_store()
.read_operation(locked_wc.old_operation_id())
.unwrap();
let wc_operation = Operation::new(
repo.op_store().clone(),
locked_wc.old_operation_id().clone(),
wc_operation_data,
);
let repo_operation = repo.operation();
let maybe_ancestor_op = dag_walk::closest_common_node(
[wc_operation.clone()],
[repo_operation.clone()],
&|op: &Operation| op.parents(),
&|op: &Operation| op.id().clone(),
);
if let Some(ancestor_op) = maybe_ancestor_op {
if ancestor_op.id() == repo_operation.id() {
// The working copy was updated since we loaded the repo. We reload the repo
// at the working copy's operation.
self.repo = repo.reload_at(&wc_operation);
} else if ancestor_op.id() == wc_operation.id() {
// The working copy was not updated when some repo operation committed,
// meaning that it's stale compared to the repo view. We update the working
// copy to what the view says.
writeln!(
ui,
"The working copy is stale (not updated since operation {}), now updating \
to operation {}",
wc_operation.id().hex(),
repo_operation.id().hex()
)?;
locked_wc.check_out(&checkout_commit.tree()).unwrap();
} else {
return Err(CommandError::InternalError(format!(
"The repo was loaded at operation {}, which seems to be a sibling of the \
working copy's operation {}",
repo_operation.id().hex(),
wc_operation.id().hex()
)));
}
} else {
return Err(CommandError::InternalError(format!(
"The repo was loaded at operation {}, which seems unrelated to the working \
copy's operation {}",
repo_operation.id().hex(),
wc_operation.id().hex()
)));
}
}
let new_tree_id = locked_wc.write_tree();
if new_tree_id != *checkout_commit.tree_id() {
let mut tx = self.repo.start_transaction("commit working copy");
let mut_repo = tx.mut_repo();
let commit = CommitBuilder::for_rewrite_from(
&self.settings,
self.repo.store(),
&checkout_commit,
)
.set_tree(new_tree_id)
.write_to_repo(mut_repo);
mut_repo.set_checkout(workspace_id, commit.id().clone());
// Rebase descendants
let num_rebased = mut_repo.rebase_descendants(&self.settings);
if num_rebased > 0 {
writeln!(
ui,
"Rebased {} descendant commits onto updated working copy",
num_rebased
)?;
}
self.repo = tx.commit();
locked_wc.finish(self.repo.op_id().clone());
} else {
locked_wc.discard();
}
self.working_copy_committed = true;
Ok(())
}
fn start_transaction(&self, description: &str) -> Transaction {
let mut tx = self.repo.start_transaction(description);
// TODO: Either do better shell-escaping here or store the values in some list
// type (which we currently don't have).
let shell_escape = |arg: &String| {
if arg.as_bytes().iter().all(|b| {
matches!(b,
b'A'..=b'Z'
| b'a'..=b'z'
| b'0'..=b'9'
| b','
| b'-'
| b'.'
| b'/'
| b':'
| b'@'
| b'_'
)
}) {
arg.clone()
} else {
format!("'{}'", arg.replace('\'', "\\'"))
}
};
let quoted_strings = self.string_args.iter().map(shell_escape).collect_vec();
tx.set_tag("args".to_string(), quoted_strings.join(" "));
tx
}
fn finish_transaction(&mut self, ui: &mut Ui, mut tx: Transaction) -> Result<(), CommandError> {
let mut_repo = tx.mut_repo();
let store = mut_repo.store().clone();
if !mut_repo.has_changes() {
writeln!(ui, "Nothing changed.")?;
return Ok(());
}
if self.rebase_descendants {
let num_rebased = mut_repo.rebase_descendants(ui.settings());
if num_rebased > 0 {
writeln!(ui, "Rebased {} descendant commits", num_rebased)?;
}
}
if self.working_copy_shared_with_git {
self.export_head_to_git(mut_repo)?;
}
let maybe_old_tree_id = tx
.base_repo()
.view()
.get_checkout(&self.workspace_id())
.map(|commit_id| store.get_commit(commit_id).unwrap().tree_id().clone());
self.repo = tx.commit();
if self.may_update_working_copy {
let stats = update_working_copy(
ui,
&self.repo,
&self.workspace_id(),
self.workspace.working_copy_mut(),
maybe_old_tree_id.as_ref(),
)?;
if let Some(stats) = stats {
if stats.added_files > 0 || stats.updated_files > 0 || stats.removed_files > 0 {
writeln!(
ui,
"Added {} files, modified {} files, removed {} files",
stats.added_files, stats.updated_files, stats.removed_files
)?;
}
}
}
if self.working_copy_shared_with_git {
let git_repo = self.repo.store().git_repo().unwrap();
git::export_refs(&self.repo, &git_repo)?;
}
Ok(())
}
}
fn rev_arg<'help>() -> Arg<'help> {
Arg::new("revision")
.long("revision")
.short('r')
.takes_value(true)
.default_value("@")
}
fn paths_arg<'help>() -> Arg<'help> {
Arg::new("paths").index(1).multiple_occurrences(true)
}
fn message_arg<'help>() -> Arg<'help> {
Arg::new("message")
.long("message")
.short('m')
.takes_value(true)
}
fn op_arg<'help>() -> Arg<'help> {
Arg::new("operation")
.long("operation")
.alias("op")
.short('o')
.takes_value(true)
.default_value("@")
}
fn resolve_single_op(repo: &ReadonlyRepo, op_str: &str) -> Result<Operation, CommandError> {
if op_str == "@" {
// Get it from the repo to make sure that it refers to the operation the repo
// was loaded at
Ok(repo.operation().clone())
} else {
resolve_single_op_from_store(repo.op_store(), repo.op_heads_store(), op_str)
}
}
fn find_all_operations(
op_store: &Arc<dyn OpStore>,
op_heads_store: &Arc<OpHeadsStore>,
) -> Vec<Operation> {
let mut visited = HashSet::new();
let mut work: VecDeque<_> = op_heads_store.get_op_heads().into_iter().collect();
let mut operations = vec![];
while !work.is_empty() {
let op_id = work.pop_front().unwrap();
if visited.insert(op_id.clone()) {
let store_operation = op_store.read_operation(&op_id).unwrap();
work.extend(store_operation.parents.iter().cloned());
let operation = Operation::new(op_store.clone(), op_id, store_operation);
operations.push(operation);
}
}
operations
}
fn resolve_single_op_from_store(
op_store: &Arc<dyn OpStore>,
op_heads_store: &Arc<OpHeadsStore>,
op_str: &str,
) -> Result<Operation, CommandError> {
if let Ok(binary_op_id) = hex::decode(op_str) {
let op_id = OperationId::new(binary_op_id);
match op_store.read_operation(&op_id) {
Ok(operation) => {
return Ok(Operation::new(op_store.clone(), op_id, operation));
}
Err(OpStoreError::NotFound) => {
// Fall through
}
Err(err) => {
return Err(CommandError::InternalError(format!(
"Failed to read operation: {:?}",
err
)));
}
}
}
let mut matches = vec![];
for op in find_all_operations(op_store, op_heads_store) {
if op.id().hex().starts_with(op_str) {
matches.push(op);
}
}
if matches.is_empty() {
Err(CommandError::UserError(format!(
"No operation ID matching \"{}\"",
op_str
)))
} else if matches.len() == 1 {
Ok(matches.pop().unwrap())
} else {
Err(CommandError::UserError(format!(
"Operation ID prefix \"{}\" is ambiguous",
op_str
)))
}
}
fn matcher_from_values(
ui: &Ui,
wc_path: &Path,
values: Option<clap::Values>,
) -> Result<Box<dyn Matcher>, CommandError> {
if let Some(values) = values {
// TODO: Add support for globs and other formats
let mut paths = vec![];
for value in values {
let repo_path = ui.parse_file_path(wc_path, value)?;
paths.push(repo_path);
}
Ok(Box::new(PrefixMatcher::new(&paths)))
} else {
Ok(Box::new(EverythingMatcher))
}
}
fn update_working_copy(
ui: &mut Ui,
repo: &Arc<ReadonlyRepo>,
workspace_id: &WorkspaceId,
wc: &mut WorkingCopy,
old_tree_id: Option<&TreeId>,
) -> Result<Option<CheckoutStats>, CommandError> {
let new_commit_id = match repo.view().get_checkout(workspace_id) {
Some(new_commit_id) => new_commit_id,
None => {
// It seems the workspace was deleted, so we shouldn't try to update it.
return Ok(None);
}
};
let new_commit = repo.store().get_commit(new_commit_id).unwrap();
let stats = if Some(new_commit.tree_id()) != old_tree_id {
// TODO: CheckoutError::ConcurrentCheckout should probably just result in a
// warning for most commands (but be an error for the checkout command)
let stats = wc
.check_out(repo.op_id().clone(), old_tree_id, &new_commit.tree())
.map_err(|err| {
CommandError::InternalError(format!(
"Failed to check out commit {}: {}",
new_commit.id().hex(),
err
))
})?;
Some(stats)
} else {
None
};
ui.write("Working copy now at: ")?;
ui.write_commit_summary(repo.as_repo_ref(), workspace_id, &new_commit)?;
ui.write("\n")?;
Ok(stats)
}
fn get_app<'help>() -> Command<'help> {
let init_command = Command::new("init")
.about("Create a new repo in the given directory")
.long_about(
"Create a new repo in the given directory. If the given directory does not exist, it \
will be created. If no directory is given, the current directory is used.",
)
.arg(
Arg::new("destination")
.index(1)
.default_value(".")
.help("The destination directory"),
)
.arg(
Arg::new("git")
.long("git")
.help("Use the Git backend, creating a jj repo backed by a Git repo"),
)
.arg(
Arg::new("git-repo")
.long("git-repo")
.takes_value(true)
.help("Path to a git repo the jj repo will be backed by"),
);
let checkout_command = Command::new("checkout")
.alias("co")
.about("Update the working copy to another revision")
.long_about(
"Update the working copy to another revision. If the revision is closed or has \
conflicts, then a new, open revision will be created on top, and that will be checked \
out. For more information, see \
https://github.com/martinvonz/jj/blob/main/docs/working-copy.md.",
)
.arg(
Arg::new("revision")
.index(1)
.required(true)
.help("The revision to update to"),
);
let untrack_command = Command::new("untrack")
.about("Stop tracking specified paths in the working copy")
.arg(paths_arg());
let files_command = Command::new("files")
.about("List files in a revision")
.arg(rev_arg().help("The revision to list files in"))
.arg(paths_arg());
let diff_command = Command::new("diff")
.about("Show changes in a revision")
.long_about(
"Show changes in a revision.
With the `-r` option, which is the default, shows the changes compared to the parent revision. If \
there are several parent revisions (i.e., the given revision is a merge), then they \
will be merged and the changes from the result to the given revision will be shown.
With the `--from` and/or `--to` options, shows the difference from/to the given revisions. If \
either is left out, it defaults to the current checkout. For example, `jj diff \
--from main` shows the changes from \"main\" (perhaps a branch name) to the current \
checkout.",
)
.arg(
Arg::new("summary")
.long("summary")
.short('s')
.help("For each path, show only whether it was modified, added, or removed"),
)
.arg(
Arg::new("git")
.long("git")
.conflicts_with("summary")
.help("Show a Git-format diff"),
)
.arg(
Arg::new("color-words")
.long("color-words")
.conflicts_with("summary")
.conflicts_with("git")
.help("Show a word-level diff with changes indicated only by color"),
)
.arg(
Arg::new("revision")
.long("revision")
.short('r')
.takes_value(true)
.help("Show changes changes in this revision, compared to its parent(s)"),
)
.arg(
Arg::new("from")
.long("from")
.takes_value(true)
.help("Show changes from this revision"),
)
.arg(
Arg::new("to")
.long("to")
.takes_value(true)
.help("Show changes to this revision"),
)
.arg(paths_arg());
let show_command = Command::new("show")
.about("Show commit description and changes in a revision")
.long_about("Show commit description and changes in a revision")
.arg(
Arg::new("summary")
.long("summary")
.short('s')
.help("For each path, show only whether it was modified, added, or removed"),
)
.arg(
Arg::new("git")
.long("git")
.conflicts_with("summary")
.help("Show a Git-format diff"),
)
.arg(
Arg::new("color-words")
.long("color-words")
.conflicts_with("summary")
.conflicts_with("git")
.help("Show a word-level diff with changes indicated only by color"),
)
.arg(
Arg::new("revision")
.index(1)
.default_value("@")
.help("Show changes changes in this revision, compared to its parent(s)"),
);
let status_command = Command::new("status")
.alias("st")
.about("Show high-level repo status")
.long_about(
"Show high-level repo status. This includes:
* The working copy commit and its (first) \
parent, and a summary of the changes between them
* Conflicted branches (see https://github.com/martinvonz/jj/blob/main/docs/branches.md)\
",
);
let log_command = Command::new("log")
.about("Show commit history")
.arg(
Arg::new("template")
.long("template")
.short('T')
.takes_value(true)
.help(
"Render each revision using the given template (the syntax is not yet \
documented and is likely to change)",
),
)
.arg(
Arg::new("revisions")
.long("revisions")
.short('r')
.takes_value(true)
.default_value(":heads()")
.help("Which revisions to show"),
)
.arg(
Arg::new("no-graph")
.long("no-graph")
.help("Don't show the graph, show a flat list of revisions"),
);
let obslog_command = Command::new("obslog")
.about("Show how a change has evolved")
.long_about("Show how a change has evolved as it's been updated, rebased, etc.")
.arg(rev_arg())
.arg(
Arg::new("template")
.long("template")
.short('T')
.takes_value(true)
.help(
"Render each revision using the given template (the syntax is not yet \
documented)",
),
)
.arg(
Arg::new("no-graph")