use super::*;
use pikopiko::report::tone::{self, Category};
use pikopiko::synth::tones::user::{pick_description, UserLibrary, WithLibraries};
const RATE: u32 = 44_100;
const GAIN_TOLERANCE_DB: f32 = 0.5;
struct Finding {
error: bool,
at: String,
message: String,
}
pub(crate) fn library_check(lib: &UserLibrary, json: bool) -> Result<ExitCode, String> {
let lang = i18n().lang().to_string();
let mut found: Vec<Finding> = Vec::new();
let root = format!("@{}", lib.name);
if lib.clashes(pikopiko::synth::all()) {
add(&mut found, true, &root, "cli-check-clash", &[]);
}
if pick_description(&lib.description, &lang).is_empty() {
add(&mut found, false, &root, "cli-check-no-description", &[]);
}
let spec = pikopiko::synth::find(pikopiko::synth::all(), &lib.synth);
if spec.is_none() {
let names: Vec<&str> = pikopiko::synth::all().iter().map(|s| s.name).collect();
add(
&mut found,
true,
&root,
"cli-check-no-synth",
&[
("synth", lib.synth.clone().into()),
("names", names.join(", ").into()),
],
);
}
let loader = WithLibraries::new(None, std::slice::from_ref(lib));
let opts = CompileOptions {
synths: pikopiko::synth::all(),
include: Some(&loader),
..Default::default()
};
let mut seen: Vec<String> = Vec::new();
let mut checked = 0usize;
for kind in &lib.kinds {
let file = format!("@{}/{}", lib.name, kind.name);
if pick_description(&kind.description, &lang).is_empty() {
add(&mut found, false, &file, "cli-check-no-description", &[]);
}
let category = Category::from_name(&kind.name);
if category.is_none() {
let names: Vec<&str> = tone::ALL.iter().map(|c| c.name()).collect();
add(
&mut found,
false,
&file,
"cli-check-unknown-kind",
&[("names", names.join(", ").into())],
);
}
for t in kind.tones() {
let at = format!("{file} ${}", t.name);
checked += 1;
if seen.contains(&t.name) {
add(&mut found, true, &at, "cli-check-dup-tone", &[]);
} else {
seen.push(t.name.clone());
}
let (Some(spec), Some(cat)) = (spec, category) else {
let mml = format!("#synth {}\n#include \"{file}\"\nA ${} c", lib.synth, t.name);
let (song, diags) = pikopiko::compile_with(&mml, &opts);
if song.is_none() {
add_compile_error(&mut found, &at, &mml, &diags);
}
continue;
};
let mml =
tone::audition_mml(cat, spec.name, &format!("#include \"{file}\"\n${}", t.name));
let (song, diags) = pikopiko::compile_with(&mml, &opts);
let Some(song) = song else {
add_compile_error(&mut found, &at, &mml, &diags);
continue;
};
let mut r = tone::report(cat, &song, mml, RATE);
pikopiko::synth::tones::compare(&mut r, spec, RATE, 1);
for d in &r.deviations {
let range = format!(
"{}〜{}",
d.min.map_or(String::new(), |v| v.to_string()),
d.max.map_or(String::new(), |v| v.to_string())
);
found.push(Finding {
error: false,
at: at.clone(),
message: ta(
"cli-tone-out",
&[
("metric", d.metric.name().into()),
("value", d.value.to_string().into()),
("range", range.into()),
],
),
});
}
if let (Some(db), Some(gain)) = (r.gain_db, r.gain) {
if db.abs() > GAIN_TOLERANCE_DB {
found.push(Finding {
error: false,
at: at.clone(),
message: ta(
"cli-check-gain",
&[
("db", format!("{db:+.1}").into()),
("gain", gain.to_string().into()),
],
),
});
}
}
if let Some(s) = r.similar.first().filter(|s| s.too_close) {
found.push(Finding {
error: false,
at: at.clone(),
message: ta(
"cli-check-too-close",
&[
("name", s.name.clone().into()),
("distance", format!("{:.3}", s.distance).into()),
],
),
});
}
}
}
let errors = found.iter().filter(|f| f.error).count();
let warnings = found.len() - errors;
if json {
let all: Vec<serde_json::Value> = found
.iter()
.map(|f| {
serde_json::json!({
"level": if f.error { "error" } else { "warning" },
"at": f.at,
"message": f.message,
})
})
.collect();
println!(
"{}",
serde_json::to_string_pretty(&all).map_err(json_error)?
);
} else {
for f in &found {
let level = t(if f.error {
"cli-check-level-error"
} else {
"cli-check-level-warning"
});
println!("{level}: {}: {}", f.at, f.message);
}
println!(
"{}",
ta(
"cli-check-summary",
&[
("tones", checked.to_string().into()),
("errors", errors.to_string().into()),
("warnings", warnings.to_string().into()),
]
)
);
}
Ok(if errors > 0 {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
})
}
fn add(found: &mut Vec<Finding>, error: bool, at: &str, key: &str, args: &[(&str, Arg)]) {
found.push(Finding {
error,
at: at.to_string(),
message: ta(key, args),
});
}
fn add_compile_error(found: &mut Vec<Finding>, at: &str, mml: &str, diags: &[Diagnostic]) {
let first = diags.iter().find(|d| d.is_error());
let _ = mml;
found.push(Finding {
error: true,
at: at.to_string(),
message: ta(
"cli-check-compile",
&[(
"error",
first
.map(|d| i18n().diagnostic(d))
.unwrap_or_default()
.into(),
)],
),
});
}