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