From 45b2de54fbd194531c317fa602b4fafbc8583b87 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 16:51:50 +0200 Subject: [PATCH 01/14] use relative path --- src/routes/agreements.rs | 2 +- src/routes/contrib.rs | 2 +- src/routes/index.rs | 2 +- src/routes/networks.rs | 2 +- src/routes/not_found.rs | 2 +- src/routes/portfolio.rs | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/routes/agreements.rs b/src/routes/agreements.rs index 3e41b74..79d894f 100644 --- a/src/routes/agreements.rs +++ b/src/routes/agreements.rs @@ -14,7 +14,7 @@ pub async fn security(req: HttpRequest, config: web::Data) -> impl Respo } #[derive(Template)] -#[template(path = "../templates/security.txt")] +#[template(path = "security.txt")] struct SecurityTemplate { contact: String, pref_lang: String, diff --git a/src/routes/contrib.rs b/src/routes/contrib.rs index 28bfdd3..b42d38a 100644 --- a/src/routes/contrib.rs +++ b/src/routes/contrib.rs @@ -9,7 +9,7 @@ pub async fn page() -> impl Responder { } #[derive(Template)] -#[template(path = "../templates/contrib.html")] +#[template(path = "contrib.html")] struct PortfolioTemplate {} pub fn get_page() -> std::string::String { diff --git a/src/routes/index.rs b/src/routes/index.rs index 0c1a953..e634b49 100644 --- a/src/routes/index.rs +++ b/src/routes/index.rs @@ -9,7 +9,7 @@ pub async fn page() -> impl Responder { } #[derive(Template)] -#[template(path = "../templates/index.html")] +#[template(path = "index.html")] struct IndexTemplate {} pub fn get_page() -> std::string::String { diff --git a/src/routes/networks.rs b/src/routes/networks.rs index 36df9ac..7758399 100644 --- a/src/routes/networks.rs +++ b/src/routes/networks.rs @@ -9,7 +9,7 @@ pub async fn page() -> impl Responder { } #[derive(Template)] -#[template(path = "../templates/networks.html")] +#[template(path = "networks.html")] struct NetworksTemplate {} pub fn get_page() -> std::string::String { diff --git a/src/routes/not_found.rs b/src/routes/not_found.rs index 5d1f566..bea0985 100644 --- a/src/routes/not_found.rs +++ b/src/routes/not_found.rs @@ -8,7 +8,7 @@ pub async fn page() -> impl Responder { } #[derive(Template)] -#[template(path = "../templates/404.html")] +#[template(path = "404.html")] struct Error404Template {} pub fn get_page() -> std::string::String { diff --git a/src/routes/portfolio.rs b/src/routes/portfolio.rs index 01323df..f17b091 100644 --- a/src/routes/portfolio.rs +++ b/src/routes/portfolio.rs @@ -9,7 +9,7 @@ pub async fn page() -> impl Responder { } #[derive(Template)] -#[template(path = "../templates/portfolio.html")] +#[template(path = "portfolio.html")] struct PortfolioTemplate {} pub fn get_page() -> std::string::String { -- 2.45.2 From f368e57d7fd82425b9821a9910bbcae1486062c9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 16:52:07 +0200 Subject: [PATCH 02/14] don't always minify when rendering html --- src/template.rs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/template.rs b/src/template.rs index 9b7c608..97ca75b 100644 --- a/src/template.rs +++ b/src/template.rs @@ -1,14 +1,5 @@ use askama::DynTemplate; -use minify_html::{minify, Cfg}; pub fn render_html(template: &dyn DynTemplate) -> String { - let data = template.dyn_render().unwrap(); - - // we just minify before sending to the client, - // we need to find a way to pre-minify static pages to the dist folder, - // maybe in release mode? to make debugging easier - // from https://git.mylloon.fr/Anri/mylloon.fr/issues/15 - - let cfg = Cfg::spec_compliant(); - String::from_utf8(minify(data.as_bytes(), &cfg)).unwrap() + template.dyn_render().unwrap() } -- 2.45.2 From ea5ce83658c335228d29723192893b2bfce051c6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 16:58:21 +0200 Subject: [PATCH 03/14] Template minification * use dist/template when exists * move the minification in config.rs * load askama.toml for the templates dirs name * extract the minification of file to minify_and_copy --- askama.toml | 3 ++ src/config.rs | 101 +++++++++++++++++++++++++++++++++++++++++++++++++- src/main.rs | 56 +--------------------------- 3 files changed, 105 insertions(+), 55 deletions(-) create mode 100644 askama.toml diff --git a/askama.toml b/askama.toml new file mode 100644 index 0000000..4c5d332 --- /dev/null +++ b/askama.toml @@ -0,0 +1,3 @@ +[general] +# Directories to search for templates, relative to the crate root. +dirs = ["dist/templates", "templates"] diff --git a/src/config.rs b/src/config.rs index 02380f4..4427086 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,5 +1,12 @@ use serde::Deserialize; -use std::fs; +use std::{ + fs::{self, read_to_string, remove_dir_all}, + path::PathBuf, +}; + +use glob::glob; +use minify_html::{minify, Cfg}; +use std::{fs::File, io::Write, path::Path}; #[derive(Deserialize, Clone, Default)] pub struct FileConfig { @@ -13,6 +20,17 @@ pub struct FileConfig { #[derive(Clone)] pub struct Config { pub fc: FileConfig, + pub static_location: String, +} + +#[derive(Deserialize)] +struct AskamaConfig { + general: AskamaConfigGeneral, +} + +#[derive(Deserialize)] +struct AskamaConfigGeneral { + dirs: Vec, } impl FileConfig { @@ -63,10 +81,91 @@ fn get_file_config(file_path: &str) -> FileConfig { } } +fn get_askama_config() -> AskamaConfig { + toml::from_str(&read_to_string("askama.toml").unwrap()).unwrap() +} + pub fn get_config(file_path: &str) -> Config { let internal_config = get_file_config(file_path); + let static_dir = "static".to_string(); + let templates_dir = get_askama_config().general.dirs.last().unwrap().to_string(); + let files_root = init(static_dir.clone(), templates_dir); + Config { fc: internal_config, + static_location: format!("{}/{}", files_root, static_dir), + } +} + +fn init(static_dir: String, templates_dir: String) -> String { + let dist_folder = "dist".to_string(); + + // println!("static = {}/{}", dist_folder, static_dir); + // println!("templates = {}/{}", dist_folder, templates_dir); + + // The static folder is minimized only in release mode + if cfg!(debug_assertions) { + // Be sure that we not gonna use the dist folder by deleting it + remove_dir_all(dist_folder).unwrap_or_default(); + + ".".to_string() + } else { + let cfg = Cfg::spec_compliant(); + + // Static files + for entry in glob(&format!("{static_dir}/**/*.*")).unwrap() { + let path = entry.unwrap(); + let path_with_dist = path + .to_string_lossy() + .replace(&static_dir, &format!("{dist_folder}/{static_dir}")); + + minify_and_copy(&cfg, path, path_with_dist); + } + + // Template files + for entry in glob(&format!("{templates_dir}/**/*.*")).unwrap() { + let path = entry.unwrap(); + let path_with_dist = path + .to_string_lossy() + .replace(&templates_dir, &format!("{dist_folder}/{templates_dir}")); + + minify_and_copy(&cfg, path, path_with_dist); + } + + dist_folder + } +} + +fn minify_and_copy(cfg: &Cfg, path: PathBuf, path_with_dist: String) { + // Create folders + let new_path = Path::new(&path_with_dist); + fs::create_dir_all(new_path.parent().unwrap()).unwrap(); + + let mut copy = true; + if let Some(ext) = path.extension() { + // List of files who should be minified + if ["html", "css", "js", "svg", "webmanifest", "xml"] + .iter() + .any(|item| ext.to_string_lossy().to_lowercase().contains(item)) + { + // We won't copy, we'll minify + copy = false; + + // Minify + let data = fs::read(&path).unwrap(); + let minified = minify(&data, cfg); + + // Write files + let file = File::create(&path_with_dist); + file.expect("Error when minify the file") + .write_all(&minified) + .unwrap(); + } + } + + if copy { + // If no minification is needed + fs::copy(path, path_with_dist).unwrap(); } } diff --git a/src/main.rs b/src/main.rs index 25874f6..00e7570 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,6 @@ use actix_files::Files; use actix_web::{middleware::DefaultHeaders, web, App, HttpServer}; -use glob::glob; -use minify_html::{minify, Cfg}; -use std::{ - fs::{self, File}, - io::{self, Write}, - path::Path, -}; +use std::io; mod config; mod template; @@ -35,52 +29,6 @@ async fn main() -> io::Result<()> { let addr = ("0.0.0.0", config.fc.port.unwrap()); - let static_folder = "static"; - let dist_folder = format!("dist/{static_folder}"); - - // The static folder is minimized only in release mode - let folder = if cfg!(debug_assertions) { - format!("{static_folder}/") - } else { - let cfg = Cfg::spec_compliant(); - - for entry in glob(&format!("{static_folder}/**/*.*")).unwrap() { - let path = entry.unwrap(); - let path_with_dist = path.to_string_lossy().replace(static_folder, &dist_folder); - - // Create folders - let new_path = Path::new(&path_with_dist); - fs::create_dir_all(new_path.parent().unwrap()).unwrap(); - - let mut copy = true; - if let Some(ext) = path.extension() { - // List of files who should be minified - if ["html", "css", "js", "svg", "webmanifest", "xml"] - .iter() - .any(|item| ext.to_string_lossy().to_lowercase().contains(item)) - { - // We won't copy, we'll minify - copy = false; - - // Minify - let data = fs::read(&path).unwrap(); - let minified = minify(&data, &cfg); - - // Write files - let mut file = File::create(&path_with_dist)?; - file.write_all(&minified)?; - } - } - - if copy { - // If no minification is needed - fs::copy(path, path_with_dist)?; - } - } - - format!("{dist_folder}/") - }; - println!( "Listening to {}://{}:{}", config.clone().fc.scheme.unwrap(), @@ -103,7 +51,7 @@ async fn main() -> io::Result<()> { .service(networks::page) .service(portfolio::page) .service(contrib::page) - .service(Files::new("/", &folder)) + .service(Files::new("/", config.static_location.clone())) .default_service(web::to(not_found::page)) }) .bind(addr)? -- 2.45.2 From c42238a624781e7cae271d53f74c523f473470fb Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 17:01:30 +0200 Subject: [PATCH 04/14] cleanup --- src/config.rs | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/config.rs b/src/config.rs index 4427086..aa85c47 100644 --- a/src/config.rs +++ b/src/config.rs @@ -89,8 +89,10 @@ pub fn get_config(file_path: &str) -> Config { let internal_config = get_file_config(file_path); let static_dir = "static".to_string(); + // TODO: Check if templates dir is coherent with the whole list let templates_dir = get_askama_config().general.dirs.last().unwrap().to_string(); - let files_root = init(static_dir.clone(), templates_dir); + // TODO: Check dist by askama config file + let files_root = init("dist".to_string(), static_dir.clone(), templates_dir); Config { fc: internal_config, @@ -98,16 +100,11 @@ pub fn get_config(file_path: &str) -> Config { } } -fn init(static_dir: String, templates_dir: String) -> String { - let dist_folder = "dist".to_string(); - - // println!("static = {}/{}", dist_folder, static_dir); - // println!("templates = {}/{}", dist_folder, templates_dir); - +fn init(dist_dir: String, static_dir: String, templates_dir: String) -> String { // The static folder is minimized only in release mode if cfg!(debug_assertions) { // Be sure that we not gonna use the dist folder by deleting it - remove_dir_all(dist_folder).unwrap_or_default(); + remove_dir_all(dist_dir).unwrap_or_default(); ".".to_string() } else { @@ -118,7 +115,7 @@ fn init(static_dir: String, templates_dir: String) -> String { let path = entry.unwrap(); let path_with_dist = path .to_string_lossy() - .replace(&static_dir, &format!("{dist_folder}/{static_dir}")); + .replace(&static_dir, &format!("{dist_dir}/{static_dir}")); minify_and_copy(&cfg, path, path_with_dist); } @@ -128,12 +125,12 @@ fn init(static_dir: String, templates_dir: String) -> String { let path = entry.unwrap(); let path_with_dist = path .to_string_lossy() - .replace(&templates_dir, &format!("{dist_folder}/{templates_dir}")); + .replace(&templates_dir, &format!("{dist_dir}/{templates_dir}")); minify_and_copy(&cfg, path, path_with_dist); } - dist_folder + dist_dir } } -- 2.45.2 From d1568f406df77e57b2efccfb721ddd5618c4e4ca Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 17:35:15 +0200 Subject: [PATCH 05/14] always use dist directory --- askama.toml | 3 +-- src/config.rs | 67 +++++++++++++++++++++++++++------------------------ 2 files changed, 36 insertions(+), 34 deletions(-) diff --git a/askama.toml b/askama.toml index 4c5d332..4ac275b 100644 --- a/askama.toml +++ b/askama.toml @@ -1,3 +1,2 @@ [general] -# Directories to search for templates, relative to the crate root. -dirs = ["dist/templates", "templates"] +dirs = ["dist/templates"] diff --git a/src/config.rs b/src/config.rs index aa85c47..589d92d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -89,10 +89,17 @@ pub fn get_config(file_path: &str) -> Config { let internal_config = get_file_config(file_path); let static_dir = "static".to_string(); - // TODO: Check if templates dir is coherent with the whole list - let templates_dir = get_askama_config().general.dirs.last().unwrap().to_string(); - // TODO: Check dist by askama config file - let files_root = init("dist".to_string(), static_dir.clone(), templates_dir); + let templates_dirs = get_askama_config().general.dirs; + if templates_dirs.len() != 1 { + panic!("Too many templates directories") + } + let mut template_data = templates_dirs[0].split('/'); + + let files_root = init( + template_data.next().unwrap().to_string(), + static_dir.clone(), + template_data.next().unwrap().to_string(), + ); Config { fc: internal_config, @@ -101,40 +108,35 @@ pub fn get_config(file_path: &str) -> Config { } fn init(dist_dir: String, static_dir: String, templates_dir: String) -> String { - // The static folder is minimized only in release mode - if cfg!(debug_assertions) { - // Be sure that we not gonna use the dist folder by deleting it - remove_dir_all(dist_dir).unwrap_or_default(); + // Be sure that we not gonna use the dist folder by deleting it + remove_dir_all(&dist_dir).unwrap_or_default(); - ".".to_string() - } else { - let cfg = Cfg::spec_compliant(); + let cfg = Cfg::spec_compliant(); - // Static files - for entry in glob(&format!("{static_dir}/**/*.*")).unwrap() { - let path = entry.unwrap(); - let path_with_dist = path - .to_string_lossy() - .replace(&static_dir, &format!("{dist_dir}/{static_dir}")); + // Static files + for entry in glob(&format!("{static_dir}/**/*.*")).unwrap() { + let path = entry.unwrap(); + let path_with_dist = path + .to_string_lossy() + .replace(&static_dir, &format!("{dist_dir}/{static_dir}")); - minify_and_copy(&cfg, path, path_with_dist); - } - - // Template files - for entry in glob(&format!("{templates_dir}/**/*.*")).unwrap() { - let path = entry.unwrap(); - let path_with_dist = path - .to_string_lossy() - .replace(&templates_dir, &format!("{dist_dir}/{templates_dir}")); - - minify_and_copy(&cfg, path, path_with_dist); - } - - dist_dir + copy_to_dist(&cfg, path, path_with_dist); } + + // Template files + for entry in glob(&format!("{templates_dir}/**/*.*")).unwrap() { + let path = entry.unwrap(); + let path_with_dist = path + .to_string_lossy() + .replace(&templates_dir, &format!("{dist_dir}/{templates_dir}")); + + copy_to_dist(&cfg, path, path_with_dist); + } + + dist_dir } -fn minify_and_copy(cfg: &Cfg, path: PathBuf, path_with_dist: String) { +fn copy_to_dist(cfg: &Cfg, path: PathBuf, path_with_dist: String) { // Create folders let new_path = Path::new(&path_with_dist); fs::create_dir_all(new_path.parent().unwrap()).unwrap(); @@ -145,6 +147,7 @@ fn minify_and_copy(cfg: &Cfg, path: PathBuf, path_with_dist: String) { if ["html", "css", "js", "svg", "webmanifest", "xml"] .iter() .any(|item| ext.to_string_lossy().to_lowercase().contains(item)) + && !cfg!(debug_assertions) { // We won't copy, we'll minify copy = false; -- 2.45.2 From 7322bf005795412083ede49755b1e7feeec1bdcd Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 17:59:18 +0200 Subject: [PATCH 06/14] add script --- run.sh | 31 ++++++++++++++++++++++++ src/main.rs | 68 ++++++++++++++++++++++++++++++++--------------------- 2 files changed, 72 insertions(+), 27 deletions(-) create mode 100755 run.sh diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..ea5d8a6 --- /dev/null +++ b/run.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash + +set -o errexit # crash the script when a command crash +set -o pipefail # same as above for piped command +set -o nounset # crash when a variable doesnt exist + + +# TRACE=1 for debug +if [[ "${TRACE-0}" == "1" ]]; then + set -o xtrace +fi + +cd "$(dirname "$0")" # change script directory + +main() { + dir_dist="./dist" + dir_template="/templates" + if [ ! -d "$dir_dist$dir_template" ]; then + echo "Copy template to dist directory" + mkdir -p "$dir_dist$dir_template" + cp -r ".$dir_template" "$dir_dist" + + echo "Generate minified templates" + cargo run --release -- --no-http + fi + + echo "Run the app" + cargo run --release +} + +main "$@" diff --git a/src/main.rs b/src/main.rs index 00e7570..31807f1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ use actix_files::Files; use actix_web::{middleware::DefaultHeaders, web, App, HttpServer}; +use std::env; use std::io; mod config; @@ -29,32 +30,45 @@ async fn main() -> io::Result<()> { let addr = ("0.0.0.0", config.fc.port.unwrap()); - println!( - "Listening to {}://{}:{}", - config.clone().fc.scheme.unwrap(), - addr.0, - addr.1 - ); + let mut http = true; + let mut args = env::args(); + args.next(); + for argument in args { + if argument == "--no-http" { + http = false + } + } - HttpServer::new(move || { - App::new() - .app_data(web::Data::new(config.clone())) - .wrap(DefaultHeaders::new().add(( - "Onion-Location", - config.fc.onion.as_deref().unwrap_or_default(), - ))) - .service(index::page) - .service(agreements::security) - .service(agreements::humans) - .service(agreements::robots) - .service(agreements::sitemap) - .service(networks::page) - .service(portfolio::page) - .service(contrib::page) - .service(Files::new("/", config.static_location.clone())) - .default_service(web::to(not_found::page)) - }) - .bind(addr)? - .run() - .await + if http { + println!( + "Listening to {}://{}:{}", + config.clone().fc.scheme.unwrap(), + addr.0, + addr.1 + ); + + HttpServer::new(move || { + App::new() + .app_data(web::Data::new(config.clone())) + .wrap(DefaultHeaders::new().add(( + "Onion-Location", + config.fc.onion.as_deref().unwrap_or_default(), + ))) + .service(index::page) + .service(agreements::security) + .service(agreements::humans) + .service(agreements::robots) + .service(agreements::sitemap) + .service(networks::page) + .service(portfolio::page) + .service(contrib::page) + .service(Files::new("/", config.static_location.clone())) + .default_service(web::to(not_found::page)) + }) + .bind(addr)? + .run() + .await + } else { + Ok(()) + } } -- 2.45.2 From 36ca74943a186ff8aa71d4bb57017cc87a8bd717 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 18:03:03 +0200 Subject: [PATCH 07/14] verbose --- run.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/run.sh b/run.sh index ea5d8a6..ca354ce 100755 --- a/run.sh +++ b/run.sh @@ -24,7 +24,8 @@ main() { cargo run --release -- --no-http fi - echo "Run the app" + echo "Run the app" \ + "(in case of minification issue, run 'rm -r dist/ target/')" cargo run --release } -- 2.45.2 From 462370b1d86c741b5d787cc41398394a49fa0e1c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 18:03:53 +0200 Subject: [PATCH 08/14] copy dist --- Dockerfile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dockerfile b/Dockerfile index 7b7f5f3..4953e30 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,6 +5,7 @@ WORKDIR /usr/src/ewp COPY . . RUN cargo install --path . +RUN ewp --no-http FROM debian:bullseye-slim @@ -14,6 +15,7 @@ WORKDIR /app COPY --from=builder /usr/local/cargo/bin/ewp /app/ewp COPY --from=builder /usr/src/ewp/LICENSE /app/LICENSE COPY --from=builder /usr/src/ewp/static /app/static +COPY --from=builder /usr/src/ewp/dist /app/dist RUN mkdir /app/config RUN touch /app/config/config.toml -- 2.45.2 From 5c796c627ba3f5cf965ff87885340f9c738e1270 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 18:23:26 +0200 Subject: [PATCH 09/14] Revert "copy dist" This reverts commit 462370b1d86c741b5d787cc41398394a49fa0e1c. --- Dockerfile | 2 -- 1 file changed, 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 4953e30..7b7f5f3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,6 @@ WORKDIR /usr/src/ewp COPY . . RUN cargo install --path . -RUN ewp --no-http FROM debian:bullseye-slim @@ -15,7 +14,6 @@ WORKDIR /app COPY --from=builder /usr/local/cargo/bin/ewp /app/ewp COPY --from=builder /usr/src/ewp/LICENSE /app/LICENSE COPY --from=builder /usr/src/ewp/static /app/static -COPY --from=builder /usr/src/ewp/dist /app/dist RUN mkdir /app/config RUN touch /app/config/config.toml -- 2.45.2 From e1b0dec100ee44c6412574024c90ce13cded3ec8 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 18:23:35 +0200 Subject: [PATCH 10/14] Revert "verbose" This reverts commit 36ca74943a186ff8aa71d4bb57017cc87a8bd717. --- run.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/run.sh b/run.sh index ca354ce..ea5d8a6 100755 --- a/run.sh +++ b/run.sh @@ -24,8 +24,7 @@ main() { cargo run --release -- --no-http fi - echo "Run the app" \ - "(in case of minification issue, run 'rm -r dist/ target/')" + echo "Run the app" cargo run --release } -- 2.45.2 From 6ebd48aeb6bec26688b965a5211d2c8a3afde25b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 18:23:46 +0200 Subject: [PATCH 11/14] Revert "add script" This reverts commit 7322bf005795412083ede49755b1e7feeec1bdcd. --- run.sh | 31 ------------------------ src/main.rs | 68 +++++++++++++++++++++-------------------------------- 2 files changed, 27 insertions(+), 72 deletions(-) delete mode 100755 run.sh diff --git a/run.sh b/run.sh deleted file mode 100755 index ea5d8a6..0000000 --- a/run.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash - -set -o errexit # crash the script when a command crash -set -o pipefail # same as above for piped command -set -o nounset # crash when a variable doesnt exist - - -# TRACE=1 for debug -if [[ "${TRACE-0}" == "1" ]]; then - set -o xtrace -fi - -cd "$(dirname "$0")" # change script directory - -main() { - dir_dist="./dist" - dir_template="/templates" - if [ ! -d "$dir_dist$dir_template" ]; then - echo "Copy template to dist directory" - mkdir -p "$dir_dist$dir_template" - cp -r ".$dir_template" "$dir_dist" - - echo "Generate minified templates" - cargo run --release -- --no-http - fi - - echo "Run the app" - cargo run --release -} - -main "$@" diff --git a/src/main.rs b/src/main.rs index 31807f1..00e7570 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,5 @@ use actix_files::Files; use actix_web::{middleware::DefaultHeaders, web, App, HttpServer}; -use std::env; use std::io; mod config; @@ -30,45 +29,32 @@ async fn main() -> io::Result<()> { let addr = ("0.0.0.0", config.fc.port.unwrap()); - let mut http = true; - let mut args = env::args(); - args.next(); - for argument in args { - if argument == "--no-http" { - http = false - } - } + println!( + "Listening to {}://{}:{}", + config.clone().fc.scheme.unwrap(), + addr.0, + addr.1 + ); - if http { - println!( - "Listening to {}://{}:{}", - config.clone().fc.scheme.unwrap(), - addr.0, - addr.1 - ); - - HttpServer::new(move || { - App::new() - .app_data(web::Data::new(config.clone())) - .wrap(DefaultHeaders::new().add(( - "Onion-Location", - config.fc.onion.as_deref().unwrap_or_default(), - ))) - .service(index::page) - .service(agreements::security) - .service(agreements::humans) - .service(agreements::robots) - .service(agreements::sitemap) - .service(networks::page) - .service(portfolio::page) - .service(contrib::page) - .service(Files::new("/", config.static_location.clone())) - .default_service(web::to(not_found::page)) - }) - .bind(addr)? - .run() - .await - } else { - Ok(()) - } + HttpServer::new(move || { + App::new() + .app_data(web::Data::new(config.clone())) + .wrap(DefaultHeaders::new().add(( + "Onion-Location", + config.fc.onion.as_deref().unwrap_or_default(), + ))) + .service(index::page) + .service(agreements::security) + .service(agreements::humans) + .service(agreements::robots) + .service(agreements::sitemap) + .service(networks::page) + .service(portfolio::page) + .service(contrib::page) + .service(Files::new("/", config.static_location.clone())) + .default_service(web::to(not_found::page)) + }) + .bind(addr)? + .run() + .await } -- 2.45.2 From d1f1d5d4784b9aa567341240422ddb2f91e28608 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 18:23:51 +0200 Subject: [PATCH 12/14] Revert "always use dist directory" This reverts commit d1568f406df77e57b2efccfb721ddd5618c4e4ca. --- askama.toml | 3 ++- src/config.rs | 67 ++++++++++++++++++++++++--------------------------- 2 files changed, 34 insertions(+), 36 deletions(-) diff --git a/askama.toml b/askama.toml index 4ac275b..4c5d332 100644 --- a/askama.toml +++ b/askama.toml @@ -1,2 +1,3 @@ [general] -dirs = ["dist/templates"] +# Directories to search for templates, relative to the crate root. +dirs = ["dist/templates", "templates"] diff --git a/src/config.rs b/src/config.rs index 589d92d..aa85c47 100644 --- a/src/config.rs +++ b/src/config.rs @@ -89,17 +89,10 @@ pub fn get_config(file_path: &str) -> Config { let internal_config = get_file_config(file_path); let static_dir = "static".to_string(); - let templates_dirs = get_askama_config().general.dirs; - if templates_dirs.len() != 1 { - panic!("Too many templates directories") - } - let mut template_data = templates_dirs[0].split('/'); - - let files_root = init( - template_data.next().unwrap().to_string(), - static_dir.clone(), - template_data.next().unwrap().to_string(), - ); + // TODO: Check if templates dir is coherent with the whole list + let templates_dir = get_askama_config().general.dirs.last().unwrap().to_string(); + // TODO: Check dist by askama config file + let files_root = init("dist".to_string(), static_dir.clone(), templates_dir); Config { fc: internal_config, @@ -108,35 +101,40 @@ pub fn get_config(file_path: &str) -> Config { } fn init(dist_dir: String, static_dir: String, templates_dir: String) -> String { - // Be sure that we not gonna use the dist folder by deleting it - remove_dir_all(&dist_dir).unwrap_or_default(); + // The static folder is minimized only in release mode + if cfg!(debug_assertions) { + // Be sure that we not gonna use the dist folder by deleting it + remove_dir_all(dist_dir).unwrap_or_default(); - let cfg = Cfg::spec_compliant(); + ".".to_string() + } else { + let cfg = Cfg::spec_compliant(); - // Static files - for entry in glob(&format!("{static_dir}/**/*.*")).unwrap() { - let path = entry.unwrap(); - let path_with_dist = path - .to_string_lossy() - .replace(&static_dir, &format!("{dist_dir}/{static_dir}")); + // Static files + for entry in glob(&format!("{static_dir}/**/*.*")).unwrap() { + let path = entry.unwrap(); + let path_with_dist = path + .to_string_lossy() + .replace(&static_dir, &format!("{dist_dir}/{static_dir}")); - copy_to_dist(&cfg, path, path_with_dist); + minify_and_copy(&cfg, path, path_with_dist); + } + + // Template files + for entry in glob(&format!("{templates_dir}/**/*.*")).unwrap() { + let path = entry.unwrap(); + let path_with_dist = path + .to_string_lossy() + .replace(&templates_dir, &format!("{dist_dir}/{templates_dir}")); + + minify_and_copy(&cfg, path, path_with_dist); + } + + dist_dir } - - // Template files - for entry in glob(&format!("{templates_dir}/**/*.*")).unwrap() { - let path = entry.unwrap(); - let path_with_dist = path - .to_string_lossy() - .replace(&templates_dir, &format!("{dist_dir}/{templates_dir}")); - - copy_to_dist(&cfg, path, path_with_dist); - } - - dist_dir } -fn copy_to_dist(cfg: &Cfg, path: PathBuf, path_with_dist: String) { +fn minify_and_copy(cfg: &Cfg, path: PathBuf, path_with_dist: String) { // Create folders let new_path = Path::new(&path_with_dist); fs::create_dir_all(new_path.parent().unwrap()).unwrap(); @@ -147,7 +145,6 @@ fn copy_to_dist(cfg: &Cfg, path: PathBuf, path_with_dist: String) { if ["html", "css", "js", "svg", "webmanifest", "xml"] .iter() .any(|item| ext.to_string_lossy().to_lowercase().contains(item)) - && !cfg!(debug_assertions) { // We won't copy, we'll minify copy = false; -- 2.45.2 From 6d3b4c8398b97cba9ef865f57b87e638aaee03b5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 19:02:06 +0200 Subject: [PATCH 13/14] migration: askama to ramhorns --- Cargo.lock | 177 ++++++++++++++++++++++++++------------- Cargo.toml | 2 +- askama.toml | 3 - src/config.rs | 28 ++----- src/routes/agreements.rs | 32 +++---- src/routes/contrib.rs | 22 ++--- src/routes/index.rs | 17 ++-- src/routes/networks.rs | 21 +++-- src/routes/not_found.rs | 17 ++-- src/routes/portfolio.rs | 21 +++-- src/template.rs | 9 +- 11 files changed, 204 insertions(+), 145 deletions(-) delete mode 100644 askama.toml diff --git a/Cargo.lock b/Cargo.lock index cba6a81..7489246 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -260,33 +260,10 @@ dependencies = [ ] [[package]] -name = "askama" -version = "0.12.0" +name = "arrayvec" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47cbc3cf73fa8d9833727bbee4835ba5c421a0d65b72daf9a7b5d0e0f9cfb57e" -dependencies = [ - "askama_derive", - "askama_escape", - "humansize", - "num-traits", - "percent-encoding", -] - -[[package]] -name = "askama_derive" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c22fbe0413545c098358e56966ff22cdd039e10215ae213cfbd65032b119fc94" -dependencies = [ - "basic-toml", - "mime", - "mime_guess", - "nom", - "proc-macro2", - "quote", - "serde", - "syn 2.0.13", -] +checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" [[package]] name = "askama_escape" @@ -300,6 +277,19 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +[[package]] +name = "bae" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33b8de67cc41132507eeece2584804efcb15f85ba516e34c944b7667f480397a" +dependencies = [ + "heck", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "base64" version = "0.21.0" @@ -307,13 +297,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" [[package]] -name = "basic-toml" -version = "0.1.2" +name = "beef" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c0de75129aa8d0cceaf750b89013f0e08804d6ec61416da787b35ad0d7cddf1" -dependencies = [ - "serde", -] +checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" [[package]] name = "bitflags" @@ -475,9 +462,9 @@ version = "0.1.0" dependencies = [ "actix-files", "actix-web", - "askama", "glob", "minify-html", + "ramhorns", "serde", "toml", ] @@ -589,6 +576,15 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +[[package]] +name = "heck" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "hermit-abi" version = "0.2.6" @@ -627,15 +623,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" -[[package]] -name = "humansize" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7" -dependencies = [ - "libm", -] - [[package]] name = "idna" version = "0.3.0" @@ -689,12 +676,6 @@ version = "0.2.141" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3304a64d199bb964be99741b7a14d26972741915b3649639149b2479bb46f4b5" -[[package]] -name = "libm" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb" - [[package]] name = "local-channel" version = "0.1.3" @@ -732,6 +713,29 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "logos" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf8b031682c67a8e3d5446840f9573eb7fe26efe7ec8d195c9ac4c0647c502f1" +dependencies = [ + "logos-derive", +] + +[[package]] +name = "logos-derive" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d849148dbaf9661a6151d1ca82b13bb4c4c128146a88d05253b38d4e2f496c" +dependencies = [ + "beef", + "fnv", + "proc-macro2", + "quote", + "regex-syntax", + "syn 1.0.109", +] + [[package]] name = "memchr" version = "2.5.0" @@ -815,15 +819,6 @@ dependencies = [ "minimal-lexical", ] -[[package]] -name = "num-traits" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" -dependencies = [ - "autocfg", -] - [[package]] name = "num_cpus" version = "1.15.0" @@ -910,6 +905,30 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" version = "1.0.56" @@ -919,6 +938,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pulldown-cmark" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d9cc634bc78768157b5cbfe988ffcd1dcba95cd2b2f03a88316c08c6d00ed63" +dependencies = [ + "bitflags", + "memchr", + "unicase", +] + [[package]] name = "quote" version = "1.0.26" @@ -928,6 +958,33 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "ramhorns" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47008ae2e2a9085a3f658203609d79f8a027829cf88a088d0c0084e18ba8f0b9" +dependencies = [ + "arrayvec", + "beef", + "fnv", + "logos", + "pulldown-cmark", + "ramhorns-derive", +] + +[[package]] +name = "ramhorns-derive" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada9bbdd21adf426f932bf76b3db7d553538dffc16afd5fb8ce2ce2110a75536" +dependencies = [ + "bae", + "fnv", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "rand" version = "0.8.5" @@ -1300,6 +1357,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + [[package]] name = "url" version = "2.3.1" diff --git a/Cargo.toml b/Cargo.toml index a817a98..8ab6a74 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ license = "AGPL-3.0-or-later" [dependencies] actix-web = "4" actix-files = "0.6" -askama = "0.12.0" +ramhorns = "0.14.0" toml = "0.7.3" serde = { version = "1.0.159", features = ["derive"] } minify-html = "0.10.8" diff --git a/askama.toml b/askama.toml deleted file mode 100644 index 4c5d332..0000000 --- a/askama.toml +++ /dev/null @@ -1,3 +0,0 @@ -[general] -# Directories to search for templates, relative to the crate root. -dirs = ["dist/templates", "templates"] diff --git a/src/config.rs b/src/config.rs index aa85c47..d0bf191 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,6 +1,6 @@ use serde::Deserialize; use std::{ - fs::{self, read_to_string, remove_dir_all}, + fs::{self, remove_dir_all}, path::PathBuf, }; @@ -21,16 +21,7 @@ pub struct FileConfig { pub struct Config { pub fc: FileConfig, pub static_location: String, -} - -#[derive(Deserialize)] -struct AskamaConfig { - general: AskamaConfigGeneral, -} - -#[derive(Deserialize)] -struct AskamaConfigGeneral { - dirs: Vec, + pub templates_location: String, } impl FileConfig { @@ -81,22 +72,21 @@ fn get_file_config(file_path: &str) -> FileConfig { } } -fn get_askama_config() -> AskamaConfig { - toml::from_str(&read_to_string("askama.toml").unwrap()).unwrap() -} - pub fn get_config(file_path: &str) -> Config { let internal_config = get_file_config(file_path); let static_dir = "static".to_string(); - // TODO: Check if templates dir is coherent with the whole list - let templates_dir = get_askama_config().general.dirs.last().unwrap().to_string(); - // TODO: Check dist by askama config file - let files_root = init("dist".to_string(), static_dir.clone(), templates_dir); + let templates_dir = "templates".to_string(); + let files_root = init( + "dist".to_string(), + static_dir.clone(), + templates_dir.clone(), + ); Config { fc: internal_config, static_location: format!("{}/{}", files_root, static_dir), + templates_location: format!("{}/{}", files_root, templates_dir), } } diff --git a/src/routes/agreements.rs b/src/routes/agreements.rs index 79d894f..4d61bdb 100644 --- a/src/routes/agreements.rs +++ b/src/routes/agreements.rs @@ -1,7 +1,6 @@ +use crate::{config::Config, template::render}; use actix_web::{dev::ConnectionInfo, get, routes, web, HttpRequest, HttpResponse, Responder}; -use askama::Template; - -use crate::config::Config; +use ramhorns::Content; #[routes] #[get("/.well-known/security.txt")] @@ -13,8 +12,7 @@ pub async fn security(req: HttpRequest, config: web::Data) -> impl Respo )) } -#[derive(Template)] -#[template(path = "security.txt")] +#[derive(Content)] struct SecurityTemplate { contact: String, pref_lang: String, @@ -22,17 +20,19 @@ struct SecurityTemplate { } fn get_security(config: Config, info: ConnectionInfo) -> String { - let data = SecurityTemplate { - contact: config.fc.mail.unwrap_or_default(), - pref_lang: config.fc.lang.unwrap_or_default(), - url: format!( - "{}://{}/.well-known/security.txt", - info.scheme(), - info.host() - ), - }; - - data.render().unwrap() + render( + config.templates_location, + "security.txt", + SecurityTemplate { + contact: config.fc.mail.unwrap_or_default(), + pref_lang: config.fc.lang.unwrap_or_default(), + url: format!( + "{}://{}/.well-known/security.txt", + info.scheme(), + info.host() + ), + }, + ) } #[get("/humans.txt")] diff --git a/src/routes/contrib.rs b/src/routes/contrib.rs index b42d38a..265684f 100644 --- a/src/routes/contrib.rs +++ b/src/routes/contrib.rs @@ -1,17 +1,19 @@ -use actix_web::{get, HttpResponse, Responder}; -use askama::Template; - -use crate::template::render_html; +use crate::{config::Config, template::render}; +use actix_web::{get, web, HttpResponse, Responder}; +use ramhorns::Content; #[get("/contrib")] -pub async fn page() -> impl Responder { - HttpResponse::Ok().body(get_page()) +pub async fn page(config: web::Data) -> impl Responder { + HttpResponse::Ok().body(get_page(config.get_ref().clone())) } -#[derive(Template)] -#[template(path = "contrib.html")] +#[derive(Content)] struct PortfolioTemplate {} -pub fn get_page() -> std::string::String { - render_html(&PortfolioTemplate {}) +pub fn get_page(config: Config) -> std::string::String { + render( + config.templates_location, + "contrib.html", + PortfolioTemplate {}, + ) } diff --git a/src/routes/index.rs b/src/routes/index.rs index e634b49..b687834 100644 --- a/src/routes/index.rs +++ b/src/routes/index.rs @@ -1,17 +1,16 @@ -use actix_web::{get, HttpResponse, Responder}; -use askama::Template; +use actix_web::{get, web, HttpResponse, Responder}; +use ramhorns::Content; -use crate::template::render_html; +use crate::{config::Config, template::render}; #[get("/")] -pub async fn page() -> impl Responder { - HttpResponse::Ok().body(get_page()) +pub async fn page(config: web::Data) -> impl Responder { + HttpResponse::Ok().body(get_page(config.get_ref().clone())) } -#[derive(Template)] -#[template(path = "index.html")] +#[derive(Content)] struct IndexTemplate {} -pub fn get_page() -> std::string::String { - render_html(&IndexTemplate {}) +pub fn get_page(config: Config) -> std::string::String { + render(config.templates_location, "index.html", IndexTemplate {}) } diff --git a/src/routes/networks.rs b/src/routes/networks.rs index 7758399..58a6c44 100644 --- a/src/routes/networks.rs +++ b/src/routes/networks.rs @@ -1,17 +1,20 @@ -use actix_web::{get, HttpResponse, Responder}; -use askama::Template; +use actix_web::{get, web, HttpResponse, Responder}; +use ramhorns::Content; -use crate::template::render_html; +use crate::{config::Config, template::render}; #[get("/networks")] -pub async fn page() -> impl Responder { - HttpResponse::Ok().body(get_page()) +pub async fn page(config: web::Data) -> impl Responder { + HttpResponse::Ok().body(get_page(config.get_ref().clone())) } -#[derive(Template)] -#[template(path = "networks.html")] +#[derive(Content)] struct NetworksTemplate {} -pub fn get_page() -> std::string::String { - render_html(&NetworksTemplate {}) +pub fn get_page(config: Config) -> std::string::String { + render( + config.templates_location, + "networks.html", + NetworksTemplate {}, + ) } diff --git a/src/routes/not_found.rs b/src/routes/not_found.rs index bea0985..2da5c3a 100644 --- a/src/routes/not_found.rs +++ b/src/routes/not_found.rs @@ -1,16 +1,15 @@ -use actix_web::{HttpResponse, Responder}; -use askama::Template; +use actix_web::{web, HttpResponse, Responder}; +use ramhorns::Content; -use crate::template::render_html; +use crate::{config::Config, template::render}; -pub async fn page() -> impl Responder { - HttpResponse::NotFound().body(get_page()) +pub async fn page(config: web::Data) -> impl Responder { + HttpResponse::NotFound().body(get_page(config.get_ref().clone())) } -#[derive(Template)] -#[template(path = "404.html")] +#[derive(Content)] struct Error404Template {} -pub fn get_page() -> std::string::String { - render_html(&Error404Template {}) +pub fn get_page(config: Config) -> std::string::String { + render(config.templates_location, "404.html", Error404Template {}) } diff --git a/src/routes/portfolio.rs b/src/routes/portfolio.rs index f17b091..328838d 100644 --- a/src/routes/portfolio.rs +++ b/src/routes/portfolio.rs @@ -1,17 +1,20 @@ -use actix_web::{get, HttpResponse, Responder}; -use askama::Template; +use actix_web::{get, web, HttpResponse, Responder}; +use ramhorns::Content; -use crate::template::render_html; +use crate::{config::Config, template::render}; #[get("/portfolio")] -pub async fn page() -> impl Responder { - HttpResponse::Ok().body(get_page()) +pub async fn page(config: web::Data) -> impl Responder { + HttpResponse::Ok().body(get_page(config.get_ref().clone())) } -#[derive(Template)] -#[template(path = "portfolio.html")] +#[derive(Content)] struct PortfolioTemplate {} -pub fn get_page() -> std::string::String { - render_html(&PortfolioTemplate {}) +pub fn get_page(config: Config) -> std::string::String { + render( + config.templates_location, + "portfolio.html", + PortfolioTemplate {}, + ) } diff --git a/src/template.rs b/src/template.rs index 97ca75b..82fee19 100644 --- a/src/template.rs +++ b/src/template.rs @@ -1,5 +1,8 @@ -use askama::DynTemplate; +use ramhorns::{Content, Ramhorns}; -pub fn render_html(template: &dyn DynTemplate) -> String { - template.dyn_render().unwrap() +pub fn render(template_dir: String, template: &str, data: C) -> String { + let mut tpls: Ramhorns = Ramhorns::lazy(template_dir).unwrap(); + let tpl = tpls.from_file(template).unwrap(); + + tpl.render(&data) } -- 2.45.2 From eb9e7e22f3b07ecb8ae7dab1a2724fd49e026f74 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 9 Apr 2023 19:26:20 +0200 Subject: [PATCH 14/14] impl render to template class --- src/config.rs | 20 ++++++++++++-------- src/routes/agreements.rs | 5 ++--- src/routes/contrib.rs | 8 ++------ src/routes/index.rs | 4 ++-- src/routes/networks.rs | 8 ++------ src/routes/not_found.rs | 4 ++-- src/routes/portfolio.rs | 8 ++------ src/template.rs | 17 ++++++++++++----- 8 files changed, 36 insertions(+), 38 deletions(-) diff --git a/src/config.rs b/src/config.rs index d0bf191..acf6af0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,6 +8,8 @@ use glob::glob; use minify_html::{minify, Cfg}; use std::{fs::File, io::Write, path::Path}; +use crate::template::Template; + #[derive(Deserialize, Clone, Default)] pub struct FileConfig { pub scheme: Option, @@ -17,13 +19,6 @@ pub struct FileConfig { pub onion: Option, } -#[derive(Clone)] -pub struct Config { - pub fc: FileConfig, - pub static_location: String, - pub templates_location: String, -} - impl FileConfig { fn new() -> Self { Self { @@ -56,6 +51,13 @@ impl FileConfig { } } +#[derive(Clone)] +pub struct Config { + pub fc: FileConfig, + pub static_location: String, + pub tmpl: Template, +} + fn get_file_config(file_path: &str) -> FileConfig { match fs::read_to_string(file_path) { Ok(file) => match toml::from_str(&file) { @@ -86,7 +88,9 @@ pub fn get_config(file_path: &str) -> Config { Config { fc: internal_config, static_location: format!("{}/{}", files_root, static_dir), - templates_location: format!("{}/{}", files_root, templates_dir), + tmpl: Template { + directory: format!("{}/{}", files_root, templates_dir), + }, } } diff --git a/src/routes/agreements.rs b/src/routes/agreements.rs index 4d61bdb..9a5c570 100644 --- a/src/routes/agreements.rs +++ b/src/routes/agreements.rs @@ -1,4 +1,4 @@ -use crate::{config::Config, template::render}; +use crate::config::Config; use actix_web::{dev::ConnectionInfo, get, routes, web, HttpRequest, HttpResponse, Responder}; use ramhorns::Content; @@ -20,8 +20,7 @@ struct SecurityTemplate { } fn get_security(config: Config, info: ConnectionInfo) -> String { - render( - config.templates_location, + config.tmpl.render( "security.txt", SecurityTemplate { contact: config.fc.mail.unwrap_or_default(), diff --git a/src/routes/contrib.rs b/src/routes/contrib.rs index 265684f..50ed003 100644 --- a/src/routes/contrib.rs +++ b/src/routes/contrib.rs @@ -1,4 +1,4 @@ -use crate::{config::Config, template::render}; +use crate::config::Config; use actix_web::{get, web, HttpResponse, Responder}; use ramhorns::Content; @@ -11,9 +11,5 @@ pub async fn page(config: web::Data) -> impl Responder { struct PortfolioTemplate {} pub fn get_page(config: Config) -> std::string::String { - render( - config.templates_location, - "contrib.html", - PortfolioTemplate {}, - ) + config.tmpl.render("contrib.html", PortfolioTemplate {}) } diff --git a/src/routes/index.rs b/src/routes/index.rs index b687834..f985d30 100644 --- a/src/routes/index.rs +++ b/src/routes/index.rs @@ -1,7 +1,7 @@ use actix_web::{get, web, HttpResponse, Responder}; use ramhorns::Content; -use crate::{config::Config, template::render}; +use crate::config::Config; #[get("/")] pub async fn page(config: web::Data) -> impl Responder { @@ -12,5 +12,5 @@ pub async fn page(config: web::Data) -> impl Responder { struct IndexTemplate {} pub fn get_page(config: Config) -> std::string::String { - render(config.templates_location, "index.html", IndexTemplate {}) + config.tmpl.render("index.html", IndexTemplate {}) } diff --git a/src/routes/networks.rs b/src/routes/networks.rs index 58a6c44..d726919 100644 --- a/src/routes/networks.rs +++ b/src/routes/networks.rs @@ -1,7 +1,7 @@ use actix_web::{get, web, HttpResponse, Responder}; use ramhorns::Content; -use crate::{config::Config, template::render}; +use crate::config::Config; #[get("/networks")] pub async fn page(config: web::Data) -> impl Responder { @@ -12,9 +12,5 @@ pub async fn page(config: web::Data) -> impl Responder { struct NetworksTemplate {} pub fn get_page(config: Config) -> std::string::String { - render( - config.templates_location, - "networks.html", - NetworksTemplate {}, - ) + config.tmpl.render("networks.html", NetworksTemplate {}) } diff --git a/src/routes/not_found.rs b/src/routes/not_found.rs index 2da5c3a..9e57b20 100644 --- a/src/routes/not_found.rs +++ b/src/routes/not_found.rs @@ -1,7 +1,7 @@ use actix_web::{web, HttpResponse, Responder}; use ramhorns::Content; -use crate::{config::Config, template::render}; +use crate::config::Config; pub async fn page(config: web::Data) -> impl Responder { HttpResponse::NotFound().body(get_page(config.get_ref().clone())) @@ -11,5 +11,5 @@ pub async fn page(config: web::Data) -> impl Responder { struct Error404Template {} pub fn get_page(config: Config) -> std::string::String { - render(config.templates_location, "404.html", Error404Template {}) + config.tmpl.render("404.html", Error404Template {}) } diff --git a/src/routes/portfolio.rs b/src/routes/portfolio.rs index 328838d..98386e0 100644 --- a/src/routes/portfolio.rs +++ b/src/routes/portfolio.rs @@ -1,7 +1,7 @@ use actix_web::{get, web, HttpResponse, Responder}; use ramhorns::Content; -use crate::{config::Config, template::render}; +use crate::config::Config; #[get("/portfolio")] pub async fn page(config: web::Data) -> impl Responder { @@ -12,9 +12,5 @@ pub async fn page(config: web::Data) -> impl Responder { struct PortfolioTemplate {} pub fn get_page(config: Config) -> std::string::String { - render( - config.templates_location, - "portfolio.html", - PortfolioTemplate {}, - ) + config.tmpl.render("portfolio.html", PortfolioTemplate {}) } diff --git a/src/template.rs b/src/template.rs index 82fee19..1c8e015 100644 --- a/src/template.rs +++ b/src/template.rs @@ -1,8 +1,15 @@ use ramhorns::{Content, Ramhorns}; -pub fn render(template_dir: String, template: &str, data: C) -> String { - let mut tpls: Ramhorns = Ramhorns::lazy(template_dir).unwrap(); - let tpl = tpls.from_file(template).unwrap(); - - tpl.render(&data) +#[derive(Clone)] +pub struct Template { + pub directory: String, +} + +impl Template { + pub fn render(&self, template: &str, data: C) -> String { + let mut templates: Ramhorns = Ramhorns::lazy(&self.directory).unwrap(); + let tplt = templates.from_file(template).unwrap(); + + tplt.render(&data) + } } -- 2.45.2