diff --git a/Cargo.lock b/Cargo.lock index 368ac2a..bf77b1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -288,7 +288,7 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "vote-counter" -version = "0.1.0" +version = "0.1.1" dependencies = [ "clap", "colored", diff --git a/Cargo.toml b/Cargo.toml index 140c499..7a3c79c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vote-counter" -version = "0.1.1" +version = "0.2.0" edition = "2021" description = "An opinionated single transferrable vote counter for the command line." license = "MIT OR Apache-2.0" diff --git a/src/main.rs b/src/main.rs index 85065a2..341394b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,14 +11,28 @@ use std::process; use clap::Parser; +/// Adjusts threshold to be within permitted range, warning the user. +fn adjust_threshold(threshold : f64) -> f64 { + reporting::threshold_squash(threshold); + if threshold < 0.0 { + 0.0 + } + else if threshold > 1.0 { + 1.0 + } + else { + threshold + } +} + #[derive(Parser, Debug)] -#[clap(author, version)] +#[clap(author, about, version)] struct Args { /// Path to the CSV containing the ballots. #[clap()] path : path::PathBuf, - /// Threshold to win. + /// Threshold to win (from 0.0 to 1.0). #[clap(long, short, default_value = "0.5")] threshold : f64, @@ -28,7 +42,9 @@ struct Args { } /// Primary entry point to vote counting algorithms. -fn count(args : Args) -> Result<(), csv::Error> { +fn count(mut args : Args) -> Result<(), csv::Error> { + + args.threshold = adjust_threshold(args.threshold); let mut ballot_box = BallotBox::from_file(&args.path, args.report)?; @@ -48,12 +64,13 @@ fn count(args : Args) -> Result<(), csv::Error> { fn main() { let args = Args::parse(); + match count(args) { Ok(_) => { process::exit(exitcode::OK); }, Err(error) => { - println!("An error occured reading the CSV data: {}", error); + reporting::csv_error(error); process::exit(exitcode::DATAERR); } } diff --git a/src/reporting.rs b/src/reporting.rs index 76728d2..93b600c 100644 --- a/src/reporting.rs +++ b/src/reporting.rs @@ -60,3 +60,18 @@ pub fn winner(winner : Option, candidates : &Candidates) { None => println!("{}", "The election was a tie".bright_blue()), } } + +/// Notifies the user if the threshold was adjusted. +pub fn threshold_squash(prev_threshold : f64) { + if prev_threshold < 0.0 { + println!("{} Threshold was below the allowed range, and set to 0", "Warning:".yellow().bold()) + } + else if prev_threshold > 1.0 { + println!("{} Threshold was above the allowed range, and set to 1", "Warning:".yellow().bold()) + } +} + +/// Displays a CSV error. +pub fn csv_error(error : csv::Error) { + println!("{} {}", "CSV Error:".red().bold(), error); +}