skip lines by counter alone
This commit is contained in:
parent
f87ef5a9c0
commit
47acf65bf7
4 changed files with 49 additions and 14 deletions
39
src/lib.rs
39
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<F>(cli: Cli, mut out: F) -> ()
|
||||
pub fn skip<F>(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<String> = 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<String> = Vec::new();
|
||||
|
||||
//when
|
||||
skip(cli, |line| lines.push(line))?;
|
||||
|
||||
//then
|
||||
assert_eq!(lines, vec!["alpha", "gamma"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
}
|
||||
|
|
20
src/main.rs
20
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(_) => ()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
4
tests/four-lines.txt
Normal file
4
tests/four-lines.txt
Normal file
|
@ -0,0 +1,4 @@
|
|||
alpha
|
||||
beta
|
||||
alpha
|
||||
gamma
|
Loading…
Reference in a new issue