diff --git a/Cargo.lock b/Cargo.lock index 9f71354..3592cfd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -157,7 +157,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" dependencies = [ "cfg-if", - "hashbrown", + "hashbrown 0.14.5", "lock_api", "once_cell", "parking_lot_core", @@ -174,6 +174,12 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "errno" version = "0.3.14" @@ -287,6 +293,12 @@ version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" @@ -401,6 +413,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -638,6 +660,15 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -773,6 +804,47 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tower" version = "0.4.13" @@ -931,7 +1003,7 @@ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" [[package]] name = "vsg-bridge-ls" -version = "0.3.1" +version = "0.3.2" dependencies = [ "anyhow", "clap", @@ -939,6 +1011,7 @@ dependencies = [ "serde", "serde_json", "tokio", + "toml", "tower", "tower-lsp", "tracing-subscriber", @@ -965,6 +1038,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "writeable" version = "0.6.4" diff --git a/Cargo.toml b/Cargo.toml index 3125150..1154faf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "vsg-bridge-ls" description = "A very featureless VSG to lsp bridge" -version = "0.3.1" +version = "0.3.2" edition = "2021" rust-version = "1.85.1" categories =["developement-tools"] @@ -15,6 +15,7 @@ anyhow = "1.0.93" clap = { version = "4.5.21", features = ["derive"] } serde = { version = "1.0.215", features = ["derive"] } serde_json = "1.0.133" +toml = "0.8.19" tokio = { version = "1.41.1", features = ["io-std", "io-util", "macros", "process", "rt-multi-thread", "sync", "time"] } tower-lsp = "0.20.0" tracing-subscriber = "0.3.18" diff --git a/README.md b/README.md index b5913ae..44d9953 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ vsg-bridge-ls --version ``` The version includes both the Cargo release and build commit, for example -`0.3.1+git.0123abcd`, so editor logs can identify the exact binary. +`0.3.2+git.0123abcd`, so editor logs can identify the exact binary. ## 3. Configure Helix @@ -65,6 +65,8 @@ Add this minimal setup to `~/.config/helix/languages.toml`: command = "vsg-bridge-ls" args = [ "--configuration", "/absolute/path/to/vsg-bridge-ls/showcase/vsg.yaml", + # Uncomment to allow an action that opens rule documentation in a browser. + # "--allow-browser-action", # Uncomment the next line to enable experimental individual rule fixes. # "--experimental-rule-fix", # Uncomment the next line to enable the experimental grouped line fix. @@ -92,8 +94,8 @@ format the current in-memory buffer through the same VSG fix-all path used by Hover a diagnosed line to see the VSG rule, configured severity, correction phase, fixability, relevant configuration, and available documentation links. -Clients supporting LSP `window/showDocument` can also ask the bridge to open a -rule's documentation externally. +With `--allow-browser-action`, clients supporting LSP `window/showDocument` can +also ask the bridge to open a rule's documentation externally. With `--experimental-rule-fix`, the code-action menu immediately offers a Quick Fix for each fixable VSG rule on the diagnosed line. Building the menu does not @@ -122,6 +124,7 @@ process environment variables. See the [debug-mode reference](doc/debug-mode.md) ## More documentation - [Installation alternatives and PATH troubleshooting](doc/installation.md) +- [Layered bridge configuration](doc/configuration.md) - [Helix, Vim, and VSCodium setup](doc/editor-configuration.md) - [VSG/bridge machine interface](doc/architecture/vsg-interface.md) - [Experimental individual rule fixes](doc/experimental-rule-fix.md) diff --git a/doc/architecture/vsg-interface.md b/doc/architecture/vsg-interface.md index 43b5420..ad35bb1 100644 --- a/doc/architecture/vsg-interface.md +++ b/doc/architecture/vsg-interface.md @@ -225,9 +225,10 @@ documentation. requests. - Offer hover Markdown containing rule, message, configured severity, phase, fixability, effective configuration, and available links. -- A `Show VSG rule documentation` action may execute a server-owned command - that requests `window/showDocument`. Fall back to a concise message when the - client does not support it. +- When explicitly enabled by `--allow-browser-action` or layered bridge + configuration, a `Show VSG rule documentation` action may execute a + server-owned command that requests `window/showDocument`. Do not advertise + the command without both permission and client support. ## Compatibility and ownership diff --git a/doc/configuration.md b/doc/configuration.md new file mode 100644 index 0000000..c149f2c --- /dev/null +++ b/doc/configuration.md @@ -0,0 +1,30 @@ +# Bridge configuration + +The bridge loads optional TOML configuration in this order: + +1. `$XDG_CONFIG_HOME/vsg-bridge-ls/config.toml`, or + `~/.config/vsg-bridge-ls/config.toml` when `XDG_CONFIG_HOME` is unset; +2. `vsg-bridge-ls.toml` in the process working directory; +3. explicit command-line options. + +Each later layer overrides values explicitly set by an earlier layer. Missing +files are ignored. An unreadable file, invalid TOML, or unknown key stops startup +with the responsible path instead of silently using unexpected settings. + +```toml +vsg_configuration = ["/absolute/path/to/vsg.yaml"] +allow_browser_action = false +experimental_rule_fix = false +experimental_multi_rule_line_fix = false +debug_mode = false +``` + +The project file can explicitly set a Boolean to `false` to disable a setting +enabled in the user file. A command-line Boolean flag enables its setting over +both files. One or more command-line `--configuration PATH` values replace the +complete `vsg_configuration` list from TOML. + +`allow_browser_action` is disabled by default because the corresponding code +action asks the LSP client to open an external HTTPS URL. It is equivalent to +the explicit `--allow-browser-action` flag. Documentation URLs remain visible +in diagnostics and hover when browser actions are disabled. diff --git a/doc/debug-mode.md b/doc/debug-mode.md index 0b3e180..dfc2477 100644 --- a/doc/debug-mode.md +++ b/doc/debug-mode.md @@ -11,7 +11,8 @@ Invoking the action displays a pretty-printed JSON snapshot containing: - the bridge version and embedded commit, executable path, process ID, and working directory; - enabled debug and experimental modes; -- whether the client advertised `window/showDocument`; +- whether browser actions are allowed and the client advertised + `window/showDocument`; - the VSG runner and exact configuration arguments; - the URI that requested the action; and - every open document's URI, version, UTF-8 byte and line counts, and current diff --git a/doc/editor-configuration.md b/doc/editor-configuration.md index 35bae9e..19f17c7 100644 --- a/doc/editor-configuration.md +++ b/doc/editor-configuration.md @@ -19,6 +19,8 @@ Add this configuration to `~/.config/helix/languages.toml`: command = "vsg-bridge-ls" args = [ "--configuration", "/absolute/path/to/vsg-bridge-ls/showcase/vsg.yaml", + # Uncomment to allow an action that opens rule documentation in a browser. + # "--allow-browser-action", # Uncomment the next line to enable experimental individual rule fixes. # "--experimental-rule-fix", # Uncomment the next line to enable the experimental grouped line fix. @@ -40,6 +42,10 @@ To use another VSG configuration, change the path in the argument list. Repeat args = ["-c", "vhdl/config.yaml"] ``` +The same bridge settings can live in the user or project TOML files described +in the [configuration reference](configuration.md). Explicit arguments in this +editor setup take precedence. + The experimental grouped same-line action is enabled by uncommenting its entry in the complete example. It is deliberately off by default; read its [safety notes](experimental-multi-rule-line-fix.md) before enabling it. diff --git a/showcase/README.md b/showcase/README.md index 06920a7..cdbcf4b 100644 --- a/showcase/README.md +++ b/showcase/README.md @@ -12,6 +12,8 @@ pass the showcase configuration to the bridge: command = "vsg-bridge-ls" args = [ "--configuration", "/absolute/path/to/vsg-bridge-ls/showcase/vsg.yaml", + # Uncomment to allow an action that opens rule documentation in a browser. + # "--allow-browser-action", # Uncomment the next line to enable experimental individual rule fixes. # "--experimental-rule-fix", # Uncomment the next line to enable the experimental grouped line fix. diff --git a/src/lib.rs b/src/lib.rs index de4c685..712c762 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,7 +11,10 @@ mod presentation; mod runner; mod server; +use anyhow::{Context, Result}; use clap::Parser; +use serde::Deserialize; +use std::path::{Path, PathBuf}; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncWrite}; use tower_lsp::{LspService, Server}; @@ -26,6 +29,11 @@ pub const VERSION: &str = concat!( env!("VSG_BRIDGE_GIT_SHA") ); +/// Project-local bridge configuration filename. +const PROJECT_CONFIG: &str = "vsg-bridge-ls.toml"; +/// Path below the user's XDG configuration directory. +const USER_CONFIG: &str = "vsg-bridge-ls/config.toml"; + /// Command-line configuration for the language server. #[derive(Clone, Debug, Parser, PartialEq, Eq)] #[command(version = VERSION, about, long_about = None)] @@ -33,6 +41,9 @@ pub struct Options { /// VSG configuration files, in the order in which VSG should load them. #[arg(short, long)] pub configuration: Vec, + /// Allows a code action that opens rule documentation in a browser. + #[arg(long)] + pub allow_browser_action: bool, /// Offers opt-in per-rule corrections for one diagnosed line. #[arg(long)] pub experimental_rule_fix: bool, @@ -44,7 +55,81 @@ pub struct Options { pub debug_mode: bool, } +/// Optional settings read from one TOML configuration layer. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +struct FileOptions { + /// VSG configuration paths forwarded in their declared order. + vsg_configuration: Option>, + /// Whether browser-opening documentation actions are offered. + allow_browser_action: Option, + /// Whether individual rule corrections are offered. + experimental_rule_fix: Option, + /// Whether grouped same-line corrections are offered. + experimental_multi_rule_line_fix: Option, + /// Whether runtime debug information is exposed. + debug_mode: Option, +} + +impl FileOptions { + /// Applies every explicitly configured value from a higher-priority layer. + fn overlay(&mut self, higher: Self) { + if higher.vsg_configuration.is_some() { + self.vsg_configuration = higher.vsg_configuration; + } + if higher.allow_browser_action.is_some() { + self.allow_browser_action = higher.allow_browser_action; + } + if higher.experimental_rule_fix.is_some() { + self.experimental_rule_fix = higher.experimental_rule_fix; + } + if higher.experimental_multi_rule_line_fix.is_some() { + self.experimental_multi_rule_line_fix = higher.experimental_multi_rule_line_fix; + } + if higher.debug_mode.is_some() { + self.debug_mode = higher.debug_mode; + } + } +} + impl Options { + /// Loads user and project configuration, then applies explicit CLI values. + pub fn resolve(self) -> Result { + let user = user_config_path(); + let project = std::env::current_dir() + .context("failed to determine the working directory")? + .join(PROJECT_CONFIG); + self.resolve_from_paths(user.as_deref(), &project) + } + + /// Resolves configuration using injectable paths for deterministic tests. + fn resolve_from_paths(self, user: Option<&Path>, project: &Path) -> Result { + let mut file = FileOptions::default(); + if let Some(user) = user { + if let Some(user) = read_file_options(user)? { + file.overlay(user); + } + } + if let Some(project) = read_file_options(project)? { + file.overlay(project); + } + + Ok(Self { + configuration: if self.configuration.is_empty() { + file.vsg_configuration.unwrap_or_default() + } else { + self.configuration + }, + allow_browser_action: self.allow_browser_action + || file.allow_browser_action.unwrap_or(false), + experimental_rule_fix: self.experimental_rule_fix + || file.experimental_rule_fix.unwrap_or(false), + experimental_multi_rule_line_fix: self.experimental_multi_rule_line_fix + || file.experimental_multi_rule_line_fix.unwrap_or(false), + debug_mode: self.debug_mode || file.debug_mode.unwrap_or(false), + }) + } + /// Converts configuration paths into the argument vector expected by VSG. #[must_use] pub fn vsg_arguments(&self) -> Vec { @@ -55,6 +140,33 @@ impl Options { } } +/// Reads one optional TOML layer while distinguishing absence from failure. +fn read_file_options(path: &Path) -> Result> { + let source = match std::fs::read_to_string(path) { + Ok(source) => source, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => { + return Err(error).with_context(|| format!("failed to read {}", path.display())) + } + }; + toml::from_str(&source) + .with_context(|| format!("invalid bridge configuration {}", path.display())) + .map(Some) +} + +/// Finds the conventional user configuration without requiring it to exist. +fn user_config_path() -> Option { + std::env::var_os("XDG_CONFIG_HOME") + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + .or_else(|| { + std::env::var_os("HOME") + .filter(|path| !path.is_empty()) + .map(|home| PathBuf::from(home).join(".config")) + }) + .map(|root| root.join(USER_CONFIG)) +} + /// Runs the language server over standard input and standard output. pub async fn run_stdio(options: Options) { let runner: Arc = Arc::new(ProcessVsgRunner::default()); @@ -74,6 +186,7 @@ where let vsg_arguments = options.vsg_arguments(); let (service, socket) = LspService::new(move |client| { Backend::new(client, Arc::clone(&runner), vsg_arguments.clone()) + .with_browser_action(options.allow_browser_action) .with_experimental_rule_fix(options.experimental_rule_fix) .with_experimental_multi_rule_line_fix(options.experimental_multi_rule_line_fix) .with_debug_mode(options.debug_mode) @@ -90,6 +203,8 @@ mod tests { use crate::VsgRunner; use anyhow::Result; use clap::{CommandFactory, Parser}; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -97,6 +212,36 @@ mod tests { #[derive(Debug)] struct UnusedRunner; + /// Process-local suffix for collision-free temporary test directories. + static NEXT_TEMP_DIRECTORY: AtomicU64 = AtomicU64::new(0); + + /// Removes a test directory and its configuration files on drop. + struct TestDirectory(PathBuf); + + impl TestDirectory { + /// Creates an isolated directory below the system temporary directory. + fn new() -> Self { + let suffix = NEXT_TEMP_DIRECTORY.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "vsg-bridge-ls-config-{}-{suffix}", + std::process::id() + )); + std::fs::create_dir(&path).expect("create temporary configuration directory"); + Self(path) + } + + /// Returns the temporary directory path. + fn path(&self) -> &std::path::Path { + &self.0 + } + } + + impl Drop for TestDirectory { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + #[tower_lsp::async_trait] impl VsgRunner for UnusedRunner { async fn lint(&self, _: &str, _: &[String]) -> Result { @@ -157,6 +302,7 @@ mod tests { .expect("options without configuration files are valid"); assert!(options.vsg_arguments().is_empty()); + assert!(!options.allow_browser_action); assert!(!options.experimental_rule_fix); assert!(!options.experimental_multi_rule_line_fix); assert!(!options.debug_mode); @@ -166,13 +312,93 @@ mod tests { #[test] fn version_includes_source_revision() { assert_eq!(Options::command().get_version(), Some(VERSION)); - assert!(VERSION.starts_with("0.3.1+git.")); + assert!(VERSION.starts_with("0.3.2+git.")); assert!(VERSION - .strip_prefix("0.3.1+git.") + .strip_prefix("0.3.2+git.") .is_some_and(|revision| revision == "unknown" || (revision.len() == 8 && revision.bytes().all(|byte| byte.is_ascii_hexdigit())))); } + /// Browser-opening actions require an explicit runtime opt-in. + #[test] + fn parses_allow_browser_action_flag() { + let options = Options::try_parse_from(["vsg-bridge-ls", "--allow-browser-action"]) + .expect("browser flag is valid"); + + assert!(options.allow_browser_action); + } + + /// User settings are overlaid by project settings and explicit CLI values. + #[test] + fn resolves_layered_toml_configuration() { + let directory = TestDirectory::new(); + let user = directory.path().join("user.toml"); + let project = directory.path().join("project.toml"); + std::fs::write( + &user, + r#" +vsg_configuration = ["user.yaml"] +allow_browser_action = true +experimental_rule_fix = true +debug_mode = true +"#, + ) + .expect("write user configuration"); + std::fs::write( + &project, + r#" +allow_browser_action = false +experimental_rule_fix = false +experimental_multi_rule_line_fix = true +debug_mode = false +"#, + ) + .expect("write project configuration"); + + let from_files = Options::try_parse_from(["vsg-bridge-ls"]) + .expect("default CLI") + .resolve_from_paths(Some(&user), &project) + .expect("layered configuration"); + assert_eq!(from_files.configuration, ["user.yaml"]); + assert!(!from_files.allow_browser_action); + assert!(!from_files.experimental_rule_fix); + assert!(from_files.experimental_multi_rule_line_fix); + assert!(!from_files.debug_mode); + + let from_cli = Options::try_parse_from([ + "vsg-bridge-ls", + "--configuration", + "cli.yaml", + "--allow-browser-action", + "--experimental-rule-fix", + "--debug-mode", + ]) + .expect("explicit CLI") + .resolve_from_paths(Some(&user), &project) + .expect("CLI overrides"); + assert_eq!(from_cli.configuration, ["cli.yaml"]); + assert!(from_cli.allow_browser_action); + assert!(from_cli.experimental_rule_fix); + assert!(from_cli.experimental_multi_rule_line_fix); + assert!(from_cli.debug_mode); + } + + /// Invalid configuration fails with the responsible path. + #[test] + fn rejects_invalid_toml_configuration() { + let directory = TestDirectory::new(); + let project = directory.path().join("project.toml"); + std::fs::write(&project, "debug_mode = maybe").expect("write invalid configuration"); + + let error = Options::try_parse_from(["vsg-bridge-ls"]) + .expect("default CLI") + .resolve_from_paths(None, &project) + .expect_err("invalid TOML must fail"); + + assert!(error.to_string().contains("invalid bridge configuration")); + assert!(error.to_string().contains("project.toml")); + } + /// Per-rule corrections require an explicit runtime opt-in. #[test] fn parses_experimental_rule_fix_flag() { @@ -211,6 +437,7 @@ mod tests { response_writer, Options { configuration: Vec::new(), + allow_browser_action: false, experimental_rule_fix: false, experimental_multi_rule_line_fix: false, debug_mode: false, diff --git a/src/main.rs b/src/main.rs index aa1fbfe..a78ba07 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,5 +9,9 @@ async fn main() { tracing_subscriber::fmt() .with_writer(std::io::stderr) .init(); - run_stdio(Options::parse()).await; + let options = Options::parse().resolve().unwrap_or_else(|error| { + eprintln!("vsg-bridge-ls: {error:#}"); + std::process::exit(2); + }); + run_stdio(options).await; } diff --git a/src/presentation.rs b/src/presentation.rs index 6455c7f..55d1de1 100644 --- a/src/presentation.rs +++ b/src/presentation.rs @@ -219,7 +219,7 @@ mod tests { #[test] fn appends_debug_information_to_hover() { let hover = hover_for_line(&[diagnostic(None, None)], 2); - let hover = append_debug_hover(hover, r#"{"version":"0.3.1","note":"```"}"#); + let hover = append_debug_hover(hover, r#"{"version":"0.3.2","note":"```"}"#); let HoverContents::Markup(markup) = hover.contents else { panic!("expected Markdown hover") }; diff --git a/src/server.rs b/src/server.rs index 5c725cc..2ec468e 100644 --- a/src/server.rs +++ b/src/server.rs @@ -94,6 +94,8 @@ pub struct Backend { documents: RwLock>, /// Whether the initialized client accepts `window/showDocument` requests. show_document_supported: AtomicBool, + /// Allows actions that ask the client to open documentation in a browser. + allow_browser_action: bool, /// Enables opt-in per-rule correction actions. experimental_rule_fix: bool, /// Enables the opt-in multi-rule action independently of per-rule fixes. @@ -114,6 +116,7 @@ impl Backend { vsg_arguments, documents: RwLock::new(HashMap::new()), show_document_supported: AtomicBool::new(false), + allow_browser_action: false, experimental_rule_fix: false, experimental_multi_rule_line_fix: false, debug_mode: false, @@ -121,6 +124,13 @@ impl Backend { } } + /// Enables or disables documentation actions that open a browser. + #[must_use] + pub fn with_browser_action(mut self, enabled: bool) -> Self { + self.allow_browser_action = enabled; + self + } + /// Enables or disables experimental per-rule correction actions. #[must_use] pub fn with_experimental_rule_fix(mut self, enabled: bool) -> Self { @@ -185,6 +195,7 @@ impl Backend { .map(|path| path.to_string_lossy().into_owned()), }, "client": { + "allow_browser_action": self.allow_browser_action, "show_document": self.show_document_supported.load(Ordering::Relaxed), }, "documents": document_state, @@ -373,7 +384,7 @@ impl LanguageServer for Backend { code_action_kinds.push(DEBUG_INFORMATION_KIND); } let mut commands = vec![APPLY_CORRECTION.to_owned()]; - if show_document_supported { + if self.allow_browser_action && show_document_supported { commands.push(SHOW_RULE_DOCUMENTATION.to_owned()); } if self.debug_mode { @@ -474,7 +485,7 @@ impl LanguageServer for Backend { if parameters.command != SHOW_RULE_DOCUMENTATION { return Err(Error::invalid_params("unknown VSG command")); } - if !self.show_document_supported.load(Ordering::Relaxed) { + if !self.allow_browser_action || !self.show_document_supported.load(Ordering::Relaxed) { return Err(Error::invalid_request()); } let url = parameters @@ -568,7 +579,8 @@ impl LanguageServer for Backend { } } - if self.show_document_supported.load(Ordering::Relaxed) { + if self.allow_browser_action && self.show_document_supported.load(Ordering::Relaxed) + { if let Some(url) = data.metadata.documentation.rule { if documentation_urls.insert(url.clone()) { actions.push(CodeActionOrCommand::CodeAction(CodeAction { @@ -1129,12 +1141,44 @@ mod tests { ); } - /// Documentation commands are advertised only to supporting clients. + /// Client browser support alone does not opt in to external navigation. + #[tokio::test] + async fn omits_documentation_command_without_permission() { + let runner = Arc::new(MockRunner::successful(ONE_DIAGNOSTIC)); + let (mut service, mut socket) = + LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); + + let response = initialize_with( + &mut service, + json!({"window": {"showDocument": {"support": true}}}), + ) + .await; + let value = serde_json::to_value(response).expect("serialize response"); + + assert_eq!( + value["result"]["capabilities"]["executeCommandProvider"]["commands"], + json!(["vsg.applyCorrection"]) + ); + open_document( + &mut service, + &mut socket, + json!({"textDocument": { + "uri": "file:///tmp/example.vhd", "languageId": "vhdl", + "version": 1, "text": "entity demo is" + }}), + ) + .await; + let actions = request_code_actions(&mut service, json!([]), json!(["quickfix"])).await; + assert!(actions.is_null()); + } + + /// Documentation commands require both permission and client support. #[tokio::test] async fn advertises_documentation_command_to_supporting_clients() { - let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); - let (mut service, _socket) = - LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); + let runner = Arc::new(MockRunner::successful(ONE_DIAGNOSTIC)); + let (mut service, mut socket) = LspService::new(move |client| { + Backend::new(client, runner.clone(), Vec::new()).with_browser_action(true) + }); let response = initialize_with( &mut service, @@ -1147,6 +1191,17 @@ mod tests { value["result"]["capabilities"]["executeCommandProvider"]["commands"], json!(["vsg.applyCorrection", "vsg.showRuleDocumentation"]) ); + open_document( + &mut service, + &mut socket, + json!({"textDocument": { + "uri": "file:///tmp/example.vhd", "languageId": "vhdl", + "version": 1, "text": "entity demo is" + }}), + ) + .await; + let actions = request_code_actions(&mut service, json!([]), json!(["quickfix"])).await; + assert_eq!(actions[0]["title"], "Show rule_001 documentation"); } /// Debug capabilities and commands are advertised only in debug mode. @@ -1237,10 +1292,11 @@ mod tests { assert!(report["bridge"]["version"] .as_str() - .is_some_and(|version| version.starts_with("0.3.1+git."))); + .is_some_and(|version| version.starts_with("0.3.2+git."))); assert_eq!(report["modes"]["debug"], true); assert_eq!(report["modes"]["experimental_rule_fix"], true); assert_eq!(report["modes"]["experimental_multi_rule_line_fix"], true); + assert_eq!(report["client"]["allow_browser_action"], false); assert_eq!(report["request"]["uri"], "file:///tmp/example.vhd"); assert_eq!(report["vsg"]["arguments"], json!(["-c", "rules.yaml"])); assert_eq!(report["documents"][0]["version"], 4); @@ -1404,8 +1460,9 @@ mod tests { #[tokio::test] async fn opens_rule_documentation_for_supporting_client() { let runner = Arc::new(MockRunner::successful(EMPTY_DIAGNOSTICS)); - let (mut service, socket) = - LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new())); + let (mut service, socket) = LspService::new(move |client| { + Backend::new(client, runner.clone(), Vec::new()).with_browser_action(true) + }); initialize_with( &mut service, json!({"window": {"showDocument": {"support": true}}}),