use clap::ValueEnum;
use eure::query::{TextFile, TextFileContent};
use eure::query_flow::{DurabilityLevel, Query, QueryError, QueryRuntime};
use eure::report::{ErrorReports, format_error_reports};
use std::fs;
use std::io::{self, Read};
pub fn read_input(file: Option<&str>) -> Result<String, String> {
match file {
None | Some("-") => {
let mut buffer = String::new();
io::stdin()
.read_to_string(&mut buffer)
.map_err(|e| format!("Error reading from stdin: {e}"))?;
Ok(buffer)
}
Some(path) => fs::read_to_string(path).map_err(|e| format!("Error reading file: {e}")),
}
}
pub fn display_path(file: Option<&str>) -> &str {
file.unwrap_or("<stdin>")
}
#[derive(ValueEnum, Clone, Debug)]
pub enum VariantFormat {
External,
Internal,
Adjacent,
Untagged,
}
pub fn handle_query_error(runtime: &QueryRuntime, e: QueryError) -> ! {
if let Some(reports) = e.downcast_ref::<ErrorReports>() {
eprintln!(
"{}",
format_error_reports(runtime, reports, true).expect("file content should be loaded")
);
} else {
eprintln!("Error: {e}");
}
std::process::exit(1);
}
pub fn run_query_with_file_loading<Q, R>(
runtime: &QueryRuntime,
query: Q,
) -> Result<std::sync::Arc<R>, QueryError>
where
Q: Query<Output = R> + Clone,
{
loop {
match runtime.query(query.clone()) {
Ok(result) => return Ok(result),
Err(QueryError::Suspend { .. }) => {
for pending in runtime.pending_assets() {
if let Some(file) = pending.key::<TextFile>() {
let content = match fs::read_to_string(&*file.path) {
Ok(c) => TextFileContent::Content(c),
Err(_) => TextFileContent::NotFound,
};
runtime.resolve_asset(file.clone(), content, DurabilityLevel::Static);
}
}
}
Err(e) => return Err(e),
}
}
}