Add auto-update system for extensions (#9890)

* [x] auto update extensions on startup
* [ ] add a manual way of updating all?
* [x] add a way to opt out of auto-updates for a particular extension

We don't believe that there should be any background polling for
extension auto-updates, because it could be disruptive to the user.

Release Notes:

- Added an auto-update system for extensions.

---------

Co-authored-by: Marshall <marshall@zed.dev>
Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
This commit is contained in:
Max Brunsfeld 2024-03-28 12:41:22 -07:00 committed by GitHub
parent 3a36b10e3a
commit 95fd426eff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 559 additions and 79 deletions

View file

@ -0,0 +1,216 @@
use std::str::FromStr;
use std::sync::Arc;
use client::ExtensionMetadata;
use extension::{ExtensionSettings, ExtensionStore};
use fs::Fs;
use fuzzy::{match_strings, StringMatch, StringMatchCandidate};
use gpui::{
prelude::*, AppContext, DismissEvent, EventEmitter, FocusableView, Task, View, WeakView,
};
use picker::{Picker, PickerDelegate};
use settings::update_settings_file;
use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
use util::{ResultExt, SemanticVersion};
use workspace::ModalView;
pub struct ExtensionVersionSelector {
picker: View<Picker<ExtensionVersionSelectorDelegate>>,
}
impl ModalView for ExtensionVersionSelector {}
impl EventEmitter<DismissEvent> for ExtensionVersionSelector {}
impl FocusableView for ExtensionVersionSelector {
fn focus_handle(&self, cx: &AppContext) -> gpui::FocusHandle {
self.picker.focus_handle(cx)
}
}
impl Render for ExtensionVersionSelector {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
v_flex().w(rems(34.)).child(self.picker.clone())
}
}
impl ExtensionVersionSelector {
pub fn new(delegate: ExtensionVersionSelectorDelegate, cx: &mut ViewContext<Self>) -> Self {
let picker = cx.new_view(|cx| Picker::uniform_list(delegate, cx));
Self { picker }
}
}
pub struct ExtensionVersionSelectorDelegate {
fs: Arc<dyn Fs>,
view: WeakView<ExtensionVersionSelector>,
extension_versions: Vec<ExtensionMetadata>,
selected_index: usize,
matches: Vec<StringMatch>,
}
impl ExtensionVersionSelectorDelegate {
pub fn new(
fs: Arc<dyn Fs>,
weak_view: WeakView<ExtensionVersionSelector>,
mut extension_versions: Vec<ExtensionMetadata>,
) -> Self {
extension_versions.sort_unstable_by(|a, b| {
let a_version = SemanticVersion::from_str(&a.manifest.version);
let b_version = SemanticVersion::from_str(&b.manifest.version);
match (a_version, b_version) {
(Ok(a_version), Ok(b_version)) => b_version.cmp(&a_version),
_ => b.published_at.cmp(&a.published_at),
}
});
let matches = extension_versions
.iter()
.map(|extension| StringMatch {
candidate_id: 0,
score: 0.0,
positions: Default::default(),
string: format!("v{}", extension.manifest.version),
})
.collect();
Self {
fs,
view: weak_view,
extension_versions,
selected_index: 0,
matches,
}
}
}
impl PickerDelegate for ExtensionVersionSelectorDelegate {
type ListItem = ui::ListItem;
fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
"Select extension version...".into()
}
fn match_count(&self) -> usize {
self.matches.len()
}
fn selected_index(&self) -> usize {
self.selected_index
}
fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
self.selected_index = ix;
}
fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
let background_executor = cx.background_executor().clone();
let candidates = self
.extension_versions
.iter()
.enumerate()
.map(|(id, extension)| {
let text = format!("v{}", extension.manifest.version);
StringMatchCandidate {
id,
char_bag: text.as_str().into(),
string: text,
}
})
.collect::<Vec<_>>();
cx.spawn(move |this, mut cx| async move {
let matches = if query.is_empty() {
candidates
.into_iter()
.enumerate()
.map(|(index, candidate)| StringMatch {
candidate_id: index,
string: candidate.string,
positions: Vec::new(),
score: 0.0,
})
.collect()
} else {
match_strings(
&candidates,
&query,
false,
100,
&Default::default(),
background_executor,
)
.await
};
this.update(&mut cx, |this, _cx| {
this.delegate.matches = matches;
this.delegate.selected_index = this
.delegate
.selected_index
.min(this.delegate.matches.len().saturating_sub(1));
})
.log_err();
})
}
fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
if self.matches.is_empty() {
self.dismissed(cx);
return;
}
let candidate_id = self.matches[self.selected_index].candidate_id;
let extension_version = &self.extension_versions[candidate_id];
let extension_store = ExtensionStore::global(cx);
extension_store.update(cx, |store, cx| {
let extension_id = extension_version.id.clone();
let version = extension_version.manifest.version.clone();
update_settings_file::<ExtensionSettings>(self.fs.clone(), cx, {
let extension_id = extension_id.clone();
move |settings| {
settings.auto_update_extensions.insert(extension_id, false);
}
});
store.install_extension(extension_id, version, cx);
});
}
fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
self.view
.update(cx, |_, cx| cx.emit(DismissEvent))
.log_err();
}
fn render_match(
&self,
ix: usize,
selected: bool,
_cx: &mut ViewContext<Picker<Self>>,
) -> Option<Self::ListItem> {
let version_match = &self.matches[ix];
let extension_version = &self.extension_versions[version_match.candidate_id];
Some(
ListItem::new(ix)
.inset(true)
.spacing(ListItemSpacing::Sparse)
.selected(selected)
.child(HighlightedLabel::new(
version_match.string.clone(),
version_match.positions.clone(),
))
.end_slot(Label::new(
extension_version
.published_at
.format("%Y-%m-%d")
.to_string(),
)),
)
}
}

