use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use laravel::time::Timestamp;
use regex::Regex;
use serde_json::{Map, Value};
use crate::markdown::Markdown;
use crate::support;
use crate::yaml::{self, Entries};
use crate::{Post, support::scalar_text};
const KNOWN: [&str; 17] = [
"title",
"slug",
"description",
"excerpt",
"date",
"updated",
"updated_at",
"category",
"tags",
"author",
"image",
"cover",
"image_alt",
"cover_alt",
"featured",
"draft",
"reading_time",
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexError {
pub file: String,
pub message: String,
}
#[derive(Debug, Default)]
pub struct IndexData {
pub posts: Vec<Post>,
pub lookup: HashMap<String, HashMap<String, usize>>,
pub positions: HashMap<String, BTreeMap<String, usize>>,
pub authors: Entries,
pub categories: Entries,
pub errors: Vec<IndexError>,
}
impl IndexData {
pub fn author(&self, key: &str) -> Option<&Value> {
self.authors
.iter()
.find(|(name, _)| name == key)
.map(|(_, value)| value)
}
pub fn category(&self, key: &str) -> Option<&Value> {
self.categories
.iter()
.find(|(name, _)| name == key)
.map(|(_, value)| value)
}
}
#[derive(Debug, Clone)]
pub struct Source {
pub name: String,
pub path: PathBuf,
pub locales: Vec<String>,
pub words_per_minute: u32,
}
impl Source {
pub fn key(&self) -> String {
format!(
"{}|{}|{}|{}",
self.name,
self.path.display(),
self.locales.join(","),
self.words_per_minute
)
}
pub fn signature(&self) -> String {
let mut parts = vec![self.locales.join(",")];
for file in self.files() {
parts.push(describe(&file));
}
for shared in ["_authors.yml", "_categories.yml"] {
parts.push(describe(&self.path.join(shared)));
}
parts.join("|")
}
pub fn files(&self) -> Vec<PathBuf> {
let mut files = Vec::new();
let Ok(entries) = std::fs::read_dir(&self.path) else {
return files;
};
let folders: Vec<PathBuf> = entries
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.is_dir())
.filter(|path| {
path.file_name()
.is_some_and(|name| !name.to_string_lossy().starts_with('_'))
})
.collect();
for locale in &self.locales {
for folder in &folders {
let file = folder.join(format!("{locale}.md"));
if file.is_file() {
files.push(file);
}
}
}
files.sort();
files
}
pub fn build(&self) -> IndexData {
let mut errors = Vec::new();
let authors = self.yaml("_authors.yml", &mut errors);
let categories = self.yaml("_categories.yml", &mut errors);
let mut posts: Vec<Post> = Vec::new();
let mut slugs: HashMap<(String, String), String> = HashMap::new();
let valid_slug = Regex::new(r"^[a-z0-9]+(?:-[a-z0-9]+)*$").expect("a valid pattern");
for file in self.files() {
let relative = file
.strip_prefix(&self.path)
.unwrap_or(&file)
.to_string_lossy()
.into_owned();
let content = match std::fs::read_to_string(&file) {
Ok(content) => content,
Err(error) => {
errors.push(IndexError {
file: relative,
message: error.to_string(),
});
continue;
}
};
let (meta, body) = match Markdown::split(&content) {
Ok(parts) => parts,
Err(error) => {
errors.push(IndexError {
file: relative,
message: error.to_string(),
});
continue;
}
};
let title = first(&meta, &["title"])
.and_then(scalar_text)
.unwrap_or_default()
.trim()
.to_owned();
if title.is_empty() {
errors.push(IndexError {
file: relative,
message: "It has no title.".to_owned(),
});
continue;
}
let locale = file
.file_stem()
.map(|stem| stem.to_string_lossy().into_owned())
.unwrap_or_default();
let slug = first(&meta, &["slug"])
.and_then(scalar_text)
.unwrap_or_else(|| support::slug(&title));
if !valid_slug.is_match(&slug) {
errors.push(IndexError {
file: relative,
message: format!("The slug `{slug}` is not lowercase letters, digits and hyphens."),
});
continue;
}
if let Some(other) = slugs.get(&(locale.clone(), slug.clone())) {
errors.push(IndexError {
file: relative,
message: format!("The slug `{slug}` is already used in {locale} by {other}."),
});
continue;
}
slugs.insert((locale.clone(), slug.clone()), relative.clone());
let category = first(&meta, &["category"]).and_then(scalar_text);
let author = first(&meta, &["author"]).and_then(scalar_text);
if let Some(category) = &category
&& !categories.iter().any(|(key, _)| key == category)
{
errors.push(IndexError {
file: relative.clone(),
message: format!("The category `{category}` is not in _categories.yml."),
});
}
if let Some(author) = &author
&& !authors.is_empty()
&& !authors.iter().any(|(key, _)| key == author)
{
errors.push(IndexError {
file: relative.clone(),
message: format!("The author `{author}` is not in _authors.yml."),
});
}
let words = support::word_count(&body);
let modified = modified(&file);
posts.push(Post {
collection: self.name.clone(),
id: file
.parent()
.and_then(Path::file_name)
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default(),
locale,
slug,
title,
description: first(&meta, &["description", "excerpt"]).and_then(string),
date: first(&meta, &["date"]).and_then(date).unwrap_or(modified),
updated: first(&meta, &["updated", "updated_at"]).and_then(date),
category,
tags: tags(meta.get("tags")),
author,
image: first(&meta, &["image", "cover"]).and_then(string),
image_alt: first(&meta, &["image_alt", "cover_alt"]).and_then(string),
featured: support::truthy(meta.get("featured")),
draft: support::truthy(meta.get("draft")),
reading_time: first(&meta, &["reading_time"]).and_then(integer).unwrap_or_else(|| {
let per_minute = usize::try_from(self.words_per_minute.max(1)).unwrap_or(220);
u32::try_from(words.div_ceil(per_minute).max(1)).unwrap_or(u32::MAX)
}),
meta: meta
.iter()
.filter(|(key, _)| !KNOWN.contains(&key.as_str()))
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
file,
});
}
posts.sort_by(|a, b| b.date.cmp(&a.date).then_with(|| a.id.cmp(&b.id)));
let mut lookup: HashMap<String, HashMap<String, usize>> = HashMap::new();
let mut positions: HashMap<String, BTreeMap<String, usize>> = HashMap::new();
for (position, post) in posts.iter().enumerate() {
lookup
.entry(post.locale.clone())
.or_default()
.insert(post.slug.clone(), position);
positions
.entry(post.id.clone())
.or_default()
.insert(post.locale.clone(), position);
}
IndexData {
posts,
lookup,
positions,
authors,
categories,
errors,
}
}
fn yaml(&self, file: &str, errors: &mut Vec<IndexError>) -> Entries {
let path = self.path.join(file);
let Ok(content) = std::fs::read_to_string(&path) else {
return Vec::new();
};
match yaml::parse_entries(&content) {
Ok(entries) => entries,
Err(message) => {
errors.push(IndexError {
file: file.to_owned(),
message: format!("Not valid YAML: {message}"),
});
Vec::new()
}
}
}
}
fn describe(file: &Path) -> String {
let (modified, size) = std::fs::metadata(file).map_or((0, 0), |metadata| {
(
metadata
.modified()
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |duration| duration.as_nanos()),
metadata.len(),
)
});
format!("{}:{modified}:{size}", file.display())
}
fn modified(file: &Path) -> Timestamp {
std::fs::metadata(file)
.and_then(|metadata| metadata.modified())
.ok()
.and_then(|time| Timestamp::try_from(time).ok())
.unwrap_or(Timestamp::UNIX_EPOCH)
}
fn first<'a>(meta: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
keys.iter()
.find_map(|key| meta.get(*key).filter(|value| !value.is_null()))
}
fn string(value: &Value) -> Option<String> {
scalar_text(value)
.map(|text| text.trim().to_owned())
.filter(|text| !text.is_empty())
}
fn integer(value: &Value) -> Option<u32> {
match value {
Value::Number(number) => number.as_f64().map(|number| number.max(0.0) as u32),
Value::String(text) => text.trim().parse::<f64>().ok().map(|number| number.max(0.0) as u32),
Value::Bool(true) => Some(1),
_ => None,
}
}
fn date(value: &Value) -> Option<Timestamp> {
match value {
Value::Number(number) => number.as_i64().and_then(|seconds| Timestamp::from_second(seconds).ok()),
Value::String(text) => support::parse_date(text),
_ => None,
}
}
fn tags(value: Option<&Value>) -> Vec<String> {
let items: Vec<&Value> = match value {
None | Some(Value::Null) => Vec::new(),
Some(Value::Array(items)) => items.iter().collect(),
Some(other) => vec![other],
};
items
.into_iter()
.filter_map(scalar_text)
.map(|tag| tag.trim().to_owned())
.filter(|tag| !tag.is_empty() && tag != "0")
.collect()
}