-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathexec.rs
More file actions
227 lines (206 loc) · 6.93 KB
/
exec.rs
File metadata and controls
227 lines (206 loc) · 6.93 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
// Copyright 2017 Google Inc.
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
use std::cell::RefCell;
use std::error::Error;
use std::ffi::OsString;
use std::io::{stderr, Write};
use std::path::Path;
use std::process::Command;
use super::{Matcher, MatcherIO, WalkEntry};
enum Arg {
FileArg(Vec<OsString>),
LiteralArg(OsString),
}
pub struct SingleExecMatcher {
executable: String,
args: Vec<Arg>,
exec_in_parent_dir: bool,
}
impl SingleExecMatcher {
pub fn new(
executable: &str,
args: &[&str],
exec_in_parent_dir: bool,
) -> Result<Self, Box<dyn Error>> {
let transformed_args = args
.iter()
.map(|&a| {
let parts = a.split("{}").collect::<Vec<_>>();
if parts.len() == 1 {
// No {} present
Arg::LiteralArg(OsString::from(a))
} else {
Arg::FileArg(parts.iter().map(OsString::from).collect())
}
})
.collect();
Ok(Self {
executable: executable.to_string(),
args: transformed_args,
exec_in_parent_dir,
})
}
}
impl Matcher for SingleExecMatcher {
fn matches(&self, file_info: &WalkEntry, _: &mut MatcherIO) -> bool {
let mut command = if &self.executable == "{}" {
Command::new(file_info.path())
} else {
Command::new(&self.executable)
};
let path_to_file = if self.exec_in_parent_dir {
if let Some(f) = file_info.path().file_name() {
Path::new(".").join(f)
} else {
Path::new(".").join(file_info.path())
}
} else {
file_info.path().to_path_buf()
};
for arg in &self.args {
match *arg {
Arg::LiteralArg(ref a) => command.arg(a.as_os_str()),
Arg::FileArg(ref parts) => command.arg(parts.join(path_to_file.as_os_str())),
};
}
if self.exec_in_parent_dir {
match file_info.path().parent() {
None => {
// Root paths like "/" have no parent. Run them from the root to match GNU find.
command.current_dir(file_info.path());
}
Some(parent) if parent == Path::new("") => {
// Paths like "foo" have a parent of "". Avoid chdir("").
}
Some(parent) => {
command.current_dir(parent);
}
}
}
match command.status() {
Ok(status) => status.success(),
Err(e) => {
writeln!(&mut stderr(), "Failed to run {}: {}", self.executable, e).unwrap();
false
}
}
}
fn has_side_effects(&self) -> bool {
true
}
}
pub struct MultiExecMatcher {
executable: String,
args: Vec<OsString>,
exec_in_parent_dir: bool,
/// Command to build while matching.
command: RefCell<Option<argmax::Command>>,
}
impl MultiExecMatcher {
pub fn new(
executable: &str,
args: &[&str],
exec_in_parent_dir: bool,
) -> Result<Self, Box<dyn Error>> {
let transformed_args = args.iter().map(OsString::from).collect();
Ok(Self {
executable: executable.to_string(),
args: transformed_args,
exec_in_parent_dir,
command: RefCell::new(None),
})
}
fn new_command(&self) -> argmax::Command {
let mut command = argmax::Command::new(&self.executable);
command.try_args(&self.args).unwrap();
command
}
fn run_command(&self, command: &mut argmax::Command, matcher_io: &mut MatcherIO) {
match command.status() {
Ok(status) => {
if !status.success() {
matcher_io.set_exit_code(1);
}
}
Err(e) => {
writeln!(&mut stderr(), "Failed to run {}: {}", self.executable, e).unwrap();
matcher_io.set_exit_code(1);
}
}
}
}
impl Matcher for MultiExecMatcher {
fn matches(&self, file_info: &WalkEntry, matcher_io: &mut MatcherIO) -> bool {
let path_to_file = if self.exec_in_parent_dir {
if let Some(f) = file_info.path().file_name() {
Path::new(".").join(f)
} else {
Path::new(".").join(file_info.path())
}
} else {
file_info.path().to_path_buf()
};
let mut command = self.command.borrow_mut();
let command = command.get_or_insert_with(|| self.new_command());
// Build command, or dispatch it before when it is long enough.
if command.try_arg(&path_to_file).is_err() {
if self.exec_in_parent_dir {
match file_info.path().parent() {
None => {
// Root paths like "/" have no parent. Run them from the root to match GNU find.
command.current_dir(file_info.path());
}
Some(parent) if parent == Path::new("") => {
// Paths like "foo" have a parent of "". Avoid chdir("").
}
Some(parent) => {
command.current_dir(parent);
}
}
}
self.run_command(command, matcher_io);
// Reset command status.
*command = self.new_command();
if let Err(e) = command.try_arg(&path_to_file) {
writeln!(
&mut stderr(),
"Cannot fit a single argument {}: {}",
&path_to_file.to_string_lossy(),
e
)
.unwrap();
matcher_io.set_exit_code(1);
}
}
true
}
fn finished_dir(&self, dir: &Path, matcher_io: &mut MatcherIO) {
// Dispatch command for -execdir.
if self.exec_in_parent_dir {
let mut command = self.command.borrow_mut();
if let Some(mut command) = command.take() {
command.current_dir(Path::new(".").join(dir));
self.run_command(&mut command, matcher_io);
}
}
}
fn finished(&self, matcher_io: &mut MatcherIO) {
// Dispatch command for -exec.
if !self.exec_in_parent_dir {
let mut command = self.command.borrow_mut();
if let Some(mut command) = command.take() {
self.run_command(&mut command, matcher_io);
}
}
}
fn has_side_effects(&self) -> bool {
true
}
}
#[cfg(test)]
/// No tests here, because we need to call out to an external executable. See
/// `tests/exec_unit_tests.rs` instead.
mod tests {}