aboutsummaryrefslogtreecommitdiffstats
path: root/rst/src/main.rs
blob: 6a7ed443cd36b126eb11e300f522d106c8a9d096 (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
use clap::arg_enum;
use quicli::{
    fs::read_file,
    prelude::{CliResult, Verbosity},
};
use structopt::StructOpt;

use rst_parser::parse;
use rst_renderer::{render_html, render_json, render_xml};

use std::io::{self, Read};

arg_enum! {
    #[derive(Debug)]
    #[allow(non_camel_case_types)]
    enum Format { json, xml, html }
}

#[derive(Debug, StructOpt)]
#[structopt(raw(setting = "structopt::clap::AppSettings::ColoredHelp"))]
struct Cli {
    #[structopt(
        long = "format", short = "f", default_value = "html",  // xml is pretty defunct…
        raw(possible_values = "&Format::variants()", case_insensitive = "true"),
    )]
    format: Format,
    file: Option<String>,
    #[structopt(flatten)]
    verbosity: Verbosity,
}

fn main() -> CliResult {
    let args = Cli::from_args();
    args.verbosity.setup_env_logger("rst")?;

    let content = if let Some(file) = args.file {
        read_file(file)?
    } else {
        let mut stdin = String::new();
        io::stdin().read_to_string(&mut stdin)?;

        stdin
    };

    // TODO: somehow make it work without replacing tabs
    let mut content = read_file(args.file)?.replace('\t', " ".repeat(8).as_ref());
    // Allows for less complex grammar
    if !content.ends_with('\n') {
        content.push('\n');
    }
    let document = parse(&content)?;
    let stdout = std::io::stdout();
    match args.format {
        Format::json => render_json(&document, stdout)?,
        Format::xml  => render_xml (&document, stdout)?,
        Format::html => render_html(&document, stdout, true)?,
    }
    Ok(())
}