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