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