summaryrefslogtreecommitdiff
path: root/src/bin/subplot.rs
blob: f693a24d2076a88dc297f655f125bf23fcfe4a8e (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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Subplot top level binary
//!

use anyhow::Result;

use env_logger::fmt::Color;
use log::{debug, error, info, trace, warn};
use subplot::{
    codegen, load_document, resource, DataFile, Document, MarkupOpts, Style, SubplotError,
};
use time::{format_description::FormatItem, macros::format_description, OffsetDateTime};

use clap::{CommandFactory, FromArgMatches, Parser};
use std::convert::TryFrom;
use std::ffi::OsString;
use std::fs::{self, write, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{self, Command};
use std::time::UNIX_EPOCH;

mod cli;

use git_testament::*;

git_testament!(VERSION);

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

    #[clap(flatten)]
    markup: MarkupOpts,

    #[clap(subcommand)]
    command: Cmd,
}

impl Toplevel {
    fn run(&self) -> Result<()> {
        trace!("Toplevel: {:?}", self);
        self.command.run()
    }

    fn handle_special_args(&self) {
        let doc_path = self.command.doc_path();
        self.resources.handle(doc_path);
        self.markup.handle();
    }
}

#[derive(Debug, Parser)]
enum Cmd {
    Extract(Extract),
    Filter(Filter),
    Metadata(Metadata),
    Docgen(Docgen),
    Codegen(Codegen),
    #[clap(hide = true)]
    Resources(Resources),
}

impl Cmd {
    fn run(&self) -> Result<()> {
        match self {
            Cmd::Extract(e) => e.run(),
            Cmd::Filter(f) => f.run(),
            Cmd::Metadata(m) => m.run(),
            Cmd::Docgen(d) => d.run(),
            Cmd::Codegen(c) => c.run(),
            Cmd::Resources(r) => r.run(),
        }
    }

    fn doc_path(&self) -> Option<&Path> {
        match self {
            Cmd::Extract(e) => e.doc_path(),
            Cmd::Filter(f) => f.doc_path(),
            Cmd::Metadata(m) => m.doc_path(),
            Cmd::Docgen(d) => d.doc_path(),
            Cmd::Codegen(c) => c.doc_path(),
            Cmd::Resources(r) => r.doc_path(),
        }
    }
}

fn long_version() -> Result<String> {
    use std::fmt::Write as _;
    let mut ret = String::new();
    writeln!(ret, "{}", render_testament!(VERSION))?;
    writeln!(ret, "Crate version: {}", env!("CARGO_PKG_VERSION"))?;
    if let Some(branch) = VERSION.branch_name {
        writeln!(ret, "Built from branch: {}", branch)?;
    } else {
        writeln!(ret, "Branch information is missing.")?;
    }
    writeln!(ret, "Commit info: {}", VERSION.commit)?;
    if VERSION.modifications.is_empty() {
        writeln!(ret, "Working tree is clean")?;
    } else {
        use GitModification::*;
        for fmod in VERSION.modifications {
            match fmod {
                Added(f) => writeln!(ret, "Added: {}", String::from_utf8_lossy(f))?,
                Removed(f) => writeln!(ret, "Removed: {}", String::from_utf8_lossy(f))?,
                Modified(f) => writeln!(ret, "Modified: {}", String::from_utf8_lossy(f))?,
                Untracked(f) => writeln!(ret, "Untracked: {}", String::from_utf8_lossy(f))?,
            }
        }
    }
    Ok(ret)
}

#[derive(Debug, Parser)]
/// Examine embedded resources built into Subplot
struct Resources {}

impl Resources {
    fn doc_path(&self) -> Option<&Path> {
        None
    }
    fn run(&self) -> Result<()> {
        for (name, bytes) in subplot::resource::embedded_files() {
            println!("{} {} bytes", name, bytes.len());
        }
        Ok(())
    }
}
#[derive(Debug, Parser)]
/// 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 {
    /// Allow warnings in document?
    #[clap(long)]
    merciful: bool,

    /// Directory to write extracted files to
    #[clap(
        name = "DIR",
        long = "directory",
        short = 'd',
        parse(from_os_str),
        default_value = "."
    )]
    directory: PathBuf,

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

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

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

impl Extract {
    fn doc_path(&self) -> Option<&Path> {
        self.filename.parent()
    }

    fn run(&self) -> Result<()> {
        let doc = load_linted_doc(&self.filename, Style::default(), None, self.merciful)?;

        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, Parser)]
