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