Skip to content

Commit

Permalink
fix(ssg): 🐛 fix formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastienrousseau committed Sep 10, 2024
1 parent fe20cc6 commit e801250
Show file tree
Hide file tree
Showing 26 changed files with 151 additions and 94 deletions.
4 changes: 3 additions & 1 deletion benches/bench_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ pub(crate) fn bench_json(c: &mut Criterion) {
b.iter(|| manifest(black_box(&manifest_data)))
});

let _ = c.bench_function("txt", |b| b.iter(|| txt(black_box(&txt_data))));
let _ = c.bench_function("txt", |b| {
b.iter(|| txt(black_box(&txt_data)))
});

let _ = c.bench_function("cname", |b| {
b.iter(|| cname(black_box(&cname_data)))
Expand Down
17 changes: 9 additions & 8 deletions benches/bench_utilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,15 @@ pub(crate) fn bench_utilities(c: &mut Criterion) {
});

// Benchmarks checking if a directory is a directory.
let _ = c.bench_function("check if directory is a directory", |b| {
b.iter(|| {
// Checks if the directory is a directory.
let result = dir.is_dir();
// Asserts that the result is true, indicating that the directory is a directory.
assert!(result);
})
});
let _ =
c.bench_function("check if directory is a directory", |b| {
b.iter(|| {
// Checks if the directory is a directory.
let result = dir.is_dir();
// Asserts that the result is true, indicating that the directory is a directory.
assert!(result);
})
});

// Benchmarks checking if a non-existent directory does not exist.
let _ = c.bench_function(
Expand Down
2 changes: 1 addition & 1 deletion examples/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
//! function to generate the website.
// Import the required libraries and modules.
use anyhow::Result;
use ssg_core::compiler::service::compile;
use ssg_core::server::serve::start;
use std::path::Path;
use anyhow::Result;

fn main() -> Result<()> {
// Define the paths to the build, site, source and template directories.
Expand Down
14 changes: 6 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,17 +117,15 @@ pub use ssg_core;
pub use ssg_cli;

use anyhow::Result;
use dtt::datetime::DateTime;
use rlg::{log_format::LogFormat, log_level::LogLevel, macro_log};
use ssg_cli::cli::print_banner;
use ssg_core::macro_serve;
use ssg_core::{
compiler::service::compile,
languages::translate,
loggers::init_logger,
server::serve::start,
compiler::service::compile, languages::translate,
loggers::init_logger, server::serve::start,
utilities::uuid::generate_unique_string,
};
use ssg_core::macro_serve;
use ssg_cli::cli::print_banner;
use dtt::datetime::DateTime;
use rlg::{log_format::LogFormat, log_level::LogLevel, macro_log};
use std::io::Write;
use std::{fs::File, path::Path};

Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
//! If an error occurs while running the `run()` function, the function prints an error message
//! to standard error and exits the program with a non-zero status code.
use ssg_core::languages::translate;
use ssg::run;
use ssg_core::languages::translate;

fn main() {
match run() {
Expand Down
5 changes: 3 additions & 2 deletions ssg-cli/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright © 2024 Shokunin Static Site Generator. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

use clap::{Command, Arg, ArgMatches};
use anyhow::Result;
use clap::{Arg, ArgMatches, Command};
use log::debug;

/// # Function: `build`
Expand Down Expand Up @@ -122,7 +122,8 @@ pub fn build() -> Result<ArgMatches> {
pub fn print_banner() {
// Define the title and description
let title = "Shokunin (ssg) 🦀 v0.0.30";
let description = "A Fast and Flexible Static Site Generator written in Rust";
let description =
"A Fast and Flexible Static Site Generator written in Rust";

// Determine the box width based on the longest string
let width = title.len().max(description.len()) + 4;
Expand Down
2 changes: 1 addition & 1 deletion ssg-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT

use anyhow::Result;
use log::info;
use ssg_cli::cli::{build, print_banner};
use ssg_cli::process::args;
use log::info;

/// # Function: `main`
///
Expand Down
14 changes: 8 additions & 6 deletions ssg-cli/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
// Copyright © 2024 Shokunin Static Site Generator. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

use anyhow::{Result, anyhow};
use anyhow::{anyhow, Result};
use clap::ArgMatches;
use std::path::Path;
use log::{info, debug};
use log::{debug, info};
use ssg_core::compiler::service::compile;
use std::path::Path;

/// # Function: `args`
///
Expand Down Expand Up @@ -85,7 +85,8 @@ pub fn args(matches: &ArgMatches) -> Result<()> {
///
/// - Returns an error if the argument is missing or if there is an issue retrieving it.
fn get_arg(matches: &ArgMatches, name: &str) -> Result<String> {
matches.get_one::<String>(name)
matches
.get_one::<String>(name)
.cloned()
.ok_or_else(|| anyhow!("Argument '{}' not provided", name))
}
Expand All @@ -110,8 +111,9 @@ fn get_arg(matches: &ArgMatches, name: &str) -> Result<String> {
/// - Returns an error if the directory does not exist and cannot be created.
fn check_directory(path: &Path, name: &str) -> Result<()> {
if !path.exists() {
std::fs::create_dir_all(path)
.map_err(|e| anyhow!("Failed to create {} directory: {}", name, e))?;
std::fs::create_dir_all(path).map_err(|e| {
anyhow!("Failed to create {} directory: {}", name, e)
})?;

Check warning on line 116 in ssg-cli/src/process.rs

View check run for this annotation

Codecov / codecov/patch

ssg-cli/src/process.rs#L112-L116

Added lines #L112 - L116 were not covered by tests
}
Ok(())
}

Check warning on line 119 in ssg-cli/src/process.rs

View check run for this annotation

Codecov / codecov/patch

ssg-cli/src/process.rs#L118-L119

Added lines #L118 - L119 were not covered by tests
26 changes: 17 additions & 9 deletions ssg-core/src/compiler/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// PaperOrientation, PaperSize,
// };

use anyhow::{Result, Context};
use anyhow::{Context, Result};
use rlg::log_level::LogLevel::ERROR;

// use crate::modules::pdf::generate_pdf;
Expand Down Expand Up @@ -65,29 +65,35 @@ pub fn compile(
template_path: &Path, // The path to the template directory
) -> Result<()> {
// Create build and site directories
macro_create_directories!(build_dir_path, site_path).context("Failed to create directories")?;
macro_create_directories!(build_dir_path, site_path)
.context("Failed to create directories")?;

Check warning on line 69 in ssg-core/src/compiler/service.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/compiler/service.rs#L68-L69

Added lines #L68 - L69 were not covered by tests

// Read files in the source directory
let source_files = add(content_path).context("Failed to read source files")?;
let source_files =
add(content_path).context("Failed to read source files")?;

Check warning on line 73 in ssg-core/src/compiler/service.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/compiler/service.rs#L73

Added line #L73 was not covered by tests

// Generate navigation bar HTML
let navigation = NavigationGenerator::generate_navigation(&source_files);
let navigation =
NavigationGenerator::generate_navigation(&source_files);

let mut global_tags_data: HashMap<String, Vec<PageData>> = HashMap::new();
let mut global_tags_data: HashMap<String, Vec<PageData>> =
HashMap::new();

// Process source files and store results in 'compiled_files' vector
let compiled_files: Result<Vec<FileData>> = source_files

Check warning on line 83 in ssg-core/src/compiler/service.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/compiler/service.rs#L83

Added line #L83 was not covered by tests
.into_iter()
.map(|file| -> Result<FileData> {

Check warning on line 85 in ssg-core/src/compiler/service.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/compiler/service.rs#L85

Added line #L85 was not covered by tests
let (metadata, keywords, all_meta_tags) = extract_and_prepare_metadata(&file.content);
let (metadata, keywords, all_meta_tags) =
extract_and_prepare_metadata(&file.content);

// Generate HTML
let html_content = generate_html(
&file.content,
&macro_metadata_option!(metadata, "title"),
&macro_metadata_option!(metadata, "description"),
Some(&macro_metadata_option!(metadata, "content")),
).context("Failed to generate HTML")?;
)
.context("Failed to generate HTML")?;

Check warning on line 96 in ssg-core/src/compiler/service.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/compiler/service.rs#L96

Added line #L96 was not covered by tests

// Determine the filename without the extension
// let filename_without_extension = Path::new(&file.name)
Expand Down Expand Up @@ -365,10 +371,12 @@ pub fn compile(
write_tags_html_to_file(&tags_html_content, build_dir_path)?;

// Cleanup site directory
macro_cleanup_directories!(site_path).context("Failed to clean up site directory")?;
macro_cleanup_directories!(site_path)
.context("Failed to clean up site directory")?;

Check warning on line 375 in ssg-core/src/compiler/service.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/compiler/service.rs#L374-L375

Added lines #L374 - L375 were not covered by tests

// Move build content to site directory and remove build directory
fs::rename(build_dir_path, site_path).context("Failed to rename build directory")?;
fs::rename(build_dir_path, site_path)
.context("Failed to rename build directory")?;

Check warning on line 379 in ssg-core/src/compiler/service.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/compiler/service.rs#L378-L379

Added lines #L378 - L379 were not covered by tests

Ok(())
}
6 changes: 2 additions & 4 deletions ssg-core/src/loggers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

//! Application logging functionality
use anyhow::Result;
use env_logger::Env;
use rlg::log_level::LogLevel;
use std::io::Write;
use anyhow::Result;

/// Initializes the logging system.
///
Expand All @@ -25,9 +25,7 @@ use anyhow::Result;
/// // Initialize the logging system with a default log level of `info`
/// init_logger(Some(LogLevel::INFO)).unwrap();
/// ```
pub fn init_logger(
default_log_level: Option<LogLevel>,
) -> Result<()> {
pub fn init_logger(default_log_level: Option<LogLevel>) -> Result<()> {
let env = Env::default().default_filter_or(
default_log_level.unwrap_or(LogLevel::INFO).to_string(),
);
Expand Down
12 changes: 6 additions & 6 deletions ssg-core/src/macros/directory_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,12 @@ macro_rules! macro_check_directory {
///
#[macro_export]
macro_rules! macro_cleanup_directories {
($path:expr) => {
{
use anyhow::Context;
std::fs::remove_dir_all($path).with_context(|| format!("Failed to clean up directory: {:?}", $path))
}
};
($path:expr) => {{
use anyhow::Context;
std::fs::remove_dir_all($path).with_context(|| {
format!("Failed to clean up directory: {:?}", $path)
})

Check warning on line 195 in ssg-core/src/macros/directory_macros.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/macros/directory_macros.rs#L193-L195

Added lines #L193 - L195 were not covered by tests
}};
}

/// # `macro_create_directories` Macro
Expand Down
14 changes: 8 additions & 6 deletions ssg-core/src/modules/plaintext.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
// Copyright © 2024 Shokunin Static Site Generator. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

use anyhow::{Error, Result}; // Ensure anyhow::Error and Result are imported
use crate::modules::preprocessor::preprocess_content;
use crate::utilities::directory::extract_front_matter;
use anyhow::{Error, Result}; // Ensure anyhow::Error and Result are imported
use pulldown_cmark::TagEnd;
use pulldown_cmark::{Event, Parser, Tag};
use regex::Regex;

/// Type alias for the result of the `generate_plain_text` function
type PlainTextResult = Result<(String, String, String, String, String, String), Error>;
type PlainTextResult =
Result<(String, String, String, String, String, String), Error>;

pub fn generate_plain_text(
content: &str,
Expand All @@ -28,11 +29,13 @@ pub fn generate_plain_text(
let markdown_content = extract_front_matter(content);

// Preprocess content to update class attributes and image tags
let processed_content = preprocess_content(markdown_content, &class_regex, &img_regex)
.map_err(|e| anyhow::Error::msg(e.to_string()))?; // Convert error to a string for compatibility
let processed_content =
preprocess_content(markdown_content, &class_regex, &img_regex)
.map_err(|e| anyhow::Error::msg(e.to_string()))?; // Convert error to a string for compatibility

Check warning on line 34 in ssg-core/src/modules/plaintext.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/modules/plaintext.rs#L34

Added line #L34 was not covered by tests

// Further preprocess to remove Markdown link references.
let no_markdown_links = link_ref_regex.replace_all(&processed_content, "$1");
let no_markdown_links =
link_ref_regex.replace_all(&processed_content, "$1");

let mut plain_text = String::new();
let parser = Parser::new(&no_markdown_links);
Expand Down Expand Up @@ -114,4 +117,3 @@ pub fn generate_plain_text(
plain_keywords.to_string(),
))
}

5 changes: 3 additions & 2 deletions ssg-core/src/utilities/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use std::fs::{self, copy, read_dir};
use std::path::Path;

// Import the anyhow Result and Context types.
use anyhow::{Result, Context};
use anyhow::{Context, Result};

// Import the time module.
use std::time::Instant;
Expand Down Expand Up @@ -72,7 +72,8 @@ pub fn write_files_to_build_directory(
file_name,
&get_file_content(file, file_name),
index_html_minified,
).context("Failed to write file")?;
)
.context("Failed to write file")?;

Check warning on line 76 in ssg-core/src/utilities/write.rs

View check run for this annotation

Codecov / codecov/patch

ssg-core/src/utilities/write.rs#L76

Added line #L76 was not covered by tests
}

for file_name in &OTHER_FILES {
Expand Down
3 changes: 2 additions & 1 deletion tests/test_cname.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ mod tests {
#[test]
fn test_create_cname_data_with_valid_cname() {
let mut metadata = HashMap::new();
let _ = metadata.insert("cname".to_string(), "example.com".to_string());
let _ = metadata
.insert("cname".to_string(), "example.com".to_string());

let cname_data = create_cname_data(&metadata);

Expand Down
3 changes: 2 additions & 1 deletion tests/test_compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ description: My Description

const EXPECTED_RESULT: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\"><channel><title>My RSS Feed</title><link>https://example.com</link><description>Latest technology news</description><language>en</language><pubDate>2023-06-29T12:00:00Z</pubDate><lastBuildDate>2023-06-29T12:00:00Z</lastBuildDate><docs>https://example.com/rss/docs</docs><generator>My RSS Generator</generator><managingEditor>editor@example.com</managingEditor><webMaster>webmaster@example.com</webMaster><category>Technology</category><ttl>60</ttl><image><url>None</url><title>My RSS Feed</title><link>https://example.com</link></image><atom:link href=\"https://example.com/rss/feed\" rel=\"self\" type=\"application/rss+xml\"/><item><author>Me</author><description>Item description</description><guid>item-guid</guid><link>https://example.com/item</link><pubDate>2023-06-29T12:00:00Z</pubDate><title>Item title</title></item></channel></rss>";

let result: Result<String, Box<dyn Error>> = generate_rss(&options);
let result: Result<String, Box<dyn Error>> =
generate_rss(&options);
assert_eq!(result?, EXPECTED_RESULT);

Ok(())
Expand Down
17 changes: 13 additions & 4 deletions tests/test_html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@
#[cfg(test)]
mod tests {
use regex::Regex;
use ssg_core::{modules::{html::{generate_html, HtmlGenerationError}, postprocessor::post_process_html}, utilities::directory::format_header_with_id_class};
use ssg_core::{
modules::{
html::{generate_html, HtmlGenerationError},
postprocessor::post_process_html,
},
utilities::directory::format_header_with_id_class,
};

#[test]
fn test_generate_html_with_front_matter() {
Expand Down Expand Up @@ -147,7 +153,8 @@ mod tests {
let html = r#"<img src="image.jpg">"#;
let class_regex = Regex::new(r#"class="[^"]*""#).unwrap();
let img_regex = Regex::new(r#"(.*<img[^>]*)(/>)"#).unwrap();
let result = post_process_html(html, &class_regex, &img_regex).unwrap();
let result =
post_process_html(html, &class_regex, &img_regex).unwrap();

// Expect no change as both alt and title are missing
assert_eq!(result.trim(), r#"<img src="image.jpg">"#);
Expand Down Expand Up @@ -176,7 +183,8 @@ mod tests {
let html = "";
let class_regex = Regex::new(r#"class="[^"]*""#).unwrap();
let img_regex = Regex::new(r#"<img[^>]*?(/?>)"#).unwrap();
let result = post_process_html(html, &class_regex, &img_regex).unwrap();
let result =
post_process_html(html, &class_regex, &img_regex).unwrap();

assert_eq!(result, "");
}
Expand All @@ -187,7 +195,8 @@ mod tests {
let html = "<p>Hello</p>\n";
let class_regex = Regex::new(r#"class="[^"]*""#).unwrap();
let img_regex = Regex::new(r#"<img[^>]*?(/?>)"#).unwrap();
let result = post_process_html(html, &class_regex, &img_regex).unwrap();
let result =
post_process_html(html, &class_regex, &img_regex).unwrap();

assert_eq!(result, html);
}
Expand Down
3 changes: 2 additions & 1 deletion tests/test_human.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ mod tests {
"author_website".to_string(),
"https://example.com".to_string(),
);
let _ = metadata.insert("author".to_string(), "John Doe".to_string());
let _ = metadata
.insert("author".to_string(), "John Doe".to_string());
let _ = metadata.insert(
"site_components".to_string(),
"Components".to_string(),
Expand Down
Loading

0 comments on commit e801250

Please sign in to comment.