/// 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 {
    #[clap(name = "INPUT", long = "input", short = 'i', parse(from_os_str))]
    /// Input file (uses STDIN if omitted)
    input: Option<PathBuf>,

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

    #[clap(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 doc_path(&self) -> Option<&Path> {
        self.input.as_deref().and_then(Path::parent)
    }

    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, None)?;
        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(())
    }
}

#[derive(Debug, Parser)]
/// Extract metadata about a document
///
/// Load and process a subplot document, extracting various metadata about the
/// document.  This can then render that either as a plain text report for humans,
/// or as a JSON object for further scripted processing.
struct Metadata {
    /// Allow warnings in document?
    #[clap(long)]
    merciful: bool,

    /// Form that you want the output to take
    #[clap(short = 'o', default_value = "plain", possible_values=&["plain", "json"])]
    output_format: cli::OutputFormat,

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

impl Metadata {
    fn doc_path(&self) -> Option<&Path> {
        self.filename.parent()
    }

    fn run(&self) -> Result<()> {
        let mut doc = load_linted_doc(&self.filename, Style::default(), None, self.merciful)?;
        let meta = cli::Metadata::try_from(&mut doc)?;
        match self.output_format {
            cli::OutputFormat::Plain => meta.write_out(),
            cli::OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&meta)?),
        }
        Ok(())
    }
}

#[derive(Debug, Parser)]
/// Typeset subplot document
///
/// Process a subplot document and typeset it using Pandoc.
struct Docgen {
    /// Allow warnings in document?
    #[clap(long)]
    merciful: bool,

    /// The template to use from the document.
    ///
    /// If not specified, subplot will try and find a unique template name from the document
    #[clap(name = "TEMPLATE", long = "template", short = 't')]
    template: Option<String>,

    // Input Subplot document
    #[clap(parse(from_os_str))]
    input: PathBuf,

    // Output document filename
    #[clap(name = "FILE", long = "output", short = 'o', parse(from_os_str))]
    output: PathBuf,

    // Set date.
    #[clap(name = "DATE", long = "date")]
    date: Option<String>,
}

impl Docgen {
    fn doc_path(&self) -> Option<&Path> {
        self.input.parent()
    }

    fn run(&self) -> Result<()> {
        let mut style = Style::default();
        if self.output.extension() == Some(&OsString::from("pdf")) {
            trace!("PDF output chosen");
            style.typeset_links_as_notes();
        }
        let mut doc = load_linted_doc(&self.input, style, self.template.as_deref(), self.merciful)?;

        let mut pandoc = pandoc::new();
        // Metadata date from command line or file mtime. However, we
        // can't set it directly, since we don't want to override the date
        // in the actual document, if given, so we only set
        // user-provided-date. Our parsing code will use that if date is
        // not document metadata.
        let date = if let Some(date) = self.date.clone() {
            date
        } else if let Some(date) = doc.meta().date() {
            date.to_string()
        } else {
            Self::mtime_formatted(Self::mtime(&self.input)?)
        };
        pandoc.add_option(pandoc::PandocOption::Meta("date".to_string(), Some(date)));
        pandoc.add_option(pandoc::PandocOption::TableOfContents);
        pandoc.add_option(pandoc::PandocOption::Standalone);
        pandoc.add_option(pandoc::PandocOption::NumberSections);

        if Self::need_output(&mut doc, self.template.as_deref(), &self.output) {
            doc.typeset();
            pandoc.set_input_format(pandoc::InputFormat::Json, vec![]);
            pandoc.set_input(pandoc::InputKind::Pipe(doc.ast()?));
            pandoc.set_output(pandoc::OutputKind::File(self.output.clone()));

            debug!("Executing pandoc to produce {}", self.output.display());
            let r = pandoc.execute();
            if let Err(pandoc::PandocError::Err(output)) = r {
                let code = output.status.code().or(Some(127)).unwrap();
                let stderr = String::from_utf8_lossy(&output.stderr);
                error!("Failed to execute Pandoc: exit code {}", code);
                error!("{}", stderr.strip_suffix('\n').unwrap());

                return Err(anyhow::Error::msg("Pandoc failed"));
            }
            r?;
        }

        Ok(())
    }

    fn mtime(filename: &Path) -> Result<(u64, u32)> {
        let mtime = fs::metadata(filename)?.modified()?;
        let mtime = mtime.duration_since(UNIX_EPOCH)?;
        Ok((mtime.as_secs(), mtime.subsec_nanos()))
    }

