summaryrefslogtreecommitdiff
path: root/src/bin/subplot.rs
blob: 94c4b53295e87b26190e4367b73c99e8738a0d08 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//! Subplot top level binary
//!

use anyhow::Result;

use structopt::StructOpt;
use subplot::{resource, DataFile, Document, Style};

use std::fs::{write, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process;

mod cli;

#[derive(Debug, StructOpt)]
struct Toplevel {
    #[structopt(flatten)]
    resources: resource::ResourceOpts,

    #[structopt(flatten)]
    command: Cmd,
}

impl Toplevel {
    fn run(&self) -> Result<()> {
        self.command.run()
    }
}

#[derive(Debug, StructOpt)]
enum Cmd {
    Extract(Extract),
    Filter(Filter),
}

impl Cmd {
    fn run(&self) -> Result<()> {
        match self {
            Cmd::Extract(e) => e.run(),
            Cmd::Filter(f) => f.run(),
        }
    }
}

#[derive(Debug, StructOpt)]
/// Extract embedded files from a subplot document
///
/// If no embedded filenames are provided, this will
/// extract all embedded files.  if the output directory
/// is not specified then this will extract to the current directory.
struct Extract {
    /// Directory to write extracted files to
    #[structopt(
        name = "DIR",
        long = "directory",
        short = "d",
        parse(from_os_str),
        default_value = "."
    )]
    directory: PathBuf,

    /// Don't actually write the files out
    #[structopt(long)]
    dry_run: bool,

    /// Input subplot document filename
    #[structopt(parse(from_os_str))]
    filename: PathBuf,

    /// Names of embedded files to be extracted.
    embedded: Vec<String>,
}

impl Extract {
    fn run(&self) -> Result<()> {
        let doc = cli::load_document(&self.filename, Style::default())?;

        let files: Vec<&DataFile> = if self.embedded.is_empty() {
            doc.files()
                .iter()
                .map(Result::Ok)
                .collect::<Result<Vec<_>>>()
        } else {
            self.embedded
                .iter()
                .map(|filename| cli::extract_file(&doc, filename))
                .collect::<Result<Vec<_>>>()
        }?;

        for f in files {
            let outfile = self.directory.join(f.filename());
            if self.dry_run {
                println!("Would write out {}", outfile.display());
            } else {
                write(outfile, f.contents())?
            }
        }

        Ok(())
    }
}

#[derive(Debug, StructOpt)]
/// Filter a pandoc JSON document.
///
/// This filters a pandoc JSON document, applying Subplot's formatting rules and
/// image conversion support.
///
/// If input/output filename is provided, this operates on STDIN/STDOUT.
struct Filter {
    #[structopt(name = "INPUT", long = "input", short = "i", parse(from_os_str))]
    /// Input file (uses STDIN if omitted)
    input: Option<PathBuf>,

    #[structopt(name = "OUTPUT", long = "output", short = "o", parse(from_os_str))]
    /// Output file (uses STDOUT if omitted)
    output: Option<PathBuf>,

    #[structopt(name = "BASE", long = "base", short = "b", parse(from_os_str))]
    /// Base directory (defaults to dir of input if given, or '.' if using STDIN)
    base: Option<PathBuf>,
}

impl Filter {
    fn run(&self) -> Result<()> {
        let mut buffer = String::new();
        if let Some(filename) = &self.input {
            File::open(filename)?.read_to_string(&mut buffer)?;
        } else {
            std::io::stdin().read_to_string(&mut buffer)?;
        }
        let basedir = if let Some(path) = &self.base {
            path.as_path()
        } else if let Some(path) = &self.input {
            path.parent().unwrap_or_else(|| Path::new("."))
        } else {
            Path::new(".")
        };
        let style = Style::default();
        let mut doc = Document::from_json(basedir, vec![], &buffer, style)?;
        doc.typeset();
        let bytes = doc.ast()?.into_bytes();
        if let Some(filename) = &self.output {
            File::create(filename)?.write_all(&bytes)?;
        } else {
            std::io::stdout().write_all(&bytes)?;
        }
        Ok(())
    }
}

fn main() {
    let args = Toplevel::from_args();
    args.resources.handle();
    match args.run() {
        Ok(_) => {}
        Err(e) => {
            eprintln!("Failure: {:?}", e);
            process::exit(1);
        }
    }
}