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