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