use super::*;
fn file_want(want: Option<&str>) -> Option<&str> {
want.and_then(|w| w.split_once('/')).map(|(_, f)| f)
}
fn self_file(want: Option<&str>, file: &str) -> bool {
want.is_some_and(|f| !file.ends_with(&format!("/{f}")))
}
pub(crate) fn library(
library: Option<&str>,
json: bool,
user: &[pikopiko::synth::tones::user::UserLibrary],
) -> Result<(), String> {
let tr = i18n();
let list = synth_catalog_with(pikopiko::synth::all(), tr.lang(), &mut |k| {
tr.override_text(k)
});
let want = library.map(|l| l.strip_prefix('@').unwrap_or(l));
let (synth, file) = match want {
Some(w) => match w.split_once('/') {
Some((s, f)) => (Some(s), Some(f)),
None => (Some(w), None),
},
None => (None, None),
};
let mut found = Vec::new();
for c in list.iter().filter(|c| !c.library.is_empty()) {
if synth.is_some_and(|s| s != c.name && !c.aliases.contains(&s)) {
continue;
}
for t in &c.library {
if file.is_some_and(|f| t.file != format!("@{}/{f}", c.name)) {
continue;
}
found.push(t);
}
}
let lang = tr.lang();
let mut mine: Vec<(String, String, String, String)> = Vec::new();
for lib in user {
if synth.is_some_and(|s| s != lib.name) {
continue;
}
for k in &lib.kinds {
let file = format!("@{}/{}", lib.name, k.name);
if self_file(file_want(want), &file) {
continue;
}
let desc = pikopiko::synth::tones::user::pick_description(&k.description, lang);
for t in k.tones() {
mine.push((file.clone(), t.kind, t.name, desc.to_string()));
}
}
}
if found.is_empty() && mine.is_empty() {
if let Some(l) = library {
let names: Vec<String> = list
.iter()
.flat_map(|c| c.library.iter().map(|t| t.file.clone()))
.chain(user.iter().flat_map(|u| {
u.kinds
.iter()
.map(|k| format!("@{}/{}", u.name, k.name))
.collect::<Vec<_>>()
}))
.fold(Vec::new(), |mut v, f| {
if !v.contains(&f) {
v.push(f);
}
v
});
return Err(ta(
"cli-err-unknown-library",
&[("name", l.into()), ("names", names.join(", ").into())],
));
}
}
if json {
let mut all: Vec<serde_json::Value> = found
.iter()
.filter_map(|t| serde_json::to_value(t).ok())
.collect();
all.extend(mine.iter().map(|(file, kind, name, description)| {
serde_json::json!({
"name": name,
"kind": kind,
"file": file,
"description": description,
"source": "user",
})
}));
println!("{}", serde_json::to_string_pretty(&all).unwrap_or_default());
return Ok(());
}
let mut last = String::new();
for t in &found {
if t.file != last {
if !last.is_empty() {
println!();
}
println!("#include \"{}\"", t.file);
last = t.file.clone();
}
println!(" [{}] ${}: {}", t.kind, t.name, t.description);
}
if !mine.is_empty() {
if !found.is_empty() {
println!();
}
println!("; {}", t("cli-library-user-header"));
let mut last = String::new();
for (file, kind, name, desc) in &mine {
if *file != last {
println!("#include \"{file}\"");
last = file.clone();
}
println!(" [{kind}] ${name}: {desc}");
}
}
Ok(())
}