1use crate::seo::{self, SeoPage, SiteConfig};
21use crate::{compile, BuildContext};
22use std::io;
23use std::path::{Path, PathBuf};
24
25#[derive(Debug, Default, Clone)]
27pub struct SiteReport {
28 pub built: Vec<PathBuf>,
30 pub errors: Vec<(PathBuf, String)>,
32 pub warnings: Vec<String>,
35 pub pages: Vec<SeoPage>,
38 pub configured: bool,
40}
41
42impl SiteReport {
43 pub fn is_clean(&self) -> bool {
45 self.errors.is_empty()
46 }
47}
48
49pub fn compile_site(src: &Path, out: &Path) -> io::Result<SiteReport> {
61 let config = SiteConfig::load(src);
62 let mut report = SiteReport {
63 configured: config.is_some(),
64 ..SiteReport::default()
65 };
66 let mut stack = vec![src.to_path_buf()];
67 while let Some(dir) = stack.pop() {
68 for entry in std::fs::read_dir(&dir)? {
69 let entry = entry?;
70 let path = entry.path();
71 let name = entry.file_name();
72 let name = name.to_string_lossy();
73 if path.is_dir() {
74 if !name.starts_with('.') {
75 stack.push(path);
76 }
77 } else if name.ends_with(".md") {
78 build_one_page(src, out, &path, config.as_ref(), &mut report);
79 }
80 }
81 }
82 if let Some(config) = &config {
83 let page_refs: &[SeoPage] = &report.pages;
84 std::fs::write(out.join("llms.txt"), seo::llms_txt(config, page_refs))?;
85 std::fs::write(out.join("sitemap.xml"), seo::sitemap_xml(config, page_refs))?;
86 std::fs::write(out.join("robots.txt"), seo::robots_txt(config))?;
87 }
88 Ok(report)
89}
90
91fn build_one_page(
93 src: &Path,
94 out: &Path,
95 path: &Path,
96 config: Option<&SiteConfig>,
97 report: &mut SiteReport,
98) {
99 let rel = match path.strip_prefix(src) {
100 Ok(r) => r.to_path_buf(),
101 Err(_) => path.to_path_buf(),
102 };
103 let source = match std::fs::read_to_string(path) {
104 Ok(s) => s,
105 Err(e) => {
106 report.errors.push((path.to_path_buf(), e.to_string()));
107 return;
108 }
109 };
110 let (meta, body_markdown) = seo::split_front_matter(&source);
111 let root = path
112 .parent()
113 .filter(|p| !p.as_os_str().is_empty())
114 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
115 let body = match compile(&body_markdown, &BuildContext::new(root)) {
116 Ok(html) => html,
117 Err(e) => {
118 report.errors.push((path.to_path_buf(), e.to_string()));
119 return;
120 }
121 };
122
123 let stem = meta.slug.clone().unwrap_or_else(|| {
124 rel.file_stem()
125 .unwrap_or_default()
126 .to_string_lossy()
127 .into_owned()
128 });
129 let dir = rel.parent().unwrap_or(Path::new(""));
130 let route = if dir.as_os_str().is_empty() {
131 format!("{stem}.html")
132 } else {
133 format!("{}/{}.html", dir.display(), stem)
134 };
135 let title = meta
136 .title
137 .clone()
138 .or_else(|| seo::first_h1(&body))
139 .unwrap_or_else(|| {
140 rel.file_stem()
141 .map(|s| s.to_string_lossy().into_owned())
142 .unwrap_or_else(|| "Untitled".to_string())
143 });
144 let description = meta
145 .description
146 .clone()
147 .or_else(|| seo::first_paragraph(&body))
148 .unwrap_or_default();
149
150 if title.chars().count() > 60 {
151 report.warnings.push(format!(
152 "{route}: title is {} chars (guidance: <= 60)",
153 title.chars().count()
154 ));
155 }
156 if description.is_empty() {
157 report.warnings.push(format!(
158 "{route}: no description (front-matter or first paragraph)"
159 ));
160 } else if description.chars().count() > 155 {
161 report.warnings.push(format!(
162 "{route}: description is {} chars (guidance: <= 155)",
163 description.chars().count()
164 ));
165 }
166
167 let document = seo::document(&body, &meta, &title, &description, &route, config);
168 let target = out.join(&route);
169 if let Some(parent) = target.parent() {
170 if let Err(e) = std::fs::create_dir_all(parent) {
171 report.errors.push((path.to_path_buf(), e.to_string()));
172 return;
173 }
174 }
175 if let Err(e) = std::fs::write(&target, document) {
176 report.errors.push((path.to_path_buf(), e.to_string()));
177 return;
178 }
179 report.built.push(path.to_path_buf());
180 report.pages.push(SeoPage {
181 route,
182 title,
183 description,
184 date: meta.date,
185 });
186}
187
188#[must_use]
193pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
194 let path = url_path.split(['?', '#']).next().unwrap_or("");
195 let decoded = percent_decode(path)?;
196 let cleaned: Vec<&str> = decoded
197 .split('/')
198 .filter(|seg| !seg.is_empty() && *seg != ".")
199 .collect();
200 if cleaned.contains(&"..") {
201 return None;
202 }
203 let mut file = out.to_path_buf();
204 for seg in &cleaned {
205 file.push(seg);
206 }
207 if cleaned.is_empty() {
208 file.push("index.html");
209 }
210 if file.is_dir() {
211 file.push("index.html");
212 }
213 if !file.exists() && file.extension().is_none() {
214 let with_html = file.with_extension("html");
215 if with_html.is_file() {
216 return Some(with_html);
217 }
218 return None;
219 }
220 if file.is_file() {
221 Some(file)
222 } else {
223 None
224 }
225}
226
227#[must_use]
230fn percent_decode(path: &str) -> Option<String> {
231 let mut out = Vec::with_capacity(path.len());
232 let mut bytes = path.bytes();
233 while let Some(b) = bytes.next() {
234 let value = if b == b'%' {
235 let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
236 let hi = decode(bytes.next()?)?;
237 let lo = decode(bytes.next()?)?;
238 hi.checked_mul(16)?.checked_add(lo)?
239 } else {
240 b
241 };
242 out.push(value);
243 }
244 String::from_utf8(out).ok()
245}
246
247#[must_use]
250pub fn mime_for(path: &Path) -> &'static str {
251 match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
252 "html" => "text/html; charset=utf-8",
253 "css" => "text/css; charset=utf-8",
254 "js" | "mjs" => "text/javascript; charset=utf-8",
255 "json" => "application/json",
256 "wasm" => "application/wasm",
257 "svg" => "image/svg+xml",
258 "png" => "image/png",
259 "jpg" | "jpeg" => "image/jpeg",
260 "gif" => "image/gif",
261 "ico" => "image/x-icon",
262 "md" => "text/markdown; charset=utf-8",
263 "xml" => "application/xml",
264 "txt" => "text/plain; charset=utf-8",
265 "woff2" => "font/woff2",
266 _ => "text/plain; charset=utf-8",
267 }
268}