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