summaryrefslogtreecommitdiff
path: root/src/bin/sp-docgen.rs
blob: c9e4879bb37bb564e2866adab9be2722b80e6b2a (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
use pandoc;
use std::path::PathBuf;
use structopt::StructOpt;

use subplot;

// Define the command line arguments.
#[derive(Debug, StructOpt)]
#[structopt(name = "docgen", about = "Subplot document generator.")]
struct Opt {
    // One or more input filename.
    #[structopt(parse(from_os_str))]
    filenames: Vec<PathBuf>,

    // Set output file name.
    #[structopt(name = "FILE", long = "--output", short = "-o", parse(from_os_str))]
    output: PathBuf,
}

fn main() -> subplot::Result<()> {
    let opt = Opt::from_args();
    let mut pandoc = pandoc::new();

    // Tell Pandoc what the input files are.
    for filename in opt.filenames {
        pandoc.add_input(&filename);
    }

    // Tell Pandoc what the input file format is.
    pandoc.set_input_format(
        pandoc::InputFormat::Markdown,
        vec![pandoc::MarkdownExtension::Citations],
    );

    // Add external Pandoc filters.
    let citeproc = std::path::Path::new("pandoc-citeproc");
    pandoc.add_option(pandoc::PandocOption::Filter(citeproc.to_path_buf()));

    // This would be nicer if pandoc took a Pathbuf for output,
    // instead of a String. Reported as
    // <https://github.com/oli-obk/rust-pandoc/issues/23>
    let output = format!("{}", opt.output.display());
    pandoc.set_output(pandoc::OutputKind::File(output));

    // Set options for Pandoc.
    pandoc.add_option(pandoc::PandocOption::TableOfContents);
    pandoc.add_option(pandoc::PandocOption::Standalone);
    pandoc.add_option(pandoc::PandocOption::NumberSections);

    // Run Pandoc to parse the inputs into an abstract syntax tree,
    // then run our filter on that, then let Pandoc produce the output
    // file from the AST.
    pandoc.add_filter(|json| {
        let mut doc = subplot::Document::from_json(&json).expect("error parsing JSON AST");
        doc.typeset();
        doc.ast().expect("error serializing into JSON AST")
    });
    pandoc.execute()?;

    Ok(())
}