sokf_core/graph/locate.rs
1//! `locate` turns ids into absolute filesystem paths (CLI-8).
2
3use std::path::PathBuf;
4
5use schemars::JsonSchema;
6use serde::Serialize;
7
8use super::resolve_id;
9use crate::{Error, Model, Result, model::KeyIndex};
10
11/// A `Location` records where one id's document is, and where its asset is when
12/// the document is a sidecar.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Location {
15 /// The id.
16 pub id: String,
17 /// The document's filesystem path.
18 pub path: PathBuf,
19 /// The asset's filesystem path, for a sidecar.
20 pub asset: Option<PathBuf>,
21}
22
23/// The report of `sokf locate --json`: one entry for each id, in argument order
24/// (CLI-8_AC-5).
25// `LocateReport` is a wire type: `sokf locate --json` prints its report with
26// this type, and the `output_schema` module generates the published JSON schema,
27// `locate-report.schema.json`, from it.
28#[derive(Serialize, JsonSchema)]
29#[serde(transparent)]
30#[schemars(title = "sokf locate report")]
31pub struct LocateReport(Vec<LocateEntry>);
32
33/// A location entry holds one id and where its document is.
34#[derive(Serialize, JsonSchema)]
35#[schemars(rename = "Location")]
36struct LocateEntry {
37 /// The id, as given.
38 id: String,
39 /// The absolute filesystem path of the document.
40 path: String,
41 /// The absolute filesystem path of the asset, when the document is a sidecar: a
42 /// document that describes a separate file, the asset.
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 #[schemars(with = "String")]
45 asset: Option<String>,
46}
47
48impl From<&[Location]> for LocateReport {
49 fn from(located: &[Location]) -> Self {
50 LocateReport(
51 located
52 .iter()
53 .map(|l| LocateEntry {
54 id: l.id.clone(),
55 path: l.path.display().to_string(),
56 asset: l.asset.as_ref().map(|a| a.display().to_string()),
57 })
58 .collect(),
59 )
60 }
61}
62
63/// `locate` returns the filesystem paths of each id, in argument order. If an
64/// id doesn't resolve, the whole call fails. With `asset`, the call also fails
65/// if an id's document isn't a sidecar.
66// sokf-implements: CLI-8_AC-1
67// sokf-implements: CLI-8_AC-4
68// sokf-implements: CLI-8_AC-2
69// sokf-implements: CLI-8_AC-3
70// sokf-implements: CLI-8_AC-7
71pub fn locate(
72 model: &Model,
73 keys: Option<&KeyIndex>,
74 ids: &[String],
75 asset: bool,
76) -> Result<Vec<Location>> {
77 ids.iter()
78 .map(|id| {
79 let path = resolve_id(model, keys, id)?;
80 let asset_path = model
81 .asset_of(&path)
82 .map(|(_, a)| a.path.to_fs(&model.tree.root));
83 if asset && asset_path.is_none() {
84 return Err(Error::Locate(format!(
85 "`{id}` identifies {path}, which is not a sidecar and has no asset"
86 )));
87 }
88 Ok(Location {
89 id: id.clone(),
90 path: path.to_fs(&model.tree.root),
91 asset: asset_path,
92 })
93 })
94 .collect()
95}