-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepl.rs
More file actions
340 lines (307 loc) · 9.72 KB
/
Copy pathrepl.rs
File metadata and controls
340 lines (307 loc) · 9.72 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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! Interactive REPL
//!
//! Provides an interactive shell experience with:
//! - Command history
//! - Tab completion
//! - Colored prompts showing transaction state
use anyhow::Result;
use colored::Colorize;
use std::io::{self, BufRead, Write};
use crate::executable::{self, ExecutableCommand, ExecutionResult};
use crate::parser;
use crate::signals;
use crate::state::ShellState;
/// Run the interactive REPL (Read-Eval-Print Loop).
///
/// Starts an interactive shell session with:
/// - Command history
/// - Colored prompts showing transaction state
/// - Ctrl+C handling for interrupting commands
/// - EOF (Ctrl+D) to exit
///
/// # Arguments
/// * `state` - Mutable shell state for command execution
///
/// # Errors
/// Returns error if:
/// - SIGINT handler installation fails
/// - Terminal I/O fails
/// - Command execution fails fatally
///
/// # Examples
/// ```no_run
/// use vsh::repl;
/// use vsh::state::ShellState;
///
/// let mut state = ShellState::new("/tmp/workspace")?;
/// repl::run(&mut state)?; // Starts interactive shell
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn run(state: &mut ShellState) -> Result<()> {
// Install SIGINT handler for graceful Ctrl+C handling
ctrlc::set_handler(move || {
signals::request_interrupt();
})
.expect("Error setting Ctrl-C handler");
let stdin = io::stdin();
let mut stdout = io::stdout();
loop {
// Build prompt
let prompt = build_prompt(state);
print!("{}", prompt);
stdout.flush()?;
// Read line
let mut input = String::new();
if stdin.lock().read_line(&mut input)? == 0 {
// EOF
break;
}
let input = input.trim();
if input.is_empty() || input.starts_with('#') {
// Skip empty lines and comments
continue;
}
// Split on semicolons and execute each segment
let segments = parser::split_on_semicolons(input);
let mut should_break = false;
for segment in segments {
let segment = segment.trim();
if segment.is_empty() || segment.starts_with('#') {
continue;
}
match execute_line(state, segment) {
Ok(should_exit) => {
if should_exit {
should_break = true;
break;
}
}
Err(e) => {
eprintln!("{} {}", "Error:".bright_red(), e);
// POSIX: continue executing remaining commands after error
}
}
}
// Fire any pending signal traps (e.g. trap 'handler' INT).
if executable::run_pending_traps(state) {
break;
}
if should_break {
break;
}
}
println!("{}", "\nGoodbye!".bright_blue());
Ok(())
}
fn build_prompt(state: &ShellState) -> String {
let txn_indicator = if let Some(ref txn) = state.active_transaction {
format!("{}/", format!("txn:{}", txn.name).bright_cyan())
} else {
String::new()
};
let undo_count = state.history.iter().filter(|o| !o.undone).count();
let undo_indicator = if undo_count > 0 {
format!(" {}", format!("[{}↩]", undo_count).bright_black())
} else {
String::new()
};
format!(
"{}{}{}> ",
"vsh".bright_blue().bold(),
txn_indicator,
undo_indicator
)
}
fn execute_line(state: &mut ShellState, input: &str) -> Result<bool> {
// Handle special commands first (not parsed)
let trimmed = input.trim();
match trimmed {
"help" | "?" => {
print_help();
return Ok(false);
}
"clear" => {
print!("\x1B[2J\x1B[1;1H");
return Ok(false);
}
"status" => {
print_status(state);
return Ok(false);
}
_ => {}
}
// Handle aliases before parsing
let input_normalized = match trimmed {
s if s.starts_with("u ") || s == "u" => trimmed.replacen("u", "undo", 1),
s if s.starts_with("r ") || s == "r" => trimmed.replacen("r", "redo", 1),
s if s.starts_with("h ") || s == "h" => trimmed.replacen("h", "history", 1),
s if s.starts_with("g ") || s == "g" => trimmed.replacen("g", "graph", 1),
"q" => "quit".to_string(),
_ => trimmed.to_string(),
};
// POSIX §2.3.1: Expand user-defined aliases on the input before parsing.
let input_aliased = state.aliases.expand(&input_normalized);
// Parse command using the parser
let cmd = parser::parse_command(&input_aliased)?;
// Execute command using trait (Seam 1↔2)
let result = cmd.execute(state)?;
// Handle execution result
match result {
ExecutionResult::Exit => Ok(true),
ExecutionResult::ExternalCommand { exit_code } | ExecutionResult::Return { exit_code } => {
// Return leaking past a function boundary is defensive: the
// `Command::Return` handler already errors if invoked outside
// a function, so we treat it as a plain exit-code result here.
state.last_exit_code = exit_code;
Ok(false)
}
ExecutionResult::Success => Ok(false),
}
}
fn print_help() {
println!("{}", "═══ Valence Shell Commands ═══".bright_blue().bold());
println!();
println!("{}", "Filesystem Operations:".bright_yellow());
println!(
" {} Create a directory",
"mkdir <path>".bright_green()
);
println!(
" {} Remove an empty directory",
"rmdir <path>".bright_green()
);
println!(
" {} Create an empty file",
"touch <path>".bright_green()
);
println!(" {} Remove a file", "rm <path>".bright_green());
println!(
" {} List directory contents",
"ls [path]".bright_green()
);
println!(" {} Change directory", "cd [path]".bright_green());
println!(
" {} Return to previous directory",
"cd -".bright_green()
);
println!(
" {} Show current directory",
"pwd".bright_green()
);
println!();
println!("{}", "Reversibility:".bright_yellow());
println!(
" {} Undo last operation(s)",
"undo [N]".bright_cyan()
);
println!(
" {} Redo last undone operation(s)",
"redo [N]".bright_cyan()
);
println!(" {} Show operation history", "history [N]".bright_cyan());
println!(
" {} Add --proofs to see theorems",
"history -p".bright_cyan()
);
println!(" {} Show operation DAG", "graph".bright_cyan());
println!();
println!("{}", "Transactions:".bright_yellow());
println!(
" {} Start a transaction group",
"begin <name>".bright_magenta()
);
println!(
" {} Commit current transaction",
"commit".bright_magenta()
);
println!(
" {} Rollback current transaction",
"rollback".bright_magenta()
);
println!();
println!("{}", "Job Control:".bright_yellow());
println!(" {} Run command in background", "cmd &".bright_green());
println!(" {} List all jobs", "jobs".bright_green());
println!(" {} List jobs with PIDs", "jobs -l".bright_green());
println!(
" {} Bring job to foreground",
"fg [%N]".bright_green()
);
println!(
" {} Continue job in background",
"bg [%N]".bright_green()
);
println!(
" {} Send signal to job",
"kill [-%N] %N".bright_green()
);
println!();
println!("{}", "Information:".bright_yellow());
println!(
" {} Show verification info",
"proofs".bright_white()
);
println!(" {} Show shell status", "status".bright_white());
println!(" {} Show this help", "help".bright_white());
println!();
println!("{}", "Other:".bright_yellow());
println!(" {} Clear screen", "clear".bright_black());
println!(" {} Exit shell", "exit".bright_black());
println!();
println!("{}", "External Commands:".bright_yellow());
println!(" Any other command will be executed as an external program");
println!(
" Example: {} or {}",
"ls -la".bright_green(),
"cat file.txt".bright_green()
);
println!();
println!(
"{}",
"All filesystem operations are reversible with 'undo'".bright_black()
);
println!(
"{}",
"Backed by formal proofs - use 'proofs' to see details".bright_black()
);
}
fn print_status(state: &ShellState) {
println!("{}", "═══ Shell Status ═══".bright_blue().bold());
println!();
println!(
" {}: {}",
"Sandbox root".bright_black(),
state.root.display()
);
println!(
" {}: {}",
"Total operations".bright_black(),
state.history.len()
);
println!(
" {}: {}",
"Undoable ops".bright_black(),
state.history.iter().filter(|o| !o.undone).count()
);
println!(
" {}: {}",
"Redo stack".bright_black(),
state.get_redo_stack().len()
);
if let Some(ref txn) = state.active_transaction {
println!();
println!(
" {}: {} ({})",
"Active transaction".bright_cyan(),
txn.name,
format!("{} ops", txn.operations.len()).bright_black()
);
}
println!(
" {}: {}",
"Completed transactions".bright_black(),
state.transactions.len()
);
}