use std::path::Path;
use crate::{
Error, Model, PathArg, RepoPath, RepoRoot, Result,
check::derived_dir,
grammar::{SokfSchema, States},
};
fn derived(schema: &SokfSchema, states: &States) -> Result<RepoPath> {
derived_dir(schema, states)
.ok_or_else(|| Error::Internal("the schema defines no directory for these states".into()))
}
fn schema_dirs(roots: &[&RepoPath]) -> String {
roots
.iter()
.filter_map(|r| r.join("schemas"))
.map(|p| p.to_string())
.collect::<Vec<_>>()
.join(", ")
}
#[derive(Debug, Clone, Copy)]
pub struct Site<'a> {
pub root: &'a RepoRoot,
pub model: &'a Model,
pub schema: &'a SokfSchema,
pub states: &'a States,
pub cwd: &'a Path,
}
pub fn place(
site: &Site<'_>,
knowledge: Option<usize>,
id: &str,
dir: Option<&Path>,
) -> Result<RepoPath> {
let Site {
root,
model,
schema,
states,
cwd,
} = *site;
let file = format!("{id}.md");
let refuse = |msg: String| Error::New(msg);
if !schema.paths.is_empty() {
let derived = derived(schema, states)?;
if let Some(d) = dir {
return Err(refuse(format!(
"the requested states fix the directory of the document, {derived}, so `--dir {}` cannot change it",
d.display()
)));
}
return derived
.join(&file)
.ok_or_else(|| Error::Internal(format!("{derived}/{file} is not a path")));
}
let roots: Vec<&RepoPath> = model.knowledges.iter().map(|k| &k.root).collect();
let type_root = schema.type_root();
let directory = match (dir, knowledge) {
(Some(d), _) => {
let shown = d.display().to_string();
let resolved = d
.to_str()
.and_then(|s| PathArg(s).resolve_new(root, cwd))
.ok_or_else(|| refuse(format!("{shown} lies outside the repository")))?;
if let Some(k) = knowledge {
let kroot = &model.knowledges[k].root;
if !resolved.starts_with(kroot) {
return Err(refuse(format!(
"{resolved} lies outside the knowledge {kroot}"
)));
}
if let Some(type_root) = type_root
&& !resolved.starts_with(&type_root)
{
return Err(refuse(format!(
"{resolved} lies outside {type_root}, the root of the type's schema"
)));
}
} else {
let is_schemas = roots
.iter()
.any(|r| r.join("schemas").as_ref() == Some(&resolved));
if !is_schemas {
return Err(refuse(format!(
"{resolved} isn't the `schemas/` directory of a root. The `schemas/` directories are: {}",
schema_dirs(&roots)
)));
}
}
resolved
}
(None, Some(k)) => type_root.unwrap_or_else(|| model.knowledges[k].root.clone()),
(None, None) => match roots.as_slice() {
[one] => one
.join("schemas")
.ok_or_else(|| Error::Internal("the root has no `schemas/` path".into()))?,
_ => {
return Err(refuse(format!(
"there is more than one root, so `--dir` must give a `schemas/` directory. The `schemas/` directories are: {}",
schema_dirs(&roots)
)));
}
},
};
directory
.join(&file)
.ok_or_else(|| Error::Internal(format!("{directory}/{file} is not a path")))
}
pub fn asset(
site: &Site<'_>,
knowledge: usize,
type_name: &str,
path: &Path,
) -> Result<(RepoPath, RepoPath)> {
let Site {
root,
model,
schema,
states,
cwd,
} = *site;
let refuse = |msg: String| Error::New(msg);
let shown = path.display().to_string();
let resolved = path
.to_str()
.and_then(|s| PathArg(s).resolve(root, cwd))
.ok_or_else(|| refuse(format!("{shown} is not a path in the repository")))?;
let Some((k, asset)) = model.asset_at(&resolved) else {
return Err(refuse(format!(
"{resolved} is not an asset: no `asset-files` glob of `{type_name}` matches it"
)));
};
let owner = model.schema(asset.schema).type_const.clone();
if k != knowledge || owner.as_deref() != Some(type_name) {
return Err(refuse(format!(
"{resolved} is an asset of `{}`, not of `{type_name}`",
owner.unwrap_or_default()
)));
}
if asset.has_sidecar {
return Err(refuse(format!(
"{resolved} already has a sidecar, {}",
asset.sidecar_path()
)));
}
if !schema.paths.is_empty() {
let derived = derived(schema, states)?;
let parent = resolved.parent().unwrap_or_else(RepoPath::root);
if parent != derived {
return Err(refuse(format!(
"{resolved} is in {parent}, but the requested states put sidecars in {derived}. Move the asset to {derived}, or request the states that match {parent}"
)));
}
}
Ok((resolved.clone(), asset.sidecar_path()))
}
pub fn slugify(stem: &str) -> Option<String> {
let mut out = String::new();
let mut pending = false;
for c in stem.chars() {
if c.is_ascii_alphanumeric() {
if pending && !out.is_empty() {
out.push('-');
}
pending = false;
out.push(c.to_ascii_lowercase());
} else {
pending = true;
}
}
if out.is_empty() { None } else { Some(out) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugify_lowers_and_hyphenates() {
assert_eq!(slugify("flowers").as_deref(), Some("flowers"));
assert_eq!(
slugify("Wild Flowers 2024").as_deref(),
Some("wild-flowers-2024")
);
assert_eq!(slugify("my.file.v2").as_deref(), Some("my-file-v2"));
assert_eq!(slugify("--Shouty__NAME--").as_deref(), Some("shouty-name"));
assert_eq!(slugify("äöü").as_deref(), None);
assert_eq!(slugify("").as_deref(), None);
}
}