Visual Studio Code, rebuilt in Rust
Rust
//! A fake gallery for the tests of gallery installs, here and in the workbench.
use serde_json::{Value, json};
/// Open VSX's answer to `/vscode/redhat/vscode-yaml/latest`: a pre-release 2.1.2026112008 and the release 2.0.0.
pub const VSCODE_YAML: &str = include_str!("vscode-yaml-latest.json");
/// vscode-yaml republished as `id` with these `extensionDependencies` and `extensionPack` in every version.
pub fn gallery_entry(id: &str, dependencies: &[&str], pack: &[&str]) -> Value {
let mut raw: Value = serde_json::from_str(VSCODE_YAML).unwrap();
let (publisher, name) = id.split_once('.').unwrap();
raw["publisher"]["publisherName"] = publisher.into();
raw["extensionName"] = name.into();
raw["extensionId"] = format!("uuid-{id}").into();
for version in raw["versions"].as_array_mut().unwrap() {
let properties = version["properties"].as_array_mut().unwrap();
properties.retain(|property| !property["key"].as_str().unwrap().starts_with("Microsoft.VisualStudio.Code.Extension"));
properties.push(json!({ "key": "Microsoft.VisualStudio.Code.ExtensionDependencies", "value": dependencies.join(",") }));
properties.push(json!({ "key": "Microsoft.VisualStudio.Code.ExtensionPack", "value": pack.join(",") }));
}
raw
}
/// A gallery on localhost that answers each query with the `entries` whose id the query names, by name or by uuid.
pub fn serve_gallery(entries: Vec<(String, Value)>) -> String {
use std::io::{BufRead, BufReader, Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let mut reader = BufReader::new(stream);
let mut length = 0;
loop {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
if line.trim().is_empty() {
break;
}
if let Some((name, value)) = line.split_once(':')
&& name.eq_ignore_ascii_case("content-length")
{
length = value.trim().parse().unwrap();
}
}
let mut body = vec![0; length];
reader.read_exact(&mut body).unwrap();
let query = String::from_utf8_lossy(&body).to_lowercase();
let named: Vec<&Value> = entries.iter().filter(|(id, _)| query.contains(id.as_str())).map(|(_, entry)| entry).collect();
let body = json!({ "results": [{ "extensions": named, "resultMetadata": [{ "metadataType": "ResultCount", "metadataItems": [{ "name": "TotalCount", "count": named.len() }] }] }] }).to_string();
let reply = format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
reader.into_inner().write_all(reply.as_bytes()).unwrap();
}
});
url
}