use std::io::{self, Read, Write};
use std::process::ExitCode;
use tabnas_dmog::{
canon, check, default_limits, explain, formats, formats_json, parsed_formats, Code, Fail,
Limits, Program, ProgramOptions, Render, Source, TranslateOptions, Translation,
};
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
const USAGE: &str = "usage: dmog canon|format|check|explain FILE\n dmog run [--grammar FORMAT] [--render csv|json] [--max-output-bytes N] PROGRAM INPUT\n dmog translate --from FORMAT --to FORMAT [--path PATH] [--key KEY] [--with PROGRAM] [--whole] [--max-output-bytes N] INPUT\n dmog formats\n (a FILE may be - for standard input)";
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
match run(&args) {
Ok(text) => {
let mut out = io::stdout().lock();
if out
.write_all(text.as_bytes())
.and_then(|()| out.flush())
.is_err()
{
return ExitCode::from(3);
}
ExitCode::SUCCESS
}
Err(exit) => {
report(&exit.fail);
ExitCode::from(exit.status)
}
}
}
fn report(fail: &Fail) {
let mut err = io::stderr().lock();
let _ = writeln!(err, "{}", fail.to_json()).and_then(|()| err.flush());
}
struct Exit {
fail: Fail,
status: u8,
}
impl From<Fail> for Exit {
fn from(fail: Fail) -> Exit {
let status = match fail.code {
Code::DslParseError
| Code::DslTypeError
| Code::StreamReused
| Code::StreamabilityUnknown => 2,
Code::ResourceLimitExceeded => 5,
Code::OutputFailed => 3,
Code::Aborted => 6,
_ => 1,
};
Exit { fail, status }
}
}
fn usage() -> Exit {
Exit {
fail: Fail::input(USAGE),
status: 2,
}
}
fn refused_option(fail: Fail) -> Exit {
match fail.code {
Code::InputInvalid => Exit { fail, status: 2 },
_ => Exit::from(fail),
}
}
fn read(file: &str) -> Result<String, Exit> {
let mut text = String::new();
let outcome = if file == "-" {
io::stdin().lock().read_to_string(&mut text).map(|_| ())
} else {
std::fs::read_to_string(file).map(|read| text = read)
};
outcome.map_err(|error| Exit {
fail: Fail::input(format!("cannot read {file}: {error}")),
status: 2,
})?;
Ok(text)
}
fn open(file: &str) -> Result<Box<dyn Read + Send>, Exit> {
if file == "-" {
return Ok(Box::new(io::stdin()));
}
match std::fs::File::open(file) {
Ok(opened) => Ok(Box::new(opened)),
Err(error) => Err(Exit {
fail: Fail::input(format!("cannot read {file}: {error}")),
status: 2,
}),
}
}
fn unreadable(file: &str, fail: Fail) -> Exit {
match fail.message.strip_prefix("unreadable: ") {
Some(reason) if fail.code == Code::InputInvalid => {
let cannot = Fail::input(format!("cannot read {file}: {reason}"));
Exit {
fail: if fail.committed_output {
cannot.committed()
} else {
cannot
},
status: 2,
}
}
_ => Exit::from(fail),
}
}
fn run(args: &[String]) -> Result<String, Exit> {
let (command, rest) = args.split_first().ok_or_else(usage)?;
match command.as_str() {
"canon" | "format" | "check" | "explain" => {
let [file] = rest else {
return Err(usage());
};
let source = Source::new(file.as_str(), read(file)?);
Ok(match command.as_str() {
"canon" => canon(&source)?,
"format" => tabnas_dmog::format(&source)?,
"check" => check(&source).map(|()| String::new())?,
_ => explain(&source)?,
})
}
"run" => {
let options = RunOptions::parse(rest)?;
let source = Source::new(options.program.as_str(), read(&options.program)?);
let program = Program::new(
source,
ProgramOptions {
render: options.render,
grammar: options.grammar,
limits: Limits {
max_output_bytes: options.max_output_bytes,
..default_limits()
},
},
)?;
let input = open(&options.input)?;
program
.run(input, io::stdout())
.map_err(|fail| unreadable(&options.input, fail))?;
Ok(String::new())
}
"translate" => {
let args = TranslateArgs::parse(rest)?;
let mut options = TranslateOptions::new(&args.from, &args.to);
options.path = args.path;
options.key = args.key;
options.whole = args.whole;
options.limits.max_output_bytes = args.max_output_bytes;
options.validate().map_err(refused_option)?;
if let Some(file) = &args.program {
options.with = Some(Source::new(file.as_str(), read(file)?));
}
let translation = Translation::new(options)?;
let input = open(&args.input)?;
translation
.run(input, io::stdout())
.map_err(|fail| unreadable(&args.input, fail))?;
Ok(String::new())
}
"formats" => {
if !rest.is_empty() {
return Err(usage());
}
Ok(formats_json() + "\n")
}
_ => Err(usage()),
}
}
fn bytes(n: &str) -> Result<u64, Exit> {
n.parse::<u64>().map_err(|_| Exit {
fail: Fail::input(format!(
"--max-output-bytes takes a number of bytes, not {n:?}"
)),
status: 2,
})
}
fn names(ids: &[String]) -> String {
match ids.split_last() {
Some((last, [])) => last.clone(),
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
None => String::new(),
}
}
struct TranslateArgs {
from: String,
to: String,
path: Option<String>,
key: Option<String>,
program: Option<String>,
whole: bool,
max_output_bytes: Option<u64>,
input: String,
}
impl TranslateArgs {
fn parse(args: &[String]) -> Result<TranslateArgs, Exit> {
let named = |option: &str, id: String| {
let ids: Vec<String> = formats().into_iter().map(|format| format.id).collect();
if ids.contains(&id) {
return Ok(id);
}
Err(Exit {
fail: Fail::input(format!("{option} takes {}, not {id:?}", names(&ids))),
status: 2,
})
};
let (mut from, mut to, mut path, mut key, mut program, mut max_output_bytes) =
(None, None, None, None, None, None);
let mut whole = false;
let mut files = Vec::new();
let mut i = 0;
while i < args.len() {
let value = || args.get(i + 1).cloned().ok_or_else(usage);
match args[i].as_str() {
"--whole" => {
whole = true;
i += 1;
continue;
}
"--from" => from = Some(named("--from", value()?)?),
"--to" => to = Some(named("--to", value()?)?),
"--path" => path = Some(value()?),
"--key" => key = Some(value()?),
"--with" => program = Some(value()?),
"--max-output-bytes" => max_output_bytes = Some(bytes(&value()?)?),
other if other.starts_with("--") => return Err(usage()),
other => {
files.push(other.to_string());
i += 1;
continue;
}
}
i += 2;
}
let (Some(from), Some(to), [input]) = (from, to, files.as_slice()) else {
return Err(usage());
};
if program.as_deref() == Some("-") && input == "-" {
return Err(Exit {
fail: Fail::input("only one of PROGRAM and INPUT may be - (standard input)"),
status: 2,
});
}
Ok(TranslateArgs {
from,
to,
path,
key,
program,
whole,
max_output_bytes,
input: input.clone(),
})
}
}
struct RunOptions {
grammar: Option<String>,
render: Option<Render>,
max_output_bytes: Option<u64>,
program: String,
input: String,
}
impl RunOptions {
fn parse(args: &[String]) -> Result<RunOptions, Exit> {
let mut grammar = None;
let mut render = None;
let mut max_output_bytes = None;
let mut files = Vec::new();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--grammar" => {
let name = args.get(i + 1).ok_or_else(usage)?;
let parsed = parsed_formats();
if !parsed.contains(name) {
return Err(Exit {
fail: Fail::input(format!(
"--grammar takes a format whose documents are parsed ({}), not \
{name:?}",
names(&parsed)
)),
status: 2,
});
}
grammar = Some(name.clone());
i += 2;
}
"--render" => {
let name = args.get(i + 1).ok_or_else(usage)?;
render = Some(match name.as_str() {
"csv" => Render::Csv,
"json" => Render::Json,
_ => {
return Err(Exit {
fail: Fail::input(format!(
"--render takes csv or json, not {name:?}"
)),
status: 2,
})
}
});
i += 2;
}
"--max-output-bytes" => {
let n = args.get(i + 1).ok_or_else(usage)?;
max_output_bytes = Some(bytes(n)?);
i += 2;
}
other if other.starts_with("--") => return Err(usage()),
other => {
files.push(other.to_string());
i += 1;
}
}
}
let [program, input] = files.as_slice() else {
return Err(usage());
};
if program == "-" && input == "-" {
return Err(Exit {
fail: Fail::input("only one of PROGRAM and INPUT may be - (standard input)"),
status: 2,
});
}
Ok(RunOptions {
grammar,
render,
max_output_bytes,
program: program.clone(),
input: input.clone(),
})
}
}