1use crate::{
2 ExtensionLibraryKind, ExtensionManifest, GrammarManifestEntry, build_debug_adapter_schema_path,
3 parse_wasm_extension_version,
4};
5use ::fs::Fs;
6use anyhow::{Context as _, Result, bail};
7use futures::{AsyncReadExt, StreamExt};
8use heck::ToSnakeCase;
9use http_client::{self, AsyncBody, HttpClient};
10use serde::Deserialize;
11use std::{
12 env, fs, mem,
13 path::{Path, PathBuf},
14 process::Stdio,
15 str::FromStr,
16 sync::Arc,
17};
18use wasm_encoder::{ComponentSectionId, Encode as _, RawSection, Section as _};
19use wasmparser::Parser;
20
21/// Currently, we compile with Rust's `wasm32-wasip2` target, which works with WASI `preview2` and the component model.
22const RUST_TARGET: &str = "wasm32-wasip2";
23
24/// Compiling Tree-sitter parsers from C to WASM requires Clang 17, and a WASM build of libc
25/// and clang's runtime library. The `wasi-sdk` provides these binaries.
26///
27/// Once Clang 17 and its wasm target are available via system package managers, we won't need
28/// to download this.
29const WASI_SDK_URL: &str = "https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-25/";
30const WASI_SDK_ASSET_NAME: Option<&str> = if cfg!(all(target_os = "macos", target_arch = "x86_64"))
31{
32 Some("wasi-sdk-25.0-x86_64-macos.tar.gz")
33} else if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
34 Some("wasi-sdk-25.0-arm64-macos.tar.gz")
35} else if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
36 Some("wasi-sdk-25.0-x86_64-linux.tar.gz")
37} else if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
38 Some("wasi-sdk-25.0-arm64-linux.tar.gz")
39} else if cfg!(all(target_os = "freebsd", target_arch = "x86_64")) {
40 Some("wasi-sdk-25.0-x86_64-linux.tar.gz")
41} else if cfg!(all(target_os = "freebsd", target_arch = "aarch64")) {
42 Some("wasi-sdk-25.0-arm64-linux.tar.gz")
43} else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
44 Some("wasi-sdk-25.0-x86_64-windows.tar.gz")
45} else {
46 None
47};
48
49pub struct ExtensionBuilder {
50 cache_dir: PathBuf,
51 pub http: Arc<dyn HttpClient>,
52}
53
54pub struct CompileExtensionOptions {
55 pub release: bool,
56}
57
58impl CompileExtensionOptions {
59 pub const fn dev() -> Self {
60 Self { release: false }
61 }
62}
63
64#[derive(Deserialize)]
65struct CargoToml {
66 package: CargoTomlPackage,
67}
68
69#[derive(Deserialize)]
70struct CargoTomlPackage {
71 name: String,
72}
73
74impl ExtensionBuilder {
75 pub fn new(http_client: Arc<dyn HttpClient>, cache_dir: PathBuf) -> Self {
76 Self {
77 cache_dir,
78 http: http_client,
79 }
80 }
81
82 pub async fn compile_extension(
83 &self,
84 extension_dir: &Path,
85 extension_manifest: &mut ExtensionManifest,
86 options: CompileExtensionOptions,
87 fs: Arc<dyn Fs>,
88 ) -> Result<()> {
89 populate_defaults(extension_manifest, extension_dir, fs).await?;
90
91 if extension_dir.is_relative() {
92 bail!(
93 "extension dir {} is not an absolute path",
94 extension_dir.display()
95 );
96 }
97
98 fs::create_dir_all(&self.cache_dir).context("failed to create cache dir")?;
99
100 if extension_manifest.lib.kind == Some(ExtensionLibraryKind::Rust) {
101 log::info!("compiling Rust extension {}", extension_dir.display());
102 self.compile_rust_extension(extension_dir, extension_manifest, options)
103 .await
104 .context("failed to compile Rust extension")?;
105 log::info!("compiled Rust extension {}", extension_dir.display());
106 }
107
108 for (debug_adapter_name, meta) in &mut extension_manifest.debug_adapters {
109 let debug_adapter_schema_path =
110 extension_dir.join(build_debug_adapter_schema_path(debug_adapter_name, meta));
111
112 let debug_adapter_schema = fs::read_to_string(&debug_adapter_schema_path)
113 .with_context(|| {
114 format!("failed to read debug adapter schema for `{debug_adapter_name}` from `{debug_adapter_schema_path:?}`")
115 })?;
116 _ = serde_json::Value::from_str(&debug_adapter_schema).with_context(|| {
117 format!("Debug adapter schema for `{debug_adapter_name}` (path: `{debug_adapter_schema_path:?}`) is not a valid JSON")
118 })?;
119 }
120 for (grammar_name, grammar_metadata) in &extension_manifest.grammars {
121 let snake_cased_grammar_name = grammar_name.to_snake_case();
122 if grammar_name.as_ref() != snake_cased_grammar_name.as_str() {
123 bail!(
124 "grammar name '{grammar_name}' must be written in snake_case: {snake_cased_grammar_name}"
125 );
126 }
127
128 log::info!(
129 "compiling grammar {grammar_name} for extension {}",
130 extension_dir.display()
131 );
132 self.compile_grammar(extension_dir, grammar_name.as_ref(), grammar_metadata)
133 .await
134 .with_context(|| format!("failed to compile grammar '{grammar_name}'"))?;
135 log::info!(
136 "compiled grammar {grammar_name} for extension {}",
137 extension_dir.display()
138 );
139 }
140
141 log::info!("finished compiling extension {}", extension_dir.display());
142 Ok(())
143 }
144
145 async fn compile_rust_extension(
146 &self,
147 extension_dir: &Path,
148 manifest: &mut ExtensionManifest,
149 options: CompileExtensionOptions,
150 ) -> anyhow::Result<()> {
151 self.install_rust_wasm_target_if_needed().await?;
152
153 let cargo_toml_content = fs::read_to_string(extension_dir.join("Cargo.toml"))?;
154 let cargo_toml: CargoToml = toml::from_str(&cargo_toml_content)?;
155
156 log::info!(
157 "compiling Rust crate for extension {}",
158 extension_dir.display()
159 );
160 let output = util::command::new_smol_command("cargo")
161 .args(["build", "--target", RUST_TARGET])
162 .args(options.release.then_some("--release"))
163 .arg("--target-dir")
164 .arg(extension_dir.join("target"))
165 // WASI builds do not work with sccache and just stuck, so disable it.
166 .env("RUSTC_WRAPPER", "")
167 .current_dir(extension_dir)
168 .output()
169 .await
170 .context("failed to run `cargo`")?;
171 if !output.status.success() {
172 bail!(
173 "failed to build extension {}",
174 String::from_utf8_lossy(&output.stderr)
175 );
176 }
177
178 log::info!(
179 "compiled Rust crate for extension {}",
180 extension_dir.display()
181 );
182
183 let mut wasm_path = PathBuf::from(extension_dir);
184 wasm_path.extend([
185 "target",
186 RUST_TARGET,
187 if options.release { "release" } else { "debug" },
188 &cargo_toml
189 .package
190 .name
191 // The wasm32-wasip2 target normalizes `-` in package names to `_` in the resulting `.wasm` file.
192 .replace('-', "_"),
193 ]);
194 wasm_path.set_extension("wasm");
195
196 log::info!(
197 "encoding wasm component for extension {}",
198 extension_dir.display()
199 );
200
201 let component_bytes = fs::read(&wasm_path)
202 .with_context(|| format!("failed to read output module `{}`", wasm_path.display()))?;
203
204 let component_bytes = self
205 .strip_custom_sections(&component_bytes)
206 .context("failed to strip debug sections from wasm component")?;
207
208 let wasm_extension_api_version =
209 parse_wasm_extension_version(&manifest.id, &component_bytes)
210 .context("compiled wasm did not contain a valid zed extension api version")?;
211 manifest.lib.version = Some(wasm_extension_api_version);
212
213 let extension_file = extension_dir.join("extension.wasm");
214 fs::write(extension_file.clone(), &component_bytes)
215 .context("failed to write extension.wasm")?;
216
217 log::info!(
218 "extension {} written to {}",
219 extension_dir.display(),
220 extension_file.display()
221 );
222
223 Ok(())
224 }
225
226 async fn compile_grammar(
227 &self,
228 extension_dir: &Path,
229 grammar_name: &str,
230 grammar_metadata: &GrammarManifestEntry,
231 ) -> Result<()> {
232 let clang_path = self.install_wasi_sdk_if_needed().await?;
233
234 let mut grammar_repo_dir = extension_dir.to_path_buf();
235 grammar_repo_dir.extend(["grammars", grammar_name]);
236
237 let mut grammar_wasm_path = grammar_repo_dir.clone();
238 grammar_wasm_path.set_extension("wasm");
239
240 log::info!("checking out {grammar_name} parser");
241 self.checkout_repo(
242 &grammar_repo_dir,
243 &grammar_metadata.repository,
244 &grammar_metadata.rev,
245 )
246 .await?;
247
248 let base_grammar_path = grammar_metadata
249 .path
250 .as_ref()
251 .map(|path| grammar_repo_dir.join(path))
252 .unwrap_or(grammar_repo_dir);
253
254 let src_path = base_grammar_path.join("src");
255 let parser_path = src_path.join("parser.c");
256 let scanner_path = src_path.join("scanner.c");
257
258 // Skip recompiling if the WASM object is already newer than the source files
259 if file_newer_than_deps(&grammar_wasm_path, &[&parser_path, &scanner_path]).unwrap_or(false)
260 {
261 log::info!(
262 "skipping compilation of {grammar_name} parser because the existing compiled grammar is up to date"
263 );
264 } else {
265 log::info!("compiling {grammar_name} parser");
266 let clang_output = util::command::new_smol_command(&clang_path)
267 .args(["-fPIC", "-shared", "-Os"])
268 .arg(format!("-Wl,--export=tree_sitter_{grammar_name}"))
269 .arg("-o")
270 .arg(&grammar_wasm_path)
271 .arg("-I")
272 .arg(&src_path)
273 .arg(&parser_path)
274 .args(scanner_path.exists().then_some(scanner_path))
275 .output()
276 .await
277 .context("failed to run clang")?;
278
279 if !clang_output.status.success() {
280 bail!(
281 "failed to compile {} parser with clang: {}",
282 grammar_name,
283 String::from_utf8_lossy(&clang_output.stderr),
284 );
285 }
286 }
287
288 Ok(())
289 }
290
291 async fn checkout_repo(&self, directory: &Path, url: &str, rev: &str) -> Result<()> {
292 let git_dir = directory.join(".git");
293
294 if directory.exists() {
295 let remotes_output = util::command::new_smol_command("git")
296 .arg("--git-dir")
297 .arg(&git_dir)
298 .args(["remote", "-v"])
299 .output()
300 .await?;
301 let has_remote = remotes_output.status.success()
302 && String::from_utf8_lossy(&remotes_output.stdout)
303 .lines()
304 .any(|line| {
305 let mut parts = line.split(|c: char| c.is_whitespace());
306 parts.next() == Some("origin") && parts.any(|part| part == url)
307 });
308 if !has_remote {
309 bail!(
310 "grammar directory '{}' already exists, but is not a git clone of '{}'",
311 directory.display(),
312 url
313 );
314 }
315 } else {
316 fs::create_dir_all(directory).with_context(|| {
317 format!("failed to create grammar directory {}", directory.display(),)
318 })?;
319 let init_output = util::command::new_smol_command("git")
320 .arg("init")
321 .current_dir(directory)
322 .output()
323 .await?;
324 if !init_output.status.success() {
325 bail!(
326 "failed to run `git init` in directory '{}'",
327 directory.display()
328 );
329 }
330
331 let remote_add_output = util::command::new_smol_command("git")
332 .arg("--git-dir")
333 .arg(&git_dir)
334 .args(["remote", "add", "origin", url])
335 .output()
336 .await
337 .context("failed to execute `git remote add`")?;
338 if !remote_add_output.status.success() {
339 bail!(
340 "failed to add remote {url} for git repository {}",
341 git_dir.display()
342 );
343 }
344 }
345
346 let fetch_output = util::command::new_smol_command("git")
347 .arg("--git-dir")
348 .arg(&git_dir)
349 .args(["fetch", "--depth", "1", "origin", rev])
350 .output()
351 .await
352 .context("failed to execute `git fetch`")?;
353
354 let checkout_output = util::command::new_smol_command("git")
355 .arg("--git-dir")
356 .arg(&git_dir)
357 .args(["checkout", rev])
358 .current_dir(directory)
359 .output()
360 .await
361 .context("failed to execute `git checkout`")?;
362 if !checkout_output.status.success() {
363 if !fetch_output.status.success() {
364 bail!(
365 "failed to fetch revision {} in directory '{}'",
366 rev,
367 directory.display()
368 );
369 }
370 bail!(
371 "failed to checkout revision {} in directory '{}': {}",
372 rev,
373 directory.display(),
374 String::from_utf8_lossy(&checkout_output.stderr)
375 );
376 }
377
378 Ok(())
379 }
380
381 async fn install_rust_wasm_target_if_needed(&self) -> Result<()> {
382 let rustc_output = util::command::new_smol_command("rustc")
383 .arg("--print")
384 .arg("sysroot")
385 .output()
386 .await
387 .context("failed to run rustc")?;
388 if !rustc_output.status.success() {
389 bail!(
390 "failed to retrieve rust sysroot: {}",
391 String::from_utf8_lossy(&rustc_output.stderr)
392 );
393 }
394
395 let sysroot = PathBuf::from(String::from_utf8(rustc_output.stdout)?.trim());
396 if sysroot.join("lib/rustlib").join(RUST_TARGET).exists() {
397 return Ok(());
398 }
399
400 let output = util::command::new_smol_command("rustup")
401 .args(["target", "add", RUST_TARGET])
402 .stderr(Stdio::piped())
403 .stdout(Stdio::inherit())
404 .output()
405 .await
406 .context("failed to run `rustup target add`")?;
407 if !output.status.success() {
408 bail!(
409 "failed to install the `{RUST_TARGET}` target: {}",
410 String::from_utf8_lossy(&rustc_output.stderr)
411 );
412 }
413
414 Ok(())
415 }
416
417 async fn install_wasi_sdk_if_needed(&self) -> Result<PathBuf> {
418 let url = if let Some(asset_name) = WASI_SDK_ASSET_NAME {
419 format!("{WASI_SDK_URL}{asset_name}")
420 } else {
421 bail!("wasi-sdk is not available for platform {}", env::consts::OS);
422 };
423
424 let wasi_sdk_dir = self.cache_dir.join("wasi-sdk");
425 let mut clang_path = wasi_sdk_dir.clone();
426 clang_path.extend(["bin", &format!("clang{}", env::consts::EXE_SUFFIX)]);
427
428 log::info!("downloading wasi-sdk to {}", wasi_sdk_dir.display());
429
430 if fs::metadata(&clang_path).is_ok_and(|metadata| metadata.is_file()) {
431 return Ok(clang_path);
432 }
433
434 let tar_out_dir = self.cache_dir.join("wasi-sdk-temp");
435
436 fs::remove_dir_all(&wasi_sdk_dir).ok();
437 fs::remove_dir_all(&tar_out_dir).ok();
438 fs::create_dir_all(&tar_out_dir).context("failed to create extraction directory")?;
439
440 let mut response = self.http.get(&url, AsyncBody::default(), true).await?;
441
442 // Write the response to a temporary file
443 let tar_gz_path = self.cache_dir.join("wasi-sdk.tar.gz");
444 let mut tar_gz_file =
445 fs::File::create(&tar_gz_path).context("failed to create temporary tar.gz file")?;
446 let response_body = response.body_mut();
447 let mut body_bytes = Vec::new();
448 response_body.read_to_end(&mut body_bytes).await?;
449 std::io::Write::write_all(&mut tar_gz_file, &body_bytes)?;
450 drop(tar_gz_file);
451
452 log::info!("un-tarring wasi-sdk to {}", tar_out_dir.display());
453
454 // Shell out to tar to extract the archive
455 let tar_output = util::command::new_smol_command("tar")
456 .arg("-xzf")
457 .arg(&tar_gz_path)
458 .arg("-C")
459 .arg(&tar_out_dir)
460 .output()
461 .await
462 .context("failed to run tar")?;
463
464 if !tar_output.status.success() {
465 bail!(
466 "failed to extract wasi-sdk archive: {}",
467 String::from_utf8_lossy(&tar_output.stderr)
468 );
469 }
470
471 log::info!("finished downloading wasi-sdk");
472
473 // Clean up the temporary tar.gz file
474 fs::remove_file(&tar_gz_path).ok();
475
476 let inner_dir = fs::read_dir(&tar_out_dir)?
477 .next()
478 .context("no content")?
479 .context("failed to read contents of extracted wasi archive directory")?
480 .path();
481 fs::rename(&inner_dir, &wasi_sdk_dir).context("failed to move extracted wasi dir")?;
482 fs::remove_dir_all(&tar_out_dir).ok();
483
484 Ok(clang_path)
485 }
486
487 // This was adapted from:
488 // https://github.com/bytecodealliance/wasm-tools/blob/e8809bb17fcf69aa8c85cd5e6db7cff5cf36b1de/src/bin/wasm-tools/strip.rs
489 fn strip_custom_sections(&self, input: &Vec<u8>) -> Result<Vec<u8>> {
490 use wasmparser::Payload::*;
491
492 let strip_custom_section = |name: &str| {
493 // Default strip everything but:
494 // * the `name` section
495 // * any `component-type` sections
496 // * the `dylink.0` section
497 // * our custom version section
498 name != "name"
499 && !name.starts_with("component-type:")
500 && name != "dylink.0"
501 && name != "zed:api-version"
502 };
503
504 let mut output = Vec::new();
505 let mut stack = Vec::new();
506
507 for payload in Parser::new(0).parse_all(input) {
508 let payload = payload?;
509
510 // Track nesting depth, so that we don't mess with inner producer sections:
511 match payload {
512 Version { encoding, .. } => {
513 output.extend_from_slice(match encoding {
514 wasmparser::Encoding::Component => &wasm_encoder::Component::HEADER,
515 wasmparser::Encoding::Module => &wasm_encoder::Module::HEADER,
516 });
517 }
518 ModuleSection { .. } | ComponentSection { .. } => {
519 stack.push(mem::take(&mut output));
520 continue;
521 }
522 End { .. } => {
523 let mut parent = match stack.pop() {
524 Some(c) => c,
525 None => break,
526 };
527 if output.starts_with(&wasm_encoder::Component::HEADER) {
528 parent.push(ComponentSectionId::Component as u8);
529 output.encode(&mut parent);
530 } else {
531 parent.push(ComponentSectionId::CoreModule as u8);
532 output.encode(&mut parent);
533 }
534 output = parent;
535 }
536 _ => {}
537 }
538
539 if let CustomSection(c) = &payload
540 && strip_custom_section(c.name())
541 {
542 continue;
543 }
544 if let Some((id, range)) = payload.as_section() {
545 RawSection {
546 id,
547 data: &input[range],
548 }
549 .append_to(&mut output);
550 }
551 }
552
553 Ok(output)
554 }
555}
556
557async fn populate_defaults(
558 manifest: &mut ExtensionManifest,
559 extension_path: &Path,
560 fs: Arc<dyn Fs>,
561) -> Result<()> {
562 // For legacy extensions on the v0 schema (aka, using `extension.json`), clear out any existing
563 // contents of the computed fields, since we don't care what the existing values are.
564 if manifest.schema_version.is_v0() {
565 manifest.languages.clear();
566 manifest.grammars.clear();
567 manifest.themes.clear();
568 }
569
570 let cargo_toml_path = extension_path.join("Cargo.toml");
571 if cargo_toml_path.exists() {
572 manifest.lib.kind = Some(ExtensionLibraryKind::Rust);
573 }
574
575 let languages_dir = extension_path.join("languages");
576 if fs.is_dir(&languages_dir).await {
577 let mut language_dir_entries = fs
578 .read_dir(&languages_dir)
579 .await
580 .context("failed to list languages dir")?;
581
582 while let Some(language_dir) = language_dir_entries.next().await {
583 let language_dir = language_dir?;
584 let config_path = language_dir.join("config.toml");
585 if fs.is_file(config_path.as_path()).await {
586 let relative_language_dir =
587 language_dir.strip_prefix(extension_path)?.to_path_buf();
588 if !manifest.languages.contains(&relative_language_dir) {
589 manifest.languages.push(relative_language_dir);
590 }
591 }
592 }
593 }
594
595 let themes_dir = extension_path.join("themes");
596 if fs.is_dir(&themes_dir).await {
597 let mut theme_dir_entries = fs
598 .read_dir(&themes_dir)
599 .await
600 .context("failed to list themes dir")?;
601
602 while let Some(theme_path) = theme_dir_entries.next().await {
603 let theme_path = theme_path?;
604 if theme_path.extension() == Some("json".as_ref()) {
605 let relative_theme_path = theme_path.strip_prefix(extension_path)?.to_path_buf();
606 if !manifest.themes.contains(&relative_theme_path) {
607 manifest.themes.push(relative_theme_path);
608 }
609 }
610 }
611 }
612
613 let icon_themes_dir = extension_path.join("icon_themes");
614 if fs.is_dir(&icon_themes_dir).await {
615 let mut icon_theme_dir_entries = fs
616 .read_dir(&icon_themes_dir)
617 .await
618 .context("failed to list icon themes dir")?;
619
620 while let Some(icon_theme_path) = icon_theme_dir_entries.next().await {
621 let icon_theme_path = icon_theme_path?;
622 if icon_theme_path.extension() == Some("json".as_ref()) {
623 let relative_icon_theme_path =
624 icon_theme_path.strip_prefix(extension_path)?.to_path_buf();
625 if !manifest.icon_themes.contains(&relative_icon_theme_path) {
626 manifest.icon_themes.push(relative_icon_theme_path);
627 }
628 }
629 }
630 };
631 if manifest.snippets.is_none()
632 && let snippets_json_path = extension_path.join("snippets.json")
633 && fs.is_file(&snippets_json_path).await
634 {
635 manifest.snippets = Some("snippets.json".into());
636 }
637
638 // For legacy extensions on the v0 schema (aka, using `extension.json`), we want to populate the grammars in
639 // the manifest using the contents of the `grammars` directory.
640 if manifest.schema_version.is_v0() {
641 let grammars_dir = extension_path.join("grammars");
642 if fs.is_dir(&grammars_dir).await {
643 let mut grammar_dir_entries = fs
644 .read_dir(&grammars_dir)
645 .await
646 .context("failed to list grammars dir")?;
647
648 while let Some(grammar_path) = grammar_dir_entries.next().await {
649 let grammar_path = grammar_path?;
650 if grammar_path.extension() == Some("toml".as_ref()) {
651 #[derive(Deserialize)]
652 struct GrammarConfigToml {
653 pub repository: String,
654 pub commit: String,
655 #[serde(default)]
656 pub path: Option<String>,
657 }
658
659 let grammar_config = fs.load(&grammar_path).await?;
660 let grammar_config: GrammarConfigToml = toml::from_str(&grammar_config)?;
661
662 let grammar_name = grammar_path
663 .file_stem()
664 .and_then(|stem| stem.to_str())
665 .context("no grammar name")?;
666 if !manifest.grammars.contains_key(grammar_name) {
667 manifest.grammars.insert(
668 grammar_name.into(),
669 GrammarManifestEntry {
670 repository: grammar_config.repository,
671 rev: grammar_config.commit,
672 path: grammar_config.path,
673 },
674 );
675 }
676 }
677 }
678 }
679 }
680
681 Ok(())
682}
683
684/// Returns `true` if the target exists and its last modified time is greater than that
685/// of each dependency which exists (i.e., dependency paths which do not exist are ignored).
686///
687/// # Errors
688///
689/// Returns `Err` if any of the underlying file I/O operations fail.
690fn file_newer_than_deps(target: &Path, dependencies: &[&Path]) -> Result<bool, std::io::Error> {
691 if !target.try_exists()? {
692 return Ok(false);
693 }
694 let target_modified = target.metadata()?.modified()?;
695 for dependency in dependencies {
696 if !dependency.try_exists()? {
697 continue;
698 }
699 let dep_modified = dependency.metadata()?.modified()?;
700 if target_modified < dep_modified {
701 return Ok(false);
702 }
703 }
704 Ok(true)
705}
706
707#[cfg(test)]
708mod tests {
709 use std::{
710 path::{Path, PathBuf},
711 str::FromStr,
712 thread::sleep,
713 time::Duration,
714 };
715
716 use gpui::TestAppContext;
717 use indoc::indoc;
718
719 use crate::{
720 ExtensionManifest,
721 extension_builder::{file_newer_than_deps, populate_defaults},
722 };
723
724 #[test]
725 fn test_file_newer_than_deps() {
726 // Don't use TempTree because we need to guarantee the order
727 let tmpdir = tempfile::tempdir().unwrap();
728 let target = tmpdir.path().join("target.wasm");
729 let dep1 = tmpdir.path().join("parser.c");
730 let dep2 = tmpdir.path().join("scanner.c");
731
732 assert!(
733 !file_newer_than_deps(&target, &[&dep1, &dep2]).unwrap(),
734 "target doesn't exist"
735 );
736 std::fs::write(&target, "foo").unwrap(); // Create target
737 assert!(
738 file_newer_than_deps(&target, &[&dep1, &dep2]).unwrap(),
739 "dependencies don't exist; target is newer"
740 );
741 sleep(Duration::from_secs(1));
742 std::fs::write(&dep1, "foo").unwrap(); // Create dep1 (newer than target)
743 // Dependency is newer
744 assert!(
745 !file_newer_than_deps(&target, &[&dep1, &dep2]).unwrap(),
746 "a dependency is newer (target {:?}, dep1 {:?})",
747 target.metadata().unwrap().modified().unwrap(),
748 dep1.metadata().unwrap().modified().unwrap(),
749 );
750 sleep(Duration::from_secs(1));
751 std::fs::write(&dep2, "foo").unwrap(); // Create dep2
752 sleep(Duration::from_secs(1));
753 std::fs::write(&target, "foobar").unwrap(); // Update target
754 assert!(
755 file_newer_than_deps(&target, &[&dep1, &dep2]).unwrap(),
756 "target is newer than dependencies (target {:?}, dep2 {:?})",
757 target.metadata().unwrap().modified().unwrap(),
758 dep2.metadata().unwrap().modified().unwrap(),
759 );
760 }
761
762 #[gpui::test]
763 async fn test_snippet_location_is_kept(cx: &mut TestAppContext) {
764 let fs = fs::FakeFs::new(cx.executor());
765 let extension_path = Path::new("/extension");
766
767 fs.insert_tree(
768 extension_path,
769 serde_json::json!({
770 "extension.toml": indoc! {r#"
771 id = "test-manifest"
772 name = "Test Manifest"
773 version = "0.0.1"
774 schema_version = 1
775
776 snippets = "./snippets/snippets.json"
777 "#
778 },
779 "snippets.json": "",
780 }),
781 )
782 .await;
783
784 let mut manifest = ExtensionManifest::load(fs.clone(), extension_path)
785 .await
786 .unwrap();
787
788 populate_defaults(&mut manifest, extension_path, fs.clone())
789 .await
790 .unwrap();
791
792 assert_eq!(
793 manifest.snippets,
794 Some(PathBuf::from_str("./snippets/snippets.json").unwrap())
795 )
796 }
797
798 #[gpui::test]
799 async fn test_automatic_snippet_location_is_relative(cx: &mut TestAppContext) {
800 let fs = fs::FakeFs::new(cx.executor());
801 let extension_path = Path::new("/extension");
802
803 fs.insert_tree(
804 extension_path,
805 serde_json::json!({
806 "extension.toml": indoc! {r#"
807 id = "test-manifest"
808 name = "Test Manifest"
809 version = "0.0.1"
810 schema_version = 1
811
812 "#
813 },
814 "snippets.json": "",
815 }),
816 )
817 .await;
818
819 let mut manifest = ExtensionManifest::load(fs.clone(), extension_path)
820 .await
821 .unwrap();
822
823 populate_defaults(&mut manifest, extension_path, fs.clone())
824 .await
825 .unwrap();
826
827 assert_eq!(
828 manifest.snippets,
829 Some(PathBuf::from_str("snippets.json").unwrap())
830 )
831 }
832}