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
use {
anstream::println,
anyhow::Result,
clap::Parser,
clap_cargo::style::CLAP_STYLING,
ignore_check::Ignore,
notify::{
Event, EventKind, RecursiveMode, Watcher,
event::{AccessKind, AccessMode},
},
sprint::{ColorOverride, Command, Shell},
std::{
collections::BTreeMap,
path::{Path, PathBuf},
thread::sleep,
time::Duration,
},
};
#[derive(Parser)]
#[command(about, version, max_term_width = 80, styles = CLAP_STYLING)]
struct Cli {
/// File(s) or command(s)
#[arg(value_name = "STRING")]
arguments: Vec<String>,
/// Shell
#[arg(short, long, value_name = "STRING", default_value = "sh -c")]
shell: String,
/// Fence
#[arg(short, long, value_name = "STRING", default_value = "```")]
fence: String,
/// Info
#[arg(short, long, value_name = "STRING", default_value = "text")]
info: String,
/// Prompt
#[arg(short, long, value_name = "STRING", default_value = "$ ")]
prompt: String,
/// Watch files/directories and rerun command on change; see also `-d` option
#[arg(short, long, value_name = "PATH")]
watch: Vec<PathBuf>,
/// Debounce; used only with `-w`
#[arg(short, long, value_name = "SECONDS", default_value = "5.0")]
debounce: f32,
/// Force enable/disable terminal colors
#[arg(short = 'C', long, default_value = "auto")]
color: ColorOverride,
}
#[allow(clippy::too_many_lines)]
fn main() -> Result<()> {
let cli = Cli::parse();
cli.color.init();
let shell = Shell {
shell: Some(cli.shell.clone()),
fence: cli.fence.clone(),
info: cli.info.clone(),
prompt: cli.prompt.clone(),
..Default::default()
};
let no_arguments = cli.arguments.is_empty();
let no_watch = cli.watch.is_empty();
if no_arguments && no_watch {
// Run interactively
let stdin = std::io::stdin();
shell.interactive_prompt(false);
loop {
let mut command = String::new();
if stdin.read_line(&mut command).is_ok() {
shell.interactive_prompt_reset();
if command.is_empty() {
// Control + D
break;
}
let result = shell.core(&Command::new(command.trim()));
if let Some(code) = &result.code {
if !result.codes.contains(code) {
std::process::exit(*code);
}
} else {
std::process::exit(1);
}
shell.interactive_prompt(true);
} else {
std::process::exit(1);
}
}
} else if no_watch {
// Run given commands / files
let results = shell.run(
&cli.arguments
.iter()
.map(|x| Command::new(x))
.collect::<Vec<_>>(),
);
// Exit with the code of the last command
std::process::exit(results.last().unwrap().code.unwrap_or(1));
} else if no_arguments {
// Watch, but no commands...
// Get watched directories & files
let (dirs, mut hashes) = watched(&cli.watch);
let ignored = Ignore::default();
let pwd = std::env::current_dir().unwrap();
let debounce = std::time::Duration::from_secs_f32(cli.debounce);
let mut ts = std::time::Instant::now();
let mut watcher =
notify::recommended_watcher(move |res: notify::Result<Event>| match res {
Ok(event) => {
let now = std::time::Instant::now();
match event.kind {
EventKind::Create(_) | EventKind::Remove(_) => {
// Created or deleted a file/directory
'outer: for path in event
.paths
.iter()
.map(|x| x.strip_prefix(&pwd).unwrap().to_path_buf())
.filter(|x| not_ignored(x, &ignored, &dirs, &hashes))
{
if now - ts > debounce {
println!(
"* {}: `{}`",
match event.kind {
EventKind::Create(_) => "Created",
EventKind::Remove(_) => "Removed",
_ => unreachable!(),
},
path.display(),
);
ts = now;
break 'outer;
}
}
}
EventKind::Access(AccessKind::Close(AccessMode::Write)) => {
// Wrote a file
let mut not_restarted = true;
let paths = event
.paths
.iter()
.map(|x| x.strip_prefix(&pwd).unwrap().to_path_buf())
.filter(|x| not_ignored(x, &ignored, &dirs, &hashes))
.collect::<Vec<_>>();
for path in paths {
if let Some(h1) = hashes.get(&path) {
let h2 = hash(&path);
if h2 != *h1 {
// File changed...
// Update the hash
hashes.insert(path.clone(), h2);
if not_restarted && now - ts > debounce {
println!("* Modified: `{}`", path.display());
ts = now;
not_restarted = false;
}
}
}
}
}
_ => {}
}
}
Err(_e) => {
std::process::exit(1);
}
})?;
for path in &cli.watch {
watcher.watch(path, RecursiveMode::Recursive)?;
}
loop {
sleep(Duration::from_secs_f32(0.25));
}
} else {
// Watch
// Error if more than one command
if cli.arguments.len() > 1 {
eprintln!("ERROR: Watch mode only works with a single command!");
std::process::exit(1);
}
// Run the command in a child process
let command = Command::new(&cli.arguments[0]);
let (mut process, mut ts) = run(&shell, &command);
// Get watched directories & files
let (dirs, mut hashes) = watched(&cli.watch);
let ignored = Ignore::default();
let pwd = std::env::current_dir().unwrap();
let debounce = std::time::Duration::from_secs_f32(cli.debounce);
let mut watcher =
notify::recommended_watcher(move |res: notify::Result<Event>| match res {
Ok(event) => {
let now = std::time::Instant::now();
match event.kind {
EventKind::Create(_) | EventKind::Remove(_) => {
// Created or deleted a file/directory
for path in event
.paths
.iter()
.map(|x| x.strip_prefix(&pwd).unwrap().to_path_buf())
.filter(|x| not_ignored(x, &ignored, &dirs, &hashes))
{
// In a watched directory...
if now - ts > debounce {
// Kill the command (if still running)
if let Ok(None) = process.try_wait() {
process.kill().expect("kill process");
}
shell.print_fence(2);
println!(
"* {}: `{}`\n",
match event.kind {
EventKind::Create(_) => "Created",
EventKind::Remove(_) => "Removed",
_ => unreachable!(),
},
path.display(),
);
// Run the command again
(process, ts) = run(&shell, &command);
break;
}
}
}
EventKind::Access(AccessKind::Close(AccessMode::Write)) => {
// Wrote a file
let mut not_restarted = true;
let paths = event
.paths
.iter()
.map(|x| x.strip_prefix(&pwd).unwrap().to_path_buf())
.filter(|x| not_ignored(x, &ignored, &dirs, &hashes))
.collect::<Vec<_>>();
for path in paths {
if let Some(h1) = hashes.get(&path) {
let h2 = hash(&path);
if h2 != *h1 {
// File changed...
// Update the hash
hashes.insert(path.clone(), h2);
if not_restarted && now - ts > debounce {
// Kill the command (if still running)
if let Ok(None) = process.try_wait() {
process.kill().expect("kill process");
}
shell.print_fence(2);
println!("* Modified: `{}`\n", path.display());
// Run the command again
(process, ts) = run(&shell, &command);
not_restarted = false;
}
}
}
}
}
_ => {}
}
}
Err(_e) => {
std::process::exit(1);
}
})?;
for path in &cli.watch {
watcher.watch(path, RecursiveMode::Recursive)?;
}
loop {
sleep(Duration::from_secs_f32(0.25));
}
}
Ok(())
}
fn run(shell: &Shell, command: &Command) -> (std::process::Child, std::time::Instant) {
shell.interactive_prompt(false);
println!("{}", command.command);
shell.interactive_prompt_reset();
(shell.run1_async(command), std::time::Instant::now())
}
fn watched(args: &[PathBuf]) -> (Vec<PathBuf>, BTreeMap<PathBuf, String>) {
// Get directories
let dirs = args
.iter()
.filter(|x| x.is_dir())
.cloned()
.collect::<Vec<_>>();
// Get hashes for all watched files
let hashes = args
.iter()
.filter(|x| x.is_file())
.cloned()
.chain(dirs.iter().flat_map(|x| {
ignore::Walk::new(x)
.flatten()
.filter(|x| x.path().is_file())
.map(|x| {
let path = x.into_path();
match path.strip_prefix("./") {
Ok(p) => p.to_path_buf(),
Err(_e) => path,
}
})
}))
.map(|x| {
let h = hash(&x);
(x, h)
})
.collect::<BTreeMap<_, _>>();
(dirs, hashes)
}
fn not_ignored(
path: &Path,
ignored: &Ignore,
dirs: &[PathBuf],
hashes: &BTreeMap<PathBuf, String>,
) -> bool {
let path = path.to_owned();
!ignored.check(&path) && !dirs.contains(&path) && !hashes.contains_key(&path)
}
fn hash(path: &Path) -> String {
fhc::file_blake3(path).unwrap().remove(0).1
}