feat: create axum_bundler

This commit is contained in:
Valerio Ageno
2024-05-14 20:07:24 +02:00
parent 65f43b3caf
commit aa5d4b689d
8 changed files with 166 additions and 24 deletions
+5 -2
View File
@@ -1,5 +1,8 @@
[workspace]
members = [
"crates/cli"
"crates/cli",
"crates/axum_bundler"
]
exclude = [
"examples/playground"
]
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "axum_bundler"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.81"
glob = "0.3.1"
fastmurmur3 = "0.2.0"
+1
View File
@@ -0,0 +1 @@
# Axum bundler
+135
View File
@@ -0,0 +1,135 @@
use glob::glob;
use std::collections::HashMap;
use std::fs;
use std::io::prelude::*;
use std::path::Path;
use std::path::PathBuf;
const AXUM_ENTRY_POINT: &'static str = r##"// File automatically generated
// Do not manually change it
use axum::response::Html;
use axum::{routing::get, Router};
use ssr_rs::Ssr;
use std::cell::RefCell;
use std::fs::read_to_string;
thread_local! {
static SSR: RefCell<Ssr<'static, 'static>> = RefCell::new(
Ssr::from(
read_to_string("out/server/server-main.js").unwrap(),
""
).unwrap()
)
}
#[tokio::main]
async fn main() {
Ssr::create_platform();
let app = Router::new()
// ROUTE_BUILDER
.route("/*key", get(catch_all));
let app = app.fallback("Catch all route");
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn catch_all() -> Html<String> {
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None));
Html(result.unwrap())
}
// ROUTE_DECLARATIONS
"##;
fn create_main_file(base_path: &Path, bundled_file: &String) {
let mut data_file =
fs::File::create(base_path.join(".tuono/main.rs")).expect("creation failed");
data_file
.write(bundled_file.as_bytes())
.expect("write failed");
}
fn clean_up_source_file(file: &mut String) {}
fn get_route_name<'a>(path: &PathBuf, base_path: &Path) -> String {
let base_path_str = base_path.to_str().unwrap();
if base_path_str == "." {
return path.to_str().unwrap().replace("/src/routes/", "");
}
// TODO: refactor this horrible code
if base_path_str.ends_with("/") {
return path
.to_str()
.unwrap()
.replace(&format!("{base_path_str}src/routes"), "")
.replace(".rs", "")
.replace("index", "");
}
path.to_str()
.unwrap()
.replace(&format!("{base_path_str}/src/routes"), "")
.replace(".rs", "")
.replace("index", "")
}
fn collect_handlers(base_path: &Path) -> (String, HashMap<String, String>) {
let mut declarations = String::from("// ROUTE_DECLARATIONS\n");
let mut fn_map: HashMap<String, String> = HashMap::new();
let _: Vec<_> = glob(base_path.join("src/routes/**/*.rs").to_str().unwrap())
.unwrap()
.map(|entry| {
let entry = entry.unwrap();
let route_name = get_route_name(&entry, base_path);
let mut file_content = fs::read_to_string(entry).unwrap();
clean_up_source_file(&mut file_content);
let hash = fastmurmur3::hash(file_content.as_bytes());
let new_fn_name = format!("fn_{}", hash);
let file_content = file_content.replace("get_server_side_props", &new_fn_name);
fn_map.insert(route_name, new_fn_name);
declarations.push_str(&file_content);
})
.collect();
println!("{fn_map:?}");
return (declarations, fn_map);
}
fn create_axum_routes_declaration(routes: HashMap<String, String>) -> String {
let mut route_declarations = String::from("// ROUTE_BUILDER\n");
for (route, handler) in routes.iter() {
route_declarations.push_str(&format!(r#".route("{route}", get({handler}))"#))
}
route_declarations
}
pub fn bundle() {
println!("Axum project bundling");
let base_path = std::env::current_dir().unwrap();
let (handlers, fn_map) = collect_handlers(&base_path);
let bundled_file = AXUM_ENTRY_POINT.replace(
"// ROUTE_BUILDER\n",
&create_axum_routes_declaration(fn_map),
);
let bundled_file = bundled_file.replace("// ROUTE_DECLARATIONS", &handlers[..]);
create_main_file(&base_path, &bundled_file);
}
+2
View File
@@ -0,0 +1,2 @@
mod bundle;
pub use bundle::bundle;
+1 -1
View File
@@ -12,4 +12,4 @@ path = "src/lib.rs"
clap = { version = "4.5.4", features = ["derive"] }
cargo-watch = "8.5.2"
axum_bundler = { path = "../axum_bundler" }
+3 -10
View File
@@ -1,12 +1,5 @@
fn is_valid_project_folder(_directory: &String) -> bool {
true
}
use axum_bundler::bundle;
pub fn run(directory: String) {
if !is_valid_project_folder(&directory) {
println!("It does not seem to be a valid project folder");
return;
}
todo!()
pub fn run() {
bundle();
}
+6 -11
View File
@@ -1,20 +1,15 @@
use clap::{Parser, Subcommand};
pub mod actions;
use actions::{build, dev, new};
#[derive(Subcommand, Debug)]
enum Actions {
/// Start the development environment
Dev,
/// Build the production assets
Build {
#[arg(short, long, default_value_t = String::from("."))]
directory: String,
},
Build,
/// Create a new project folder
New {
#[arg(short, long, default_value_t = String::from("."))]
_directory: String,
},
New,
}
#[derive(Parser, Debug)]
@@ -28,8 +23,8 @@ pub fn cli() {
let args = Args::parse();
match args.action.unwrap() {
Actions::Dev => actions::dev::run(),
Actions::Build { directory } => actions::build::run(directory),
Actions::New { _directory } => actions::new::run(),
Actions::Dev => dev::run(),
Actions::Build => build::run(),
Actions::New => new::run(),
}
}