1use anyhow::{Context as _, Result, anyhow, 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).map_err(|err| {
230 anyhow!("Invalid extension.toml for extension {extension_name}:\n{err}")
231 })
232 }
233 }
234}
235
236fn manifest_from_old_manifest(
237 manifest_json: OldExtensionManifest,
238 extension_id: &str,
239) -> ExtensionManifest {
240 ExtensionManifest {
241 id: extension_id.into(),
242 name: manifest_json.name,
243 version: manifest_json.version,
244 description: manifest_json.description,
245 repository: manifest_json.repository,
246 authors: manifest_json.authors,
247 schema_version: SchemaVersion::ZERO,
248 lib: Default::default(),
249 themes: {
250 let mut themes = manifest_json.themes.into_values().collect::<Vec<_>>();
251 themes.sort();
252 themes.dedup();
253 themes
254 },
255 icon_themes: Vec::new(),
256 languages: {
257 let mut languages = manifest_json.languages.into_values().collect::<Vec<_>>();
258 languages.sort();
259 languages.dedup();
260 languages
261 },
262 grammars: manifest_json
263 .grammars
264 .into_keys()
265 .map(|grammar_name| (grammar_name, Default::default()))
266 .collect(),
267 language_servers: Default::default(),
268 context_servers: BTreeMap::default(),
269 slash_commands: BTreeMap::default(),
270 snippets: None,
271 capabilities: Vec::new(),
272 debug_adapters: Default::default(),
273 debug_locators: Default::default(),
274 }
275}
276
277#[cfg(test)]
278mod tests {
279 use pretty_assertions::assert_eq;
280
281 use crate::ProcessExecCapability;
282
283 use super::*;
284
285 fn extension_manifest() -> ExtensionManifest {
286 ExtensionManifest {
287 id: "test".into(),
288 name: "Test".to_string(),
289 version: "1.0.0".into(),
290 schema_version: SchemaVersion::ZERO,
291 description: None,
292 repository: None,
293 authors: vec![],
294 lib: Default::default(),
295 themes: vec![],
296 icon_themes: vec![],
297 languages: vec![],
298 grammars: BTreeMap::default(),
299 language_servers: BTreeMap::default(),
300 context_servers: BTreeMap::default(),
301 slash_commands: BTreeMap::default(),
302 snippets: None,
303 capabilities: vec![],
304 debug_adapters: Default::default(),
305 debug_locators: Default::default(),
306 }
307 }
308
309 #[test]
310 fn test_build_adapter_schema_path_with_schema_path() {
311 let adapter_name = Arc::from("my_adapter");
312 let entry = DebugAdapterManifestEntry {
313 schema_path: Some(PathBuf::from("foo/bar")),
314 };
315
316 let path = build_debug_adapter_schema_path(&adapter_name, &entry);
317 assert_eq!(path, PathBuf::from("foo/bar"));
318 }
319
320 #[test]
321 fn test_build_adapter_schema_path_without_schema_path() {
322 let adapter_name = Arc::from("my_adapter");
323 let entry = DebugAdapterManifestEntry { schema_path: None };
324
325 let path = build_debug_adapter_schema_path(&adapter_name, &entry);
326 assert_eq!(
327 path,
328 PathBuf::from("debug_adapter_schemas").join("my_adapter.json")
329 );
330 }
331
332 #[test]
333 fn test_allow_exec_exact_match() {
334 let manifest = ExtensionManifest {
335 capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
336 command: "ls".to_string(),
337 args: vec!["-la".to_string()],
338 })],
339 ..extension_manifest()
340 };
341
342 assert!(manifest.allow_exec("ls", &["-la"]).is_ok());
343 assert!(manifest.allow_exec("ls", &["-l"]).is_err());
344 assert!(manifest.allow_exec("pwd", &[] as &[&str]).is_err());
345 }
346
347 #[test]
348 fn test_allow_exec_wildcard_arg() {
349 let manifest = ExtensionManifest {
350 capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
351 command: "git".to_string(),
352 args: vec!["*".to_string()],
353 })],
354 ..extension_manifest()
355 };
356
357 assert!(manifest.allow_exec("git", &["status"]).is_ok());
358 assert!(manifest.allow_exec("git", &["commit"]).is_ok());
359 assert!(manifest.allow_exec("git", &["status", "-s"]).is_err()); // too many args
360 assert!(manifest.allow_exec("npm", &["install"]).is_err()); // wrong command
361 }
362
363 #[test]
364 fn test_allow_exec_double_wildcard() {
365 let manifest = ExtensionManifest {
366 capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
367 command: "cargo".to_string(),
368 args: vec!["test".to_string(), "**".to_string()],
369 })],
370 ..extension_manifest()
371 };
372
373 assert!(manifest.allow_exec("cargo", &["test"]).is_ok());
374 assert!(manifest.allow_exec("cargo", &["test", "--all"]).is_ok());
375 assert!(
376 manifest
377 .allow_exec("cargo", &["test", "--all", "--no-fail-fast"])
378 .is_ok()
379 );
380 assert!(manifest.allow_exec("cargo", &["build"]).is_err()); // wrong first arg
381 }
382
383 #[test]
384 fn test_allow_exec_mixed_wildcards() {
385 let manifest = ExtensionManifest {
386 capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
387 command: "docker".to_string(),
388 args: vec!["run".to_string(), "*".to_string(), "**".to_string()],
389 })],
390 ..extension_manifest()
391 };
392
393 assert!(manifest.allow_exec("docker", &["run", "nginx"]).is_ok());
394 assert!(manifest.allow_exec("docker", &["run"]).is_err());
395 assert!(
396 manifest
397 .allow_exec("docker", &["run", "ubuntu", "bash"])
398 .is_ok()
399 );
400 assert!(
401 manifest
402 .allow_exec("docker", &["run", "alpine", "sh", "-c", "echo hello"])
403 .is_ok()
404 );
405 assert!(manifest.allow_exec("docker", &["ps"]).is_err()); // wrong first arg
406 }
407}