1pub mod extension_settings;
2pub mod headless_host;
3pub mod wasm_host;
4
5#[cfg(test)]
6mod extension_store_test;
7
8use anyhow::{Context as _, Result, anyhow, bail};
9use async_compression::futures::bufread::GzipDecoder;
10use async_tar::Archive;
11use client::ExtensionProvides;
12use client::{Client, ExtensionMetadata, GetExtensionsResponse, proto, telemetry::Telemetry};
13use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
14pub use extension::ExtensionManifest;
15use extension::extension_builder::{CompileExtensionOptions, ExtensionBuilder};
16use extension::{
17 ExtensionContextServerProxy, ExtensionDebugAdapterProviderProxy, ExtensionEvents,
18 ExtensionGrammarProxy, ExtensionHostProxy, ExtensionIndexedDocsProviderProxy,
19 ExtensionLanguageProxy, ExtensionLanguageServerProxy, ExtensionSlashCommandProxy,
20 ExtensionSnippetProxy, ExtensionThemeProxy,
21};
22use fs::{Fs, RemoveOptions};
23use futures::future::join_all;
24use futures::{
25 AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
26 channel::{
27 mpsc::{UnboundedSender, unbounded},
28 oneshot,
29 },
30 io::BufReader,
31 select_biased,
32};
33use gpui::{
34 App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, Task, WeakEntity,
35 actions,
36};
37use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
38use language::{
39 LanguageConfig, LanguageMatcher, LanguageName, LanguageQueries, LoadedLanguage,
40 QUERY_FILENAME_PREFIXES, Rope,
41};
42use node_runtime::NodeRuntime;
43use project::ContextProviderWithTasks;
44use release_channel::ReleaseChannel;
45use remote::SshRemoteClient;
46use semantic_version::SemanticVersion;
47use serde::{Deserialize, Serialize};
48use settings::Settings;
49use std::ops::RangeInclusive;
50use std::str::FromStr;
51use std::{
52 cmp::Ordering,
53 path::{self, Path, PathBuf},
54 sync::Arc,
55 time::{Duration, Instant},
56};
57use url::Url;
58use util::{ResultExt, paths::RemotePathBuf};
59use wasm_host::{
60 WasmExtension, WasmHost,
61 wit::{is_supported_wasm_api_version, wasm_api_version_range},
62};
63
64pub use extension::{
65 ExtensionLibraryKind, GrammarManifestEntry, OldExtensionManifest, SchemaVersion,
66};
67pub use extension_settings::ExtensionSettings;
68
69pub const RELOAD_DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
70const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
71
72/// The current extension [`SchemaVersion`] supported by Zed.
73const CURRENT_SCHEMA_VERSION: SchemaVersion = SchemaVersion(1);
74
75/// Returns the [`SchemaVersion`] range that is compatible with this version of Zed.
76pub fn schema_version_range() -> RangeInclusive<SchemaVersion> {
77 SchemaVersion::ZERO..=CURRENT_SCHEMA_VERSION
78}
79
80/// Returns whether the given extension version is compatible with this version of Zed.
81pub fn is_version_compatible(
82 release_channel: ReleaseChannel,
83 extension_version: &ExtensionMetadata,
84) -> bool {
85 let schema_version = extension_version.manifest.schema_version.unwrap_or(0);
86 if CURRENT_SCHEMA_VERSION.0 < schema_version {
87 return false;
88 }
89
90 if let Some(wasm_api_version) = extension_version
91 .manifest
92 .wasm_api_version
93 .as_ref()
94 .and_then(|wasm_api_version| SemanticVersion::from_str(wasm_api_version).ok())
95 {
96 if !is_supported_wasm_api_version(release_channel, wasm_api_version) {
97 return false;
98 }
99 }
100
101 true
102}
103
104pub struct ExtensionStore {
105 pub proxy: Arc<ExtensionHostProxy>,
106 pub builder: Arc<ExtensionBuilder>,
107 pub extension_index: ExtensionIndex,
108 pub fs: Arc<dyn Fs>,
109 pub http_client: Arc<HttpClientWithUrl>,
110 pub telemetry: Option<Arc<Telemetry>>,
111 pub reload_tx: UnboundedSender<Option<Arc<str>>>,
112 pub reload_complete_senders: Vec<oneshot::Sender<()>>,
113 pub installed_dir: PathBuf,
114 pub outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
115 pub index_path: PathBuf,
116 pub modified_extensions: HashSet<Arc<str>>,
117 pub wasm_host: Arc<WasmHost>,
118 pub wasm_extensions: Vec<(Arc<ExtensionManifest>, WasmExtension)>,
119 pub tasks: Vec<Task<()>>,
120 pub ssh_clients: HashMap<String, WeakEntity<SshRemoteClient>>,
121 pub ssh_registered_tx: UnboundedSender<()>,
122}
123
124#[derive(Clone, Copy)]
125pub enum ExtensionOperation {
126 Upgrade,
127 Install,
128 Remove,
129}
130
131#[derive(Clone)]
132pub enum Event {
133 ExtensionsUpdated,
134 StartedReloading,
135 ExtensionInstalled(Arc<str>),
136 ExtensionUninstalled(Arc<str>),
137 ExtensionFailedToLoad(Arc<str>),
138}
139
140impl EventEmitter<Event> for ExtensionStore {}
141
142struct GlobalExtensionStore(Entity<ExtensionStore>);
143
144impl Global for GlobalExtensionStore {}
145
146#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
147pub struct ExtensionIndex {
148 pub extensions: BTreeMap<Arc<str>, ExtensionIndexEntry>,
149 pub themes: BTreeMap<Arc<str>, ExtensionIndexThemeEntry>,
150 #[serde(default)]
151 pub icon_themes: BTreeMap<Arc<str>, ExtensionIndexIconThemeEntry>,
152 pub languages: BTreeMap<LanguageName, ExtensionIndexLanguageEntry>,
153}
154
155#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
156pub struct ExtensionIndexEntry {
157 pub manifest: Arc<ExtensionManifest>,
158 pub dev: bool,
159}
160
161#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
162pub struct ExtensionIndexThemeEntry {
163 pub extension: Arc<str>,
164 pub path: PathBuf,
165}
166
167#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
168pub struct ExtensionIndexIconThemeEntry {
169 pub extension: Arc<str>,
170 pub path: PathBuf,
171}
172
173#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
174pub struct ExtensionIndexLanguageEntry {
175 pub extension: Arc<str>,
176 pub path: PathBuf,
177 pub matcher: LanguageMatcher,
178 pub hidden: bool,
179 pub grammar: Option<Arc<str>>,
180}
181
182actions!(
183 zed,
184 [
185 /// Reloads all installed extensions.
186 ReloadExtensions
187 ]
188);
189
190pub fn init(
191 extension_host_proxy: Arc<ExtensionHostProxy>,
192 fs: Arc<dyn Fs>,
193 client: Arc<Client>,
194 node_runtime: NodeRuntime,
195 cx: &mut App,
196) {
197 ExtensionSettings::register(cx);
198
199 let store = cx.new(move |cx| {
200 ExtensionStore::new(
201 paths::extensions_dir().clone(),
202 None,
203 extension_host_proxy,
204 fs,
205 client.http_client(),
206 client.http_client(),
207 Some(client.telemetry().clone()),
208 node_runtime,
209 cx,
210 )
211 });
212
213 cx.on_action(|_: &ReloadExtensions, cx| {
214 let store = cx.global::<GlobalExtensionStore>().0.clone();
215 store.update(cx, |store, cx| drop(store.reload(None, cx)));
216 });
217
218 cx.set_global(GlobalExtensionStore(store));
219}
220
221impl ExtensionStore {
222 pub fn try_global(cx: &App) -> Option<Entity<Self>> {
223 cx.try_global::<GlobalExtensionStore>()
224 .map(|store| store.0.clone())
225 }
226
227 pub fn global(cx: &App) -> Entity<Self> {
228 cx.global::<GlobalExtensionStore>().0.clone()
229 }
230
231 pub fn new(
232 extensions_dir: PathBuf,
233 build_dir: Option<PathBuf>,
234 extension_host_proxy: Arc<ExtensionHostProxy>,
235 fs: Arc<dyn Fs>,
236 http_client: Arc<HttpClientWithUrl>,
237 builder_client: Arc<dyn HttpClient>,
238 telemetry: Option<Arc<Telemetry>>,
239 node_runtime: NodeRuntime,
240 cx: &mut Context<Self>,
241 ) -> Self {
242 let work_dir = extensions_dir.join("work");
243 let build_dir = build_dir.unwrap_or_else(|| extensions_dir.join("build"));
244 let installed_dir = extensions_dir.join("installed");
245 let index_path = extensions_dir.join("index.json");
246
247 let (reload_tx, mut reload_rx) = unbounded();
248 let (connection_registered_tx, mut connection_registered_rx) = unbounded();
249 let mut this = Self {
250 proxy: extension_host_proxy.clone(),
251 extension_index: Default::default(),
252 installed_dir,
253 index_path,
254 builder: Arc::new(ExtensionBuilder::new(builder_client, build_dir)),
255 outstanding_operations: Default::default(),
256 modified_extensions: Default::default(),
257 reload_complete_senders: Vec::new(),
258 wasm_host: WasmHost::new(
259 fs.clone(),
260 http_client.clone(),
261 node_runtime,
262 extension_host_proxy,
263 work_dir,
264 cx,
265 ),
266 wasm_extensions: Vec::new(),
267 fs,
268 http_client,
269 telemetry,
270 reload_tx,
271 tasks: Vec::new(),
272
273 ssh_clients: HashMap::default(),
274 ssh_registered_tx: connection_registered_tx,
275 };
276
277 // The extensions store maintains an index file, which contains a complete
278 // list of the installed extensions and the resources that they provide.
279 // This index is loaded synchronously on startup.
280 let (index_content, index_metadata, extensions_metadata) =
281 cx.background_executor().block(async {
282 futures::join!(
283 this.fs.load(&this.index_path),
284 this.fs.metadata(&this.index_path),
285 this.fs.metadata(&this.installed_dir),
286 )
287 });
288
289 // Normally, there is no need to rebuild the index. But if the index file
290 // is invalid or is out-of-date according to the filesystem mtimes, then
291 // it must be asynchronously rebuilt.
292 let mut extension_index = ExtensionIndex::default();
293 let mut extension_index_needs_rebuild = true;
294 if let Ok(index_content) = index_content {
295 if let Some(index) = serde_json::from_str(&index_content).log_err() {
296 extension_index = index;
297 if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
298 (index_metadata, extensions_metadata)
299 {
300 if index_metadata
301 .mtime
302 .bad_is_greater_than(extensions_metadata.mtime)
303 {
304 extension_index_needs_rebuild = false;
305 }
306 }
307 }
308 }
309
310 // Immediately load all of the extensions in the initial manifest. If the
311 // index needs to be rebuild, then enqueue
312 let load_initial_extensions = this.extensions_updated(extension_index, cx);
313 let mut reload_future = None;
314 if extension_index_needs_rebuild {
315 reload_future = Some(this.reload(None, cx));
316 }
317
318 cx.spawn(async move |this, cx| {
319 if let Some(future) = reload_future {
320 future.await;
321 }
322 this.update(cx, |this, cx| this.auto_install_extensions(cx))
323 .ok();
324 this.update(cx, |this, cx| this.check_for_updates(cx)).ok();
325 })
326 .detach();
327
328 // Perform all extension loading in a single task to ensure that we
329 // never attempt to simultaneously load/unload extensions from multiple
330 // parallel tasks.
331 this.tasks.push(cx.spawn(async move |this, cx| {
332 async move {
333 load_initial_extensions.await;
334
335 let mut index_changed = false;
336 let mut debounce_timer = cx.background_spawn(futures::future::pending()).fuse();
337 loop {
338 select_biased! {
339 _ = debounce_timer => {
340 if index_changed {
341 let index = this
342 .update(cx, |this, cx| this.rebuild_extension_index(cx))?
343 .await;
344 this.update( cx, |this, cx| this.extensions_updated(index, cx))?
345 .await;
346 index_changed = false;
347 }
348
349 Self::update_ssh_clients(&this, cx).await?;
350 }
351 _ = connection_registered_rx.next() => {
352 debounce_timer = cx
353 .background_executor()
354 .timer(RELOAD_DEBOUNCE_DURATION)
355 .fuse();
356 }
357 extension_id = reload_rx.next() => {
358 let Some(extension_id) = extension_id else { break; };
359 this.update( cx, |this, _| {
360 this.modified_extensions.extend(extension_id);
361 })?;
362 index_changed = true;
363 debounce_timer = cx
364 .background_executor()
365 .timer(RELOAD_DEBOUNCE_DURATION)
366 .fuse();
367 }
368 }
369 }
370
371 anyhow::Ok(())
372 }
373 .map(drop)
374 .await;
375 }));
376
377 // Watch the installed extensions directory for changes. Whenever changes are
378 // detected, rebuild the extension index, and load/unload any extensions that
379 // have been added, removed, or modified.
380 this.tasks.push(cx.background_spawn({
381 let fs = this.fs.clone();
382 let reload_tx = this.reload_tx.clone();
383 let installed_dir = this.installed_dir.clone();
384 async move {
385 let (mut paths, _) = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
386 while let Some(events) = paths.next().await {
387 for event in events {
388 let Ok(event_path) = event.path.strip_prefix(&installed_dir) else {
389 continue;
390 };
391
392 if let Some(path::Component::Normal(extension_dir_name)) =
393 event_path.components().next()
394 {
395 if let Some(extension_id) = extension_dir_name.to_str() {
396 reload_tx.unbounded_send(Some(extension_id.into())).ok();
397 }
398 }
399 }
400 }
401 }
402 }));
403
404 this
405 }
406
407 pub fn reload(
408 &mut self,
409 modified_extension: Option<Arc<str>>,
410 cx: &mut Context<Self>,
411 ) -> impl Future<Output = ()> + use<> {
412 let (tx, rx) = oneshot::channel();
413 self.reload_complete_senders.push(tx);
414 self.reload_tx
415 .unbounded_send(modified_extension)
416 .expect("reload task exited");
417 cx.emit(Event::StartedReloading);
418
419 async move {
420 rx.await.ok();
421 }
422 }
423
424 fn extensions_dir(&self) -> PathBuf {
425 self.installed_dir.clone()
426 }
427
428 pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
429 &self.outstanding_operations
430 }
431
432 pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
433 &self.extension_index.extensions
434 }
435
436 pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
437 self.extension_index
438 .extensions
439 .values()
440 .filter_map(|extension| extension.dev.then_some(&extension.manifest))
441 }
442
443 pub fn extension_manifest_for_id(&self, extension_id: &str) -> Option<&Arc<ExtensionManifest>> {
444 self.extension_index
445 .extensions
446 .get(extension_id)
447 .map(|extension| &extension.manifest)
448 }
449
450 /// Returns the names of themes provided by extensions.
451 pub fn extension_themes<'a>(
452 &'a self,
453 extension_id: &'a str,
454 ) -> impl Iterator<Item = &'a Arc<str>> {
455 self.extension_index
456 .themes
457 .iter()
458 .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
459 }
460
461 /// Returns the path to the theme file within an extension, if there is an
462 /// extension that provides the theme.
463 pub fn path_to_extension_theme(&self, theme_name: &str) -> Option<PathBuf> {
464 let entry = self.extension_index.themes.get(theme_name)?;
465
466 Some(
467 self.extensions_dir()
468 .join(entry.extension.as_ref())
469 .join(&entry.path),
470 )
471 }
472
473 /// Returns the names of icon themes provided by extensions.
474 pub fn extension_icon_themes<'a>(
475 &'a self,
476 extension_id: &'a str,
477 ) -> impl Iterator<Item = &'a Arc<str>> {
478 self.extension_index
479 .icon_themes
480 .iter()
481 .filter_map(|(name, icon_theme)| {
482 icon_theme
483 .extension
484 .as_ref()
485 .eq(extension_id)
486 .then_some(name)
487 })
488 }
489
490 /// Returns the path to the icon theme file within an extension, if there is
491 /// an extension that provides the icon theme.
492 pub fn path_to_extension_icon_theme(
493 &self,
494 icon_theme_name: &str,
495 ) -> Option<(PathBuf, PathBuf)> {
496 let entry = self.extension_index.icon_themes.get(icon_theme_name)?;
497
498 let icon_theme_path = self
499 .extensions_dir()
500 .join(entry.extension.as_ref())
501 .join(&entry.path);
502 let icons_root_path = self.extensions_dir().join(entry.extension.as_ref());
503
504 Some((icon_theme_path, icons_root_path))
505 }
506
507 pub fn fetch_extensions(
508 &self,
509 search: Option<&str>,
510 provides_filter: Option<&BTreeSet<ExtensionProvides>>,
511 cx: &mut Context<Self>,
512 ) -> Task<Result<Vec<ExtensionMetadata>>> {
513 let version = CURRENT_SCHEMA_VERSION.to_string();
514 let mut query = vec![("max_schema_version", version.as_str())];
515 if let Some(search) = search {
516 query.push(("filter", search));
517 }
518
519 let provides_filter = provides_filter.map(|provides_filter| {
520 provides_filter
521 .iter()
522 .map(|provides| provides.to_string())
523 .collect::<Vec<_>>()
524 .join(",")
525 });
526 if let Some(provides_filter) = provides_filter.as_deref() {
527 query.push(("provides", provides_filter));
528 }
529
530 self.fetch_extensions_from_api("/extensions", &query, cx)
531 }
532
533 pub fn fetch_extensions_with_update_available(
534 &mut self,
535 cx: &mut Context<Self>,
536 ) -> Task<Result<Vec<ExtensionMetadata>>> {
537 let schema_versions = schema_version_range();
538 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
539 let extension_settings = ExtensionSettings::get_global(cx);
540 let extension_ids = self
541 .extension_index
542 .extensions
543 .iter()
544 .filter(|(id, entry)| !entry.dev && extension_settings.should_auto_update(id))
545 .map(|(id, _)| id.as_ref())
546 .collect::<Vec<_>>()
547 .join(",");
548 let task = self.fetch_extensions_from_api(
549 "/extensions/updates",
550 &[
551 ("min_schema_version", &schema_versions.start().to_string()),
552 ("max_schema_version", &schema_versions.end().to_string()),
553 (
554 "min_wasm_api_version",
555 &wasm_api_versions.start().to_string(),
556 ),
557 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
558 ("ids", &extension_ids),
559 ],
560 cx,
561 );
562 cx.spawn(async move |this, cx| {
563 let extensions = task.await?;
564 this.update(cx, |this, _cx| {
565 extensions
566 .into_iter()
567 .filter(|extension| {
568 this.extension_index.extensions.get(&extension.id).map_or(
569 true,
570 |installed_extension| {
571 installed_extension.manifest.version != extension.manifest.version
572 },
573 )
574 })
575 .collect()
576 })
577 })
578 }
579
580 pub fn fetch_extension_versions(
581 &self,
582 extension_id: &str,
583 cx: &mut Context<Self>,
584 ) -> Task<Result<Vec<ExtensionMetadata>>> {
585 self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
586 }
587
588 /// Installs any extensions that should be included with Zed by default.
589 ///
590 /// This can be used to make certain functionality provided by extensions
591 /// available out-of-the-box.
592 pub fn auto_install_extensions(&mut self, cx: &mut Context<Self>) {
593 let extension_settings = ExtensionSettings::get_global(cx);
594
595 let extensions_to_install = extension_settings
596 .auto_install_extensions
597 .keys()
598 .filter(|extension_id| extension_settings.should_auto_install(extension_id))
599 .filter(|extension_id| {
600 let is_already_installed = self
601 .extension_index
602 .extensions
603 .contains_key(extension_id.as_ref());
604 !is_already_installed
605 })
606 .cloned()
607 .collect::<Vec<_>>();
608
609 cx.spawn(async move |this, cx| {
610 for extension_id in extensions_to_install {
611 this.update(cx, |this, cx| {
612 this.install_latest_extension(extension_id.clone(), cx);
613 })
614 .ok();
615 }
616 })
617 .detach();
618 }
619
620 pub fn check_for_updates(&mut self, cx: &mut Context<Self>) {
621 let task = self.fetch_extensions_with_update_available(cx);
622 cx.spawn(async move |this, cx| Self::upgrade_extensions(this, task.await?, cx).await)
623 .detach();
624 }
625
626 async fn upgrade_extensions(
627 this: WeakEntity<Self>,
628 extensions: Vec<ExtensionMetadata>,
629 cx: &mut AsyncApp,
630 ) -> Result<()> {
631 for extension in extensions {
632 let task = this.update(cx, |this, cx| {
633 if let Some(installed_extension) =
634 this.extension_index.extensions.get(&extension.id)
635 {
636 let installed_version =
637 SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
638 let latest_version =
639 SemanticVersion::from_str(&extension.manifest.version).ok()?;
640
641 if installed_version >= latest_version {
642 return None;
643 }
644 }
645
646 Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
647 })?;
648
649 if let Some(task) = task {
650 task.await.log_err();
651 }
652 }
653 anyhow::Ok(())
654 }
655
656 fn fetch_extensions_from_api(
657 &self,
658 path: &str,
659 query: &[(&str, &str)],
660 cx: &mut Context<ExtensionStore>,
661 ) -> Task<Result<Vec<ExtensionMetadata>>> {
662 let url = self.http_client.build_zed_api_url(path, query);
663 let http_client = self.http_client.clone();
664 cx.spawn(async move |_, _| {
665 let mut response = http_client
666 .get(url?.as_ref(), AsyncBody::empty(), true)
667 .await?;
668
669 let mut body = Vec::new();
670 response
671 .body_mut()
672 .read_to_end(&mut body)
673 .await
674 .context("error reading extensions")?;
675
676 if response.status().is_client_error() {
677 let text = String::from_utf8_lossy(body.as_slice());
678 bail!(
679 "status error {}, response: {text:?}",
680 response.status().as_u16()
681 );
682 }
683
684 let response: GetExtensionsResponse = serde_json::from_slice(&body)?;
685 Ok(response.data)
686 })
687 }
688
689 pub fn install_extension(
690 &mut self,
691 extension_id: Arc<str>,
692 version: Arc<str>,
693 cx: &mut Context<Self>,
694 ) {
695 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
696 .detach_and_log_err(cx);
697 }
698
699 fn install_or_upgrade_extension_at_endpoint(
700 &mut self,
701 extension_id: Arc<str>,
702 url: Url,
703 operation: ExtensionOperation,
704 cx: &mut Context<Self>,
705 ) -> Task<Result<()>> {
706 let extension_dir = self.installed_dir.join(extension_id.as_ref());
707 let http_client = self.http_client.clone();
708 let fs = self.fs.clone();
709
710 match self.outstanding_operations.entry(extension_id.clone()) {
711 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
712 btree_map::Entry::Vacant(e) => e.insert(operation),
713 };
714 cx.notify();
715
716 cx.spawn(async move |this, cx| {
717 let _finish = cx.on_drop(&this, {
718 let extension_id = extension_id.clone();
719 move |this, cx| {
720 this.outstanding_operations.remove(extension_id.as_ref());
721 cx.notify();
722 }
723 });
724
725 let mut response = http_client
726 .get(url.as_ref(), Default::default(), true)
727 .await
728 .context("downloading extension")?;
729
730 fs.remove_dir(
731 &extension_dir,
732 RemoveOptions {
733 recursive: true,
734 ignore_if_not_exists: true,
735 },
736 )
737 .await?;
738
739 let content_length = response
740 .headers()
741 .get(http_client::http::header::CONTENT_LENGTH)
742 .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
743
744 let mut body = BufReader::new(response.body_mut());
745 let mut tar_gz_bytes = Vec::new();
746 body.read_to_end(&mut tar_gz_bytes).await?;
747
748 if let Some(content_length) = content_length {
749 let actual_len = tar_gz_bytes.len();
750 if content_length != actual_len {
751 bail!("downloaded extension size {actual_len} does not match content length {content_length}");
752 }
753 }
754 let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
755 let archive = Archive::new(decompressed_bytes);
756 archive.unpack(extension_dir).await?;
757 this.update( cx, |this, cx| {
758 this.reload(Some(extension_id.clone()), cx)
759 })?
760 .await;
761
762 if let ExtensionOperation::Install = operation {
763 this.update( cx, |this, cx| {
764 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
765 if let Some(events) = ExtensionEvents::try_global(cx) {
766 if let Some(manifest) = this.extension_manifest_for_id(&extension_id) {
767 events.update(cx, |this, cx| {
768 this.emit(
769 extension::Event::ExtensionInstalled(manifest.clone()),
770 cx,
771 )
772 });
773 }
774 }
775 })
776 .ok();
777 }
778
779 anyhow::Ok(())
780 })
781 }
782
783 pub fn install_latest_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
784 log::info!("installing extension {extension_id} latest version");
785
786 let schema_versions = schema_version_range();
787 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
788
789 let Some(url) = self
790 .http_client
791 .build_zed_api_url(
792 &format!("/extensions/{extension_id}/download"),
793 &[
794 ("min_schema_version", &schema_versions.start().to_string()),
795 ("max_schema_version", &schema_versions.end().to_string()),
796 (
797 "min_wasm_api_version",
798 &wasm_api_versions.start().to_string(),
799 ),
800 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
801 ],
802 )
803 .log_err()
804 else {
805 return;
806 };
807
808 self.install_or_upgrade_extension_at_endpoint(
809 extension_id,
810 url,
811 ExtensionOperation::Install,
812 cx,
813 )
814 .detach_and_log_err(cx);
815 }
816
817 pub fn upgrade_extension(
818 &mut self,
819 extension_id: Arc<str>,
820 version: Arc<str>,
821 cx: &mut Context<Self>,
822 ) -> Task<Result<()>> {
823 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
824 }
825
826 fn install_or_upgrade_extension(
827 &mut self,
828 extension_id: Arc<str>,
829 version: Arc<str>,
830 operation: ExtensionOperation,
831 cx: &mut Context<Self>,
832 ) -> Task<Result<()>> {
833 log::info!("installing extension {extension_id} {version}");
834 let Some(url) = self
835 .http_client
836 .build_zed_api_url(
837 &format!("/extensions/{extension_id}/{version}/download"),
838 &[],
839 )
840 .log_err()
841 else {
842 return Task::ready(Ok(()));
843 };
844
845 self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
846 }
847
848 pub fn uninstall_extension(
849 &mut self,
850 extension_id: Arc<str>,
851 cx: &mut Context<Self>,
852 ) -> Task<Result<()>> {
853 let extension_dir = self.installed_dir.join(extension_id.as_ref());
854 let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
855 let fs = self.fs.clone();
856
857 let extension_manifest = self.extension_manifest_for_id(&extension_id).cloned();
858
859 match self.outstanding_operations.entry(extension_id.clone()) {
860 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
861 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
862 };
863
864 cx.spawn(async move |extension_store, cx| {
865 let _finish = cx.on_drop(&extension_store, {
866 let extension_id = extension_id.clone();
867 move |this, cx| {
868 this.outstanding_operations.remove(extension_id.as_ref());
869 cx.notify();
870 }
871 });
872
873 fs.remove_dir(
874 &extension_dir,
875 RemoveOptions {
876 recursive: true,
877 ignore_if_not_exists: true,
878 },
879 )
880 .await
881 .with_context(|| format!("Removing extension dir {extension_dir:?}"))?;
882
883 extension_store
884 .update(cx, |extension_store, cx| extension_store.reload(None, cx))?
885 .await;
886
887 // There's a race between wasm extension fully stopping and the directory removal.
888 // On Windows, it's impossible to remove a directory that has a process running in it.
889 for i in 0..3 {
890 cx.background_executor()
891 .timer(Duration::from_millis(i * 100))
892 .await;
893 let removal_result = fs
894 .remove_dir(
895 &work_dir,
896 RemoveOptions {
897 recursive: true,
898 ignore_if_not_exists: true,
899 },
900 )
901 .await;
902 match removal_result {
903 Ok(()) => break,
904 Err(e) => {
905 if i == 2 {
906 log::error!("Failed to remove extension work dir {work_dir:?} : {e}");
907 }
908 }
909 }
910 }
911
912 extension_store.update(cx, |_, cx| {
913 cx.emit(Event::ExtensionUninstalled(extension_id.clone()));
914 if let Some(events) = ExtensionEvents::try_global(cx) {
915 if let Some(manifest) = extension_manifest {
916 events.update(cx, |this, cx| {
917 this.emit(extension::Event::ExtensionUninstalled(manifest.clone()), cx)
918 });
919 }
920 }
921 })?;
922
923 anyhow::Ok(())
924 })
925 }
926
927 pub fn install_dev_extension(
928 &mut self,
929 extension_source_path: PathBuf,
930 cx: &mut Context<Self>,
931 ) -> Task<Result<()>> {
932 let extensions_dir = self.extensions_dir();
933 let fs = self.fs.clone();
934 let builder = self.builder.clone();
935
936 cx.spawn(async move |this, cx| {
937 let mut extension_manifest =
938 ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
939 let extension_id = extension_manifest.id.clone();
940
941 if !this.update(cx, |this, cx| {
942 match this.outstanding_operations.entry(extension_id.clone()) {
943 btree_map::Entry::Occupied(_) => return false,
944 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
945 };
946 cx.notify();
947 true
948 })? {
949 return Ok(());
950 }
951
952 let _finish = cx.on_drop(&this, {
953 let extension_id = extension_id.clone();
954 move |this, cx| {
955 this.outstanding_operations.remove(extension_id.as_ref());
956 cx.notify();
957 }
958 });
959
960 cx.background_spawn({
961 let extension_source_path = extension_source_path.clone();
962 async move {
963 builder
964 .compile_extension(
965 &extension_source_path,
966 &mut extension_manifest,
967 CompileExtensionOptions { release: false },
968 )
969 .await
970 }
971 })
972 .await
973 .inspect_err(|error| {
974 util::log_err(error);
975 })?;
976
977 let output_path = &extensions_dir.join(extension_id.as_ref());
978 if let Some(metadata) = fs.metadata(output_path).await? {
979 if metadata.is_symlink {
980 fs.remove_file(
981 output_path,
982 RemoveOptions {
983 recursive: false,
984 ignore_if_not_exists: true,
985 },
986 )
987 .await?;
988 } else {
989 bail!("extension {extension_id} is already installed");
990 }
991 }
992
993 fs.create_symlink(output_path, extension_source_path)
994 .await?;
995
996 this.update(cx, |this, cx| this.reload(None, cx))?.await;
997 this.update(cx, |this, cx| {
998 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
999 if let Some(events) = ExtensionEvents::try_global(cx) {
1000 if let Some(manifest) = this.extension_manifest_for_id(&extension_id) {
1001 events.update(cx, |this, cx| {
1002 this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
1003 });
1004 }
1005 }
1006 })?;
1007
1008 Ok(())
1009 })
1010 }
1011
1012 pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
1013 let path = self.installed_dir.join(extension_id.as_ref());
1014 let builder = self.builder.clone();
1015 let fs = self.fs.clone();
1016
1017 match self.outstanding_operations.entry(extension_id.clone()) {
1018 btree_map::Entry::Occupied(_) => return,
1019 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
1020 };
1021
1022 cx.notify();
1023 let compile = cx.background_spawn(async move {
1024 let mut manifest = ExtensionManifest::load(fs, &path).await?;
1025 builder
1026 .compile_extension(
1027 &path,
1028 &mut manifest,
1029 CompileExtensionOptions { release: true },
1030 )
1031 .await
1032 });
1033
1034 cx.spawn(async move |this, cx| {
1035 let result = compile.await;
1036
1037 this.update(cx, |this, cx| {
1038 this.outstanding_operations.remove(&extension_id);
1039 cx.notify();
1040 })?;
1041
1042 if result.is_ok() {
1043 this.update(cx, |this, cx| this.reload(Some(extension_id), cx))?
1044 .await;
1045 }
1046
1047 result
1048 })
1049 .detach_and_log_err(cx)
1050 }
1051
1052 /// Updates the set of installed extensions.
1053 ///
1054 /// First, this unloads any themes, languages, or grammars that are
1055 /// no longer in the manifest, or whose files have changed on disk.
1056 /// Then it loads any themes, languages, or grammars that are newly
1057 /// added to the manifest, or whose files have changed on disk.
1058 fn extensions_updated(
1059 &mut self,
1060 mut new_index: ExtensionIndex,
1061 cx: &mut Context<Self>,
1062 ) -> Task<()> {
1063 let old_index = &self.extension_index;
1064
1065 // Determine which extensions need to be loaded and unloaded, based
1066 // on the changes to the manifest and the extensions that we know have been
1067 // modified.
1068 let mut extensions_to_unload = Vec::default();
1069 let mut extensions_to_load = Vec::default();
1070 {
1071 let mut old_keys = old_index.extensions.iter().peekable();
1072 let mut new_keys = new_index.extensions.iter().peekable();
1073 loop {
1074 match (old_keys.peek(), new_keys.peek()) {
1075 (None, None) => break,
1076 (None, Some(_)) => {
1077 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1078 }
1079 (Some(_), None) => {
1080 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1081 }
1082 (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1083 Ordering::Equal => {
1084 let (old_key, old_value) = old_keys.next().unwrap();
1085 let (new_key, new_value) = new_keys.next().unwrap();
1086 if old_value != new_value || self.modified_extensions.contains(old_key)
1087 {
1088 extensions_to_unload.push(old_key.clone());
1089 extensions_to_load.push(new_key.clone());
1090 }
1091 }
1092 Ordering::Less => {
1093 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1094 }
1095 Ordering::Greater => {
1096 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1097 }
1098 },
1099 }
1100 }
1101 self.modified_extensions.clear();
1102 }
1103
1104 if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1105 return Task::ready(());
1106 }
1107
1108 let reload_count = extensions_to_unload
1109 .iter()
1110 .filter(|id| extensions_to_load.contains(id))
1111 .count();
1112
1113 log::info!(
1114 "extensions updated. loading {}, reloading {}, unloading {}",
1115 extensions_to_load.len() - reload_count,
1116 reload_count,
1117 extensions_to_unload.len() - reload_count
1118 );
1119
1120 for extension_id in &extensions_to_load {
1121 if let Some(extension) = new_index.extensions.get(extension_id) {
1122 telemetry::event!(
1123 "Extension Loaded",
1124 extension_id,
1125 version = extension.manifest.version
1126 );
1127 }
1128 }
1129
1130 let themes_to_remove = old_index
1131 .themes
1132 .iter()
1133 .filter_map(|(name, entry)| {
1134 if extensions_to_unload.contains(&entry.extension) {
1135 Some(name.clone().into())
1136 } else {
1137 None
1138 }
1139 })
1140 .collect::<Vec<_>>();
1141 let icon_themes_to_remove = old_index
1142 .icon_themes
1143 .iter()
1144 .filter_map(|(name, entry)| {
1145 if extensions_to_unload.contains(&entry.extension) {
1146 Some(name.clone().into())
1147 } else {
1148 None
1149 }
1150 })
1151 .collect::<Vec<_>>();
1152 let languages_to_remove = old_index
1153 .languages
1154 .iter()
1155 .filter_map(|(name, entry)| {
1156 if extensions_to_unload.contains(&entry.extension) {
1157 Some(name.clone())
1158 } else {
1159 None
1160 }
1161 })
1162 .collect::<Vec<_>>();
1163 let mut grammars_to_remove = Vec::new();
1164 let mut server_removal_tasks = Vec::with_capacity(extensions_to_unload.len());
1165 for extension_id in &extensions_to_unload {
1166 let Some(extension) = old_index.extensions.get(extension_id) else {
1167 continue;
1168 };
1169 grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1170 for (language_server_name, config) in &extension.manifest.language_servers {
1171 for language in config.languages() {
1172 server_removal_tasks.push(self.proxy.remove_language_server(
1173 &language,
1174 language_server_name,
1175 cx,
1176 ));
1177 }
1178 }
1179
1180 for (server_id, _) in &extension.manifest.context_servers {
1181 self.proxy.unregister_context_server(server_id.clone(), cx);
1182 }
1183 for (adapter, _) in &extension.manifest.debug_adapters {
1184 self.proxy.unregister_debug_adapter(adapter.clone());
1185 }
1186 for (locator, _) in &extension.manifest.debug_locators {
1187 self.proxy.unregister_debug_locator(locator.clone());
1188 }
1189 for (command_name, _) in &extension.manifest.slash_commands {
1190 self.proxy.unregister_slash_command(command_name.clone());
1191 }
1192 for (provider_id, _) in &extension.manifest.indexed_docs_providers {
1193 self.proxy
1194 .unregister_indexed_docs_provider(provider_id.clone());
1195 }
1196 }
1197
1198 self.wasm_extensions
1199 .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1200 self.proxy.remove_user_themes(themes_to_remove);
1201 self.proxy.remove_icon_themes(icon_themes_to_remove);
1202 self.proxy
1203 .remove_languages(&languages_to_remove, &grammars_to_remove);
1204
1205 let mut grammars_to_add = Vec::new();
1206 let mut themes_to_add = Vec::new();
1207 let mut icon_themes_to_add = Vec::new();
1208 let mut snippets_to_add = Vec::new();
1209 for extension_id in &extensions_to_load {
1210 let Some(extension) = new_index.extensions.get(extension_id) else {
1211 continue;
1212 };
1213
1214 grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1215 let mut grammar_path = self.installed_dir.clone();
1216 grammar_path.extend([extension_id.as_ref(), "grammars"]);
1217 grammar_path.push(grammar_name.as_ref());
1218 grammar_path.set_extension("wasm");
1219 (grammar_name.clone(), grammar_path)
1220 }));
1221 themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1222 let mut path = self.installed_dir.clone();
1223 path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1224 path
1225 }));
1226 icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1227 |icon_theme_path| {
1228 let mut path = self.installed_dir.clone();
1229 path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1230
1231 let mut icons_root_path = self.installed_dir.clone();
1232 icons_root_path.extend([Path::new(extension_id.as_ref())]);
1233
1234 (path, icons_root_path)
1235 },
1236 ));
1237 snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1238 let mut path = self.installed_dir.clone();
1239 path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1240 path
1241 }));
1242 }
1243
1244 self.proxy.register_grammars(grammars_to_add);
1245 let languages_to_add = new_index
1246 .languages
1247 .iter_mut()
1248 .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1249 .collect::<Vec<_>>();
1250 for (language_name, language) in languages_to_add {
1251 let mut language_path = self.installed_dir.clone();
1252 language_path.extend([
1253 Path::new(language.extension.as_ref()),
1254 language.path.as_path(),
1255 ]);
1256 self.proxy.register_language(
1257 language_name.clone(),
1258 language.grammar.clone(),
1259 language.matcher.clone(),
1260 language.hidden,
1261 Arc::new(move || {
1262 let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1263 let config: LanguageConfig = ::toml::from_str(&config)?;
1264 let queries = load_plugin_queries(&language_path);
1265 let context_provider =
1266 std::fs::read_to_string(language_path.join("tasks.json"))
1267 .ok()
1268 .and_then(|contents| {
1269 let definitions =
1270 serde_json_lenient::from_str(&contents).log_err()?;
1271 Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1272 });
1273
1274 Ok(LoadedLanguage {
1275 config,
1276 queries,
1277 context_provider,
1278 toolchain_provider: None,
1279 })
1280 }),
1281 );
1282 }
1283
1284 let fs = self.fs.clone();
1285 let wasm_host = self.wasm_host.clone();
1286 let root_dir = self.installed_dir.clone();
1287 let proxy = self.proxy.clone();
1288 let extension_entries = extensions_to_load
1289 .iter()
1290 .filter_map(|name| new_index.extensions.get(name).cloned())
1291 .collect::<Vec<_>>();
1292 self.extension_index = new_index;
1293 cx.notify();
1294 cx.emit(Event::ExtensionsUpdated);
1295
1296 cx.spawn(async move |this, cx| {
1297 cx.background_spawn({
1298 let fs = fs.clone();
1299 async move {
1300 let _ = join_all(server_removal_tasks).await;
1301 for theme_path in themes_to_add {
1302 proxy
1303 .load_user_theme(theme_path, fs.clone())
1304 .await
1305 .log_err();
1306 }
1307
1308 for (icon_theme_path, icons_root_path) in icon_themes_to_add {
1309 proxy
1310 .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1311 .await
1312 .log_err();
1313 }
1314
1315 for snippets_path in &snippets_to_add {
1316 match fs
1317 .load(snippets_path)
1318 .await
1319 .with_context(|| format!("Loading snippets from {snippets_path:?}"))
1320 {
1321 Ok(snippets_contents) => {
1322 proxy
1323 .register_snippet(snippets_path, &snippets_contents)
1324 .log_err();
1325 }
1326 Err(e) => log::error!("Cannot load snippets: {e:#}"),
1327 }
1328 }
1329 }
1330 })
1331 .await;
1332
1333 let mut wasm_extensions = Vec::new();
1334 for extension in extension_entries {
1335 if extension.manifest.lib.kind.is_none() {
1336 continue;
1337 };
1338
1339 let extension_path = root_dir.join(extension.manifest.id.as_ref());
1340 let wasm_extension = WasmExtension::load(
1341 &extension_path,
1342 &extension.manifest,
1343 wasm_host.clone(),
1344 &cx,
1345 )
1346 .await
1347 .with_context(|| format!("Loading extension from {extension_path:?}"));
1348
1349 match wasm_extension {
1350 Ok(wasm_extension) => {
1351 wasm_extensions.push((extension.manifest.clone(), wasm_extension))
1352 }
1353 Err(e) => {
1354 log::error!("Failed to load extension: {e:#}");
1355 this.update(cx, |_, cx| {
1356 cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1357 })
1358 .ok();
1359 }
1360 }
1361 }
1362
1363 this.update(cx, |this, cx| {
1364 this.reload_complete_senders.clear();
1365
1366 for (manifest, wasm_extension) in &wasm_extensions {
1367 let extension = Arc::new(wasm_extension.clone());
1368
1369 for (language_server_id, language_server_config) in &manifest.language_servers {
1370 for language in language_server_config.languages() {
1371 this.proxy.register_language_server(
1372 extension.clone(),
1373 language_server_id.clone(),
1374 language.clone(),
1375 );
1376 }
1377 }
1378
1379 for (slash_command_name, slash_command) in &manifest.slash_commands {
1380 this.proxy.register_slash_command(
1381 extension.clone(),
1382 extension::SlashCommand {
1383 name: slash_command_name.to_string(),
1384 description: slash_command.description.to_string(),
1385 // We don't currently expose this as a configurable option, as it currently drives
1386 // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1387 // defined in extensions, as they are not able to be added to the menu.
1388 tooltip_text: String::new(),
1389 requires_argument: slash_command.requires_argument,
1390 },
1391 );
1392 }
1393
1394 for (id, _context_server_entry) in &manifest.context_servers {
1395 this.proxy
1396 .register_context_server(extension.clone(), id.clone(), cx);
1397 }
1398
1399 for (provider_id, _provider) in &manifest.indexed_docs_providers {
1400 this.proxy
1401 .register_indexed_docs_provider(extension.clone(), provider_id.clone());
1402 }
1403
1404 for (debug_adapter, meta) in &manifest.debug_adapters {
1405 let mut path = root_dir.clone();
1406 path.push(Path::new(manifest.id.as_ref()));
1407 if let Some(schema_path) = &meta.schema_path {
1408 path.push(schema_path);
1409 } else {
1410 path.push("debug_adapter_schemas");
1411 path.push(Path::new(debug_adapter.as_ref()).with_extension("json"));
1412 }
1413
1414 this.proxy.register_debug_adapter(
1415 extension.clone(),
1416 debug_adapter.clone(),
1417 &path,
1418 );
1419 }
1420
1421 for debug_adapter in manifest.debug_locators.keys() {
1422 this.proxy
1423 .register_debug_locator(extension.clone(), debug_adapter.clone());
1424 }
1425 }
1426
1427 this.wasm_extensions.extend(wasm_extensions);
1428 this.proxy.set_extensions_loaded();
1429 this.proxy.reload_current_theme(cx);
1430 this.proxy.reload_current_icon_theme(cx);
1431
1432 if let Some(events) = ExtensionEvents::try_global(cx) {
1433 events.update(cx, |this, cx| {
1434 this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1435 });
1436 }
1437 })
1438 .ok();
1439 })
1440 }
1441
1442 fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1443 let fs = self.fs.clone();
1444 let work_dir = self.wasm_host.work_dir.clone();
1445 let extensions_dir = self.installed_dir.clone();
1446 let index_path = self.index_path.clone();
1447 let proxy = self.proxy.clone();
1448 cx.background_spawn(async move {
1449 let start_time = Instant::now();
1450 let mut index = ExtensionIndex::default();
1451
1452 fs.create_dir(&work_dir).await.log_err();
1453 fs.create_dir(&extensions_dir).await.log_err();
1454
1455 let extension_paths = fs.read_dir(&extensions_dir).await;
1456 if let Ok(mut extension_paths) = extension_paths {
1457 while let Some(extension_dir) = extension_paths.next().await {
1458 let Ok(extension_dir) = extension_dir else {
1459 continue;
1460 };
1461
1462 if extension_dir
1463 .file_name()
1464 .map_or(false, |file_name| file_name == ".DS_Store")
1465 {
1466 continue;
1467 }
1468
1469 Self::add_extension_to_index(
1470 fs.clone(),
1471 extension_dir,
1472 &mut index,
1473 proxy.clone(),
1474 )
1475 .await
1476 .log_err();
1477 }
1478 }
1479
1480 if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1481 fs.save(&index_path, &index_json.as_str().into(), Default::default())
1482 .await
1483 .context("failed to save extension index")
1484 .log_err();
1485 }
1486
1487 log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1488 index
1489 })
1490 }
1491
1492 async fn add_extension_to_index(
1493 fs: Arc<dyn Fs>,
1494 extension_dir: PathBuf,
1495 index: &mut ExtensionIndex,
1496 proxy: Arc<ExtensionHostProxy>,
1497 ) -> Result<()> {
1498 let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1499 let extension_id = extension_manifest.id.clone();
1500
1501 // TODO: distinguish dev extensions more explicitly, by the absence
1502 // of a checksum file that we'll create when downloading normal extensions.
1503 let is_dev = fs
1504 .metadata(&extension_dir)
1505 .await?
1506 .context("directory does not exist")?
1507 .is_symlink;
1508
1509 if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1510 while let Some(language_path) = language_paths.next().await {
1511 let language_path = language_path?;
1512 let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1513 continue;
1514 };
1515 let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1516 continue;
1517 };
1518 if !fs_metadata.is_dir {
1519 continue;
1520 }
1521 let config = fs.load(&language_path.join("config.toml")).await?;
1522 let config = ::toml::from_str::<LanguageConfig>(&config)?;
1523
1524 let relative_path = relative_path.to_path_buf();
1525 if !extension_manifest.languages.contains(&relative_path) {
1526 extension_manifest.languages.push(relative_path.clone());
1527 }
1528
1529 index.languages.insert(
1530 config.name.clone(),
1531 ExtensionIndexLanguageEntry {
1532 extension: extension_id.clone(),
1533 path: relative_path,
1534 matcher: config.matcher,
1535 hidden: config.hidden,
1536 grammar: config.grammar,
1537 },
1538 );
1539 }
1540 }
1541
1542 if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1543 while let Some(theme_path) = theme_paths.next().await {
1544 let theme_path = theme_path?;
1545 let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1546 continue;
1547 };
1548
1549 let Some(theme_families) = proxy
1550 .list_theme_names(theme_path.clone(), fs.clone())
1551 .await
1552 .log_err()
1553 else {
1554 continue;
1555 };
1556
1557 let relative_path = relative_path.to_path_buf();
1558 if !extension_manifest.themes.contains(&relative_path) {
1559 extension_manifest.themes.push(relative_path.clone());
1560 }
1561
1562 for theme_name in theme_families {
1563 index.themes.insert(
1564 theme_name.into(),
1565 ExtensionIndexThemeEntry {
1566 extension: extension_id.clone(),
1567 path: relative_path.clone(),
1568 },
1569 );
1570 }
1571 }
1572 }
1573
1574 if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1575 while let Some(icon_theme_path) = icon_theme_paths.next().await {
1576 let icon_theme_path = icon_theme_path?;
1577 let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1578 continue;
1579 };
1580
1581 let Some(icon_theme_families) = proxy
1582 .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1583 .await
1584 .log_err()
1585 else {
1586 continue;
1587 };
1588
1589 let relative_path = relative_path.to_path_buf();
1590 if !extension_manifest.icon_themes.contains(&relative_path) {
1591 extension_manifest.icon_themes.push(relative_path.clone());
1592 }
1593
1594 for icon_theme_name in icon_theme_families {
1595 index.icon_themes.insert(
1596 icon_theme_name.into(),
1597 ExtensionIndexIconThemeEntry {
1598 extension: extension_id.clone(),
1599 path: relative_path.clone(),
1600 },
1601 );
1602 }
1603 }
1604 }
1605
1606 let extension_wasm_path = extension_dir.join("extension.wasm");
1607 if fs.is_file(&extension_wasm_path).await {
1608 extension_manifest
1609 .lib
1610 .kind
1611 .get_or_insert(ExtensionLibraryKind::Rust);
1612 }
1613
1614 index.extensions.insert(
1615 extension_id.clone(),
1616 ExtensionIndexEntry {
1617 dev: is_dev,
1618 manifest: Arc::new(extension_manifest),
1619 },
1620 );
1621
1622 Ok(())
1623 }
1624
1625 fn prepare_remote_extension(
1626 &mut self,
1627 extension_id: Arc<str>,
1628 is_dev: bool,
1629 tmp_dir: PathBuf,
1630 cx: &mut Context<Self>,
1631 ) -> Task<Result<()>> {
1632 let src_dir = self.extensions_dir().join(extension_id.as_ref());
1633 let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1634 else {
1635 return Task::ready(Err(anyhow!("extension no longer installed")));
1636 };
1637 let fs = self.fs.clone();
1638 cx.background_spawn(async move {
1639 const EXTENSION_TOML: &str = "extension.toml";
1640 const EXTENSION_WASM: &str = "extension.wasm";
1641 const CONFIG_TOML: &str = "config.toml";
1642
1643 if is_dev {
1644 let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1645 fs.save(
1646 &tmp_dir.join(EXTENSION_TOML),
1647 &Rope::from(manifest_toml),
1648 language::LineEnding::Unix,
1649 )
1650 .await?;
1651 } else {
1652 fs.copy_file(
1653 &src_dir.join(EXTENSION_TOML),
1654 &tmp_dir.join(EXTENSION_TOML),
1655 fs::CopyOptions::default(),
1656 )
1657 .await?
1658 }
1659
1660 if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1661 fs.copy_file(
1662 &src_dir.join(EXTENSION_WASM),
1663 &tmp_dir.join(EXTENSION_WASM),
1664 fs::CopyOptions::default(),
1665 )
1666 .await?
1667 }
1668
1669 for language_path in loaded_extension.manifest.languages.iter() {
1670 if fs
1671 .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1672 .await
1673 {
1674 fs.create_dir(&tmp_dir.join(language_path)).await?;
1675 fs.copy_file(
1676 &src_dir.join(language_path).join(CONFIG_TOML),
1677 &tmp_dir.join(language_path).join(CONFIG_TOML),
1678 fs::CopyOptions::default(),
1679 )
1680 .await?
1681 }
1682 }
1683
1684 for (adapter_name, meta) in loaded_extension.manifest.debug_adapters.iter() {
1685 let schema_path = &extension::build_debug_adapter_schema_path(adapter_name, meta);
1686
1687 if fs.is_file(&src_dir.join(schema_path)).await {
1688 match schema_path.parent() {
1689 Some(parent) => fs.create_dir(&tmp_dir.join(parent)).await?,
1690 None => {}
1691 }
1692 fs.copy_file(
1693 &src_dir.join(schema_path),
1694 &tmp_dir.join(schema_path),
1695 fs::CopyOptions::default(),
1696 )
1697 .await?
1698 }
1699 }
1700
1701 Ok(())
1702 })
1703 }
1704
1705 async fn sync_extensions_over_ssh(
1706 this: &WeakEntity<Self>,
1707 client: WeakEntity<SshRemoteClient>,
1708 cx: &mut AsyncApp,
1709 ) -> Result<()> {
1710 let extensions = this.update(cx, |this, _cx| {
1711 this.extension_index
1712 .extensions
1713 .iter()
1714 .filter_map(|(id, entry)| {
1715 if !entry.manifest.allow_remote_load() {
1716 return None;
1717 }
1718 Some(proto::Extension {
1719 id: id.to_string(),
1720 version: entry.manifest.version.to_string(),
1721 dev: entry.dev,
1722 })
1723 })
1724 .collect()
1725 })?;
1726
1727 let response = client
1728 .update(cx, |client, _cx| {
1729 client
1730 .proto_client()
1731 .request(proto::SyncExtensions { extensions })
1732 })?
1733 .await?;
1734 let path_style = client.read_with(cx, |client, _| client.path_style())?;
1735
1736 for missing_extension in response.missing_extensions.into_iter() {
1737 let tmp_dir = tempfile::tempdir()?;
1738 this.update(cx, |this, cx| {
1739 this.prepare_remote_extension(
1740 missing_extension.id.clone().into(),
1741 missing_extension.dev,
1742 tmp_dir.path().to_owned(),
1743 cx,
1744 )
1745 })?
1746 .await?;
1747 let dest_dir = RemotePathBuf::new(
1748 PathBuf::from(&response.tmp_dir).join(missing_extension.clone().id),
1749 path_style,
1750 );
1751 log::info!("Uploading extension {}", missing_extension.clone().id);
1752
1753 client
1754 .update(cx, |client, cx| {
1755 client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
1756 })?
1757 .await?;
1758
1759 log::info!(
1760 "Finished uploading extension {}",
1761 missing_extension.clone().id
1762 );
1763
1764 client
1765 .update(cx, |client, _cx| {
1766 client.proto_client().request(proto::InstallExtension {
1767 tmp_dir: dest_dir.to_proto(),
1768 extension: Some(missing_extension),
1769 })
1770 })?
1771 .await?;
1772 }
1773
1774 anyhow::Ok(())
1775 }
1776
1777 pub async fn update_ssh_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
1778 let clients = this.update(cx, |this, _cx| {
1779 this.ssh_clients.retain(|_k, v| v.upgrade().is_some());
1780 this.ssh_clients.values().cloned().collect::<Vec<_>>()
1781 })?;
1782
1783 for client in clients {
1784 Self::sync_extensions_over_ssh(&this, client, cx)
1785 .await
1786 .log_err();
1787 }
1788
1789 anyhow::Ok(())
1790 }
1791
1792 pub fn register_ssh_client(&mut self, client: Entity<SshRemoteClient>, cx: &mut Context<Self>) {
1793 let connection_options = client.read(cx).connection_options();
1794 let ssh_url = connection_options.ssh_url();
1795
1796 if let Some(existing_client) = self.ssh_clients.get(&ssh_url) {
1797 if existing_client.upgrade().is_some() {
1798 return;
1799 }
1800 }
1801
1802 self.ssh_clients.insert(ssh_url, client.downgrade());
1803 self.ssh_registered_tx.unbounded_send(()).ok();
1804 }
1805}
1806
1807fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1808 let mut result = LanguageQueries::default();
1809 if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1810 for entry in entries {
1811 let Some(entry) = entry.log_err() else {
1812 continue;
1813 };
1814 let path = entry.path();
1815 if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1816 if !remainder.ends_with(".scm") {
1817 continue;
1818 }
1819 for (name, query) in QUERY_FILENAME_PREFIXES {
1820 if remainder.starts_with(name) {
1821 if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1822 match query(&mut result) {
1823 None => *query(&mut result) = Some(contents.into()),
1824 Some(r) => r.to_mut().push_str(contents.as_ref()),
1825 }
1826 }
1827 break;
1828 }
1829 }
1830 }
1831 }
1832 }
1833 result
1834}