-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathexec.rs
More file actions
441 lines (407 loc) · 12 KB
/
exec.rs
File metadata and controls
441 lines (407 loc) · 12 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
use crate::repos::Repo;
use std::env;
use std::io::{BufRead, BufReader, Error, Read};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::thread;
pub fn exec(exec_args: Vec<String>, repos: Vec<Repo>, oneline: bool) {
let mut error_count = 0;
let mut skipped_count = 0;
for repo in &repos {
if !exists(&repo.path) {
if oneline {
println!("{}\tRepo folder missing, skipped.", &repo.path);
} else {
println!();
println!("🏢 {}> Repo folder missing, skipped.", &repo.path);
}
skipped_count += 1;
continue;
}
if oneline {
let (output, success) =
repo_exec_oneline(&repo.path, &exec_args).expect("Failed to execute command.");
match output {
Some(output_text) => println!("{}\t{}", &repo.path, output_text),
None => println!("{}\t", &repo.path),
}
if !success {
error_count += 1;
}
} else {
let exit_status =
repo_exec(&repo.path, &exec_args).expect("Failed to execute command.");
if !exit_status.success() {
error_count += 1
}
println!();
}
}
if error_count > 0 || skipped_count > 0 {
if error_count > 0 {
eprintln!("{error_count} commands exited with non-zero status code");
}
if skipped_count > 0 {
eprintln!("{skipped_count} repos skipped");
}
std::process::exit(1);
}
}
fn exists(repo_path: &String) -> bool {
let mut path = env::current_dir().expect("failed to get current working directory");
path.push(repo_path);
path.exists() && path.is_dir()
}
fn needs_quoting(arg: &str) -> bool {
arg.chars().any(|c| {
c.is_whitespace()
|| matches!(
c,
'|' | '&'
| ';' | '<' | '>'
| '(' | ')' | '$'
| '`' | '\\' | '"'
| '\'' | '*' | '?'
| '[' | ']' | '{'
| '}' | '!' | '#'
)
})
}
/// Formats command arguments for display with intelligent quoting.
///
/// This function reconstructs a shell command string from parsed arguments,
/// adding quotes where needed to make the output readable and copy-pasteable.
///
/// # Why We Need Heuristics
///
/// By the time we receive the arguments here, the shell has already parsed
/// the user's input and consumed the original quotes. For example:
/// - User types: `gitopolis exec -- git log --since="One Week"`
/// - Shell parses this into separate args: `["git", "log", "--since=One Week"]`
/// - We receive: The value "One Week" with no information about original quoting
///
/// Since we've lost the original quoting style, we use heuristics to reconstruct
/// a readable command that would execute correctly if copy-pasted.
///
/// # Strategy
///
/// - Arguments without special chars: display as-is
/// - Arguments with spaces/special chars: wrap in single quotes
/// - Arguments matching `--flag=value` pattern: quote only the value portion
/// for better readability (e.g., `--since='One Week'` vs `'--since=One Week'`)
/// - Values containing single quotes: use double quotes with escaping
fn format_args_for_display(args: &[String]) -> String {
args.iter()
.map(|arg| {
if needs_quoting(arg) {
// Check if this is a --flag=value or -flag=value pattern
if arg.starts_with('-') && arg.contains('=') {
format_key_value_for_display(arg)
} else {
// Not a flag=value pattern, quote the whole thing
quote_arg(arg)
}
} else {
arg.clone()
}
})
.collect::<Vec<_>>()
.join(" ")
}
/// Formats a --key=value argument, quoting only the value portion if needed.
///
/// For example: `--since=One Week` becomes `--since='One Week'`
fn format_key_value_for_display(arg: &str) -> String {
let eq_pos = arg.find('=').expect("arg must contain '='");
let (key, value) = arg.split_at(eq_pos);
let value = &value[1..]; // Skip the '=' character
// Quote only the value portion if it needs quoting
if needs_quoting(value) {
if value.contains('\'') {
// For values containing single quotes, use double quotes and escape
format!(
"{}=\"{}\"",
key,
value.replace('\\', "\\\\").replace('"', "\\\"")
)
} else {
format!("{}='{}'", key, value)
}
} else {
// Value doesn't need quoting, return as-is
arg.to_string()
}
}
fn quote_arg(arg: &str) -> String {
// Use single quotes for simplicity, escape any single quotes in the string
if arg.contains('\'') {
// For strings containing single quotes, use double quotes and escape
format!("\"{}\"", arg.replace('\\', "\\\\").replace('"', "\\\""))
} else {
format!("'{}'", arg)
}
}
fn repo_exec(path: &str, exec_args: &[String]) -> Result<ExitStatus, Error> {
println!();
println!("🏢 {}> {}", path, format_args_for_display(exec_args));
// If single argument, pass directly to shell for interpretation (supports pipes, etc.)
// If multiple arguments, pass via positional parameters to avoid quoting issues
#[cfg(unix)]
let mut child_process: Child = if exec_args.len() == 1 {
Command::new("sh")
.arg("-c")
.arg(&exec_args[0]) // Single arg passed directly for shell interpretation
.current_dir(path)
.stdin(Stdio::null()) // Prevent interactive prompts/pagers
.stdout(Stdio::piped()) // Prevent TTY detection for pagers
.stderr(Stdio::piped())
.spawn()?
} else {
Command::new("sh")
.arg("-c")
.arg(r#""$@""#) // Execute all positional parameters
.arg("--") // $0 placeholder (ignored)
.args(exec_args) // These become $1, $2, $3, etc.
.current_dir(path)
.stdin(Stdio::null()) // Prevent interactive prompts/pagers
.stdout(Stdio::piped()) // Prevent TTY detection for pagers
.stderr(Stdio::piped())
.spawn()?
};
#[cfg(windows)]
let mut child_process: Child = if exec_args.len() == 1 {
Command::new("cmd")
.arg("/C")
.arg(&exec_args[0]) // Single arg passed directly for shell interpretation
.current_dir(path)
.stdin(Stdio::null()) // Prevent interactive prompts/pagers
.stdout(Stdio::piped()) // Prevent TTY detection for pagers
.stderr(Stdio::piped())
.spawn()?
} else {
// Windows cmd doesn't have an equivalent to sh -c "$@"
// We need to join args with proper quoting
let command_string = exec_args
.iter()
.map(|arg| {
// Quote if contains spaces or special chars
if arg.contains(' ') || arg.contains('"') || arg.contains('&') || arg.contains('|')
{
format!("\"{}\"", arg.replace('"', "\"\""))
} else {
arg.clone()
}
})
.collect::<Vec<_>>()
.join(" ");
Command::new("cmd")
.arg("/C")
.arg(command_string)
.current_dir(path)
.stdin(Stdio::null()) // Prevent interactive prompts/pagers
.stdout(Stdio::piped()) // Prevent TTY detection for pagers
.stderr(Stdio::piped())
.spawn()?
};
// Stream stdout and stderr in real-time using threads
let stdout = child_process
.stdout
.take()
.expect("Failed to capture stdout");
let stderr = child_process
.stderr
.take()
.expect("Failed to capture stderr");
let stdout_thread = thread::spawn(move || {
let reader = BufReader::new(stdout);
for line in reader.lines().map_while(Result::ok) {
println!("{}", line);
}
});
let stderr_thread = thread::spawn(move || {
let reader = BufReader::new(stderr);
for line in reader.lines().map_while(Result::ok) {
eprintln!("{}", line);
}
});
let exit_code = child_process.wait()?;
// Wait for output threads to finish
let _ = stdout_thread.join();
let _ = stderr_thread.join();
if !exit_code.success() {
eprintln!(
"Command exited with code {}",
exit_code.code().expect("exit code missing")
);
}
Ok(exit_code)
}
fn repo_exec_oneline(path: &str, exec_args: &[String]) -> Result<(Option<String>, bool), Error> {
// If single argument, pass directly to shell for interpretation (supports pipes, etc.)
// If multiple arguments, pass via positional parameters to avoid quoting issues
#[cfg(unix)]
let mut child_process: Child = if exec_args.len() == 1 {
Command::new("sh")
.arg("-c")
.arg(&exec_args[0]) // Single arg passed directly for shell interpretation
.current_dir(path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?
} else {
Command::new("sh")
.arg("-c")
.arg(r#""$@""#) // Execute all positional parameters
.arg("--") // $0 placeholder (ignored)
.args(exec_args) // These become $1, $2, $3, etc.
.current_dir(path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?
};
#[cfg(windows)]
let mut child_process: Child = if exec_args.len() == 1 {
Command::new("cmd")
.arg("/C")
.arg(&exec_args[0]) // Single arg passed directly for shell interpretation
.current_dir(path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?
} else {
// Windows cmd doesn't have an equivalent to sh -c "$@"
// We need to join args with proper quoting
let command_string = exec_args
.iter()
.map(|arg| {
// Quote if contains spaces or special chars
if arg.contains(' ') || arg.contains('"') || arg.contains('&') || arg.contains('|')
{
format!("\"{}\"", arg.replace('"', "\"\""))
} else {
arg.clone()
}
})
.collect::<Vec<_>>()
.join(" ");
Command::new("cmd")
.arg("/C")
.arg(command_string)
.current_dir(path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?
};
let mut stdout = String::new();
if let Some(mut stdout_pipe) = child_process.stdout.take() {
stdout_pipe.read_to_string(&mut stdout)?;
}
let mut stderr = String::new();
if let Some(mut stderr_pipe) = child_process.stderr.take() {
stderr_pipe.read_to_string(&mut stderr)?;
}
let exit_code = child_process.wait()?;
let success = exit_code.success();
// Flatten multi-line output to single line by replacing newlines with spaces
let stdout_clean = stdout.trim().replace('\n', " ");
let stderr_clean = stderr.trim().replace('\n', " ");
// Combine stdout and stderr, with stderr included when command fails
let output = if !success && !stderr_clean.is_empty() {
if stdout_clean.is_empty() {
stderr_clean
} else {
format!("{} {}", stdout_clean, stderr_clean)
}
} else if !stdout_clean.is_empty() {
stdout_clean
} else {
String::new()
};
if output.is_empty() {
Ok((None, success))
} else {
Ok((Some(output), success))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_args_no_quoting_needed() {
let args = vec!["git".to_string(), "status".to_string()];
assert_eq!(format_args_for_display(&args), "git status");
}
#[test]
fn test_format_args_simple_quoting() {
let args = vec!["echo".to_string(), "hello world".to_string()];
assert_eq!(format_args_for_display(&args), "echo 'hello world'");
}
#[test]
fn test_format_args_flag_with_value() {
let args = vec![
"git".to_string(),
"log".to_string(),
"-n".to_string(),
"5".to_string(),
"--since=One Week".to_string(),
];
assert_eq!(
format_args_for_display(&args),
"git log -n 5 --since='One Week'"
);
}
#[test]
fn test_format_args_flag_with_value_containing_single_quote() {
let args = vec![
"git".to_string(),
"commit".to_string(),
"-m=Don't panic".to_string(),
];
assert_eq!(
format_args_for_display(&args),
"git commit -m=\"Don't panic\""
);
}
#[test]
fn test_format_args_non_flag_key_value() {
// If it doesn't start with -, quote the whole thing
let args = vec!["foo=bar baz".to_string()];
assert_eq!(format_args_for_display(&args), "'foo=bar baz'");
}
#[test]
fn test_format_args_flag_with_no_spaces() {
let args = vec!["--since=yesterday".to_string()];
assert_eq!(format_args_for_display(&args), "--since=yesterday");
}
#[test]
fn test_format_args_mixed() {
let args = vec![
"git".to_string(),
"log".to_string(),
"--author=John Doe".to_string(),
"--format=%H".to_string(),
"-n".to_string(),
"10".to_string(),
];
assert_eq!(
format_args_for_display(&args),
"git log --author='John Doe' --format=%H -n 10"
);
}
#[test]
fn test_format_args_with_special_chars() {
let args = vec!["echo".to_string(), "hello|world".to_string()];
assert_eq!(format_args_for_display(&args), "echo 'hello|world'");
}
#[test]
fn test_format_args_double_dash_flag() {
let args = vec!["grep".to_string(), "--exclude=*.tmp files".to_string()];
assert_eq!(
format_args_for_display(&args),
"grep --exclude='*.tmp files'"
);
}
}