summaryrefslogtreecommitdiff
path: root/src/bin/sp-extract.rs
blob: 9be159fa1df6434e9c7b60fe8822139dc156420f (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
use anyhow::Result;
use std::fs::write;
use std::path::PathBuf;

use structopt::StructOpt;

use subplot::{DataFile, Document, Style, SubplotError};

mod cli;

#[derive(Debug, StructOpt)]
#[structopt(name = "sp-meta", about = "Show Subplot document metadata.")]
struct Opt {
    /// Input subplot document filename
    #[structopt(parse(from_os_str))]
    filename: PathBuf,

    /// Names of embedded files to be extracted.
    #[structopt()]
    embedded: Vec<String>,

    // Set output directory.
    #[structopt(name = "DIR", long = "--directory", short = "-d", parse(from_os_str))]
    directory: PathBuf,
}

fn main() -> Result<()> {
    let opt = Opt::from_args();
    let doc = cli::load_document(&opt.filename, Style::default())?;

    for filename in opt.embedded {
        let file = get_embedded(&doc, &filename)?;
        let output = opt.directory.join(filename);
        write(output, file.contents())?;
    }

    Ok(())
}

fn get_embedded<'a>(doc: &'a Document, filename: &str) -> Result<&'a DataFile> {
    for file in doc.files() {
        if file.filename() == filename {
            return Ok(file);
        }
    }
    Err(SubplotError::EmbeddedFileNotFound(filename.to_owned()).into())
}