skip lines by counter alone

This commit is contained in:
Paul Campbell 2023-03-21 07:23:20 +00:00
parent f87ef5a9c0
commit 47acf65bf7
4 changed files with 49 additions and 14 deletions

View file

@ -1,6 +1,8 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::fmt::Debug; use std::fmt::Debug;
use clap::Parser; use clap::Parser;
use std::fs;
use std::io;
#[derive(Parser,Debug)] #[derive(Parser,Debug)]
#[command(version)] #[command(version)]
@ -20,10 +22,24 @@ pub struct Cli {
ignore_extras: bool, ignore_extras: bool,
} }
pub fn skip<F>(cli: Cli, mut out: F) -> () pub fn skip<F>(cli: Cli, mut out: F) -> io::Result<()>
where F: FnMut(String) -> () 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)] #[cfg(test)]
@ -32,16 +48,31 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn skip_one_line() { fn skip_one_line_from_two() -> io::Result<()> {
//given //given
let cli = Cli { lines: 1, file: Some(PathBuf::from("tests/two-lines.txt")), line: None, token: None, ignore_extras: false }; let cli = Cli { lines: 1, file: Some(PathBuf::from("tests/two-lines.txt")), line: None, token: None, ignore_extras: false };
let mut lines: Vec<String> = Vec::new(); let mut lines: Vec<String> = Vec::new();
//when //when
skip(cli, |line| lines.push(line)); skip(cli, |line| lines.push(line))?;
//then //then
assert_eq!(lines, vec!["line 2"]); 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<String> = Vec::new();
//when
skip(cli, |line| lines.push(line))?;
//then
assert_eq!(lines, vec!["alpha", "gamma"]);
Ok(())
} }
} }

View file

@ -2,16 +2,16 @@ use skip::{Cli, skip};
use clap::Parser; use clap::Parser;
use std::io::Write; use std::io::Write;
fn main() { fn main() -> std::io::Result<()> {
let args = Cli::parse(); let args = Cli::parse();
let stdout = std::io::stdout(); let stdout = std::io::stdout();
{
let mut output = stdout.lock(); let mut output = stdout.lock();
skip(args, |line| { skip(args, |line| {
match writeln!(output, "{}", line) { match writeln!(output, "{}", line) {
Err(_) => (), Err(_) => (),
Ok(_) => () Ok(_) => ()
} }
}); })
}
} }

4
tests/four-lines.txt Normal file
View file

@ -0,0 +1,4 @@
alpha
beta
alpha
gamma