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