use std::path::PathBuf;
use schemars::JsonSchema;
use serde::Serialize;
use super::resolve_id;
use crate::{Error, Model, Result, model::KeyIndex};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Location {
pub id: String,
pub path: PathBuf,
pub asset: Option<PathBuf>,
}
#[derive(Serialize, JsonSchema)]
#[serde(transparent)]
#[schemars(title = "sokf locate report")]
pub struct LocateReport(Vec<LocateEntry>);
#[derive(Serialize, JsonSchema)]
#[schemars(rename = "Location")]
struct LocateEntry {
id: String,
path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
asset: Option<String>,
}
impl From<&[Location]> for LocateReport {
fn from(located: &[Location]) -> Self {
LocateReport(
located
.iter()
.map(|l| LocateEntry {
id: l.id.clone(),
path: l.path.display().to_string(),
asset: l.asset.as_ref().map(|a| a.display().to_string()),
})
.collect(),
)
}
}
pub fn locate(
model: &Model,
keys: Option<&KeyIndex>,
ids: &[String],
asset: bool,
) -> Result<Vec<Location>> {
ids.iter()
.map(|id| {
let path = resolve_id(model, keys, id)?;
let asset_path = model
.asset_of(&path)
.map(|(_, a)| a.path.to_fs(&model.tree.root));
if asset && asset_path.is_none() {
return Err(Error::Locate(format!(
"`{id}` identifies {path}, which is not a sidecar and has no asset"
)));
}
Ok(Location {
id: id.clone(),
path: path.to_fs(&model.tree.root),
asset: asset_path,
})
})
.collect()
}