From b98c2ef50ec96d581aaef31d4360740575dbba22 Mon Sep 17 00:00:00 2001 From: Filipe Rodrigues Date: Fri, 1 May 2020 11:32:23 +0100 Subject: [PATCH] Started using a formatter. --- rustfmt.toml | 18 ++++++++++ src/extractor/cli.rs | 67 +++++++++++++++------------------- src/extractor/main.rs | 81 ++++++++++++++++++------------------------ src/extractor/panic.rs | 12 +++---- src/patcher/cli.rs | 52 ++++++++++++--------------- src/patcher/main.rs | 69 ++++++++++++++--------------------- src/patcher/panic.rs | 12 +++---- 7 files changed, 142 insertions(+), 169 deletions(-) create mode 100644 rustfmt.toml diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..844da63 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,18 @@ +# We're fine with unstable features +unstable_features = true + + + +binop_separator = "Back" +hard_tabs = true +condense_wildcard_suffixes = true +match_block_trailing_comma = true +newline_style = "Unix" +reorder_impl_items = true +overflow_delimited_expr = true +use_field_init_shorthand = true +enum_discrim_align_threshold = 100 +fn_args_layout = "Compressed" +merge_derives = false +merge_imports = true +max_width = 150 diff --git a/src/extractor/cli.rs b/src/extractor/cli.rs index 24b38b4..9f3fe38 100644 --- a/src/extractor/cli.rs +++ b/src/extractor/cli.rs @@ -4,69 +4,60 @@ use std::path::{Path, PathBuf}; // Clap -use clap::{Arg as ClapArg, App as ClapApp}; +use clap::{App as ClapApp, Arg as ClapArg}; // Errors use err_panic::ErrorExtPanic; +/// Data from the command line +#[derive(PartialEq, Clone, Debug)] +pub struct CliData { + /// The game file + pub game_file_path: PathBuf, -/// All of the data received form the command line -/// -/// # Public fields -/// All fields are public as this type has no invariants. -pub struct CliData -{ - /// The input filename - pub input_filename: PathBuf, - - /// The output directory + /// The ouput directory pub output_dir: PathBuf, } -impl CliData -{ +impl CliData { /// Constructs all of the cli data given and returns it - pub fn new() -> Self - { + pub fn new() -> Self { // Get all matches from cli let matches = ClapApp::new("Dcb Extractor") .version("0.0") .author("Filipe [...] <[...]@gmail.com>") .about("Extracts all data from a Digimon Digital Card Battle `.bin` game file") - .arg( ClapArg::with_name("INPUT") - .help("Sets the input game file to use") - .required(true) - .index(1) + .arg( + ClapArg::with_name("GAME_FILE") + .help("Sets the input game file to use") + .required(true) + .index(1), ) - .arg( ClapArg::with_name("OUTPUT") - .help("Sets the output directory to use") - .short("o") - .long("output") - .takes_value(true) - .required(false) + .arg( + ClapArg::with_name("OUTPUT") + .help("Sets the output directory to use") + .short("o") + .long("output") + .takes_value(true) + .required(false), ) .get_matches(); - + // Get the input filename // Note: required - let input_filename = matches.value_of("INPUT") + let game_file_path = matches + .value_of("GAME_FILE") .map(Path::new) .map(Path::to_path_buf) - .panic_msg("Unable to get required argument `INPUT`"); - + .panic_msg("Unable to get required argument `GAME_FILE`"); + // Try to get the output let output_dir = match matches.value_of("OUTPUT") { Some(output) => PathBuf::from(output), - None => input_filename - .parent() - .unwrap_or_else(|| Path::new(".")) - .to_path_buf() + None => game_file_path.parent().unwrap_or_else(|| Path::new(".")).to_path_buf(), }; - + // Return the cli data - Self { - input_filename, - output_dir, - } + Self { game_file_path, output_dir } } } diff --git a/src/extractor/main.rs b/src/extractor/main.rs index dbb2f70..6e5f0c3 100644 --- a/src/extractor/main.rs +++ b/src/extractor/main.rs @@ -1,31 +1,22 @@ //! Data extractor -//! +//! //! # Details //! Extracts data from the game file to several other files, that can be //! edited and then used by `Patcher` to modify the game file. -//! +//! //! # Syntax //! The executable may be called as `./extractor {-o }` -//! +//! //! Use the command `./extractor --help` for more information. -//! +//! //! # Data extracted //! Currently only the following is extracted: //! - Card table // Features -#![feature( - box_syntax, - backtrace, - panic_info_message, -)] - +#![feature(box_syntax, backtrace, panic_info_message)] // Lints -#![warn( - clippy::restriction, - clippy::pedantic, - clippy::nursery, -)] +#![warn(clippy::restriction, clippy::pedantic, clippy::nursery)] #![allow( clippy::implicit_return, // We prefer implicit returns where possible clippy::module_name_repetitions, // This happens often due to separating things into modules finely @@ -43,64 +34,62 @@ mod panic; use cli::CliData; // Dcb -use dcb::{ - GameFile, - game::card::Table as CardTable, -}; +use dcb::{game::card::Table as CardTable, GameFile}; // Errors +use err_backtrace::ErrBacktraceExt; use err_ext::ResultExt; use err_panic::ErrorExtPanic; -use err_backtrace::ErrBacktraceExt; fn main() { // Initialize the logger and set the panic handler init_logger(); std::panic::set_hook(box panic::log_handler); - + // Get all data from cli - let CliData { input_filename, output_dir } = CliData::new(); - + let CliData { game_file_path, output_dir } = CliData::new(); + // Open the game file - let input_file = std::fs::File::open(&input_filename) - .panic_err_msg("Unable to open input file"); - let mut game_file = GameFile::from_reader(input_file) - .panic_err_msg("Unable to parse input file as dcb"); - + let input_file = std::fs::File::open(&game_file_path).panic_err_msg("Unable to open input file"); + let mut game_file = GameFile::from_reader(input_file).panic_err_msg("Unable to parse input file as dcb"); + // Get the cards table - let cards_table = CardTable::deserialize(&mut game_file) - .panic_err_msg("Unable to deserialize cards table from game file"); - let cards_table_yaml = serde_yaml::to_string(&cards_table) - .panic_err_msg("Unable to serialize cards table to yaml"); - + let cards_table = CardTable::deserialize(&mut game_file).panic_err_msg("Unable to deserialize cards table from game file"); + let cards_table_yaml = serde_yaml::to_string(&cards_table).panic_err_msg("Unable to serialize cards table to yaml"); + log::info!("Extracted {} cards", cards_table.card_count()); - + // And output everything to the files let cards_table_output_filename = output_dir.join("cards.yaml"); std::fs::write(&cards_table_output_filename, cards_table_yaml) - .map_err(|err| log::warn!("Unable to write output file {}:\n{}", cards_table_output_filename.display(), err.err_backtrace() )) + .map_err(|err| { + log::warn!( + "Unable to write output file {}:\n{}", + cards_table_output_filename.display(), + err.err_backtrace() + ) + }) .ignore(); } /// Initializes the global logger fn init_logger() { - use simplelog::{CombinedLogger, SharedLogger, TermLogger, WriteLogger, Config, TerminalMode}; use log::LevelFilter::{Info, Trace}; + use simplelog::{CombinedLogger, Config, SharedLogger, TermLogger, TerminalMode, WriteLogger}; use std::convert::identity; /// The type of logger required to pass to `CombinedLogger::init` type BoxedLogger = Box; - + // All loggers to try and initialize - let loggers: Vec< Option > = vec![ - TermLogger ::new(Info, Config::default(), TerminalMode::Mixed) - .map(|logger| BoxedLogger::from(logger)), - std::fs::File::create("latest.log").ok() + let loggers: Vec> = vec![ + TermLogger::new(Info, Config::default(), TerminalMode::Mixed).map(|logger| BoxedLogger::from(logger)), + std::fs::File::create("latest.log") + .ok() .map(|file| WriteLogger::new(Trace, Config::default(), file)) - .map(|logger| BoxedLogger::from(logger)) + .map(|logger| BoxedLogger::from(logger)), ]; - + // Filter all logger that actually work and initialize them - CombinedLogger::init( - loggers.into_iter().filter_map(identity).collect() - ).ignore_with_err(|_| log::warn!("Logger was already initialized at the start of the program")); + CombinedLogger::init(loggers.into_iter().filter_map(identity).collect()) + .ignore_with_err(|_| log::warn!("Logger was already initialized at the start of the program")); } diff --git a/src/extractor/panic.rs b/src/extractor/panic.rs index 595c8ef..10657ef 100644 --- a/src/extractor/panic.rs +++ b/src/extractor/panic.rs @@ -2,8 +2,8 @@ // Std use std::{ - error::Error, backtrace::{Backtrace, BacktraceStatus}, + error::Error, }; // Error backtrace use err_backtrace::ErrBacktraceExt; @@ -12,15 +12,15 @@ use err_backtrace::ErrBacktraceExt; pub fn log_handler(info: &std::panic::PanicInfo) { // Log that this thread has panicked log::error!("Thread \"{}\" panicked", std::thread::current().name().unwrap_or("[Unknown]")); - + // Log any message that came with the panic - log::info!("Panic message: {}", info.message().unwrap_or( &format_args!("None") )); - + log::info!("Panic message: {}", info.message().unwrap_or(&format_args!("None"))); + // Print an error backtrace if we found any - if let Some(err) = info.payload().downcast_ref::< Box >() { + if let Some(err) = info.payload().downcast_ref::>() { log::info!("Error backtrace:\n{}", err.err_backtrace()); } - + // And print a backtrace of where this panic occured. let backtrace = Backtrace::force_capture(); if backtrace.status() == BacktraceStatus::Captured { diff --git a/src/patcher/cli.rs b/src/patcher/cli.rs index 85e4899..630dddc 100644 --- a/src/patcher/cli.rs +++ b/src/patcher/cli.rs @@ -4,66 +4,58 @@ use std::path::{Path, PathBuf}; // Clap -use clap::{Arg as ClapArg, App as ClapApp}; +use clap::{App as ClapApp, Arg as ClapArg}; // Errors use err_panic::ErrorExtPanic; - /// Data from the command line #[derive(PartialEq, Clone, Debug)] -pub struct CliData -{ +pub struct CliData { /// The game file pub game_file_path: PathBuf, - + /// The input directory pub input_dir: PathBuf, } -impl CliData -{ +impl CliData { /// Constructs all of the cli data given and returns it - pub fn new() -> Self - { + pub fn new() -> Self { // Get all matches from cli let matches = ClapApp::new("Dcb Patcher") .version("0.0") .author("Filipe [...] <[...]@gmail.com>") .about("Patches data to a Digimon Digital Card Battle `.bin` game file") - .arg( ClapArg::with_name("GAME_FILE") - .help("Sets the game file to use") - .required(true) - .index(1) - ) - .arg( ClapArg::with_name("INPUT") - .help("Sets the output directory to use") - .short("i") - .long("input") - .index(2) - .takes_value(true) - .required(true) + .arg(ClapArg::with_name("GAME_FILE").help("Sets the game file to use").required(true).index(1)) + .arg( + ClapArg::with_name("INPUT") + .help("Sets the output directory to use") + .short("i") + .long("input") + .index(2) + .takes_value(true) + .required(true), ) .get_matches(); - + // Get the ouput filename // Note: required - let game_file_path = matches.value_of("GAME_FILE") + let game_file_path = matches + .value_of("GAME_FILE") .map(Path::new) .map(Path::to_path_buf) .panic_msg("Unable to get required argument `GAME_FILE`"); - + // Get the input dir // Note: required - let input_dir = matches.value_of("INPUT") + let input_dir = matches + .value_of("INPUT") .map(Path::new) .map(Path::to_path_buf) .panic_msg("Unable to get required argument `INPUT`"); - + // Return the cli data - Self { - game_file_path, - input_dir, - } + Self { game_file_path, input_dir } } } diff --git a/src/patcher/main.rs b/src/patcher/main.rs index 7ae66b3..f247867 100644 --- a/src/patcher/main.rs +++ b/src/patcher/main.rs @@ -1,30 +1,21 @@ //! Data patches -//! +//! //! # Details //! Patches data to the game file from several other files. -//! +//! //! # Syntax //! The executable may be called as `./patcher ` -//! +//! //! Use the command `./patcher --help` for more information. -//! +//! //! # Data patched //! Currently only the following is patched: //! - Card table // Features -#![feature( - box_syntax, - backtrace, - panic_info_message, -)] - +#![feature(box_syntax, backtrace, panic_info_message)] // Lints -#![warn( - clippy::restriction, - clippy::pedantic, - clippy::nursery, -)] +#![warn(clippy::restriction, clippy::pedantic, clippy::nursery)] #![allow( clippy::implicit_return, // We prefer implicit returns where possible clippy::module_name_repetitions, // This happens often due to separating things into modules finely @@ -42,10 +33,7 @@ mod panic; use cli::CliData; // Dcb -use dcb::{ - GameFile, - game::card::Table as CardTable, -}; +use dcb::{game::card::Table as CardTable, GameFile}; // Errors use err_ext::ResultExt; @@ -55,49 +43,44 @@ fn main() { // Initialize the logger and set the panic handler init_logger(); std::panic::set_hook(box panic::log_handler); - + // Get all data from cli let CliData { game_file_path, input_dir } = CliData::new(); - + // Load the card table - let cards_table_file = std::fs::File::open( input_dir.join("cards.yaml") ) - .panic_err_msg("Unable to open `cards.yaml`"); - let cards_table: CardTable = serde_yaml::from_reader( cards_table_file ) - .panic_err_msg("Unable to parse `cards.yaml`"); - + let cards_table_file = std::fs::File::open(input_dir.join("cards.yaml")).panic_err_msg("Unable to open `cards.yaml`"); + let cards_table: CardTable = serde_yaml::from_reader(cards_table_file).panic_err_msg("Unable to parse `cards.yaml`"); + // Open the game file let game_file = std::fs::OpenOptions::new() .write(true) .truncate(false) - .open( game_file_path ) + .open(game_file_path) .panic_err_msg("Unable to open game file"); - let mut game_file = GameFile::from_reader( game_file ) - .panic_err_msg("Unable to initialize game file"); - + let mut game_file = GameFile::from_reader(game_file).panic_err_msg("Unable to initialize game file"); + // And write the cards table - cards_table.serialize(&mut game_file) - .panic_err_msg("Unable to serialize cards table"); + cards_table.serialize(&mut game_file).panic_err_msg("Unable to serialize cards table"); } /// Initializes the global logger fn init_logger() { - use simplelog::{CombinedLogger, SharedLogger, TermLogger, WriteLogger, Config, TerminalMode}; use log::LevelFilter::{Info, Trace}; + use simplelog::{CombinedLogger, Config, SharedLogger, TermLogger, TerminalMode, WriteLogger}; use std::convert::identity; /// The type of logger required to pass to `CombinedLogger::init` type BoxedLogger = Box; - + // All loggers to try and initialize - let loggers: Vec< Option > = vec![ - TermLogger ::new(Info, Config::default(), TerminalMode::Mixed) - .map(|logger| BoxedLogger::from(logger)), - std::fs::File::create("latest.log").ok() + let loggers: Vec> = vec![ + TermLogger::new(Info, Config::default(), TerminalMode::Mixed).map(|logger| BoxedLogger::from(logger)), + std::fs::File::create("latest.log") + .ok() .map(|file| WriteLogger::new(Trace, Config::default(), file)) - .map(|logger| BoxedLogger::from(logger)) + .map(|logger| BoxedLogger::from(logger)), ]; - + // Filter all logger that actually work and initialize them - CombinedLogger::init( - loggers.into_iter().filter_map(identity).collect() - ).ignore_with_err(|_| log::warn!("Logger was already initialized at the start of the program")); + CombinedLogger::init(loggers.into_iter().filter_map(identity).collect()) + .ignore_with_err(|_| log::warn!("Logger was already initialized at the start of the program")); } diff --git a/src/patcher/panic.rs b/src/patcher/panic.rs index 595c8ef..10657ef 100644 --- a/src/patcher/panic.rs +++ b/src/patcher/panic.rs @@ -2,8 +2,8 @@ // Std use std::{ - error::Error, backtrace::{Backtrace, BacktraceStatus}, + error::Error, }; // Error backtrace use err_backtrace::ErrBacktraceExt; @@ -12,15 +12,15 @@ use err_backtrace::ErrBacktraceExt; pub fn log_handler(info: &std::panic::PanicInfo) { // Log that this thread has panicked log::error!("Thread \"{}\" panicked", std::thread::current().name().unwrap_or("[Unknown]")); - + // Log any message that came with the panic - log::info!("Panic message: {}", info.message().unwrap_or( &format_args!("None") )); - + log::info!("Panic message: {}", info.message().unwrap_or(&format_args!("None"))); + // Print an error backtrace if we found any - if let Some(err) = info.payload().downcast_ref::< Box >() { + if let Some(err) = info.payload().downcast_ref::>() { log::info!("Error backtrace:\n{}", err.err_backtrace()); } - + // And print a backtrace of where this panic occured. let backtrace = Backtrace::force_capture(); if backtrace.status() == BacktraceStatus::Captured {