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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
//! jj command executor
//!
//! Handles running jj commands and capturing their output.
//!
//! ## Concurrency rules for jj command execution
//!
//! - **Read-Read**: Safe to parallelize (`jj log` + `jj status` + `jj op log`, etc.)
//! - **Write → Read**: Must be sequential (action must complete before refresh reads its result)
//! - **Write-Write**: Must be sequential (never parallelize two write operations)
//! - **Result consistency**: When parallel reads complete, apply all results to App state
//! atomically to avoid partial/inconsistent UI state.
use std::path::PathBuf;
use std::process::Command;
use crate::model::{
AnnotationContent, Bookmark, BookmarkInfo, Change, ChangeId, CommitId, ConflictFile,
DiffContent, Operation, RebaseMode, Status, TagInfo,
};
use super::JjError;
use super::constants::{self, commands, errors, flags, resolve_flags};
use super::parser::Parser;
use super::template::Templates;
/// Bulk push mode (repository-wide push operations)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PushBulkMode {
/// Push all bookmarks (including new) — `--all`
All,
/// Push tracked bookmarks only — `--tracked`
Tracked,
/// Push deleted bookmarks — `--deleted`
Deleted,
}
impl PushBulkMode {
/// Return the jj CLI flag for this mode
pub fn flag(&self) -> &'static str {
match self {
Self::All => flags::ALL,
Self::Tracked => flags::TRACKED,
Self::Deleted => flags::DELETED,
}
}
/// Human-readable label for UI
pub fn label(&self) -> &'static str {
match self {
Self::All => "all bookmarks",
Self::Tracked => "tracked bookmarks",
Self::Deleted => "deleted bookmarks",
}
}
}
/// Result of running a jj command, including the captured arguments
pub struct RunResult {
/// The command output (stdout)
pub output: String,
/// The stderr output (informational messages, warnings)
pub stderr: String,
/// The arguments passed to jj (excluding --color=never and --repository)
pub args: Vec<String>,
}
/// Executor for jj commands
///
/// All methods take `&self` (no mutable state), making `JjExecutor` safe to
/// share across threads via `&JjExecutor`. This is verified by the compile-time
/// assertion below.
#[derive(Debug, Clone)]
pub struct JjExecutor {
/// Path to the repository (None = current directory)
repo_path: Option<PathBuf>,
}
// Compile-time assertion: JjExecutor must be Sync for thread::scope sharing.
// If this fails, consider wrapping in Arc or removing interior mutability.
const _: () = {
const fn assert_sync<T: Sync>() {}
assert_sync::<JjExecutor>();
};
impl Default for JjExecutor {
fn default() -> Self {
Self::new()
}
}
impl JjExecutor {
/// Create a new executor for the current directory
pub fn new() -> Self {
Self { repo_path: None }
}
/// Create a new executor for a specific repository path
#[allow(dead_code)]
pub fn with_repo_path(path: PathBuf) -> Self {
Self {
repo_path: Some(path),
}
}
/// Get the repository path (for use by other impl blocks in sibling modules)
pub(crate) fn repo_path(&self) -> Option<&PathBuf> {
self.repo_path.as_ref()
}
/// Run a jj command with the given arguments
///
/// Automatically adds `--color=never` to ensure parseable output.
/// Returns `RunResult` containing both the output and the captured args.
pub fn run(&self, args: &[&str]) -> Result<RunResult, JjError> {
use std::process::Stdio;
let args_vec: Vec<String> = args.iter().map(|s| s.to_string()).collect();
let mut cmd = Command::new(constants::JJ_COMMAND);
// Add repository path if specified
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
// Always disable color for parsing
cmd.arg(flags::NO_COLOR);
// Add user-specified arguments
cmd.args(args);
// Explicitly close stdin to prevent jj from waiting for input
// (e.g., during snapshot warnings or interactive prompts).
// Without this, Command::output() creates a pipe for stdin,
// which may not signal EOF properly under raw-mode terminals.
cmd.stdin(Stdio::null());
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(RunResult {
output: String::from_utf8_lossy(&output.stdout).into_owned(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
args: args_vec,
})
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
// Check for common error patterns
if stderr.contains(errors::NOT_A_REPO) {
return Err(JjError::NotARepository);
}
// jj exits with code 1 when snapshot warnings are present
// (e.g., large files exceeding snapshot.max-new-file-size)
// but the command itself may have succeeded.
//
// The snapshot is a pre-command operation; its failure does not
// mean the command failed. Treat "Refused to snapshot" as
// non-fatal for all commands — the proper fix is configuring
// .jjignore or snapshot.max-new-file-size in the repository.
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
if stderr.contains("Refused to snapshot") {
return Ok(RunResult {
output: stdout,
stderr,
args: args_vec,
});
}
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Run a jj command and return only the output string.
///
/// Convenience wrapper around `run()` for callers that don't need `RunResult.args`.
// Used by run_and_record: see execute_*() in app/actions/
fn run_str(&self, args: &[&str]) -> Result<String, JjError> {
self.run(args).map(|r| r.output)
}
/// Run `jj log` with optional revset filter (raw output)
///
/// Note: Graph output is enabled to show DAG structure.
/// The parser handles graph prefixes in the output.
pub fn log_raw(&self, revset: Option<&str>, reversed: bool) -> Result<String, JjError> {
let template = Templates::log();
let mut args = vec![commands::LOG, flags::TEMPLATE, template];
if let Some(rev) = revset {
args.push(flags::REVISION);
args.push(rev);
// No --limit for revset queries (preserve exploration)
} else {
// Default view: limit to avoid slowness on large repos
args.push(flags::LIMIT);
args.push(constants::DEFAULT_LOG_LIMIT);
}
if reversed {
args.push(flags::REVERSED);
}
self.run_str(&args)
}
/// Run `jj log` and parse the output into Changes
pub fn log(&self, revset: Option<&str>, reversed: bool) -> Result<Vec<Change>, JjError> {
let output = self.log_raw(revset, reversed)?;
Parser::parse_log(&output).map_err(|e| JjError::ParseError(e.to_string()))
}
/// Run `jj log` and parse output into Changes for current view.
/// This is the preferred API for application code.
pub fn log_changes(
&self,
revset: Option<&str>,
reversed: bool,
) -> Result<Vec<Change>, JjError> {
self.log(revset, reversed)
}
/// Run `jj status`
pub fn status_raw(&self) -> Result<String, JjError> {
self.run_str(&[commands::STATUS])
}
/// Run `jj status` and parse the output into Status
pub fn status(&self) -> Result<Status, JjError> {
let output = self.status_raw()?;
Parser::parse_status(&output)
}
/// Run `jj show` for a specific change
pub fn show_raw(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::SHOW, flags::REVISION, revision])
}
/// Run `jj show` and parse the output into DiffContent
///
/// This is the preferred API for application code, following the same pattern as log_changes().
pub fn show(&self, revision: &str) -> Result<DiffContent, JjError> {
let output = self.show_raw(revision)?;
Parser::parse_show(&output)
}
/// Run `jj show --stat` for a specific change (histogram overview)
pub fn show_stat(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::SHOW, flags::STAT, flags::REVISION, revision])
}
/// Run `jj show --git` for a specific change (git unified diff)
pub fn show_git(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::SHOW, flags::GIT_FORMAT, flags::REVISION, revision])
}
/// Run `jj describe` to update change description
///
/// Uses positional argument format: `jj describe <change-id> -m <message>`
/// Note: `-r` is accepted as an alias for compatibility but positional is preferred.
pub fn describe(&self, revision: &str, message: &str) -> Result<String, JjError> {
self.run_str(&[commands::DESCRIBE, revision, "-m", message])
}
/// Get the full description (multi-line) for a change
///
/// Uses `jj log -r <change-id> -T 'description'` to fetch the complete description.
/// Unlike the normal log output which uses `description.first_line()`, this returns
/// the entire description including all lines.
pub fn get_description(&self, revision: &str) -> Result<String, JjError> {
let output = self.run_str(&[
commands::LOG,
flags::NO_GRAPH,
flags::REVISION,
revision,
flags::TEMPLATE,
"description",
])?;
Ok(output)
}
/// Check if a revision is immutable
pub fn is_immutable(&self, revision: &str) -> bool {
self.run_str(&[
commands::LOG,
flags::NO_GRAPH,
flags::REVISION,
revision,
flags::TEMPLATE,
r#"if(immutable, "true", "false")"#,
])
.is_ok_and(|output| output.trim() == "true")
}
/// Run `jj edit` to set working-copy revision
pub fn edit(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::EDIT, revision])
}
/// Run `jj new` to create a new empty change
pub fn new_change(&self) -> Result<String, JjError> {
self.run_str(&[commands::NEW])
}
/// Run `jj new <revision>` to create a new change with specified parent
///
/// Creates a new empty change as a child of the specified revision.
/// The working copy (@) moves to the new change.
pub fn new_change_from(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::NEW, revision])
}
/// Run `jj commit` to commit current changes with a message
///
/// This is equivalent to `jj describe` + `jj new`, but atomic.
/// After commit, a new empty change is created on top.
pub fn commit(&self, message: &str) -> Result<String, JjError> {
self.run_str(&[commands::COMMIT, "-m", message])
}
/// Run `jj squash` to squash @ into @- (non-interactive)
///
/// Moves changes from the current working copy into its parent.
/// If the current change becomes empty, it is automatically abandoned.
/// This uses `--use-destination-message` to avoid opening an editor.
pub fn squash(&self) -> Result<String, JjError> {
self.run_str(&[commands::SQUASH, "--use-destination-message"])
}
/// Run `jj abandon <change-id>` to abandon a revision
///
/// Descendants are automatically rebased onto the parent.
/// If @ is abandoned, a new empty change is created.
pub fn abandon(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::ABANDON, revision])
}
/// Run `jj revert -r <change_id> --onto @` to create a reverse-diff commit
///
/// Creates a new commit on top of @ that undoes the changes from the specified revision.
pub fn revert(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[
commands::REVERT,
flags::REVISION,
revision,
flags::ONTO,
"@",
])
}
/// Run `jj restore <file_path>` to restore a specific file to its parent state
pub fn restore_file(&self, file_path: &str) -> Result<String, JjError> {
self.run_str(&[commands::RESTORE, file_path])
}
/// Run `jj restore` to restore all files to their parent state
pub fn restore_all(&self) -> Result<String, JjError> {
self.run_str(&[commands::RESTORE])
}
/// Run `jj evolog -r <change_id>` with template output
pub fn evolog(&self, revision: &str) -> Result<String, JjError> {
// evolog template context is EvolutionEntry, not Commit.
// Fields must be accessed via `commit.` prefix (e.g. commit.commit_id()).
// Uses committer timestamp (when each version was created), not author
// timestamp (which stays the same across all versions).
let template = concat!(
"separate(\"\\t\",",
" commit.commit_id().short(),",
" commit.change_id().short(),",
" commit.author().email(),",
" commit.committer().timestamp().format(\"%Y-%m-%d %H:%M:%S\"),",
" if(commit.empty(), \"[empty]\", \"\"),",
" if(commit.description(), commit.description().first_line(), \"(no description set)\")",
") ++ \"\\n\""
);
self.run_str(&[
commands::EVOLOG,
flags::REVISION,
revision,
flags::TEMPLATE,
template,
])
}
/// Run `jj undo` to undo the last operation
///
/// Returns the raw output from the command for notification display.
pub fn undo(&self) -> Result<String, JjError> {
self.run_str(&[commands::UNDO])
}
/// Run `jj op restore` to restore a previous operation (redo)
///
/// This restores the operation before the most recent undo, effectively redoing.
/// The operation ID should be obtained from `get_redo_target()`.
pub fn redo(&self, operation_id: &str) -> Result<String, JjError> {
self.run_str(&[commands::OP, commands::OP_RESTORE, operation_id])
}
/// Get the redo target operation ID, if we're in an undo/redo chain.
///
/// Returns `Some(operation_id)` if the most recent operation is an undo or restore
/// (i.e., we're in an undo/redo chain).
/// Returns `None` if there's nothing to redo.
///
/// # Limitations
///
/// **Single redo only**: This implementation only supports redoing after a single undo.
/// After multiple consecutive undos, this returns `None` because the second line
/// in the op log is also an undo operation.
///
/// For multiple undo recovery, users should use Operation History View ('o' key)
/// to restore to any arbitrary point in history.
///
/// # Implementation Note
///
/// This uses string matching on `description.first_line()` to detect undo/restore.
/// The detection checks if the description starts with "undo" or "restore" (case-insensitive).
///
/// **Known limitation**: If jj changes the operation description format,
/// this detection may break. As of jj 0.37+:
/// - Undo: "undo operation <id>"
/// - Restore: "restore operation <id>"
///
/// If jj adds a native `jj redo` command in the future, this implementation
/// should be updated to use it instead.
pub fn get_redo_target(&self) -> Result<Option<String>, JjError> {
// Template: id<TAB>description.first_line()
let output = self.run_str(&[
commands::OP,
commands::OP_LOG,
flags::NO_GRAPH,
flags::TEMPLATE,
r#"id.short() ++ "\t" ++ description.first_line() ++ "\n""#,
"--limit",
"2",
])?;
let lines: Vec<&str> = output.lines().collect();
// We need at least 2 operations to redo
if lines.len() < 2 {
return Ok(None);
}
// Parse first line: check if it's an undo or restore operation
let first_line = lines[0];
let parts: Vec<&str> = first_line.split('\t').collect();
if parts.len() < 2 {
return Ok(None);
}
let first_desc = parts[1].to_lowercase();
// Allow redo if the latest operation is an undo OR restore (in redo chain)
if !first_desc.starts_with("undo") && !first_desc.starts_with("restore") {
return Ok(None);
}
// Parse second line to get the operation to restore
let second_line = lines[1];
let second_parts: Vec<&str> = second_line.split('\t').collect();
if second_parts.len() < 2 {
return Ok(None);
}
let second_desc = second_parts[1].to_lowercase();
// If second line is also an undo/restore, we can't redo properly
// (multiple consecutive undos - need more complex logic)
if second_desc.starts_with("undo") || second_desc.starts_with("restore") {
return Ok(None);
}
Ok(Some(second_parts[0].trim().to_string()))
}
/// Run `jj op log` and parse the output into Operations
///
/// Returns a list of operations, most recent first.
/// The first operation in the list is the current operation.
pub fn op_log(&self, limit: Option<usize>) -> Result<Vec<Operation>, JjError> {
let template = Templates::op_log();
let mut args = vec![
commands::OP,
commands::OP_LOG,
flags::NO_GRAPH,
flags::TEMPLATE,
template,
];
// Convert limit to String and store it
let limit_str;
if let Some(n) = limit {
limit_str = n.to_string();
args.push("--limit");
args.push(&limit_str);
}
let output = self.run_str(&args)?;
Parser::parse_op_log(&output)
}
/// Run `jj op restore <operation_id>` to restore a previous state
///
/// This restores the repository state to what it was after the specified operation.
/// Use with caution - this is a powerful operation.
pub fn op_restore(&self, operation_id: &str) -> Result<String, JjError> {
self.run_str(&[commands::OP, commands::OP_RESTORE, operation_id])
}
/// Run `jj bookmark create <name> -r <change-id>` to create a bookmark
///
/// Creates a new bookmark pointing to the specified change.
/// Returns an error if a bookmark with the same name already exists.
pub fn bookmark_create(&self, name: &str, revision: &str) -> Result<String, JjError> {
self.run_str(&[
commands::BOOKMARK,
commands::BOOKMARK_CREATE,
name,
"-r",
revision,
])
}
/// Run `jj bookmark set <name> -r <change-id> --allow-backwards` to move an existing bookmark
///
/// Moves an existing bookmark to point to the specified change.
/// Uses `--allow-backwards` to permit moving in any direction.
pub fn bookmark_set(&self, name: &str, revision: &str) -> Result<String, JjError> {
self.run_str(&[
commands::BOOKMARK,
commands::BOOKMARK_SET,
name,
"-r",
revision,
"--allow-backwards",
])
}
/// Run `jj bookmark delete <names>...` to delete bookmarks
///
/// Deletes the specified bookmarks. Deletions propagate to remotes on push.
pub fn bookmark_delete(&self, names: &[&str]) -> Result<String, JjError> {
let mut args = vec![commands::BOOKMARK, commands::BOOKMARK_DELETE];
args.extend(names);
self.run_str(&args)
}
/// Run `jj bookmark list --all-remotes` to get all bookmarks
///
/// Returns both local and remote bookmarks with their tracking status.
/// Uses a template to output: name, remote, tracked (tab-separated).
///
/// Note: Requires jj 0.37+ which supports the `tracked` template field.
pub fn bookmark_list_all(&self) -> Result<Vec<Bookmark>, JjError> {
const BOOKMARK_LIST_TEMPLATE: &str = r#"separate("\t", name, remote, tracked) ++ "\n""#;
let output = self.run_str(&[
commands::BOOKMARK,
commands::BOOKMARK_LIST,
flags::ALL_REMOTES,
flags::TEMPLATE,
BOOKMARK_LIST_TEMPLATE,
])?;
Ok(super::parser::parse_bookmark_list(&output))
}
/// Get extended bookmark information for Bookmark Jump/View
///
/// Two-stage approach:
/// 1. `jj bookmark list --all-remotes` - get all bookmarks with tracking status
/// 2. `jj log -r 'bookmarks()'` - get change_id and description for local bookmarks
///
/// Remote-only bookmarks will have `change_id = None` and cannot be jumped to.
/// Remote tracked bookmarks (e.g., main@origin) also have `change_id = None`
/// to ensure only local bookmarks appear in Jump dialog.
pub fn bookmark_list_with_info(&self) -> Result<Vec<BookmarkInfo>, JjError> {
use std::collections::HashMap;
// Step 1: Get all bookmarks
let bookmarks = self.bookmark_list_all()?;
// Step 2: Get revision info for local bookmarks
// Template: explicitly format bookmarks as space-separated names
// Using bookmarks.map(|x| x.name()).join(" ") for stable parsing
// Use short(8) to match LogView's change_id length for exact matching
const BOOKMARK_INFO_TEMPLATE: &str = r#"bookmarks.map(|x| x.name()).join(" ") ++ "\t" ++ change_id.short(8) ++ "\t" ++ commit_id.short(8) ++ "\t" ++ description.first_line() ++ "\n""#;
let log_output = self.run_str(&[
commands::LOG,
flags::NO_GRAPH,
flags::REVISION,
"bookmarks()",
flags::TEMPLATE,
BOOKMARK_INFO_TEMPLATE,
])?;
// Parse log output into a map: bookmark_name -> (change_id, commit_id, description)
// Note: This only includes LOCAL bookmarks (from `jj log -r 'bookmarks()'`)
let mut info_map: HashMap<String, (String, String, String)> = HashMap::new();
for line in log_output.lines() {
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 4 {
let bookmark_names = parts[0]; // Space-separated bookmark names
let change_id = parts[1].to_string();
let commit_id = parts[2].to_string();
let description = parts[3].to_string();
// Multiple bookmarks may point to the same commit
for name in bookmark_names.split_whitespace() {
info_map.insert(
name.to_string(),
(change_id.clone(), commit_id.clone(), description.clone()),
);
}
}
}
// Step 3: Merge bookmark list with revision info
// Only local bookmarks (remote.is_none()) get change_id from info_map
// Remote bookmarks (including tracked ones like main@origin) get change_id = None
// This ensures only local bookmarks appear in Jump dialog
let result: Vec<BookmarkInfo> = bookmarks
.into_iter()
.map(|bookmark| {
// Only apply info_map to local bookmarks
let info = if bookmark.remote.is_none() {
info_map.get(&bookmark.name)
} else {
None
};
BookmarkInfo {
change_id: info.map(|(c, _, _)| ChangeId::new(c.clone())),
commit_id: info.map(|(_, c, _)| CommitId::new(c.clone())),
description: info.map(|(_, _, d)| d.clone()),
bookmark,
}
})
.collect();
Ok(result)
}
/// Run `jj bookmark track <names>...` to start tracking remote bookmarks
///
/// Starts tracking the specified remote bookmarks locally.
/// After tracking, `jj git fetch` will update the local copy.
///
/// Format: `<name>@<remote>` (e.g., "feature-x@origin")
pub fn bookmark_track(&self, names: &[&str]) -> Result<String, JjError> {
let mut args = vec![commands::BOOKMARK, commands::BOOKMARK_TRACK];
args.extend(names);
self.run_str(&args)
}
/// Run `jj bookmark untrack <names...>` to stop tracking remote bookmarks
///
/// Stops tracking the specified remote bookmarks locally.
/// Format: `<name>@<remote>` (e.g., "feature-x@origin")
pub fn bookmark_untrack(&self, names: &[&str]) -> Result<String, JjError> {
let mut args = vec![commands::BOOKMARK, commands::BOOKMARK_UNTRACK];
args.extend(names);
self.run_str(&args)
}
/// Unified rebase: run jj rebase with the given mode and optional extra flags
///
/// Supports all five modes:
/// - `Revision` (`-r`): Move single change, descendants rebased onto parent
/// - `Source` (`-s`): Move change and all descendants together
/// - `Branch` (`-b`): Move entire branch relative to destination's ancestors
/// - `InsertAfter` (`-A`): Insert change after target in history
/// - `InsertBefore` (`-B`): Insert change before target in history
///
/// `extra_flags` can include e.g. `--skip-emptied`.
///
/// Returns the command output which may contain conflict information.
pub fn rebase_unified(
&self,
mode: RebaseMode,
source: &str,
target: &str,
extra_flags: &[&str],
) -> Result<String, JjError> {
let mut args = vec![commands::REBASE];
match mode {
RebaseMode::Revision => {
args.extend_from_slice(&[flags::REVISION, source, "-d", target]);
}
RebaseMode::Source => {
args.extend_from_slice(&[flags::SOURCE, source, "-d", target]);
}
RebaseMode::Branch => {
args.extend_from_slice(&[flags::BRANCH_SHORT, source, "-d", target]);
}
RebaseMode::InsertAfter => {
args.extend_from_slice(&[flags::REVISION, source, flags::INSERT_AFTER, target]);
}
RebaseMode::InsertBefore => {
args.extend_from_slice(&[flags::REVISION, source, flags::INSERT_BEFORE, target]);
}
}
args.extend_from_slice(extra_flags);
self.run_str(&args)
}
/// Check if a specific change has conflicts
///
/// Uses `jj log -r <change_id> -T 'conflict'` to query the conflict status.
/// Returns true if the change has unresolved conflicts.
pub fn has_conflict(&self, revision: &str) -> Result<bool, JjError> {
let output = self.run_str(&[
commands::LOG,
flags::NO_GRAPH,
flags::REVISION,
revision,
flags::TEMPLATE,
"conflict",
])?;
Ok(output.trim() == "true")
}
/// Run `jj absorb` to move changes into ancestor commits
///
/// Each hunk in the working copy (@) is moved to the closest mutable
/// ancestor where the corresponding lines were modified last.
/// If the destination cannot be determined unambiguously, the change
/// remains in the source.
///
/// Returns the command output which describes what was absorbed.
pub fn absorb(&self) -> Result<String, JjError> {
self.run_str(&[commands::ABSORB])
}
/// Run `jj simplify-parents -r <change_id>` to remove redundant parent edges
///
/// Removes parents that are ancestors of other parents, simplifying the DAG
/// without changing content. Returns the command output.
pub fn simplify_parents(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::SIMPLIFY_PARENTS, flags::REVISION, revision])
}
/// Run `jj fix -s <change_id>`
///
/// Applies configured code formatters to the specified revision
/// and its descendants. Requires `[fix.tools.*]` in jj config.
pub fn fix(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::FIX, flags::SOURCE, revision])
}
/// Run `jj parallelize` to convert a linear chain into parallel (sibling) commits
///
/// Uses the revset `from::to | to::from` to handle both directions
/// (user may select newer→older or older→newer). One side will be empty,
/// and the union ensures the correct range is always used.
pub fn parallelize(&self, from: &str, to: &str) -> Result<String, JjError> {
let revset = format!("{}::{} | {}::{}", from, to, to, from);
self.run_str(&[commands::PARALLELIZE, &revset])
}
/// List conflicted files for a change
///
/// Runs `jj resolve --list [-r <change_id>]` and parses the output.
/// Returns an empty list if there are no conflicts.
pub fn resolve_list(&self, revision: Option<&str>) -> Result<Vec<ConflictFile>, JjError> {
let mut args = vec![commands::RESOLVE, resolve_flags::LIST];
if let Some(rev) = revision {
args.push(flags::REVISION);
args.push(rev);
}
let output = self.run_str(&args)?;
Ok(Parser::parse_resolve_list(&output))
}
/// Resolve a conflict using a built-in tool (:ours or :theirs)
///
/// Works for any change (not just @).
pub fn resolve_with_tool(
&self,
file_path: &str,
tool: &str,
revision: Option<&str>,
) -> Result<String, JjError> {
let mut args = vec![commands::RESOLVE, resolve_flags::TOOL, tool];
if let Some(rev) = revision {
args.push(flags::REVISION);
args.push(rev);
}
args.push(file_path);
self.run_str(&args)
}
/// Rename a local bookmark
///
/// Runs `jj bookmark rename <old> <new>`.
/// Only works for local bookmarks. Remote bookmarks cannot be renamed.
pub fn bookmark_rename(&self, old_name: &str, new_name: &str) -> Result<String, JjError> {
self.run_str(&[
commands::BOOKMARK,
commands::BOOKMARK_RENAME,
old_name,
new_name,
])
}
/// Forget bookmarks (removes local and remote tracking info)
///
/// Unlike `bookmark delete`, forget removes remote tracking information.
/// The bookmark will NOT be re-created on the next `jj git fetch`.
pub fn bookmark_forget(&self, names: &[&str]) -> Result<String, JjError> {
let mut args = vec![commands::BOOKMARK, commands::BOOKMARK_FORGET];
args.extend(names);
self.run_str(&args)
}
/// Run `jj next --edit` to move @ to the next child
pub fn next(&self) -> Result<String, JjError> {
self.run_str(&[commands::NEXT, flags::EDIT_FLAG])
}
/// Run `jj prev --edit` to move @ to the previous parent
pub fn prev(&self) -> Result<String, JjError> {
self.run_str(&[commands::PREV, flags::EDIT_FLAG])
}
/// Run `jj duplicate <change_id>` to create a copy of the specified change
///
/// Returns the jj stderr output containing the new change ID.
/// Note: `jj duplicate` writes its result to stderr, not stdout.
/// Output format: "Duplicated <commit_id> as <new_change_id> <new_commit_id> <description>"
pub fn duplicate(&self, revision: &str) -> Result<String, JjError> {
let mut cmd = Command::new(constants::JJ_COMMAND);
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
cmd.arg(flags::NO_COLOR);
cmd.args([commands::DUPLICATE, revision]);
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stderr).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Run `jj git fetch` to fetch from default remotes
///
/// Returns the command output describing what was fetched.
/// Empty output typically means "already up to date".
pub fn git_fetch(&self) -> Result<String, JjError> {
self.run_str(&[commands::GIT, commands::GIT_FETCH])
}
/// Run `jj git fetch --all-remotes`
pub fn git_fetch_all_remotes(&self) -> Result<String, JjError> {
self.run_str(&[commands::GIT, commands::GIT_FETCH, flags::ALL_REMOTES])
}
/// Run `jj git fetch --remote <name>`
pub fn git_fetch_remote(&self, remote: &str) -> Result<String, JjError> {
self.run_str(&[commands::GIT, commands::GIT_FETCH, flags::REMOTE, remote])
}
/// Run `jj git fetch --tracked`
///
/// Fetches only bookmarks that are already tracked from the default remote(s).
/// `flags::TRACKED` (`"--tracked"`) is the same string for both fetch and push.
pub fn git_fetch_tracked(&self) -> Result<String, JjError> {
self.run_str(&[commands::GIT, commands::GIT_FETCH, flags::TRACKED])
}
/// Run `jj git fetch --tracked --remote <name>`
pub fn git_fetch_tracked_remote(&self, remote: &str) -> Result<String, JjError> {
self.run_str(&[
commands::GIT,
commands::GIT_FETCH,
flags::TRACKED,
flags::REMOTE,
remote,
])
}
/// Run `jj git remote list` to get all remote names
pub fn git_remote_list(&self) -> Result<Vec<String>, JjError> {
let output = self.run_str(&[
commands::GIT,
commands::GIT_REMOTE,
commands::GIT_REMOTE_LIST,
])?;
Ok(output
.lines()
.filter_map(|line| line.split_whitespace().next().map(|s| s.to_string()))
.collect())
}
/// Run `jj git push --bookmark <name>` to push a bookmark to remote
///
/// Pushes the specified bookmark to the default remote (origin).
/// jj automatically performs force-with-lease equivalent safety checks.
pub fn git_push_bookmark(&self, bookmark_name: &str) -> Result<String, JjError> {
self.run_str(&[
commands::GIT,
commands::GIT_PUSH,
flags::BOOKMARK_FLAG,
bookmark_name,
])
}
/// Run `jj git push --bookmark <name> --allow-new` for new remote bookmarks
///
/// Same as git_push_bookmark but allows creating new remote bookmarks.
/// Note: --allow-new is deprecated in jj 0.37+ but still functional.
/// Users should configure `remotes.origin.auto-track-bookmarks` for a permanent fix.
pub fn git_push_bookmark_allow_new(&self, bookmark_name: &str) -> Result<String, JjError> {
self.run_str(&[
commands::GIT,
commands::GIT_PUSH,
flags::BOOKMARK_FLAG,
bookmark_name,
flags::ALLOW_NEW,
])
}
/// Run `jj git push --dry-run --bookmark <name>` to preview push
///
/// Returns the dry-run output describing what would change on the remote.
/// Does NOT actually push anything.
///
/// On success (exit 0), returns stderr which can be parsed with `parse_push_dry_run()`.
/// On failure (exit != 0), returns `Err(JjError)` — e.g., untracked bookmark or
/// empty description validation errors.
pub fn git_push_dry_run(&self, bookmark_name: &str) -> Result<String, JjError> {
// Note: `jj git push --dry-run` outputs to stderr, not stdout,
// so we can't use the generic `run()` method here.
let mut cmd = Command::new(constants::JJ_COMMAND);
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
cmd.arg(flags::NO_COLOR);
cmd.args([
commands::GIT,
commands::GIT_PUSH,
flags::DRY_RUN,
flags::BOOKMARK_FLAG,
bookmark_name,
]);
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stderr).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Run `jj git push --named <bookmark>=<revision>` for new remote bookmarks (jj 0.37+)
///
/// This is the recommended way to push new bookmarks in jj 0.37+.
/// The --named flag creates the bookmark if it doesn't exist, auto-tracks it,
/// and pushes it in a single operation.
pub fn git_push_named(&self, bookmark_name: &str, revision: &str) -> Result<String, JjError> {
let named_arg = format!("{}={}", bookmark_name, revision);
self.run_str(&[commands::GIT, commands::GIT_PUSH, flags::NAMED, &named_arg])
}
/// Run `jj git push --change <change_id>` to push by change ID
///
/// Automatically creates a bookmark named `push-<change_id_prefix>`
/// and pushes it to the remote. If the bookmark already exists, it
/// reuses it.
pub fn git_push_change(&self, change_id: &str) -> Result<String, JjError> {
self.run_str(&[commands::GIT, commands::GIT_PUSH, flags::CHANGE, change_id])
}
/// Run `jj git push --bookmark <name> --remote <remote>` to push to specific remote
pub fn git_push_bookmark_to_remote(
&self,
bookmark_name: &str,
remote: &str,
) -> Result<String, JjError> {
self.run_str(&[
commands::GIT,
commands::GIT_PUSH,
flags::BOOKMARK_FLAG,
bookmark_name,
flags::REMOTE,
remote,
])
}
/// Run `jj git push --bookmark <name> --allow-new --remote <remote>` for new remote bookmarks
pub fn git_push_bookmark_allow_new_to_remote(
&self,
bookmark_name: &str,
remote: &str,
) -> Result<String, JjError> {
self.run_str(&[
commands::GIT,
commands::GIT_PUSH,
flags::BOOKMARK_FLAG,
bookmark_name,
flags::ALLOW_NEW,
flags::REMOTE,
remote,
])
}
/// Run `jj git push --dry-run --bookmark <name> --remote <remote>` to preview push to specific remote
pub fn git_push_dry_run_to_remote(
&self,
bookmark_name: &str,
remote: &str,
) -> Result<String, JjError> {
let mut cmd = Command::new(constants::JJ_COMMAND);
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
cmd.arg(flags::NO_COLOR);
cmd.args([
commands::GIT,
commands::GIT_PUSH,
flags::DRY_RUN,
flags::BOOKMARK_FLAG,
bookmark_name,
flags::REMOTE,
remote,
]);
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stderr).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Run `jj git push --change <change_id> --remote <remote>`
pub fn git_push_change_to_remote(
&self,
change_id: &str,
remote: &str,
) -> Result<String, JjError> {
self.run_str(&[
commands::GIT,
commands::GIT_PUSH,
flags::CHANGE,
change_id,
flags::REMOTE,
remote,
])
}
/// Run `jj git push --change <change_id> --dry-run --remote <remote>` to preview push to specific remote
pub fn git_push_change_dry_run_to_remote(
&self,
change_id: &str,
remote: &str,
) -> Result<String, JjError> {
let mut cmd = Command::new(constants::JJ_COMMAND);
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
cmd.arg(flags::NO_COLOR);
cmd.args([
commands::GIT,
commands::GIT_PUSH,
flags::DRY_RUN,
flags::CHANGE,
change_id,
flags::REMOTE,
remote,
]);
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stderr).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Run `jj git push --change <change_id> --dry-run` to preview push
///
/// Returns stderr output describing what would change on the remote
/// if this change were pushed. Does NOT actually push anything.
pub fn git_push_change_dry_run(&self, change_id: &str) -> Result<String, JjError> {
let mut cmd = Command::new(constants::JJ_COMMAND);
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
cmd.arg(flags::NO_COLOR);
cmd.args([
commands::GIT,
commands::GIT_PUSH,
flags::DRY_RUN,
flags::CHANGE,
change_id,
]);
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stderr).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Push with a bulk flag (--all, --tracked, --deleted)
pub fn git_push_bulk(
&self,
mode: PushBulkMode,
remote: Option<&str>,
) -> Result<String, JjError> {
let mut args = vec![commands::GIT, commands::GIT_PUSH, mode.flag()];
if let Some(r) = remote {
args.extend([flags::REMOTE, r]);
}
self.run_str(&args)
}
/// Dry-run push with a bulk flag
///
/// Returns stderr output (jj git push --dry-run outputs to stderr).
pub fn git_push_bulk_dry_run(
&self,
mode: PushBulkMode,
remote: Option<&str>,
) -> Result<String, JjError> {
let mut cmd = Command::new(constants::JJ_COMMAND);
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
cmd.arg(flags::NO_COLOR);
let mut args = vec![
commands::GIT,
commands::GIT_PUSH,
flags::DRY_RUN,
mode.flag(),
];
if let Some(r) = remote {
args.extend([flags::REMOTE, r]);
}
cmd.args(&args);
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stderr).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Run `jj git push --bookmark <name>` with extra flags (e.g. --allow-private)
///
/// Used for retry after error detection.
pub fn git_push_bookmark_with_flags(
&self,
bookmark_name: &str,
extra_flags: &[&str],
) -> Result<String, JjError> {
let mut args = vec![
commands::GIT,
commands::GIT_PUSH,
flags::BOOKMARK_FLAG,
bookmark_name,
];
args.extend_from_slice(extra_flags);
self.run_str(&args)
}
/// Run `jj git push --bookmark <name> --remote <remote>` with extra flags
pub fn git_push_bookmark_to_remote_with_flags(
&self,
bookmark_name: &str,
remote: &str,
extra_flags: &[&str],
) -> Result<String, JjError> {
let mut args = vec![
commands::GIT,
commands::GIT_PUSH,
flags::BOOKMARK_FLAG,
bookmark_name,
flags::REMOTE,
remote,
];
args.extend_from_slice(extra_flags);
self.run_str(&args)
}
/// Run `jj git push --change <change_id>` with extra flags
pub fn git_push_change_with_flags(
&self,
change_id: &str,
extra_flags: &[&str],
) -> Result<String, JjError> {
let mut args = vec![commands::GIT, commands::GIT_PUSH, flags::CHANGE, change_id];
args.extend_from_slice(extra_flags);
self.run_str(&args)
}
/// Run `jj git push --change <change_id> --remote <remote>` with extra flags
pub fn git_push_change_to_remote_with_flags(
&self,
change_id: &str,
remote: &str,
extra_flags: &[&str],
) -> Result<String, JjError> {
let mut args = vec![
commands::GIT,
commands::GIT_PUSH,
flags::CHANGE,
change_id,
flags::REMOTE,
remote,
];
args.extend_from_slice(extra_flags);
self.run_str(&args)
}
/// Run `jj git push --revisions <change_id>` with extra flags
pub fn git_push_revisions_with_flags(
&self,
revision: &str,
extra_flags: &[&str],
) -> Result<String, JjError> {
let mut args = vec![
commands::GIT,
commands::GIT_PUSH,
flags::REVISIONS,
revision,
];
args.extend_from_slice(extra_flags);
self.run_str(&args)
}
/// Run `jj git push --revisions <change_id> --remote <remote>` with extra flags
pub fn git_push_revisions_to_remote_with_flags(
&self,
revision: &str,
remote: &str,
extra_flags: &[&str],
) -> Result<String, JjError> {
let mut args = vec![
commands::GIT,
commands::GIT_PUSH,
flags::REVISIONS,
revision,
flags::REMOTE,
remote,
];
args.extend_from_slice(extra_flags);
self.run_str(&args)
}
/// Run `jj git fetch --branch <name>` to fetch a specific branch
pub fn git_fetch_branch(&self, branch: &str) -> Result<String, JjError> {
self.run_str(&[commands::GIT, commands::GIT_FETCH, flags::BRANCH, branch])
}
/// Run `jj git push --revisions <change_id>` to push all bookmarks on a revision
pub fn git_push_revisions(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[
commands::GIT,
commands::GIT_PUSH,
flags::REVISIONS,
revision,
])
}
/// Run `jj git push --revisions <change_id> --remote <remote>`
pub fn git_push_revisions_to_remote(
&self,
revision: &str,
remote: &str,
) -> Result<String, JjError> {
self.run_str(&[
commands::GIT,
commands::GIT_PUSH,
flags::REVISIONS,
revision,
flags::REMOTE,
remote,
])
}
/// Run `jj git push --dry-run --revisions <change_id>` to preview push
///
/// Returns stderr output (jj git push --dry-run outputs to stderr).
pub fn git_push_revisions_dry_run(&self, revision: &str) -> Result<String, JjError> {
let mut cmd = Command::new(constants::JJ_COMMAND);
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
cmd.arg(flags::NO_COLOR);
cmd.args([
commands::GIT,
commands::GIT_PUSH,
flags::DRY_RUN,
flags::REVISIONS,
revision,
]);
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stderr).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Run `jj git push --dry-run --revisions <change_id> --remote <remote>`
pub fn git_push_revisions_dry_run_to_remote(
&self,
revision: &str,
remote: &str,
) -> Result<String, JjError> {
let mut cmd = Command::new(constants::JJ_COMMAND);
if let Some(ref path) = self.repo_path {
cmd.arg(flags::REPO_PATH).arg(path);
}
cmd.arg(flags::NO_COLOR);
cmd.args([
commands::GIT,
commands::GIT_PUSH,
flags::DRY_RUN,
flags::REVISIONS,
revision,
flags::REMOTE,
remote,
]);
let output = cmd.output().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
JjError::JjNotFound
} else {
JjError::IoError(e)
}
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stderr).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code().unwrap_or(-1);
Err(JjError::CommandFailed { stderr, exit_code })
}
}
/// Move a bookmark to a revision
///
/// Runs `jj bookmark move <name> --to <to>`.
/// Forward moves succeed; backward/sideways moves require --allow-backwards.
pub fn bookmark_move(&self, name: &str, to: &str) -> Result<String, JjError> {
self.run_str(&[
commands::BOOKMARK,
commands::BOOKMARK_MOVE,
name,
flags::TO,
to,
])
}
/// Move a bookmark with --allow-backwards
///
/// Runs `jj bookmark move <name> --to <to> --allow-backwards`.
pub fn bookmark_move_allow_backwards(&self, name: &str, to: &str) -> Result<String, JjError> {
self.run_str(&[
commands::BOOKMARK,
commands::BOOKMARK_MOVE,
name,
flags::TO,
to,
flags::ALLOW_BACKWARDS,
])
}
/// Run `jj diff -r <change_id>` for a specific change (raw output, no parse)
///
/// Returns diff-only output without the commit header (unlike `jj show`).
pub fn diff_raw(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::DIFF, flags::REVISION, revision])
}
/// Run `jj diff --git -r <change_id>` for git-compatible unified patch output
///
/// Produces output suitable for `git apply`.
pub fn diff_git_raw(&self, revision: &str) -> Result<String, JjError> {
self.run_str(&[commands::DIFF, flags::GIT_FORMAT, flags::REVISION, revision])
}
/// Run `jj diff --from <from> --to <to>` to compare two revisions
///
/// Returns the raw diff output between the two revisions.
pub fn diff_range(&self, from: &str, to: &str) -> Result<String, JjError> {
self.run_str(&[commands::DIFF, flags::FROM, from, flags::TO, to])
}
/// Run `jj diff --git --from <from> --to <to>` for git-compatible unified patch
pub fn diff_range_git(&self, from: &str, to: &str) -> Result<String, JjError> {
self.run_str(&[
commands::DIFF,
flags::GIT_FORMAT,
flags::FROM,
from,
flags::TO,
to,
])
}
/// Run `jj diff --stat --from <from> --to <to>` for histogram overview
pub fn diff_range_stat(&self, from: &str, to: &str) -> Result<String, JjError> {
self.run_str(&[
commands::DIFF,
flags::STAT,
flags::FROM,
from,
flags::TO,
to,
])
}
/// Get metadata for a specific change (for compare info)
///
/// Returns (change_id, bookmarks, author, timestamp, description).
pub fn get_change_info(
&self,
change_id: &str,
) -> Result<(String, Vec<String>, String, String, String), JjError> {
let template = Templates::change_info();
let output = self.run_str(&[
commands::LOG,
flags::NO_GRAPH,
flags::REVISION,
change_id,
flags::TEMPLATE,
template,
])?;
let line = output.lines().next().unwrap_or("");
let parts: Vec<&str> = line.splitn(5, '\t').collect();
if parts.len() == 5 {
let bookmarks: Vec<String> = if parts[1].is_empty() {
Vec::new()
} else {
parts[1].split(',').map(|s| s.to_string()).collect()
};
Ok((
parts[0].to_string(),
bookmarks,
parts[2].to_string(),
parts[3].to_string(),
parts[4].to_string(),
))
} else {
Err(JjError::ParseError(format!(
"Failed to parse change info: {}",
line
)))
}
}
/// Run `jj file annotate` to show blame information for a file
///
/// Shows the change responsible for each line of the specified file.
/// Optionally annotates at a specific revision.
///
/// Returns AnnotationContent containing line-by-line blame information.
///
/// Uses a custom template with `change_id.short(8)` to ensure change_id
/// length matches the log template, enabling reliable cross-view ID matching.
pub fn file_annotate(
&self,
file_path: &str,
revision: Option<&str>,
) -> Result<AnnotationContent, JjError> {
let template = Templates::file_annotate();
let mut args = vec![commands::FILE, commands::FILE_ANNOTATE];
if let Some(rev) = revision {
args.push(flags::REVISION);
args.push(rev);
}
args.push(flags::TEMPLATE);
args.push(template);
args.push(file_path);
let output = self.run_str(&args)?;
Parser::parse_file_annotate(&output, file_path)
}
// ── Tag operations ─────────────────────────────────────────────
/// List all local tags with their target commit info
///
/// Uses a single-stage query (unlike bookmarks which need 2 stages)
/// because `jj tag list -T` can access `normal_target` directly.
pub fn tag_list(&self) -> Result<Vec<TagInfo>, JjError> {
const TAG_LIST_TEMPLATE: &str = r#"separate("\t", name, if(remote, remote, ""), if(present, "true", "false"), if(tracked, "true", "false"), normal_target.change_id().short(8), normal_target.commit_id().short(8), normal_target.description().first_line()) ++ "\n""#;
let output = self.run_str(&[
commands::TAG,
commands::TAG_LIST,
flags::TEMPLATE,
TAG_LIST_TEMPLATE,
])?;
Ok(super::parser::parse_tag_list(&output))
}
/// Create a tag on a specific revision
///
/// Runs `jj tag set <name> -r <revision>`.
pub fn tag_set(&self, name: &str, revision: &str) -> Result<String, JjError> {
self.run_str(&[
commands::TAG,
commands::TAG_SET,
name,
flags::REVISION,
revision,
])
}
/// Delete a tag
///
/// Runs `jj tag delete <name>`.
pub fn tag_delete(&self, name: &str) -> Result<String, JjError> {
self.run_str(&[commands::TAG, commands::TAG_DELETE, name])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_executor_default() {
let executor = JjExecutor::default();
assert!(executor.repo_path().is_none());
}
#[test]
fn test_executor_with_path() {
let executor = JjExecutor::with_repo_path(PathBuf::from("/tmp/test"));
assert_eq!(executor.repo_path(), Some(&PathBuf::from("/tmp/test")));
}
#[test]
fn test_push_bulk_mode_flag() {
assert_eq!(PushBulkMode::All.flag(), "--all");
assert_eq!(PushBulkMode::Tracked.flag(), "--tracked");
assert_eq!(PushBulkMode::Deleted.flag(), "--deleted");
}
#[test]
fn test_push_bulk_mode_label() {
assert_eq!(PushBulkMode::All.label(), "all bookmarks");
assert_eq!(PushBulkMode::Tracked.label(), "tracked bookmarks");
assert_eq!(PushBulkMode::Deleted.label(), "deleted bookmarks");
}
}