Skip to main content

sokf_core/api/
new.rs

1//! This module implements `sokf new` (CLI-6).
2
3use std::{collections::BTreeMap, path::PathBuf};
4
5use schemars::JsonSchema;
6use serde::Serialize;
7
8use crate::{
9    Cache, CacheMode, Error, Model, PathArg, RepoPath, RepoRoot, Result, config,
10    grammar::{self, SokfSchema},
11    markdown::{is_slug, split_store},
12    scaffold,
13};
14
15/// `NewOptions` holds the options of `sokf new`.
16#[derive(Debug, Clone)]
17pub struct NewOptions {
18    /// `type_name` is the value of `TYPE`.
19    pub type_name: String,
20    /// `slug` is the value of `--slug`.
21    pub slug: Option<String>,
22    /// `id` is the value of `--id`.
23    pub id: Option<String>,
24    /// `title` is the value of `--title`.
25    pub title: Option<String>,
26    /// `seq` is the value of `--seq`, the sequence number that the id takes
27    /// in place of the next one.
28    pub seq: Option<u64>,
29    /// `states` holds the values of `--state`, each a key and a state, in the
30    /// order of the arguments.
31    pub states: Vec<(String, String)>,
32    /// `dir` is the value of `--dir`, as a path in the repository or a path
33    /// relative to `cwd`.
34    pub dir: Option<PathBuf>,
35    /// `for_asset` is the value of `--for`, as a path in the repository or a
36    /// path relative to `cwd`.
37    pub for_asset: Option<PathBuf>,
38    /// `cwd` is the current directory, from which a relative `--dir` or
39    /// `--for` resolves.
40    pub cwd: PathBuf,
41    /// `write` is true when the command has `--write`.
42    pub write: bool,
43    /// `id_only` is true when the command has `--id-only`.
44    pub id_only: bool,
45    /// `cache` is the cache mode.
46    pub cache: CacheMode,
47}
48
49/// `NewResult` is the report of `sokf new --json`: it holds the document that
50/// the command builds. Without `--write`, the command prints the document but
51/// does not write it (CLI-6_AC-12). With `--write`, it also writes the
52/// document at `path` (CLI-6_AC-72).
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
54#[schemars(title = "sokf new report")]
55pub struct NewResult {
56    /// `id` is the `id` of the document.
57    pub id: String,
58    /// `path` is the path at which `--write` writes the document. An asset is
59    /// a file of the knowledge that is not Markdown, such as an image, and a
60    /// sidecar is the document that describes an asset. `--write` writes a
61    /// sidecar beside its asset. It writes any other document as `<id>.md`,
62    /// either in the directory that the schema gives the document's lifecycle
63    /// states or in the directory set by `--dir`.
64    pub path: RepoPath,
65    /// `document` is the whole text of the document: its skeleton, which
66    /// holds only what is true of it, and no example and no guidance.
67    pub document: String,
68    /// `guide` is the guide of the new document, as `sokf guide --json`
69    /// gives it for the document: the guidance and the example of each part
70    /// at the document's states (CLI-6_AC-130).
71    #[serde(skip_serializing_if = "Option::is_none")]
72    #[schemars(with = "super::guide::DocumentGuide")]
73    pub guide: Option<super::guide::DocumentGuide>,
74    /// `created` is true when `--write` wrote the file. The JSON report leaves this field
75    /// out.
76    #[serde(skip)]
77    pub created: bool,
78    /// `indexes` holds each index that `--write` created or rewrote. The JSON
79    /// report leaves this field out.
80    #[serde(skip)]
81    pub indexes: Vec<RepoPath>,
82    /// `index_error` holds the error that stopped `--write` from bringing the
83    /// indexes up to date, after it wrote the document. The JSON report
84    /// leaves this field out.
85    #[serde(skip)]
86    pub index_error: Option<String>,
87}
88
89/// `refused` says that the schema of `type_name` in the store `knowledge`
90/// derives no scaffold, with one line for each of `refusals`, each with the
91/// line of its rule.
92// sokf-implements: CLI-6_AC-16
93// sokf-implements: CLI-6_AC-59
94fn refused(
95    model: &Model,
96    compiled: &grammar::Compiled,
97    knowledge: Option<usize>,
98    type_name: &str,
99    refusals: &[scaffold::Refusal],
100) -> Error {
101    let schema = knowledge
102        .and_then(|k| compiled.for_type(model, k, type_name))
103        .map(|(r, _)| model.schema(r).doc.path.clone());
104    Error::New(scaffold::no_template(type_name, schema.as_ref(), refusals))
105}
106
107/// `new` builds a document of a type from the skeleton of the type's schema,
108/// with the document's guide, and writes it when `write` is set. When it refuses, it has written
109/// nothing.
110// sokf-implements: CLI-6_AC-1
111// sokf-implements: CLI-6_AC-24
112// sokf-implements: CLI-6_AC-32
113// sokf-implements: CLI-6_AC-46
114// sokf-implements: CLI-9_AC-1
115// sokf-implements: CLI-6_AC-26
116// sokf-implements: CLI-6_AC-13
117// sokf-implements: CACHE-1_AC-21
118// sokf-implements: CACHE-1_AC-27
119// sokf-implements: CLI-6_AC-22
120// sokf-implements: CLI-6_AC-25
121pub fn new(root: &RepoRoot, opts: &NewOptions) -> Result<NewResult> {
122    let (store, type_name) = split_store(opts.type_name.as_str());
123    let config = config::load_config(root)?;
124    let (grammar, repo) = super::load::load_formats(root)?;
125    let cache = Cache::open(root, opts.cache);
126    let mut model = super::load_for_lookup(root, &config, &cache)?;
127    super::admit_schemas_of_type(&mut model, root, &cache, type_name)?;
128    // sokf-implements: CONF-12_AC-7
129    let texts = config::load_texts(root)?;
130    let compiled = grammar::compile_all(&model, grammar, &repo, texts);
131    let chosen = chosen_store(root, &model, opts, store, type_name)?;
132    let (knowledge, schema) = scaffold::schema_for(&model, &compiled, type_name, chosen)?;
133    // A qualified `Schema` goes in the `schemas/` directory of its store.
134    let schemas_dir = match (type_name, chosen, &opts.dir) {
135        ("Schema", Some(k), None) => model.knowledges[k]
136            .root
137            .join("schemas")
138            .map(|p| PathBuf::from(p.as_str())),
139        _ => None,
140    };
141    let dir = opts.dir.as_deref().or(schemas_dir.as_deref());
142    let states = scaffold::states(schema, &opts.states)?;
143    let site = scaffold::Site {
144        root,
145        model: &model,
146        schema,
147        states: &states,
148        cwd: &opts.cwd,
149    };
150
151    let asset = sidecar_asset(&site, opts, knowledge, type_name)?;
152    // sokf-implements: CLI-6_AC-15
153    let stem_slug = asset.as_ref().and_then(|(a, _)| {
154        let name = a.file_name();
155        let stem = name.rsplit_once('.').map_or(name, |(s, _)| s);
156        scaffold::slugify(stem)
157    });
158    let slug = opts.slug.clone().or(stem_slug);
159    if asset.is_some() && slug.is_none() {
160        return Err(Error::New(
161            "the asset's filename can't be made into a slug, so give `--slug`".to_string(),
162        ));
163    }
164
165    let id = resolve_id(
166        root,
167        &model,
168        schema,
169        knowledge,
170        opts,
171        slug.as_deref(),
172        &states,
173    )?;
174    // `--id-only` loads and compiles the knowledge as a full `new` does,
175    // because the id template is in the compiled schema.
176    if opts.id_only {
177        return Ok(NewResult {
178            id,
179            path: RepoPath::root(),
180            document: String::new(),
181            guide: None,
182            created: false,
183            indexes: Vec::new(),
184            index_error: None,
185        });
186    }
187
188    // sokf-implements: CLI-6_AC-52
189    let path = match &asset {
190        Some((_, sidecar)) => sidecar.clone(),
191        None => scaffold::place(&site, knowledge, &id, dir)?,
192    };
193    // The title comes before the scaffold, so that a type whose schema sets a
194    // rule for `title` refuses before anything is built.
195    let title = scaffold::title(type_name, schema, &states, opts.title.as_deref())?;
196    let at = model.knowledge_of(&path);
197    let language = scaffold::language(&model, &compiled, schema, type_name, knowledge, at);
198    let words = scaffold::Words::new(&compiled.texts, language);
199    let identity = scaffold::identity(
200        &id,
201        slug.as_deref(),
202        title.as_deref(),
203        states.clone(),
204        asset.as_ref().map(|(a, _)| a.clone()),
205    );
206    let (document, guide) = build(
207        &site, &compiled, knowledge, type_name, &path, &identity, &words,
208    )?;
209
210    let mut created = false;
211    let mut indexes = Vec::new();
212    let mut index_error = None;
213    // sokf-implements: CLI-6_AC-9
214    // sokf-implements: CLI-9_AC-3
215    if opts.write {
216        let fs_path = path.to_fs(root);
217        // sokf-implements: CLI-6_AC-20
218        if fs_path.exists() {
219            return Err(Error::New(format!("{path} exists, so sokf writes nothing")));
220        }
221        scaffold::create_new(&fs_path, &document)?;
222        created = true;
223        // The store closes before `fix_indexes` opens it again.
224        drop(cache);
225        (indexes, index_error) = update_indexes(root, &model, opts.cache, &path);
226    }
227    Ok(NewResult {
228        id,
229        path,
230        document,
231        guide: Some(guide),
232        created,
233        indexes,
234        index_error,
235    })
236}
237
238/// `build` returns the new document at `path` and its guide: the skeleton of
239/// the schema of `site` at its states, with the id, the title, and the
240/// `resource` of `identity`, from which each heading, unit, and key that
241/// derives from them derives, filled with the rest of `identity`, and with the anchor of each
242/// key that it captures.
243// sokf-implements: CLI-6_AC-130
244fn build(
245    site: &scaffold::Site,
246    compiled: &grammar::Compiled,
247    knowledge: Option<usize>,
248    type_name: &str,
249    path: &RepoPath,
250    identity: &scaffold::Identity,
251    words: &scaffold::Words<'_>,
252) -> Result<(String, super::guide::DocumentGuide)> {
253    let (model, schema, states) = (site.model, site.schema, site.states);
254    // A heading or a unit bound to `resource` takes the asset's path, as one
255    // bound to the id or the title takes theirs.
256    let mut values = BTreeMap::from([
257        ("id".to_string(), identity.id.clone()),
258        ("title".to_string(), identity.title.clone()),
259    ]);
260    if let Some(r) = &identity.resource {
261        values.insert("resource".to_string(), r.to_string());
262    }
263    let skeleton = scaffold::skeleton(schema, states, words, &values).map_err(|r| match r {
264        scaffold::Refused::Schema(r) => refused(model, compiled, knowledge, type_name, &r),
265        scaffold::Refused::Values(r) => fails(model, compiled, knowledge, type_name, &r),
266    })?;
267    let filled = scaffold::fill(&skeleton, schema, identity);
268    let document = scaffold::bind(&filled, path, schema, states, model, compiled, knowledge)?;
269    let guide = super::guide::new_guide(
270        path, &document, type_name, schema, model, compiled, knowledge, states, words,
271    );
272    Ok((document, guide))
273}
274
275/// `fails` says that no document with the id and the title that the command
276/// gives passes the schema, with the first of `refusals`, which the scaffold
277/// for those values gives, and the line of its rule in the schema of
278/// `type_name`, such as a title that a paragraph bound to it can't hold.
279// sokf-implements: CLI-6_AC-131
280fn fails(
281    model: &Model,
282    compiled: &grammar::Compiled,
283    knowledge: Option<usize>,
284    type_name: &str,
285    refusals: &[scaffold::Refusal],
286) -> Error {
287    let schema = knowledge
288        .and_then(|k| compiled.for_type(model, k, type_name))
289        .map_or_else(
290            || "line ".to_string(),
291            |(r, _)| format!("{}:", model.schema(r).doc.path),
292        );
293    let why = refusals
294        .first()
295        .map_or_else(String::new, |r| format!(": {schema}{}: {}", r.line, r.what));
296    Error::New(format!(
297        "the new document fails the schema of `{type_name}`{why}"
298    ))
299}
300
301/// `sidecar_asset` returns the asset that `--for` names and the path of its
302/// sidecar, or `None` for a type that declares no `asset-files`. It refuses
303/// `--dir` with `--for`, `--for` for a type that declares no
304/// `asset-files`, and a type that declares them without `--for`.
305// sokf-implements: CLI-6_AC-51
306fn sidecar_asset(
307    site: &scaffold::Site,
308    opts: &NewOptions,
309    knowledge: Option<usize>,
310    type_name: &str,
311) -> Result<Option<(RepoPath, RepoPath)>> {
312    if opts.dir.is_some() && opts.for_asset.is_some() {
313        return Err(Error::New(
314            "`--dir` can't be given with `--for`, because the asset's location determines the document's path".to_string(),
315        ));
316    }
317    // The location of a sidecar's asset determines the document's path, and
318    // the asset's filename supplies the default slug.
319    match (
320        &opts.for_asset,
321        site.schema.asset_files.is_empty(),
322        knowledge,
323    ) {
324        (Some(_), true, _) | (Some(_), _, None) => Err(Error::New(format!(
325            "`--for` is given, but `{type_name}` declares no `asset-files`"
326        ))),
327        (None, false, _) => Err(Error::New(format!(
328            "`{type_name}` declares `asset-files`, so give `--for <PATH>` with the asset that the document describes"
329        ))),
330        (Some(path), false, Some(k)) => Ok(Some(scaffold::asset(site, k, type_name, path)?)),
331        (None, true, _) => Ok(None),
332    }
333}
334
335/// `update_indexes` brings up to date the index of each directory that
336/// holds the new document at `path`. It returns each
337/// index that it created or rewrote, or the error that stopped it.
338// sokf-implements: CLI-6_AC-73
339fn update_indexes(
340    root: &RepoRoot,
341    model: &Model,
342    mode: CacheMode,
343    path: &RepoPath,
344) -> (Vec<RepoPath>, Option<String>) {
345    // The index of each directory that holds the document lists it, so
346    // the command writes them as `validate --fix` would, and a check
347    // after `new` finds no stale index that sokf itself left.
348    // A failure here leaves an index stale, which `validate --fix`
349    // repairs, so it doesn't undo the document that the command wrote
350    // (CLI-9_AC-1), and the handler warns of it.
351    let dirs = holding_dirs(model, path);
352    if dirs.is_empty() {
353        return (Vec::new(), None);
354    }
355    match super::validate::fix_indexes(root, mode, &dirs) {
356        Ok(ops) => (
357            ops.into_iter()
358                .filter_map(|op| match op {
359                    crate::FixOp::Created { path } | crate::FixOp::Rewrote { path } => Some(path),
360                    crate::FixOp::Moved { .. } => None,
361                })
362                .collect(),
363            None,
364        ),
365        Err(e) => (Vec::new(), Some(e.to_string())),
366    }
367}
368
369/// `holding_dirs` returns each directory that holds `path`, from its own
370/// directory up to the root of the store that holds it, or none when no
371/// store holds it.
372fn holding_dirs(model: &Model, path: &RepoPath) -> Vec<RepoPath> {
373    let Some(k) = model.knowledge_of(path) else {
374        return Vec::new();
375    };
376    let store = &model.knowledges[k].root;
377    std::iter::successors(path.parent(), RepoPath::parent)
378        .take_while(|d| d.starts_with(store))
379        .collect()
380}
381
382/// `chosen_store` returns the store that the command chooses for the type:
383/// the store that qualifies the type, or else the store that holds the path
384/// of `--dir` or `--for`, when that store declares the type. It refuses a
385/// store that no root has, and a qualified type whose store differs from
386/// the store of the path.
387// sokf-implements: CLI-6_AC-60
388// sokf-implements: CLI-6_AC-61
389// sokf-implements: CLI-6_AC-62
390fn chosen_store(
391    root: &RepoRoot,
392    model: &Model,
393    opts: &NewOptions,
394    store: Option<&str>,
395    type_name: &str,
396) -> Result<Option<usize>> {
397    let named = match store {
398        None => None,
399        Some(s) => match model.stores_named(s).as_slice() {
400            [k] => Some(*k),
401            [] => return Err(Error::New(format!("no store is named `{s}`"))),
402            _ => {
403                return Err(Error::New(format!(
404                    "more than one store is named `{s}`, so write its scope too, as `<scope>/{s}:{type_name}`"
405                )));
406            }
407        },
408    };
409    let located = opts
410        .dir
411        .as_deref()
412        .or(opts.for_asset.as_deref())
413        .and_then(|p| p.to_str())
414        .and_then(|p| PathArg(p).resolve_new(root, &opts.cwd))
415        .and_then(|p| model.knowledge_of(&p))
416        .filter(|&k| type_name == "Schema" || model.declares(k, type_name));
417    match (named, located) {
418        (Some(n), Some(l)) if n != l => Err(Error::New(format!(
419            "`{store}:{type_name}` names the store in {}, but the path of `{option}` lies in {}",
420            model.knowledges[n].root,
421            model.knowledges[l].root,
422            store = store.unwrap_or_default(),
423            option = if opts.dir.is_some() { "--dir" } else { "--for" },
424        ))),
425        (n, l) => Ok(n.or(l)),
426    }
427}
428
429/// `resolve_id` returns the id of the document under the rules of CLI-6
430/// for `--slug`, `--id`, and `--seq`. The number comes from `--seq` when it
431/// is given, and is otherwise the next one.
432// sokf-implements: CLI-6_AC-34
433// sokf-implements: CLI-6_AC-49
434// sokf-implements: CLI-6_AC-50
435// sokf-implements: CLI-6_AC-18
436// sokf-implements: CLI-6_AC-33
437fn resolve_id(
438    root: &RepoRoot,
439    model: &crate::Model,
440    schema: &SokfSchema,
441    knowledge: Option<usize>,
442    opts: &NewOptions,
443    slug: Option<&str>,
444    states: &crate::grammar::States,
445) -> Result<String> {
446    let type_name = split_store(opts.type_name.as_str()).1;
447    if let (Some(template), Some(k)) = (schema.core.core.id_template(), knowledge) {
448        if let Some(given) = &opts.id {
449            return Err(Error::New(format!(
450                "`--id {given}` is given, but `{type_name}` has an id template, so use `--slug`"
451            )));
452        }
453        let at = scaffold::Where {
454            root,
455            knowledge: k,
456            type_root: schema.type_root(),
457        };
458        let seq = match (template.seq_width(), opts.seq) {
459            (Some(_), Some(given)) => scaffold::given_seq(model, &at, type_name, template, given)?,
460            (Some(_), None) => scaffold::next_seq(model, &at, type_name, template)?,
461            (None, Some(given)) => {
462                return Err(Error::New(format!(
463                    "`--seq {given}` is given, but the id template of `{type_name}` has no `seq` placeholder"
464                )));
465            }
466            (None, None) => 0,
467        };
468        scaffold::render_id(template, seq, slug, states)
469    } else {
470        if let Some(given) = opts.seq {
471            return Err(Error::New(format!(
472                "`--seq {given}` is given, but `{type_name}` has no id template"
473            )));
474        }
475        if opts.id_only {
476            return Err(Error::New(format!(
477                "`{type_name}` has no id template, so give the id with `--id`"
478            )));
479        }
480        if let Some(s) = &opts.slug {
481            return Err(Error::New(format!(
482                "`--slug {s}` is given, but `{type_name}` has no id template, so use `--id`"
483            )));
484        }
485        match &opts.id {
486            Some(id) if is_slug(id) => Ok(id.clone()),
487            Some(id) => Err(Error::New(format!("`{id}` is not a slug"))),
488            None => Err(Error::New(format!(
489                "`{type_name}` has no id template, so `--id` is required"
490            ))),
491        }
492    }
493}