🚧 Working on 0.1.0 version

This commit is contained in:
Manuel Cillero 2024-11-30 11:35:48 +01:00
parent 9f62955acb
commit 41cedf2541
28 changed files with 3473 additions and 535 deletions

View file

@ -3,20 +3,17 @@ name = "pagetop-build"
version = "0.0.11"
edition = "2021"
description = "Simplifies the process of embedding resources in PageTop app binaries."
homepage = "https://pagetop.cillero.es"
repository = "https://github.com/manuelcillero/pagetop"
license = "MIT OR Apache-2.0"
description = """\
Simplifies the process of embedding resources in PageTop app binaries.\
"""
categories = ["development-tools::build-utils", "web-programming"]
keywords = ["pagetop", "build", "assets", "resources", "static"]
authors = [
"Manuel Cillero <manuel@cillero.es>"
]
categories = [
"development-tools::build-utils", "web-programming"
]
keywords = [
"pagetop", "build", "assets", "resources", "static"
]
repository = "https://github.com/manuelcillero/pagetop"
homepage = "https://pagetop.cillero.es"
license = "MIT OR Apache-2.0"
authors = ["Manuel Cillero <manuel@cillero.es>"]
[dependencies]
grass = "0.13.4"
static-files = "0.2.4"

View file

@ -1,57 +1,74 @@
//! This function uses the [static_files](https://docs.rs/static-files/latest/static_files/) library
//! to embed at compile time a bundle of static files in your binary.
//! Easily embed static or compiled SCSS files into your binary at compile time.
//!
//! Just create folder with static resources in your project (for example `static`):
//! ## Adding to your project
//!
//! ```bash
//! cd project_dir
//! mkdir static
//! echo "Hello, world!" > static/hello
//! ```
//!
//! Add to `Cargo.toml` the required dependencies:
//! Add the following to your `Cargo.toml`:
//!
//! ```toml
//! [build-dependencies]
//! pagetop-build = { ... }
//! ```
//!
//! Add `build.rs` with call to bundle resources (*guides* will be the magic word in this example):
//! Next, create a `build.rs` file to configure how your static resources or SCSS files will be
//! bundled in your PageTop application, package, or theme.
//!
//! ## Usage examples
//!
//! ### 1. Embedding static files from a directory
//!
//! Include all files from a directory:
//!
//! ```rust#ignore
//! use pagetop_build::StaticFilesBundle;
//!
//! fn main() -> std::io::Result<()> {
//! StaticFilesBundle::from_dir("./static")
//! StaticFilesBundle::from_dir("./static", None)
//! .with_name("guides")
//! .build()
//! }
//! ```
//!
//! Optionally, you can pass a function to filter those files into the `./static` folder which
//! should be excluded in the resources bundle:
//! Apply a filter to include only specific files:
//!
//! ```rust#ignore
//! use pagetop_build::StaticFilesBundle;
//! use std::path::Path;
//!
//! fn main() -> std::io::Result<()> {
//! StaticFilesBundle::from_dir("./static")
//! .with_name("guides")
//! .with_filter(except_css_dir)
//! .build()
//! }
//!
//! fn except_css_dir(p: &Path) -> bool {
//! if let Some(parent) = p.parent() {
//! !matches!(parent.to_str(), Some("/css"))
//! fn only_css_files(path: &Path) -> bool {
//! // Include only files with `.css` extension.
//! path.extension().map_or(false, |ext| ext == "css")
//! }
//! true
//!
//! StaticFilesBundle::from_dir("./static", Some(only_css_files))
//! .with_name("guides")
//! .build()
//! }
//! ```
//!
//! This will create a file called `guides.rs` in the standard directory
//! ### 2. Compiling SCSS files to CSS
//!
//! Compile a SCSS file into CSS and embed it:
//!
//! ```rust#ignore
//! use pagetop_build::StaticFilesBundle;
//!
//! fn main() -> std::io::Result<()> {
//! StaticFilesBundle::from_scss("./styles/main.scss", "main.css")
//! .with_name("main_styles")
//! .build()
//! }
//! ```
//!
//! This compiles the `main.scss` file, including all imported SCSS files, into `main.css`. All
//! imports are resolved automatically, and the result is accessible within the binary file.
//!
//! ## Generated module
//!
//! [`StaticFilesBundle`] generates a file in the standard directory
//! [OUT_DIR](https://doc.rust-lang.org/cargo/reference/environment-variables.html) where all
//! intermediate and output artifacts are placed during compilation.
//! intermediate and output artifacts are placed during compilation. For example, if you use
//! `with_name("guides")`, it generates a file named `guides.rs`:
//!
//! You don't need to access this file, just include it in your project using the builder name as an
//! identifier:
@ -59,27 +76,118 @@
//! ```rust#ignore
//! use pagetop::prelude::*;
//!
//! static_files!(guides);
//! include_files!(guides);
//! ```
//!
//! Also you can get the bundle as a static reference to the generated `HashMap` resources
//! collection:
//! Or, access the entire bundle as a global static `HashMap`:
//!
//! ```rust#ignore
//! use pagetop::prelude::*;
//!
//! static_files!(guides => BUNDLE_GUIDES);
//! include_files!(guides => BUNDLE_GUIDES);
//! ```
//!
//! You can build more than one resources file to compile with your project.
use grass::{from_path, Options, OutputStyle};
use static_files::{resource_dir, ResourceDir};
use std::fs::{create_dir_all, remove_dir_all, File};
use std::io::Write;
use std::path::Path;
pub struct StaticFilesBundle(static_files::ResourceDir);
/// Generates the resources to embed at compile time using
/// [static_files](https://docs.rs/static-files/latest/static_files/).
pub struct StaticFilesBundle {
resource_dir: ResourceDir,
}
impl StaticFilesBundle {
pub fn from_dir(dir: &'static str) -> Self {
StaticFilesBundle(static_files::resource_dir(dir))
/// Creates a bundle from a directory of static files, with an optional filter.
///
/// # Arguments
///
/// * `dir` - The directory containing the static files.
/// * `filter` - An optional function to filter files or directories to include.
pub fn from_dir(dir: &'static str, filter: Option<fn(p: &Path) -> bool>) -> Self {
let mut resource_dir = resource_dir(dir);
// Apply the filter if provided.
if let Some(f) = filter {
resource_dir.with_filter(f);
}
StaticFilesBundle { resource_dir }
}
/// Creates a bundle starting from a SCSS file.
///
/// # Arguments
///
/// * `path` - The SCSS file to compile.
/// * `target_name` - The name for the CSS file in the bundle.
///
/// This function will panic:
///
/// * If the environment variable `OUT_DIR` is not set.
/// * If it is unable to create a temporary directory in the `OUT_DIR`.
/// * If the SCSS file cannot be compiled due to syntax errors in the SCSS file or missing
/// dependencies or import paths required for compilation.
/// * If it is unable to create the output CSS file in the temporary directory due to an invalid
/// `target_name` or insufficient permissions to create files in the temporary directory.
/// * If the function fails to write the compiled CSS content to the file.
pub fn from_scss<P>(path: P, target_name: &str) -> Self
where
P: AsRef<Path>,
{
// Create a temporary directory for the CSS file.
let out_dir = std::env::var("OUT_DIR").unwrap();
let temp_dir = Path::new(&out_dir).join("from_scss_files");
// Clean up the temporary directory from previous runs, if it exists.
if temp_dir.exists() {
remove_dir_all(&temp_dir).unwrap_or_else(|e| {
panic!(
"Failed to clean temporary directory `{}`: {e}",
temp_dir.display()
);
});
}
create_dir_all(&temp_dir).unwrap_or_else(|e| {
panic!(
"Failed to create temporary directory `{}`: {e}",
temp_dir.display()
);
});
// Compile SCSS to CSS.
let css_content = from_path(
path.as_ref(),
&Options::default().style(OutputStyle::Compressed),
)
.unwrap_or_else(|e| {
panic!(
"Failed to compile SCSS file `{}`: {e}",
path.as_ref().display(),
)
});
// Write the compiled CSS to the temporary directory.
let css_path = temp_dir.join(target_name);
File::create(&css_path)
.expect(&format!(
"Failed to create CSS file `{}`",
css_path.display()
))
.write_all(css_content.as_bytes())
.expect(&format!(
"Failed to write CSS content to `{}`",
css_path.display()
));
// Initialize ResourceDir with the temporary directory.
StaticFilesBundle {
resource_dir: resource_dir(temp_dir.to_str().unwrap()),
}
}
/// Configures the name for the bundle of static files.
@ -88,16 +196,11 @@ impl StaticFilesBundle {
///
/// This function will panic if the standard `OUT_DIR` environment variable is not set.
pub fn with_name(mut self, name: &'static str) -> Self {
self.0.with_generated_filename(
Path::new(std::env::var("OUT_DIR").unwrap().as_str()).join(format!("{name}.rs")),
);
self.0.with_module_name(format!("bundle_{name}"));
self.0.with_generated_fn(name);
self
}
pub fn with_filter(mut self, filter: fn(p: &Path) -> bool) -> Self {
self.0.with_filter(filter);
let out_dir = std::env::var("OUT_DIR").unwrap();
let filename = Path::new(&out_dir).join(format!("{name}.rs"));
self.resource_dir.with_generated_filename(filename);
self.resource_dir.with_module_name(format!("bundle_{name}"));
self.resource_dir.with_generated_fn(name);
self
}
@ -108,6 +211,6 @@ impl StaticFilesBundle {
/// This function will return an error if there is an issue with I/O operations, such as failing
/// to read or write to a file.
pub fn build(self) -> std::io::Result<()> {
self.0.build()
self.resource_dir.build()
}
}

View file

@ -3,28 +3,23 @@ name = "pagetop-macros"
version = "0.0.13"
edition = "2021"
description = "A collection of procedural macros that boost PageTop development."
homepage = "https://pagetop.cillero.es"
repository = "https://github.com/manuelcillero/pagetop"
license = "MIT OR Apache-2.0"
description = """\
A collection of macros that boost PageTop development.\
"""
categories = ["development-tools::procedural-macro-helpers", "web-programming"]
keywords = ["pagetop", "macros", "proc-macros", "codegen"]
authors = [
"Manuel Cillero <manuel@cillero.es>"
]
categories = [
"development-tools::procedural-macro-helpers", "web-programming"
]
keywords = [
"pagetop", "macros", "proc-macros", "codegen"
]
repository = "https://github.com/manuelcillero/pagetop"
homepage = "https://pagetop.cillero.es"
license = "MIT OR Apache-2.0"
authors = ["Manuel Cillero <manuel@cillero.es>"]
[lib]
proc-macro = true
[dependencies]
concat-string = "1.0.1"
proc-macro2 = "1.0"
proc-macro-crate = "3.1.0"
proc-macro2 = "1.0.92"
proc-macro-crate = "3.2.0"
proc-macro-error = "1.0.4"
quote = "1.0"
syn = { version = "2.0", features = ["full"] }
quote = "1.0.37"
syn = { version = "2.0.90", features = ["full"] }

View file

@ -2,7 +2,7 @@
<h1>PageTop Macros</h1>
<p>A collection of procedural macros that boost PageTop development.</p>
<p>A collection of macros that boost PageTop development.</p>
[![License](https://img.shields.io/badge/license-MIT%2FApache-blue.svg?style=for-the-badge)](#-license)
[![API Docs](https://img.shields.io/docsrs/pagetop-macros?label=API%20Docs&style=for-the-badge&logo=Docs.rs)](https://docs.rs/pagetop-macros)
@ -25,11 +25,16 @@ frequent changes. Production use is not recommended until version **0.1.0**.
# 🔖 Credits
This crate includes an adapted version of [maud-macros](https://crates.io/crates/maud_macros),
version [0.25.0](https://github.com/lambda-fairy/maud/tree/v0.25.0/maud_macros), by
[Chris Wong](https://crates.io/users/lambda-fairy). This adaptation integrates its functionalities
into **PageTop**, eliminating the need for direct references to `maud` in the `Cargo.toml` file of
each project.
This crate includes an adapted version of [maud-macros](https://crates.io/crates/maud_macros)
(version [0.25.0](https://github.com/lambda-fairy/maud/tree/v0.25.0/maud_macros)) by
[Chris Wong](https://crates.io/users/lambda-fairy).
Additionally, the [SmartDefault](https://crates.io/crates/smart_default) crate (version 0.7.1) by
[Jane Doe](https://crates.io/users/jane-doe) has been embedded as `AutoDefault`, simplifying
`Default` implementations.
Both eliminate the need to explicitly reference `maud` or `smart_default` in the `Cargo.toml` file
of each project.
# 📜 License

View file

@ -1,18 +1,11 @@
mod maud;
mod smart_default;
use concat_string::concat_string;
use proc_macro::TokenStream;
use proc_macro_error::proc_macro_error;
use quote::{quote, quote_spanned, ToTokens};
use syn::{parse_macro_input, parse_str, DeriveInput, ItemFn};
#[proc_macro]
#[proc_macro_error]
pub fn html(input: TokenStream) -> TokenStream {
maud::expand(input.into()).into()
}
/// Macro attribute to generate builder methods from `set_` methods.
///
/// This macro takes a method with the `set_` prefix and generates a corresponding method with the
@ -57,7 +50,7 @@ pub fn fn_builder(_: TokenStream, item: TokenStream) -> TokenStream {
fn_with_name.clone()
} else {
let g = &fn_set.sig.generics;
concat_string!(fn_with_name, quote! { #g }.to_string())
format!("{fn_with_name}{}", quote! { #g }.to_string())
};
let where_clause = fn_set
@ -66,7 +59,7 @@ pub fn fn_builder(_: TokenStream, item: TokenStream) -> TokenStream {
.where_clause
.as_ref()
.map_or(String::new(), |where_clause| {
concat_string!(quote! { #where_clause }.to_string(), " ")
format!("{} ", quote! { #where_clause }.to_string())
});
let args: Vec<String> = fn_set
@ -89,21 +82,21 @@ pub fn fn_builder(_: TokenStream, item: TokenStream) -> TokenStream {
.collect();
#[rustfmt::skip]
let fn_with = parse_str::<ItemFn>(concat_string!("
pub fn ", fn_with_generics, "(mut self, ", args.join(", "), ") -> Self ", where_clause, "{
self.", fn_set_name, "(", params.join(", "), ");
let fn_with = parse_str::<ItemFn>(format!(r##"
pub fn {fn_with_generics}(mut self, {}) -> Self {where_clause} {{
self.{fn_set_name}({});
self
}
").as_str()).unwrap();
}}
"##, args.join(", "), params.join(", ")
).as_str()).unwrap();
#[rustfmt::skip]
let fn_set_doc = concat_string!(
"<p id=\"method.", fn_with_name, "\" style=\"margin-bottom: 12px;\">Use ",
"<code class=\"code-header\">pub fn <span class=\"fn\" href=\"#method.", fn_with_name, "\">",
fn_with_name,
"</span>(self, …) -> Self</code> for the <a href=\"#method.new\">builder pattern</a>.",
"</p>"
);
let fn_set_doc = format!(r##"
<p id="method.{fn_with_name}" style="margin-bottom: 12px;">Use
<code class="code-header">pub fn <span class="fn" href="#method.{fn_with_name}">{fn_with_name}</span>(self, ) -> Self</code>
for the <a href="#method.new">builder pattern</a>.
</p>
"##);
let expanded = quote! {
#[doc(hidden)]
@ -115,6 +108,52 @@ pub fn fn_builder(_: TokenStream, item: TokenStream) -> TokenStream {
expanded.into()
}
#[proc_macro]
#[proc_macro_error]
pub fn html(input: TokenStream) -> TokenStream {
maud::expand(input.into()).into()
}
#[proc_macro_derive(AutoDefault, attributes(default))]
pub fn derive_auto_default(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match smart_default::body_impl::impl_my_derive(&input) {
Ok(output) => output.into(),
Err(error) => error.to_compile_error().into(),
}
}
#[proc_macro_derive(ComponentClasses)]
pub fn derive_component_classes(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
#[rustfmt::skip]
let fn_set_doc = format!(r##"
<p id="method.with_classes">Use
<code class="code-header"><span class="fn" href="#method.with_classes">with_classes</span>(self, ) -> Self</code>
to apply the <a href="#method.new">builder pattern</a>.
</p>
"##);
let expanded = quote! {
impl ComponentClasses for #name {
#[inline]
#[doc = #fn_set_doc]
fn set_classes(&mut self, op: ClassesOp, classes: impl Into<String>) -> &mut Self {
self.classes.set_value(op, classes);
self
}
fn classes(&self) -> &OptionClasses {
&self.classes
}
}
};
TokenStream::from(expanded)
}
/// Marks async main function as the `PageTop` entry-point.
///
/// # Examples
@ -154,43 +193,3 @@ pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
output.extend(item);
output
}
#[proc_macro_derive(AutoDefault, attributes(default))]
pub fn derive_auto_default(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match smart_default::body_impl::impl_my_derive(&input) {
Ok(output) => output.into(),
Err(error) => error.to_compile_error().into(),
}
}
#[proc_macro_derive(ComponentClasses)]
pub fn derive_component_classes(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let fn_set_doc = concat_string!(
"<p id=\"method.with_classes\">",
"Use <code class=\"code-header\">",
" <span class=\"fn\" href=\"#method.with_classes\">with_classes</span>(self, …) -> Self ",
"</code> to apply the <a href=\"#method.new\">builder pattern</a>.",
"</p>"
);
let expanded = quote! {
impl ComponentClasses for #name {
#[inline]
#[doc = #fn_set_doc]
fn set_classes(&mut self, op: ClassesOp, classes: impl Into<String>) -> &mut Self {
self.classes.set_value(op, classes);
self
}
fn classes(&self) -> &OptionClasses {
&self.classes
}
}
};
TokenStream::from(expanded)
}