99 lines
2.7 KiB
Rust
99 lines
2.7 KiB
Rust
use std::io::{self, BufReader, BufWriter, Read, Write};
|
|
use std::path::Path;
|
|
use std::{env, fs::OpenOptions, process::ExitCode};
|
|
|
|
mod cfg;
|
|
mod cli;
|
|
mod constants;
|
|
mod generate;
|
|
|
|
fn main() -> ExitCode {
|
|
let args: Vec<String> = env::args().collect();
|
|
|
|
if args.len() < 2 {
|
|
eprintln!("Not enough arguments, see the --help option");
|
|
return ExitCode::FAILURE;
|
|
}
|
|
|
|
if args.contains(&String::from("--help")) || args.contains(&String::from("-h")) {
|
|
println!("{}", constants::BIN2HPP_HELP_TEXT);
|
|
return ExitCode::SUCCESS;
|
|
}
|
|
|
|
if args.contains(&String::from("--version")) || args.contains(&String::from("-v")) {
|
|
println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
|
|
return ExitCode::SUCCESS;
|
|
}
|
|
|
|
let args = match cli::parse_cli_args(&args) {
|
|
Ok(args) => args,
|
|
Err(e) => {
|
|
eprintln!("Failed to parse command line arguments: {}", e);
|
|
return ExitCode::FAILURE;
|
|
}
|
|
};
|
|
let cfg = match cfg::parse_config_from_args(&args) {
|
|
Ok(cfg) => cfg,
|
|
Err(e) => {
|
|
eprintln!("Invalid configuration specified: {}", e);
|
|
return ExitCode::FAILURE;
|
|
}
|
|
};
|
|
|
|
let in_data = match read_input_file(&cfg.input_file_path) {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
eprintln!("Failed to read input file: {}", e);
|
|
return ExitCode::FAILURE;
|
|
}
|
|
};
|
|
let header_src = match generate::header(&cfg, &in_data) {
|
|
Ok(s) => s,
|
|
Err(e) => {
|
|
eprintln!("Failed to generate header source file: {}", e);
|
|
return ExitCode::FAILURE;
|
|
}
|
|
};
|
|
|
|
match write_output_file(header_src.as_bytes(), cfg.overwrite, &cfg.output_file_path) {
|
|
Ok(_) => (),
|
|
Err(e) => {
|
|
eprintln!("Failed to write output file: {}", e);
|
|
return ExitCode::FAILURE;
|
|
}
|
|
};
|
|
|
|
return ExitCode::SUCCESS;
|
|
}
|
|
|
|
fn read_input_file(input_path: &Path) -> Result<Vec<u8>, io::Error> {
|
|
let in_file = OpenOptions::new()
|
|
.read(true)
|
|
.write(false)
|
|
.open(input_path)?;
|
|
|
|
let file_size = in_file.metadata()?.len();
|
|
let mut in_data: Vec<u8> = Vec::with_capacity(file_size as usize);
|
|
let mut reader = BufReader::new(in_file);
|
|
|
|
let _ = reader.read_to_end(&mut in_data)?;
|
|
|
|
Ok(in_data)
|
|
}
|
|
|
|
fn write_output_file(buf: &[u8], overwrite: bool, output_path: &Path) -> Result<(), io::Error> {
|
|
if overwrite {
|
|
let _ = std::fs::remove_file(output_path);
|
|
}
|
|
let out_file = OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(output_path)?;
|
|
|
|
let mut writer = BufWriter::new(out_file);
|
|
|
|
writer.write_all(buf)?;
|
|
|
|
Ok(())
|
|
}
|