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