    fn mtime_formatted(mtime: (u64, u32)) -> String {
        const DATE_FORMAT: &[FormatItem<'_>] =
            format_description!("[year]-[month]-[day] [hour]:[minute]");

        let secs: i64 = format!("{}", mtime.0).parse().unwrap_or(0);
        let time = OffsetDateTime::from_unix_timestamp(secs).unwrap();
        time.format(DATE_FORMAT).unwrap()
    }

    fn need_output(doc: &mut subplot::Document, template: Option<&str>, output: &Path) -> bool {
        let output = match Self::mtime(output) {
            Err(_) => return true,
            Ok(ts) => ts,
        };

        for filename in doc.sources(template) {
            let source = match Self::mtime(&filename) {
                Err(_) => return true,
                Ok(ts) => ts,
            };
            if source >= output {
                return true;
            }
        }
        false
    }
}

#[derive(Debug, Parser)]
/// Generate test suites from Subplot documents
///
/// This reads a subplot document, extracts the scenarios, and writes out a test
/// program capable of running the scenarios in the subplot document.
struct Codegen {
    /// The template to use from the document.
    ///
    /// If not specified, subplot will try and find a unique template name from the document
    #[clap(name = "TEMPLATE", long = "template", short = 't')]
    template: Option<String>,

    /// Input filename.
    #[clap(parse(from_os_str))]
    filename: PathBuf,

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

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

impl Codegen {
    fn doc_path(&self) -> Option<&Path> {
        self.filename.parent()
    }

    fn run(&self) -> Result<()> {
        debug!("codegen starts");
        let output = codegen(&self.filename, &self.output, self.template.as_deref())?;
        if self.run {
            let spec = output
                .doc
                .meta()
                .document_impl(&output.template)
                .unwrap()
                .spec();
            let run = match spec.run() {
                None => {
                    error!(
                        "Template {} does not specify how to run suites",
                        spec.template_filename().display()
                    );
                    std::process::exit(1);
                }
                Some(x) => x,
            };

            let status = Command::new(run).arg(&self.output).status()?;
            if !status.success() {
                error!("Test suite failed!");
                std::process::exit(2);
            }
        }
        debug!("codegen ends successfully");
        Ok(())
    }
}

fn load_linted_doc(
    filename: &Path,
    style: Style,
    template: Option<&str>,
    merciful: bool,
) -> Result<Document, SubplotError> {
    let mut doc = load_document(filename, style, None)?;
    trace!("Got doc, now linting it");
    doc.lint()?;
    trace!("Doc linted ok");

    let meta = doc.meta();
    trace!("Looking for template, meta={:#?}", meta);

    // Get template as given to use (from command line), or from
    // document, or else default to the empty string.
    let template = if let Some(t) = template {
        t
    } else if let Ok(t) = doc.template() {
        t
    } else {
        ""
    };
    let template = template.to_string();
    trace!("Template: {:#?}", template);
    doc.check_named_files_exist(&template)?;
    doc.check_matched_steps_have_impl(&template);
    doc.check_embedded_files_are_used(&template)?;

    for w in doc.warnings() {
        warn!("{}", w);
    }

    if !doc.warnings().is_empty() && !merciful {
        return Err(SubplotError::Warnings(doc.warnings().len()));
    }

    Ok(doc)
}

fn print_source_errors(e: Option<&dyn std::error::Error>) {
    if let Some(e) = e {
        error!("{}", e);
        print_source_errors(e.source());
    }
}

fn real_main() {
    info!("Starting Subplot");
    let argparser = Toplevel::command();
    let version = long_version().unwrap();
    let argparser = argparser.long_version(version.as_str());
    let args = argparser.get_matches();
    let args = Toplevel::from_arg_matches(&args).unwrap();
    args.handle_special_args();
    match args.run() {
        Ok(_) => {
            info!("Subplot finished successfully");
        }
        Err(e) => {
            error!("{}", e);
            print_source_errors(e.source());
            process::exit(1);
        }
    }
}

fn main() {
    let env = env_logger::Env::new()
        .filter_or("SUBPLOT_LOG", "info")
        .write_style("SUBPLOT_LOG_STYLE");
    env_logger::Builder::from_env(env)
        .format_timestamp(None)
        .format(|buf, record| {
            let mut level_style = buf.style();
            level_style.set_color(Color::Red).set_bold(true);
            writeln!(
                buf,
                "{}: {}",
                level_style.value(record.level()),
                record.args()
            )
        })
        .init();
    real_main();
}