1#[cfg(any(
17 feature = "gen-zola",
18 feature = "gen-hugo",
19 feature = "gen-astro",
20 feature = "gen-build-awesome"
21))]
22pub mod external;
23mod files;
24mod plan;
25mod render;
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::path::Path;
29use std::sync::Arc;
30
31use async_trait::async_trait;
32use awp_types::{ContentId, GeneratorRef, LanguageTag, Redirect};
33use serde::{Deserialize, Serialize};
34
35use crate::content::SiteProject;
36use crate::error::{Result, SiteError};
37
38pub use files::CHARTER_PATH;
39pub use plan::DepKey;
40pub use render::markdown_to_html;
41
42#[async_trait]
47pub trait SiteGenerator: Send + Sync {
48 async fn build(&self, project: &SiteProject, out: &Path) -> Result<BuildReport>;
55
56 async fn build_incremental(
63 &self,
64 project: &SiteProject,
65 out: &Path,
66 changes: &ChangeSet,
67 ) -> Result<BuildReport> {
68 let _ = changes;
69 self.build(project, out).await
70 }
71}
72
73#[derive(Debug, Clone, Default)]
75pub struct ChangeSet {
76 pub items: BTreeSet<ContentId>,
78 pub previous: DependencyGraph,
80}
81
82#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(rename_all = "camelCase")]
85pub struct DependencyGraph {
86 pub outputs: BTreeMap<String, BTreeSet<DepKey>>,
88 pub footprints: BTreeMap<ContentId, BTreeSet<DepKey>>,
90 pub nav: BTreeMap<String, String>,
92 pub groups: BTreeMap<String, String>,
94}
95
96impl DependencyGraph {
97 pub fn affected_keys(
99 &self,
100 next: &DependencyGraph,
101 items: &BTreeSet<ContentId>,
102 ) -> BTreeSet<DepKey> {
103 let mut keys = BTreeSet::new();
104 for id in items {
105 keys.insert(DepKey::Item { id: id.clone() });
106 for graph in [self, next] {
107 if let Some(footprint) = graph.footprints.get(id) {
108 keys.extend(footprint.iter().cloned());
109 }
110 }
111 }
112 let languages: BTreeSet<&String> = self.nav.keys().chain(next.nav.keys()).collect();
113 for language in languages {
114 if self.nav.get(language) != next.nav.get(language) {
115 keys.insert(DepKey::Nav { language: language.clone() });
116 }
117 }
118 let groups: BTreeSet<&String> = self.groups.keys().chain(next.groups.keys()).collect();
119 for group in groups {
120 if self.groups.get(group) != next.groups.get(group)
121 && let Some((kind, slug)) = group.split_once('/')
122 && let Ok(kind) = serde_json::from_value(serde_json::Value::String(kind.into()))
123 {
124 keys.insert(DepKey::Group { kind, slug: slug.to_string() });
125 }
126 }
127 keys
128 }
129
130 pub fn outputs_for(&self, keys: &BTreeSet<DepKey>) -> BTreeSet<String> {
132 self.outputs
133 .iter()
134 .filter(|(_, deps)| !deps.is_disjoint(keys))
135 .map(|(path, _)| path.clone())
136 .collect()
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "camelCase")]
143pub struct PageRecord {
144 pub path: String,
146 pub language: LanguageTag,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub item: Option<ContentId>,
151 pub html: String,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub markdown: Option<String>,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub machine_view: Option<String>,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163#[serde(rename_all = "camelCase")]
164pub struct BuildReport {
165 pub generator: GeneratorRef,
167 pub pages: Vec<PageRecord>,
169 pub outputs: BTreeSet<String>,
171 pub written: BTreeSet<String>,
173 pub removed: BTreeSet<String>,
175 pub redirects: Vec<Redirect>,
177 pub graph: DependencyGraph,
179 pub theme: String,
181 pub incremental: bool,
183}
184
185#[derive(Debug, Clone, Copy, Default)]
205pub struct BuiltinGenerator;
206
207impl BuiltinGenerator {
208 pub fn reference() -> GeneratorRef {
210 GeneratorRef { name: "adk-site".into(), version: env!("CARGO_PKG_VERSION").into() }
211 }
212}
213
214#[async_trait]
215impl SiteGenerator for BuiltinGenerator {
216 async fn build(&self, project: &SiteProject, out: &Path) -> Result<BuildReport> {
217 let project = Arc::new(project.clone());
218 let out = out.to_path_buf();
219 tokio::task::spawn_blocking(move || build_sync(&project, &out, None))
220 .await
221 .map_err(|e| SiteError::Pipeline(format!("build task failed: {e}")))?
222 }
223
224 async fn build_incremental(
225 &self,
226 project: &SiteProject,
227 out: &Path,
228 changes: &ChangeSet,
229 ) -> Result<BuildReport> {
230 let project = Arc::new(project.clone());
231 let out = out.to_path_buf();
232 let changes = changes.clone();
233 tokio::task::spawn_blocking(move || build_sync(&project, &out, Some(&changes)))
234 .await
235 .map_err(|e| SiteError::Pipeline(format!("build task failed: {e}")))?
236 }
237}
238
239enum Output {
240 Page(usize),
241 Media(String),
242 Site,
243}
244
245fn write(out: &Path, path: &str, bytes: &[u8]) -> Result<()> {
246 let full = out.join(path);
247 if let Some(parent) = full.parent() {
248 std::fs::create_dir_all(parent).map_err(|e| SiteError::io(parent, e))?;
249 }
250 std::fs::write(&full, bytes).map_err(|e| SiteError::io(&full, e))
251}
252
253pub(crate) fn list_files(dir: &Path) -> Result<BTreeSet<String>> {
255 let mut files = BTreeSet::new();
256 if !dir.exists() {
257 return Ok(files);
258 }
259 let mut stack = vec![dir.to_path_buf()];
260 while let Some(current) = stack.pop() {
261 for entry in std::fs::read_dir(¤t).map_err(|e| SiteError::io(¤t, e))? {
262 let entry = entry.map_err(|e| SiteError::io(¤t, e))?;
263 let path = entry.path();
264 let file_type = entry.file_type().map_err(|e| SiteError::io(&path, e))?;
265 if file_type.is_dir() {
266 stack.push(path);
267 } else {
268 let relative =
269 path.strip_prefix(dir).unwrap_or(&path).to_string_lossy().replace('\\', "/");
270 files.insert(relative);
271 }
272 }
273 }
274 Ok(files)
275}
276
277fn remove(out: &Path, path: &str) -> Result<()> {
278 let full = out.join(path);
279 match std::fs::remove_file(&full) {
280 Ok(()) => {}
281 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
282 Err(e) => return Err(SiteError::io(&full, e)),
283 }
284 let mut dir = full.parent();
285 while let Some(current) = dir {
286 if current == out || std::fs::remove_dir(current).is_err() {
287 break;
288 }
289 dir = current.parent();
290 }
291 Ok(())
292}
293
294fn build_sync(
295 project: &SiteProject,
296 out: &Path,
297 changes: Option<&ChangeSet>,
298) -> Result<BuildReport> {
299 if let Some(issue) = project.issues().into_iter().next() {
300 return Err(SiteError::InvalidContent {
301 path: issue.item.map_or_else(|| "site.toml".into(), |id| id.0),
302 message: issue.message,
303 });
304 }
305 let plan = plan::plan(project)?;
306 let mut outputs: BTreeMap<String, (Output, BTreeSet<DepKey>)> = BTreeMap::new();
307 let mut claim = |path: String, output: Output, deps: BTreeSet<DepKey>| -> Result<()> {
308 if outputs.insert(path.clone(), (output, deps)).is_some() {
309 return Err(SiteError::InvalidContent {
310 path,
311 message: "two outputs share this file; rename a media file or change a redirect"
312 .into(),
313 });
314 }
315 Ok(())
316 };
317 for (index, page) in plan.pages.iter().enumerate() {
318 let (html, md, view) = plan::page_files(&page.path);
319 for path in std::iter::once(html).chain(md).chain(view) {
320 claim(path, Output::Page(index), page.deps.clone())?;
321 }
322 }
323 for (path, repo_path, index) in &plan.media {
324 let deps = BTreeSet::from([DepKey::Item { id: project.items[*index].id.clone() }]);
325 claim(path.clone(), Output::Media(repo_path.clone()), deps)?;
326 }
327 for (path, deps) in files::site_file_paths(project, &plan) {
328 claim(path, Output::Site, deps)?;
329 }
330 let graph = DependencyGraph {
331 outputs: outputs.iter().map(|(path, (_, deps))| (path.clone(), deps.clone())).collect(),
332 footprints: plan.footprints.clone(),
333 nav: project
334 .config
335 .languages
336 .iter()
337 .map(|l| (plan::lang_key(l), plan.nav_signature(&plan::lang_key(l))))
338 .collect(),
339 groups: plan.group_signatures(&project.items),
340 };
341 let on_disk = list_files(out)?;
342 let (render, removed): (BTreeSet<String>, BTreeSet<String>) = match changes {
343 None => {
344 let stale: BTreeSet<String> =
345 on_disk.difference(&graph.outputs.keys().cloned().collect()).cloned().collect();
346 (graph.outputs.keys().cloned().collect(), stale)
347 }
348 Some(changes) => {
349 let keys = changes.previous.affected_keys(&graph, &changes.items);
350 let mut render = graph.outputs_for(&keys);
351 for path in graph.outputs.keys() {
352 if !changes.previous.outputs.contains_key(path) || !on_disk.contains(path) {
353 render.insert(path.clone());
354 }
355 }
356 let removed = changes
357 .previous
358 .outputs
359 .keys()
360 .filter(|path| !graph.outputs.contains_key(*path))
361 .cloned()
362 .collect();
363 (render, removed)
364 }
365 };
366 for path in &removed {
367 remove(out, path)?;
368 }
369 let renderer = render::Renderer::new(project, &plan)?;
370 let mut written = BTreeSet::new();
371 let mut rendered_pages = BTreeSet::new();
372 for path in &render {
373 let Some((output, _)) = outputs.get(path) else { continue };
374 match output {
375 Output::Page(index) => {
376 if !rendered_pages.insert(*index) {
377 continue;
378 }
379 for (file, bytes) in renderer.page(&plan.pages[*index])? {
380 write(out, &file, &bytes)?;
381 written.insert(file);
382 }
383 }
384 Output::Media(repo_path) => {
385 write(out, path, &project.media_bytes(repo_path)?)?;
386 written.insert(path.clone());
387 }
388 Output::Site => {
389 write(out, path, &files::render(project, &plan, path)?)?;
390 written.insert(path.clone());
391 }
392 }
393 }
394 let pages = plan
395 .pages
396 .iter()
397 .map(|page| {
398 let (html, markdown, machine_view) = plan::page_files(&page.path);
399 let item = match &page.kind {
400 plan::PageKind::Item(i) | plan::PageKind::Notice(i, _) => {
401 Some(project.items[*i].id.clone())
402 }
403 plan::PageKind::Home { item, .. } => item.map(|i| project.items[i].id.clone()),
404 plan::PageKind::Listing { collection, .. } => {
405 collection.map(|i| project.items[i].id.clone())
406 }
407 plan::PageKind::NotFound | plan::PageKind::Gone => None,
408 };
409 PageRecord {
410 path: page.path.clone(),
411 language: page.language.clone(),
412 item,
413 html,
414 markdown,
415 machine_view,
416 }
417 })
418 .collect();
419 Ok(BuildReport {
420 generator: BuiltinGenerator::reference(),
421 pages,
422 outputs: graph.outputs.keys().cloned().collect(),
423 written,
424 removed,
425 redirects: files::redirects(project, &plan),
426 graph,
427 theme: project.theme.name.clone(),
428 incremental: changes.is_some(),
429 })
430}