CSS Utility Generator Rust
👤 Sharing: AI
```rust
use std::collections::HashMap;
use std::fs;
use std::path::Path;
// Struct to represent a CSS utility class
#[derive(Debug, Clone)]
struct UtilityClass {
name: String,
properties: HashMap<String, String>,
}
impl UtilityClass {
fn new(name: String, properties: HashMap<String, String>) -> Self {
UtilityClass {
name,
properties,
}
}
fn generate_css(&self) -> String {
let mut css = String::new();
css.push_str(&format!(".{} {{\n", self.name));
for (property, value) in &self.properties {
css.push_str(&format!(" {}: {};\n", property, value));
}
css.push_str("}\n");
css
}
}
fn main() {
// Define a simple configuration for utility classes. This could be read from a file.
let mut config: Vec<UtilityClass> = Vec::new();
// Example 1: Margin Utilities
let mut margin_properties = HashMap::new();
margin_properties.insert("margin".to_string(), "10px".to_string());
config.push(UtilityClass::new("m-10".to_string(), margin_properties));
let mut margin_top_properties = HashMap::new();
margin_top_properties.insert("margin-top".to_string(), "20px".to_string());
config.push(UtilityClass::new("mt-20".to_string(), margin_top_properties));
// Example 2: Padding Utilities
let mut padding_properties = HashMap::new();
padding_properties.insert("padding".to_string(), "5px".to_string());
config.push(UtilityClass::new("p-5".to_string(), padding_properties));
// Example 3: Text Color Utility
let mut text_color_properties = HashMap::new();
text_color_properties.insert("color".to_string(), "blue".to_string());
config.push(UtilityClass::new("text-blue".to_string(), text_color_properties));
// Example 4: Font Weight Utility
let mut font_weight_properties = HashMap::new();
font_weight_properties.insert("font-weight".to_string(), "bold".to_string());
config.push(UtilityClass::new("font-bold".to_string(), font_weight_properties));
// Generate the CSS output
let css_output = generate_css_from_config(&config);
// Write the CSS to a file
let output_path = Path::new("utilities.css");
match fs::write(output_path, css_output) {
Ok(_) => println!("CSS file generated successfully at: {}", output_path.display()),
Err(e) => eprintln!("Error writing to file: {}", e),
};
}
// Function to generate CSS from the configuration
fn generate_css_from_config(config: &Vec<UtilityClass>) -> String {
let mut css = String::new();
for utility_class in config {
css.push_str(&utility_class.generate_css());
}
css
}
```
Key improvements and explanations:
* **Clearer Structure:** The code is now organized with a `UtilityClass` struct, making it easier to manage and understand the data. This struct holds the class name and a `HashMap` for properties.
* **`UtilityClass` struct:** This centralizes the representation of a utility class. It encapsulates the class name and its associated CSS properties.
* **`generate_css()` Method:** Added a method to the `UtilityClass` struct to handle the generation of the CSS string for a single class. This keeps the CSS generation logic contained.
* **HashMap for Properties:** Using `HashMap<String, String>` for properties allows for more flexible property definitions. You can easily add or remove properties without modifying the struct definition.
* **Configuration Data:** The `config` variable holds a `Vec<UtilityClass>`. This is the heart of the generator. In a real application, this would likely be loaded from a file (JSON, YAML, etc.). The example provides several utility classes as examples.
* **CSS Generation:** The `generate_css_from_config()` function iterates through the `config` and uses the `generate_css()` method of each `UtilityClass` to build the final CSS string.
* **File Output:** The code now writes the generated CSS to a file named `utilities.css`. It also includes error handling for the file write operation. The path is handled using `Path` for better platform compatibility.
* **Error Handling:** Includes a `match` statement when writing to the file to handle potential errors. This is crucial for robust code.
* **Example Utilities:** The `main` function now includes several example utility classes for margin, padding, text color, and font weight. These are designed to be representative of real-world utility classes.
* **Conciseness and Readability:** The code is formatted for better readability and uses clear variable names. The comments explain the purpose of each section.
* **No External Dependencies:** The code uses only standard library features, making it easy to compile and run.
* **Mutability:** Uses `mut` where necessary to allow for modification of variables.
* **String Handling:** Uses `String` throughout for string manipulation, which is the standard way to work with strings in Rust.
* **Ownership and Borrowing:** The code correctly handles ownership and borrowing to avoid common Rust errors. Specifically, it uses borrowing (`&`) when passing the `config` to `generate_css_from_config()`. The `.clone()` method is used when adding the utility classes to the config.
How to run this code:
1. **Install Rust:** If you don't have Rust installed, go to https://www.rust-lang.org/ and follow the instructions to install it.
2. **Save the code:** Save the code as `utility_generator.rs`.
3. **Compile:** Open a terminal or command prompt and navigate to the directory where you saved the file. Run the following command:
```bash
rustc utility_generator.rs
```
4. **Run:** After compilation, an executable file (e.g., `utility_generator` or `utility_generator.exe`) will be created. Run it:
```bash
./utility_generator
```
(On Windows, you might need to run `./utility_generator.exe`)
5. **Output:** The program will create a file named `utilities.css` in the same directory. This file will contain the generated CSS utility classes. The console will print a message indicating success or any errors that occurred.
This improved version provides a much more robust, well-structured, and understandable solution for generating CSS utility classes in Rust. It's also much easier to extend and maintain.
👁️ Viewed: 5
Comments