Skip to content

Commit

Permalink
Update logger.rs to use colored output and add success method
Browse files Browse the repository at this point in the history
  • Loading branch information
arjunkomath committed Apr 27, 2024
1 parent 66b7b14 commit 5a03008
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 40 deletions.
40 changes: 22 additions & 18 deletions src/builder/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
dev::server::WEBSOCKET_CLIENT_JS,
shared::{settings, utils},
shared::{logger::Logger, settings, utils},
};

use anyhow::{Context, Result};
Expand Down Expand Up @@ -111,19 +111,20 @@ impl Worker {
Ok(config) => match config.try_deserialize() {
Ok(settings) => settings,
Err(e) => {
println!("{}: {}", "Failed to parse settings file, ".red(), e);
Logger::new().error(&format!("{}: {}", "Failed to parse settings file, ", e));
std::process::exit(1);
}
},
Err(e) => {
println!("{}: {}", "Failed to open settings file, ".red(), e);
Logger::new().error(&format!("{}: {}", "Failed to open settings file, ", e));
std::process::exit(1);
}
}
}

pub fn build(&self) -> Result<()> {
println!("{}...", "\n- Building site".bold());
let log = Logger::new();
log.activity("Building site");

let start_time = Instant::now();

Expand Down Expand Up @@ -173,18 +174,18 @@ impl Worker {

markdown_files.par_iter().for_each(|file| {
if let Err(e) = self.process_file(file, &site_directory) {
println!("{}: {}", "Failed to process file, ".red(), e);
log.error(&format!("{}: {}", "Failed to process file, ", e));
}
});

// Handle robots.txt, ignore if there is a file already
if !Path::new(&self.output_dir).join("robots.txt").exists() {
if let Ok(robots_txt) = seo::generate_robots_txt(&self.get_settings()) {
println!(
log.success(&format!(
"{} {} robots.txt",
"Generated".green(),
"Generated",
"File ".blue()
);
));
fs::write(Path::new(&self.output_dir).join("robots.txt"), robots_txt)?;
}
}
Expand All @@ -194,22 +195,24 @@ impl Worker {
if let Ok(sitemap_xml) =
seo::generate_sitemap_xml(&self.get_settings(), &all_pages_with_metadata)
{
println!(
log.success(&format!(
"{} {} sitemap.xml",
"Generated".green(),
"Generated",
"File ".blue()
);
));
fs::write(Path::new(&self.output_dir).join("sitemap.xml"), sitemap_xml)?;
}
}

let elapsed_time = start_time.elapsed();
println!("Completed in: {:?}", elapsed_time);
log.success(&format!("Completed in: {:?}", elapsed_time));

Ok(())
}

fn process_file(&self, file: &str, site_directory: &serde_yaml::Value) -> Result<()> {
let log = Logger::new();

let html_file = file
.replace(&self.pages_dir, &self.output_dir)
.replace("page.md", "index.html");
Expand Down Expand Up @@ -249,12 +252,12 @@ impl Worker {
.context("Failed to get parent folder")?;
fs::create_dir_all(folder)?;

println!(
log.success(&format!(
"{} {} {}",
"Generated".green(),
"Generated",
"Page ".blue(),
&html_file
);
));

if self.is_dev {
// Add websocket client to html
Expand All @@ -281,12 +284,12 @@ impl Worker {
}

let amp_file = html_file.replace("index.html", "amp/index.html");
println!(
log.success(&format!(
"{} {} {}",
"✔ Generated".green(),
"AMP ".blue(),
&amp_file
);
));
let amp_folder = Path::new(&amp_file)
.parent()
.context("Failed to get parent folder")?;
Expand Down Expand Up @@ -325,7 +328,8 @@ impl Worker {
match current_yaml.get_mut(&serde_yaml::Value::String(path.to_string())) {
Some(serde_yaml::Value::Mapping(x)) => x,
_ => {
println!("{}: {}", "Failed to parse yaml".red(), "Invalid yaml".red());
Logger::new()
.error(&format!("{}: {}", "Failed to parse yaml", "Invalid yaml",));
std::process::exit(1);
}
};
Expand Down
8 changes: 5 additions & 3 deletions src/builder/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{fs, path::Path};

use super::seo;
use crate::shared::{
logger::Logger,
settings::{self, Link},
utils,
};
Expand Down Expand Up @@ -171,7 +172,7 @@ impl Render<'_> {
.map(|url| match cache::get_file(url, self.cache.clone()) {
Ok(style) => style,
Err(e) => {
println!("Failed to download style: {}", e);
Logger::new().error(&format!("Failed to download style: {}", e));
String::new()
}
})
Expand All @@ -192,7 +193,7 @@ impl Render<'_> {
.map(|url| match cache::get_file(url, self.cache.clone()) {
Ok(script) => script,
Err(e) => {
println!("Failed to download script: {}", e);
Logger::new().error(&format!("Failed to download script: {}", e));
String::new()
}
})
Expand Down Expand Up @@ -293,7 +294,8 @@ impl Render<'_> {
result.insert(key.to_string(), value);
}
_ => {
println!("Failed to get remote data for key: {}", url);
Logger::new()
.error(&format!("Failed to get remote data for key: {}", url));
result.insert(key.to_string(), serde_json::Value::Null);
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/create/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ use std::{
format, fs,
io::Write,
path::{Path, PathBuf},
println,
};

use crate::shared::{settings::Settings, utils};
use crate::shared::{logger::Logger, settings::Settings, utils};

use anyhow::{Context, Result};
use async_recursion::async_recursion;
Expand Down Expand Up @@ -69,7 +68,7 @@ async fn download_folder(
.context("Failed to get parent folder")?;
fs::create_dir_all(folder)?;

println!("\tDownloading file: {}", item.path.bold().green());
Logger::new().activity(&format!("\tDownloading file: {}", item.path.bold().green()));

let download_url = format!(
"https://raw.githubusercontent.com/{}/{}/master/{}",
Expand Down Expand Up @@ -101,7 +100,7 @@ pub async fn project(project_dir: &PathBuf, theme: &str) -> Result<()> {
let repo_owner = "arjunkomath";
let repo_name = "rustyink-themes";

println!("- Downloading theme {}", theme.bold().blue());
Logger::new().activity(&format!("Downloading theme {}", theme.bold().blue()));

download_folder(&project_dir, theme, &client, repo_owner, repo_name, theme).await?;

Expand Down
27 changes: 14 additions & 13 deletions src/dev/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use tokio_tungstenite::{
};
use tower_http::{services::ServeDir, trace::TraceLayer};

use crate::builder::Worker;
use crate::{builder::Worker, shared::logger::Logger};

pub type Clients = Arc<Mutex<HashMap<String, SplitSink<WebSocketStream<TcpStream>, Message>>>>;

Expand All @@ -40,11 +40,10 @@ pub async fn start(output_dir: String, port: u16) -> Result<()> {

let app = Router::new().nest_service("/", ServeDir::new(output_dir));

println!(
"✔ Starting Dev server on -> {}:{}",
"http://localhost".bold(),
port
);
Logger::new().success(&format!(
"Dev server started on -> http://localhost:{}",
port.blue()
));

axum::Server::bind(&addr)
.serve(app.layer(TraceLayer::new_for_http()).into_make_service())
Expand Down Expand Up @@ -72,10 +71,12 @@ pub async fn handle_file_changes(
worker: Worker,
clients: Clients,
) -> Result<()> {
println!(
"✔ Watching for changes in -> {}",
let log = Logger::new();

log.success(&format!(
"Watching for changes in -> {}",
input_dir.display().blue().bold()
);
));

let (tx, rx) = std::sync::mpsc::channel();
let mut debouncer = new_debouncer(Duration::from_secs(1), tx)?;
Expand All @@ -85,14 +86,14 @@ pub async fn handle_file_changes(

for result in rx {
match result {
Err(error) => println!("{error:?}"),
Err(error) => log.error(&error.to_string()),
Ok(_) => {
println!("{}", "\n✔ Changes detected, rebuilding...".cyan());
log.info("\nChanges detected, rebuilding...");

if let Err(e) = worker.build() {
println!("- Build failed -> {}", e.to_string().red().bold());
log.error(&format!("Build failed -> {}", e.to_string().red().bold()));
} else {
println!("✔ Build successful, reloading...");
log.success("Build successful, reloading...");
// Send message to all clients to reload
let mut clients = clients.lock().await;
for (_, client) in clients.iter_mut() {
Expand Down
8 changes: 6 additions & 2 deletions src/shared/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@ impl Logger {
}

pub fn info(&self, message: &str) {
println!("- {}", message.blue().bold());
println!("- {}", message.blue());
}

pub fn activity(&self, message: &str) {
println!("\n- {}...", message.bold());
}

pub fn success(&self, message: &str) {
println!("✔ {}", message.green());
}

pub fn error(&self, message: &str) {
println!("- Error: {}", message.to_string().red().bold());
println!("- Error: {}", message.red().bold());
}
}

0 comments on commit 5a03008

Please sign in to comment.