use owo_colors::OwoColorize;
use crate::conversion::{get_conv_dft, serialisation::deser_toml, ConvFmt};
use std::{
borrow::Cow,
ffi::OsStr,
path::{Path, PathBuf},
};
pub(crate) const FORMATS: [&str; 9] = [
"toml", "yaml", "yml", "json", "ron", "bson", "sexp", "xml", "json5",
];
#[cfg(all(feature = "xml", feature = "json"))]
use crate::conversion::serialisation::deser_xml;
#[cfg(feature = "json")]
use crate::conversion::serialisation::deser_json;
#[cfg(feature = "json5")]
use crate::conversion::serialisation::deser_json5;
#[cfg(feature = "ron")]
use crate::conversion::serialisation::deser_ron;
#[cfg(feature = "yaml")]
use crate::conversion::serialisation::deser_yaml;
impl<'fmt, 'dst, 'src: 'dst> ConvFmt<'fmt, 'dst, 'src> {
pub(crate) fn new<P: Into<PathBuf>>(
src: &'src Path,
src_fmt: &'fmt str,
dst_fmt: &'fmt str,
dst: P,
save: bool,
) -> Self {
Self {
src: Cow::from(src),
src_fmt,
dst_fmt,
dst: Cow::from(dst.into()),
save,
}
}
}
pub(crate) fn auto_detect_unknown_fmt(s: &str) -> &'static str {
match s.trim_start() {
s if deser_toml(s).is_ok() => "toml",
#[cfg(feature = "json")]
s if deser_json(s).is_ok() => "json",
#[cfg(feature = "json5")]
s if deser_json5(s).is_ok() => "json5",
#[cfg(feature = "yaml")]
s if deser_yaml(s).is_ok() => "yaml",
#[cfg(feature = "ron")]
s if deser_ron(s).is_ok() => "ron",
#[cfg(all(feature = "xml", feature = "json"))]
s if deser_xml(s).is_ok() => "xml",
_ => {
log::error!("{}", get_conv_dft("unknown-fmt"));
log::error!("{}: {:?}", get_conv_dft("currently-supported"), FORMATS);
panic!("{}", get_conv_dft("auto-detection-failed"))
}
}
}
pub(crate) fn yml_is_yaml(s: &str) -> &str {
if s == "yml" {
"yaml"
} else {
s
}
}
pub(crate) fn get_src_format(src: &Path) -> &str {
match src
.extension()
.and_then(|o| o.to_str())
{
Some(s) if FORMATS.contains(&s) => yml_is_yaml(s),
_ => {
log::warn!(
"Unknown format, file name: {:?}",
src.file_name()
.unwrap_or_else(|| OsStr::new("UNKNOWN"))
);
log::warn!("Attempting to automatically detect the file format. If detection fails, please specify the format manually.");
""
}
}
}
pub(crate) fn get_diff_dst_format(src_fmt: &str) -> &str {
match src_fmt {
"json5" => "json",
"toml" => "yaml",
"yaml" => "json",
_ => "toml",
}
}
pub(crate) fn get_different_file_format(s: &str) -> &str {
get_diff_dst_format(check_supported_formats(s))
}
pub(super) fn check_supported_formats(ext: &str) -> &str {
FORMATS
.iter()
.find(|&&x| x == ext)
.copied()
.unwrap_or_else(|| {
log::warn!("{}: {}", get_conv_dft("unknown-fmt"), ext.purple());
""
})
}
pub(super) fn trim_unknown_fmt(ext: &str) -> Option<&str> {
let trimmed = match ext.len() {
0..=2 => ext,
3..=4 => &ext[..1],
_ => &ext[..2],
};
FORMATS
.iter()
.find(|&&x| x.starts_with(trimmed))
.copied()
}