cargo-wiiu 0.2.1

Cargo extension to easily work with Nintendo Wii U binaries.
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
//! cargo wiiu
//!
//! Note
//!
//! unwrap() must be used in places that can not be fixed by the user (e.g. Cursor::write on a Vec). Result::context() by anyhow should be used in places where the user can fix the error (e.g. reading missing file).

mod elf;
mod rpl;
mod upload;
mod wuhb;

use anyhow::Context;
use clap::{Args, Parser, Subcommand};
use std::{
    fs,
    net::Ipv4Addr,
    path::{Path, PathBuf},
    process::Command,
};

#[derive(Parser)]
#[command(name = "cargo", bin_name = "cargo")]
enum Cargo {
    #[command(name = "wiiu")]
    Input(Input),
}

#[derive(Args)]
#[command(author, version, about)]
struct Input {
    #[command(subcommand)]
    pub cmd: Commands,
}

fn extension<const N: usize>(
    exts: [&'static str; N],
) -> impl Fn(&str) -> Result<PathBuf, String> + Clone + Send + Sync + 'static {
    move |s| {
        let path = PathBuf::from(s);
        match path.extension() {
            Some(e) if exts.iter().any(|&ext| e == ext) => Ok(path),
            _ => {
                let listed = exts.join(", ");
                Err(format!(
                    "'{s}' does not have a valid extension (expected: {listed})"
                ))
            }
        }
    }
}

#[derive(Args, Debug, Clone)]
struct WuhbConfig {
    /// Display name of the app in the Home Menu
    #[arg(long, default_value = "Rust App")]
    long_name: String,
    /// ???
    #[arg(long, default_value = "Rust App")]
    short_name: String,
    /// Icon of the app in the Home Menu
    #[arg(long, value_parser = extension(["png", "tga"]))]
    icon: Option<PathBuf>,
    /// Splash screen on TV
    #[arg(long, value_parser = extension(["png", "tga"]))]
    tv_image: Option<PathBuf>,
    /// Splash screen on DRC
    #[arg(long, value_parser = extension(["png", "tga"]))]
    drc_image: Option<PathBuf>,
    /// Path to the content directory
    #[arg(long)]
    content: Option<PathBuf>,
}

impl Default for WuhbConfig {
    fn default() -> Self {
        Self {
            long_name: String::from("Rust App"),
            short_name: String::from("Rust App"),
            icon: None,
            tv_image: None,
            drc_image: None,
            content: None,
        }
    }
}

impl WuhbConfig {
    fn read_manifest_metadata(&mut self) -> anyhow::Result<()> {
        let metadata = cargo_metadata::MetadataCommand::new()
            .current_dir(std::env::current_dir().unwrap())
            .no_deps()
            .exec();

        match metadata {
            Ok(metadata) => match metadata.root_package().unwrap().metadata.get("wuhb") {
                Some(wuhb) => {
                    if self.long_name == "Rust App" {
                        if let Some(manifest_val) = wuhb.get("long-name") {
                            self.long_name = manifest_val
                                .as_str()
                                .context("`long-name` manifest entry must be a string")
                                .map(String::from)?;
                        }
                    }

                    if self.short_name == "Rust App" {
                        if let Some(manifest_val) = wuhb.get("short-name") {
                            self.short_name = manifest_val
                                .as_str()
                                .context("`short-name` manifest entry must be a string")
                                .map(String::from)?;
                        }
                    }

                    self.icon = wuhb
                        .get("icon")
                        .map(|v| {
                            v.as_str()
                                .context("`icon` manifest entry must be a string")
                                .map(PathBuf::from) // Removed semicolon here
                        })
                        .transpose()?;

                    self.tv_image = wuhb
                        .get("tv-image")
                        .map(|v| {
                            v.as_str()
                                .context("`tv-image` manifest entry must be a string")
                                .map(PathBuf::from) // Removed semicolon here
                        })
                        .transpose()?;

                    self.drc_image = wuhb
                        .get("drc-image")
                        .map(|v| {
                            v.as_str()
                                .context("`drc-image` manifest entry must be a string")
                                .map(PathBuf::from) // Removed semicolon here
                        })
                        .transpose()?;

                    self.content = wuhb
                        .get("content")
                        .map(|v| {
                            v.as_str()
                                .context("`content` manifest entry must be a string")
                                .map(PathBuf::from) // Removed semicolon here
                        })
                        .transpose()?;
                }
                None => {
                    log::info!("No \"wuhb\" section in manifest found");
                }
            },
            Err(e) => {
                log::warn!("Executed outside of a Rust crate. Using default values.");
                log::info!("Error: {e}");
            }
        }

        Ok(())
    }
}

