main.rs

  1mod theme_printer;
  2mod util;
  3mod vscode;
  4mod vscode_syntax;
  5
  6use std::fs::{self, File};
  7use std::io::Write;
  8use std::path::PathBuf;
  9use std::process::Command;
 10use std::str::FromStr;
 11
 12use anyhow::{anyhow, Context, Result};
 13use convert_case::{Case, Casing};
 14use gpui::serde_json;
 15use log::LevelFilter;
 16use serde::Deserialize;
 17use simplelog::SimpleLogger;
 18use theme::{Appearance, UserThemeFamily};
 19use vscode::VsCodeThemeConverter;
 20
 21use crate::theme_printer::UserThemeFamilyPrinter;
 22use crate::vscode::VsCodeTheme;
 23
 24#[derive(Debug, Deserialize)]
 25struct FamilyMetadata {
 26    pub name: String,
 27    pub author: String,
 28    pub themes: Vec<ThemeMetadata>,
 29}
 30
 31#[derive(Debug, Deserialize)]
 32#[serde(rename_all = "snake_case")]
 33pub enum ThemeAppearanceJson {
 34    Light,
 35    Dark,
 36}
 37
 38impl From<ThemeAppearanceJson> for Appearance {
 39    fn from(value: ThemeAppearanceJson) -> Self {
 40        match value {
 41            ThemeAppearanceJson::Light => Self::Light,
 42            ThemeAppearanceJson::Dark => Self::Dark,
 43        }
 44    }
 45}
 46
 47#[derive(Debug, Deserialize)]
 48pub struct ThemeMetadata {
 49    pub name: String,
 50    pub file_name: String,
 51    pub appearance: ThemeAppearanceJson,
 52}
 53
 54fn main() -> Result<()> {
 55    const SOURCE_PATH: &str = "assets/themes/src/vscode";
 56    const OUT_PATH: &str = "crates/theme2/src/themes";
 57
 58    SimpleLogger::init(LevelFilter::Info, Default::default()).expect("could not initialize logger");
 59
 60    println!("Loading themes source...");
 61    let vscode_themes_path = PathBuf::from_str(SOURCE_PATH)?;
 62    if !vscode_themes_path.exists() {
 63        return Err(anyhow!(format!(
 64            "Couldn't find {}, make sure it exists",
 65            SOURCE_PATH
 66        )));
 67    }
 68
 69    let mut theme_families = Vec::new();
 70
 71    for theme_family_dir in fs::read_dir(&vscode_themes_path)? {
 72        let theme_family_dir = theme_family_dir?;
 73
 74        if !theme_family_dir.file_type()?.is_dir() {
 75            continue;
 76        }
 77
 78        let theme_family_slug = theme_family_dir
 79            .path()
 80            .file_stem()
 81            .ok_or(anyhow!("no file stem"))
 82            .map(|stem| stem.to_string_lossy().to_string())?;
 83
 84        let family_metadata_file = File::open(theme_family_dir.path().join("family.json"))
 85            .context(format!(
 86                "no `family.json` found for '{}'",
 87                theme_family_slug
 88            ))?;
 89
 90        let license_file_path = theme_family_dir.path().join("LICENSE");
 91
 92        if !license_file_path.exists() {
 93            println!("Skipping theme family '{}' because it does not have a LICENSE file. This theme will only be imported once a LICENSE file is provided.", theme_family_slug);
 94            continue;
 95        }
 96
 97        let family_metadata: FamilyMetadata = serde_json::from_reader(family_metadata_file)
 98            .context(format!(
 99                "failed to parse `family.json` for '{theme_family_slug}'"
100            ))?;
101
102        let mut themes = Vec::new();
103
104        for theme_metadata in family_metadata.themes {
105            let theme_file_path = theme_family_dir.path().join(&theme_metadata.file_name);
106
107            let theme_file = match File::open(&theme_file_path) {
108                Ok(file) => file,
109                Err(_) => {
110                    println!("Failed to open file at path: {:?}", theme_file_path);
111                    continue;
112                }
113            };
114
115            let vscode_theme: VsCodeTheme = serde_json::from_reader(theme_file)
116                .context(format!("failed to parse theme {theme_file_path:?}"))?;
117
118            let converter = VsCodeThemeConverter::new(vscode_theme, theme_metadata);
119
120            let theme = converter.convert()?;
121
122            themes.push(theme);
123        }
124
125        let theme_family = UserThemeFamily {
126            name: family_metadata.name.into(),
127            author: family_metadata.author.into(),
128            themes,
129        };
130
131        theme_families.push(theme_family);
132    }
133
134    let themes_output_path = PathBuf::from_str(OUT_PATH)?;
135
136    if !themes_output_path.exists() {
137        println!("Creating directory: {:?}", themes_output_path);
138        fs::create_dir_all(&themes_output_path)?;
139    }
140
141    let mut mod_rs_file = File::create(themes_output_path.join(format!("mod.rs")))?;
142
143    let mut theme_modules = Vec::new();
144
145    for theme_family in theme_families {
146        let theme_family_slug = theme_family.name.to_string().to_case(Case::Snake);
147
148        let mut output_file =
149            File::create(themes_output_path.join(format!("{theme_family_slug}.rs")))?;
150        println!(
151            "Creating file: {:?}",
152            themes_output_path.join(format!("{theme_family_slug}.rs"))
153        );
154
155        let theme_module = format!(
156            r#"
157            // This file was generated by the `theme_importer`.
158            // Be careful when modifying it by hand.
159
160            use gpui::rgba;
161
162            use crate::{{
163                Appearance, ThemeColorsRefinement, StatusColorsRefinement, UserTheme, UserThemeFamily, UserThemeStylesRefinement,
164            }};
165
166            pub fn {theme_family_slug}() -> UserThemeFamily {{
167                {theme_family_definition}
168            }}
169            "#,
170            theme_family_definition = format!("{:#?}", UserThemeFamilyPrinter::new(theme_family))
171        );
172
173        output_file.write_all(theme_module.as_bytes())?;
174
175        theme_modules.push(theme_family_slug);
176    }
177
178    let themes_vector_contents = format!(
179        r#"
180        use crate::UserThemeFamily;
181
182        pub(crate) fn all_user_themes() -> Vec<UserThemeFamily> {{
183            vec![{all_themes}]
184        }}
185        "#,
186        all_themes = theme_modules
187            .iter()
188            .map(|module| format!("{}()", module))
189            .collect::<Vec<_>>()
190            .join(", ")
191    );
192
193    let mod_rs_contents = format!(
194        r#"
195        // This file was generated by the `theme_importer`.
196        // Be careful when modifying it by hand.
197
198        {mod_statements}
199
200        {use_statements}
201
202        {themes_vector_contents}
203        "#,
204        mod_statements = theme_modules
205            .iter()
206            .map(|module| format!("mod {module};"))
207            .collect::<Vec<_>>()
208            .join("\n"),
209        use_statements = theme_modules
210            .iter()
211            .map(|module| format!("pub use {module}::*;"))
212            .collect::<Vec<_>>()
213            .join("\n"),
214        themes_vector_contents = themes_vector_contents
215    );
216
217    mod_rs_file.write_all(mod_rs_contents.as_bytes())?;
218
219    println!("Formatting themes...");
220
221    let format_result = format_themes_crate()
222        // We need to format a second time to catch all of the formatting issues.
223        .and_then(|_| format_themes_crate());
224
225    if let Err(err) = format_result {
226        eprintln!("Failed to format themes: {}", err);
227    }
228
229    println!("Done!");
230
231    Ok(())
232}
233
234fn format_themes_crate() -> std::io::Result<std::process::Output> {
235    Command::new("cargo")
236        .args(["fmt", "--package", "theme2"])
237        .output()
238}