extract into lib and add first test

This commit is contained in:
Paul Campbell 2023-03-20 21:33:10 +00:00
parent 3f79ffd928
commit f87ef5a9c0
3 changed files with 61 additions and 21 deletions

47
src/lib.rs Normal file
View file

@ -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<PathBuf>,
/// Skip until N lines matching this
#[arg(short,long, conflicts_with = "token")]
line: Option<String>,
/// Skip lines until N tokens found
#[arg(short,long, conflicts_with = "line", required_if_eq("ignore_extras", "true"))]
token: Option<String>,
/// Only count the first token on each line
#[arg(short, long="ignore-extras")]
ignore_extras: bool,
}
pub fn skip<F>(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<String> = Vec::new();
//when
skip(cli, |line| lines.push(line));
//then
assert_eq!(lines, vec!["line 2"]);
}
}

View file

@ -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<PathBuf>,
/// Skip until N lines matching this
#[arg(short,long, conflicts_with = "token")]
line: Option<String>,
/// Skip lines until N tokens found
#[arg(short,long, conflicts_with = "line", required_if_eq("ignore_extras", "true"))]
token: Option<String>,
/// 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(_) => ()
}
});
}
}

2
test/two-lines.txt Normal file
View file

@ -0,0 +1,2 @@
line 1
line 2