#[derive(Subcommand)]
enum Commands {
    /// Build a project. Same as calling `cargo build` followed by `cargo wiiu rpx`. WUHB file will be created if configured in manifest.
    #[command(trailing_var_arg = true, allow_hyphen_values = true)]
    Build {
        /// Arguments given directly to `cargo build`
        cargo_args: Vec<String>,
    },
    /// Create a new project. Alias for `cargo new foo && cd foo && cargo wiiu init`.
    New { path: PathBuf },
    /// Initializes an existing project
    Init { path: PathBuf },
    /// Build a project and run it in Cemu. When not specified, the `CEMU` environment variable is used.
    #[command(trailing_var_arg = true, allow_hyphen_values = true)]
    Run {
        #[arg(long)]
        cemu: Option<PathBuf>,
        /// Arguments given directly to `cargo build`
        cargo_args: Vec<String>,
    },
    /// Upload a binary to a console via the wiiload-plugin.
    #[command(trailing_var_arg = true, allow_hyphen_values = true)]
    Upload {
        /// IP address of the console
        #[arg(long)]
        ip: Ipv4Addr,
        /// Binary to upload
        #[arg(value_parser = extension(["rpx", "wuhb"]))]
        binary: Option<PathBuf>,
        /// Arguments given directly to `cargo build` if an explicit binary is not provided
        cargo_args: Vec<String>,
    },
    /// Convert ELF to RPX (executable)
    Rpx {
        /// Path to the elf binary
        #[arg(value_parser = extension(["elf"]))]
        elf: PathBuf,
        /// Path to the resulting rpx binary. Defaults to elf path with ".rpx" extension.
        #[arg(value_parser = extension(["rpx"]))]
        rpx: Option<PathBuf>,
    },
    /// Convert ELF to RPL (library)
    Rpl {
        /// Path to the elf binary
        #[arg(value_parser = extension(["elf"]))]
        elf: PathBuf,
        /// Path to the resulting rpl binary. Defaults to elf path with ".rpl" extension.
        #[arg(value_parser = extension(["rpl"]))]
        rpl: Option<PathBuf>,
    },
    Wuhb {
        /// Path to the binary (elf / rpx)
        #[arg(value_parser = extension(["rpx"]))]
        rpx: PathBuf,
        /// Path to the resulting WUHB archive. Defaults to rpx path with ".wuhb" extension.
        #[arg(value_parser = extension(["wuhb"]))]
        wuhb: Option<PathBuf>,
        /// Configuration flags for the WUHB archive
        #[command(flatten)]
        config: WuhbConfig,
    },
}

fn main() -> anyhow::Result<()> {
    env_logger::Builder::default()
        .format_timestamp(None)
        .format_module_path(false)
        .format_target(false)
        .init();

    let Cargo::Input(input) = Cargo::parse();

    match input.cmd {
        Commands::Build { cargo_args } => {
            build(&cargo_args)?;
        }
        Commands::New { path } => {
            new(&path)?;
            init(&path)?;
        }
        Commands::Init { path } => init(&path)?,
        Commands::Run { cemu, cargo_args } => {
            let binary = build(&cargo_args)?;

            let cemu = cemu.unwrap_or_else(|| {
                PathBuf::from(
                    std::env::var("CEMU")
                        .expect("Either `--cemu <PATH>` or env var `CEMU` must be specified"),
                )
            });

            let output = Command::new(cemu)
                .arg("-g")
                .arg(binary.canonicalize()?)
                .output()?;

            if !output.status.success() {
                eprint!("{}", String::from_utf8_lossy(&output.stdout));
                eprint!("{}", String::from_utf8_lossy(&output.stderr));
            }
        }
        Commands::Upload {
            ip,
            binary,
            cargo_args,
        } => {
            log::info!("Read input file");

            let path = match binary {
                Some(path) => path,
                None => build(&cargo_args).unwrap(),
            };

            let data =
                fs::read(&path).context(format!("Failed to read file: {}", path.display()))?;

            upload::upload_binary(data, ip)?;
        }
        Commands::Rpx { elf, rpx } => {
            let rpx = rpx.unwrap_or_else(|| elf.with_extension("rpx"));

            log::info!("Read input file");
            let input =
                fs::read(&elf).context(format!("Failed to read file: {}", elf.display()))?;

            let output = rpl::from_elf(input, false);

            log::info!("Write output file");
            fs::write(&rpx, output).context(format!("Failed to write file: {}", rpx.display()))?;
        }
        Commands::Rpl { elf, rpl } => {
            let rpl = rpl.unwrap_or_else(|| elf.with_extension("rpl"));

            log::info!("Read input file");
            let input =
                fs::read(&elf).context(format!("Failed to read file: {}", elf.display()))?;

            let output = rpl::from_elf(input, true);

            log::info!("Write output file");
            fs::write(&rpl, output).context(format!("Failed to write file: {}", rpl.display()))?;
        }
        Commands::Wuhb {
            rpx,
            wuhb,
            mut config,
        } => {
            let wuhb = wuhb.unwrap_or_else(|| rpx.with_extension("wuhb"));

            log::info!("Read input file");
            let input =
                fs::read(&rpx).context(format!("Failed to read file: {}", rpx.display()))?;

            log::info!("Read manifest file");
            config.read_manifest_metadata()?;

            let output = wuhb::from_rpx(input, config)?;

            log::info!("Write output file");
            fs::write(&wuhb, output)
                .context(format!("Failed to write file: {}", wuhb.display()))?;
        }
    }

    Ok(())
}

