Skip to main content

sokf_core/api/
info.rs

1//! This module implements the `sokf info` command (CLI-5).
2
3use std::collections::BTreeMap;
4
5use schemars::JsonSchema;
6use serde::Serialize;
7
8use crate::{
9    Cache, CacheMode, Error, RepoRoot, Result, config,
10    grammar::{self, FormatRegistry, RegexCache, TypeDef},
11    graph::yaml_json,
12    model::SchemaRef,
13};
14
15/// `InfoLayer` lists the values of the `--layer` option of `sokf info
16/// formats` (CLI-5).
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum InfoLayer {
19    /// `Embedded` selects the formats embedded in the tool, without those of
20    /// the repository.
21    Embedded,
22    /// `Repo` selects the formats of `/.sokf/formats.yaml`, without those of
23    /// the tool.
24    Repo,
25    /// `FormatsD` selects the formats of the files of `/.sokf/formats.d/`,
26    /// without those of the tool and of `/.sokf/formats.yaml`.
27    FormatsD,
28    /// `Effective` selects the formats of the tool, with the layer `formats.d`
29    /// and then the repository's formats merged on top, where a nearer layer's
30    /// format replaces a farther layer's format of the same name.
31    Effective,
32}
33
34/// `info_grammar` returns the schema language verbatim: the tramlines core
35/// grammar, then the tramlines-md grammar, and then the schema extension of
36/// SOKF.
37// sokf-implements: CLI-5_AC-1
38// sokf-implements: CLI-5_AC-2
39// sokf-implements: CLI-5_AC-12
40pub fn info_grammar() -> String {
41    grammar::grammar_text()
42}
43
44/// The registry of `sokf info formats --json`: the types and the formats of
45/// the registry that the command prints as YAML, in the shape of a formats
46/// file, each entry with its source (CLI-5_AC-38).
47// `FormatsJson` is a wire type: the `output_schema` module generates
48// `info-formats-registry.schema.json` from it.
49#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
50#[schemars(title = "sokf info formats registry")]
51pub struct FormatsJson {
52    /// The placeholder types, by name, an empty map where the registry
53    /// declares none.
54    pub types: BTreeMap<String, FormatType>,
55    /// The line formats, by name, an empty map where the registry holds
56    /// none.
57    pub registry: BTreeMap<String, FormatEntry>,
58}
59
60/// One placeholder type of the registry.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
62pub struct FormatType {
63    /// What the type matches: a regular expression, or a list of literal
64    /// choices.
65    #[serde(rename = "match")]
66    pub matches: TypeMatch,
67    /// Where the type comes from: `built-in`, `embedded`, `repo`, the path
68    /// of a file of `/.sokf/formats.d/`, or the id of a schema.
69    pub source: String,
70}
71
72/// What a placeholder type matches.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
74#[serde(untagged)]
75pub enum TypeMatch {
76    /// A regular expression with no anchors and no capture groups.
77    Regex(String),
78    /// Literal choices.
79    Choices(Vec<String>),
80}
81
82/// One line format of the registry: its keys as a formats file writes
83/// them, which the grammar `format` of `sokf info grammar` defines, such as
84/// `template`, `example`, and `variants`, and its source.
85#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
86pub struct FormatEntry {
87    /// The keys of the format as its formats file writes them, with a patch
88    /// merged onto the entry that it patches.
89    #[serde(flatten)]
90    pub entry: serde_json::Map<String, serde_json::Value>,
91    /// Where the format comes from: `embedded`, `repo`, the path of a file
92    /// of `/.sokf/formats.d/`, or the id of a schema.
93    pub source: String,
94}
95
96/// `formats_json` returns `registry` as the object of `--json`, with the
97/// built-in types where `built_ins` asks for them, as the YAML has them.
98// sokf-implements: CLI-5_AC-38
99// sokf-implements: CLI-5_AC-39
100fn formats_json(registry: &FormatRegistry, built_ins: bool) -> FormatsJson {
101    let types = if built_ins {
102        registry.types_seen()
103    } else {
104        registry.types.clone()
105    };
106    FormatsJson {
107        types: types
108            .entries
109            .iter()
110            .map(|(name, (def, source))| {
111                let matches = match def {
112                    TypeDef::Regex(r) => TypeMatch::Regex(r.clone()),
113                    TypeDef::Choices(c) => TypeMatch::Choices(c.clone()),
114                };
115                let source = source.label().into_owned();
116                (name.clone(), FormatType { matches, source })
117            })
118            .collect(),
119        registry: registry
120            .entries
121            .iter()
122            .map(|(name, (format, source))| {
123                let mut entry = match yaml_json(&format.raw) {
124                    serde_json::Value::Object(map) => map,
125                    _ => serde_json::Map::new(),
126                };
127                // The source replaces any key of that name, as in the YAML,
128                // so that the object holds the key once.
129                entry.retain(|key, _| key != "source");
130                let source = source.label().into_owned();
131                (name.clone(), FormatEntry { entry, source })
132            })
133            .collect(),
134    }
135}
136
137/// `info_formats` returns a format registry as YAML, from `registry`.
138// sokf-implements: CLI-5_AC-3
139// sokf-implements: CLI-5_AC-13
140pub fn info_formats(
141    root: Option<&RepoRoot>,
142    layer: InfoLayer,
143    schema: Option<&str>,
144    cache: CacheMode,
145) -> Result<String> {
146    let (formats, built_ins) = registry(root, layer, schema, cache)?;
147    Ok(formats.to_yaml(built_ins))
148}
149
150/// `info_formats_json` returns the format registry that `info_formats`
151/// prints as YAML, as the object of `--json`.
152pub fn info_formats_json(
153    root: Option<&RepoRoot>,
154    layer: InfoLayer,
155    schema: Option<&str>,
156    cache: CacheMode,
157) -> Result<FormatsJson> {
158    let (formats, built_ins) = registry(root, layer, schema, cache)?;
159    Ok(formats_json(&formats, built_ins))
160}
161
162/// `registry` returns a format registry, and whether its view prints the
163/// built-in types, which every view but the `Repo` layer does. When the
164/// caller gives `schema`, the registry holds the formats of that schema, and
165/// `registry` ignores `layer`. Each entry records the source it comes from.
166/// A call for any layer except `Embedded` needs `root`. A call that gives
167/// `schema` also needs `root`, because `registry` reads the knowledge
168/// through the cache to find the schema.
169// sokf-implements: CLI-5_AC-6
170// sokf-implements: CLI-5_AC-15
171// sokf-implements: CACHE-1_AC-27
172// sokf-implements: CLI-5_AC-4
173// sokf-implements: CLI-5_AC-5
174// sokf-implements: CLI-5_AC-7
175// sokf-implements: CLI-5_AC-8
176// sokf-implements: CLI-5_AC-10
177// sokf-implements: CLI-5_AC-11
178// sokf-implements: CLI-5_AC-14
179fn registry(
180    root: Option<&RepoRoot>,
181    layer: InfoLayer,
182    schema: Option<&str>,
183    cache: CacheMode,
184) -> Result<(FormatRegistry, bool)> {
185    let grammar = grammar::load_grammar()?;
186    let regexes = RegexCache::new();
187    if let Some(id) = schema {
188        let root = root.ok_or(Error::NoRepository)?;
189        let config = config::load_config(root)?;
190        let repo = config::load_repo_formats(root, &grammar, &regexes)?;
191        let cache = Cache::open(root, cache);
192        let mut model = super::load_for_lookup(root, &config, &cache)?;
193        super::admit_schema_by_id(&mut model, root, &cache, id)?;
194        // `info` checks no document with these compiled schemas, which list
195        // only the formats, so they hold sokf's English.
196        let compiled = grammar::compile_all(&model, grammar, &repo, crate::Texts::english());
197        let found: Vec<SchemaRef> = model
198            .knowledges
199            .iter()
200            .enumerate()
201            .filter_map(|(k, knowledge)| {
202                knowledge.schema_by_id(id).map(|i| SchemaRef {
203                    knowledge: k,
204                    index: i,
205                })
206            })
207            .collect();
208        let roots = |ks: &mut dyn Iterator<Item = usize>| -> String {
209            ks.map(|k| model.knowledges[k].root.as_str())
210                .collect::<Vec<_>>()
211                .join(", ")
212        };
213        let r = match found.as_slice() {
214            [] => {
215                return Err(Error::Info(format!(
216                    "schema `{id}` is not in any root. The roots are {}",
217                    roots(&mut (0..model.knowledges.len()))
218                )));
219            }
220            [one] => *one,
221            many => {
222                return Err(Error::Info(format!(
223                    "schema `{id}` is declared in more than one root: {}",
224                    roots(&mut many.iter().map(|r| r.knowledge))
225                )));
226            }
227        };
228        let Some(schema) = compiled.schema(r) else {
229            return Err(Error::Info(format!(
230                "schema `{id}` does not match the grammar. Run `sokf validate` to see the errors"
231            )));
232        };
233        return Ok((schema.core.core.formats.clone(), true));
234    }
235    let embedded = grammar::embedded_formats(&grammar, &regexes)?;
236    match layer {
237        InfoLayer::Embedded => Ok((embedded, true)),
238        InfoLayer::Repo => {
239            let root = root.ok_or(Error::NoRepository)?;
240            match config::load_repo_formats(root, &grammar, &regexes)?.repo {
241                Some(repo) => Ok((repo, false)),
242                None => Err(Error::Info(
243                    "the repository has no /.sokf/formats.yaml".into(),
244                )),
245            }
246        }
247        // sokf-implements: CLI-5_AC-42
248        // sokf-implements: CLI-5_AC-43
249        InfoLayer::FormatsD => {
250            let root = root.ok_or(Error::NoRepository)?;
251            match config::load_repo_formats(root, &grammar, &regexes)?.folder_layer() {
252                Some(folder) => Ok((folder, false)),
253                None => Err(Error::Info(format!(
254                    "/{}/ holds no file *.yaml",
255                    config::FORMATS_DIR
256                ))),
257            }
258        }
259        InfoLayer::Effective => {
260            let root = root.ok_or(Error::NoRepository)?;
261            let formats = config::load_repo_formats(root, &grammar, &regexes)?;
262            Ok((formats.effective(&embedded), true))
263        }
264    }
265}