refactor: added the build command to build into static files
This commit is contained in:
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,3 +1,5 @@
|
|||||||
/target
|
/target
|
||||||
/themes
|
/themes
|
||||||
/result
|
/result
|
||||||
|
/example/*.html
|
||||||
|
/example/*.css
|
||||||
|
|||||||
263
src/main.rs
263
src/main.rs
@@ -1,3 +1,4 @@
|
|||||||
|
use ax_models::Page;
|
||||||
use axum::{
|
use axum::{
|
||||||
Router,
|
Router,
|
||||||
extract::{Path, State},
|
extract::{Path, State},
|
||||||
@@ -8,7 +9,6 @@ use axum::{
|
|||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use pulldown_cmark::{Options, Parser as MarkdownParser, html};
|
use pulldown_cmark::{Options, Parser as MarkdownParser, html};
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::{io::Cursor, path::PathBuf};
|
use std::{io::Cursor, path::PathBuf};
|
||||||
use syntect::{highlighting::ThemeSet, parsing::SyntaxSet};
|
use syntect::{highlighting::ThemeSet, parsing::SyntaxSet};
|
||||||
@@ -33,10 +33,7 @@ lazy_static! {
|
|||||||
pub static ref SYNTAX_SET: SyntaxSet = SyntaxSet::load_defaults_newlines();
|
pub static ref SYNTAX_SET: SyntaxSet = SyntaxSet::load_defaults_newlines();
|
||||||
pub static ref THEME_SET: ThemeSet = {
|
pub static ref THEME_SET: ThemeSet = {
|
||||||
let mut set = ThemeSet::load_defaults();
|
let mut set = ThemeSet::load_defaults();
|
||||||
|
|
||||||
// let theme_bytes = include_bytes!("../themes/Catppuccin-Macchiato.tmTheme");
|
|
||||||
let theme_bytes = include_bytes!(env!("THEME_FILE_PATH"));
|
let theme_bytes = include_bytes!(env!("THEME_FILE_PATH"));
|
||||||
|
|
||||||
let mut cursor = Cursor::new(theme_bytes);
|
let mut cursor = Cursor::new(theme_bytes);
|
||||||
match syntect::highlighting::ThemeSet::load_from_reader(&mut cursor) {
|
match syntect::highlighting::ThemeSet::load_from_reader(&mut cursor) {
|
||||||
Ok(theme) => {
|
Ok(theme) => {
|
||||||
@@ -51,7 +48,7 @@ lazy_static! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(author, version, about = "A simple markdown book server")]
|
#[command(author, version, about = "A simple markdown book server/builder")]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
command: Commands,
|
command: Commands,
|
||||||
@@ -59,9 +56,9 @@ struct Cli {
|
|||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
enum Commands {
|
enum Commands {
|
||||||
/// Serve the markdown files in a directory
|
/// Serve the markdown files dynamically
|
||||||
Serve {
|
Serve {
|
||||||
/// Path to the directory containing SUMMARY.md
|
/// Path to the directory containing markdown files
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
|
||||||
/// Whether the home page and navbar should be removed
|
/// Whether the home page and navbar should be removed
|
||||||
@@ -76,6 +73,19 @@ enum Commands {
|
|||||||
#[arg(short = 'H', long)]
|
#[arg(short = 'H', long)]
|
||||||
host: bool,
|
host: bool,
|
||||||
},
|
},
|
||||||
|
/// Build static HTML files from the markdown directory
|
||||||
|
Build {
|
||||||
|
/// Path to the directory containing markdown files
|
||||||
|
path: PathBuf,
|
||||||
|
|
||||||
|
/// Whether the home page and navbar should be removed
|
||||||
|
#[arg(short, long)]
|
||||||
|
no_navigation: bool,
|
||||||
|
|
||||||
|
/// Output directory (defaults to the input directory)
|
||||||
|
#[arg(short, long)]
|
||||||
|
out_dir: Option<PathBuf>,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
struct AppState {
|
struct AppState {
|
||||||
@@ -86,7 +96,6 @@ struct AppState {
|
|||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
lazy_static::initialize(&TEMPLATES);
|
lazy_static::initialize(&TEMPLATES);
|
||||||
|
|
||||||
tracing_subscriber::fmt()
|
tracing_subscriber::fmt()
|
||||||
.with_max_level(tracing::Level::INFO)
|
.with_max_level(tracing::Level::INFO)
|
||||||
.init();
|
.init();
|
||||||
@@ -101,15 +110,13 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
no_navigation,
|
no_navigation,
|
||||||
} => {
|
} => {
|
||||||
let abs_path = std::fs::canonicalize(&path)?;
|
let abs_path = std::fs::canonicalize(&path)?;
|
||||||
|
|
||||||
let shared_state = Arc::new(AppState {
|
let shared_state = Arc::new(AppState {
|
||||||
docs_dir: abs_path,
|
docs_dir: abs_path,
|
||||||
no_navigation,
|
no_navigation,
|
||||||
});
|
});
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/", get(render_summary))
|
.route("/", get(render_summary_handler))
|
||||||
.route("/{page}", get(render_page))
|
.route("/{page}", get(render_page_handler))
|
||||||
.route("/style.css", get(serve_css))
|
.route("/style.css", get(serve_css))
|
||||||
.with_state(shared_state);
|
.with_state(shared_state);
|
||||||
|
|
||||||
@@ -118,72 +125,181 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
} else {
|
} else {
|
||||||
format!("127.0.0.1:{}", port)
|
format!("127.0.0.1:{}", port)
|
||||||
};
|
};
|
||||||
|
|
||||||
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
||||||
tracing::info!("Listening on {}", addr);
|
tracing::info!("Listening on http://{}", addr);
|
||||||
axum::serve(listener, app).await?;
|
axum::serve(listener, app).await?;
|
||||||
}
|
}
|
||||||
}
|
Commands::Build {
|
||||||
|
path,
|
||||||
|
no_navigation,
|
||||||
|
out_dir,
|
||||||
|
} => {
|
||||||
|
let abs_path = std::fs::canonicalize(&path)?;
|
||||||
|
let output_path = out_dir.unwrap_or_else(|| abs_path.clone());
|
||||||
|
tokio::fs::create_dir_all(&output_path).await?;
|
||||||
|
|
||||||
|
run_build(abs_path, output_path, no_navigation).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn render_summary(State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
async fn get_summary_data(docs_dir: &PathBuf) -> Vec<Page> {
|
||||||
if state.no_navigation {
|
let mut pages = Vec::new();
|
||||||
return (StatusCode::NOT_FOUND, "Navigation is disabled").into_response();
|
if let Ok(mut entries) = tokio::fs::read_dir(docs_dir).await {
|
||||||
}
|
|
||||||
|
|
||||||
let mut context = Context::new();
|
|
||||||
context.insert("title", "Pages");
|
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
|
||||||
struct Page {
|
|
||||||
filename: String,
|
|
||||||
title: String,
|
|
||||||
datetime: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pages: Vec<Page> = Vec::new();
|
|
||||||
if let Ok(mut entries) = tokio::fs::read_dir(&state.docs_dir).await {
|
|
||||||
while let Ok(Some(entry)) = entries.next_entry().await {
|
while let Ok(Some(entry)) = entries.next_entry().await {
|
||||||
let path = entry.path();
|
let path = entry.path();
|
||||||
|
if path.extension().and_then(|s| s.to_str()) != Some("md") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
let filename = entry.file_name();
|
let filename = entry.file_name();
|
||||||
let filename = filename.to_str().unwrap_or("<filename>");
|
let filename_str = filename.to_str().unwrap_or("");
|
||||||
|
|
||||||
let title = if let Ok(file) = tokio::fs::File::open(&path).await {
|
let title = if let Ok(file) = tokio::fs::File::open(&path).await {
|
||||||
let mut reader = BufReader::new(file);
|
let mut reader = BufReader::new(file);
|
||||||
let mut line = String::new();
|
let mut line = String::new();
|
||||||
match reader.read_line(&mut line).await {
|
match reader.read_line(&mut line).await {
|
||||||
Ok(_) => line.trim_start_matches('#').trim().to_string(),
|
Ok(_) => line.trim_start_matches('#').trim().to_string(),
|
||||||
Err(_) => filename.to_string(),
|
Err(_) => filename_str.to_string(),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
filename.to_string()
|
filename_str.to_string()
|
||||||
};
|
};
|
||||||
|
|
||||||
let datetime = filename
|
let datetime = filename_str
|
||||||
.split_once('@')
|
.split_once('@')
|
||||||
.and_then(|(_, ts_with_ext)| ts_with_ext.split('.').next())
|
.and_then(|(_, ts_with_ext)| ts_with_ext.split('.').next())
|
||||||
.map(|dt| dt.to_string())
|
.map(|dt| dt.to_string())
|
||||||
.unwrap_or_else(|| "Invalid Date".to_string());
|
.unwrap_or_else(|| "Invalid Date".to_string());
|
||||||
|
|
||||||
pages.push(Page {
|
pages.push(Page {
|
||||||
filename: filename.to_string(),
|
filename: filename_str.to_string(),
|
||||||
title,
|
title,
|
||||||
datetime,
|
datetime,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pages.sort_by(|a, b| b.datetime.cmp(&a.datetime));
|
||||||
|
pages
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn render_markdown_to_html(
|
||||||
|
content: &str,
|
||||||
|
filename: &str,
|
||||||
|
docs_dir: &PathBuf,
|
||||||
|
no_navigation: bool,
|
||||||
|
is_static: bool,
|
||||||
|
) -> String {
|
||||||
|
let mut options = Options::empty();
|
||||||
|
options.insert(
|
||||||
|
Options::ENABLE_TABLES
|
||||||
|
| Options::ENABLE_FOOTNOTES
|
||||||
|
| Options::ENABLE_STRIKETHROUGH
|
||||||
|
| Options::ENABLE_TASKLISTS,
|
||||||
|
);
|
||||||
|
|
||||||
|
let parser = MarkdownParser::new_ext(content, options);
|
||||||
|
let renderer = CodeblockRenderer::new(parser);
|
||||||
|
let mut html_output = String::new();
|
||||||
|
html::push_html(&mut html_output, renderer);
|
||||||
|
|
||||||
|
let (mut prev, mut next) = if no_navigation {
|
||||||
|
(None, None)
|
||||||
|
} else {
|
||||||
|
get_nav_links(docs_dir, filename)
|
||||||
|
};
|
||||||
|
|
||||||
|
// If building statically, rewrite .md links to .html
|
||||||
|
if is_static {
|
||||||
|
prev = prev.map(|s| {
|
||||||
|
if s == "." {
|
||||||
|
"index.html".to_string()
|
||||||
|
} else {
|
||||||
|
s.replace(".md", ".html")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
next = next.map(|s| s.replace(".md", ".html"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut context = Context::new();
|
||||||
|
context.insert("title", filename);
|
||||||
|
context.insert("content", &html_output);
|
||||||
|
context.insert("prev_page", &prev);
|
||||||
|
context.insert("next_page", &next);
|
||||||
|
context.insert("no_navigation", &no_navigation);
|
||||||
|
context.insert("is_static", &is_static);
|
||||||
|
|
||||||
|
TEMPLATES
|
||||||
|
.render("page.html", &context)
|
||||||
|
.unwrap_or_else(|e| format!("Error: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_build(docs_dir: PathBuf, out_dir: PathBuf, no_navigation: bool) -> anyhow::Result<()> {
|
||||||
|
tracing::info!("Building static site to: {:?}", out_dir);
|
||||||
|
|
||||||
|
// Build summary
|
||||||
|
if !no_navigation {
|
||||||
|
let pages = get_summary_data(&docs_dir).await;
|
||||||
|
// Rewrite filenames for static links in home page
|
||||||
|
let static_pages: Vec<Page> = pages
|
||||||
|
.into_iter()
|
||||||
|
.map(|mut p| {
|
||||||
|
p.filename = p.filename.replace(".md", ".html");
|
||||||
|
p
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut context = Context::new();
|
||||||
|
context.insert("title", "Pages");
|
||||||
|
context.insert("files", &static_pages);
|
||||||
|
context.insert("is_static", &true);
|
||||||
|
|
||||||
|
let rendered = TEMPLATES.render("home.html", &context)?;
|
||||||
|
tokio::fs::write(out_dir.join("index.html"), rendered).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build css
|
||||||
|
let css = TEMPLATES.render("style.css", &Context::new())?;
|
||||||
|
tokio::fs::write(out_dir.join("style.css"), css).await?;
|
||||||
|
|
||||||
|
// Build pages
|
||||||
|
let mut entries = tokio::fs::read_dir(&docs_dir).await?;
|
||||||
|
while let Some(entry) = entries.next_entry().await? {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.extension().and_then(|s| s.to_str()) == Some("md") {
|
||||||
|
let filename = entry.file_name().to_str().unwrap().to_string();
|
||||||
|
let content = tokio::fs::read_to_string(&path).await?;
|
||||||
|
let rendered =
|
||||||
|
render_markdown_to_html(&content, &filename, &docs_dir, no_navigation, true).await;
|
||||||
|
|
||||||
|
let out_file = out_dir.join(filename.replace(".md", ".html"));
|
||||||
|
tokio::fs::write(out_file, rendered).await?;
|
||||||
|
tracing::info!("Generated {}", filename);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!("Build complete!");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn render_summary_handler(State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
||||||
|
if state.no_navigation {
|
||||||
|
return (StatusCode::NOT_FOUND, "Disabled").into_response();
|
||||||
|
}
|
||||||
|
let pages = get_summary_data(&state.docs_dir).await;
|
||||||
|
let mut context = Context::new();
|
||||||
|
context.insert("title", "Pages");
|
||||||
context.insert("files", &pages);
|
context.insert("files", &pages);
|
||||||
|
context.insert("is_static", &false);
|
||||||
|
|
||||||
match TEMPLATES.render("home.html", &context) {
|
match TEMPLATES.render("home.html", &context) {
|
||||||
Ok(rendered) => Html(rendered).into_response(),
|
Ok(rendered) => Html(rendered).into_response(),
|
||||||
Err(e) => Html(format!("<h1>Template Error</h1><pre>{}</pre>", e)).into_response(),
|
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn render_page(
|
async fn render_page_handler(
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
Path(page): Path<String>,
|
Path(page): Path<String>,
|
||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
@@ -192,18 +308,25 @@ async fn render_page(
|
|||||||
} else {
|
} else {
|
||||||
format!("{}.md", page)
|
format!("{}.md", page)
|
||||||
};
|
};
|
||||||
|
|
||||||
let file_path = state.docs_dir.join(&filename);
|
let file_path = state.docs_dir.join(&filename);
|
||||||
|
|
||||||
let content = match tokio::fs::read_to_string(&file_path).await {
|
match tokio::fs::read_to_string(&file_path).await {
|
||||||
Ok(c) => c,
|
Ok(content) => Html(
|
||||||
Err(_) => return Html("<h1>404</h1><p>Page not found</p>".to_string()),
|
render_markdown_to_html(
|
||||||
};
|
&content,
|
||||||
render_md_file(&content, &filename, state).await
|
&filename,
|
||||||
|
&state.docs_dir,
|
||||||
|
state.no_navigation,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
),
|
||||||
|
Err(_) => Html("<h1>404</h1><p>Page not found</p>".to_string()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn serve_css() -> impl IntoResponse {
|
async fn serve_css() -> impl IntoResponse {
|
||||||
match TEMPLATES.render("style.css", &tera::Context::new()) {
|
match TEMPLATES.render("style.css", &Context::new()) {
|
||||||
Ok(css) => Response::builder()
|
Ok(css) => Response::builder()
|
||||||
.header("content-type", "text/css")
|
.header("content-type", "text/css")
|
||||||
.body(css.into())
|
.body(css.into())
|
||||||
@@ -212,36 +335,14 @@ async fn serve_css() -> impl IntoResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn render_md_file(content: &String, filename: &str, state: Arc<AppState>) -> Html<String> {
|
// Helper model for Tera
|
||||||
let mut options = Options::empty();
|
mod ax_models {
|
||||||
options.insert(Options::ENABLE_TABLES);
|
use serde::{Deserialize, Serialize};
|
||||||
options.insert(Options::ENABLE_FOOTNOTES);
|
#[derive(Deserialize, Serialize, Clone)]
|
||||||
options.insert(Options::ENABLE_STRIKETHROUGH);
|
pub struct Page {
|
||||||
options.insert(Options::ENABLE_TASKLISTS);
|
pub filename: String,
|
||||||
|
pub title: String,
|
||||||
let parser = MarkdownParser::new_ext(&content, options);
|
pub datetime: String,
|
||||||
|
|
||||||
let renderer = CodeblockRenderer::new(parser);
|
|
||||||
|
|
||||||
let mut html_output = String::new();
|
|
||||||
html::push_html(&mut html_output, renderer);
|
|
||||||
|
|
||||||
let (prev_page, next_page) = if state.no_navigation {
|
|
||||||
(None, None)
|
|
||||||
} else {
|
|
||||||
get_nav_links(&state.docs_dir, filename)
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut context = Context::new();
|
|
||||||
context.insert("title", filename);
|
|
||||||
context.insert("content", &html_output);
|
|
||||||
context.insert("prev_page", &prev_page);
|
|
||||||
context.insert("next_page", &next_page);
|
|
||||||
context.insert("no_navigation", &state.no_navigation);
|
|
||||||
|
|
||||||
match TEMPLATES.render("page.html", &context) {
|
|
||||||
Ok(rendered) => Html(rendered),
|
|
||||||
Err(e) => Html(format!("<h1>Template Error</h1><pre>{}</pre>", e)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -259,27 +360,17 @@ fn get_nav_links(dir: &PathBuf, current_file: &str) -> (Option<String>, Option<S
|
|||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
files.sort();
|
files.sort();
|
||||||
|
|
||||||
if current_file == "SUMMARY.md" {
|
|
||||||
return (None, files.first().cloned());
|
|
||||||
}
|
|
||||||
|
|
||||||
let pos = files.iter().position(|f| f == current_file);
|
let pos = files.iter().position(|f| f == current_file);
|
||||||
|
|
||||||
match pos {
|
match pos {
|
||||||
Some(i) => {
|
Some(i) => {
|
||||||
let prev = if i == 0 {
|
let prev = if i == 0 {
|
||||||
// If first page, point back to summary page
|
|
||||||
Some(".".to_string())
|
Some(".".to_string())
|
||||||
} else {
|
} else {
|
||||||
// Otherwise point to the previous file in the list
|
|
||||||
files.get(i - 1).cloned()
|
files.get(i - 1).cloned()
|
||||||
};
|
};
|
||||||
|
|
||||||
let next = files.get(i + 1).cloned();
|
let next = files.get(i + 1).cloned();
|
||||||
(prev, next)
|
(prev, next)
|
||||||
}
|
}
|
||||||
|
|
||||||
None => (None, None),
|
None => (None, None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>{{ title }}</title>
|
<title>{{ title }}</title>
|
||||||
<link rel="stylesheet" href="/style.css">
|
<link rel="stylesheet" href="style.css">
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
||||||
{% endblock head %}
|
{% endblock head %}
|
||||||
</head>
|
</head>
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
<body {% if no_navigation %}style="padding-top: 40px;"{% endif %}>
|
<body {% if no_navigation %}style="padding-top: 40px;"{% endif %}>
|
||||||
{% if not no_navigation %}
|
{% if not no_navigation %}
|
||||||
<nav>
|
<nav>
|
||||||
<a href="/">Home</a>
|
<a href="{% if is_static %}index.html{% else %}/{% endif %}">Home</a>
|
||||||
</nav>
|
</nav>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
|||||||
@@ -38,8 +38,10 @@ body {
|
|||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
article {
|
#content {
|
||||||
max-width: 1000px;
|
width: 100%;
|
||||||
|
max-width: var(--container-width);
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
::selection {
|
::selection {
|
||||||
|
|||||||
Reference in New Issue
Block a user