5 use crate::template::{Context, Value};
6 use std::collections::HashMap;
9 use std::path::{Path, PathBuf};
10 use time::{format_description::FormatItem, macros::format_description, OffsetDateTime};
12 const DATE_FORMAT: &[FormatItem<'_>] = format_description!("[year]-[month]-[day]");
19 type Archiver = fn(&Path, &Path, &Path, &Context) -> Result<()>;
22 pub fn to_template_context(archive_entries: &[ArchiveEntry]) -> Context {
23 let mut context = HashMap::new();
25 let archive_entries_collection = archive_entries
27 .map(ArchiveEntry::to_template_value)
31 "archive_length".to_string(),
32 Value::Unsigned(archive_entries.len().try_into().unwrap()),
36 Value::Collection(archive_entries_collection),
42 pub fn to_template_value(&self) -> Context {
43 let mut context = HashMap::new();
45 context.insert("id".to_string(), Value::String(self.id.clone()));
47 context.insert("slug".to_string(), Value::String(self.slug.clone()));
49 if let Some(title) = self.title() {
50 context.insert("title".to_string(), Value::String(title));
56 fn title(&self) -> Option<String> {
57 let date = OffsetDateTime::from_unix_timestamp_nanos(
58 (self.id.parse::<u64>().ok()? * 1_000_000).into(),
61 let short_date = date.format(&DATE_FORMAT).ok()?;
62 let title = self.slug.replace('-', " ");
63 Some(format!("{short_date} {title}"))
67 fn read_archive(archive_directory: &PathBuf) -> Vec<ArchiveEntry> {
68 let mut archive_entries = Vec::new();
69 if let Ok(entries) = read_dir(archive_directory) {
70 for entry in entries.filter_map(Result::ok) {
71 let entry_path = entry.path();
72 let post_id = entry.file_name();
73 if let Ok(entry_type) = entry.file_type() {
74 if entry_type.is_dir() {
75 if let Ok(candidates) = read_dir(&entry_path) {
76 for candidate in candidates.filter_map(Result::ok) {
77 let candidate_path = candidate.path();
78 match candidate_path.extension() {
80 if extension == "gmi" {
81 if let Some(slug) = candidate_path.file_stem() {
82 if let (Some(post_id), Some(slug)) =
83 (post_id.to_str(), slug.to_str())
85 archive_entries.push(ArchiveEntry {
86 id: post_id.to_string(),
87 slug: slug.to_string(),
102 archive_entries.sort_by(|a, b| b.id.cmp(&a.id));
107 archive_directory: &PathBuf,
108 template_directory: &Path,
109 output_directory: &Path,
111 let archivers = available_archivers();
112 let archive_entries = read_archive(archive_directory);
113 let context = ArchiveEntry::to_template_context(&archive_entries);
114 for archiver in archivers {
125 fn available_archivers() -> Vec<Archiver> {
126 vec![raw::archive, gemini::archive, gopher::archive]