Prechádzať zdrojové kódy

Improved CLI arguments

AvariceLHubris 1 rok pred
rodič
commit
394de0e4e7
2 zmenil súbory, kde vykonal 46 pridanie a 10 odobranie
  1. 19 6
      src/cli.rs
  2. 27 4
      src/main.rs

+ 19 - 6
src/cli.rs

@@ -6,19 +6,32 @@ use clap::ValueEnum;
 #[derive(Parser, Debug)]
 #[command(version, about, long_about = None)]
 pub struct Args {
-    #[arg(short, long)]
+
+    /// input file
     pub input_file: OsString,
 
-    #[arg(short, long)]
-    pub output_file: OsString,
+    /// output file
+    pub output_file: Option<OsString>,
 
-    #[arg(short, long, value_enum)]
+    /// Whether to compress or extract.
+    #[arg(short, value_enum, default_value = Mode::C)]
     pub mode: Mode,
 }
 
 #[derive(Clone, Copy, Debug, ValueEnum, Default)]
 pub enum Mode {
-    Extract,
+    /// Extract
+    X,
     #[default]
-    Compress,
+    /// Compress
+    C,
+}
+
+impl Into<clap::builder::OsStr> for Mode {
+    fn into(self) -> clap::builder::OsStr {
+        match self {
+            Mode::X => clap::builder::OsStr::from("x"),
+            Mode::C => clap::builder::OsStr::from("c"),
+        }
+    }
 }

+ 27 - 4
src/main.rs

@@ -1,6 +1,6 @@
-use std::io::Write;
+use std::{ffi::OsString, io::Write};
 
-use clap::Parser;
+use clap::{Parser};
 use huffman::{cli, hufftree, storage};
 
 fn main() -> Result<(), std::io::Error> {
@@ -10,6 +10,29 @@ fn main() -> Result<(), std::io::Error> {
     let outputf = args.output_file;
     let mode = args.mode;
 
+    let outputf = match outputf {
+        Some(name) => name,
+        None => {
+            match mode {
+                cli::Mode::X => {
+                    let mut temp = inputf.clone().into_string().expect("Not a valid input file name.");
+                    if temp.ends_with(".z") {
+                        temp.pop();
+                        temp.pop();
+                    } else {
+                        temp.push_str(".unhuffed");
+                    }
+                    OsString::from(temp)
+                },
+                cli::Mode::C => {
+                    let mut temp = inputf.clone();
+                    temp.push(".z");
+                    temp
+                },
+            }
+        },
+    };
+
     let working_directory = std::path::Path::new(".");
     let inputf = working_directory.join(inputf);
 
@@ -17,7 +40,7 @@ fn main() -> Result<(), std::io::Error> {
     let mut outputf = std::fs::File::create(outputf)?;
 
     match mode {
-        cli::Mode::Extract => {
+        cli::Mode::X => {
             println!("Reading file...");
             let inputf = std::fs::read(inputf)?;
             println!("Done.");
@@ -31,7 +54,7 @@ fn main() -> Result<(), std::io::Error> {
             println!("Stored!");
         }
 
-        cli::Mode::Compress => {
+        cli::Mode::C => {
             println!("Reading file...");
             let inputf = std::fs::read_to_string(inputf)?;
             println!("Done.");