-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.rs
797 lines (692 loc) · 25.1 KB
/
main.rs
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
use anyhow::{anyhow, bail, Error};
use inflector::cases::titlecase::to_title_case;
use log::{debug, info};
use serde_derive::Deserialize;
use std::{
env,
fs::{self},
io::Write,
path::{Path, PathBuf},
process::Command,
thread, time,
};
use structopt::StructOpt;
use zip::{write::FileOptions, CompressionMethod};
use zip_extensions::zip_create_from_directory_with_options;
#[cfg(unix)]
use anyhow::Context;
mod config;
#[cfg(target_os = "macos")]
const GCC_PATH_STR: &'static str = "/usr/local/bin/arm-none-eabi-gcc";
#[cfg(all(unix, not(target_os = "macos")))]
const GCC_PATH_STR: &'static str = "arm-none-eabi-gcc";
#[cfg(windows)]
const GCC_PATH_STR: &'static str =
r"C:\Program Files (x86)\GNU Tools Arm Embedded\9 2019-q4-major\bin\arm-none-eabi-gcc.exe";
#[cfg(target_os = "macos")]
const OBJCOPY_PATH_STR: &'static str = "/usr/local/bin/arm-none-eabi-objcopy";
#[cfg(all(unix, not(target_os = "macos")))]
const OBJCOPY_PATH_STR: &'static str = "arm-none-eabi-objcopy";
#[cfg(windows)]
const OBJCOPY_PATH_STR: &'static str =
r"C:\Program Files (x86)\GNU Tools Arm Embedded\9 2019-q4-major\bin\arm-none-eabi-objcopy.exe";
#[cfg(unix)]
#[allow(unused)]
const PDUTIL_NAME: &'static str = "pdutil";
#[cfg(windows)]
const PDUTIL_NAME: &'static str = "PDUTIL.EXE";
#[cfg(unix)]
const PDC_NAME: &'static str = "pdc";
#[cfg(windows)]
const PDC_NAME: &'static str = "PDC.EXE";
#[cfg(unix)]
const SDK_DIR: &'static str = "Developer";
#[cfg(windows)]
const SDK_DIR: &'static str = "Documents";
fn playdate_sdk_cfg() -> Result<config::SdkCfg, Error> {
let cfg_path = dirs::home_dir()
.ok_or(anyhow!("Can't find home dir"))?
.join(config::CFG_DIR)
.join(config::CFG_FILENAME);
fs::read_to_string(cfg_path)?.parse()
}
fn playdate_sdk_path() -> Result<PathBuf, Error> {
match playdate_sdk_cfg() {
Err(_) => {
debug!("Unable to read PlaydateSDK config from home dir, so using default.");
playdate_sdk_path_default()
}
Ok(cfg) => cfg.sdk_path().map(|p| Ok(p)).unwrap_or_else(|| {
debug!("Unable to determine PlaydateSDK path by config, so using default.");
playdate_sdk_path_default()
}),
}
}
fn playdate_sdk_path_default() -> Result<PathBuf, Error> {
let sdk_location = match env::var("PLAYDATE_SDK_PATH") {
Ok(path) => PathBuf::from(path),
Err(_) => {
// couldn't find the expected env variable, try defaulting to their home directory
let home_dir = dirs::home_dir().ok_or(anyhow!("Can't find home dir"))?;
home_dir.join(SDK_DIR).join("PlaydateSDK")
}
};
Ok(sdk_location)
}
fn playdate_c_api_path() -> Result<PathBuf, Error> {
Ok(playdate_sdk_path()?.join("C_API"))
}
type Assets = Vec<String>;
#[derive(Clone, Debug, Default, Deserialize)]
struct Metadata {
name: Option<String>,
author: Option<String>,
description: Option<String>,
bundle_id: Option<String>,
version: Option<String>,
build_number: Option<u64>,
image_path: Option<String>,
launch_sound_path: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize)]
struct Target {
name: String,
assets: Option<Assets>,
metadata: Option<Metadata>,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct Manifest {
#[serde(default, alias = "target")]
targets: Vec<Target>,
}
impl Manifest {
fn get_target(&self, target_name: &str) -> Option<&Target> {
self.targets
.iter()
.find(|target| &target.name == target_name)
}
}
pub fn load_manifest(manifest_path: &Option<PathBuf>) -> Result<Manifest, Error> {
let cwd: PathBuf = if let Some(actual_manifest_path) = manifest_path.as_ref() {
actual_manifest_path
.parent()
.expect("manifest_path parent")
.to_path_buf()
} else {
std::env::current_dir()?
};
let manifest_path = cwd.join("Crank.toml");
if !manifest_path.exists() {
return Ok(Manifest::default());
}
let manifest_contents = fs::read_to_string(manifest_path)?;
let manifest = toml::from_str(&manifest_contents)?;
Ok(manifest)
}
#[derive(Debug, StructOpt)]
#[structopt(about = "Crank commands")]
enum CrankCommand {
/// Build binary targeting Playdate device or Simulator
Build(Build),
/// Build binary targeting Playdate device or Simulator and run it
Run(Build),
/// Make a pdx file for both device and simulator and compress it.
Package(Package),
}
#[derive(Debug, StructOpt, Clone)]
struct Build {
/// Build for the Playdate device.
#[structopt(long)]
device: bool,
/// Build artifacts in release mode, with optimizations.
#[structopt(long)]
release: bool,
/// Build a specific example from the examples/ dir.
#[structopt(long)]
example: Option<String>,
/// Run.
#[structopt(long)]
run: bool,
}
impl Build {
fn setup_path() -> Result<PathBuf, Error> {
let playdate_c_api_path = playdate_c_api_path()?;
Ok(playdate_c_api_path.join("buildsupport").join("setup.c"))
}
fn get_target_name(&self, opt: &Opt) -> Result<Option<String>, Error> {
let mut cmd = cargo_metadata::MetadataCommand::new();
if let Some(manifest_path) = &opt.manifest_path {
cmd.manifest_path(manifest_path);
}
cmd.no_deps();
let static_lib: String = "staticlib".to_string();
let cdylib: String = "cdylib".to_string();
let metadata = cmd.exec()?;
for package in metadata.packages {
if let Some(lib_target) = package
.targets
.iter()
.filter(|target| target.kind.contains(&static_lib) && target.kind.contains(&cdylib))
.nth(0)
{
return Ok(Some(lib_target.name.clone()));
}
}
Ok(None)
}
fn compile_setup(&self, target_dir: &PathBuf) -> Result<(), Error> {
let gcc_compile_static_args = "-g -c -mthumb -mcpu=cortex-m7 -mfloat-abi=hard \
-mfpu=fpv4-sp-d16 -D__FPU_USED=1 -O2 -falign-functions=16 -fomit-frame-pointer \
-gdwarf-2 -Wall -Wno-unused -Wstrict-prototypes -Wno-unknown-pragmas -fverbose-asm \
-ffunction-sections -fdata-sections -DTARGET_PLAYDATE=1 -DTARGET_EXTENSION=1";
let args_iter = gcc_compile_static_args.split(" ");
let playdate_c_api_path = playdate_c_api_path()?;
let setup_path = Self::setup_path()?;
let mut command = Command::new(GCC_PATH_STR);
command
.args(args_iter)
.arg(setup_path)
.arg("-I")
.arg(playdate_c_api_path)
.arg("-o")
.arg(target_dir.join("setup.o"));
info!("compile_setup: {:?}", command);
let status = command.status()?;
if !status.success() {
bail!("gcc failed with error {:?}", status);
}
Ok(())
}
fn link_binary(
&self,
target_dir: &PathBuf,
example_name: &str,
lib_path: &PathBuf,
) -> Result<(), Error> {
let gcc_link_static_args = "-mthumb -mcpu=cortex-m7 -mfloat-abi=hard \
-mfpu=fpv4-sp-d16 -D__FPU_USED=1 -Wl,--gc-sections,--no-warn-mismatch";
let mut cmd = Command::new(GCC_PATH_STR);
let setup_obj_path = target_dir.join("setup.o");
cmd.arg(setup_obj_path);
cmd.arg(lib_path);
let args_iter = gcc_link_static_args.split(" ");
cmd.args(args_iter);
let playdate_c_api_path = playdate_c_api_path()?;
let link_map_path = playdate_c_api_path.join("buildsupport").join("link_map.ld");
cmd.arg("-T");
cmd.arg(link_map_path);
let target_path = target_dir.join(format!("{}.elf", example_name));
cmd.arg("-o");
cmd.arg(target_path);
info!("link_binary: {:?}", cmd);
let status = cmd.status()?;
if !status.success() {
bail!("gcc failed with error {:?}", status);
}
Ok(())
}
fn make_binary(
&self,
target_dir: &PathBuf,
example_name: &str,
source_dir: &PathBuf,
) -> Result<(), Error> {
let mut cmd = Command::new(OBJCOPY_PATH_STR);
let source_path = target_dir.join(format!("{}.elf", example_name));
let dest_path = target_dir.join(format!("{}.bin", example_name));
cmd.arg("-O");
cmd.arg("binary");
cmd.arg(&source_path);
cmd.arg(&dest_path);
info!("make_binary: {:?}", cmd);
let status = cmd.status()?;
if !status.success() {
bail!("objcopy failed with error {:?}", status);
}
let source_dir_path = source_dir.join("pdex.bin");
fs::copy(&dest_path, &source_dir_path)?;
Ok(())
}
fn make_source_dir(
&self,
overall_target_dir: &PathBuf,
example_title: &str,
) -> Result<PathBuf, Error> {
info!("make_source_dir");
let pdx_path = overall_target_dir.join(example_title);
fs::create_dir_all(&pdx_path)?;
Ok(pdx_path)
}
fn copy_assets(
&self,
target_name: &str,
source_dir: &Path,
crank_manifest: &Manifest,
dest_dir: &PathBuf,
) -> Result<(), Error> {
info!("copy_assets");
let target = crank_manifest.get_target(target_name);
if let Some(Target {
assets: Some(assets),
..
}) = target
{
for asset in assets {
let src_path = source_dir.join(asset);
let dst_path = dest_dir.join(asset);
info!("copy {:?} to {:?}", src_path, dst_path);
if let Some(dst_parent) = dst_path.parent() {
fs::create_dir_all(&dst_parent)?;
}
fs::copy(&src_path, &dst_path)?;
}
}
Ok(())
}
fn make_manifest(
&self,
crank_manifest: &Manifest,
target_name: &str,
source_dir: &PathBuf,
) -> Result<(), Error> {
info!("make_manifest");
let target = crank_manifest.get_target(target_name);
if let Some(Target {
metadata: Some(metadata),
..
}) = target
{
let pdx_info_path = source_dir.join("pdxinfo");
let mut pdx_info = fs::File::create(&pdx_info_path)?;
if let Some(name) = &metadata.name {
writeln!(pdx_info, "name={}", name)?;
}
if let Some(author) = &metadata.author {
writeln!(pdx_info, "author={}", author)?;
}
if let Some(description) = &metadata.description {
writeln!(pdx_info, "description={}", description)?;
}
if let Some(bundle_id) = &metadata.bundle_id {
writeln!(pdx_info, "bundleID={}", bundle_id)?;
}
if let Some(version) = &metadata.version {
writeln!(pdx_info, "version={}", version)?;
}
if let Some(build_number) = &metadata.build_number {
writeln!(pdx_info, "buildNumber={}", build_number)?;
}
if let Some(image_path) = &metadata.image_path {
writeln!(pdx_info, "imagePath={}", image_path)?;
}
if let Some(launch_sound_path) = &metadata.launch_sound_path {
writeln!(pdx_info, "launchSoundPath={}", launch_sound_path)?;
}
}
Ok(())
}
fn run_pdc(&self, source_dir: &PathBuf, dest_dir: &PathBuf) -> Result<(), Error> {
info!("run_pdc");
let pdc_path = playdate_sdk_path()?.join("bin").join(PDC_NAME);
let mut cmd = Command::new(pdc_path);
cmd.arg(source_dir);
cmd.arg(dest_dir);
debug!("{:?}", cmd);
let status = cmd.status()?;
if !status.success() {
bail!("pdc failed with error {:?}", status);
}
Ok(())
}
#[cfg(unix)]
fn copy_directory(src: &Path, dst: &Path) -> Result<(), Error> {
info!("copy_directory {:?} -> {:?}", src, dst);
for entry in fs::read_dir(src).context("Reading source game directory")? {
let entry = entry.context("bad entry")?;
let target_path = dst.join(entry.file_name());
if entry.path().is_dir() {
fs::create_dir_all(&target_path)
.context(format!("Creating directory {:#?} on device", target_path))?;
Self::copy_directory(&entry.path(), &target_path)?;
} else {
info!("copy_file {:?} -> {:?}", entry.path(), target_path);
fs::copy(entry.path(), target_path).context("copy file")?;
}
}
Ok(())
}
#[cfg(windows)]
fn run_target(&self, pdx_dir: &PathBuf, example_title: &str) -> Result<(), Error> {
info!("run_target");
let pdutil_path = playdate_sdk_path()?.join("bin").join(PDUTIL_NAME);
let device_path = format!("/Games/{}.pdx", example_title);
let duration = time::Duration::from_millis(100);
let _ = Command::new(&pdutil_path)
.arg("install")
.arg(pdx_dir)
.status()?;
thread::sleep(duration * 5);
let _ = Command::new(&pdutil_path)
.arg("run")
.arg(device_path)
.status()?;
Ok(())
}
#[cfg(unix)]
fn run_target(&self, pdx_dir: &PathBuf, example_title: &str) -> Result<(), Error> {
info!("run_target");
let pdutil_path = playdate_sdk_path()?.join("bin").join(PDUTIL_NAME);
#[cfg(target_os = "macos")]
let modem_path = PathBuf::from(
env::var("PLAYDATE_SERIAL_DEVICE")
.unwrap_or(String::from("/dev/cu.usbmodemPDU1_Y0005491")),
);
#[cfg(not(target_os = "macos"))]
let modem_path = PathBuf::from(
env::var("PLAYDATE_SERIAL_DEVICE").unwrap_or(String::from("/dev/ttyACM0")),
);
#[cfg(target_os = "macos")]
let data_path = PathBuf::from(
env::var("PLAYDATE_MOUNT_POINT").unwrap_or(String::from("/Volumes/PLAYDATE")),
);
#[cfg(not(target_os = "macos"))]
let data_path = PathBuf::from(env::var("PLAYDATE_MOUNT_POINT").unwrap_or(format!(
"/run/media/{}/PLAYDATE",
env::var("USER").expect("user")
)));
let duration = time::Duration::from_millis(100);
if modem_path.exists() {
let mut cmd = Command::new(&pdutil_path);
cmd.arg(modem_path.clone()).arg("datadisk").arg(pdx_dir);
info!("datadisk cmd: {:#?}", cmd);
let _ = cmd.status()?;
while modem_path.exists() {
thread::sleep(duration);
}
}
while !data_path.exists() {
thread::sleep(duration);
}
let games_dir = data_path.join("Games");
// This prevents issues that occur when the PLAYDATE volume is mounted
// but not all of the inner folders are available yet.
while !games_dir.exists() {
thread::sleep(duration);
}
let game_device_dir = format!("{}.pdx", example_title);
let games_target_dir = games_dir.join(&game_device_dir);
fs::create_dir(&games_target_dir).ok();
Self::copy_directory(&pdx_dir, &games_target_dir)?;
#[cfg(target_os = "macos")]
{
let mut cmd = Command::new("diskutil");
cmd.arg("eject").arg(&data_path);
info!("eject cmd: {:#?}", cmd);
let _ = cmd.status()?;
}
#[cfg(not(target_os = "macos"))]
{
let mut cmd = Command::new("eject");
cmd.arg(&data_path);
info!("eject cmd: {:#?}", cmd);
let _ = cmd.status()?;
}
while !modem_path.exists() {
thread::sleep(duration);
}
let mut cmd = Command::new(&pdutil_path);
cmd.arg(modem_path)
.arg("run")
.arg(format!("/Games/{}", game_device_dir));
info!("run cmd: {:#?}", cmd);
let _ = cmd.status()?;
Ok(())
}
fn link_dylib(
&self,
target_dir: &PathBuf,
example_name: &str,
source_dir: &PathBuf,
) -> Result<(), Error> {
info!("link_dylib");
let (lib_target_path, source_dir_path) = if cfg!(target_os = "macos") {
let lib_target_path = target_dir.join(format!("lib{}.dylib", example_name));
let source_dir_path = source_dir.join("pdex.dylib");
(lib_target_path, source_dir_path)
} else if cfg!(unix) {
let lib_target_path = target_dir.join(format!("lib{}.so", example_name));
let source_dir_path = source_dir.join("pdex.so");
(lib_target_path, source_dir_path)
} else if cfg!(windows) {
let lib_target_path = target_dir.join(format!("{}.dll", example_name));
let source_dir_path = source_dir.join("pdex.dll");
(lib_target_path, source_dir_path)
} else {
unreachable!("platform not supported")
};
debug!("copy: {:?} -> {:?}", lib_target_path, source_dir_path);
fs::copy(&lib_target_path, &source_dir_path)?;
let pdx_bin_path = source_dir.join("pdex.bin");
if !pdx_bin_path.exists() {
fs::File::create(&pdx_bin_path)?;
}
Ok(())
}
fn run_simulator(&self, pdx_path: &PathBuf) -> Result<(), Error> {
info!("run_simulator");
#[cfg(windows)]
let status = {
let mut cmd = Command::new("PlaydateSimulator.exe");
cmd.arg(&pdx_path);
cmd.status()?
};
#[cfg(target_os = "macos")]
let status = {
let mut cmd = Command::new("open");
cmd.arg("-a");
cmd.arg("Playdate Simulator");
cmd.arg(&pdx_path);
cmd.status()?
};
#[cfg(all(unix, not(target_os = "macos")))]
let status = {
let mut cmd = Command::new("PlaydateSimulator");
cmd.arg(&pdx_path);
cmd.status()?
};
if !status.success() {
bail!("open failed with error {:?}", status);
}
Ok(())
}
pub fn execute(
&self,
opt: &Opt,
crank_manifest: &Manifest,
) -> Result<(PathBuf, String), Error> {
info!("building");
let current_dir = std::env::current_dir()?;
let manifest_path_str;
let mut args = if self.device {
vec!["+nightly", "build", "-Z", "build-std"]
} else {
vec!["build"]
};
let project_path = if let Some(manifest_path) = opt.manifest_path.as_ref() {
args.push("--manifest-path");
manifest_path_str = manifest_path.to_string_lossy();
args.push(&manifest_path_str);
manifest_path.parent().expect("parent")
} else {
current_dir.as_path()
};
let (target_name, target_path) = if let Some(example) = self.example.as_ref() {
args.push("--example");
args.push(example);
(example.clone(), format!("examples/"))
} else {
args.push("--lib");
if let Some(target_name) = self.get_target_name(&opt)? {
(target_name.clone(), "".to_string())
} else {
bail!("Could not find compatible target");
}
};
if self.release {
args.push("--release");
}
if self.device {
args.push("--target");
args.push("thumbv7em-none-eabihf");
}
let mut command = Command::new("cargo");
command.args(args);
info!("build command: {:?}", command);
let status = command.status()?;
if !status.success() {
bail!("cargo failed with error {:?}", status);
}
let overall_target_dir = project_path.join("target");
let game_title = crank_manifest
.get_target(&target_name)
.and_then(|target| target.metadata.as_ref())
.and_then(|metadata| metadata.name.clone())
.unwrap_or(to_title_case(&target_name));
let source_path = self.make_source_dir(&overall_target_dir, &game_title)?;
let dest_path = overall_target_dir.join(format!("{}.pdx", &game_title));
if dest_path.exists() {
fs::remove_dir_all(&dest_path).unwrap_or_else(|_err| ());
}
let mut target_dir = project_path.join("target");
let dir_name = if self.release { "release" } else { "debug" };
if self.device {
target_dir = target_dir.join("thumbv7em-none-eabihf").join(dir_name);
let lib_file = target_dir.join(format!("{}lib{}.a", target_path, target_name));
self.compile_setup(&target_dir)?;
self.link_binary(&target_dir, &target_name, &lib_file)?;
self.make_binary(&target_dir, &target_name, &source_path)?;
self.copy_assets(&target_name, &project_path, &crank_manifest, &source_path)?;
self.make_manifest(&crank_manifest, &target_name, &source_path)?;
self.run_pdc(&source_path, &dest_path)?;
if self.run {
self.run_target(&dest_path, &game_title)?;
}
} else {
target_dir = target_dir.join(dir_name).join(target_path);
self.link_dylib(&target_dir, &target_name, &source_path)?;
self.copy_assets(&target_name, &project_path, &crank_manifest, &source_path)?;
self.make_manifest(&crank_manifest, &target_name, &source_path)?;
self.run_pdc(&source_path, &dest_path)?;
if self.run {
self.run_simulator(&dest_path)?;
}
}
Ok((dest_path, game_title))
}
}
#[derive(Debug, StructOpt)]
struct Package {
/// Build a specific example from the examples/ dir.
#[structopt(long)]
example: Option<String>,
/// clean before building
#[structopt(long)]
clean: bool,
/// Reveal the resulting archive in the Finder/Exporer
#[structopt(long)]
reveal: bool,
}
impl Package {
pub fn execute(&self, opt: &Opt, crank_manifest: &Manifest) -> Result<(), Error> {
if self.clean {
info!("cleaning");
let manifest_path_str;
let mut args = Vec::new();
if let Some(manifest_path) = opt.manifest_path.as_ref() {
args.push("--manifest-path");
manifest_path_str = manifest_path.to_string_lossy();
args.push(&manifest_path_str);
};
let status = Command::new("cargo").arg("clean").args(args).status()?;
if !status.success() {
bail!("cargo failed with error {:?}", status);
}
}
let device_build = Build {
device: true,
example: self.example.clone(),
release: true,
run: false,
};
device_build.execute(opt, crank_manifest)?;
let sim_build = Build {
device: false,
example: self.example.clone(),
release: true,
run: false,
};
let (target_dir, game_title) = sim_build.execute(opt, crank_manifest)?;
let parent = target_dir.parent().expect("parent");
let target_archive = parent.join(format!("{}.pdx.zip", game_title));
info!("target_dir {:#?}", target_dir);
info!("target_archive {:#?}", target_archive);
fs::remove_dir_all(&target_archive).unwrap_or_else(|_err| ());
let options = FileOptions::default().compression_method(CompressionMethod::Deflated);
zip_create_from_directory_with_options(&target_archive, &target_dir, options)?;
#[cfg(windows)]
if self.reveal {
let _ = Command::new("Explorer")
.arg(format!("/Select,{}", target_archive.to_string_lossy()))
.status()?;
}
#[cfg(target_os = "macos")]
if self.reveal {
let _ = Command::new("open")
.arg("-R")
.arg(target_archive)
.status()?;
}
#[cfg(target_os = "linux")]
if self.reveal {
let _ = Command::new("xdg-open").arg(parent).status()?;
}
Ok(())
}
}
#[derive(StructOpt, Debug)]
#[structopt(name = "crank")]
struct Opt {
#[structopt(short, long)]
verbose: bool,
/// Path to Cargo.toml
#[structopt(long, global = true)]
manifest_path: Option<PathBuf>,
#[structopt(subcommand)]
cmd: CrankCommand,
}
fn main() -> Result<(), Error> {
let opt = Opt::from_args();
if opt.verbose {
env::set_var("RUST_LOG", "info");
}
pretty_env_logger::init();
info!("starting");
let crank_manifest = load_manifest(&opt.manifest_path)?;
info!("manifest = {:#?}", crank_manifest);
match &opt.cmd {
CrankCommand::Build(build) => {
build.execute(&opt, &crank_manifest)?;
}
CrankCommand::Run(build) => {
let build_and_run = Build {
run: true,
..build.clone()
};
build_and_run.execute(&opt, &crank_manifest)?;
}
CrankCommand::Package(package) => {
package.execute(&opt, &crank_manifest)?;
}
}
Ok(())
}