electron-cli 0.3.0-alpha.2 → 0.3.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,426 @@
1
+ use std::{
2
+ fs,
3
+ fs::File,
4
+ io::{self, BufWriter},
5
+ path::{Path, PathBuf},
6
+ };
7
+
8
+ use anyhow::{bail, Context, Result};
9
+ use camino::Utf8PathBuf;
10
+ use serde::Serialize;
11
+ use zip::{write::SimpleFileOptions, CompressionMethod, ZipWriter};
12
+
13
+ use crate::{
14
+ cli::{MakeArgs, PackageArgs},
15
+ commands::package::{self, PackageReport},
16
+ output,
17
+ };
18
+
19
+ #[derive(Debug, Serialize)]
20
+ struct MakeReport {
21
+ package: PackageReport,
22
+ target: String,
23
+ skip_package: bool,
24
+ dry_run: bool,
25
+ make_dir: Utf8PathBuf,
26
+ artifact: Utf8PathBuf,
27
+ artifact_size: Option<u64>,
28
+ status: MakeStatus,
29
+ warnings: Vec<String>,
30
+ }
31
+
32
+ #[derive(Debug, Serialize)]
33
+ #[serde(rename_all = "kebab-case")]
34
+ enum MakeStatus {
35
+ Planned,
36
+ Made,
37
+ }
38
+
39
+ pub fn run(args: MakeArgs) -> Result<()> {
40
+ let mut report = build_report(&args)?;
41
+
42
+ if args.dry_run {
43
+ return print_report(&report, args.json);
44
+ }
45
+
46
+ execute_make(&mut report, &args)?;
47
+ report.status = MakeStatus::Made;
48
+ report.artifact_size = Some(
49
+ fs::metadata(report.artifact.as_str())
50
+ .with_context(|| format!("Could not stat {}", report.artifact))?
51
+ .len(),
52
+ );
53
+
54
+ print_report(&report, args.json)
55
+ }
56
+
57
+ fn build_report(args: &MakeArgs) -> Result<MakeReport> {
58
+ let package_args = PackageArgs {
59
+ cwd: args.cwd.clone(),
60
+ out_dir: args.out_dir.clone(),
61
+ name: args.name.clone(),
62
+ platform: args.platform.clone(),
63
+ arch: args.arch.clone(),
64
+ force: args.force,
65
+ dry_run: false,
66
+ json: false,
67
+ };
68
+ let snapshot = crate::project::inspect(&package_args.cwd)?;
69
+ let package = package::build_report(snapshot, &package_args)?;
70
+ let make_dir = Path::new(package.output_dir().as_str())
71
+ .join("make")
72
+ .join(args.target.as_str())
73
+ .join(package.platform())
74
+ .join(package.arch());
75
+ let artifact = make_dir.join(format!(
76
+ "{}-{}-{}.zip",
77
+ package.artifact_stem(),
78
+ package.platform(),
79
+ package.arch()
80
+ ));
81
+
82
+ let mut warnings = package.warnings().to_vec();
83
+ if args.skip_package && !Path::new(package.bundle_dir().as_str()).exists() {
84
+ warnings.push(format!(
85
+ "Package output does not exist: {}.",
86
+ package.bundle_dir()
87
+ ));
88
+ }
89
+
90
+ if artifact.exists() && !args.force {
91
+ warnings.push(format!(
92
+ "Make artifact already exists: {}. Use --force to overwrite it.",
93
+ artifact.display()
94
+ ));
95
+ }
96
+
97
+ Ok(MakeReport {
98
+ package,
99
+ target: args.target.as_str().to_string(),
100
+ skip_package: args.skip_package,
101
+ dry_run: args.dry_run,
102
+ make_dir: utf8_path(make_dir)?,
103
+ artifact: utf8_path(artifact)?,
104
+ artifact_size: None,
105
+ status: MakeStatus::Planned,
106
+ warnings,
107
+ })
108
+ }
109
+
110
+ fn execute_make(report: &mut MakeReport, args: &MakeArgs) -> Result<()> {
111
+ if !args.skip_package {
112
+ package::execute_package(&report.package, args.force)?;
113
+ report.package.mark_packaged();
114
+ } else if !Path::new(report.package.bundle_dir().as_str()).exists() {
115
+ bail!(
116
+ "Package output does not exist: {}. Run without --skip-package or run electron-cli package first.",
117
+ report.package.bundle_dir()
118
+ );
119
+ }
120
+
121
+ let artifact = Path::new(report.artifact.as_str());
122
+ if artifact.exists() {
123
+ if args.force {
124
+ fs::remove_file(artifact)
125
+ .with_context(|| format!("Could not remove {}", artifact.display()))?;
126
+ } else {
127
+ bail!(
128
+ "Make artifact already exists: {}. Use --force to overwrite it.",
129
+ artifact.display()
130
+ );
131
+ }
132
+ }
133
+
134
+ fs::create_dir_all(report.make_dir.as_str())
135
+ .with_context(|| format!("Could not create {}", report.make_dir))?;
136
+ write_zip_archive(Path::new(report.package.bundle_dir().as_str()), artifact)?;
137
+
138
+ Ok(())
139
+ }
140
+
141
+ fn print_report(report: &MakeReport, json: bool) -> Result<()> {
142
+ if json {
143
+ return output::json(report);
144
+ }
145
+
146
+ println!("electron-cli make");
147
+ println!();
148
+ println!("Project");
149
+ println!(" root: {}", report.package.project().root);
150
+ match report.package.project().package_label() {
151
+ Some(label) => println!(" package: {label}"),
152
+ None => println!(" package: not found"),
153
+ }
154
+ println!(" app name: {}", report.package.app_name());
155
+ println!(
156
+ " target: {} {} {}",
157
+ report.target,
158
+ report.package.platform(),
159
+ report.package.arch()
160
+ );
161
+ println!(" status: {}", report.status.as_str());
162
+
163
+ println!();
164
+ println!("Artifact");
165
+ println!(" {}", report.artifact);
166
+ if let Some(size) = report.artifact_size {
167
+ println!(" size: {size} bytes");
168
+ }
169
+
170
+ if !report.warnings.is_empty() {
171
+ println!();
172
+ println!("Warnings");
173
+ for warning in &report.warnings {
174
+ println!(" {warning}");
175
+ }
176
+ }
177
+
178
+ Ok(())
179
+ }
180
+
181
+ fn write_zip_archive(source: &Path, artifact: &Path) -> Result<()> {
182
+ if !source.exists() {
183
+ bail!("Package output does not exist: {}", source.display());
184
+ }
185
+
186
+ let parent = artifact
187
+ .parent()
188
+ .with_context(|| format!("Artifact path has no parent: {}", artifact.display()))?;
189
+ fs::create_dir_all(parent).with_context(|| format!("Could not create {}", parent.display()))?;
190
+
191
+ let file = File::create(artifact)
192
+ .with_context(|| format!("Could not create {}", artifact.display()))?;
193
+ let mut writer = ZipWriter::new(BufWriter::new(file));
194
+ let base = source
195
+ .parent()
196
+ .with_context(|| format!("Package output has no parent: {}", source.display()))?;
197
+
198
+ add_path_to_zip(source, base, &mut writer)?;
199
+ writer
200
+ .finish()
201
+ .with_context(|| format!("Could not finish {}", artifact.display()))?;
202
+
203
+ Ok(())
204
+ }
205
+
206
+ fn add_path_to_zip(
207
+ path: &Path,
208
+ base: &Path,
209
+ writer: &mut ZipWriter<BufWriter<File>>,
210
+ ) -> Result<()> {
211
+ let metadata =
212
+ fs::metadata(path).with_context(|| format!("Could not stat {}", path.display()))?;
213
+ let relative_path = zip_relative_path(path, base)?;
214
+
215
+ if metadata.is_dir() {
216
+ if !relative_path.is_empty() {
217
+ let directory_name = format!("{relative_path}/");
218
+ writer
219
+ .add_directory(directory_name, directory_options(&metadata))
220
+ .with_context(|| format!("Could not add {} to archive", path.display()))?;
221
+ }
222
+
223
+ let mut entries = fs::read_dir(path)
224
+ .with_context(|| format!("Could not read {}", path.display()))?
225
+ .collect::<Result<Vec<_>, io::Error>>()?;
226
+ entries.sort_by_key(|entry| entry.path());
227
+
228
+ for entry in entries {
229
+ add_path_to_zip(&entry.path(), base, writer)?;
230
+ }
231
+ } else {
232
+ writer
233
+ .start_file(relative_path, file_options(&metadata))
234
+ .with_context(|| format!("Could not add {} to archive", path.display()))?;
235
+ let mut file =
236
+ File::open(path).with_context(|| format!("Could not open {}", path.display()))?;
237
+ io::copy(&mut file, writer)
238
+ .with_context(|| format!("Could not write {} to archive", path.display()))?;
239
+ }
240
+
241
+ Ok(())
242
+ }
243
+
244
+ fn zip_relative_path(path: &Path, base: &Path) -> Result<String> {
245
+ let relative = path.strip_prefix(base).with_context(|| {
246
+ format!(
247
+ "Could not make {} relative to {}",
248
+ path.display(),
249
+ base.display()
250
+ )
251
+ })?;
252
+ Ok(relative
253
+ .components()
254
+ .map(|component| component.as_os_str().to_string_lossy())
255
+ .collect::<Vec<_>>()
256
+ .join("/"))
257
+ }
258
+
259
+ fn file_options(metadata: &fs::Metadata) -> SimpleFileOptions {
260
+ SimpleFileOptions::default()
261
+ .compression_method(CompressionMethod::Deflated)
262
+ .unix_permissions(unix_mode(metadata, 0o644))
263
+ }
264
+
265
+ fn directory_options(metadata: &fs::Metadata) -> SimpleFileOptions {
266
+ SimpleFileOptions::default()
267
+ .compression_method(CompressionMethod::Stored)
268
+ .unix_permissions(unix_mode(metadata, 0o755))
269
+ }
270
+
271
+ #[cfg(unix)]
272
+ fn unix_mode(metadata: &fs::Metadata, _fallback: u32) -> u32 {
273
+ use std::os::unix::fs::PermissionsExt;
274
+
275
+ metadata.permissions().mode()
276
+ }
277
+
278
+ #[cfg(not(unix))]
279
+ fn unix_mode(_metadata: &fs::Metadata, fallback: u32) -> u32 {
280
+ fallback
281
+ }
282
+
283
+ fn utf8_path(path: PathBuf) -> Result<Utf8PathBuf> {
284
+ Utf8PathBuf::from_path_buf(path).map_err(|path| {
285
+ anyhow::anyhow!(
286
+ "Path contains invalid UTF-8 and cannot be represented in JSON: {}",
287
+ path.display()
288
+ )
289
+ })
290
+ }
291
+
292
+ impl MakeStatus {
293
+ fn as_str(&self) -> &'static str {
294
+ match self {
295
+ MakeStatus::Planned => "planned",
296
+ MakeStatus::Made => "made",
297
+ }
298
+ }
299
+ }
300
+
301
+ #[cfg(test)]
302
+ mod tests {
303
+ use super::*;
304
+ use zip::ZipArchive;
305
+
306
+ #[test]
307
+ fn builds_make_report_for_zip_target() {
308
+ let root = unique_temp_dir("plan");
309
+ write_package_json(&root);
310
+ write_app_file(&root);
311
+ write_fake_electron_dist(&root);
312
+
313
+ let args = MakeArgs {
314
+ cwd: root.clone(),
315
+ out_dir: PathBuf::from("out"),
316
+ name: None,
317
+ platform: None,
318
+ arch: None,
319
+ target: crate::cli::MakeTarget::Zip,
320
+ skip_package: false,
321
+ force: false,
322
+ dry_run: true,
323
+ json: true,
324
+ };
325
+ let report = build_report(&args).expect("report should build");
326
+
327
+ assert_eq!(report.target, "zip");
328
+ let expected_suffix = PathBuf::from("out")
329
+ .join("make")
330
+ .join("zip")
331
+ .join(report.package.platform())
332
+ .join(report.package.arch())
333
+ .join(format!(
334
+ "starter-app-{}-{}.zip",
335
+ report.package.platform(),
336
+ report.package.arch()
337
+ ));
338
+ assert!(Path::new(report.artifact.as_str()).ends_with(expected_suffix));
339
+
340
+ let _ = fs::remove_dir_all(root);
341
+ }
342
+
343
+ #[test]
344
+ fn makes_zip_artifact_after_packaging() {
345
+ let root = unique_temp_dir("execute");
346
+ write_package_json(&root);
347
+ write_app_file(&root);
348
+ write_fake_electron_dist(&root);
349
+
350
+ let args = MakeArgs {
351
+ cwd: root.clone(),
352
+ out_dir: PathBuf::from("out"),
353
+ name: None,
354
+ platform: None,
355
+ arch: None,
356
+ target: crate::cli::MakeTarget::Zip,
357
+ skip_package: false,
358
+ force: false,
359
+ dry_run: false,
360
+ json: false,
361
+ };
362
+ let mut report = build_report(&args).expect("report should build");
363
+
364
+ execute_make(&mut report, &args).expect("make should succeed");
365
+
366
+ let file = File::open(report.artifact.as_str()).expect("artifact should exist");
367
+ let mut archive = ZipArchive::new(file).expect("zip should open");
368
+ let app_entry = if report.package.platform() == "darwin" {
369
+ "starter-app.app/Contents/Resources/app/package.json".to_string()
370
+ } else {
371
+ format!(
372
+ "starter-app-{}-{}/resources/app/package.json",
373
+ report.package.platform(),
374
+ report.package.arch()
375
+ )
376
+ };
377
+
378
+ archive
379
+ .by_name(&app_entry)
380
+ .expect("app package.json should be archived");
381
+
382
+ let _ = fs::remove_dir_all(root);
383
+ }
384
+
385
+ fn write_package_json(root: &Path) {
386
+ fs::write(
387
+ root.join("package.json"),
388
+ r#"{"name":"starter-app","version":"0.1.0","main":"src/main.js","devDependencies":{"electron":"30.0.0"}}"#,
389
+ )
390
+ .expect("package.json should be written");
391
+ }
392
+
393
+ fn write_app_file(root: &Path) {
394
+ fs::create_dir_all(root.join("src")).expect("src should be created");
395
+ fs::write(root.join("src/main.js"), "console.log('hello');")
396
+ .expect("main file should be written");
397
+ }
398
+
399
+ fn write_fake_electron_dist(root: &Path) {
400
+ let dist = root.join("node_modules/electron/dist");
401
+ if cfg!(target_os = "macos") {
402
+ let app = dist.join("Electron.app/Contents/MacOS");
403
+ fs::create_dir_all(&app).expect("fake macOS electron app should be created");
404
+ fs::write(app.join("Electron"), "").expect("fake macOS binary should be written");
405
+ } else if cfg!(target_os = "windows") {
406
+ fs::create_dir_all(&dist).expect("fake electron dist should be created");
407
+ fs::write(dist.join("electron.exe"), "").expect("fake exe should be written");
408
+ } else {
409
+ fs::create_dir_all(&dist).expect("fake electron dist should be created");
410
+ fs::write(dist.join("electron"), "").expect("fake binary should be written");
411
+ }
412
+ }
413
+
414
+ fn unique_temp_dir(label: &str) -> PathBuf {
415
+ let nanos = std::time::SystemTime::now()
416
+ .duration_since(std::time::UNIX_EPOCH)
417
+ .expect("clock should be after epoch")
418
+ .as_nanos();
419
+ let path = std::env::temp_dir().join(format!(
420
+ "electron-cli-make-{label}-{}-{nanos}",
421
+ std::process::id()
422
+ ));
423
+ fs::create_dir_all(&path).expect("temp dir should be created");
424
+ path
425
+ }
426
+ }
@@ -1,4 +1,7 @@
1
1
  pub mod doctor;
2
2
  pub mod init;
3
3
  pub mod inspect;
4
+ pub mod make;
5
+ pub mod package;
4
6
  pub mod plan;
7
+ pub mod start;