about summary refs log tree commit diff
path: root/examples/copyline.rs
blob: f0c2b67d5a67b5a5afa428b994ed1a023c4712fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::{
	fs::File,
	io::{self, BufRead, BufReader, ErrorKind, Write},
	path::PathBuf,
};

use scurvy::{
	Argument, Scurvy,
	formula::{PathFormula, UsizeFormula},
};

pub fn main() {
	let args = vec![
		Argument::new(&["infile", "ifile"]).arg("path"),
		Argument::new(&["line-number", "ln"]).arg("line#"),
		Argument::new(&["outfile", "ofile"]).arg("path"),
	];

	let scurvy = Scurvy::make(args);

	if scurvy.should_print_help() {
		println!("{HELP_STR}");
		return;
	}

	let input = scurvy.parse_req("infile", PathFormula::new());
	let output = scurvy.parse_req("outfile", PathFormula::new());
	let line_number = scurvy.parse_req("line-number", UsizeFormula::new().bounds(1..));

	if let Err(e) = do_work(input, output, line_number) {
		eprintln!("{e}");
		std::process::exit(-1);
	}
}

fn do_work(input: PathBuf, output: PathBuf, line_number: usize) -> io::Result<()> {
	let bufr = BufReader::new(File::open(input)?);
	let mut out = File::create(output)?;

	match bufr.lines().nth(line_number) {
		Some(line) => {
			out.write_all((line?).as_bytes())?;
			Ok(())
		}
		None => Err(io::Error::from(ErrorKind::UnexpectedEof)),
	}
}

// Tab width is usually eight in terminals. Our max line-length for an options
// name line is 72, the help-text itself is 66
const HELP_STR: &'static str = "\
usage: copyline ifile=<path> ofile=<path> ln=<line#>

ARGUMENTS
	infile=<path> | ifile=<path>
		Input file path. Where we read the line from

	outfile=<path> | ofile=<path>
		Output file path. Where we write the line to.

	line-number=<line#> | ln=<line#>
		The line you want, starting at 1.
";