### Starting the LSP server Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt The `bazel-lsp` binary is invoked by editors automatically. It accepts several flags to customize its behavior, such as specifying a custom Bazel binary, disabling a distinct output base for queries, or setting a custom directory for query output bases. ```APIDOC ## Starting the LSP server The `bazel-lsp` binary is invoked by editors automatically. It accepts several flags: ```sh # Default: use "bazel" from PATH, with a distinct output base for queries bazel-lsp # Point to a custom Bazel binary bazel-lsp --bazel /path/to/custom/bazel # Disable the separate query output base (queries may block concurrent builds) bazel-lsp --no-distinct-output-base # Use a custom directory for query output bases bazel-lsp --query-output-base /tmp/my-lsp-output-bases ``` ``` -------------------------------- ### Start Bazel LSP Server Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Invoke the bazel-lsp binary. Editors typically start this automatically. Flags can customize Bazel binary path, output base behavior, and query output base directory. ```sh bazel-lsp ``` ```sh bazel-lsp --bazel /path/to/custom/bazel ``` ```sh bazel-lsp --no-distinct-output-base ``` ```sh bazel-lsp --query-output-base /tmp/my-lsp-output-bases ``` -------------------------------- ### Build Bazel LSP with Bazel Source: https://github.com/cameron-martin/bazel-lsp/blob/master/README.md Build the bazel-lsp binary from source using Bazel. Ensure you are in the project's root directory. ```sh bazel build //:bazel-lsp -c opt ``` -------------------------------- ### Download Pre-built Bazel LSP Release Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Download a pre-built Bazel LSP binary from GitHub Releases and make it executable. Place it on your system's PATH. ```sh curl -L https://github.com/cameron-martin/bazel-lsp/releases/latest/download/bazel-lsp-linux-amd64 \ -o /usr/local/bin/bazel-lsp chmod +x /usr/local/bin/bazel-lsp ``` -------------------------------- ### Implement BazelContext for LspContext Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Instantiate `BazelContext` with a `BazelClient` and an optional query output base path. This context is then passed to the LSP server. ```rust use bazel_lsp::bazel::BazelContext; use bazel_lsp::client::BazelCli; use std::path::PathBuf; // Production usage: real Bazel CLI, distinct query output base (default) let ctx = BazelContext::new( BazelCli::new("bazel"), // uses "bazel" from $PATH Some(PathBuf::from("/tmp/bazel-lsp")), // query output base directory ).unwrap(); // Disable distinct output base (simpler, but queries can block builds) let ctx_no_separate = BazelContext::new( BazelCli::new("/usr/local/bin/bazel"), None, ).unwrap(); // The context is then passed to the stdio LSP server: starlark_lsp::server::stdio_server(ctx).unwrap(); ``` -------------------------------- ### VSCode Integration Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Configuration for VSCode using the Bazel VSCode extension. This involves setting the `bazel.lsp.command` to point to the `bazel-lsp` binary and optionally providing extra flags via `bazel.lsp.args` or environment variables via `bazel.lsp.env`. ```APIDOC ## VSCode Integration ### Configuring with the Bazel VSCode extension Requires the [BazelBuild.vscode-bazel](https://marketplace.visualstudio.com/items?itemName=BazelBuild.vscode-bazel) extension. ```jsonc // settings.json { // Point the Bazel extension to the bazel-lsp binary "bazel.lsp.command": "bazel-lsp", // Optional: pass extra flags to the LSP server "bazel.lsp.args": ["--query-output-base", "/tmp/bazel-lsp-queries"], // Optional: enable structured logging "bazel.lsp.env": { "RUST_LOG": "info" } } ``` ``` -------------------------------- ### Build Bazel Workspace Metadata Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Construct `BazelWorkspace` metadata from `bazel info` output. This includes resolving repository paths and identifying the repository for a given file. ```rust use bazel_lsp::workspace::BazelWorkspace; use bazel_lsp::client::BazelInfo; use std::path::PathBuf; let info = BazelInfo { workspace: "/home/user/myproject".to_string(), output_base: "/home/user/.cache/bazel/_bazel_user/abc123".to_string(), execution_root: "/home/user/.cache/bazel/_bazel_user/abc123/execroot/myproject".to_string(), }; let workspace = BazelWorkspace::from_bazel_info(info, Some("/tmp/bazel-lsp-queries")).unwrap(); assert_eq!(workspace.root, PathBuf::from("/home/user/myproject")); assert_eq!( workspace.external_output_base, PathBuf::from("/home/user/.cache/bazel/_bazel_user/abc123/external") ); // workspace_name is derived from execution_root's final component assert_eq!(workspace.workspace_name.as_deref(), Some("myproject")); // query_output_base is a SHA-256-hashed subdirectory of the provided path assert!(workspace.query_output_base.is_some()); // Resolving a repository path let repo_path = workspace.get_repository_path("rules_rust~0.36.2"); // => /home/user/.cache/bazel/_bazel_user/abc123/external/rules_rust~0.36.2 // Identifying which repository a file belongs to let file = PathBuf::from( "/home/user/.cache/bazel/_bazel_user/abc123/external/rules_rust~0.36.2/rust/defs.bzl" ); let (repo_name, relative_path) = workspace.get_repository_for_path(&file).unwrap(); assert_eq!(repo_name, "rules_rust~0.36.2"); assert_eq!(relative_path, std::path::Path::new("rust/defs.bzl")); ``` -------------------------------- ### Autocomplete Suggestions for String Literals and Load Paths Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Provides autocomplete suggestions for repository names, directories within repositories, and Bazel build targets. Ensure the correct `StringCompletionType` is used for the desired suggestions. ```rust use starlark_lsp::server::{LspContext, LspUrl}; use starlark_lsp::completion::{StringCompletionResult, StringCompletionType}; use lsp_types::CompletionItemKind; let fixture = TestFixture::new("simple").unwrap(); // Complete repository names (prefix "@") let ctx = fixture.context().unwrap(); let completions = ctx.get_string_completion_options( &LspUrl::File(fixture.workspace_root().join("BUILD")), StringCompletionType::String, "@", Some(&fixture.workspace_root()), ).unwrap(); // Returns @foo, @bar, etc. with insert_text "@foo//" // Complete directories inside a repository let completions = ctx.get_string_completion_options( &LspUrl::File(fixture.workspace_root().join("BUILD")), StringCompletionType::LoadPath, "@rules_rust//", Some(&fixture.workspace_root()), ).unwrap(); assert_eq!(completions[0], StringCompletionResult { value: "rust".into(), insert_text: Some("rust".into()), insert_text_offset: "@rules_rust//".len(), kind: CompletionItemKind::FOLDER, }); // Complete build targets using `bazel query //foo:*` let ctx = fixture.context_builder().unwrap() .query("//foo:*", "//foo:main\n") .build().unwrap(); let completions = ctx.get_string_completion_options( &LspUrl::File(fixture.workspace_root().join("BUILD")), StringCompletionType::String, "//foo:", Some(&fixture.workspace_root()), ).unwrap(); let target = completions.iter().find(|c| c.value == "main").unwrap(); assert_eq!(*target, StringCompletionResult { value: "main".into(), insert_text: Some("main".into()), insert_text_offset: "//foo:".len(), kind: CompletionItemKind::PROPERTY, }); ``` -------------------------------- ### VSCode Equivalent Logging Configuration Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Configure Rust logging levels within VSCode settings.json for the Bazel LSP extension. ```jsonc // Equivalent VSCode settings.json configuration { "bazel.lsp.env": { "RUST_LOG": "bazel_lsp=debug,starlark_lsp=warn" } } ``` -------------------------------- ### Configure Bazel VSCode Extension Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Configure the Bazel VSCode extension to use the bazel-lsp binary. You can specify the command, pass extra arguments, and set environment variables for logging. ```jsonc // settings.json { // Point the Bazel extension to the bazel-lsp binary "bazel.lsp.command": "bazel-lsp", // Optional: pass extra flags to the LSP server "bazel.lsp.args": ["--query-output-base", "/tmp/bazel-lsp-queries"], // Optional: enable structured logging "bazel.lsp.env": { "RUST_LOG": "info" } } ``` -------------------------------- ### String Literal and Load Path Autocompletion Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Provides autocomplete suggestions for string literals and Bazel load paths. It handles repository names, directory completions, and Bazel build targets based on the `StringCompletionType` and the current input string. ```APIDOC ## `LspContext::get_string_completion_options` ### Description Returns a list of `StringCompletionResult` items for the partial string the user is currently typing. This method supports autocompletion for repository names, directories, and Bazel build targets. ### Method ```rust fn get_string_completion_options( &self, file_url: &LspUrl, completion_type: StringCompletionType, partial_string: &str, workspace_root: Option<&PathBuf>, ) -> Result> ``` ### Parameters #### `file_url` (LspUrl) - Required - The URL of the file where the completion is requested. #### `completion_type` (StringCompletionType) - Required - Specifies the type of completion: `StringCompletionType::LoadPath` for `.bzl` files or `StringCompletionType::String` for general string completions including build targets. #### `partial_string` (&str) - Required - The partial string the user is currently typing, used to filter suggestions. #### `workspace_root` (Option<&PathBuf>) - Optional - The root path of the workspace, used for context in completions. ### Request Example ```rust // Complete repository names (prefix "@") let completions = ctx.get_string_completion_options( &LspUrl::File(fixture.workspace_root().join("BUILD")), StringCompletionType::String, "@", Some(&fixture.workspace_root()), ).unwrap(); // Returns @foo, @bar, etc. with insert_text "@foo//" // Complete directories inside a repository let completions = ctx.get_string_completion_options( &LspUrl::File(fixture.workspace_root().join("BUILD")), StringCompletionType::LoadPath, "@rules_rust//", Some(&fixture.workspace_root()), ).unwrap(); // Complete build targets using `bazel query //foo:*` let completions = ctx.get_string_completion_options( &LspUrl::File(fixture.workspace_root().join("BUILD")), StringCompletionType::String, "//foo:", Some(&fixture.workspace_root()), ).unwrap(); ``` ### Response - Returns a `Vec` containing suggested completions. ``` -------------------------------- ### Enable Bazel LSP Logging in VSCode Source: https://github.com/cameron-martin/bazel-lsp/blob/master/README.md Configure the RUST_LOG environment variable within VSCode settings to enable logging for Bazel LSP. Use 'info' for general logging. ```json { "bazel.lsp.env": { "RUST_LOG": "info" }, } ``` -------------------------------- ### Abstracting Bazel CLI Invocations for Testability Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Demonstrates the `BazelClient` trait for abstracting Bazel CLI commands, with `BazelCli` for production and `MockBazel` for testing. `ProfilingClient` can wrap any client to count invocations. ```rust // Production: BazelCli shells out to bazel use bazel_lsp::client::BazelCli; let client = BazelCli::new("bazel"); // client.info(workspace_root) -> runs: bazel info // client.query(workspace, "//...") -> runs: bazel query //... // client.build_language(workspace) -> runs: bazel info build-language // client.dump_repo_mapping(ws, "") -> runs: bazel mod dump_repo_mapping "" // Testing: MockBazel with fixture-based workspace layout use bazel_lsp::test_fixture::TestFixture; let fixture = TestFixture::new("simple").unwrap(); // Build a context with a canned query response let ctx = fixture.context_builder().unwrap() .query("//foo:*", "//foo:main\n//foo:main_test\n") .repo_mapping_json("", serde_json::json!({ "": "", "rules_rust": "rules_rust~0.36.2", })).unwrap() .build().unwrap(); // ProfilingClient wraps any BazelClient to count invocations in tests assert_eq!(ctx.client.profile.borrow().query, 0); // ... after LSP operations that trigger queries: // assert_eq!(ctx.client.profile.borrow().query, 1); ``` -------------------------------- ### Configure VSCode for Bazel LSP Source: https://github.com/cameron-martin/bazel-lsp/blob/master/README.md Add this configuration to your VSCode user settings.json to specify the bazel-lsp command. ```json { "bazel.lsp.command": "bazel-lsp" } ``` -------------------------------- ### Enabling diagnostic logging via RUST_LOG Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Bazel LSP uses the `tracing_subscriber` crate for logging, with all output directed to stderr. Diagnostic logging can be enabled by setting the `RUST_LOG` environment variable. ```APIDOC ## Logging ### Enabling diagnostic logging via RUST_LOG Bazel LSP uses the `tracing_subscriber` crate; all log output is written to stderr. ```sh # Log all INFO-level messages RUST_LOG=info bazel-lsp # Enable DEBUG logs only for the bazel_lsp crate RUST_LOG=bazel_lsp=debug bazel-lsp # Multiple directives (comma-separated) RUST_LOG=bazel_lsp=debug,starlark_lsp=warn bazel-lsp ``` ```jsonc // Equivalent VSCode settings.json configuration { "bazel.lsp.env": { "RUST_LOG": "bazel_lsp=debug,starlark_lsp=warn" } } ``` ``` -------------------------------- ### LspContext::resolve_load Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Resolving a load() label to an absolute file URL. Converts a label string from a `load()` statement into an `LspUrl::File` pointing to the actual file on disk. Handles relative labels (`:foo.bzl`), workspace-absolute labels (`//pkg:foo.bzl`), external repository labels (`@repo//pkg:foo.bzl`), and Bzlmod canonical labels (`@@repo~version//pkg:foo.bzl`). Falls back to finding a BUILD file in the package directory if the target file does not exist. ```APIDOC ## `LspContext::resolve_load` ### Description Resolving a load() label to an absolute file URL. Converts a label string from a `load()` statement into an `LspUrl::File` pointing to the actual file on disk. Handles relative labels (`:foo.bzl`), workspace-absolute labels (`//pkg:foo.bzl`), external repository labels (`@repo//pkg:foo.bzl`), and Bzlmod canonical labels (`@@repo~version//pkg:foo.bzl`). Falls back to finding a BUILD file in the package directory if the target file does not exist. ### Method `LspContext::resolve_load` ### Parameters #### Path Parameters - **label** (`&str`) - The label string from a `load()` statement. - **current_file** (`&LspUrl`) - The URL of the file containing the `load()` statement. - **workspace_root** (`Option<&Path>`) - The path to the workspace root, if available. ### Response - **Ok(LspUrl)** - The resolved `LspUrl::File` for the label. - **Err(anyhow::Error)** - An error if the label could not be resolved. ``` -------------------------------- ### Exposing Bazel Global Symbols Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Retrieves a `DocModule` containing all global symbols available in a given file. This includes Bazel build rules and Starlark built-ins, with specific exclusions for BUILD-file-only functions in `.bzl` environments. ```APIDOC ## `LspContext::get_environment` ### Description Returns a `DocModule` containing all global symbols available in a given file. This method sources symbols from `bazel info build-language` and a bundled builtins proto, excluding BUILD-file-only functions from `.bzl` environments. ### Method ```rust fn get_environment(&self, file_url: &LspUrl) -> DocModule ``` ### Parameters #### `file_url` (LspUrl) - Required - The URL of the file for which to retrieve the environment symbols. ### Response - Returns a `DocModule` which contains the global symbols available in the specified file. ### Request Example ```rust let bzl_env = ctx.get_environment(&LspUrl::File(PathBuf::from("/foo/bar.bzl"))); // `glob` is not available in .bzl files assert!(!has_member(&bzl_env, "glob")); // `range` and `cc_library` are available assert!(has_member(&bzl_env, "range")); assert!(has_member(&bzl_env, "cc_library")); let build_env = ctx.get_environment(&LspUrl::File(PathBuf::from("/foo/BUILD"))); // `glob` is available in BUILD files assert!(has_member(&build_env, "glob")); ``` ``` -------------------------------- ### Exposing Bazel Global Symbols for Autocomplete and Linting Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Retrieves a `DocModule` containing global symbols for a given file. BUILD files include additional symbols like `glob` compared to `.bzl` files. ```rust use starlark_lsp::server::{LspContext, LspUrl}; use std::path::PathBuf; let fixture = TestFixture::new("simple").unwrap(); let ctx = fixture.context().unwrap(); let has_member = |module: &starlark::docs::DocModule, name: &str| { module.members.iter().any(|(k, _)| k == name) }; // In a .bzl file: no glob, but range and cc_library are available let bzl_env = ctx.get_environment(&LspUrl::File(PathBuf::from("/foo/bar.bzl"))); assert!(!has_member(&bzl_env, "glob")); assert!(has_member(&bzl_env, "range")); assert!(has_member(&bzl_env, "cc_library")); // In a BUILD file: glob is additionally available let build_env = ctx.get_environment(&LspUrl::File(PathBuf::from("/foo/BUILD"))); assert!(has_member(&build_env, "glob")); assert!(has_member(&build_env, "range")); assert!(has_member(&build_env, "cc_library")); ``` -------------------------------- ### Parse and Lint Starlark/BUILD Files Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Parses Starlark/BUILD file content with extended dialect and runs Bazel-aware linting. Detects undefined globals and misplaced loads. Produces AST and LSP diagnostics. ```rust use starlark_lsp::server::{LspContext, LspUrl}; use std::path::PathBuf; // In tests, use a TestFixture to get a BazelContext backed by a MockBazel let fixture = TestFixture::new("simple").unwrap(); let ctx = fixture.context().unwrap(); // Simulate editing a .bzl file with an undefined global let result = ctx.parse_file_with_contents( &LspUrl::File(PathBuf::from("/foo.bzl")), r#" test_suite(name = 'my_suite') unknown_global_function(42) # <- undefined a = int(7) register_toolchains([':my_toolchain']) "#.to_string(), ); // One diagnostic: use of undefined variable assert_eq!(result.diagnostics.len(), 1); assert_eq!( result.diagnostics[0].message, "Use of undefined variable `unknown_global_function`" ); assert!(result.ast.is_some()); // AST is still produced for valid parses // BUILD files: misplaced-load lint fires (load() must be at top) let result = ctx.parse_file_with_contents( &LspUrl::File(PathBuf::from("/BUILD")), "test_suite(name='t'); load('foo.bzl', 'bar')".to_string(), ); assert!(result.diagnostics.iter().any(|d| { matches!(&d.code, Some(lsp_types::NumberOrString::String(s)) if s == "misplaced-load") })); // WORKSPACE files: misplaced-load lint is suppressed let result = ctx.parse_file_with_contents( &LspUrl::File(PathBuf::from("/WORKSPACE")), "test_suite(name='t'); load('foo.bzl', 'bar')".to_string(), ); assert!(result.diagnostics.iter().all(|d| { !matches!(&d.code, Some(lsp_types::NumberOrString::String(s)) if s == "misplaced-load") })); ``` -------------------------------- ### Parsing and linting a Starlark/BUILD file Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Called by the LSP server whenever a document is opened or changed. Parses the content with the extended Starlark dialect, runs Bazel-aware linting (including undefined global symbol detection and misplaced-load checks), and returns both the AST and LSP diagnostics. ```APIDOC ## Parsing and linting a Starlark/BUILD file ### Description Called by the LSP server whenever a document is opened or changed. Parses the content with the extended Starlark dialect, runs Bazel-aware linting (including undefined global symbol detection and misplaced-load checks), and returns both the AST and LSP diagnostics. ### Method `LspContext::parse_file_with_contents` ### Parameters #### Path Parameters - **url** (`LspUrl`) - The URL of the file being parsed. - **contents** (`String`) - The content of the file. ### Response - **diagnostics** (`Vec`) - A list of LSP diagnostics found in the file. - **ast** (`Option>`) - The Abstract Syntax Tree of the parsed file, if parsing was successful. ``` -------------------------------- ### Enable Diagnostic Logging via RUST_LOG Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Configure Rust logging levels for Bazel LSP and its dependencies using the RUST_LOG environment variable. Output is written to stderr. ```sh # Log all INFO-level messages RUST_LOG=info bazel-lsp ``` ```sh # Enable DEBUG logs only for the bazel_lsp crate RUST_LOG=bazel_lsp=debug bazel-lsp ``` ```sh # Multiple directives (comma-separated) RUST_LOG=bazel_lsp=debug,starlark_lsp=warn bazel-lsp ``` -------------------------------- ### Resolve load() Label to File URL Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Converts load() statement labels to absolute file URLs, supporting relative, workspace-absolute, external repository, and Bzlmod canonical labels. Falls back to BUILD files if the target doesn't exist. ```rust use starlark_lsp::server::{LspContext, LspUrl}; use lsp_types::Url; let fixture = TestFixture::new("simple").unwrap(); let ctx = fixture.context().unwrap(); // Resolve a workspace-absolute label from a file in an external repo let url = ctx.resolve_load( "//:foo.bzl", &LspUrl::File(fixture.external_dir("foo").join("BUILD")), None, ).unwrap(); assert_eq!( url, Url::from_file_path(fixture.external_dir("foo").join("foo.bzl")) .unwrap().try_into().unwrap() ); // Resolve an external repo label from the workspace root let url = ctx.resolve_load( "@foo//:foo.bzl", &LspUrl::File(fixture.workspace_root().join("BUILD")), Some(&fixture.workspace_root()), ).unwrap(); assert_eq!( url, Url::from_file_path(fixture.external_dir("foo").join("foo.bzl")) .unwrap().try_into().unwrap() ); // Bzlmod: resolve with repo mapping applied let fixture = TestFixture::new("bzlmod").unwrap(); let ctx = fixture.context_builder().unwrap() .repo_mapping_json("", serde_json::json!({ "": "", "rules_rust": "rules_rust~0.36.2", })).unwrap() .build().unwrap(); let url = ctx.resolve_load( "@rules_rust//rust:defs.bzl", &LspUrl::File(fixture.workspace_root().join("BUILD")), Some(&fixture.workspace_root()), ).unwrap(); assert_eq!( url, Url::from_file_path( fixture.external_dir("rules_rust~0.36.2").join("rust").join("defs.bzl") ).unwrap().try_into().unwrap() ); ``` -------------------------------- ### Classify Bazel File Types Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Use `FileType::from_path` to classify paths as Build, Library, or Unknown. This is crucial for determining symbol visibility in the LSP environment. ```rust use bazel_lsp::file_type::FileType; use std::path::Path; // BUILD files assert_eq!(FileType::from_path(Path::new("/workspace/foo/BUILD")), FileType::Build); assert_eq!(FileType::from_path(Path::new("/workspace/foo/BUILD.bazel")), FileType::Build); // .bzl library files assert_eq!(FileType::from_path(Path::new("/workspace/foo/defs.bzl")), FileType::Library); assert_eq!(FileType::from_path(Path::new("rules.bzl")), FileType::Library); // Other files (MODULE.bazel, WORKSPACE, .rs, etc.) assert_eq!(FileType::from_path(Path::new("/workspace/MODULE.bazel")), FileType::Unknown); assert_eq!(FileType::from_path(Path::new("/workspace/WORKSPACE")), FileType::Unknown); assert_eq!(FileType::from_path(Path::new("main.rs")), FileType::Unknown); ``` -------------------------------- ### Bazel Client Abstraction Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt The `BazelClient` trait abstracts Bazel CLI invocations, allowing for different implementations like `BazelCli` (production) and `MockBazel` (testing). It defines methods for common Bazel operations. ```APIDOC ## `BazelClient` Trait ### Description An interface for abstracting Bazel CLI invocations, enabling testability through different implementations. The production implementation (`BazelCli`) interacts with the `bazel` binary, while testing implementations like `MockBazel` use pre-registered responses. ### Methods (Examples) - `info(workspace_root: &Path)`: Runs `bazel info`. - `query(workspace: &Path, query: &str)`: Runs `bazel query`. - `build_language(workspace: &Path)`: Runs `bazel info build-language`. - `dump_repo_mapping(ws: &Path, filter: &str)`: Runs `bazel mod dump_repo_mapping`. ### Request Example (Production) ```rust use bazel_lsp::client::BazelCli; let client = BazelCli::new("bazel"); // Example invocation: // client.info(workspace_root) ``` ### Request Example (Testing) ```rust use bazel_lsp::test_fixture::TestFixture; let fixture = TestFixture::new("simple").unwrap(); // Build a context with a canned query response let ctx = fixture.context_builder().unwrap() .query("//foo:*", "//foo:main\n//foo:main_test\n") .repo_mapping_json("", serde_json::json!({ "": "", "rules_rust": "rules_rust~0.36.2", })).unwrap() .build().unwrap(); // ProfilingClient wraps any BazelClient to count invocations in tests // assert_eq!(ctx.client.profile.borrow().query, 0); // ... after LSP operations that trigger queries: // assert_eq!(ctx.client.profile.borrow().query, 1); ``` ``` -------------------------------- ### Label::parse Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Parses a Bazel label string into a structured `Label` object. This method handles various label formats, including canonical and non-canonical repository prefixes, absolute and relative labels, and implicit target names. ```APIDOC ## Label Parsing (`Label::parse`) ### Parsing Bazel labels into structured components `Label::parse` converts a Bazel label string into a `Label` struct with optional `repo` (`LabelRepo`), optional `package`, and a `name`. It supports canonical (`@@repo`) and non-canonical (`@repo`) repository prefixes, absolute (`//pkg:target`) and relative (`:target`, `target`) labels, and implicit target names derived from the last package path segment. ```rust use bazel_lsp::label::{Label, LabelRepo}; // Absolute label with explicit target name let label = Label::parse("@rules_rust//rust:defs.bzl").unwrap(); assert_eq!(label.repo.as_ref().unwrap().name, "rules_rust"); assert_eq!(label.repo.as_ref().unwrap().is_canonical, false); assert_eq!(label.package.as_deref(), Some("rust")); assert_eq!(label.name, "defs.bzl"); // Canonical repository label (Bzlmod) let label = Label::parse("@@rules_rust~0.36.2//rust:defs.bzl").unwrap(); assert_eq!(label.repo.as_ref().unwrap().is_canonical, true); // Implicit name from package path let label = Label::parse("//foo/bar").unwrap(); assert_eq!(label.package.as_deref(), Some("foo/bar")); assert_eq!(label.name, "bar"); // derived from last segment // Relative (name-only) label let label = Label::parse(":my_lib").unwrap(); assert!(label.repo.is_none()); assert!(label.package.is_none()); assert_eq!(label.name, "my_lib"); // Display round-trips correctly assert_eq!(format!("{}", Label::parse("@foo//bar/baz:qux").unwrap()), "@foo//bar/baz:qux"); assert_eq!(format!("{}", Label::parse("//foo/bar").unwrap()), "//foo/bar:bar"); // Invalid label returns an error assert!(Label::parse("foo//bar/baz").is_err()); ``` ``` -------------------------------- ### Parse Bazel Labels in Rust Source: https://context7.com/cameron-martin/bazel-lsp/llms.txt Use the `Label::parse` function in Rust to convert Bazel label strings into structured `Label` objects. This handles various label formats, including canonical and non-canonical repositories, and implicit target names. ```rust use bazel_lsp::label::{Label, LabelRepo}; // Absolute label with explicit target name let label = Label::parse("@rules_rust//rust:defs.bzl").unwrap(); assert_eq!(label.repo.as_ref().unwrap().name, "rules_rust"); assert_eq!(label.repo.as_ref().unwrap().is_canonical, false); assert_eq!(label.package.as_deref(), Some("rust")); assert_eq!(label.name, "defs.bzl"); // Canonical repository label (Bzlmod) let label = Label::parse("@@rules_rust~0.36.2//rust:defs.bzl").unwrap(); assert_eq!(label.repo.as_ref().unwrap().is_canonical, true); // Implicit name from package path let label = Label::parse("//foo/bar").unwrap(); assert_eq!(label.package.as_deref(), Some("foo/bar")); assert_eq!(label.name, "bar"); // derived from last segment // Relative (name-only) label let label = Label::parse(":my_lib").unwrap(); assert!(label.repo.is_none()); assert!(label.package.is_none()); assert_eq!(label.name, "my_lib"); // Display round-trips correctly assert_eq!(format!("{}", Label::parse("@foo//bar/baz:qux").unwrap()), "@foo//bar/baz:qux"); assert_eq!(format!("{}", Label::parse("//foo/bar").unwrap()), "//foo/bar:bar"); // Invalid label returns an error assert!(Label::parse("foo//bar/baz").is_err()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.