-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.rs
More file actions
2887 lines (2604 loc) · 100 KB
/
Copy pathcommands.rs
File metadata and controls
2887 lines (2604 loc) · 100 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! Command Implementations
//!
//! Each command performs the operation, records it in history,
//! and shows proof references if verbose mode is enabled.
use anyhow::{Context, Result};
use colored::Colorize;
use std::fs;
use thiserror::Error;
use crate::proof_refs;
use crate::state::{Operation, OperationType, ShellState};
use crate::verification;
// Secure deletion (RMO - Remove-Match-Obliterate)
pub mod secure_deletion;
/// Typed errors raised by the command layer.
///
/// Previously several branches in the inverse/undo dispatch reached
/// `unreachable!()` after upstream filters were supposed to exclude them.
/// Those panics have been replaced with typed `CommandError::Internal*`
/// variants so that any future regression in the filtering logic surfaces
/// as a *recoverable* error rather than aborting the shell.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CommandError {
/// An `OperationType` whose inverse is dispatched by an earlier match arm
/// (e.g. `FileTruncated` → `WriteFile`, `CopyFile` → `DeleteFile`) reached
/// a branch that should have been pre-handled.
///
/// Encountering this in the wild indicates a bug in
/// [`OperationType::inverse`](crate::state::OperationType::inverse)
/// or in the surrounding match dispatch.
#[error("internal invariant violated: inverse-type arm reached for {op_type:?} which should have been handled by an earlier branch (expected WriteFile / DeleteFile)")]
InternalUnreachableInverseArm { op_type: OperationType },
/// An irreversible operation (`Obliterate`, `HardwareErase`) reached the
/// inverse dispatch despite `inverse()` returning `None` for these types.
/// The filter at the top of `undo`/`rollback` is supposed to skip them.
#[error("internal invariant violated: irreversible operation {op_type:?} reached inverse dispatch — `OperationType::inverse` should have returned None and the caller should have filtered")]
InternalUnreachableIrreversible { op_type: OperationType },
/// `explain_command` extracted the path-bearing arm of a pattern that
/// only contains `Chmod` or `Chown`, but the inner re-match observed a
/// different variant.
#[error("internal invariant violated: explain_command path-extraction reached a non-{{Chmod,Chown}} arm")]
InternalUnreachableExplainPathArm,
}
/// Create a directory at the specified path.
///
/// This operation is reversible via [`undo`] and corresponds to the Lean 4 theorem
/// `mkdir_rmdir_reversible` in FilesystemModel.lean.
///
/// # Arguments
/// * `state` - Mutable shell state for recording the operation
/// * `path` - Path relative to shell root or absolute path
/// * `verbose` - Whether to show proof references
///
/// # Errors
/// Returns error if:
/// - Path already exists (EEXIST)
/// - Parent directory doesn't exist (ENOENT)
/// - Insufficient permissions
///
/// # Examples
/// ```no_run
/// use vsh::commands;
/// use vsh::state::ShellState;
///
/// let mut state = ShellState::new("/tmp/test")?;
/// commands::mkdir(&mut state, "project", false)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn mkdir(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
let full_path = state.resolve_path(path);
// Optional Lean 4 verification (compile-time feature flag)
// Provides mathematical guarantee that preconditions are satisfied
verification::verify_mkdir(state.root(), path)?;
// Check preconditions (matching Coq)
if full_path.exists() {
anyhow::bail!("Path already exists (EEXIST)");
}
let parent = full_path.parent().context("Invalid path")?;
if !parent.exists() {
anyhow::bail!("Parent directory does not exist (ENOENT)");
}
// Execute operation
fs::create_dir(&full_path).context("mkdir failed")?;
// Record in history
let op = Operation::new(OperationType::Mkdir, path.to_string(), None);
let op_id = op.id;
state.record_operation(op);
// Output
println!(
"{} {} {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"mkdir".bright_green(),
path
);
if verbose {
let proof = OperationType::Mkdir.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
println!(" {} rmdir {}", "Undo:".bright_black(), path);
}
Ok(())
}
/// Remove an empty directory at the specified path.
///
/// This operation is reversible via [`undo`] and corresponds to the Lean 4 theorem
/// `rmdir_mkdir_reversible` in FilesystemModel.lean.
///
/// # Arguments
/// * `state` - Mutable shell state for recording the operation
/// * `path` - Path relative to shell root or absolute path
/// * `verbose` - Whether to show proof references
///
/// # Errors
/// Returns error if:
/// - Path does not exist (ENOENT)
/// - Path is not a directory (ENOTDIR)
/// - Directory is not empty (ENOTEMPTY)
/// - Insufficient permissions
///
/// # Examples
/// ```no_run
/// # use vsh::commands;
/// # use vsh::state::ShellState;
/// let mut state = ShellState::new("/tmp/test")?;
/// commands::mkdir(&mut state, "old_dir", false)?;
/// commands::rmdir(&mut state, "old_dir", false)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn rmdir(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
let full_path = state.resolve_path(path);
// Optional Lean 4 verification
verification::verify_rmdir(state.root(), path)?;
// Check preconditions
if !full_path.exists() {
anyhow::bail!("Path does not exist (ENOENT)");
}
if !full_path.is_dir() {
anyhow::bail!("Path is not a directory (ENOTDIR)");
}
if fs::read_dir(&full_path)?.next().is_some() {
anyhow::bail!("Directory is not empty (ENOTEMPTY)");
}
// Execute
fs::remove_dir(&full_path).context("rmdir failed")?;
// Record
let op = Operation::new(OperationType::Rmdir, path.to_string(), None);
let op_id = op.id;
state.record_operation(op);
println!(
"{} {} {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"rmdir".bright_yellow(),
path
);
if verbose {
let proof = OperationType::Rmdir.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
}
Ok(())
}
/// Create an empty file at the specified path.
///
/// This operation is reversible via [`undo`] and corresponds to the Lean 4 theorem
/// `createFile_deleteFile_reversible` in FileOperations.lean.
///
/// # Arguments
/// * `state` - Mutable shell state for recording the operation
/// * `path` - Path relative to shell root or absolute path
/// * `verbose` - Whether to show proof references
///
/// # Errors
/// Returns error if:
/// - Path already exists (EEXIST)
/// - Parent directory doesn't exist (ENOENT)
/// - Insufficient permissions
///
/// # Examples
/// ```no_run
/// # use vsh::commands;
/// # use vsh::state::ShellState;
/// let mut state = ShellState::new("/tmp/test")?;
/// commands::touch(&mut state, "README.md", false)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn touch(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
let full_path = state.resolve_path(path);
// Optional Lean 4 verification
verification::verify_create_file(state.root(), path)?;
if full_path.exists() {
anyhow::bail!("Path already exists (EEXIST)");
}
let parent = full_path.parent().context("Invalid path")?;
if !parent.exists() {
anyhow::bail!("Parent directory does not exist (ENOENT)");
}
fs::write(&full_path, "").context("touch failed")?;
let op = Operation::new(OperationType::CreateFile, path.to_string(), None);
let op_id = op.id;
state.record_operation(op);
println!(
"{} {} {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"touch".bright_green(),
path
);
if verbose {
let proof = OperationType::CreateFile.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
println!(" {} rm {}", "Undo:".bright_black(), path);
}
Ok(())
}
/// Remove a file at the specified path.
///
/// The file's content is preserved for undo. This operation is reversible via [`undo`]
/// and corresponds to the Lean 4 theorem `deleteFile_createFile_reversible`.
///
/// # Arguments
/// * `state` - Mutable shell state for recording the operation
/// * `path` - Path relative to shell root or absolute path
/// * `verbose` - Whether to show proof references
///
/// # Errors
/// Returns error if:
/// - Path does not exist (ENOENT)
/// - Path is a directory (EISDIR) - use [`rmdir`] instead
/// - Insufficient permissions
///
/// # Examples
/// ```no_run
/// # use vsh::commands;
/// # use vsh::state::ShellState;
/// let mut state = ShellState::new("/tmp/test")?;
/// commands::touch(&mut state, "temp.txt", false)?;
/// commands::rm(&mut state, "temp.txt", false)?;
/// commands::undo(&mut state, 1, false)?; // File restored
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn rm(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
let full_path = state.resolve_path(path);
// Optional Lean 4 verification
verification::verify_delete_file(state.root(), path)?;
if !full_path.exists() {
anyhow::bail!("Path does not exist (ENOENT)");
}
if full_path.is_dir() {
anyhow::bail!("Path is a directory - use rmdir (EISDIR)");
}
// Store content for undo (pure read of the soon-to-be-deleted file;
// routed through fs_pure to honour the noatime discipline).
let content = crate::fs_pure::read_to_end(&full_path).unwrap_or_default();
fs::remove_file(&full_path).context("rm failed")?;
let op =
Operation::new(OperationType::DeleteFile, path.to_string(), None).with_undo_data(content);
let op_id = op.id;
state.record_operation(op);
println!(
"{} {} {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"rm".bright_red(),
path
);
if verbose {
let proof = OperationType::DeleteFile.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
}
Ok(())
}
/// Copy a file from source to destination.
///
/// This operation is reversible via [`undo`] (deletes the copy) and corresponds
/// to the Lean 4 theorem `copyFile_reversible` in CopyMoveOperations.lean.
///
/// # Arguments
/// * `state` - Mutable shell state for recording the operation
/// * `src` - Source path relative to shell root or absolute path
/// * `dst` - Destination path relative to shell root or absolute path
/// * `verbose` - Whether to show proof references
///
/// # Errors
/// Returns error if:
/// - Source does not exist (ENOENT)
/// - Source is a directory (EISDIR) - directory copy not yet supported
/// - Destination already exists (EEXIST)
/// - Parent of destination doesn't exist (ENOENT)
///
/// # Examples
/// ```no_run
/// # use vsh::commands;
/// # use vsh::state::ShellState;
/// let mut state = ShellState::new("/tmp/test")?;
/// commands::touch(&mut state, "original.txt", false)?;
/// commands::cp(&mut state, "original.txt", "copy.txt", false)?;
/// commands::undo(&mut state, 1, false)?; // Deletes copy.txt
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn cp(state: &mut ShellState, src: &str, dst: &str, verbose: bool) -> Result<()> {
let src_path = state.resolve_path(src);
let dst_path = state.resolve_path(dst);
// Optional verification
verification::verify_copy_file(state.root(), src, dst)?;
// Check preconditions (matching Lean 4 copyFilePrecondition)
if !src_path.exists() {
anyhow::bail!("Source does not exist (ENOENT): {}", src);
}
if src_path.is_dir() {
anyhow::bail!("Source is a directory - recursive copy not yet supported (EISDIR)");
}
if dst_path.exists() {
anyhow::bail!("Destination already exists (EEXIST): {}", dst);
}
let dst_parent = dst_path.parent().context("Invalid destination path")?;
if !dst_parent.exists() {
anyhow::bail!("Parent of destination does not exist (ENOENT)");
}
// Execute operation
fs::copy(&src_path, &dst_path).context("cp failed")?;
// Record in history: path = dst, undo_data = src path for reference
// Undo = delete the destination file
let op = Operation::new(OperationType::CopyFile, dst.to_string(), None)
.with_undo_data(src.as_bytes().to_vec());
let op_id = op.id;
state.record_operation(op);
println!(
"{} {} {} → {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"cp".bright_green(),
src,
dst
);
if verbose {
let proof = OperationType::CopyFile.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
println!(" {} rm {}", "Undo:".bright_black(), dst);
}
Ok(())
}
/// Move/rename a file or directory.
///
/// This operation is reversible via [`undo`] (moves it back) and corresponds
/// to the Lean 4 theorem `move_reversible` in CopyMoveOperations.lean.
///
/// # Arguments
/// * `state` - Mutable shell state for recording the operation
/// * `src` - Source path relative to shell root or absolute path
/// * `dst` - Destination path relative to shell root or absolute path
/// * `verbose` - Whether to show proof references
///
/// # Errors
/// Returns error if:
/// - Source does not exist (ENOENT)
/// - Destination already exists (EEXIST)
/// - Source and destination are the same
/// - Moving a directory into itself
///
/// # Examples
/// ```no_run
/// # use vsh::commands;
/// # use vsh::state::ShellState;
/// let mut state = ShellState::new("/tmp/test")?;
/// commands::touch(&mut state, "old.txt", false)?;
/// commands::mv(&mut state, "old.txt", "new.txt", false)?;
/// commands::undo(&mut state, 1, false)?; // Moves new.txt back to old.txt
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn mv(state: &mut ShellState, src: &str, dst: &str, verbose: bool) -> Result<()> {
let src_path = state.resolve_path(src);
let dst_path = state.resolve_path(dst);
// Optional verification
verification::verify_move(state.root(), src, dst)?;
// Check preconditions (matching Lean 4 movePrecondition)
if !src_path.exists() {
anyhow::bail!("Source does not exist (ENOENT): {}", src);
}
if dst_path.exists() {
anyhow::bail!("Destination already exists (EEXIST): {}", dst);
}
if src_path == dst_path {
anyhow::bail!("Source and destination are the same");
}
// Prevent moving directory into itself
if src_path.is_dir() && dst_path.starts_with(&src_path) {
anyhow::bail!("Cannot move directory into itself");
}
let dst_parent = dst_path.parent().context("Invalid destination path")?;
if !dst_parent.exists() {
anyhow::bail!("Parent of destination does not exist (ENOENT)");
}
// Execute operation
fs::rename(&src_path, &dst_path).context("mv failed")?;
// Record: store both paths null-separated for undo
// path = "src\0dst" so undo can move dst back to src
let combined_path = format!("{}\0{}", src, dst);
let op = Operation::new(OperationType::Move, combined_path, None);
let op_id = op.id;
state.record_operation(op);
println!(
"{} {} {} → {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"mv".bright_green(),
src,
dst
);
if verbose {
let proof = OperationType::Move.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
println!(" {} mv {} {}", "Undo:".bright_black(), dst, src);
}
Ok(())
}
/// Create a symbolic link.
///
/// This operation is reversible via [`undo`] (removes the symlink) and corresponds
/// to the Lean 4 theorem `symlink_unlink_reversible` in SymlinkOperations.lean.
///
/// # Arguments
/// * `state` - Mutable shell state for recording the operation
/// * `target` - The path the symlink points to
/// * `link` - The path where the symlink is created
/// * `verbose` - Whether to show proof references
///
/// # Errors
/// Returns error if:
/// - Link path already exists (EEXIST)
/// - Parent of link doesn't exist (ENOENT)
///
/// # Examples
/// ```no_run
/// # use vsh::commands;
/// # use vsh::state::ShellState;
/// let mut state = ShellState::new("/tmp/test")?;
/// commands::touch(&mut state, "real.txt", false)?;
/// commands::symlink(&mut state, "real.txt", "link.txt", false)?;
/// commands::undo(&mut state, 1, false)?; // Removes link.txt
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn symlink(state: &mut ShellState, target: &str, link: &str, verbose: bool) -> Result<()> {
let link_path = state.resolve_path(link);
// Optional verification
verification::verify_symlink(state.root(), target, link)?;
// Check preconditions (matching Lean 4 SymlinkPrecondition)
if link_path.exists() || link_path.symlink_metadata().is_ok() {
anyhow::bail!("Link path already exists (EEXIST): {}", link);
}
let link_parent = link_path.parent().context("Invalid link path")?;
if !link_parent.exists() {
anyhow::bail!("Parent of link does not exist (ENOENT)");
}
// Execute operation
#[cfg(unix)]
std::os::unix::fs::symlink(target, &link_path).context("ln -s failed")?;
#[cfg(not(unix))]
anyhow::bail!("Symbolic links not supported on this platform");
// Record: path = link path, undo_data = target for re-creation
let op = Operation::new(OperationType::Symlink, link.to_string(), None)
.with_undo_data(target.as_bytes().to_vec());
let op_id = op.id;
state.record_operation(op);
println!(
"{} {} {} → {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"ln -s".bright_green(),
target,
link
);
if verbose {
let proof = OperationType::Symlink.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
println!(" {} unlink {}", "Undo:".bright_black(), link);
}
Ok(())
}
/// Change file permissions (reversible — captures old mode for undo).
///
/// Supports octal modes (755, 0644) and symbolic modes (u+x, go-w, a=r).
/// Records the previous permissions in undo_data for perfect reversal.
///
/// # Proof Reference
/// PermissionOperations.lean: chmod_reversible
pub fn chmod(state: &mut ShellState, mode_str: &str, path: &str, verbose: bool) -> Result<()> {
let file_path = state.resolve_path(path);
if !file_path.exists() && file_path.symlink_metadata().is_err() {
anyhow::bail!("chmod: cannot access '{}': No such file or directory", path);
}
// Capture current permissions for undo
#[cfg(unix)]
let old_mode = {
use std::os::unix::fs::PermissionsExt;
let metadata =
fs::symlink_metadata(&file_path).context("chmod: failed to read metadata")?;
metadata.permissions().mode()
};
#[cfg(not(unix))]
let old_mode: u32 = 0;
// Parse mode
let new_mode = parse_chmod_mode(mode_str, old_mode)
.context(format!("chmod: invalid mode: '{}'", mode_str))?;
// Apply permissions
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = fs::Permissions::from_mode(new_mode);
fs::set_permissions(&file_path, perms).context("chmod failed")?;
}
#[cfg(not(unix))]
anyhow::bail!("chmod not supported on this platform");
// Record operation with old mode for undo
let op = Operation::new(OperationType::Chmod, path.to_string(), None)
.with_undo_data(old_mode.to_le_bytes().to_vec());
let op_id = op.id;
state.record_operation(op);
println!(
"{} {} {:o} {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"chmod".bright_green(),
new_mode & 0o7777,
path
);
if verbose {
let proof = OperationType::Chmod.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
println!(
" {} chmod {:o} {}",
"Undo:".bright_black(),
old_mode & 0o7777,
path
);
}
Ok(())
}
/// Parse chmod mode string — supports octal (755) and symbolic (u+x, go-w, a=rwx).
fn parse_chmod_mode(mode_str: &str, current_mode: u32) -> Result<u32> {
// Try octal first
if mode_str.chars().all(|c| c.is_ascii_digit()) {
let mode = u32::from_str_radix(mode_str, 8).context("Invalid octal mode")?;
if mode > 0o7777 {
anyhow::bail!("Mode out of range: {:o}", mode);
}
// Preserve file type bits, only change permission bits
return Ok((current_mode & !0o7777) | mode);
}
// Symbolic mode: [ugoa]*[+-=][rwxXst]*
let mut result = current_mode;
for part in mode_str.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
// Parse who: u, g, o, a
let mut who_mask: u32 = 0;
let mut chars = part.chars().peekable();
while let Some(&c) = chars.peek() {
match c {
'u' => {
who_mask |= 0o700;
chars.next();
}
'g' => {
who_mask |= 0o070;
chars.next();
}
'o' => {
who_mask |= 0o007;
chars.next();
}
'a' => {
who_mask |= 0o777;
chars.next();
}
'+' | '-' | '=' => break,
_ => anyhow::bail!("Invalid who character: '{}'", c),
}
}
if who_mask == 0 {
who_mask = 0o777; // default = all
}
// Parse operator
let op = chars.next().context("Missing operator in chmod mode")?;
// Parse permissions
let mut perm_bits: u32 = 0;
for c in chars {
match c {
'r' => perm_bits |= 0o444,
'w' => perm_bits |= 0o222,
'x' => perm_bits |= 0o111,
'X' => {
// Execute only if directory or already has execute
if current_mode & 0o111 != 0 {
perm_bits |= 0o111;
}
}
's' => perm_bits |= 0o6000, // setuid/setgid
't' => perm_bits |= 0o1000, // sticky
_ => anyhow::bail!("Invalid permission character: '{}'", c),
}
}
let masked = perm_bits & who_mask;
match op {
'+' => result |= masked,
'-' => result &= !masked,
'=' => {
result &= !who_mask;
result |= masked;
}
_ => anyhow::bail!("Invalid operator: '{}'", op),
}
}
Ok(result)
}
/// Change file ownership (reversible — captures old uid:gid for undo).
///
/// Supports `user`, `user:group`, `:group`, and `user:` formats.
/// Records previous ownership in undo_data for perfect reversal.
///
/// # Proof Reference
/// PermissionOperations.lean: chown_reversible
#[cfg(unix)]
pub fn chown(state: &mut ShellState, owner_str: &str, path: &str, verbose: bool) -> Result<()> {
let file_path = state.resolve_path(path);
if !file_path.exists() && file_path.symlink_metadata().is_err() {
anyhow::bail!("chown: cannot access '{}': No such file or directory", path);
}
// Capture current ownership for undo
use std::os::unix::fs::MetadataExt;
let metadata = fs::symlink_metadata(&file_path).context("chown: failed to read metadata")?;
let old_uid = metadata.uid();
let old_gid = metadata.gid();
// Parse owner[:group]
let (new_uid, new_gid) = parse_chown_spec(owner_str, old_uid, old_gid)?;
// Apply ownership via libc
let c_path = std::ffi::CString::new(file_path.to_str().context("Invalid path")?)
.context("Path contains null bytes")?;
// SAFETY: c_path is a valid NUL-terminated CString; chown is a POSIX syscall.
let ret = unsafe { libc::chown(c_path.as_ptr(), new_uid, new_gid) };
if ret != 0 {
let err = std::io::Error::last_os_error();
anyhow::bail!("chown failed: {}", err);
}
// Record operation with old uid:gid for undo
let undo_str = format!("{}:{}", old_uid, old_gid);
let op = Operation::new(OperationType::Chown, path.to_string(), None)
.with_undo_data(undo_str.into_bytes());
let op_id = op.id;
state.record_operation(op);
println!(
"{} {} {} {}",
format!("[op:{}]", &op_id.to_string()[..8]).bright_black(),
"chown".bright_green(),
owner_str,
path
);
if verbose {
let proof = OperationType::Chown.proof_reference();
println!(" {} {}", "Proof:".bright_black(), proof.format_short());
println!(
" {} chown {}:{} {}",
"Undo:".bright_black(),
old_uid,
old_gid,
path
);
}
Ok(())
}
/// Parse chown owner spec: `user`, `user:group`, `:group`, `user:`.
/// Returns (uid, gid) where unchanged values keep the original.
#[cfg(unix)]
fn parse_chown_spec(spec: &str, current_uid: u32, current_gid: u32) -> Result<(u32, u32)> {
if spec.contains(':') {
let parts: Vec<&str> = spec.splitn(2, ':').collect();
let uid = if parts[0].is_empty() {
current_uid
} else {
parts[0].parse::<u32>().unwrap_or_else(|_| {
// Try looking up user by name
match std::ffi::CString::new(parts[0]) {
Ok(c_name) => {
// SAFETY: c_name is a valid NUL-terminated string; getpwnam
// returns a pointer to a static passwd struct or null.
let pw = unsafe { libc::getpwnam(c_name.as_ptr()) };
if pw.is_null() {
u32::MAX
} else {
unsafe { (*pw).pw_uid }
}
}
Err(_) => u32::MAX, // Name contains null bytes — invalid
}
})
};
let gid = if parts[1].is_empty() {
current_gid
} else {
parts[1].parse::<u32>().unwrap_or_else(|_| {
match std::ffi::CString::new(parts[1]) {
Ok(c_name) => {
// SAFETY: c_name is a valid NUL-terminated string; getgrnam
// returns a pointer to a static group struct or null.
let gr = unsafe { libc::getgrnam(c_name.as_ptr()) };
if gr.is_null() {
u32::MAX
} else {
unsafe { (*gr).gr_gid }
}
}
Err(_) => u32::MAX, // Name contains null bytes — invalid
}
})
};
if uid == u32::MAX {
anyhow::bail!("chown: invalid user: '{}'", parts[0]);
}
if gid == u32::MAX {
anyhow::bail!("chown: invalid group: '{}'", parts[1]);
}
Ok((uid, gid))
} else {
// Just user — keep group
let uid = spec.parse::<u32>().unwrap_or_else(|_| {
match std::ffi::CString::new(spec) {
Ok(c_name) => {
// SAFETY: c_name is a valid NUL-terminated string; getpwnam is POSIX-safe.
let pw = unsafe { libc::getpwnam(c_name.as_ptr()) };
if pw.is_null() {
u32::MAX
} else {
unsafe { (*pw).pw_uid }
}
}
Err(_) => u32::MAX,
}
});
if uid == u32::MAX {
anyhow::bail!("chown: invalid user: '{}'", spec);
}
Ok((uid, current_gid))
}
}
/// Undo the last N operations.
///
/// Reverses operations in reverse order, executing their inverse operations.
/// Each undo is itself a new operation and can be undone with [`redo`].
///
/// # Arguments
/// * `state` - Mutable shell state for accessing history
/// * `count` - Number of operations to undo (default: 1)
/// * `verbose` - Whether to show proof references
///
/// # Errors
/// Returns error if:
/// - No operations to undo
/// - Inverse operation fails (filesystem inconsistency)
/// - Missing undo data for file operations
///
/// # Examples
/// ```no_run
/// # use vsh::commands;
/// # use vsh::state::ShellState;
/// let mut state = ShellState::new("/tmp/test")?;
/// commands::mkdir(&mut state, "test", false)?;
/// commands::undo(&mut state, 1, false)?; // Removes test/
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn undo(state: &mut ShellState, count: usize, verbose: bool) -> Result<()> {
// Clone operations to avoid borrowing state
let ops_to_undo: Vec<Operation> = state.last_n_undoable(count).into_iter().cloned().collect();
if ops_to_undo.is_empty() {
println!("{}", "Nothing to undo".bright_yellow());
return Ok(());
}
for op in &ops_to_undo {
// Check if operation is reversible
let Some(inverse_type) = op.op_type.inverse() else {
println!(
"{} {} (irreversible: {})",
"Cannot undo".bright_red(),
op.path,
op.op_type
);
continue;
};
let path = state.resolve_path(&op.path);
// Execute inverse operation
match inverse_type {
OperationType::Rmdir => {
fs::remove_dir(&path).context("Undo mkdir failed")?;
}
OperationType::Mkdir => {
fs::create_dir(&path).context("Undo rmdir failed")?;
}
OperationType::DeleteFile => {
fs::remove_file(&path).context("Undo touch failed")?;
}
OperationType::CreateFile => {
let content = op.undo_data.as_ref().cloned().unwrap_or_default();
fs::write(&path, content).context("Undo rm failed")?;
}
OperationType::WriteFile => {
let content = op.undo_data.as_ref().cloned().unwrap_or_default();
fs::write(&path, content).context("Undo write failed")?;
}
OperationType::FileAppended => {
// Undo append: truncate file to original size
let size_bytes = op
.undo_data
.as_ref()
.context("Missing original size for undo")?;
let original_size =
u64::from_le_bytes(size_bytes[..8].try_into().context("Invalid size data")?);
use std::fs::OpenOptions;
let file = OpenOptions::new()
.write(true)
.open(&path)
.context("Failed to open file for truncation")?;
file.set_len(original_size)
.context("Undo append (truncate) failed")?;
}
OperationType::Move => {
// Undo move = move it back (dst -> src)
let parts: Vec<&str> = op.path.splitn(2, '\0').collect();
if parts.len() != 2 {
anyhow::bail!("Invalid move operation record");
}
let src_path = state.resolve_path(parts[0]);
let dst_path = state.resolve_path(parts[1]);
fs::rename(&dst_path, &src_path).context("Undo mv failed")?;
}
OperationType::Unlink => {
// Undo symlink = remove the symlink
fs::remove_file(&path).context("Undo ln -s failed")?;
}
OperationType::Symlink => {
// Undo unlink = re-create the symlink
let target = op
.undo_data
.as_ref()
.map(|d| String::from_utf8_lossy(d).to_string())
.context("Missing symlink target for undo")?;
#[cfg(unix)]
std::os::unix::fs::symlink(&target, &path)
.context("Undo unlink (re-create symlink) failed")?;
#[cfg(not(unix))]
anyhow::bail!("Symbolic links not supported on this platform");
}
OperationType::SetVariable => {
// Undo variable set = restore previous value (or unset if was unset)
let previous: Option<crate::state::VariableValue> = op
.undo_data
.as_ref()
.and_then(|d| serde_json::from_slice(d).ok())
.unwrap_or(None);
match previous {
Some(val) => {
state.variables.insert(op.path.clone(), val);
}
None => {
state.variables.remove(&op.path);
state.exported_vars.remove(&op.path);
}
}
}
OperationType::UnsetVariable => {
// Undo unset = restore the variable to its previous value
let previous: Option<crate::state::VariableValue> = op
.undo_data
.as_ref()
.and_then(|d| serde_json::from_slice(d).ok())
.unwrap_or(None);
if let Some(val) = previous {
state.variables.insert(op.path.clone(), val);
}
}
OperationType::Chmod => {
// Undo chmod = restore previous mode from undo_data
let mode_bytes = op
.undo_data
.as_ref()
.context("Missing mode data for undo chmod")?;
let old_mode =
u32::from_le_bytes(mode_bytes[..4].try_into().context("Invalid mode data")?);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = fs::Permissions::from_mode(old_mode);
fs::set_permissions(&path, perms).context("Undo chmod failed")?;
}
}
OperationType::Chown => {
// Undo chown = restore previous uid:gid from undo_data
let uid_gid_str = op
.undo_data
.as_ref()
.map(|d| String::from_utf8_lossy(d).to_string())
.context("Missing uid:gid data for undo chown")?;
#[cfg(unix)]
{
let parts: Vec<&str> = uid_gid_str.splitn(2, ':').collect();
let uid: u32 = parts[0].parse().context("Invalid uid")?;
let gid: u32 = parts[1].parse().context("Invalid gid")?;