main.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. extern crate getopts;
  2. use getopts::Options;
  3. use std::env;
  4. use std::error::Error;
  5. use std::fs::File;
  6. use std::io::prelude::*;
  7. use std::path::Path;
  8. use std::process::exit;
  9. mod day1;
  10. mod day2;
  11. mod day3;
  12. fn main() {
  13. let args: Vec<String> = env::args().collect();
  14. parse_opt( &args );
  15. }
  16. fn parse_opt( args: &Vec<String> ) {
  17. let mut options = Options::new();
  18. options.optopt( "d", "day", "specify the day number", "<day_number>" );
  19. options.optopt( "i", "input", "specify an input file", "<file_name>" );
  20. options.optflag( "h", "help", "print this help menu" );
  21. let matches = match options.parse( &args[1..] ) {
  22. Ok ( m ) => { m },
  23. Err( f ) => {
  24. println!( "{}", f.to_string() );
  25. exit( 1 );
  26. },
  27. };
  28. if matches.opt_present( "h" ) {
  29. print_usage( &args[0], options );
  30. exit( 0 );
  31. }
  32. let input_file = matches.opt_str( "i" );
  33. let input = match input_file {
  34. Some( x ) => { read_input( &x ) },
  35. None => {
  36. println!( "No input file specified!" );
  37. exit( 1 );
  38. },
  39. };
  40. let day = matches.opt_str( "d" );
  41. match day {
  42. Some( x ) => {
  43. match x.as_ref() {
  44. "1" => day1::main( &input ),
  45. "2" => day2::main( &input ),
  46. "3" => day3::main( &input ),
  47. _ => {
  48. println!( "Unknown day number {}", x );
  49. exit( 1 );
  50. },
  51. }
  52. },
  53. None => {
  54. println!( "No day specified!" );
  55. exit( 1 );
  56. },
  57. }
  58. }
  59. fn print_usage( prog_name: &str, options: Options ) {
  60. let brief = format!( "Usage: {} -d <day_number> -i <input_file> [-h]", prog_name );
  61. print!( "{}", options.usage( &brief ) );
  62. }
  63. fn read_input( input: &str ) -> String {
  64. let path = Path::new( input );
  65. let mut file = match File::open( &path ) {
  66. Ok ( f ) => { f },
  67. Err( f ) => {
  68. println!( "Error opening file {}: {}", path.display(), f.description() );
  69. exit( 1 );
  70. },
  71. };
  72. let mut data = String::new();
  73. match file.read_to_string( &mut data ) {
  74. Ok ( _ ) => { }
  75. Err( f ) => {
  76. println!( "Error reading from file {}: {}", path.display(), f.description() );
  77. },
  78. }
  79. data
  80. }