#![allow(dead_code)]
#![allow(clippy::result_large_err)]
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::OnceLock;
use serde_json::Value as Json;
use tabnas::{Tabnas, Value};
use tabnas_multisource::{
multisource, MapResolver, MultiSourceOptions, ProcessorInput, Resolution,
};
use tabnas_support::Failure;
pub fn make_with(options: MultiSourceOptions) -> Tabnas {
let mut parser = tabnas_jsonic::make();
multisource(&mut parser, options).expect("the MultiSource plugin installs on jsonic");
parser
}
pub fn make() -> Tabnas {
make_with(MultiSourceOptions::default())
}
pub fn json_processor(resolution: &mut Resolution, _input: &ProcessorInput<'_>) {
let Some(src) = resolution.src.clone() else {
resolution.val = Value::Undefined;
return;
};
match strict_json().parse(&src) {
Ok(value) => resolution.val = value,
Err(error) => {
resolution.val = Value::String(src);
resolution.err = Some(Box::new(error));
}
}
}
fn strict_json() -> &'static Tabnas {
static PARSER: OnceLock<Tabnas> = OnceLock::new();
PARSER.get_or_init(tabnas_jsonic::make_json)
}
pub fn with_json(options: MultiSourceOptions) -> MultiSourceOptions {
options.with_processor("json", json_processor)
}
pub fn repo_root() -> &'static Path {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("rs/ has a parent")
}
pub fn scratch_dir(label: &str) -> std::path::PathBuf {
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!(
"tabnas-multisource-{label}-{}-{:?}-{}",
std::process::id(),
std::thread::current().id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("a scratch folder");
dir
}
pub fn cwd_scratch_dir(label: &str) -> (std::path::PathBuf, String) {
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT: AtomicUsize = AtomicUsize::new(0);
let relative = format!(
"target/scratch/{label}-{}-{:?}-{}",
std::process::id(),
std::thread::current().id(),
NEXT.fetch_add(1, Ordering::Relaxed)
);
let absolute = std::env::current_dir()
.expect("a working directory")
.join(&relative);
let _ = std::fs::remove_dir_all(&absolute);
std::fs::create_dir_all(&absolute).expect("a scratch folder");
(absolute, relative)
}
pub fn parser_for(options: &Json) -> Result<Tabnas, Failure> {
let mut sources: BTreeMap<String, String> = BTreeMap::new();
if let Some(entries) = options.get("mem").and_then(Json::as_object) {
for (path, content) in entries {
if let Some(content) = content.as_str() {
sources.insert(path.clone(), content.to_string());
}
}
}
let mut parser = make_with(with_json(MultiSourceOptions::new(MapResolver::from_map(
sources,
))));
if let Some(engine) = options.get("options") {
apply_spec_options(&mut parser, engine)?;
}
Ok(parser)
}
fn apply_spec_options(parser: &mut Tabnas, engine: &Json) -> Result<(), Failure> {
if let Some(extend) = engine.pointer("/map/extend").and_then(Json::as_bool) {
parser
.set_options(|options| options.map.extend = extend)
.map_err(|error| Failure::message(format!("spec options: {error}")))?;
return Ok(());
}
Err(Failure::message(format!(
"spec options not supported by the runner: {engine}"
)))
}
pub fn to_json(value: &Value) -> Json {
canon(value.to_json())
}
pub fn canon(value: Json) -> Json {
match value {
Json::Number(number) => match number.as_f64() {
Some(number) => serde_json::Number::from_f64(number)
.map(Json::Number)
.unwrap_or(Json::Null),
None => Json::Null,
},
Json::Array(items) => Json::Array(items.into_iter().map(canon).collect()),
Json::Object(entries) => Json::Object(
entries
.into_iter()
.map(|(key, item)| (key, canon(item)))
.collect(),
),
other => other,
}
}
pub fn to_failure(error: tabnas::TabnasError) -> Failure {
Failure::new(error.code.clone())
.at(error.row, error.col)
.with_message(error.to_string())
}