summaryrefslogtreecommitdiff
path: root/src/bin/sp-codegen.rs
blob: c316bea89065673685a90cef1b314f418b643bf6 (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
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::Result;
use structopt::StructOpt;

use subplot::{generate_test_program, resource, template_spec, Style, SubplotError, TemplateSpec};

mod cli;

fn main() -> Result<()> {
    let opt = Opt::from_args();
    opt.resources.handle();
    let mut doc = cli::load_document(&opt.filename, Style::default())?;
    doc.lint()?;
    if !doc.check_named_files_exist()? {
        eprintln!("Unable to continue");
        std::process::exit(1);
    }

    let spec = template_spec(&doc)?;
    generate_test_program(&mut doc, &spec, &opt.output)?;

    if opt.run && !run(&spec, &opt.output)? {
        eprintln!("Test program failed.");
        std::process::exit(1);
    }

    Ok(())
}

// Define the command line arguments.
#[derive(Debug, StructOpt)]
#[structopt(name = "codegen", about = "Subplot code generator.")]
struct Opt {
    // Input filename.
    #[structopt(parse(from_os_str))]
    filename: PathBuf,

    // Write generated test program to this file.
    #[structopt(
        long,
        short,
        parse(from_os_str),
        help = "Writes generated test program to FILE"
    )]
    output: PathBuf,

    // Run the generated test program after writing it?
    #[structopt(long, short, help = "Runs generated test program")]
    run: bool,

    #[structopt(flatten)]
    resources: resource::ResourceOpts,
}

fn run(spec: &TemplateSpec, filename: &Path) -> subplot::Result<bool> {
    let run = match spec.run() {
        None => return Err(SubplotError::TemplateNoRun),
        Some(x) => x,
    };

    let status = Command::new(run).arg(filename).status()?;
    Ok(status.success())
}