use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use clap::Parser;
use litcheck_filecheck::litcheck::diagnostics::{
FileName, Report, SourceFile, SourceLanguage, SourceManager, SourceManagerExt,
};
use litcheck_filecheck::litcheck::reporting::PrintDiagnostic;
use litcheck_filecheck::litcheck::Symbol;
use litcheck_filecheck::{Config, Dump, Options, Test, TestFailed};
use crate::shell::{ShellCommandHandler, ShellCommandOutput};
#[derive(Debug, Parser)]
#[command(
name = "FileCheck",
version,
about = "Checks text against directives in a file",
override_usage = "FileCheck [OPTIONS] <CHECK-FILE>",
no_binary_name = true,
args_override_self = true
)]
struct Invocation {
#[command(flatten)]
options: Options,
#[arg(value_name = "CHECK-FILE")]
check_file: Option<PathBuf>,
#[arg(long, value_name = "FILENAME", default_value = "-")]
input_file: PathBuf,
}
#[derive(Debug, Default)]
pub(crate) struct FileCheckCommand;
impl ShellCommandHandler for FileCheckCommand {
fn execute(
&self,
args: &[String],
stdin: &[u8],
cwd: &Path,
environment: &HashMap<String, String>,
) -> Result<ShellCommandOutput, String> {
let explicit_args = args.get(1..).unwrap_or_default();
let mut arguments = match environment.get("FILECHECK_OPTS") {
Some(value) => match shlex::split(value) {
Some(arguments) => arguments,
None => {
return Ok(error_output(
"FILECHECK_OPTS contains an unterminated quote",
));
}
},
None => Vec::new(),
};
arguments.extend_from_slice(explicit_args);
normalize_option_spellings(&mut arguments);
let invocation = match Invocation::try_parse_from(arguments) {
Ok(invocation) => invocation,
Err(error) => return Ok(clap_output(error)),
};
if invocation.options.dump_input == Dump::Help {
return Ok(ShellCommandOutput {
stdout: format!("{}\n", Dump::HELP).into_bytes(),
..ShellCommandOutput::default()
});
}
let Some(check_file) = invocation.check_file else {
return Ok(error_output("CHECK-FILE is required"));
};
if let Some(duplicate) = duplicate_prefix(&invocation.options.check_prefixes) {
return Ok(error_output(format!(
"check prefix '{duplicate}' is specified more than once"
)));
}
if let Some(duplicate) = duplicate_prefix(&invocation.options.comment_prefixes) {
return Ok(error_output(format!(
"comment prefix '{duplicate}' is specified more than once"
)));
}
if let Err(report) = invocation.options.validate() {
return Ok(report_output(&report, 2));
}
if check_file == Path::new("-") && invocation.input_file == Path::new("-") {
return Ok(error_output(
"CHECK-FILE and input cannot both read standard input",
));
}
let config = Config {
options: invocation.options,
..Config::default()
};
let checks = match load_source(config.source_manager(), &check_file, stdin, cwd) {
Ok(source) => source,
Err(message) => return Ok(error_output(message)),
};
let input = match load_source(config.source_manager(), &invocation.input_file, stdin, cwd) {
Ok(source) => source,
Err(message) => return Ok(error_output(message)),
};
let mut test = Test::new(checks, &config);
match test.verify(input) {
Ok(_) => Ok(ShellCommandOutput::default()),
Err(report) => {
let exit_code = if report.downcast_ref::<TestFailed>().is_some() {
1
} else {
2
};
Ok(report_output(&report, exit_code))
}
}
}
}
fn normalize_option_spellings(arguments: &mut [String]) {
for argument in arguments {
let Some(spelling) = argument
.strip_prefix('-')
.filter(|spelling| !spelling.starts_with('-'))
else {
continue;
};
let name = spelling.split_once('=').map_or(spelling, |(name, _)| name);
if matches!(
name,
"allow-empty"
| "allow-unused-prefixes"
| "check-prefix"
| "check-prefixes"
| "color"
| "comment-prefix"
| "comment-prefixes"
| "define"
| "dump-input"
| "dump-input-filter"
| "enable-var-scope"
| "help"
| "ignore-case"
| "implicit-check-not"
| "input-file"
| "match-full-lines"
| "strict-whitespace"
| "verbose"
| "version"
) {
argument.insert(0, '-');
}
}
}
fn duplicate_prefix(prefixes: &[Symbol]) -> Option<Symbol> {
prefixes
.iter()
.enumerate()
.find_map(|(index, prefix)| prefixes[..index].contains(prefix).then_some(*prefix))
}
fn clap_output(error: clap::Error) -> ShellCommandOutput {
let exit_code = error.exit_code();
let rendered = error.to_string().into_bytes();
if error.use_stderr() {
ShellCommandOutput {
stderr: rendered,
exit_code,
..ShellCommandOutput::default()
}
} else {
ShellCommandOutput {
stdout: rendered,
exit_code,
..ShellCommandOutput::default()
}
}
}
fn error_output(message: impl std::fmt::Display) -> ShellCommandOutput {
ShellCommandOutput {
stderr: format!("FileCheck: {message}\n").into_bytes(),
exit_code: 2,
..ShellCommandOutput::default()
}
}
fn report_output(report: &Report, exit_code: i32) -> ShellCommandOutput {
let mut stderr = PrintDiagnostic::narrated(report).to_string().into_bytes();
if !stderr.ends_with(b"\n") {
stderr.push(b'\n');
}
ShellCommandOutput {
stderr,
exit_code,
..ShellCommandOutput::default()
}
}
fn load_source(
source_manager: &dyn SourceManager,
path: &Path,
stdin: &[u8],
cwd: &Path,
) -> Result<Arc<SourceFile>, String> {
if path == Path::new("-") {
let content = String::from_utf8(stdin.to_vec())
.map_err(|_| "standard input is not valid UTF-8".to_string())?;
return Ok(source_manager.load(SourceLanguage::Unknown, FileName::Stdin, content));
}
let path = if path.is_absolute() {
path.to_path_buf()
} else {
cwd.join(path)
};
source_manager
.load_file(&path)
.map_err(|error| match std::error::Error::source(&error) {
Some(source) => format!("cannot load '{}': {source}", path.display()),
None => format!("cannot load '{}': {error}", path.display()),
})
}