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
|
mod error;
mod main_result;
use std::{
cmp::Reverse,
collections::{hash_map::DefaultHasher, HashSet},
env,
ffi::OsString,
fs,
hash::{Hash, Hasher},
io::{self, BufRead, BufReader, BufWriter, Write},
iter,
path::{Component, Path, PathBuf},
process::{Command, Stdio},
};
use tempfile::tempdir;
use {error::Error, main_result::MainResult};
#[derive(Default)]
struct Flags {
pub dryrun: bool,
pub encode: bool,
pub individual: bool,
pub nul: bool,
pub verbose: bool,
}
fn main() -> MainResult {
work().into()
}
fn work() -> Result<(), Error> {
let (flags, rest) = parse_args()?;
let (cmd, args) = rest.split_first().ok_or(Error::BadArgs(None))?;
// Collect sources from standard input
let srcs = io::stdin()
.lines()
.map(|l| {
l.map_err(Error::from).and_then(|l| {
if l.is_empty() {
Err(Error::BadArgs(None))
} else {
Ok(l)
}
})
})
.collect::<Result<Vec<String>, Error>>()?;
// Spawn the child process
let mut child = Command::new(cmd)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(|e| Error::SpawnFailed(cmd.to_owned(), e))?;
// Pass the source files to the child process.
// TODO: Don’t use expect; create a custom error
{
let ci = child
.stdin
.take()
.expect("Could not open the child process’ stdin");
let mut ci = BufWriter::new(ci);
if flags.encode {
srcs.iter()
.try_for_each(|src| writeln!(ci, "{}", encode_string(src)))?;
} else {
srcs.iter().try_for_each(|src| writeln!(ci, "{}", src))?;
}
}
// Read the destination file list from the process.
let mut dsts = Vec::with_capacity(srcs.len());
{
let co = child
.stdout
.take()
.expect("Could not open the child process’ stdout.");
let co = BufReader::new(co);
// TODO: Don’t allocate an intermediary String per line, by using the BufReader buffer.
co.lines().try_for_each(|dst| -> Result<(), Error> {
if flags.encode {
dsts.push(decode_string(&dst?)?);
} else {
dsts.push(dst?);
}
Ok(())
})?;
if dsts.len() != srcs.len() {
return Err(Error::BadLengths);
}
}
/* If the process failed, it is expected to print an error message; as such,
we exit directly. */
if !child.wait()?.success() {
return Err(Error::Nop);
}
let mut uniq_srcs: HashSet<PathBuf> = HashSet::with_capacity(srcs.len());
let mut uniq_dsts: HashSet<PathBuf> = HashSet::with_capacity(dsts.len());
let mut src_dst = srcs
.iter()
.zip(dsts)
.map(|(s, d)| -> Result<(PathBuf, PathBuf), Error> {
let s = fs::canonicalize(s)?;
let d = env::current_dir()?.join(Path::new(&d));
let d = normalize_path(&d);
if !uniq_srcs.insert(s.clone()) {
Err(Error::DuplicateInput(s))
} else if !uniq_dsts.insert(d.clone()) {
Err(Error::DuplicateOutput(d))
} else {
Ok((s, d))
}
})
.collect::<Result<Vec<_>, Error>>()?;
/* Sort the src/dst pairs so that the sources with the longest componenets
* come first.
*/
src_dst.sort_by_key(|(s, _)| Reverse(s.components().count()));
let dir = tempdir()?;
for s_d in src_dst.iter_mut() {
let (s, d) = s_d;
let mut hasher = DefaultHasher::new();
s.hash(&mut hasher);
let file = hasher.finish().to_string();
let dst = dir.path().join(&file);
if flags.dryrun {
println!("{} -> {}", s.as_path().display(), dst.as_path().display());
} else {
fs::rename(s, &dst)?;
}
*s_d = (dst, d.to_path_buf())
}
for (s, d) in src_dst.iter().rev() {
if flags.dryrun {
println!("{} -> {}", s.as_path().display(), d.as_path().display());
} else {
fs::rename(s, d)?;
}
}
Ok(())
}
fn parse_args() -> Result<(Flags, Vec<OsString>), lexopt::Error> {
use lexopt::prelude::*;
let mut rest = Vec::with_capacity(env::args().len());
let mut flags = Flags::default();
let mut parser = lexopt::Parser::from_env();
while let Some(arg) = parser.next()? {
match arg {
Short('0') | Long("nul") => flags.nul = true,
Short('d') | Long("dryrun") => flags.dryrun = true,
Short('e') | Long("encode") => flags.encode = true,
Short('i') | Long("individual") => flags.individual = true,
Short('v') | Long("verbose") => flags.verbose = true,
Value(v) => {
rest.push(v);
rest.extend(iter::from_fn(|| parser.value().ok()));
}
_ => return Err(arg.unexpected()),
}
}
Ok((flags, rest))
}
fn encode_string(s: &str) -> String {
s.chars()
.flat_map(|c| {
let cs = match c {
'\\' => ['\\', '\\'],
'\n' => ['\\', 'n'],
_ => [c, '\0'],
};
cs.into_iter()
.enumerate()
.filter(|(i, c)| *i != 1 || *c != '\0')
.map(|(_, c)| c)
})
.collect::<String>()
}
fn decode_string(s: &str) -> Result<String, Error> {
let mut pv = false;
s.chars()
.map(|c| {
Ok(match (pv, c) {
(true, '\\') => {
pv = false;
Some('\\')
}
(true, 'n') => {
pv = false;
Some('\n')
}
(true, _) => {
pv = false;
return Err(());
}
(false, '\\') => {
pv = true;
None
}
(false, _) => Some(c),
})
})
.filter_map(Result::transpose)
.collect::<Result<String, ()>>()
.map_err(|()| Error::BadDecoding(s.to_string()))
}
/* Blatantly stolen from the Cargo source code. This is MIT licensed. */
fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
|