fn new(path: impl AsRef<Path>) -> anyhow::Result<()> {
    Command::new("cargo")
        .arg("new")
        .args(path.as_ref())
        .status()
        .context("Failed to execute cargo new")?;

    Ok(())
}

fn init(path: impl AsRef<Path>) -> anyhow::Result<()> {
    let path = path.as_ref();

    let cafe = path.join(".cafe");
    if !cafe.is_dir() {
        log::info!("Add `.cafe` submodule");
        Command::new("git")
            .current_dir(path)
            .args([
                "submodule",
                "add",
                "https://github.com/rust-wiiu/cafe-target-spec",
                ".cafe",
            ])
            .status()
            .context("Failed to initialize `.cafe` submodule. Make sure you are in a git repository or clone the files manually.")?;

        Command::new("git")
            .current_dir(path)
            .args(["submodule", "update", "--init", "--recursive", ".cafe"])
            .status()
            .context("Failed to init `.cafe` submodule")?;
    } else {
        log::warn!("{} folder already exists. Do nothing.", cafe.display());
    }

    let toolchain = path.join("rust-toolchain.toml");
    if !toolchain.is_file() {
        log::info!("Create `rust-toolchain.toml`");
        fs::write(&toolchain, include_str!("templates/rust-toolchain.toml"))
            .context("Failed to create `rust-toolchain.toml`")?;
    } else {
        log::warn!("{} already exists. Do nothing.", toolchain.display());
    }

    let cargo = path.join(".cargo");
    let config = cargo.join("config.toml");
    if !config.is_file() {
        log::info!("Create `.cargo/config.toml`");

        if !cargo.is_dir() {
            fs::create_dir(&cargo).context("Failed to create `.cargo` directory")?;
        }

        fs::write(&config, include_str!("templates/cargo-config.toml"))
            .context("Failed to create `.cargo/config.toml`")?;
    } else {
        log::warn!("{} already exists. Do nothing.", config.display());
    }

    Ok(())
}

fn build(args: &Vec<String>) -> anyhow::Result<PathBuf> {
    Command::new("cargo")
        .arg("build")
        .args(args)
        .status()
        .context("Failed to build")?;

    let target_dir = cargo_metadata::MetadataCommand::new()
        .no_deps()
        .exec()
        .unwrap()
        .target_directory
        .to_string();

    let profile = if let Some(pos) = args.iter().position(|x| x == "--profile") {
        args.get(pos + 1).map(|s| s.as_str()).unwrap_or("debug")
    } else if args.iter().any(|x| x == "--release") {
        "release"
    } else {
        "debug"
    };

    let name = cargo_metadata::MetadataCommand::new()
        .no_deps()
        .exec()
        .unwrap()
        .root_package()
        .unwrap()
        .name
        .to_string();

    let binary = PathBuf::from(target_dir)
        .join("powerpc-cafe-nintendo")
        .join(profile)
        .join(name);

    let mut final_binary;

    {
        let input = fs::read(binary.with_extension("elf")).context("Failed to read elf file")?;

        let output = rpl::from_elf(input, false);

        final_binary = binary.with_extension("rpx");

        fs::write(&final_binary, output).context("Failed to write rpx file")?;
    }

    // check if [package.metadata.wuhb] is present in Cargo.toml
    if cargo_metadata::MetadataCommand::new()
        .no_deps()
        .exec()
        .context("Failed to read manifest")?
        .root_package()
        .and_then(|pkg| pkg.metadata.get("wuhb"))
        .is_some()
    {
        let mut config = WuhbConfig::default();
        config.read_manifest_metadata()?;

        let input = fs::read(&binary.with_extension("rpx")).context("Failed to read rpx file")?;

        let output = wuhb::from_rpx(input, config)?;

        final_binary = binary.with_extension("wuhb");
        fs::write(&final_binary, output).context("Failed to write rpx file")?;
    }

    Ok(final_binary)
}