-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
333 lines (291 loc) · 10.8 KB
/
Copy pathmain.rs
File metadata and controls
333 lines (291 loc) · 10.8 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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! Valence Shell (vsh) - A Formally Verified Reversible Shell
//!
//! This is the user-facing CLI for Valence Shell. It provides:
//! - Interactive shell with command history
//! - Undo/redo for all filesystem operations
//! - Transaction grouping
//! - Proof references for each operation
//! - Shell script execution (`vsh script.sh`, `vsh -c "cmd"`)
//!
//! Architecture:
//! - This Rust binary handles UI and fast-path operations
//! - Complex operations delegate to BEAM daemon
//! - Zig FFI provides the verified POSIX interface
//!
//! Author: Jonathan D.A. Jewell
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use colored::Colorize;
// Use library modules
use vsh::executable::{ExecutableCommand, ExecutionResult};
use vsh::{commands, state};
// REPL modules (choose one based on feature flags)
#[cfg(feature = "enhanced-repl")]
use vsh::enhanced_repl as repl_impl;
#[cfg(not(feature = "enhanced-repl"))]
use vsh::repl as repl_impl;
/// Valence Shell - Every operation is reversible
#[derive(Parser)]
#[command(name = "vsh")]
#[command(author = "Hyperpolymath")]
#[command(version = "0.9.0")]
#[command(about = "A formally verified reversible shell", long_about = None)]
struct Cli {
/// Enable verbose output showing proof references
#[arg(short, long)]
verbose: bool,
/// Path to sandbox root (default: current directory)
#[arg(short, long)]
root: Option<String>,
/// Execute command string and exit (like bash -c)
#[arg(short = 'c')]
command_string: Option<String>,
/// Script file to execute (positional argument)
#[arg(value_name = "SCRIPT")]
script: Option<String>,
/// Arguments passed to the script ($1, $2, etc.)
#[arg(value_name = "ARGS", trailing_var_arg = true)]
script_args: Vec<String>,
/// Subcommand to run (or enter interactive mode if none)
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand)]
enum Commands {
/// Create a directory (reversible)
Mkdir {
/// Path to create
path: String,
},
/// Remove a directory (reversible)
Rmdir {
/// Path to remove
path: String,
},
/// Create an empty file (reversible)
Touch {
/// Path to create
path: String,
},
/// Remove a file (reversible)
Rm {
/// Path to remove
path: String,
},
/// Undo the last operation
Undo {
/// Number of operations to undo (default: 1)
#[arg(short, long, default_value = "1")]
count: usize,
},
/// Redo the last undone operation
Redo {
/// Number of operations to redo (default: 1)
#[arg(short, long, default_value = "1")]
count: usize,
},
/// Show operation history with proof references
History {
/// Show last N operations
#[arg(short, long, default_value = "10")]
count: usize,
/// Show full proof references
#[arg(short, long)]
proofs: bool,
},
/// Start a transaction group
Begin {
/// Transaction name
name: String,
},
/// Commit current transaction
Commit,
/// Rollback current transaction
Rollback,
/// Show undo graph
Graph,
/// Enter interactive shell mode
Shell,
/// Show proof status and verification info
Proofs,
}
fn main() -> Result<()> {
let cli = Cli::parse();
// Initialize shell state
let root = match cli.root {
Some(r) => r,
None => {
let current = std::env::current_dir().context("Failed to get current directory")?;
current.to_string_lossy().to_string()
}
};
let mut state = state::ShellState::new(&root)?;
// Mode 1: Execute inline command string (-c "command")
if let Some(ref cmd_string) = cli.command_string {
// Set positional parameters: $0 = "vsh", $1.. = script_args
state.set_positional_params(cli.script_args.clone());
return execute_script_content(cmd_string, &mut state);
}
// Mode 2: Execute a script file (vsh script.sh [args...])
if let Some(ref script_path) = cli.script {
// Check for shebang or just execute
let script_content = vsh::fs_pure::read_to_string(std::path::Path::new(script_path))
.context(format!("Cannot read script: {}", script_path))?;
// Set positional parameters: $0 = script_path, $1.. = script_args
state.set_positional_params(cli.script_args.clone());
// Skip shebang line if present
let content = if script_content.starts_with("#!") {
// Skip first line (shebang)
match script_content.find('\n') {
Some(pos) => &script_content[pos + 1..],
None => "",
}
} else {
&script_content
};
return execute_script_content(content, &mut state);
}
// Mode 3: Interactive or subcommand mode
// Print banner in interactive mode or verbose
if cli.command.is_none() || cli.verbose {
print_banner();
}
match cli.command {
Some(Commands::Mkdir { path }) => {
commands::mkdir(&mut state, &path, cli.verbose)?;
}
Some(Commands::Rmdir { path }) => {
commands::rmdir(&mut state, &path, cli.verbose)?;
}
Some(Commands::Touch { path }) => {
commands::touch(&mut state, &path, cli.verbose)?;
}
Some(Commands::Rm { path }) => {
commands::rm(&mut state, &path, cli.verbose)?;
}
Some(Commands::Undo { count }) => {
commands::undo(&mut state, count, cli.verbose)?;
}
Some(Commands::Redo { count }) => {
commands::redo(&mut state, count, cli.verbose)?;
}
Some(Commands::History { count, proofs }) => {
commands::history(&state, count, proofs)?;
}
Some(Commands::Begin { name }) => {
commands::begin_transaction(&mut state, &name)?;
}
Some(Commands::Commit) => {
commands::commit_transaction(&mut state)?;
}
Some(Commands::Rollback) => {
commands::rollback_transaction(&mut state)?;
}
Some(Commands::Graph) => {
commands::show_graph(&state)?;
}
Some(Commands::Shell) | None => {
// Use enhanced REPL with tab completion and syntax highlighting
repl_impl::run(&mut state)?;
}
Some(Commands::Proofs) => {
commands::show_proofs()?;
}
}
// Run EXIT trap if registered
if let Some(exit_cmd) = state
.traps
.get(vsh::posix_builtins::TrapSignal::Exit)
.map(|s| s.to_string())
{
if let Ok(cmd) = vsh::parser::parse_command(&exit_cmd) {
let _ = cmd.execute(&mut state);
}
}
Ok(())
}
/// Execute script content (string of commands, one per line or semicolon-separated)
///
/// We split the *entire* content on top-level statement separators (both `;`
/// and `\n`, respecting quotes and control-structure depth), so multi-line
/// `if/fi`, `for/done`, `while/done`, and `case/esac` work exactly as they
/// do in a POSIX shell.
fn execute_script_content(content: &str, state: &mut state::ShellState) -> Result<()> {
// Strip full-line comments before splitting. (A `#` inside a statement
// may be part of a quoted string or a parameter expansion, so we only
// trim whole-line comments here.)
let stripped: String = content
.lines()
.map(|line| {
let trimmed = line.trim_start();
if trimmed.starts_with('#') {
""
} else {
line
}
})
.collect::<Vec<_>>()
.join("\n");
for segment in vsh::parser::split_on_statement_separators(&stripped) {
let segment = segment.trim();
if segment.is_empty() || segment.starts_with('#') {
continue;
}
match vsh::parser::parse_command(segment) {
Ok(cmd) => {
let result = cmd.execute(state)?;
match result {
ExecutionResult::Exit => return Ok(()),
ExecutionResult::ExternalCommand { exit_code }
| ExecutionResult::Return { exit_code } => {
state.last_exit_code = exit_code;
}
ExecutionResult::Success => {
state.last_exit_code = 0;
}
}
}
Err(e) => {
eprintln!("vsh: {}", e);
state.last_exit_code = 1;
}
}
}
// Run EXIT trap if registered
if let Some(exit_cmd) = state
.traps
.get(vsh::posix_builtins::TrapSignal::Exit)
.map(|s| s.to_string())
{
if let Ok(cmd) = vsh::parser::parse_command(&exit_cmd) {
let _ = cmd.execute(state);
}
}
std::process::exit(state.last_exit_code);
}
fn print_banner() {
println!(
"{}",
r#"
╔═══════════════════════════════════════════════════════════╗
║ ██╗ ██╗ █████╗ ██╗ ███████╗███╗ ██╗ ██████╗███████╗ ║
║ ██║ ██║██╔══██╗██║ ██╔════╝████╗ ██║██╔════╝██╔════╝ ║
║ ██║ ██║███████║██║ █████╗ ██╔██╗ ██║██║ █████╗ ║
║ ╚██╗ ██╔╝██╔══██║██║ ██╔══╝ ██║╚██╗██║██║ ██╔══╝ ║
║ ╚████╔╝ ██║ ██║███████╗███████╗██║ ╚████║╚██████╗███████╗ ║
║ ╚═══╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═══╝ ╚═════╝╚══════╝ ║
║ ║
║ The Thermodynamic Shell - Every operation is reversible ║
║ Backed by 200+ formal theorems across 6 verification systems ║
╚═══════════════════════════════════════════════════════════╝
"#
.bright_blue()
);
println!(
"{}",
"Type 'help' for commands, 'undo' to reverse, 'history --proofs' for proof refs\n"
.bright_black()
);
}