Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ path = "src/main.rs"

[dependencies]
anyhow = "1.0.100"
async-stream = "0.3.6"
chrono = { version = "0.4.42", features = [ "serde" ] }
clap = "4.5.51"
fs_extra = "1.3.0"
Expand Down
10 changes: 7 additions & 3 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ pub struct Builder<'a> {
tmp_dir: Option<TempDir>,
built: bool,
no_verify: bool,
extra_content: Option<&'a str>,
}

impl<'a> Builder<'a> {
pub fn new(config: &'a Config, no_verify: bool) -> Self {
pub fn new(config: &'a Config, no_verify: bool, extra_content: Option<&'a str>) -> Self {
Self {
template_env: TemplateEnvironment::new(),
pages: Vec::new(),
Expand All @@ -44,6 +45,7 @@ impl<'a> Builder<'a> {
tmp_dir: None,
built: false,
no_verify: no_verify | config.build.no_verify,
extra_content,
}
}

Expand Down Expand Up @@ -156,11 +158,13 @@ impl<'a> Builder<'a> {
let mut dst_path = self.build_root.join(&page.rel_path);
dst_path.set_extension("html");

let extra_str = self.extra_content.unwrap_or("");

if let Some(tmpl_name) = &page.meta.template {
let render_str = self.template_env.render_template(&ctx, tmpl_name)?;
write(&dst_path, render_str)?;
write(&dst_path, format!("{}{}", render_str, extra_str))?;
} else {
write(&dst_path, &page.content)?;
write(&dst_path, format!("{}{}", &page.content, extra_str))?;
}

println!("Generated {}", &page.rel_path.display());
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ async fn main() {
}
TarsSubcommand::Build(args) => {
let config = load_config(&args.config);
let mut builder = Builder::new(&config, args.no_verify);
let mut builder = Builder::new(&config, args.no_verify, None);

if let Err(e) = builder.build() {
println!("{e}");
Expand All @@ -88,7 +88,7 @@ async fn main() {
}
TarsSubcommand::Clean(args) => {
let config = load_config(&args.config);
let builder = Builder::new(&config, false);
let builder = Builder::new(&config, false, None);

if let Err(e) = builder.clean() {
println!("{e}");
Expand Down
35 changes: 32 additions & 3 deletions src/serve.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
use anyhow::Result;
use notify::{Event, EventKind, RecursiveMode, Watcher};
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use std::{path::Path, sync::mpsc};
use warp::Filter;

use crate::{build::Builder, config::Config};

const RELOAD_JS: &str = "
<script>
const es = new EventSource(\"/__tars_reload__\");
es.onmessage = () => location.reload();
</script>
";

pub async fn run_server(config: Arc<Config>) -> Result<()> {
let socket_str = format!("{}:{}", config.serve.host, config.serve.port);
let socket_addr: SocketAddr = socket_str.parse()?;
let build_dir = config.build.build_dir.clone();

let (refresh_tx, _) = tokio::sync::broadcast::channel::<()>(16);
let refresh_sse = refresh_tx.clone();
let (notify_tx, notify_rx) = mpsc::channel::<notify::Result<Event>>();
let mut watcher = notify::recommended_watcher(notify_tx)?;
watcher.watch(
Expand All @@ -26,8 +37,8 @@ pub async fn run_server(config: Arc<Config>) -> Result<()> {
RecursiveMode::Recursive,
)?;

tokio::spawn(async move {
let mut builder = Builder::new(&config, false);
std::thread::spawn(move || {
let mut builder = Builder::new(&config, false, Some(RELOAD_JS));
println!("Building...");
if let Err(e) = builder.build() {
println!("Build error: {e}");
Expand All @@ -41,6 +52,7 @@ pub async fn run_server(config: Arc<Config>) -> Result<()> {
if let Err(e) = builder.rebuild() {
println!("Build error: {e}");
}
let _ = refresh_tx.send(());
}
_ => {}
},
Expand All @@ -53,7 +65,24 @@ pub async fn run_server(config: Arc<Config>) -> Result<()> {

println!("Running server on http://{socket_addr}");

warp::serve(warp::fs::dir(build_dir)).run(socket_addr).await;
let sse = warp::path("__tars_reload__").and(warp::get()).map(move || {
let mut rx = refresh_sse.subscribe();

let stream = async_stream::stream! {
loop {
if rx.recv().await.is_ok() {
yield Ok::<_, Infallible>(
warp::sse::Event::default().data("reload")
);
}
}
};

warp::sse::reply(warp::sse::keep_alive().stream(stream))
});

let routes = warp::fs::dir(build_dir).or(sse);
warp::serve(routes).run(socket_addr).await;

Ok(())
}