View file

@ -1,11 +1,15 @@
mod components;
mod extension_suggest;
mod extension_version_selector;
use crate::components::ExtensionCard;
use crate::extension_version_selector::{
ExtensionVersionSelector, ExtensionVersionSelectorDelegate,
};
use client::telemetry::Telemetry;
use client::ExtensionMetadata;
use editor::{Editor, EditorElement, EditorStyle};
use extension::{ExtensionManifest, ExtensionStatus, ExtensionStore};
use extension::{ExtensionManifest, ExtensionOperation, ExtensionStore};
use fuzzy::{match_strings, StringMatchCandidate};
use gpui::{
actions, canvas, uniform_list, AnyElement, AppContext, EventEmitter, FocusableView, FontStyle,
@ -17,7 +21,7 @@ use std::ops::DerefMut;
use std::time::Duration;
use std::{ops::Range, sync::Arc};
use theme::ThemeSettings;
use ui::{prelude::*, ToggleButton, Tooltip};
use ui::{popover_menu, prelude::*, ContextMenu, ToggleButton, Tooltip};
use util::ResultExt as _;
use workspace::{
item::{Item, ItemEvent},
@ -77,6 +81,15 @@ pub fn init(cx: &mut AppContext) {
.detach();
}
#[derive(Clone)]
pub enum ExtensionStatus {
NotInstalled,
Installing,
Upgrading,
Installed(Arc<str>),
Removing,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
enum ExtensionFilter {
All,
@ -94,6 +107,7 @@ impl ExtensionFilter {
}
pub struct ExtensionsPage {
workspace: WeakView<Workspace>,
list: UniformListScrollHandle,
telemetry: Arc<Telemetry>,
is_fetching_extensions: bool,
@ -131,6 +145,7 @@ impl ExtensionsPage {
cx.subscribe(&query_editor, Self::on_query_change).detach();
let mut this = Self {
workspace: workspace.weak_handle(),
list: UniformListScrollHandle::new(),
telemetry: workspace.client().telemetry().clone(),
is_fetching_extensions: false,
@ -174,9 +189,21 @@ impl ExtensionsPage {
}
}
fn filter_extension_entries(&mut self, cx: &mut ViewContext<Self>) {
fn extension_status(extension_id: &str, cx: &mut ViewContext<Self>) -> ExtensionStatus {
let extension_store = ExtensionStore::global(cx).read(cx);
match extension_store.outstanding_operations().get(extension_id) {
Some(ExtensionOperation::Install) => ExtensionStatus::Installing,
Some(ExtensionOperation::Remove) => ExtensionStatus::Removing,
Some(ExtensionOperation::Upgrade) => ExtensionStatus::Upgrading,
None => match extension_store.installed_extensions().get(extension_id) {
Some(extension) => ExtensionStatus::Installed(extension.manifest.version.clone()),
None => ExtensionStatus::NotInstalled,
},
}
}
fn filter_extension_entries(&mut self, cx: &mut ViewContext<Self>) {
self.filtered_remote_extension_indices.clear();
self.filtered_remote_extension_indices.extend(
self.remote_extension_entries
@ -185,11 +212,11 @@ impl ExtensionsPage {
.filter(|(_, extension)| match self.filter {
ExtensionFilter::All => true,
ExtensionFilter::Installed => {
let status = extension_store.extension_status(&extension.id);
let status = Self::extension_status(&extension.id, cx);
matches!(status, ExtensionStatus::Installed(_))
}
ExtensionFilter::NotInstalled => {
let status = extension_store.extension_status(&extension.id);
let status = Self::extension_status(&extension.id, cx);
matches!(status, ExtensionStatus::NotInstalled)
}
@ -285,9 +312,7 @@ impl ExtensionsPage {
extension: &ExtensionManifest,
cx: &mut ViewContext<Self>,
) -> ExtensionCard {
let status = ExtensionStore::global(cx)
.read(cx)
.extension_status(&extension.id);
let status = Self::extension_status(&extension.id, cx);
let repository_url = extension.repository.clone();
@ -389,10 +414,10 @@ impl ExtensionsPage {
extension: &ExtensionMetadata,
cx: &mut ViewContext<Self>,
) -> ExtensionCard {
let status = ExtensionStore::global(cx)
.read(cx)
.extension_status(&extension.id);
let this = cx.view().clone();
let status = Self::extension_status(&extension.id, cx);
let extension_id = extension.id.clone();
let (install_or_uninstall_button, upgrade_button) =
self.buttons_for_entry(extension, &status, cx);
let repository_url = extension.manifest.repository.clone();
@ -454,24 +479,99 @@ impl ExtensionsPage {
)
}))
.child(
IconButton::new(
SharedString::from(format!("repository-{}", extension.id)),
IconName::Github,
)
.icon_color(Color::Accent)
.icon_size(IconSize::Small)
.style(ButtonStyle::Filled)
.on_click(cx.listener({
let repository_url = repository_url.clone();
move |_, _, cx| {
cx.open_url(&repository_url);
}
}))
.tooltip(move |cx| Tooltip::text(repository_url.clone(), cx)),
h_flex()
.gap_2()
.child(
IconButton::new(
SharedString::from(format!("repository-{}", extension.id)),
IconName::Github,
)
.icon_color(Color::Accent)
.icon_size(IconSize::Small)
.style(ButtonStyle::Filled)
.on_click(cx.listener({
let repository_url = repository_url.clone();
move |_, _, cx| {
cx.open_url(&repository_url);
}
}))
.tooltip(move |cx| Tooltip::text(repository_url.clone(), cx)),
)
.child(
popover_menu(SharedString::from(format!("more-{}", extension.id)))
.trigger(
IconButton::new(
SharedString::from(format!("more-{}", extension.id)),
IconName::Ellipsis,
)
.icon_color(Color::Accent)
.icon_size(IconSize::Small)
.style(ButtonStyle::Filled),
)
.menu(move |cx| {
Some(Self::render_remote_extension_context_menu(
&this,
extension_id.clone(),
cx,
))
}),
),
),
)
}
fn render_remote_extension_context_menu(
this: &View<Self>,
extension_id: Arc<str>,
cx: &mut WindowContext,
) -> View<ContextMenu> {
let context_menu = ContextMenu::build(cx, |context_menu, cx| {
context_menu.entry(
"Install Another Version...",
None,
cx.handler_for(&this, move |this, cx| {
this.show_extension_version_list(extension_id.clone(), cx)
}),
)
});
context_menu
}
fn show_extension_version_list(&mut self, extension_id: Arc<str>, cx: &mut ViewContext<Self>) {
let Some(workspace) = self.workspace.upgrade() else {
return;
};
cx.spawn(move |this, mut cx| async move {
let extension_versions_task = this.update(&mut cx, |_, cx| {
let extension_store = ExtensionStore::global(cx);
extension_store.update(cx, |store, cx| {
store.fetch_extension_versions(&extension_id, cx)
})
})?;
let extension_versions = extension_versions_task.await?;
workspace.update(&mut cx, |workspace, cx| {
let fs = workspace.project().read(cx).fs().clone();
workspace.toggle_modal(cx, |cx| {
let delegate = ExtensionVersionSelectorDelegate::new(
fs,
cx.view().downgrade(),
extension_versions,
);
ExtensionVersionSelector::new(delegate, cx)
});
})?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
}
fn buttons_for_entry(
&self,
extension: &ExtensionMetadata,
@ -531,11 +631,13 @@ impl ExtensionsPage {
"extensions: install extension".to_string(),
);
ExtensionStore::global(cx).update(cx, |store, cx| {
store.upgrade_extension(
extension_id.clone(),
version.clone(),
cx,
)
store
.upgrade_extension(
extension_id.clone(),
version.clone(),
cx,
)
.detach_and_log_err(cx)
});
}
}),