use std::io::{self, Write};
use std::path::PathBuf;
use clap::{Parser, ValueEnum};
use pdf_annotation_extractor::{
Descriptor, Error, GlyphSpace, Numbering, Options, Style, error, extract, markdown,
};
#[derive(Copy, Clone, PartialEq, ValueEnum)]
enum ShowArg {
Colour,
Kind,
Author,
Date,
}
impl From<ShowArg> for Descriptor {
fn from(a: ShowArg) -> Self {
match a {
ShowArg::Colour => Descriptor::Colour,
ShowArg::Kind => Descriptor::Kind,
ShowArg::Author => Descriptor::Author,
ShowArg::Date => Descriptor::Date,
}
}
}
#[derive(Copy, Clone, PartialEq, ValueEnum)]
enum NumberArg {
None,
Global,
PerPage,
}
impl From<NumberArg> for Numbering {
fn from(a: NumberArg) -> Self {
match a {
NumberArg::None => Numbering::None,
NumberArg::Global => Numbering::Global,
NumberArg::PerPage => Numbering::PerPage,
}
}
}
#[derive(Parser)]
#[command(about = "Extract highlights and comments from an annotated PDF")]
struct Args {
file: PathBuf,
#[arg(short, long, value_enum, default_value_t = Format::Markdown)]
format: Format,
#[arg(long, default_value_t = 0.5, hide_short_help = true)]
min_overlap: f32,
#[arg(long, default_value_t = 0.25, hide_short_help = true)]
space_gap: f32,
#[arg(long, value_enum, default_value_t = GeometryArg::Auto, hide_short_help = true)]
geometry: GeometryArg,
#[arg(long, hide_short_help = true)]
debug_geometry: bool,
#[arg(long, hide_short_help = true)]
debug_quads: bool,
#[arg(long)]
stats: bool,
#[arg(long)]
strict: bool,
#[arg(long)]
keep_hyphens: bool,
#[arg(long)]
keep_ligatures: bool,
#[arg(long)]
split_quads: bool,
#[arg(long)]
keep_empty: bool,
#[arg(long, value_delimiter = ',', value_name = "LIST")]
show: Vec<ShowArg>,
#[arg(long, value_enum, default_value_t = NumberArg::None)]
number: NumberArg,
}
#[derive(Copy, Clone, ValueEnum)]
enum Format {
Markdown,
Json,
}
#[derive(Copy, Clone, PartialEq, ValueEnum)]
enum GeometryArg {
Auto,
TopDownTop,
TopDownBottom,
BottomUp,
}
enum Outcome {
Clean,
StrictWarnings(usize),
}
fn main() {
match run() {
Ok(Outcome::Clean) => {}
Ok(Outcome::StrictWarnings(n)) => {
eprintln!("error: {n} warning(s) and --strict was set");
std::process::exit(3);
}
Err(e) => {
eprint!("{}", error::report(&e));
std::process::exit(1);
}
}
}
impl From<&Args> for Options {
#[allow(clippy::field_reassign_with_default)]
fn from(args: &Args) -> Self {
let mut o = Options::default();
o.min_overlap = args.min_overlap;
o.space_gap = args.space_gap;
o.geometry = match args.geometry {
GeometryArg::Auto => None,
GeometryArg::TopDownTop => Some(GlyphSpace::TopDownTop),
GeometryArg::TopDownBottom => Some(GlyphSpace::TopDownBottom),
GeometryArg::BottomUp => Some(GlyphSpace::BottomUp),
};
o.keep_hyphens = args.keep_hyphens;
o.keep_ligatures = args.keep_ligatures;
o.split_quads = args.split_quads;
o.keep_empty = args.keep_empty;
o.document_name = args
.file
.file_name()
.map(|s| s.to_string_lossy().to_string());
o.page_counts = args.stats;
o.debug_geometry = args.debug_geometry;
o.debug_quads = args.debug_quads;
o
}
}
fn run() -> Result<Outcome, Error> {
let args = Args::parse();
let opts = Options::from(&args);
let bytes = std::fs::read(&args.file).map_err(|e| Error::read(&args.file, e))?;
let report = extract(bytes, &opts)?;
let text = match args.format {
Format::Json => format!("{}\n", serde_json::to_string_pretty(&report.annotations)?),
Format::Markdown => markdown::render(
&report.annotations,
&Style {
descriptors: args.show.iter().copied().map(Descriptor::from).collect(),
numbering: args.number.into(),
..Style::default()
},
),
};
let notes = report.diagnostics.render();
if !notes.is_empty() {
write_to(io::stderr().lock(), ¬es)?;
}
write_out(&text)?;
let warnings = report.diagnostics.warnings();
Ok(if args.strict && warnings > 0 {
Outcome::StrictWarnings(warnings)
} else {
Outcome::Clean
})
}
fn write_to<W: Write>(mut out: W, text: &str) -> Result<(), Error> {
match out.write_all(text.as_bytes()).and_then(|()| out.flush()) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),
Err(e) => Err(e.into()),
}
}
fn write_out(text: &str) -> Result<(), Error> {
write_to(io::stdout().lock(), text)
}
#[cfg(test)]
mod tests {
use super::*;
struct FailingWriter(io::ErrorKind);
impl Write for FailingWriter {
fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
Err(io::Error::new(self.0, "injected"))
}
fn flush(&mut self) -> io::Result<()> {
Err(io::Error::new(self.0, "injected"))
}
}
#[test]
fn writes_the_whole_report_to_the_sink() {
let mut sink: Vec<u8> = Vec::new();
assert!(write_to(&mut sink, "hello").is_ok());
assert_eq!(sink, b"hello");
}
#[test]
fn broken_pipe_is_not_an_error() {
assert!(write_to(FailingWriter(io::ErrorKind::BrokenPipe), "x").is_ok());
}
#[test]
fn other_write_errors_still_propagate() {
assert!(write_to(FailingWriter(io::ErrorKind::PermissionDenied), "x").is_err());
}
#[test]
fn defaults_match_the_clap_defaults() {
let from_cli = Options::from(&Args::parse_from(["x", "paper.pdf"]));
let plain = Options::default();
assert_eq!(from_cli.min_overlap, plain.min_overlap);
assert_eq!(from_cli.space_gap, plain.space_gap);
assert_eq!(from_cli.geometry, plain.geometry);
assert!(!from_cli.keep_hyphens);
assert!(!from_cli.keep_ligatures);
assert!(!from_cli.split_quads);
assert!(!from_cli.keep_empty);
assert!(!from_cli.page_counts);
}
#[test]
fn auto_geometry_is_the_absence_of_a_choice() {
assert_eq!(
Options::from(&Args::parse_from(["x", "p.pdf"])).geometry,
None
);
assert_eq!(
Options::from(&Args::parse_from(["x", "p.pdf", "--geometry", "bottom-up"])).geometry,
Some(GlyphSpace::BottomUp)
);
}
#[test]
fn every_extraction_flag_reaches_options() {
let opts = Options::from(&Args::parse_from([
"x",
"paper.pdf",
"--min-overlap",
"0.7",
"--space-gap",
"0.4",
"--geometry",
"top-down-top",
"--keep-hyphens",
"--keep-ligatures",
"--split-quads",
"--keep-empty",
"--stats",
"--debug-geometry",
"--debug-quads",
]));
assert_eq!(opts.min_overlap, 0.7);
assert_eq!(opts.space_gap, 0.4);
assert_eq!(opts.geometry, Some(GlyphSpace::TopDownTop));
assert!(opts.keep_hyphens);
assert!(opts.keep_ligatures);
assert!(opts.split_quads);
assert!(opts.keep_empty);
assert!(opts.page_counts);
assert!(opts.debug_geometry);
assert!(opts.debug_quads);
}
#[test]
fn the_document_name_comes_from_the_path() {
let opts = Options::from(&Args::parse_from(["x", "/home/rai/papers/merton.pdf"]));
assert_eq!(opts.document_name.as_deref(), Some("merton.pdf"));
}
}