larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Everything a collection holds on disk, read once and cached until a file changes.
//!
//! A stable entry holds the posts and a locale/slug lookup. File signatures are checked
//! periodically (every 60 seconds in production, on every use elsewhere); a missing entry is built
//! by the first use. Problems (a post with no title, a slug used twice in one language, a category
//! nobody defined) are collected rather than raised, so one bad file never takes the blog down;
//! `larablog:check` reports them.

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};

/// Frontmatter keys with a property of their own; everything else stays in `meta`.
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",
];

/// A problem found reading the files.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexError {
    /// The file, relative to the collection's folder.
    pub file: String,
    /// What is wrong with it.
    pub message: String,
}

/// The posts of a collection and the lookups over them.
#[derive(Debug, Default)]
pub struct IndexData {
    /// Every post in every language, newest first, drafts and scheduled ones included.
    pub posts: Vec<Post>,
    /// Language => slug => position in `posts`.
    pub lookup: HashMap<String, HashMap<String, usize>>,
    /// Folder => language => position in `posts`.
    pub positions: HashMap<String, BTreeMap<String, usize>>,
    /// `_authors.yml`, in file order.
    pub authors: Entries,
    /// `_categories.yml`, in file order.
    pub categories: Entries,
    /// What was wrong with the files.
    pub errors: Vec<IndexError>,
}

impl IndexData {
    /// An author's entry.
    pub fn author(&self, key: &str) -> Option<&Value> {
        self.authors
            .iter()
            .find(|(name, _)| name == key)
            .map(|(_, value)| value)
    }

    /// A category's entry.
    pub fn category(&self, key: &str) -> Option<&Value> {
        self.categories
            .iter()
            .find(|(name, _)| name == key)
            .map(|(_, value)| value)
    }
}

/// How a collection is read.
#[derive(Debug, Clone)]
pub struct Source {
    /// The collection's name.
    pub name: String,
    /// Its folder.
    pub path: PathBuf,
    /// The languages it is written in.
    pub locales: Vec<String>,
    /// Words a minute for the reading time.
    pub words_per_minute: u32,
}

impl Source {
    /// The key the cache keeps this index under.
    pub fn key(&self) -> String {
        format!(
            "{}|{}|{}|{}",
            self.name,
            self.path.display(),
            self.locales.join(","),
            self.words_per_minute
        )
    }

    /// The modification time and size of every file the index depends on.
    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("|")
    }

    /// Every `{path}/{folder}/{locale}.md`, folders starting with `_` excluded.
    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
    }

    /// Read every file of the collection.
    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)
}

/// PHP's `$meta['a'] ?? $meta['b']`: the first key whose value is not null.
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()
}