libmake/macros/
generator_macros.rs

1// Copyright notice and licensing information.
2// These lines indicate the copyright of the software and its licensing terms.
3// SPDX-License-Identifier: Apache-2.0 OR MIT indicates dual licensing under Apache 2.0 or MIT licenses.
4// Copyright © 2023-2024 LibMake. All rights reserved.
5
6//! Macros for the `libmake` crate.
7//!
8//! This module provides macros for generating templates from various configuration files
9//! (JSON, YAML, CSV, INI, TOML), and for executing operations with logging.
10//!
11//! Each macro is documented with its purpose and usage, ensuring clear and maintainable code.
12//! For detailed examples and error handling strategies, refer to the crate's documentation.
13
14// Macro for generating file templates using a command-line interface.
15#[macro_export]
16/// Attempts to generate file templates from the given parameters.
17///
18/// # Arguments
19///
20/// * `$params` - Parameters for file generation, specified as `FileGenerationParams`.
21///
22/// # Returns
23///
24/// Returns a `Result<(), String>` indicating the success or failure of file generation.
25/// If successful, returns `Ok(())`. If an error occurs, returns `Err` with an error message.
26macro_rules! macro_generate_files {
27    ($params:expr) => {{
28        use $crate::generator::generate_files;
29        match generate_files($params) {
30            Ok(_) => Ok(()),
31            Err(e) => Err(format!("Failed to generate files with parameters: {:?} - Error: {}", $params, e)),
32        }
33    }};
34}
35
36#[macro_export]
37/// Attempts to generate file templates from a CSV file.
38///
39/// # Arguments
40///
41/// * `$csv_path` - The path to the CSV file as a string slice.
42///
43/// # Returns
44///
45/// Returns a `Result<(), String>` indicating the success or failure of file generation.
46/// If successful, returns `Ok(())`. If an error occurs, returns `Err` with an error message.
47macro_rules! macro_generate_from_csv {
48    ($csv_path:expr) => {{
49        use $crate::generators::csv::generate_from_csv;
50        match generate_from_csv($csv_path) {
51            Ok(_) => Ok(()),
52            Err(e) => Err(format!("Failed to generate files from CSV at: {} - Error: {}", $csv_path, e)),
53        }
54    }};
55}
56
57#[macro_export]
58/// Attempts to generate file templates from a INI file.
59///
60/// # Arguments
61///
62/// * `$ini_path` - The path to the INI file as a string slice.
63///
64/// # Returns
65///
66/// Returns a `Result<(), String>` indicating the success or failure of file generation.
67/// If successful, returns `Ok(())`. If an error occurs, returns `Err` with an error message.
68macro_rules! macro_generate_from_ini {
69    ($ini_path:expr) => {{
70        use $crate::generators::ini::generate_from_ini;
71        match generate_from_ini($ini_path) {
72            Ok(_) => Ok(()),
73            Err(e) => Err(format!("Failed to generate files from INI at: {} - Error: {}", $ini_path, e)),
74        }
75    }};
76}
77
78#[macro_export]
79/// Attempts to generate file templates from a JSON file.
80///
81/// # Arguments
82///
83/// * `$json_path` - The path to the JSON file as a string slice.
84///
85/// # Returns
86///
87/// Returns a `Result<(), String>` indicating the success or failure of file generation.
88/// If successful, returns `Ok(())`. If an error occurs, returns `Err` with an error message.
89macro_rules! macro_generate_from_json {
90    ($json_path:expr) => {{
91        use $crate::generators::json::generate_from_json;
92        match generate_from_json($json_path) {
93            Ok(_) => Ok(()),
94            Err(e) => Err(format!("Failed to generate files from JSON at: {} - Error: {}", $json_path, e)),
95        }
96    }};
97}
98
99#[macro_export]
100/// Attempts to generate file templates from a TOML file.
101///
102/// # Arguments
103///
104/// * `$toml_path` - The path to the TOML file as a string slice.
105///
106/// # Returns
107///
108/// Returns a `Result<(), String>` indicating the success or failure of file generation.
109/// If successful, returns `Ok(())`. If an error occurs, returns `Err` with an error message.
110macro_rules! macro_generate_from_toml {
111    ($toml_path:expr) => {{
112        use $crate::generators::toml::generate_from_toml;
113        match generate_from_toml($toml_path) {
114            Ok(_) => Ok(()),
115            Err(e) => Err(format!("Failed to generate files from TOML at: {} - Error: {}", $toml_path, e)),
116        }
117    }};
118}
119
120#[macro_export]
121/// Attempts to generate file templates from a YAML file.
122///
123/// # Arguments
124///
125/// * `$yaml_path` - The path to the YAML file as a string slice.
126///
127/// # Returns
128///
129/// Returns a `Result<(), String>` indicating the success or failure of file generation.
130/// If successful, returns `Ok(())`. If an error occurs, returns `Err` with an error message.
131macro_rules! macro_generate_from_yaml {
132    ($yaml_path:expr) => {{
133        use $crate::generators::yaml::generate_from_yaml;
134        match generate_from_yaml($yaml_path) {
135            Ok(_) => Ok(()),
136            Err(e) => Err(format!("Failed to generate files from YAML at: {} - Error: {}", $yaml_path, e)),
137        }
138    }};
139}
140
141#[macro_export]
142/// Attempts to generate file templates from command-line arguments.
143///
144/// # Arguments
145///
146/// * `$args` - Command-line arguments as a string slice.
147///
148/// # Returns
149///
150/// Returns a `Result<(), String>` indicating the success or failure of file generation.
151/// If successful, returns `Ok(())`. If an error occurs, returns `Err` with an error message.
152macro_rules! macro_generate_from_args {
153    ($args:expr) => {{
154        use $crate::generators::args::generate_from_args;
155        match generate_from_args($args) {
156            Ok(_) => Ok(()),
157            Err(e) => Err(format!("Failed to generate files from arguments: {:?} - Error: {}", $args, e)),
158        }
159    }};
160}
161
162#[macro_export]
163/// Attempts to generate file templates from a configuration file.
164///
165/// # Arguments
166///
167/// * `$path` - The path to the configuration file as a string slice.
168/// * `$file_type` - The type of the configuration file (e.g., "json", "yaml").
169///
170/// # Returns
171///
172/// Returns a `Result<(), String>` indicating the success or failure of file generation.
173/// If successful, returns `Ok(())`. If an error occurs, returns `Err` with an error message.
174macro_rules! macro_generate_from_config {
175    ($path:expr, $file_type:expr) => {{
176        use $crate::generator::generate_from_config;
177        match generate_from_config($path, $file_type) {
178            Ok(_) => Ok(()),
179            Err(e) => Err(format!("Failed to generate files from {} configuration at: {} - Error: {}", $file_type, $path, e)),
180        }
181    }};
182}
183
184#[macro_export]
185/// Executes a shell command and logs the start, completion, and any errors.
186///
187/// # Parameters
188///
189/// * `$command` - The shell command to execute as a string slice.
190/// * `$package` - The name of the package being operated on as a string slice.
191/// * `$operation` - A description of the operation as a string slice.
192/// * `$start_message` - The message to log at the start of the operation as a string slice.
193/// * `$complete_message` - The message to log upon successful completion as a string slice.
194/// * `$error_message` - The message to log in case of an error as a string slice.
195///
196/// # Returns
197///
198/// Returns a `Result<(), anyhow::Error>` to indicate the success or failure of the command execution.
199macro_rules! macro_execute_and_log {
200    ($command:expr, $package:expr, $operation:expr, $start_message:expr, $complete_message:expr, $error_message:expr) => {{
201        use anyhow::{Context, Result as AnyResult};
202        // Using a fictional logging framework for demonstration purposes. You'll need to replace
203        // crate::log with your actual logging implementation.
204        $crate::log::info!("Starting operation: {}", $start_message);
205
206        std::process::Command::new("sh")
207            .arg("-c")
208            .arg($command)
209            .output()
210            .map(|output| {
211                if output.status.success() {
212                    $crate::log::info!("Operation completed successfully: {}", $complete_message);
213                    Ok(())
214                } else {
215                    $crate::log::error!("Operation failed: {} - Error: {}", $error_message, String::from_utf8_lossy(&output.stderr));
216                    Err(std::io::Error::new(std::io::ErrorKind::Other, "Command execution failed").into())
217                }
218            })
219            .with_context(|| {
220                format!(
221                    "Failed to execute '{}' for {} on package '{}'",
222                    stringify!($command),
223                    $operation,
224                    $package
225                )
226            })
227    }};
228}
229
230/// Extracts a parameter from a `Matches` object.
231///
232/// This macro takes two arguments: `$matches` and `$name`. It attempts to retrieve the value
233/// associated with `$name` from the `$matches` object. If the value is found and is of type `String`,
234/// it returns a `Some` variant containing a cloned copy of the value. Otherwise, it returns `None`.
235///
236/// # Arguments
237///
238/// * `$matches` - A `Matches` object that contains the parameter values.
239/// * `$name` - The name of the parameter to extract.
240///
241/// # Returns
242///
243/// A `Option<String>` containing the extracted parameter value, or `None` if the parameter is not found
244/// or is not of type `String`.
245#[macro_export]
246macro_rules! extract_param {
247    ($matches:expr, $name:expr) => {
248        $matches.get_one::<String>($name).map(|s| s.to_owned())
249    };
250}