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
use crate::Settings;
use std::{
ffi::OsStr,
fs::{self, File},
io::{self, BufRead, BufReader, BufWriter, Write},
path::{Component, Path, PathBuf},
process::{Command, Stdio},
};
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
pub fn is_retina<P: AsRef<Path>>(path: P) -> bool {
path
.as_ref()
.file_stem()
.and_then(OsStr::to_str)
.map(|stem| stem.ends_with("@2x"))
.unwrap_or(false)
}
pub fn create_file(path: &Path) -> crate::Result<BufWriter<File>> {
if let Some(parent) = path.parent() {
fs::create_dir_all(&parent)?;
}
let file = File::create(path)?;
Ok(BufWriter::new(file))
}
#[cfg(unix)]
fn symlink_dir(src: &Path, dst: &Path) -> io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
#[cfg(windows)]
fn symlink_dir(src: &Path, dst: &Path) -> io::Result<()> {
std::os::windows::fs::symlink_dir(src, dst)
}
#[cfg(unix)]
fn symlink_file(src: &Path, dst: &Path) -> io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
#[cfg(windows)]
fn symlink_file(src: &Path, dst: &Path) -> io::Result<()> {
std::os::windows::fs::symlink_file(src, dst)
}
pub fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> crate::Result<()> {
let from = from.as_ref();
let to = to.as_ref();
if !from.exists() {
return Err(crate::Error::GenericError(format!(
"{:?} does not exist",
from
)));
}
if !from.is_file() {
return Err(crate::Error::GenericError(format!(
"{:?} is not a file",
from
)));
}
let dest_dir = to.parent().expect("No data in parent");
fs::create_dir_all(dest_dir)?;
fs::copy(from, to)?;
Ok(())
}
pub fn copy_dir(from: &Path, to: &Path) -> crate::Result<()> {
if !from.exists() {
return Err(crate::Error::GenericError(format!(
"{:?} does not exist",
from
)));
}
if !from.is_dir() {
return Err(crate::Error::GenericError(format!(
"{:?} is not a Directory",
from
)));
}
if to.exists() {
return Err(crate::Error::GenericError(format!(
"{:?} already exists",
from
)));
}
let parent = to.parent().expect("No data in parent");
fs::create_dir_all(parent)?;
for entry in walkdir::WalkDir::new(from) {
let entry = entry?;
debug_assert!(entry.path().starts_with(from));
let rel_path = entry.path().strip_prefix(from)?;
let dest_path = to.join(rel_path);
if entry.file_type().is_symlink() {
let target = fs::read_link(entry.path())?;
if entry.path().is_dir() {
symlink_dir(&target, &dest_path)?;
} else {
symlink_file(&target, &dest_path)?;
}
} else if entry.file_type().is_dir() {
fs::create_dir(dest_path)?;
} else {
fs::copy(entry.path(), dest_path)?;
}
}
Ok(())
}
pub fn resource_relpath(path: &Path) -> PathBuf {
let mut dest = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) => {}
Component::RootDir => dest.push("_root_"),
Component::CurDir => {}
Component::ParentDir => dest.push("_up_"),
Component::Normal(string) => dest.push(string),
}
}
dest
}
pub fn print_bundling(filename: &str) -> crate::Result<()> {
print_progress("Bundling", filename)
}
pub fn print_finished(bundles: &[crate::bundle::Bundle]) -> crate::Result<()> {
let pluralised = if bundles.len() == 1 {
"bundle"
} else {
"bundles"
};
let msg = format!("{} {} at:", bundles.len(), pluralised);
print_progress("Finished", &msg)?;
for bundle in bundles {
for path in &bundle.bundle_paths {
let mut note = "";
if bundle.package_type == crate::PackageType::Updater {
note = " (updater)";
}
println!(" {}{}", path.display(), note,);
}
}
Ok(())
}
pub fn print_signed_updater_archive(output_paths: &[PathBuf]) -> crate::Result<()> {
let pluralised = if output_paths.len() == 1 {
"updater archive"
} else {
"updater archives"
};
let msg = format!("{} {} at:", output_paths.len(), pluralised);
print_progress("Signed", &msg)?;
for path in output_paths {
println!(" {}", path.display());
}
Ok(())
}
fn print_progress(step: &str, msg: &str) -> crate::Result<()> {
let mut output = StandardStream::stderr(ColorChoice::Always);
let _ = output.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true));
write!(output, " {}", step)?;
output.reset()?;
writeln!(output, " {}", msg)?;
output.flush()?;
Ok(())
}
pub fn print_warning(message: &str) -> crate::Result<()> {
let mut output = StandardStream::stderr(ColorChoice::Always);
let _ = output.set_color(ColorSpec::new().set_fg(Some(Color::Yellow)).set_bold(true));
write!(output, "warning:")?;
output.reset()?;
writeln!(output, " {}", message)?;
output.flush()?;
Ok(())
}
pub fn print_info(message: &str) -> crate::Result<()> {
let mut output = StandardStream::stderr(ColorChoice::Always);
let _ = output.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_bold(true));
write!(output, "info:")?;
output.reset()?;
writeln!(output, " {}", message)?;
output.flush()?;
Ok(())
}
pub fn print_error(error: &anyhow::Error) -> crate::Result<()> {
let mut output = StandardStream::stderr(ColorChoice::Always);
let _ = output.set_color(ColorSpec::new().set_fg(Some(Color::Red)).set_bold(true));
write!(output, "error:")?;
output.reset()?;
let _ = output.set_color(ColorSpec::new().set_bold(true));
writeln!(output, " {}", error)?;
output.reset()?;
for cause in error.chain().skip(1) {
writeln!(output, " Caused by: {}", cause)?;
}
output.flush()?;
std::process::exit(1)
}
pub fn execute_with_verbosity(cmd: &mut Command, settings: &Settings) -> crate::Result<()> {
let stdio_config = if settings.is_verbose() {
Stdio::piped
} else {
Stdio::null
};
let mut child = cmd
.stdout(stdio_config())
.stderr(stdio_config())
.spawn()
.expect("failed to spawn command");
if settings.is_verbose() {
let stdout = child.stdout.as_mut().expect("Failed to get stdout handle");
let reader = BufReader::new(stdout);
for line in reader.lines() {
println!("{}", line.expect("Failed to get line"));
}
}
let status = child.wait()?;
if status.success() {
Ok(())
} else {
Err(anyhow::anyhow!("command failed").into())
}
}
#[cfg(test)]
mod tests {
use super::{create_file, is_retina, resource_relpath};
use std::{io::Write, path::PathBuf};
#[test]
fn create_file_with_parent_dirs() {
let tmp = tempfile::tempdir().expect("Unable to create temp dir");
assert!(!tmp.path().join("parent").exists());
{
let mut file =
create_file(&tmp.path().join("parent/file.txt")).expect("Failed to create file");
writeln!(file, "Hello, world!").expect("unable to write file");
}
assert!(tmp.path().join("parent").is_dir());
assert!(tmp.path().join("parent/file.txt").is_file());
}
#[cfg(not(windows))]
#[test]
fn copy_dir_with_symlinks() {
let tmp = tempfile::tempdir().expect("unable to create tempdir");
{
let mut file =
create_file(&tmp.path().join("orig/sub/file.txt")).expect("Unable to create file");
writeln!(file, "Hello, world!").expect("Unable to write to file");
}
super::symlink_file(
&PathBuf::from("sub/file.txt"),
&tmp.path().join("orig/link"),
)
.expect("Failed to create symlink");
assert_eq!(
std::fs::read(tmp.path().join("orig/link"))
.expect("Failed to read file")
.as_slice(),
b"Hello, world!\n"
);
super::copy_dir(&tmp.path().join("orig"), &tmp.path().join("parent/copy"))
.expect("Failed to copy dir");
assert!(tmp.path().join("parent/copy").is_dir());
assert!(tmp.path().join("parent/copy/sub").is_dir());
assert!(tmp.path().join("parent/copy/sub/file.txt").is_file());
assert_eq!(
std::fs::read(tmp.path().join("parent/copy/sub/file.txt"))
.expect("Failed to read file")
.as_slice(),
b"Hello, world!\n"
);
assert!(tmp.path().join("parent/copy/link").exists());
assert_eq!(
std::fs::read_link(tmp.path().join("parent/copy/link")).expect("Failed to read from symlink"),
PathBuf::from("sub/file.txt")
);
assert_eq!(
std::fs::read(tmp.path().join("parent/copy/link"))
.expect("Failed to read from file")
.as_slice(),
b"Hello, world!\n"
);
}
#[test]
fn retina_icon_paths() {
assert!(!is_retina("data/icons/512x512.png"));
assert!(is_retina("data/icons/512x512@2x.png"));
}
#[test]
fn resource_relative_paths() {
assert_eq!(
resource_relpath(&PathBuf::from("./data/images/button.png")),
PathBuf::from("data/images/button.png")
);
assert_eq!(
resource_relpath(&PathBuf::from("../../images/wheel.png")),
PathBuf::from("_up_/_up_/images/wheel.png")
);
assert_eq!(
resource_relpath(&PathBuf::from("/home/ferris/crab.png")),
PathBuf::from("_root_/home/ferris/crab.png")
);
}
}