Skip to content

Commit

Permalink
feat(libmake): added macros
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastienrousseau committed Mar 1, 2023
1 parent afc5359 commit 7527eb5
Show file tree
Hide file tree
Showing 10 changed files with 174 additions and 27 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ zip = "0.6.4"

[dev-dependencies]
criterion = "0.4.0"
predicates = "2.1.5"

[lib]
crate-type = ["lib"]
Expand Down
2 changes: 1 addition & 1 deletion build.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fn main() {
// Avoid unnecessary re-building.
// println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=build.rs");
}
4 changes: 4 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
edition = "2021"
max_width = 72
tab_spaces = 4
use_field_init_shorthand = true
86 changes: 71 additions & 15 deletions src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,18 @@ use std::{
///
///
#[non_exhaustive]
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[derive(
Clone,
Debug,
Default,
Eq,
Hash,
Ord,
PartialEq,
PartialOrd,
Serialize,
Deserialize,
)]
pub struct FileGenerationParams {
/// The author of the project (optional).
pub author: Option<String>,
Expand Down Expand Up @@ -65,14 +76,14 @@ pub struct FileGenerationParams {
///
/// - `path` - The path to the directory.
///
fn create_directory(path: &Path) -> io::Result<()> {
pub fn create_directory(path: &Path) -> io::Result<()> {
fs::create_dir(path).or_else(|e| match e.kind() {
io::ErrorKind::AlreadyExists => Ok(()),
_ => Err(e),
})
}

fn create_template_folder() -> io::Result<()> {
/// Creates the template directory and downloads the template files.
pub fn create_template_folder() -> io::Result<()> {
let current_dir = std::env::current_dir()?;
let template_dir_path = current_dir.join("template");
create_directory(&template_dir_path)?;
Expand Down Expand Up @@ -127,7 +138,7 @@ fn create_template_folder() -> io::Result<()> {
/// was successful, the result will be `Ok(())`. If the operation failed,
/// the result will be `Err(io::Error)`.
///
fn copy_and_replace_template(
pub fn copy_and_replace_template(
template_file: &str,
dest_file: &str,
project_directory: &PathBuf,
Expand Down Expand Up @@ -214,8 +225,18 @@ pub fn generate_files(params: FileGenerationParams) -> io::Result<()> {
&project_directory,
&params,
)?;
copy_and_replace_template("build.tpl", "build.rs", &project_directory, &params)?;
copy_and_replace_template("Cargo.tpl", "Cargo.toml", &project_directory, &params)?;
copy_and_replace_template(
"build.tpl",
"build.rs",
&project_directory,
&params,
)?;
copy_and_replace_template(
"Cargo.tpl",
"Cargo.toml",
&project_directory,
&params,
)?;
copy_and_replace_template(
"CONTRIBUTING.tpl",
"CONTRIBUTING.md",
Expand All @@ -228,11 +249,36 @@ pub fn generate_files(params: FileGenerationParams) -> io::Result<()> {
&project_directory,
&params,
)?;
copy_and_replace_template("gitignore.tpl", ".gitignore", &project_directory, &params)?;
copy_and_replace_template("lib.tpl", "src/lib.rs", &project_directory, &params)?;
copy_and_replace_template("main.tpl", "src/main.rs", &project_directory, &params)?;
copy_and_replace_template("README.tpl", "README.md", &project_directory, &params)?;
copy_and_replace_template("test.tpl", "tests/test.rs", &project_directory, &params)?;
copy_and_replace_template(
"gitignore.tpl",
".gitignore",
&project_directory,
&params,
)?;
copy_and_replace_template(
"lib.tpl",
"src/lib.rs",
&project_directory,
&params,
)?;
copy_and_replace_template(
"main.tpl",
"src/main.rs",
&project_directory,
&params,
)?;
copy_and_replace_template(
"README.tpl",
"README.md",
&project_directory,
&params,
)?;
copy_and_replace_template(
"test.tpl",
"tests/test.rs",
&project_directory,
&params,
)?;

// Displaying the argument and value pairs
println!("{:<15}Value", "Argument");
Expand All @@ -255,8 +301,16 @@ pub fn generate_files(params: FileGenerationParams) -> io::Result<()> {
);
println!("{:<15}{}", "edition", params.edition.unwrap_or_default());
println!("{:<15}{}", "email", params.email.unwrap_or_default());
println!("{:<15}{}", "homepage", params.homepage.unwrap_or_default());
println!("{:<15}{}", "keywords", params.keywords.unwrap_or_default());
println!(
"{:<15}{}",
"homepage",
params.homepage.unwrap_or_default()
);
println!(
"{:<15}{}",
"keywords",
params.keywords.unwrap_or_default()
);
println!("{:<15}{}", "license", params.license.unwrap_or_default());
println!("{:<15}{}", "name", params.name.unwrap_or_default());
println!("{:<15}{}", "output", output.clone());
Expand Down Expand Up @@ -388,7 +442,9 @@ pub fn generate_via_json(path: &str) -> std::io::Result<()> {
pub fn generate_via_yaml(path: &str) -> std::io::Result<()> {
let contents = fs::read_to_string(path)?;
let params: FileGenerationParams = serde_yaml::from_str(&contents)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
.map_err(|e| {
std::io::Error::new(std::io::ErrorKind::Other, e)
})?;
generate_files(params)?;
Ok(())
}
16 changes: 10 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ pub mod generator;
/// The `interface` module contains functions for displaying the
/// interface.
pub mod interface;
/// The `macros` module contains functions for generating macros.
pub mod macros;
/// The `utils` module contains a function for reading a CSV file at the
/// given file path and returns the value of the given field.
pub mod utils;
Expand Down Expand Up @@ -124,11 +126,13 @@ pub fn run() -> Result<(), Box<dyn Error>> {

let matches = cli::build_cli()?;
args::process_arguments(matches);
eprintln!(
"Welcome to LibMake! 👋\n\nLet's get started! Please, run `libmake --help` for more information.\n"
);

Err("Unable to get the command-line arguments"
.to_string()
.into())
// Print the welcome message if no arguments were passed
if std::env::args().len() == 1 {
eprintln!(
"Welcome to LibMake! 👋\n\nLet's get started! Please, run `libmake --help` for more information.\n"
);
}

Ok(())
}
36 changes: 36 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#[macro_export]
/// Asserts create directory.
macro_rules! assert_create_directory {
($path:expr) => {
assert!(create_directory(Path::new($path)).is_ok());
assert!(create_directory(Path::new($path)).is_ok());
};
}
#[macro_export]
/// Asserts generate files.
macro_rules! assert_generate_files {
($params:expr) => {
assert!(generate_files($params).is_ok());
};
}
#[macro_export]
/// Asserts generate files from CSV.
macro_rules! assert_generate_files_from_csv {
($csv_path:expr) => {
assert!(generate_files_from_csv($csv_path).is_ok());
};
}
#[macro_export]
/// Asserts generate via JSON.
macro_rules! assert_generate_via_json {
($path:expr) => {
assert!(generate_via_json($path).is_ok());
};
}
#[macro_export]
/// Asserts generate via YAML.
macro_rules! assert_generate_via_yaml {
($path:expr) => {
assert!(generate_via_yaml($path).is_ok());
};
}
2 changes: 1 addition & 1 deletion template/Cargo.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ include = [
[[bench]]
name = "benchmark"
harness = false
path = "benches/criterion.rs"
path = "benches/bench.rs"

[profile.bench]
debug = true
Expand Down
1 change: 1 addition & 0 deletions template/criterion.ion.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
404: Not Found
44 changes: 44 additions & 0 deletions tests/test_macros.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#[cfg(test)]
mod tests {

extern crate libmake;
use libmake::generator::FileGenerationParams;
use libmake::generator::{
create_directory, generate_files, generate_files_from_csv,
generate_via_json, generate_via_yaml,
};
use std::path::Path;

use libmake::{
assert_create_directory, assert_generate_files,
assert_generate_files_from_csv, assert_generate_via_json,
assert_generate_via_yaml,
};

#[test]
fn test_create_directory() {
assert_create_directory!("my_library");
}

#[test]
fn test_generate_files() {
let mut params = FileGenerationParams::default();
params.output = Some("my_library".into());
assert_generate_files!(params);
}

#[test]
fn test_generate_files_from_csv() {
assert_generate_files_from_csv!("./tests/data/mylibrary.csv");
}

#[test]
fn test_generate_via_json() {
assert_generate_via_json!("./tests/data/mylibrary.json");
}

#[test]
fn test_generate_via_yaml() {
assert_generate_via_yaml!("./tests/data/mylibrary.yaml");
}
}
9 changes: 5 additions & 4 deletions tests/test_main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@
mod tests {
use assert_cmd::Command;
use libmake::run;
use std::io::Write;
use std::{error::Error, io::Write};

#[test]
fn test_main() {
let mut cmd = Command::cargo_bin("libmake").unwrap();
let assert = cmd.assert();
assert.failure();
assert.success();
}

#[test]
fn test_main_run() {
// Redirect stdout to a buffer so we can check it later
let mut buffer = Vec::new();
let result = {
let _result: Result<(), Box<dyn Error>> = {
let _stdout = std::io::stdout();
let mut handle = std::io::BufWriter::new(buffer.by_ref());
std::io::stdout().flush().unwrap();
Expand All @@ -26,7 +26,8 @@ mod tests {
handle.flush().unwrap();
result
};

let output = String::from_utf8(buffer).unwrap();
assert_ne!(output, result.unwrap_err().to_string());
assert_eq!(output, "".to_string());
}
}

0 comments on commit 7527eb5

Please sign in to comment.