oswilno/crates/web-assets/src/lib.rs
2023-08-04 16:32:10 +02:00

88 lines
2.2 KiB
Rust

use std::{borrow::Cow, sync::Once};
use actix_web::{get, web::ServiceConfig, HttpResponse};
pub fn configure(config: &mut ServiceConfig) {
config
.service(serve_build_js)
.service(serve_build_js_map)
.service(serve_build_css)
.service(serve_build_css_map);
}
macro_rules! static_resource {
($serve: ident, $name: ident, $path: expr, $once: ident, $content: ident, $ty: expr) => {
static $once: Once = Once::new();
static mut $content: String = String::new();
fn $name() -> Cow<'static, str> {
if cfg!(debug_assertions) {
build();
std::fs::read_to_string(concat!(".", $path)).unwrap().into()
} else {
$once.call_once(|| {
build();
unsafe {
$content = std::fs::read_to_string(concat!(".", $path)).unwrap();
}
});
unsafe { $content.as_str().into() }
}
}
#[get($path)]
async fn $serve() -> HttpResponse {
HttpResponse::Ok()
.append_header(("Content-Type", $ty.unwrap_or("application/javascript")))
.body($name())
}
};
}
static_resource!(
serve_build_js,
build_js,
"/assets/build.js",
BUILD_JS_GUARD,
BUILD_JS,
Some("application/javascript")
);
static_resource!(
serve_build_js_map,
build_js_map,
"/assets/build.js.map",
BUILD_JS_MAP_GUARD,
BUILD_JS_MAP,
Some("application/javascript")
);
static_resource!(
serve_build_css,
build_css,
"/assets/style.css",
BUILD_CSS_GUARD,
BUILD_CSS,
Some("text/css")
);
static_resource!(
serve_build_css_map,
build_css_map,
"/assets/style.css.map",
BUILD_CSS_MAP_GUARD,
BUILD_CSS_MAP,
Some("text/plain")
);
fn build() {
use std::process::Stdio;
let child = std::process::Command::new("./crates/web-assets/build.sh")
.env("RUST_BACKTRACE", "1")
.env("RUST_LOG", "debug")
.stdout(Stdio::piped())
.spawn()
.expect("Failed to create child process for building JS");
child
.wait_with_output()
.expect("Failed to run child process for building JS");
}