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