extension_manifest.rs

  1use anyhow::{Context as _, Result, bail};
  2use collections::{BTreeMap, HashMap};
  3use fs::Fs;
  4use language::LanguageName;
  5use lsp::LanguageServerName;
  6use semantic_version::SemanticVersion;
  7use serde::{Deserialize, Serialize};
  8use std::{
  9    ffi::OsStr,
 10    fmt,
 11    path::{Path, PathBuf},
 12    sync::Arc,
 13};
 14
 15use crate::ExtensionCapability;
 16
 17/// This is the old version of the extension manifest, from when it was `extension.json`.
 18#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
 19pub struct OldExtensionManifest {
 20    pub name: String,
 21    pub version: Arc<str>,
 22
 23    #[serde(default)]
 24    pub description: Option<String>,
 25    #[serde(default)]
 26    pub repository: Option<String>,
 27    #[serde(default)]
 28    pub authors: Vec<String>,
 29
 30    #[serde(default)]
 31    pub themes: BTreeMap<Arc<str>, PathBuf>,
 32    #[serde(default)]
 33    pub languages: BTreeMap<Arc<str>, PathBuf>,
 34    #[serde(default)]
 35    pub grammars: BTreeMap<Arc<str>, PathBuf>,
 36}
 37
 38/// The schema version of the [`ExtensionManifest`].
 39#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
 40pub struct SchemaVersion(pub i32);
 41
 42impl fmt::Display for SchemaVersion {
 43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 44        write!(f, "{}", self.0)
 45    }
 46}
 47
 48impl SchemaVersion {
 49    pub const ZERO: Self = Self(0);
 50
 51    pub fn is_v0(&self) -> bool {
 52        self == &Self::ZERO
 53    }
 54}
 55
 56#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
 57pub struct ExtensionManifest {
 58    pub id: Arc<str>,
 59    pub name: String,
 60    pub version: Arc<str>,
 61    pub schema_version: SchemaVersion,
 62
 63    #[serde(default)]
 64    pub description: Option<String>,
 65    #[serde(default)]
 66    pub repository: Option<String>,
 67    #[serde(default)]
 68    pub authors: Vec<String>,
 69    #[serde(default)]
 70    pub lib: LibManifestEntry,
 71
 72    #[serde(default)]
 73    pub themes: Vec<PathBuf>,
 74    #[serde(default)]
 75    pub icon_themes: Vec<PathBuf>,
 76    #[serde(default)]
 77    pub languages: Vec<PathBuf>,
 78    #[serde(default)]
 79    pub grammars: BTreeMap<Arc<str>, GrammarManifestEntry>,
 80    #[serde(default)]
 81    pub language_servers: BTreeMap<LanguageServerName, LanguageServerManifestEntry>,
 82    #[serde(default)]
 83    pub context_servers: BTreeMap<Arc<str>, ContextServerManifestEntry>,
 84    #[serde(default)]
 85    pub slash_commands: BTreeMap<Arc<str>, SlashCommandManifestEntry>,
 86    #[serde(default)]
 87    pub snippets: Option<PathBuf>,
 88    #[serde(default)]
 89    pub capabilities: Vec<ExtensionCapability>,
 90    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
 91    pub debug_adapters: BTreeMap<Arc<str>, DebugAdapterManifestEntry>,
 92    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
 93    pub debug_locators: BTreeMap<Arc<str>, DebugLocatorManifestEntry>,
 94}
 95
 96impl ExtensionManifest {
 97    pub fn allow_exec(
 98        &self,
 99        desired_command: &str,
100        desired_args: &[impl AsRef<str> + std::fmt::Debug],
101    ) -> Result<()> {
102        let is_allowed = self.capabilities.iter().any(|capability| match capability {
103            ExtensionCapability::ProcessExec(capability) => {
104                capability.allows(desired_command, desired_args)
105            }
106            _ => false,
107        });
108
109        if !is_allowed {
110            bail!(
111                "capability for process:exec {desired_command} {desired_args:?} was not listed in the extension manifest",
112            );
113        }
114
115        Ok(())
116    }
117
118    pub fn allow_remote_load(&self) -> bool {
119        !self.language_servers.is_empty()
120            || !self.debug_adapters.is_empty()
121            || !self.debug_locators.is_empty()
122    }
123}
124
125pub fn build_debug_adapter_schema_path(
126    adapter_name: &Arc<str>,
127    meta: &DebugAdapterManifestEntry,
128) -> PathBuf {
129    meta.schema_path.clone().unwrap_or_else(|| {
130        Path::new("debug_adapter_schemas")
131            .join(Path::new(adapter_name.as_ref()).with_extension("json"))
132    })
133}
134
135#[derive(Clone, Default, PartialEq, Eq, Debug, Deserialize, Serialize)]
136pub struct LibManifestEntry {
137    pub kind: Option<ExtensionLibraryKind>,
138    pub version: Option<SemanticVersion>,
139}
140
141#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
142pub enum ExtensionLibraryKind {
143    Rust,
144}
145
146#[derive(Clone, Default, PartialEq, Eq, Debug, Deserialize, Serialize)]
147pub struct GrammarManifestEntry {
148    pub repository: String,
149    #[serde(alias = "commit")]
150    pub rev: String,
151    #[serde(default)]
152    pub path: Option<String>,
153}
154
155#[derive(Clone, Default, PartialEq, Eq, Debug, Deserialize, Serialize)]
156pub struct LanguageServerManifestEntry {
157    /// Deprecated in favor of `languages`.
158    #[serde(default)]
159    language: Option<LanguageName>,
160    /// The list of languages this language server should work with.
161    #[serde(default)]
162    languages: Vec<LanguageName>,
163    #[serde(default)]
164    pub language_ids: HashMap<LanguageName, String>,
165    #[serde(default)]
166    pub code_action_kinds: Option<Vec<lsp::CodeActionKind>>,
167}
168
169impl LanguageServerManifestEntry {
170    /// Returns the list of languages for the language server.
171    ///
172    /// Prefer this over accessing the `language` or `languages` fields directly,
173    /// as we currently support both.
174    ///
175    /// We can replace this with just field access for the `languages` field once
176    /// we have removed `language`.
177    pub fn languages(&self) -> impl IntoIterator<Item = LanguageName> + '_ {
178        let language = if self.languages.is_empty() {
179            self.language.clone()
180        } else {
181            None
182        };
183        self.languages.iter().cloned().chain(language)
184    }
185}
186
187#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
188pub struct ContextServerManifestEntry {}
189
190#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
191pub struct SlashCommandManifestEntry {
192    pub description: String,
193    pub requires_argument: bool,
194}
195
196#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
197pub struct DebugAdapterManifestEntry {
198    pub schema_path: Option<PathBuf>,
199}
200
201#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
202pub struct DebugLocatorManifestEntry {}
203
204impl ExtensionManifest {
205    pub async fn load(fs: Arc<dyn Fs>, extension_dir: &Path) -> Result<Self> {
206        let extension_name = extension_dir
207            .file_name()
208            .and_then(OsStr::to_str)
209            .context("invalid extension name")?;
210
211        let mut extension_manifest_path = extension_dir.join("extension.json");
212        if fs.is_file(&extension_manifest_path).await {
213            let manifest_content = fs
214                .load(&extension_manifest_path)
215                .await
216                .with_context(|| format!("failed to load {extension_name} extension.json"))?;
217            let manifest_json = serde_json::from_str::<OldExtensionManifest>(&manifest_content)
218                .with_context(|| {
219                    format!("invalid extension.json for extension {extension_name}")
220                })?;
221
222            Ok(manifest_from_old_manifest(manifest_json, extension_name))
223        } else {
224            extension_manifest_path.set_extension("toml");
225            let manifest_content = fs
226                .load(&extension_manifest_path)
227                .await
228                .with_context(|| format!("failed to load {extension_name} extension.toml"))?;
229            toml::from_str(&manifest_content)
230                .with_context(|| format!("invalid extension.toml for extension {extension_name}"))
231        }
232    }
233}
234
235fn manifest_from_old_manifest(
236    manifest_json: OldExtensionManifest,
237    extension_id: &str,
238) -> ExtensionManifest {
239    ExtensionManifest {
240        id: extension_id.into(),
241        name: manifest_json.name,
242        version: manifest_json.version,
243        description: manifest_json.description,
244        repository: manifest_json.repository,
245        authors: manifest_json.authors,
246        schema_version: SchemaVersion::ZERO,
247        lib: Default::default(),
248        themes: {
249            let mut themes = manifest_json.themes.into_values().collect::<Vec<_>>();
250            themes.sort();
251            themes.dedup();
252            themes
253        },
254        icon_themes: Vec::new(),
255        languages: {
256            let mut languages = manifest_json.languages.into_values().collect::<Vec<_>>();
257            languages.sort();
258            languages.dedup();
259            languages
260        },
261        grammars: manifest_json
262            .grammars
263            .into_keys()
264            .map(|grammar_name| (grammar_name, Default::default()))
265            .collect(),
266        language_servers: Default::default(),
267        context_servers: BTreeMap::default(),
268        slash_commands: BTreeMap::default(),
269        snippets: None,
270        capabilities: Vec::new(),
271        debug_adapters: Default::default(),
272        debug_locators: Default::default(),
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use pretty_assertions::assert_eq;
279
280    use crate::ProcessExecCapability;
281
282    use super::*;
283
284    fn extension_manifest() -> ExtensionManifest {
285        ExtensionManifest {
286            id: "test".into(),
287            name: "Test".to_string(),
288            version: "1.0.0".into(),
289            schema_version: SchemaVersion::ZERO,
290            description: None,
291            repository: None,
292            authors: vec![],
293            lib: Default::default(),
294            themes: vec![],
295            icon_themes: vec![],
296            languages: vec![],
297            grammars: BTreeMap::default(),
298            language_servers: BTreeMap::default(),
299            context_servers: BTreeMap::default(),
300            slash_commands: BTreeMap::default(),
301            snippets: None,
302            capabilities: vec![],
303            debug_adapters: Default::default(),
304            debug_locators: Default::default(),
305        }
306    }
307
308    #[test]
309    fn test_build_adapter_schema_path_with_schema_path() {
310        let adapter_name = Arc::from("my_adapter");
311        let entry = DebugAdapterManifestEntry {
312            schema_path: Some(PathBuf::from("foo/bar")),
313        };
314
315        let path = build_debug_adapter_schema_path(&adapter_name, &entry);
316        assert_eq!(path, PathBuf::from("foo/bar"));
317    }
318
319    #[test]
320    fn test_build_adapter_schema_path_without_schema_path() {
321        let adapter_name = Arc::from("my_adapter");
322        let entry = DebugAdapterManifestEntry { schema_path: None };
323
324        let path = build_debug_adapter_schema_path(&adapter_name, &entry);
325        assert_eq!(
326            path,
327            PathBuf::from("debug_adapter_schemas").join("my_adapter.json")
328        );
329    }
330
331    #[test]
332    fn test_allow_exec_exact_match() {
333        let manifest = ExtensionManifest {
334            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
335                command: "ls".to_string(),
336                args: vec!["-la".to_string()],
337            })],
338            ..extension_manifest()
339        };
340
341        assert!(manifest.allow_exec("ls", &["-la"]).is_ok());
342        assert!(manifest.allow_exec("ls", &["-l"]).is_err());
343        assert!(manifest.allow_exec("pwd", &[] as &[&str]).is_err());
344    }
345
346    #[test]
347    fn test_allow_exec_wildcard_arg() {
348        let manifest = ExtensionManifest {
349            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
350                command: "git".to_string(),
351                args: vec!["*".to_string()],
352            })],
353            ..extension_manifest()
354        };
355
356        assert!(manifest.allow_exec("git", &["status"]).is_ok());
357        assert!(manifest.allow_exec("git", &["commit"]).is_ok());
358        assert!(manifest.allow_exec("git", &["status", "-s"]).is_err()); // too many args
359        assert!(manifest.allow_exec("npm", &["install"]).is_err()); // wrong command
360    }
361
362    #[test]
363    fn test_allow_exec_double_wildcard() {
364        let manifest = ExtensionManifest {
365            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
366                command: "cargo".to_string(),
367                args: vec!["test".to_string(), "**".to_string()],
368            })],
369            ..extension_manifest()
370        };
371
372        assert!(manifest.allow_exec("cargo", &["test"]).is_ok());
373        assert!(manifest.allow_exec("cargo", &["test", "--all"]).is_ok());
374        assert!(
375            manifest
376                .allow_exec("cargo", &["test", "--all", "--no-fail-fast"])
377                .is_ok()
378        );
379        assert!(manifest.allow_exec("cargo", &["build"]).is_err()); // wrong first arg
380    }
381
382    #[test]
383    fn test_allow_exec_mixed_wildcards() {
384        let manifest = ExtensionManifest {
385            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
386                command: "docker".to_string(),
387                args: vec!["run".to_string(), "*".to_string(), "**".to_string()],
388            })],
389            ..extension_manifest()
390        };
391
392        assert!(manifest.allow_exec("docker", &["run", "nginx"]).is_ok());
393        assert!(manifest.allow_exec("docker", &["run"]).is_err());
394        assert!(
395            manifest
396                .allow_exec("docker", &["run", "ubuntu", "bash"])
397                .is_ok()
398        );
399        assert!(
400            manifest
401                .allow_exec("docker", &["run", "alpine", "sh", "-c", "echo hello"])
402                .is_ok()
403        );
404        assert!(manifest.allow_exec("docker", &["ps"]).is_err()); // wrong first arg
405    }
406}