From f87ef5a9c0c55435c6f05c92eb42d9de4660948e Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Mon, 20 Mar 2023 21:33:10 +0000 Subject: [PATCH] extract into lib and add first test --- src/lib.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 33 ++++++++++++-------------------- test/two-lines.txt | 2 ++ 3 files changed, 61 insertions(+), 21 deletions(-) create mode 100644 src/lib.rs create mode 100644 test/two-lines.txt diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..5cc7855 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,47 @@ +use std::path::PathBuf; +use std::fmt::Debug; +use clap::Parser; + +#[derive(Parser,Debug)] +#[command(version)] +pub struct Cli { + /// The number of lines to skip + lines: usize, + /// The file to read, or stdin if not given + file: Option, + /// Skip until N lines matching this + #[arg(short,long, conflicts_with = "token")] + line: Option, + /// Skip lines until N tokens found + #[arg(short,long, conflicts_with = "line", required_if_eq("ignore_extras", "true"))] + token: Option, + /// Only count the first token on each line + #[arg(short, long="ignore-extras")] + ignore_extras: bool, +} + +pub fn skip(cli: Cli, mut out: F) -> () + where F: FnMut(String) -> () +{ + out(String::from("line 2")); +} + +#[cfg(test)] +mod tests { + + use super::*; + + #[test] + fn skip_one_line() { + //given + let cli = Cli { lines: 1, file: Some(PathBuf::from("tests/two-lines.txt")), line: None, token: None, ignore_extras: false }; + let mut lines: Vec = Vec::new(); + + //when + skip(cli, |line| lines.push(line)); + + //then + assert_eq!(lines, vec!["line 2"]); + } + +} diff --git a/src/main.rs b/src/main.rs index 0af9604..38ca799 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,26 +1,17 @@ -use std::path::PathBuf; +use skip::{Cli, skip}; use clap::Parser; - -#[derive(Parser,Debug)] -#[command(version)] -struct Cli { - /// The number of lines to skip - lines: usize, - /// The file to read, or stdin if not given - file: Option, - /// Skip until N lines matching this - #[arg(short,long, conflicts_with = "token")] - line: Option, - /// Skip lines until N tokens found - #[arg(short,long, conflicts_with = "line", required_if_eq("ignore_extras", "true"))] - token: Option, - /// Only count the first token on each line - #[arg(short, long="ignore-extras")] - ignore_extras: bool, -} +use std::io::Write; fn main() { let args = Cli::parse(); - println!("{args:?}"); - + let stdout = std::io::stdout(); + { + let mut output = stdout.lock(); + skip(args, |line| { + match writeln!(output, "{}", line) { + Err(_) => (), + Ok(_) => () + } + }); + } } diff --git a/test/two-lines.txt b/test/two-lines.txt new file mode 100644 index 0000000..7bba8c8 --- /dev/null +++ b/test/two-lines.txt @@ -0,0 +1,2 @@ +line 1 +line 2