use std::io::{BufWriter, Write};
use std::process::ExitCode;
use clap::Parser;
use skimmd::format::render;
use skimmd::lines::{LineMap, LoadErr, io_reason, load_stdin, load_text};
use skimmd::ranges;
use skimmd::toc::{build_toc, filter_rows};
#[derive(Parser)]
#[command(
version,
about = "Print a Markdown file's structure as a TOC (line numbers and sizes), or read verbatim line ranges.",
after_help = "RANGE grammar: N-M or N- (N- = through the last line). \
Ranges are comma- and/or space-separated, e.g. 1-5,9-12 or 1-5 9-12. \
With no ranges, the TOC is printed. \
Omit FILE (or use -) to read from standard input. "
)]
struct Cli {
#[arg(short = 'f', long = "filter", value_name = "SUBSTRING")]
filter: Option<String>,
#[arg(required = false)]
file: Option<String>,
#[arg(value_name = "RANGE")]
ranges: Vec<String>,
}
fn main() -> ExitCode {
let cli = Cli::parse();
let (label, res) = match &cli.file {
Some(f) if f != "-" => (f.as_str(), load_text(std::path::Path::new(f))),
_ => ("<stdin>", load_stdin()),
};
let text = match res {
Ok(t) => t,
Err(LoadErr::Io(e)) => die(&format!("{label}: {}", io_reason(&e))),
Err(LoadErr::NotUtf8) => die(&format!("{label}: not valid UTF-8")),
};
let lm = LineMap::new(text);
if cli.ranges.is_empty() {
toc_mode(&lm, cli.filter.as_deref())
} else {
range_mode(&lm, &cli.ranges)
}
}
fn toc_mode(lm: &LineMap, filter: Option<&str>) -> ExitCode {
let rows = build_toc(lm);
let rows = match filter {
Some(kw) => filter_rows(lm, &rows, kw),
None => rows,
};
write_stdout(&render(&rows))
}
fn range_mode(lm: &LineMap, specs: &[String]) -> ExitCode {
let merged = match ranges::parse(specs, lm.n()) {
Ok(m) => m,
Err(e) => die(&e.message()),
};
let mut out = String::new();
for r in &merged {
out.push_str(lm.span(r.start, r.end));
}
write_stdout(&out)
}
fn write_stdout(out: &str) -> ExitCode {
let stdout = std::io::stdout();
let mut w = BufWriter::new(stdout);
match w.write_all(out.as_bytes()).and_then(|_| w.flush()) {
Ok(()) => ExitCode::SUCCESS,
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
Err(e) => die(&format!("error writing to stdout: {e}")),
}
}
#[cold]
fn die(msg: &str) -> ! {
eprintln!("skimmd: {msg}");
std::process::exit(1);
}