1use std::collections::{BTreeSet, HashMap};
  2use std::env;
  3use std::fs;
  4use std::path::{Path, PathBuf};
  5use std::sync::Arc;
  6
  7use ::fs::{CopyOptions, Fs, RealFs, copy_recursive};
  8use anyhow::{Context as _, Result, bail};
  9use clap::Parser;
 10use extension::ExtensionManifest;
 11use extension::extension_builder::{CompileExtensionOptions, ExtensionBuilder};
 12use language::LanguageConfig;
 13use reqwest_client::ReqwestClient;
 14use rpc::ExtensionProvides;
 15use tokio::process::Command;
 16use tree_sitter::{Language, Query, WasmStore};
 17
 18#[derive(Parser, Debug)]
 19#[command(name = "zed-extension")]
 20struct Args {
 21    /// The path to the extension directory
 22    #[arg(long)]
 23    source_dir: PathBuf,
 24    /// The output directory to place the packaged extension.
 25    #[arg(long)]
 26    output_dir: PathBuf,
 27    /// The path to a directory where build dependencies are downloaded
 28    #[arg(long)]
 29    scratch_dir: PathBuf,
 30}
 31
 32#[tokio::main]
 33async fn main() -> Result<()> {
 34    env_logger::init();
 35
 36    let args = Args::parse();
 37    let fs = Arc::new(RealFs::new(None, gpui::background_executor()));
 38    let engine = wasmtime::Engine::default();
 39    let mut wasm_store = WasmStore::new(&engine)?;
 40
 41    let extension_path = args
 42        .source_dir
 43        .canonicalize()
 44        .context("failed to canonicalize source_dir")?;
 45    let scratch_dir = args
 46        .scratch_dir
 47        .canonicalize()
 48        .context("failed to canonicalize scratch_dir")?;
 49    let output_dir = if args.output_dir.is_relative() {
 50        env::current_dir()?.join(&args.output_dir)
 51    } else {
 52        args.output_dir
 53    };
 54
 55    log::info!("loading extension manifest");
 56    let mut manifest = ExtensionManifest::load(fs.clone(), &extension_path).await?;
 57
 58    log::info!("compiling extension");
 59
 60    let user_agent = format!(
 61        "Zed Extension CLI/{} ({}; {})",
 62        env!("CARGO_PKG_VERSION"),
 63        std::env::consts::OS,
 64        std::env::consts::ARCH
 65    );
 66    let http_client = Arc::new(ReqwestClient::user_agent(&user_agent)?);
 67
 68    let builder = ExtensionBuilder::new(http_client, scratch_dir);
 69    builder
 70        .compile_extension(
 71            &extension_path,
 72            &mut manifest,
 73            CompileExtensionOptions { release: true },
 74        )
 75        .await
 76        .context("failed to compile extension")?;
 77
 78    let grammars = test_grammars(&manifest, &extension_path, &mut wasm_store)?;
 79    test_languages(&manifest, &extension_path, &grammars)?;
 80    test_themes(&manifest, &extension_path, fs.clone()).await?;
 81
 82    let archive_dir = output_dir.join("archive");
 83    fs::remove_dir_all(&archive_dir).ok();
 84    copy_extension_resources(&manifest, &extension_path, &archive_dir, fs.clone())
 85        .await
 86        .context("failed to copy extension resources")?;
 87
 88    let tar_output = Command::new("tar")
 89        .current_dir(&output_dir)
 90        .args(["-czvf", "archive.tar.gz", "-C", "archive", "."])
 91        .output()
 92        .await
 93        .context("failed to run tar")?;
 94    if !tar_output.status.success() {
 95        bail!(
 96            "failed to create archive.tar.gz: {}",
 97            String::from_utf8_lossy(&tar_output.stderr)
 98        );
 99    }
100
101    let extension_provides = extension_provides(&manifest);
102
103    let manifest_json = serde_json::to_string(&rpc::ExtensionApiManifest {
104        name: manifest.name,
105        version: manifest.version,
106        description: manifest.description,
107        authors: manifest.authors,
108        schema_version: Some(manifest.schema_version.0),
109        repository: manifest
110            .repository
111            .context("missing repository in extension manifest")?,
112        wasm_api_version: manifest.lib.version.map(|version| version.to_string()),
113        provides: extension_provides,
114    })?;
115    fs::remove_dir_all(&archive_dir)?;
116    fs::write(output_dir.join("manifest.json"), manifest_json.as_bytes())?;
117
118    Ok(())
119}
120
121/// Returns the set of features provided by the extension.
122fn extension_provides(manifest: &ExtensionManifest) -> BTreeSet<ExtensionProvides> {
123    let mut provides = BTreeSet::default();
124    if !manifest.themes.is_empty() {
125        provides.insert(ExtensionProvides::Themes);
126    }
127
128    if !manifest.icon_themes.is_empty() {
129        provides.insert(ExtensionProvides::IconThemes);
130    }
131
132    if !manifest.languages.is_empty() {
133        provides.insert(ExtensionProvides::Languages);
134    }
135
136    if !manifest.grammars.is_empty() {
137        provides.insert(ExtensionProvides::Grammars);
138    }
139
140    if !manifest.language_servers.is_empty() {
141        provides.insert(ExtensionProvides::LanguageServers);
142    }
143
144    if !manifest.context_servers.is_empty() {
145        provides.insert(ExtensionProvides::ContextServers);
146    }
147
148    if manifest.snippets.is_some() {
149        provides.insert(ExtensionProvides::Snippets);
150    }
151
152    if !manifest.debug_adapters.is_empty() {
153        provides.insert(ExtensionProvides::DebugAdapters);
154    }
155
156    provides
157}
158
159async fn copy_extension_resources(
160    manifest: &ExtensionManifest,
161    extension_path: &Path,
162    output_dir: &Path,
163    fs: Arc<dyn Fs>,
164) -> Result<()> {
165    fs::create_dir_all(output_dir).context("failed to create output dir")?;
166
167    let manifest_toml = toml::to_string(&manifest).context("failed to serialize manifest")?;
168    fs::write(output_dir.join("extension.toml"), &manifest_toml)
169        .context("failed to write extension.toml")?;
170
171    if manifest.lib.kind.is_some() {
172        fs::copy(
173            extension_path.join("extension.wasm"),
174            output_dir.join("extension.wasm"),
175        )
176        .context("failed to copy extension.wasm")?;
177    }
178
179    if !manifest.grammars.is_empty() {
180        let source_grammars_dir = extension_path.join("grammars");
181        let output_grammars_dir = output_dir.join("grammars");
182        fs::create_dir_all(&output_grammars_dir)?;
183        for grammar_name in manifest.grammars.keys() {
184            let mut grammar_filename = PathBuf::from(grammar_name.as_ref());
185            grammar_filename.set_extension("wasm");
186            fs::copy(
187                source_grammars_dir.join(&grammar_filename),
188                output_grammars_dir.join(&grammar_filename),
189            )
190            .with_context(|| format!("failed to copy grammar '{}'", grammar_filename.display()))?;
191        }
192    }
193
194    if !manifest.themes.is_empty() {
195        let output_themes_dir = output_dir.join("themes");
196        fs::create_dir_all(&output_themes_dir)?;
197        for theme_path in &manifest.themes {
198            fs::copy(
199                extension_path.join(theme_path),
200                output_themes_dir.join(theme_path.file_name().context("invalid theme path")?),
201            )
202            .with_context(|| format!("failed to copy theme '{}'", theme_path.display()))?;
203        }
204    }
205
206    if !manifest.icon_themes.is_empty() {
207        let output_icon_themes_dir = output_dir.join("icon_themes");
208        fs::create_dir_all(&output_icon_themes_dir)?;
209        for icon_theme_path in &manifest.icon_themes {
210            fs::copy(
211                extension_path.join(icon_theme_path),
212                output_icon_themes_dir.join(
213                    icon_theme_path
214                        .file_name()
215                        .context("invalid icon theme path")?,
216                ),
217            )
218            .with_context(|| {
219                format!("failed to copy icon theme '{}'", icon_theme_path.display())
220            })?;
221        }
222
223        let output_icons_dir = output_dir.join("icons");
224        fs::create_dir_all(&output_icons_dir)?;
225        copy_recursive(
226            fs.as_ref(),
227            &extension_path.join("icons"),
228            &output_icons_dir,
229            CopyOptions {
230                overwrite: true,
231                ignore_if_exists: false,
232            },
233        )
234        .await
235        .with_context(|| "failed to copy icons")?;
236    }
237
238    for (_, agent_entry) in &manifest.agent_servers {
239        if let Some(icon_path) = &agent_entry.icon {
240            let source_icon = extension_path.join(icon_path);
241            let dest_icon = output_dir.join(icon_path);
242
243            // Create parent directory if needed
244            if let Some(parent) = dest_icon.parent() {
245                fs::create_dir_all(parent)?;
246            }
247
248            fs::copy(&source_icon, &dest_icon)
249                .with_context(|| format!("failed to copy agent server icon '{}'", icon_path))?;
250        }
251    }
252
253    if !manifest.languages.is_empty() {
254        let output_languages_dir = output_dir.join("languages");
255        fs::create_dir_all(&output_languages_dir)?;
256        for language_path in &manifest.languages {
257            copy_recursive(
258                fs.as_ref(),
259                &extension_path.join(language_path),
260                &output_languages_dir
261                    .join(language_path.file_name().context("invalid language path")?),
262                CopyOptions {
263                    overwrite: true,
264                    ignore_if_exists: false,
265                },
266            )
267            .await
268            .with_context(|| {
269                format!("failed to copy language dir '{}'", language_path.display())
270            })?;
271        }
272    }
273
274    if !manifest.debug_adapters.is_empty() {
275        for (debug_adapter, entry) in &manifest.debug_adapters {
276            let schema_path = entry.schema_path.clone().unwrap_or_else(|| {
277                PathBuf::from("debug_adapter_schemas".to_owned())
278                    .join(debug_adapter.as_ref())
279                    .with_extension("json")
280            });
281            let parent = schema_path
282                .parent()
283                .with_context(|| format!("invalid empty schema path for {debug_adapter}"))?;
284            fs::create_dir_all(output_dir.join(parent))?;
285            copy_recursive(
286                fs.as_ref(),
287                &extension_path.join(&schema_path),
288                &output_dir.join(&schema_path),
289                CopyOptions {
290                    overwrite: true,
291                    ignore_if_exists: false,
292                },
293            )
294            .await
295            .with_context(|| {
296                format!(
297                    "failed to copy debug adapter schema '{}'",
298                    schema_path.display()
299                )
300            })?;
301        }
302    }
303
304    if let Some(snippets_path) = manifest.snippets.as_ref() {
305        let parent = snippets_path.parent();
306        if let Some(parent) = parent.filter(|p| p.components().next().is_some()) {
307            fs::create_dir_all(output_dir.join(parent))?;
308        }
309        copy_recursive(
310            fs.as_ref(),
311            &extension_path.join(&snippets_path),
312            &output_dir.join(&snippets_path),
313            CopyOptions {
314                overwrite: true,
315                ignore_if_exists: false,
316            },
317        )
318        .await
319        .with_context(|| format!("failed to copy snippets from '{}'", snippets_path.display()))?;
320    }
321
322    Ok(())
323}
324
325fn test_grammars(
326    manifest: &ExtensionManifest,
327    extension_path: &Path,
328    wasm_store: &mut WasmStore,
329) -> Result<HashMap<String, Language>> {
330    let mut grammars = HashMap::default();
331    let grammars_dir = extension_path.join("grammars");
332
333    for grammar_name in manifest.grammars.keys() {
334        let mut grammar_path = grammars_dir.join(grammar_name.as_ref());
335        grammar_path.set_extension("wasm");
336
337        let wasm = fs::read(&grammar_path)?;
338        let language = wasm_store.load_language(grammar_name, &wasm)?;
339        log::info!("loaded grammar {grammar_name}");
340        grammars.insert(grammar_name.to_string(), language);
341    }
342
343    Ok(grammars)
344}
345
346fn test_languages(
347    manifest: &ExtensionManifest,
348    extension_path: &Path,
349    grammars: &HashMap<String, Language>,
350) -> Result<()> {
351    for relative_language_dir in &manifest.languages {
352        let language_dir = extension_path.join(relative_language_dir);
353        let config_path = language_dir.join("config.toml");
354        let config_content = fs::read_to_string(&config_path)?;
355        let config: LanguageConfig = toml::from_str(&config_content)?;
356        let grammar = if let Some(name) = &config.grammar {
357            Some(
358                grammars
359                    .get(name.as_ref())
360                    .with_context(|| format!("grammar not found: '{name}'"))?,
361            )
362        } else {
363            None
364        };
365
366        let query_entries = fs::read_dir(&language_dir)?;
367        for entry in query_entries {
368            let entry = entry?;
369            let query_path = entry.path();
370            if query_path.extension() == Some("scm".as_ref()) {
371                let grammar = grammar.with_context(|| {
372                    format! {
373                        "language {} provides query {} but no grammar",
374                        config.name,
375                        query_path.display()
376                    }
377                })?;
378
379                let query_source = fs::read_to_string(&query_path)?;
380                let _query = Query::new(grammar, &query_source)?;
381            }
382        }
383
384        log::info!("loaded language {}", config.name);
385    }
386
387    Ok(())
388}
389
390async fn test_themes(
391    manifest: &ExtensionManifest,
392    extension_path: &Path,
393    fs: Arc<dyn Fs>,
394) -> Result<()> {
395    for relative_theme_path in &manifest.themes {
396        let theme_path = extension_path.join(relative_theme_path);
397        let theme_family = theme::read_user_theme(&theme_path, fs.clone()).await?;
398        log::info!("loaded theme family {}", theme_family.name);
399
400        for theme in &theme_family.themes {
401            if theme
402                .style
403                .colors
404                .deprecated_scrollbar_thumb_background
405                .is_some()
406            {
407                bail!(
408                    r#"Theme "{theme_name}" is using a deprecated style property: scrollbar_thumb.background. Use `scrollbar.thumb.background` instead."#,
409                    theme_name = theme.name
410                )
411            }
412        }
413    }
414
415    Ok(())
416}