Visual Studio Code, rebuilt in Rust
Rust
feat(exthost): fetch a gallery extension's versions for every platform
rokartur31e61bc05ec4
diff --git a/native/crates/exthost/src/gallery.rs b/native/crates/exthost/src/gallery.rsindex 98d06116553..6b8d030ba8a 100644--- a/native/crates/exthost/src/gallery.rs+++ b/native/crates/exthost/src/gallery.rs@@ -34,9 +34,9 @@ const BLOCKED_MESSAGE: &str = "This extension has been blocked by the Extensionpub const CURRENT_TARGET_PLATFORM: &str = if cfg!(target_arch = "aarch64") { "darwin-arm64" } else { "darwin-x64" };#[cfg(target_os = "linux")]pub const CURRENT_TARGET_PLATFORM: &str = if cfg!(target_arch = "aarch64") { "linux-arm64" } else { "linux-x64" };-const UNDEFINED: &str = "undefined";-const UNIVERSAL: &str = "universal";-const UNKNOWN: &str = "unknown";+pub const UNDEFINED: &str = "undefined";+pub const UNIVERSAL: &str = "universal";+pub const UNKNOWN: &str = "unknown";const WEB: &str = "web";#[derive(Debug, Clone, PartialEq, Default)]@@ -99,9 +99,15 @@ impl GalleryExtension {}/// `TargetPlatformToString`.-fn target_platform_label(platform: &str) -> &str {+pub fn target_platform_label(platform: &str) -> &str {match platform {+ "win32-x64" => "Windows 64 bit",+ "win32-arm64" => "Windows ARM","linux-x64" => "Linux 64 bit",+ "linux-armhf" => "Linux ARM",+ "alpine-x64" => "Alpine Linux 64 bit",+ "alpine-arm64" => "Alpine ARM 64",+ "web" => "Web","linux-arm64" => "Linux ARM 64","darwin-x64" => "Mac","darwin-arm64" => "Mac Silicon",@@ -238,6 +244,7 @@ struct ExtensionsCriteria<'a> {versions: &'a [ExtensionInfo],}+#[derive(Clone)]pub struct Gallery {pub service_url: String,pub product_version: String,@@ -291,6 +298,11 @@ impl Gallery {/// `getExtensions`: the latest-version resource for ids with a uuid and no version, the query for the rest/// and for what the resource could not answer.pub fn get_extensions(&self, infos: &[ExtensionInfo], compatible: bool) -> anyhow::Result<Vec<GalleryExtension>> {+ self.get_extensions_for_platform(infos, compatible, CURRENT_TARGET_PLATFORM)+ }++ /// `getExtensions` with `options.targetPlatform`.+ pub fn get_extensions_for_platform(&self, infos: &[ExtensionInfo], compatible: bool, target_platform: &'static str) -> anyhow::Result<Vec<GalleryExtension>> {let mut result = Vec::new();let mut to_query = Vec::new();for info in infos {@@ -301,7 +313,7 @@ impl Gallery {to_query.push(info.clone());continue;}- match self.latest_gallery_extension(info, compatible) {+ match self.latest_gallery_extension(info, compatible, target_platform) {Ok(Some(extension)) => result.push(extension),Ok(None) => to_query.push(info.clone()),Err(error) => {@@ -311,13 +323,13 @@ impl Gallery {}}if !to_query.is_empty() {- result.extend(self.get_extensions_using_query_api(&to_query, compatible)?);+ result.extend(self.get_extensions_using_query_api(&to_query, compatible, target_platform)?);}let uuids: Vec<&str> = result.iter().map(|extension| extension.uuid.as_str()).collect();let by_name: Vec<ExtensionInfo> =infos.iter().filter(|info| info.uuid.as_deref().is_some_and(|uuid| !uuids.contains(&uuid))).map(|info| ExtensionInfo { uuid: None, ..info.clone() }).collect();if !by_name.is_empty() {- result.extend(self.get_extensions_using_query_api(&by_name, compatible)?);+ result.extend(self.get_extensions_using_query_api(&by_name, compatible, target_platform)?);}Ok(result)}@@ -340,9 +352,19 @@ impl Gallery {Ok(self.query_gallery_extensions(query, &criteria)?.0.into_iter().next())}- /// `getAllCompatibleVersions` (`getVersions`): the versions this product can install, newest first, each number- /// once with the platforms it is built for.+ /// `getAllVersions`: every version that is not blocked, whatever its platform or engine.+ pub fn get_all_versions(&self, id: &str) -> anyhow::Result<Vec<GalleryVersion>> {+ self.get_versions(id, None, None)+ }++ /// `getAllCompatibleVersions`: the versions this product can install.pub fn get_all_compatible_versions(&self, id: &str, uuid: Option<&str>, include_pre_release: bool) -> anyhow::Result<Vec<GalleryVersion>> {+ self.get_versions(id, uuid, Some(include_pre_release))+ }++ /// `getVersions`: newest first, each number once with the platforms it is built for; `only_compatible` holds+ /// whether pre-releases count.+ fn get_versions(&self, id: &str, uuid: Option<&str>, only_compatible: Option<bool>) -> anyhow::Result<Vec<GalleryVersion>> {let mut query = match uuid {Some(uuid) => Query::new(1).with_filter(filter::EXTENSION_ID, &[uuid.to_owned()]),None => Query::new(1).with_filter(filter::EXTENSION_NAME, &[id.to_owned()]),@@ -350,6 +372,11 @@ impl Gallery {query.flags = flag::INCLUDE_VERSIONS | flag::INCLUDE_CATEGORY_AND_TAGS | flag::INCLUDE_FILES | flag::INCLUDE_VERSION_PROPERTIES;let Some(raw) = self.query_raw_gallery_extensions(&query)?.0.into_iter().next() else { return Ok(Vec::new()) };let all_target_platforms = all_target_platforms(&raw);+ let Some(include_pre_release) = only_compatible else {+ let mut versions: Vec<Value> = raw["versions"].as_array().into_iter().flatten().filter(|version| !is_blocked(version)).cloned().collect();+ sort_extension_versions(&mut versions, CURRENT_TARGET_PLATFORM);+ return Ok(group_versions(&versions));+ };if is_not_web_extension_in_web_target_platform(&all_target_platforms, CURRENT_TARGET_PLATFORM) {return Ok(Vec::new());}@@ -364,21 +391,7 @@ impl Gallery {}}sort_extension_versions(&mut versions, CURRENT_TARGET_PLATFORM);- let mut result: Vec<GalleryVersion> = Vec::new();- for version in &versions {- let number = version["version"].as_str().unwrap_or_default();- let target_platform = target_platform_of(version);- match result.iter_mut().find(|existing| existing.version == number) {- Some(existing) => existing.target_platforms.push(target_platform),- None => result.push(GalleryVersion {- version: number.to_owned(),- date: version["lastUpdated"].as_str().unwrap_or_default().to_owned(),- is_pre_release_version: is_pre_release_version(version),- target_platforms: vec![target_platform],- }),- }- }- Ok(result)+ Ok(group_versions(&versions))}/// `extensionsWorkbenchService._install(id)` then `checkAndGetCompatibleVersion`: the gallery version to download.@@ -493,7 +506,7 @@ impl Gallery {self.get_compatible_extension(extension, pre_release)}- fn get_extensions_using_query_api(&self, infos: &[ExtensionInfo], compatible: bool) -> anyhow::Result<Vec<GalleryExtension>> {+ fn get_extensions_using_query_api(&self, infos: &[ExtensionInfo], compatible: bool, target_platform: &'static str) -> anyhow::Result<Vec<GalleryExtension>> {let ids: Vec<String> = infos.iter().filter_map(|info| info.uuid.clone()).collect();let names: Vec<String> = infos.iter().filter(|info| info.uuid.is_none()).map(|info| info.id.clone()).collect();let mut query = Query::new(infos.len());@@ -505,7 +518,7 @@ impl Gallery {}let versions: Vec<ExtensionInfo> = infos.iter().filter(|info| info.version.is_some()).cloned().collect();let pre_release = |id: &str| infos.iter().any(|info| info.id.eq_ignore_ascii_case(id) && info.pre_release);- let criteria = ExtensionsCriteria { target_platform: CURRENT_TARGET_PLATFORM, compatible, include_pre_release: &pre_release, versions: &versions };+ let criteria = ExtensionsCriteria { target_platform, compatible, include_pre_release: &pre_release, versions: &versions };Ok(self.query_gallery_extensions(query, &criteria)?.0)}@@ -595,7 +608,7 @@ impl Gallery {}/// `getLatestGalleryExtension`: `None` when the resource has no fitting version and the query should answer.- fn latest_gallery_extension(&self, info: &ExtensionInfo, compatible: bool) -> anyhow::Result<Option<GalleryExtension>> {+ fn latest_gallery_extension(&self, info: &ExtensionInfo, compatible: bool, target_platform: &'static str) -> anyhow::Result<Option<GalleryExtension>> {let (publisher, name) = info.id.split_once('.').context("invalid extension id")?;let url = format!("{}/vscode/{publisher}/{name}/latest", self.service_url);let response = self.get(&url, "application/json;api-version=7.2-preview")?;@@ -611,9 +624,9 @@ impl Gallery {return Ok(None);}let all_target_platforms = all_target_platforms(&raw);- let mut latest = filter_latest_extension_versions_for_target_platform(versions, CURRENT_TARGET_PLATFORM, &all_target_platforms);+ let mut latest = filter_latest_extension_versions_for_target_platform(versions, target_platform, &all_target_platforms);let id = raw_id(&raw);- let criteria = |version| VersionCriteria { target_platform: CURRENT_TARGET_PLATFORM, compatible, version };+ let criteria = |version| VersionCriteria { target_platform, compatible, version };let requested = if info.pre_release { VersionKind::Prerelease } else { VersionKind::Release };let found = self.valid_version(&id, &mut latest, &criteria(requested), &all_target_platforms);let chosen = if !info.pre_release {@@ -776,6 +789,11 @@ impl Gallery {Ok(verify(vsix, &archive, &key))}+ /// `download(extension, location, InstallOperation.None)`: the VSIX as the gallery serves it, unchecked.+ pub fn download_to(&self, extension: &GalleryExtension, location: &Path) -> anyhow::Result<()> {+ Ok(std::fs::write(location, self.get_asset(&extension.download)?.body)?)+ }+/// `downloadVSIX`: two attempts, each checked to be a zip with `extension/package.json`.fn download_vsix(&self, extension: &GalleryExtension, operation: Operation) -> anyhow::Result<Vec<u8>> {let parameter = match operation {@@ -944,6 +962,25 @@ fn is_target_platform_compatible(extension_target_platform: &str, all_target_pla}}+/// The `IGalleryExtensionVersion` list of `getVersions`: each number once, with every platform it is built for.+fn group_versions(versions: &[Value]) -> Vec<GalleryVersion> {+ let mut result: Vec<GalleryVersion> = Vec::new();+ for version in versions {+ let number = version["version"].as_str().unwrap_or_default();+ let target_platform = target_platform_of(version);+ match result.iter_mut().find(|existing| existing.version == number) {+ Some(existing) => existing.target_platforms.push(target_platform),+ None => result.push(GalleryVersion {+ version: number.to_owned(),+ date: version["lastUpdated"].as_str().unwrap_or_default().to_owned(),+ is_pre_release_version: is_pre_release_version(version),+ target_platforms: vec![target_platform],+ }),+ }+ }+ result+}+/// `sortExtensionVersions`: versions of the same number keep their order, the preferred platform's build first.fn sort_extension_versions(versions: &mut [Value], preferred_target_platform: &str) {for index in 1..versions.len() {diff --git a/native/crates/exthost/src/gallery/tests.rs b/native/crates/exthost/src/gallery/tests.rsindex 12a2b327821..59aa6223e21 100644--- a/native/crates/exthost/src/gallery/tests.rs+++ b/native/crates/exthost/src/gallery/tests.rs@@ -210,3 +210,14 @@ fn all_compatible_versions_follow_the_kind_and_the_engine() {let unknown = Gallery { service_url: url, product_version: "1.147.0".into() };assert_eq!(unknown.get_all_compatible_versions("a.other", None, true).unwrap(), []);}++#[test]+fn all_versions_ignore_the_engine_but_not_the_block() {+ let mut blocked = gallery_entry("b.yaml", &[], &[]);+ blocked["versions"][0]["flags"] = "blocked".into();+ let url = serve_gallery(vec![("a.yaml".to_owned(), gallery_entry("a.yaml", &[], &[])), ("b.yaml".to_owned(), blocked)]);+ let gallery = Gallery { service_url: url, product_version: "1.90.0".into() };+ let versions = |id| gallery.get_all_versions(id).unwrap().into_iter().map(|version| (version.version, version.target_platforms)).collect::<Vec<_>>();+ assert_eq!(versions("a.yaml"), [("2.1.2026112008".to_owned(), vec!["universal"]), ("2.0.0".to_owned(), vec!["universal"])]);+ assert_eq!(versions("b.yaml"), [("2.0.0".to_owned(), vec!["universal"])]);+}