use std::path::PathBuf;
use schemars::JsonSchema;
use serde::Serialize;
use crate::{
Cache, CacheMode, Error, Model, PathArg, RepoPath, RepoRoot, Result, config,
grammar::{self, SokfSchema},
markdown::{is_slug, split_store},
scaffold,
};
#[derive(Debug, Clone)]
pub struct NewOptions {
pub type_name: String,
pub slug: Option<String>,
pub id: Option<String>,
pub title: Option<String>,
pub seq: Option<u64>,
pub states: Vec<(String, String)>,
pub dir: Option<PathBuf>,
pub for_asset: Option<PathBuf>,
pub cwd: PathBuf,
pub write: bool,
pub id_only: bool,
pub cache: CacheMode,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(title = "sokf new report")]
pub struct NewResult {
pub id: String,
pub path: RepoPath,
pub document: String,
#[serde(skip)]
pub created: bool,
#[serde(skip)]
pub indexes: Vec<RepoPath>,
#[serde(skip)]
pub index_error: Option<String>,
}
fn refused(
model: &Model,
compiled: &grammar::Compiled,
knowledge: Option<usize>,
type_name: &str,
refusals: &[scaffold::Refusal],
) -> Error {
let schema = knowledge
.and_then(|k| compiled.for_type(model, k, type_name))
.map(|(r, _)| model.schema(r).doc.path.clone());
Error::New(scaffold::no_template(type_name, schema.as_ref(), refusals))
}
pub fn new(root: &RepoRoot, opts: &NewOptions) -> Result<NewResult> {
let (store, type_name) = split_store(opts.type_name.as_str());
let config = config::load_config(root)?;
let (grammar, repo) = super::load::load_formats(root)?;
let cache = Cache::open(root, opts.cache);
let mut model = super::load_for_lookup(root, &config, &cache)?;
super::admit_schemas_of_type(&mut model, root, &cache, type_name)?;
let texts = config::load_texts(root)?;
let compiled = grammar::compile_all(&model, grammar, &repo, texts);
let chosen = chosen_store(root, &model, opts, store, type_name)?;
let (knowledge, schema) = scaffold::schema_for(&model, &compiled, type_name, chosen)?;
let schemas_dir = match (type_name, chosen, &opts.dir) {
("Schema", Some(k), None) => model.knowledges[k]
.root
.join("schemas")
.map(|p| PathBuf::from(p.as_str())),
_ => None,
};
let dir = opts.dir.as_deref().or(schemas_dir.as_deref());
let states = scaffold::states(schema, &opts.states)?;
let site = scaffold::Site {
root,
model: &model,
schema,
states: &states,
cwd: &opts.cwd,
};
let asset = sidecar_asset(&site, opts, knowledge, type_name)?;
let stem_slug = asset.as_ref().and_then(|(a, _)| {
let name = a.file_name();
let stem = name.rsplit_once('.').map_or(name, |(s, _)| s);
scaffold::slugify(stem)
});
let slug = opts.slug.clone().or(stem_slug);
if asset.is_some() && slug.is_none() {
return Err(Error::New(
"the asset's filename can't be made into a slug, so give `--slug`".to_string(),
));
}
let id = resolve_id(
root,
&model,
schema,
knowledge,
opts,
slug.as_deref(),
&states,
)?;
if opts.id_only {
return Ok(NewResult {
id,
path: RepoPath::root(),
document: String::new(),
created: false,
indexes: Vec::new(),
index_error: None,
});
}
let path = match &asset {
Some((_, sidecar)) => sidecar.clone(),
None => scaffold::place(&site, knowledge, &id, dir)?,
};
let title = scaffold::title(type_name, schema, &states, opts.title.as_deref())?;
let at = model.knowledge_of(&path);
let language = scaffold::language(&model, &compiled, schema, type_name, knowledge, at);
let words = scaffold::Words::new(&compiled.texts, language);
let seed = scaffold::seed(schema, &states, &words)
.map_err(|r| refused(&model, &compiled, knowledge, type_name, &r))?;
let gated = scaffold::gate(&seed.document, &states);
let identity = scaffold::identity(
&id,
slug.as_deref(),
title.as_deref(),
states.clone(),
asset.as_ref().map(|(a, _)| a.clone()),
);
let filled = scaffold::fill(&gated, schema, &identity);
let document = scaffold::bind(
&filled, &path, schema, &states, &model, &compiled, knowledge,
)?;
let mut created = false;
let mut indexes = Vec::new();
let mut index_error = None;
if opts.write {
let fs_path = path.to_fs(root);
if fs_path.exists() {
return Err(Error::New(format!("{path} exists, so sokf writes nothing")));
}
scaffold::create_new(&fs_path, &document)?;
created = true;
drop(cache);
(indexes, index_error) = update_indexes(root, &model, opts.cache, &path);
}
Ok(NewResult {
id,
path,
document,
created,
indexes,
index_error,
})
}
fn sidecar_asset(
site: &scaffold::Site,
opts: &NewOptions,
knowledge: Option<usize>,
type_name: &str,
) -> Result<Option<(RepoPath, RepoPath)>> {
if opts.dir.is_some() && opts.for_asset.is_some() {
return Err(Error::New(
"`--dir` can't be given with `--for`, because the asset's location determines the document's path".to_string(),
));
}
match (
&opts.for_asset,
site.schema.asset_files.is_empty(),
knowledge,
) {
(Some(_), true, _) | (Some(_), _, None) => Err(Error::New(format!(
"`--for` is given, but `{type_name}` declares no `asset-files`"
))),
(None, false, _) => Err(Error::New(format!(
"`{type_name}` declares `asset-files`, so give `--for <PATH>` with the asset that the document describes"
))),
(Some(path), false, Some(k)) => Ok(Some(scaffold::asset(site, k, type_name, path)?)),
(None, true, _) => Ok(None),
}
}
fn update_indexes(
root: &RepoRoot,
model: &Model,
mode: CacheMode,
path: &RepoPath,
) -> (Vec<RepoPath>, Option<String>) {
let dirs = holding_dirs(model, path);
if dirs.is_empty() {
return (Vec::new(), None);
}
match super::validate::fix_indexes(root, mode, &dirs) {
Ok(ops) => (
ops.into_iter()
.filter_map(|op| match op {
crate::FixOp::Created { path } | crate::FixOp::Rewrote { path } => Some(path),
crate::FixOp::Moved { .. } => None,
})
.collect(),
None,
),
Err(e) => (Vec::new(), Some(e.to_string())),
}
}
fn holding_dirs(model: &Model, path: &RepoPath) -> Vec<RepoPath> {
let Some(k) = model.knowledge_of(path) else {
return Vec::new();
};
let store = &model.knowledges[k].root;
std::iter::successors(path.parent(), RepoPath::parent)
.take_while(|d| d.starts_with(store))
.collect()
}
fn chosen_store(
root: &RepoRoot,
model: &Model,
opts: &NewOptions,
store: Option<&str>,
type_name: &str,
) -> Result<Option<usize>> {
let named = match store {
None => None,
Some(s) => match model.stores_named(s).as_slice() {
[k] => Some(*k),
[] => return Err(Error::New(format!("no store is named `{s}`"))),
_ => {
return Err(Error::New(format!(
"more than one store is named `{s}`, so write its scope too, as `<scope>/{s}:{type_name}`"
)));
}
},
};
let located = opts
.dir
.as_deref()
.or(opts.for_asset.as_deref())
.and_then(|p| p.to_str())
.and_then(|p| PathArg(p).resolve_new(root, &opts.cwd))
.and_then(|p| model.knowledge_of(&p))
.filter(|&k| type_name == "Schema" || model.declares(k, type_name));
match (named, located) {
(Some(n), Some(l)) if n != l => Err(Error::New(format!(
"`{store}:{type_name}` names the store in {}, but the path of `{option}` lies in {}",
model.knowledges[n].root,
model.knowledges[l].root,
store = store.unwrap_or_default(),
option = if opts.dir.is_some() { "--dir" } else { "--for" },
))),
(n, l) => Ok(n.or(l)),
}
}
fn resolve_id(
root: &RepoRoot,
model: &crate::Model,
schema: &SokfSchema,
knowledge: Option<usize>,
opts: &NewOptions,
slug: Option<&str>,
states: &crate::grammar::States,
) -> Result<String> {
let type_name = split_store(opts.type_name.as_str()).1;
if let (Some(template), Some(k)) = (schema.core.core.id_template(), knowledge) {
if let Some(given) = &opts.id {
return Err(Error::New(format!(
"`--id {given}` is given, but `{type_name}` has an id template, so use `--slug`"
)));
}
let at = scaffold::Where {
root,
knowledge: k,
type_root: schema.type_root(),
};
let seq = match (template.seq_width(), opts.seq) {
(Some(_), Some(given)) => scaffold::given_seq(model, &at, type_name, template, given)?,
(Some(_), None) => scaffold::next_seq(model, &at, type_name, template)?,
(None, Some(given)) => {
return Err(Error::New(format!(
"`--seq {given}` is given, but the id template of `{type_name}` has no `seq` placeholder"
)));
}
(None, None) => 0,
};
scaffold::render_id(template, seq, slug, states)
} else {
if let Some(given) = opts.seq {
return Err(Error::New(format!(
"`--seq {given}` is given, but `{type_name}` has no id template"
)));
}
if opts.id_only {
return Err(Error::New(format!(
"`{type_name}` has no id template, so give the id with `--id`"
)));
}
if let Some(s) = &opts.slug {
return Err(Error::New(format!(
"`--slug {s}` is given, but `{type_name}` has no id template, so use `--id`"
)));
}
match &opts.id {
Some(id) if is_slug(id) => Ok(id.clone()),
Some(id) => Err(Error::New(format!("`{id}` is not a slug"))),
None => Err(Error::New(format!(
"`{type_name}` has no id template, so `--id` is required"
))),
}
}
}