Skip to content

Commit

Permalink
Use logger on all modules
Browse files Browse the repository at this point in the history
  • Loading branch information
Bruno rocha committed Oct 19, 2024
1 parent 2153a7d commit ac0ee87
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 86 deletions.
85 changes: 34 additions & 51 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use chrono::{NaiveDate, NaiveDateTime};
use clap::Parser;
use comrak::{markdown_to_html, ComrakOptions};
use env_logger::{Env, Builder};
use env_logger::{Builder, Env};
use frontmatter_gen::{extract, Frontmatter, Value};
use fs_extra::dir::{copy, CopyOptions};
use log::{error, info};
use log::{debug, error, info};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
Expand All @@ -23,26 +23,25 @@ mod robots;
mod server; // Import the server module // Import the robots module

fn main() -> io::Result<()> {

let args = cli::Cli::parse();
let input_folder = args.input_folder;
let output_folder = Arc::new(args.output_folder);
let serve = args.serve;
let debug = args.debug;
let config_path = input_folder.join(args.config);
let bind_address: &str = args.bind.as_str();

let env = Env::default().default_filter_or(if debug { "debug" } else { "info" });
let env = Env::default().default_filter_or(if args.debug { "debug" } else { "info" });
if let Err(e) = Builder::from_env(env).try_init() {
error!("Logger already initialized: {}", e);
}

// Initialize site data
let marmite = fs::read_to_string(&config_path).unwrap_or_else(|e| {
if debug {
error!("Unable to read '{}': {}", &config_path.display(), e);
}
// Default to empty string if config not found, so defaults are applied
debug!(
"Unable to read '{}', assuming defaults.: {}",
&config_path.display(),
e
);
String::new()
});
let site: Marmite = match serde_yaml::from_str(&marmite) {
Expand Down Expand Up @@ -114,7 +113,7 @@ fn main() -> io::Result<()> {
};

// Render templates
if let Err(e) = render_templates(&site_data, &tera, &output_path, debug) {
if let Err(e) = render_templates(&site_data, &tera, &output_path) {
error!("Failed to render templates: {}", e);
process::exit(1);
}
Expand Down Expand Up @@ -344,68 +343,54 @@ fn get_tags(frontmatter: &Frontmatter) -> Vec<String> {
tags
}

fn render_templates(
site_data: &SiteData,
tera: &Tera,
output_dir: &Path,
debug: bool,
) -> Result<(), String> {
fn render_templates(site_data: &SiteData, tera: &Tera, output_dir: &Path) -> Result<(), String> {
// Build the context of variables that are global on every template
let mut global_context = Context::new();
global_context.insert("site_data", &site_data);
global_context.insert("site", &site_data.site);
global_context.insert("menu", &site_data.site.menu);
if debug {
info!("Global Context: {:?}", &site_data.site)
}

debug!("Global Context: {:?}", &site_data.site);
// Render index.html from list.html template
let mut list_context = global_context.clone();
list_context.insert("title", site_data.site.list_title);
list_context.insert("content_list", &site_data.posts);
if debug {
info!(
"Index Context: {:?}",
&site_data
.posts
.iter()
.map(|p| format!("{},{}", p.title, p.slug))
.collect::<Vec<_>>()
)
}
debug!(
"Index Context: {:?}",
&site_data
.posts
.iter()
.map(|p| format!("{},{}", p.title, p.slug))
.collect::<Vec<_>>()
);
generate_html("list.html", "index.html", &tera, &list_context, output_dir)?;

// Render pages.html from list.html template
let mut list_context = global_context.clone();
list_context.insert("title", site_data.site.pages_title);
list_context.insert("content_list", &site_data.pages);
if debug {
info!(
"Pages Context: {:?}",
&site_data
.pages
.iter()
.map(|p| format!("{},{}", p.title, p.slug))
.collect::<Vec<_>>()
)
}
debug!(
"Pages Context: {:?}",
&site_data
.pages
.iter()
.map(|p| format!("{},{}", p.title, p.slug))
.collect::<Vec<_>>()
);
generate_html("list.html", "pages.html", &tera, &list_context, output_dir)?;

// Render individual content-slug.html from content.html template
for content in site_data.posts.iter().chain(&site_data.pages) {
let mut content_context = global_context.clone();
content_context.insert("title", &content.title);
content_context.insert("content", &content);
if debug {
info!(
"{} context: {:?}",
&content.slug,
format!(
"title: {},date: {:?},tags: {:?}",
&content.title, &content.date, &content.tags
)
debug!(
"{} context: {:?}",
&content.slug,
format!(
"title: {},date: {:?},tags: {:?}",
&content.title, &content.date, &content.tags
)
}
);
generate_html(
"content.html",
&format!("{}.html", &content.slug),
Expand Down Expand Up @@ -435,8 +420,6 @@ fn generate_html(
Ok(())
}



#[derive(Debug, Deserialize, Serialize)]
struct Marmite<'a> {
#[serde(default = "default_name")]
Expand Down
61 changes: 31 additions & 30 deletions src/robots.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
use std::fs;
use std::path::Path;

// Copy or create robots.txt
const ROBOTS_SRC: &str = "robots.txt";
const DEFAULT_ROBOTS: &str = "User-agent: *
Disallow: /private
Allow: /public";

pub fn handle_robots(content_dir: &Path, output_path: &Path) {
let robots_src = content_dir.join(ROBOTS_SRC);
let robots_dst = output_path.join(ROBOTS_SRC);

match robots_src.exists() {
true => {
if let Err(e) = fs::copy(&robots_src, &robots_dst) {
eprintln!("Failed to copy robots.txt: {}", e);
} else {
println!("Copied robots.txt to output folder");
}
}
false => {
if let Err(e) = fs::write(&robots_dst, DEFAULT_ROBOTS) {
eprintln!("Failed to create default robots.txt: {}", e);
} else {
println!("Generated default robots.txt in output folder");
}
}
}
}
use log::{error, info};
use std::fs;
use std::path::Path;

// Copy or create robots.txt
const ROBOTS_SRC: &str = "robots.txt";
const DEFAULT_ROBOTS: &str = "User-agent: *
Disallow: /private
Allow: /public";

pub fn handle_robots(content_dir: &Path, output_path: &Path) {
let robots_src = content_dir.join(ROBOTS_SRC);
let robots_dst = output_path.join(ROBOTS_SRC);

match robots_src.exists() {
true => {
if let Err(e) = fs::copy(&robots_src, &robots_dst) {
error!("Failed to copy robots.txt: {}", e);
} else {
info!("Copied robots.txt to output folder");
}
}
false => {
if let Err(e) = fs::write(&robots_dst, DEFAULT_ROBOTS) {
error!("Failed to create default robots.txt: {}", e);
} else {
info!("Generated default robots.txt in output folder");
}
}
}
}
11 changes: 6 additions & 5 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use log::{error, info};
use std::fs::File;
use std::io::Cursor;
use std::path::PathBuf;
Expand All @@ -7,7 +8,7 @@ use tiny_http::{Response, Server};
pub fn start_server(bind_address: &str, output_folder: Arc<PathBuf>) {
let server = Server::http(bind_address).unwrap();

println!(
info!(
"Server started at http://{}/ - Type ^C to stop.",
bind_address
);
Expand All @@ -16,13 +17,13 @@ pub fn start_server(bind_address: &str, output_folder: Arc<PathBuf>) {
let response = match handle_request(&request, &output_folder) {
Ok(response) => response,
Err(err) => {
eprintln!("Error handling request: {}", err);
error!("Error handling request: {}", err);
Response::from_string("Internal Server Error").with_status_code(500)
}
};

if let Err(err) = request.respond(response) {
eprintln!("Failed to send response: {}", err);
error!("Failed to send response: {}", err);
}
}
}
Expand All @@ -46,12 +47,12 @@ fn handle_request(
Ok(Response::from_data(buffer))
}
Err(err) => {
eprintln!("Failed to read file {}: {}", file_path.display(), err);
error!("Failed to read file {}: {}", file_path.display(), err);
Err(format!("Error reading file: {}", err))
}
}
} else {
eprintln!("File not found: {}", file_path.display());
error!("File not found: {}", file_path.display());
Ok(Response::from_string("404 Not Found").with_status_code(404))
}
}

0 comments on commit ac0ee87

Please sign in to comment.