use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
use serde::{Deserialize, Serialize};
pub const HOST_API_VERSION: &str = "0.15";
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ApiRange {
pub min: String,
pub max: String,
}
impl Default for ApiRange {
fn default() -> Self {
Self::line(HOST_API_VERSION)
}
}
impl ApiRange {
pub fn new(min: impl Into<String>, max: impl Into<String>) -> Self {
Self {
min: min.into(),
max: max.into(),
}
}
pub fn line(version: &str) -> Self {
let mut parts = version.split('.');
let major = parts.next().unwrap_or("0");
let minor = parts.next().unwrap_or("0").parse::<u64>().unwrap_or(0);
Self {
min: format!("{major}.{minor}"),
max: format!("{major}.{}", minor + 1),
}
}
pub fn allows(&self, version: &str) -> bool {
[version, &self.min, &self.max].iter().all(|text| well_formed(text))
&& compare(version, &self.min) >= 0
&& compare(version, &self.max) < 0
}
}
fn well_formed(version: &str) -> bool {
let mut parts = version.split('.');
parts.clone().count() >= 2 && parts.all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
}
fn compare(left: &str, right: &str) -> i32 {
let mut left = left.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
let mut right = right.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
for _ in 0..2 {
let a = left.next().unwrap_or(0);
let b = right.next().unwrap_or(0);
if a != b {
return if a < b { -1 } else { 1 };
}
}
0
}
fn entry_is_safe(entry: &str) -> bool {
if entry.is_empty() || entry.contains('\\') || entry.contains(':') {
return false;
}
Path::new(entry)
.components()
.all(|component| matches!(component, Component::Normal(_)))
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Capability {
Commands,
Panels,
Viewers,
Themes,
Keybindings,
Settings,
ChartLayers,
FilesystemRead {
prefix: String,
},
Data,
Selection,
}
impl Capability {
pub fn parse(text: &str) -> Result<Self, ManifestError> {
let value = match text {
"commands" => Self::Commands,
"panels" => Self::Panels,
"viewers" => Self::Viewers,
"themes" => Self::Themes,
"keybindings" => Self::Keybindings,
"settings" => Self::Settings,
"chart-layers" => Self::ChartLayers,
"data" => Self::Data,
"selection" => Self::Selection,
other => {
if let Some(prefix) = other.strip_prefix("filesystem:read:") {
if prefix.is_empty() {
return Err(ManifestError::Capability(other.to_owned()));
}
Self::FilesystemRead {
prefix: prefix.to_owned(),
}
} else {
return Err(ManifestError::Capability(other.to_owned()));
}
}
};
Ok(value)
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExtensionManifest {
pub id: String,
pub version: String,
pub name: String,
pub api: ApiRange,
pub entry: String,
pub checksum: Option<String>,
pub signature: Option<String>,
#[serde(default)]
pub capabilities: BTreeSet<String>,
pub author: Option<String>,
pub description: Option<String>,
}
impl ExtensionManifest {
#[cfg(feature = "threads")]
pub fn load(directory: impl Into<PathBuf>) -> Result<(Self, PathBuf), ManifestError> {
let directory = directory.into();
let path = directory.join("extension.json");
let text = std::fs::read_to_string(&path).map_err(|error| ManifestError::Io(error.to_string()))?;
let manifest: Self = serde_json::from_str(&text).map_err(|error| ManifestError::Json(error.to_string()))?;
manifest.validate()?;
Ok((manifest, directory))
}
pub fn validate(&self) -> Result<(), ManifestError> {
if self.id.is_empty()
|| self.id.len() > 128
|| self.id.starts_with('.')
|| !self
.id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
{
return Err(ManifestError::Id(self.id.clone()));
}
if self.version.split('.').count() < 2 || self.version.split('.').any(|part| part.parse::<u64>().is_err()) {
return Err(ManifestError::Version(self.version.clone()));
}
if !entry_is_safe(&self.entry) {
return Err(ManifestError::Entry(self.entry.clone()));
}
if !self.api.allows(crate::extensions::HOST_API_VERSION) {
return Err(ManifestError::Api {
min: self.api.min.clone(),
max: self.api.max.clone(),
});
}
for capability in &self.capabilities {
Capability::parse(capability)?;
}
Ok(())
}
pub fn parsed_capabilities(&self) -> Result<BTreeSet<Capability>, ManifestError> {
self.capabilities.iter().map(|text| Capability::parse(text)).collect()
}
pub fn module_path(&self, directory: &std::path::Path) -> PathBuf {
directory.join(&self.entry)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ManifestError {
#[error("{0}")]
Io(String),
#[error("{0}")]
Json(String),
#[error("invalid extension id `{0}`")]
Id(String),
#[error("invalid extension version `{0}`")]
Version(String),
#[error("invalid entry `{0}`")]
Entry(String),
#[error("host API {host} is outside {min}..{max}", host = crate::extensions::HOST_API_VERSION)]
Api {
min: String,
max: String,
},
#[error("unknown capability `{0}`")]
Capability(String),
}