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 for (adapter, _) in extension.manifest.debug_adapters.iter() {
1139 self.proxy.unregister_debug_adapter(adapter.clone());
1140 }
1141 for (locator, _) in extension.manifest.debug_locators.iter() {
1142 self.proxy.unregister_debug_locator(locator.clone());
1143 }
1144 }
1145
1146 self.wasm_extensions
1147 .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1148 self.proxy.remove_user_themes(themes_to_remove);
1149 self.proxy.remove_icon_themes(icon_themes_to_remove);
1150 self.proxy
1151 .remove_languages(&languages_to_remove, &grammars_to_remove);
1152
1153 let mut grammars_to_add = Vec::new();
1154 let mut themes_to_add = Vec::new();
1155 let mut icon_themes_to_add = Vec::new();
1156 let mut snippets_to_add = Vec::new();
1157 for extension_id in &extensions_to_load {
1158 let Some(extension) = new_index.extensions.get(extension_id) else {
1159 continue;
1160 };
1161
1162 grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1163 let mut grammar_path = self.installed_dir.clone();
1164 grammar_path.extend([extension_id.as_ref(), "grammars"]);
1165 grammar_path.push(grammar_name.as_ref());
1166 grammar_path.set_extension("wasm");
1167 (grammar_name.clone(), grammar_path)
1168 }));
1169 themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1170 let mut path = self.installed_dir.clone();
1171 path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1172 path
1173 }));
1174 icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1175 |icon_theme_path| {
1176 let mut path = self.installed_dir.clone();
1177 path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1178
1179 let mut icons_root_path = self.installed_dir.clone();
1180 icons_root_path.extend([Path::new(extension_id.as_ref())]);
1181
1182 (path, icons_root_path)
1183 },
1184 ));
1185 snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1186 let mut path = self.installed_dir.clone();
1187 path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1188 path
1189 }));
1190 }
1191
1192 self.proxy.register_grammars(grammars_to_add);
1193 let languages_to_add = new_index
1194 .languages
1195 .iter_mut()
1196 .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1197 .collect::<Vec<_>>();
1198 for (language_name, language) in languages_to_add {
1199 let mut language_path = self.installed_dir.clone();
1200 language_path.extend([
1201 Path::new(language.extension.as_ref()),
1202 language.path.as_path(),
1203 ]);
1204 self.proxy.register_language(
1205 language_name.clone(),
1206 language.grammar.clone(),
1207 language.matcher.clone(),
1208 language.hidden,
1209 Arc::new(move || {
1210 let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1211 let config: LanguageConfig = ::toml::from_str(&config)?;
1212 let queries = load_plugin_queries(&language_path);
1213 let context_provider =
1214 std::fs::read_to_string(language_path.join("tasks.json"))
1215 .ok()
1216 .and_then(|contents| {
1217 let definitions =
1218 serde_json_lenient::from_str(&contents).log_err()?;
1219 Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1220 });
1221
1222 Ok(LoadedLanguage {
1223 config,
1224 queries,
1225 context_provider,
1226 toolchain_provider: None,
1227 })
1228 }),
1229 );
1230 }
1231
1232 let fs = self.fs.clone();
1233 let wasm_host = self.wasm_host.clone();
1234 let root_dir = self.installed_dir.clone();
1235 let proxy = self.proxy.clone();
1236 let extension_entries = extensions_to_load
1237 .iter()
1238 .filter_map(|name| new_index.extensions.get(name).cloned())
1239 .collect::<Vec<_>>();
1240 self.extension_index = new_index;
1241 cx.notify();
1242 cx.emit(Event::ExtensionsUpdated);
1243
1244 cx.spawn(async move |this, cx| {
1245 cx.background_spawn({
1246 let fs = fs.clone();
1247 async move {
1248 for theme_path in themes_to_add.into_iter() {
1249 proxy
1250 .load_user_theme(theme_path, fs.clone())
1251 .await
1252 .log_err();
1253 }
1254
1255 for (icon_theme_path, icons_root_path) in icon_themes_to_add.into_iter() {
1256 proxy
1257 .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1258 .await
1259 .log_err();
1260 }
1261
1262 for snippets_path in &snippets_to_add {
1263 if let Some(snippets_contents) = fs.load(snippets_path).await.log_err() {
1264 proxy
1265 .register_snippet(snippets_path, &snippets_contents)
1266 .log_err();
1267 }
1268 }
1269 }
1270 })
1271 .await;
1272
1273 let mut wasm_extensions = Vec::new();
1274 for extension in extension_entries {
1275 if extension.manifest.lib.kind.is_none() {
1276 continue;
1277 };
1278
1279 let extension_path = root_dir.join(extension.manifest.id.as_ref());
1280 let wasm_extension = WasmExtension::load(
1281 extension_path,
1282 &extension.manifest,
1283 wasm_host.clone(),
1284 &cx,
1285 )
1286 .await;
1287
1288 if let Some(wasm_extension) = wasm_extension.log_err() {
1289 wasm_extensions.push((extension.manifest.clone(), wasm_extension));
1290 } else {
1291 this.update(cx, |_, cx| {
1292 cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1293 })
1294 .ok();
1295 }
1296 }
1297
1298 this.update(cx, |this, cx| {
1299 this.reload_complete_senders.clear();
1300
1301 for (manifest, wasm_extension) in &wasm_extensions {
1302 let extension = Arc::new(wasm_extension.clone());
1303
1304 for (language_server_id, language_server_config) in &manifest.language_servers {
1305 for language in language_server_config.languages() {
1306 this.proxy.register_language_server(
1307 extension.clone(),
1308 language_server_id.clone(),
1309 language.clone(),
1310 );
1311 }
1312 }
1313
1314 for (slash_command_name, slash_command) in &manifest.slash_commands {
1315 this.proxy.register_slash_command(
1316 extension.clone(),
1317 extension::SlashCommand {
1318 name: slash_command_name.to_string(),
1319 description: slash_command.description.to_string(),
1320 // We don't currently expose this as a configurable option, as it currently drives
1321 // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1322 // defined in extensions, as they are not able to be added to the menu.
1323 tooltip_text: String::new(),
1324 requires_argument: slash_command.requires_argument,
1325 },
1326 );
1327 }
1328
1329 for (id, _context_server_entry) in &manifest.context_servers {
1330 this.proxy
1331 .register_context_server(extension.clone(), id.clone(), cx);
1332 }
1333
1334 for (provider_id, _provider) in &manifest.indexed_docs_providers {
1335 this.proxy
1336 .register_indexed_docs_provider(extension.clone(), provider_id.clone());
1337 }
1338
1339 for (debug_adapter, meta) in &manifest.debug_adapters {
1340 let mut path = root_dir.clone();
1341 path.push(Path::new(manifest.id.as_ref()));
1342 if let Some(schema_path) = &meta.schema_path {
1343 path.push(schema_path);
1344 } else {
1345 path.push("debug_adapter_schemas");
1346 path.push(Path::new(debug_adapter.as_ref()).with_extension("json"));
1347 }
1348
1349 this.proxy.register_debug_adapter(
1350 extension.clone(),
1351 debug_adapter.clone(),
1352 &path,
1353 );
1354 }
1355
1356 for debug_adapter in manifest.debug_locators.keys() {
1357 this.proxy
1358 .register_debug_locator(extension.clone(), debug_adapter.clone());
1359 }
1360 }
1361
1362 this.wasm_extensions.extend(wasm_extensions);
1363 this.proxy.set_extensions_loaded();
1364 this.proxy.reload_current_theme(cx);
1365 this.proxy.reload_current_icon_theme(cx);
1366
1367 if let Some(events) = ExtensionEvents::try_global(cx) {
1368 events.update(cx, |this, cx| {
1369 this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1370 });
1371 }
1372 })
1373 .ok();
1374 })
1375 }
1376
1377 fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1378 let fs = self.fs.clone();
1379 let work_dir = self.wasm_host.work_dir.clone();
1380 let extensions_dir = self.installed_dir.clone();
1381 let index_path = self.index_path.clone();
1382 let proxy = self.proxy.clone();
1383 cx.background_spawn(async move {
1384 let start_time = Instant::now();
1385 let mut index = ExtensionIndex::default();
1386
1387 fs.create_dir(&work_dir).await.log_err();
1388 fs.create_dir(&extensions_dir).await.log_err();
1389
1390 let extension_paths = fs.read_dir(&extensions_dir).await;
1391 if let Ok(mut extension_paths) = extension_paths {
1392 while let Some(extension_dir) = extension_paths.next().await {
1393 let Ok(extension_dir) = extension_dir else {
1394 continue;
1395 };
1396
1397 if extension_dir
1398 .file_name()
1399 .map_or(false, |file_name| file_name == ".DS_Store")
1400 {
1401 continue;
1402 }
1403
1404 Self::add_extension_to_index(
1405 fs.clone(),
1406 extension_dir,
1407 &mut index,
1408 proxy.clone(),
1409 )
1410 .await
1411 .log_err();
1412 }
1413 }
1414
1415 if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1416 fs.save(&index_path, &index_json.as_str().into(), Default::default())
1417 .await
1418 .context("failed to save extension index")
1419 .log_err();
1420 }
1421
1422 log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1423 index
1424 })
1425 }
1426
1427 async fn add_extension_to_index(
1428 fs: Arc<dyn Fs>,
1429 extension_dir: PathBuf,
1430 index: &mut ExtensionIndex,
1431 proxy: Arc<ExtensionHostProxy>,
1432 ) -> Result<()> {
1433 let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1434 let extension_id = extension_manifest.id.clone();
1435
1436 // TODO: distinguish dev extensions more explicitly, by the absence
1437 // of a checksum file that we'll create when downloading normal extensions.
1438 let is_dev = fs
1439 .metadata(&extension_dir)
1440 .await?
1441 .context("directory does not exist")?
1442 .is_symlink;
1443
1444 if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1445 while let Some(language_path) = language_paths.next().await {
1446 let language_path = language_path?;
1447 let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1448 continue;
1449 };
1450 let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1451 continue;
1452 };
1453 if !fs_metadata.is_dir {
1454 continue;
1455 }
1456 let config = fs.load(&language_path.join("config.toml")).await?;
1457 let config = ::toml::from_str::<LanguageConfig>(&config)?;
1458
1459 let relative_path = relative_path.to_path_buf();
1460 if !extension_manifest.languages.contains(&relative_path) {
1461 extension_manifest.languages.push(relative_path.clone());
1462 }
1463
1464 index.languages.insert(
1465 config.name.clone(),
1466 ExtensionIndexLanguageEntry {
1467 extension: extension_id.clone(),
1468 path: relative_path,
1469 matcher: config.matcher,
1470 hidden: config.hidden,
1471 grammar: config.grammar,
1472 },
1473 );
1474 }
1475 }
1476
1477 if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1478 while let Some(theme_path) = theme_paths.next().await {
1479 let theme_path = theme_path?;
1480 let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1481 continue;
1482 };
1483
1484 let Some(theme_families) = proxy
1485 .list_theme_names(theme_path.clone(), fs.clone())
1486 .await
1487 .log_err()
1488 else {
1489 continue;
1490 };
1491
1492 let relative_path = relative_path.to_path_buf();
1493 if !extension_manifest.themes.contains(&relative_path) {
1494 extension_manifest.themes.push(relative_path.clone());
1495 }
1496
1497 for theme_name in theme_families {
1498 index.themes.insert(
1499 theme_name.into(),
1500 ExtensionIndexThemeEntry {
1501 extension: extension_id.clone(),
1502 path: relative_path.clone(),
1503 },
1504 );
1505 }
1506 }
1507 }
1508
1509 if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1510 while let Some(icon_theme_path) = icon_theme_paths.next().await {
1511 let icon_theme_path = icon_theme_path?;
1512 let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1513 continue;
1514 };
1515
1516 let Some(icon_theme_families) = proxy
1517 .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1518 .await
1519 .log_err()
1520 else {
1521 continue;
1522 };
1523
1524 let relative_path = relative_path.to_path_buf();
1525 if !extension_manifest.icon_themes.contains(&relative_path) {
1526 extension_manifest.icon_themes.push(relative_path.clone());
1527 }
1528
1529 for icon_theme_name in icon_theme_families {
1530 index.icon_themes.insert(
1531 icon_theme_name.into(),
1532 ExtensionIndexIconThemeEntry {
1533 extension: extension_id.clone(),
1534 path: relative_path.clone(),
1535 },
1536 );
1537 }
1538 }
1539 }
1540
1541 let extension_wasm_path = extension_dir.join("extension.wasm");
1542 if fs.is_file(&extension_wasm_path).await {
1543 extension_manifest
1544 .lib
1545 .kind
1546 .get_or_insert(ExtensionLibraryKind::Rust);
1547 }
1548
1549 index.extensions.insert(
1550 extension_id.clone(),
1551 ExtensionIndexEntry {
1552 dev: is_dev,
1553 manifest: Arc::new(extension_manifest),
1554 },
1555 );
1556
1557 Ok(())
1558 }
1559
1560 fn prepare_remote_extension(
1561 &mut self,
1562 extension_id: Arc<str>,
1563 is_dev: bool,
1564 tmp_dir: PathBuf,
1565 cx: &mut Context<Self>,
1566 ) -> Task<Result<()>> {
1567 let src_dir = self.extensions_dir().join(extension_id.as_ref());
1568 let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1569 else {
1570 return Task::ready(Err(anyhow!("extension no longer installed")));
1571 };
1572 let fs = self.fs.clone();
1573 cx.background_spawn(async move {
1574 const EXTENSION_TOML: &str = "extension.toml";
1575 const EXTENSION_WASM: &str = "extension.wasm";
1576 const CONFIG_TOML: &str = "config.toml";
1577
1578 if is_dev {
1579 let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1580 fs.save(
1581 &tmp_dir.join(EXTENSION_TOML),
1582 &Rope::from(manifest_toml),
1583 language::LineEnding::Unix,
1584 )
1585 .await?;
1586 } else {
1587 fs.copy_file(
1588 &src_dir.join(EXTENSION_TOML),
1589 &tmp_dir.join(EXTENSION_TOML),
1590 fs::CopyOptions::default(),
1591 )
1592 .await?
1593 }
1594
1595 if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1596 fs.copy_file(
1597 &src_dir.join(EXTENSION_WASM),
1598 &tmp_dir.join(EXTENSION_WASM),
1599 fs::CopyOptions::default(),
1600 )
1601 .await?
1602 }
1603
1604 for language_path in loaded_extension.manifest.languages.iter() {
1605 if fs
1606 .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1607 .await
1608 {
1609 fs.create_dir(&tmp_dir.join(language_path)).await?;
1610 fs.copy_file(
1611 &src_dir.join(language_path).join(CONFIG_TOML),
1612 &tmp_dir.join(language_path).join(CONFIG_TOML),
1613 fs::CopyOptions::default(),
1614 )
1615 .await?
1616 }
1617 }
1618
1619 Ok(())
1620 })
1621 }
1622
1623 async fn sync_extensions_over_ssh(
1624 this: &WeakEntity<Self>,
1625 client: WeakEntity<SshRemoteClient>,
1626 cx: &mut AsyncApp,
1627 ) -> Result<()> {
1628 let extensions = this.update(cx, |this, _cx| {
1629 this.extension_index
1630 .extensions
1631 .iter()
1632 .filter_map(|(id, entry)| {
1633 if entry.manifest.language_servers.is_empty() {
1634 return None;
1635 }
1636 Some(proto::Extension {
1637 id: id.to_string(),
1638 version: entry.manifest.version.to_string(),
1639 dev: entry.dev,
1640 })
1641 })
1642 .collect()
1643 })?;
1644
1645 let response = client
1646 .update(cx, |client, _cx| {
1647 client
1648 .proto_client()
1649 .request(proto::SyncExtensions { extensions })
1650 })?
1651 .await?;
1652
1653 for missing_extension in response.missing_extensions.into_iter() {
1654 let tmp_dir = tempfile::tempdir()?;
1655 this.update(cx, |this, cx| {
1656 this.prepare_remote_extension(
1657 missing_extension.id.clone().into(),
1658 missing_extension.dev,
1659 tmp_dir.path().to_owned(),
1660 cx,
1661 )
1662 })?
1663 .await?;
1664 let dest_dir = PathBuf::from(&response.tmp_dir).join(missing_extension.clone().id);
1665 log::info!("Uploading extension {}", missing_extension.clone().id);
1666
1667 client
1668 .update(cx, |client, cx| {
1669 client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
1670 })?
1671 .await?;
1672
1673 log::info!(
1674 "Finished uploading extension {}",
1675 missing_extension.clone().id
1676 );
1677
1678 client
1679 .update(cx, |client, _cx| {
1680 client.proto_client().request(proto::InstallExtension {
1681 tmp_dir: dest_dir.to_string_lossy().to_string(),
1682 extension: Some(missing_extension),
1683 })
1684 })?
1685 .await?;
1686 }
1687
1688 anyhow::Ok(())
1689 }
1690
1691 pub async fn update_ssh_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
1692 let clients = this.update(cx, |this, _cx| {
1693 this.ssh_clients.retain(|_k, v| v.upgrade().is_some());
1694 this.ssh_clients.values().cloned().collect::<Vec<_>>()
1695 })?;
1696
1697 for client in clients {
1698 Self::sync_extensions_over_ssh(&this, client, cx)
1699 .await
1700 .log_err();
1701 }
1702
1703 anyhow::Ok(())
1704 }
1705
1706 pub fn register_ssh_client(&mut self, client: Entity<SshRemoteClient>, cx: &mut Context<Self>) {
1707 let connection_options = client.read(cx).connection_options();
1708 let ssh_url = connection_options.ssh_url();
1709
1710 if let Some(existing_client) = self.ssh_clients.get(&ssh_url) {
1711 if existing_client.upgrade().is_some() {
1712 return;
1713 }
1714 }
1715
1716 self.ssh_clients.insert(ssh_url, client.downgrade());
1717 self.ssh_registered_tx.unbounded_send(()).ok();
1718 }
1719}
1720
1721fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1722 let mut result = LanguageQueries::default();
1723 if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1724 for entry in entries {
1725 let Some(entry) = entry.log_err() else {
1726 continue;
1727 };
1728 let path = entry.path();
1729 if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1730 if !remainder.ends_with(".scm") {
1731 continue;
1732 }
1733 for (name, query) in QUERY_FILENAME_PREFIXES {
1734 if remainder.starts_with(name) {
1735 if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1736 match query(&mut result) {
1737 None => *query(&mut result) = Some(contents.into()),
1738 Some(r) => r.to_mut().push_str(contents.as_ref()),
1739 }
1740 }
1741 break;
1742 }
1743 }
1744 }
1745 }
1746 }
1747 result
1748}