From 47acf65bf7c195cb5286678fae76b8983648bd10 Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Tue, 21 Mar 2023 07:23:20 +0000 Subject: [PATCH] skip lines by counter alone --- src/lib.rs | 39 +++++++++++++++++++++++++++++++---- src/main.rs | 20 +++++++++--------- tests/four-lines.txt | 4 ++++ {test => tests}/two-lines.txt | 0 4 files changed, 49 insertions(+), 14 deletions(-) create mode 100644 tests/four-lines.txt rename {test => tests}/two-lines.txt (100%) diff --git a/src/lib.rs b/src/lib.rs index 5cc7855..c82db68 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,8 @@ use std::path::PathBuf; use std::fmt::Debug; use clap::Parser; +use std::fs; +use std::io; #[derive(Parser,Debug)] #[command(version)] @@ -20,10 +22,24 @@ pub struct Cli { ignore_extras: bool, } -pub fn skip(cli: Cli, mut out: F) -> () +pub fn skip(cli: Cli, mut out: F) -> io::Result<()> where F: FnMut(String) -> () { - out(String::from("line 2")); + match &cli.file { + Some(file) => { + let content = fs::read_to_string(file).expect("Could not read file"); + let mut counter = 0usize; + for current_line in content.lines() { + counter += 1; + if counter > cli.lines { + out(String::from(current_line)); + } + } + }, + None => todo!("reading from stdin") + } + + Ok(()) } #[cfg(test)] @@ -32,16 +48,31 @@ mod tests { use super::*; #[test] - fn skip_one_line() { + fn skip_one_line_from_two() -> io::Result<()> { //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)); + skip(cli, |line| lines.push(line))?; //then assert_eq!(lines, vec!["line 2"]); + Ok(()) + } + + #[test] + fn skip_two_lines_from_four() -> io::Result<()> { + //given + let cli = Cli { lines: 2, file: Some(PathBuf::from("tests/four-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!["alpha", "gamma"]); + Ok(()) } } diff --git a/src/main.rs b/src/main.rs index 38ca799..6c73ba1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,16 +2,16 @@ use skip::{Cli, skip}; use clap::Parser; use std::io::Write; -fn main() { +fn main() -> std::io::Result<()> { let args = Cli::parse(); + let stdout = std::io::stdout(); - { - let mut output = stdout.lock(); - skip(args, |line| { - match writeln!(output, "{}", line) { - Err(_) => (), - Ok(_) => () - } - }); - } + let mut output = stdout.lock(); + + skip(args, |line| { + match writeln!(output, "{}", line) { + Err(_) => (), + Ok(_) => () + } + }) } diff --git a/tests/four-lines.txt b/tests/four-lines.txt new file mode 100644 index 0000000..536a7f5 --- /dev/null +++ b/tests/four-lines.txt @@ -0,0 +1,4 @@ +alpha +beta +alpha +gamma diff --git a/test/two-lines.txt b/tests/two-lines.txt similarity index 100% rename from test/two-lines.txt rename to tests/two-lines.txt