From cf6f4f9e1ea6246e3c5aa2434aa748fec537d882 Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Sat, 8 Dec 2018 08:00:43 +0100 Subject: [PATCH] Better usage of clap. --- 2018/Cargo.toml | 1 + 2018/src/main.rs | 39 ++++++++++++++++++--------------------- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/2018/Cargo.toml b/2018/Cargo.toml index 42d2855..c86bbc0 100644 --- a/2018/Cargo.toml +++ b/2018/Cargo.toml @@ -2,6 +2,7 @@ name = "aoc-2018" version = "0.1.0" authors = ["Bert Peters "] +description = "Implementation of the problems of Advent of Code 2018" [dependencies] clap = "2.32" diff --git a/2018/src/main.rs b/2018/src/main.rs index de8d0a7..9f26c50 100644 --- a/2018/src/main.rs +++ b/2018/src/main.rs @@ -1,5 +1,5 @@ extern crate chrono; -extern crate clap; +#[macro_use] extern crate clap; extern crate aoc_2018; use std::fs; @@ -8,27 +8,24 @@ use std::time::Instant; use aoc_2018::*; -use clap::{App, Arg}; +use clap::Arg; -fn get_impl(day: &str) -> Box { - match day.parse() { - Ok(1) => Box::new(day01::Day01::new()), - Ok(2) => Box::new(day02::Day02::new()), - Ok(3) => Box::new(day03::Day03::new()), - Ok(4) => Box::new(day04::Day04::new()), - Ok(5) => Box::new(day05::Day05::new()), - Ok(6) => Box::new(day06::Day06::new()), - Ok(7) => Box::new(day07::Day07::new()), - Ok(8) => Box::new(day08::Day08::new()), - Ok(val) => panic!("Unimplemented day {}", val), - _ => panic!("Invalid number"), +fn get_impl(day: u32) -> Box { + match day { + 1 => Box::new(day01::Day01::new()), + 2 => Box::new(day02::Day02::new()), + 3 => Box::new(day03::Day03::new()), + 4 => Box::new(day04::Day04::new()), + 5 => Box::new(day05::Day05::new()), + 6 => Box::new(day06::Day06::new()), + 7 => Box::new(day07::Day07::new()), + 8 => Box::new(day08::Day08::new()), + val => panic!("Unimplemented day {}", val), } } fn main() { - let matches = App::new("Advent of Code") - .version("2018") - .author("Bert Peters ") + let matches = app_from_crate!() .arg(Arg::with_name("day") .value_name("DAY") .help("Number of the day to execute") @@ -36,7 +33,7 @@ fn main() { .takes_value(true)) .arg(Arg::with_name("part2") .short("2") - .help("Whether to run part 2") + .help("Run part 2 instead of part 1") .long("part2")) .arg(Arg::with_name("input") .short("i") @@ -49,7 +46,7 @@ fn main() { .help("Print the time for the result")) .get_matches(); - let mut implementation = get_impl(matches.value_of("day").unwrap()); + let mut implementation = get_impl(value_t_or_exit!(matches, "day", u32)); let mut data: Box = match matches.value_of("input") { Some(filename) => { Box::new(fs::File::open(filename).unwrap()) } None => { Box::new(io::stdin()) } @@ -74,9 +71,9 @@ mod tests { #[test] fn test_get_impl() { // Verify that we can load all days - let last_implemented = 6; + let last_implemented = 8; for d in 1..=last_implemented { - get_impl(&format!("{}", d)); + get_impl(d); } } }