BefehlsWerk/src/lib.rs
2025-05-25 21:46:52 +02:00

64 lines
1.7 KiB
Rust

#![allow(clippy::expect_used)]
use db::import_scripts;
use router::new_router;
use script::Script;
use tokio::net::TcpListener;
use tracing::info;
use walkdir::WalkDir;
mod db;
mod router;
mod script;
pub fn run<T: AsRef<str>>(db_path: T, script_path: T) {
let rt = tokio::runtime::Runtime::new().expect("async runtime should always be available");
rt.block_on(async {
tracing_subscriber::fmt::init();
let db = if let Ok(db) = db::open(db_path.as_ref()).await {
db
} else {
db::new(db_path.as_ref())
.await
.expect("should always be able to create database")
};
let scripts = read_scripts(script_path.as_ref()).expect("failed to read scripts from dir");
import_scripts(&db, scripts)
.await
.expect("failed to write scripts to db");
let app = new_router(db);
let listener = TcpListener::bind("0.0.0.0:3000")
.await
.expect("could not attach listener");
info!(
"listening" = format!(
"http://{}",
listener
.local_addr()
.expect("should always return local address")
)
);
axum::serve(listener, app)
.await
.expect("should always serve app");
});
}
fn read_scripts<T: AsRef<str>>(dir: T) -> Result<Vec<Script>, String> {
WalkDir::new(dir.as_ref())
.into_iter()
.flatten()
.filter(|e| {
let p = e.path();
p.is_file() && p.extension().is_some_and(|ext| ext == "ps1")
})
.map(|e| format!("{}", e.path().to_string_lossy()))
.map(Script::from_file)
.collect()
}