Skip to main content

cargo_color_gen/
lib.rs

1use anyhow::Result;
2use quote::quote;
3use std::{
4    fs::{self, File},
5    io::{self, Write},
6};
7use tailwind::TailwindMap;
8mod ir;
9mod tailwind;
10
11use clap::Parser;
12
13#[derive(Parser, Debug, Default)]
14#[command(version, about)]
15pub struct Args {
16    #[arg(short, long)]
17    pub input_file: Option<String>,
18    #[arg(short, long)]
19    pub output_file: Option<String>,
20}
21impl Args {
22    pub fn new(input_file: impl ToString, output_file: impl ToString) -> Self {
23        Self {
24            input_file: Some(input_file.to_string()),
25            output_file: Some(output_file.to_string()),
26        }
27    }
28}
29
30/// The main entry point for converting a file with the CLI tool.
31///
32/// If you don't need to open files/use stdin, then see [`generate`].
33pub fn handle_args(args: Args) -> Result<()> {
34    const RED: &str = "\x1b[31m";
35    const RESET: &str = "\x1b[0m";
36    eprintln!(
37        "{}⚠️ This CLI tool has been moved to the bevygen! ⚠️\n{}",
38        RED, RESET
39    );
40    let input = match args.input_file {
41        Some(file) => fs::read_to_string(file)?,
42        None => loop {
43            let mut input = String::new();
44            println!("Paste your JSON [press ENTER to continue]:");
45            if io::stdin().read_line(&mut input).is_err() {
46                println!("Failed to read input.");
47                continue;
48            }
49            break input;
50        },
51    };
52    let result = generate(&input)?;
53
54    if let Some(output_path) = args.output_file {
55        let Ok(mut of) = File::create(output_path) else {
56            println!("Error creating file at path. Generated Output:\n=====\n{result}\n=====");
57            return Ok(());
58        };
59
60        if let Err(e) = of.write_all(result.to_string().as_bytes()) {
61            println!(
62                "Error at path:\n{:?}\nGenerated Output:\n=====\n{result}\n=====",
63                e
64            );
65            return Ok(());
66        };
67        println!("Result written to output.");
68
69        return Ok(());
70    }
71    println!("Output\n=====\n{result}\n=====");
72    Ok(())
73}
74
75/// Takes in a JSObject or JSON and returns file contents
76pub fn generate(input: &str) -> Result<String> {
77    let val = TailwindMap::from_json(input)?;
78    let header = quote! {
79        /// Generated using `color-gen` v0.2
80
81        use bevy::color::Color;
82    };
83
84    let token_colors = val.to_token_colors();
85
86    let output = quote! {
87        #header
88
89        #(#token_colors)*
90    };
91
92    let file = syn::parse_file(&output.to_string())?;
93    let result = prettyplease::unparse(&file);
94
95    Ok(result)
96}