### Run Conan indexer with install and output flags Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/cli-binaries.md Runs conan profile detect and conan install . --build=missing before indexing, then invokes the Conan indexer with --output and --install flags. The --install flag triggers the conan commands; failure of conan profile detect is tolerated, but failure of conan install is fatal. ```bash conan profile detect conan install . --build=missing bazel run @gazelle_cc//index/conan -- --output=conan.ccindex --install ``` -------------------------------- ### Example: ResolveModuleInfo with error handling Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Shows how to create a config, checkout the registry, resolve a module, and handle the result. Uses 'fmt' version '11.1.4' as an example. ```go cfg := bcr.NewBazelRegistryConfig() client, err := bcr.CheckoutBazelRegistry(cfg) if err != nil { log.Fatalf("checkout failed: %v", err) } result := client.ResolveModuleInfo("fmt", "11.1.4") if result.IsResolved() { fmt.Printf("resolved %d targets for %s\n", len(result.Info.Targets), result.Info.Module) } else { fmt.Printf("unresolved: %s (%s)\n", result.Unresolved.Module, result.Unresolved.Reason) } ``` -------------------------------- ### Example: WriteToFile with error handling Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/indexer.md Shows how to create a header index and write it to a file, handling errors with log.Fatalf. The example writes to 'deps.ccindex'. ```go result := indexer.CreateHeaderIndex(modules) if err := result.WriteToFile("deps.ccindex"); err != nil { log.Fatalf("failed to write index: %v", err) } ``` -------------------------------- ### Create platform example with error handling Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/platform.md Shows basic usage of `platform.Create` with a valid platform, an alias, and an unknown OS that returns an error. The example prints `linux/x86_64` and demonstrates that `macos`/`amd64` maps to `{osx, x86_64}`, while `beos` causes a non-nil error. ```go p, err := platform.Create(platform.OS("linux"), platform.Arch("x86_64")) if err != nil { log.Fatal(err) } fmt.Println(p) // linux/x86_64 // Alias accepted: p2, err := platform.Create(platform.OS("macos"), platform.Arch("amd64")) // p2 == {osx, x86_64} // Unknown OS -> error: _, err = platform.Create(platform.OS("beos"), platform.Arch("x86_64")) // err != nil ``` -------------------------------- ### Example: Query and GetNamedAttribute usage Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Example showing how to run a bazel query for cc_library targets and retrieve the 'hdrs' attribute from each target. The result is a *proto.Attribute. ```go result, err := bazel.Query(workdir, "kind(cc_library, //...:*)") if err != nil { return err } for _, t := range result.GetTarget() { hdrs := bazel.GetNamedAttribute(t, "hdrs") _ = hdrs // *proto.Attribute } ``` -------------------------------- ### ParseSource basic usage example Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/parser.md Example of parsing a C/C++ source string with includes and conditional guards, then collecting includes and checking HasMain. ```go src := []byte(` #include #ifdef __APPLE__ #include "apple.h" #else #include "unix.h" #endif int main() { return 0; } `) info := parser.ParseSource(src) includes := info.CollectIncludes() for _, inc := range includes { fmt.Printf("path=%q system=%v line=%d\n", inc.Path, inc.IsSystem, inc.LineNumber) } // info.HasMain == true ``` -------------------------------- ### ParseSourceFile error handling example Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/parser.md Example of reading a source file, handling read errors, and printing parse issues from the returned SourceInfo. ```go info, err := parser.ParseSourceFile("src/foo.cc") if err != nil { log.Fatalf("could not read source file: %v", err) } for _, parseErr := range info.Errors { fmt.Printf("parse issue: %v\n", parseErr) } ``` -------------------------------- ### Set basic example Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/collections.md Demonstrates creating a set, adding elements, joining with another set, and using `Contains` and `Diff` with `SortedValues`. ```go s := collections.SetOf("a", "b", "c") s.Add("d").Join(collections.SetOf("b", "e")) fmt.Println(s.Contains("e")) // true fmt.Println(s.Diff(collections.SetOf("a")).SortedValues(strings.Compare)) // [b c d e] ``` -------------------------------- ### Basic lexer usage example Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/lexer.md Creates a lexer for a simple C/C++ source string and iterates over all tokens, printing each token's type, location, and content. ```go lx := lexer.NewLexer([]byte("#include \nint x = 1;\n")) for tok := range lx.AllTokens() { fmt.Printf("%v at %v: %q\n", tok.Type, tok.Location, tok.Content) } ``` -------------------------------- ### Example PR titles Source: https://github.com/engflow/gazelle_cc/blob/main/CONTRIBUTING.md Example PR titles that start with a topic or package name followed by a colon and more information. Use descriptive titles for pull requests. ```text language/cc: support Plan 9 style tests. docs: convert documentation to LaTeX ``` -------------------------------- ### ParseMacros usage example Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/parser.md Example of parsing macro definitions, handling errors, and noting that invalid definitions are skipped. ```go env, err := parser.ParseMacros([]string{"USING_MAC", "USING_ARM64=1", "FOO=notanint"}) if err != nil { fmt.Println("some definitions failed:", err) } // env == {"USING_MAC":1, "USING_ARM64":1, "FOO": ...} (FOO skipped) ``` -------------------------------- ### Example: WithAmbiguousTargetsResolved usage Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/indexer.md Shows how to create a module with ambiguous targets and resolve them. The example creates a module with two targets that share a common header and then calls WithAmbiguousTargetsResolved. ```go module := indexer.Module{ Repository: "conan", Targets: []indexer.Target{ {Name: label.New("conan", "pkg/a", "a"), Hdrs: setOf("common.h", "a.h")}, {Name: label.New("conan", "pkg/b", "b"), Hdrs: setOf("common.h", "b.h")}, }, } resolved := module.WithAmbiguousTargetsResolved() ``` -------------------------------- ### Functional utilities example Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/collections.md Shows using `FilterSlice` and `MapSlice` to filter even numbers and double them, and `FilterMapSlice` to parse strings while dropping failures. ```go nums := []int{1, 2, 3, 4} evens := collections.FilterSlice(nums, func(n int) bool { return n%2 == 0 }) doubled := collections.MapSlice(evens, func(n int) int { return n * 2 }) // doubled == [4, 8] // FilterMapSlice drops failures: parsed := collections.FilterMapSlice([]string{"1", "x", "3"}, strconv.Atoi) // parsed == [1, 3] ``` -------------------------------- ### cc_library with strip_include_prefix and include_prefix Source: https://github.com/engflow/gazelle_cc/blob/main/README.md Example of a cc_library target with header file in inc/foo.h, using strip_include_prefix and include_prefix to map include path foo/foo.h to third_party/foo/inc/foo.h. ```bzl cc_library( name = "foo", hdrs = ["inc/foo.h"], strip_include_prefix = "third_party/foo/inc", include_prefix = "foo", visibility = ["//visibility:public"], ) ``` -------------------------------- ### WORKSPACE setup for gazelle_cc Source: https://github.com/engflow/gazelle_cc/blob/main/docs/workspace_setup.md This snippet shows the complete WORKSPACE configuration needed to use gazelle_cc. It loads rules_go and gazelle, registers the Go toolchain, and then adds gazelle_cc with a repo_mapping to adjust dependency names for WORKSPACE. The repo_mapping is required because gazelle_cc uses bzlmod naming conventions by default. ```bazel load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "io_bazel_rules_go", integrity = "sha256-t493RY53Fi9FtFZNayC2+S9WQx7VnqqrCeeBnR2FAxM=", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.53.0/rules_go-v0.53.0.zip", "https://github.com/bazelbuild/rules_go/releases/download/v0.53.0/rules_go-v0.53.0.zip", ], ) http_archive( name = "bazel_gazelle", integrity = "sha256-fEC3Rjh80Mmk1bsLIDWr0TSz91EQFXEKXuXgdZEAjd4=", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.43.0/bazel-gazelle-v0.43.0.tar.gz", "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.43.0/bazel-gazelle-v0.43.0.tar.gz", ], ) load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies") go_rules_dependencies() go_register_toolchains(version = "1.24.0") gazelle_dependencies(go_sdk = "go_sdk") http_archive( name = "gazelle_cc", sha256 = "8e990e454b06c529e383239e0692a1f17b003e3e7a5a0f967ee5f6aeb400105a", strip_prefix = "gazelle_cc-0.1.0", url = "https://github.com/EngFlow/gazelle_cc/releases/download/v0.1.0/gazelle_cc-v0.1.0.tar.gz", repo_mapping = { "@rules_go": "@io_bazel_rules_go", "@gazelle": "@bazel_gazelle", }, ) load("@gazelle_cc//:deps.bzl", "gazelle_cc_dependencies") gazelle_cc_dependencies() ``` -------------------------------- ### Generate Conan index with @gazelle_cc//index/conan Source: https://github.com/engflow/gazelle_cc/blob/main/README.md Commands to create a Conan index: detect profile, install dependencies, and run the index generator. The output file is specified with --output. ```bash conan profile detect conan install . --build=missing bazel run @gazelle_cc//index/conan -- --output=conan.ccindex ``` -------------------------------- ### DependencyIndex JSON marshal/unmarshal example Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/collections.md Shows how to marshal a `DependencyIndex` to JSON and unmarshal it back. The JSON format is an object keyed by header path with arrays of label strings. Invalid labels cause unmarshal to fail. ```go idx := index.DependencyIndex{ "gtest/gtest.h": {label.New("googletest", "", "gtest")}, } data, _ := json.Marshal(idx) // {"gtest/gtest.h":["@googletest//:gtest"]} var decoded index.DependencyIndex _ = json.Unmarshal(data, &decoded) ``` -------------------------------- ### gazelle:cc_platform directive example Source: https://github.com/engflow/gazelle_cc/blob/main/README.md Shows how to configure platform-specific header dependencies using the cc_platform directive. The BUILD.bazel file declares two platforms: windows x86_64 and osx aarch64 with optional macros. The source.cc file uses preprocessor conditions to include different headers based on platform. Running gazelle_cc emits a cc_library rule with a select() statement mapping each platform to its corresponding implementation dependency. ```bazel # BUILD.bazel # gazelle:cc_platform windows x86_64 @platforms//os:windows # gazelle:cc_platform osx aarch64 //platforms/macos_arm USING_MAC USING_ARM64=1 ``` ```c // source.cc #include "shared.h" #if defined(_WIN32) #include "win_impl.h" #elif USING_MAC #include "mac_impl.h" #else #include "unix_impl.h" #endif ``` ```bazel cc_library( name = "source", srcs = ["source.cc"], implementation_deps = [":shared"] + select({ "@platforms//os:windows": [":win_impl"], "//platforms:macos_arm": [":mac_impl"], "//conditions:default": [":unix_impl"], }) ) ``` -------------------------------- ### NewLexer function signature Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/lexer.md Creates a lexer positioned at the start of the provided source code, with the cursor initialized to `CursorInit`. ```go func NewLexer(sourceCode []byte) *Lexer ``` -------------------------------- ### Platform String method Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/platform.md Renders a `Platform` as a string in the format `"/"`, e.g., `"linux/x86_64"`. ```go func (p Platform) String() string ``` -------------------------------- ### Configure method signature Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/language-cc.md Creates or clones the per-directory ccConfig, parses every # gazelle:cc_* directive, and records rel into buildFileDirRels. ```go func (c *ccLanguage) Configure(config *config.Config, rel string, f *rule.File) ``` -------------------------------- ### func NewLexer(sourceCode []byte) *Lexer Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/lexer.md Creates a lexer positioned at the start of the given source code. ```APIDOC ## NewLexer ### Description Creates a lexer positioned at the start of `sourceCode` (cursor `CursorInit`). ### Signature ```go func NewLexer(sourceCode []byte) *Lexer ``` ### Parameters - **sourceCode** ([]byte) - Required - The source code to tokenize. ### Returns - **\*Lexer** - A new lexer instance. ``` -------------------------------- ### Compare platforms function Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/platform.md Orders two `Platform` values first by `OS`, then by `Arch`, using string ordering. ```go func Compare(a, b Platform) int ``` -------------------------------- ### Create platform with error handling Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/platform.md Constructs a `Platform` after de-aliasing both identifiers and validating them against known sets. Returns an error for unknown OS or arch. Aliases include `"macos" -> osx`, `"arm" -> aarch32`, `"arm64" -> aarch64`, `"amd64" -> x86_64`. ```go func Create(os OS, arch Arch) (Platform, error) ``` -------------------------------- ### Run Gazelle to generate BUILD files Source: https://github.com/engflow/gazelle_cc/blob/main/README.md Execute this command to run Gazelle, which scans C/C++ source files and generates appropriate cc_library, cc_proto_library, cc_binary, and cc_test rules with automatic dependency handling and visibility settings. ```bash bazel run //:gazelle ``` -------------------------------- ### Squash commits and force push for DCO Source: https://github.com/engflow/gazelle_cc/blob/main/CONTRIBUTING.md Example of squashing commit history into a single commit, appending the DCO sign-off, and force pushing. Use this if the DCO check fails on the PR branch. ```bash git rebase --interactive HEAD~3 # squash 3 commits, add Signed-off-by to commit message git push --force ``` -------------------------------- ### ModuleVersion struct and String method Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Represents a module name and version. Includes a String method. ```go type ModuleVersion struct { Name string `json:"name"` Version string `json:"version"` } func (m ModuleVersion) String() string ``` -------------------------------- ### Cursor type definition Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/lexer.md Defines the Cursor struct with Line and Column fields, along with the CursorInit and CursorEOF variables. CursorInit represents the starting position (line 1, column 1), and CursorEOF represents the end of input. ```go type Cursor struct { Line, Column int } var ( CursorInit = Cursor{Line: 1, Column: 1} CursorEOF = Cursor{} ) ``` -------------------------------- ### func Create(os OS, arch Arch) (Platform, error) Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/platform.md Constructs a Platform after de-aliasing both identifiers and validates them against known sets. Returns an error for unknown OS or arch values. ```APIDOC ## func Create(os OS, arch Arch) (Platform, error) ### Description Constructs a `Platform` after de-aliasing both identifiers, and validates them against the known sets. Returns an error for unknown OS or arch values. ### Method Create ### Parameters #### Input Parameters - **os** (OS) - Required - The operating system identifier, e.g., `"linux"`, `"macos"` (alias for `osx`). - **arch** (Arch) - Required - The architecture identifier, e.g., `"x86_64"`, `"amd64"` (alias for `x86_64`). ### Returns - **Platform** - The constructed platform with de-aliased OS and arch. - **error** - Non-nil if the OS is not in `allKnownOs` (and not an alias) or the arch is not in `allKnownArch` (and not an alias). ### Aliases - `"macos"` -> `osx` - `"arm"` -> `aarch32` - `"arm64"` -> `aarch64` - `"amd64"` -> `x86_64` ### Example ```go p, err := platform.Create(platform.OS("linux"), platform.Arch("x86_64")) if err != nil { log.Fatal(err) } fmt.Println(p) // linux/x86_64 // Alias accepted: p2, err := platform.Create(platform.OS("macos"), platform.Arch("amd64")) // p2 == {osx, x86_64} // Unknown OS -> error: _, err = platform.Create(platform.OS("beos"), platform.Arch("x86_64")) // err != nil ``` ``` -------------------------------- ### OS and Arch type definitions Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/platform.md Defines the `OS` and `Arch` string types used by `Platform`. ```go type OS string type Arch string ``` -------------------------------- ### func (c *ccLanguage) Configure(config *config.Config, rel string, f *rule.File) Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/language-cc.md Configures the extension for a specific directory by parsing all # gazelle:cc_* directives in the given file. It creates or clones the per-directory ccConfig and stores it in config.Exts["cc"]. ```APIDOC ## func (c *ccLanguage) Configure(config *config.Config, rel string, f *rule.File) ### Description Configures the extension for a specific directory by parsing all `# gazelle:cc_*` directives in the given file. It creates or clones the per-directory `ccConfig` and stores it in `config.Exts["cc"]`. ### Method N/A (Go function) ### Signature ```go func (c *ccLanguage) Configure(config *config.Config, rel string, f *rule.File) ``` ### Parameters - **config** (*config.Config) - Required - The configuration object to mutate. - **rel** (string) - Required - The relative path of the directory. - **f** (*rule.File) - Required - The file containing directives. ### Returns Nothing. ### Directive Parsing Details - `selectDirectiveChoice[T ~string](target *T, options []T, d rule.Directive)` - Picks one of the allowed values for `cc_group`, `cc_group_unit_cycles`, `cc_ambiguous_deps`, `cc_unresolved_deps`, `cc_parsing_errors`. - `parseBoolDirective(target *bool, d rule.Directive)` - For `cc_generate`, `cc_generate_proto`, `cc_use_builtin_bzlmod_index`. - `parsePatternListDirective(patterns *[]string, key, value string)` - For the three `cc_group_subdirectory_*` patterns. - `cc_indexfile` - Loads a user index via `loadUserProvidedDependencyIndex`, resetting the list on an empty value. - `cc_search` - Parses `strip_include_prefix`/`include_prefix` pairs using `splitQuoted`, resetting to `defaultCcSearch()` on an empty value. - `cc_platform` - Builds `platform.Platform` entries plus optional macro definitions via `parser.ParseMacros`; an empty value resets the platform map. - `cc_include_prefix` / `cc_strip_include_prefix` - Stored verbatim as strings. ``` -------------------------------- ### NewBazelRegistryConfig function signature Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Returns a config with CacheDir defaulting to './.cache' in the current working directory. All other fields are zero-valued. ```go func NewBazelRegistryConfig() BazelRegistryConfig ``` -------------------------------- ### Run bzlmod indexer with --output flag Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/cli-binaries.md Runs the bzlmod indexer to create an index from bazel_dep directives in MODULE.bazel. The --output flag sets the output file path; the default is output.ccidx. On failure the binary exits non-zero via log.Fatalf. ```bash bazel run @gazelle_cc//index/bzlmod -- --output=bzlmod.ccidx ``` -------------------------------- ### ResolveWorkingDir and ResolveOutputFile helper signatures Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/cli-binaries.md Common helper functions from the index/internal/indexer/cli package. ResolveWorkingDir prefers --repository, then BUILD_WORKSPACE_DIRECTORY, then os.Getwd(). ResolveOutputFile resolves the --output path relative to the working directory if relative. Both log.Panic if flags have not been parsed yet. ```go func ResolveWorkingDir() (string, error) func ResolveOutputFile() string ``` -------------------------------- ### func (p Platform) String() string Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/platform.md Renders the platform as a string in the format "/", e.g., "linux/x86_64". ```APIDOC ## func (p Platform) String() string ### Description Renders the platform as a string in the format `"/"`, e.g., `"linux/x86_64"`. ### Method String ### Parameters #### Receiver - **p** (Platform) - Required - The platform to render. ### Returns - **string** - The string representation of the platform. ### Example ```go p := platform.Platform{OS: "linux", Arch: "x86_64"} fmt.Println(p.String()) // linux/x86_64 ``` ``` -------------------------------- ### Set constructors Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/collections.md Constructors for creating a `Set` from variadic elements, a slice, or a sequence. ```go func SetOf[T comparable](elems ...T) Set[T] func ToSet[T comparable](slice []T) Set[T] func CollectToSet[T comparable](seq iter.Seq[T]) Set[T] ``` -------------------------------- ### Generate bzlmod index with @gazelle_cc//index/bzlmod Source: https://github.com/engflow/gazelle_cc/blob/main/README.md Runs the bzlmod index generator to create a dedicated index file from MODULE.bazel bazel_dep directives. The output file is specified with --output. ```bash bazel run @gazelle_cc//index/bzlmod -- --output=bzlmod.ccindex ``` -------------------------------- ### NewLanguage() function signature Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/language-cc.md Declares the constructor for the cc language. Returns a language.Language that also implements config.Configurer, resolve.Resolver, and language.LifecycleManager. Eagerly loads the built-in Bazel Central Registry index. ```go func NewLanguage() language.Language ``` -------------------------------- ### String method signature Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/lexer.md Returns a human-readable description of the token type, such as `"directive '#include'"` or `"identifier"`. ```go func (t TokenType) String() string ``` -------------------------------- ### NewBazelRegistryConfig Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Returns a BazelRegistryConfig with default settings, including CacheDir set to './.cache' in the current working directory. ```APIDOC ## NewBazelRegistryConfig ### Description Returns a BazelRegistryConfig with CacheDir defaulting to './.cache' in the current working directory. All other fields are zero-valued. ### Method FUNCTION ### Endpoint NewBazelRegistryConfig() BazelRegistryConfig ### Parameters None ### Request Example N/A ### Response #### Success Response - **BazelRegistryConfig** - The configuration with default values. #### Response Example ```go cfg := bcr.NewBazelRegistryConfig() ``` ``` -------------------------------- ### func Query(cwd string, query string) (proto.QueryResult, error) Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Runs `bazel query` with `--output=proto` and `--incompatible_disallow_empty_glob=false`. Equivalent to `ConfiguredQuery(cwd, query, QueryConfig{KeepGoing: false})`. ```APIDOC ## func Query(cwd string, query string) (proto.QueryResult, error) ### Description Runs `bazel query` with `--output=proto` and `--incompatible_disallow_empty_glob=false`. Equivalent to `ConfiguredQuery(cwd, query, QueryConfig{KeepGoing: false})`. ### Parameters - **cwd** (string) - Required - The working directory in which to run the query. - **query** (string) - Required - The Bazel query expression to execute. ### Returns - **proto.QueryResult** - The parsed query result. - **error** - An error if the query fails. ``` -------------------------------- ### Define gazelle binary in BUILD.bazel Source: https://github.com/engflow/gazelle_cc/blob/main/README.md Defines a gazelle binary with the C++ language extension and a gazelle rule for CI integration. The proto language is optional and should be defined before cc. ```bazel load("@gazelle//:def.bzl", "gazelle", "gazelle_binary") # Define a gazelle binary with a list of enabled extensions gazelle_binary( name = "gazelle_cc", languages = [ "@gazelle//language/proto", # Optional, should be defined before cc "@gazelle_cc//language/cc", ], ) # `gazelle` rule can be used to provide additional arguments, eg. for CI integration gazelle( name = "gazelle", gazelle = ":gazelle_cc", ) ``` -------------------------------- ### func Compare(a, b Platform) int Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/platform.md Orders two platforms first by OS, then by Arch, using string ordering. Returns a negative integer, zero, or a positive integer as `a` is less than, equal to, or greater than `b`. ```APIDOC ## func Compare(a, b Platform) int ### Description Orders two platforms first by OS, then by Arch, using string ordering. Returns a negative integer, zero, or a positive integer as `a` is less than, equal to, or greater than `b`. ### Method Compare ### Parameters #### Input Parameters - **a** (Platform) - Required - The first platform to compare. - **b** (Platform) - Required - The second platform to compare. ### Returns - **int** - Negative if `a < b`, zero if `a == b`, positive if `a > b`. ### Example ```go // Assuming p1 and p2 are Platform values result := platform.Compare(p1, p2) ``` ``` -------------------------------- ### CreateHeaderIndex(modules []Module) IndexingResult Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/indexer.md Processes a list of modules into a single header-to-rule mapping. Each header is expanded into all valid #include paths and partitioned into unambiguous and ambiguous mappings. ```APIDOC ## CreateHeaderIndex(modules []Module) IndexingResult ### Description Processes a list of modules into a single header-to-rule mapping. Each header is expanded into all valid #include paths via IndexableIncludePaths, then partitioned into unambiguous (HeaderToRule) and ambiguous (Ambiguous) mappings. ### Method CreateHeaderIndex ### Signature func CreateHeaderIndex(modules []Module) IndexingResult ### Parameters - **modules** ([]Module) - Required - The list of modules to process. ### Returns - **IndexingResult** - The resulting header-to-rule mapping. ### Notes Expects intra-module ambiguity to already be resolved via WithAmbiguousTargetsResolved before being called. ``` -------------------------------- ### CheckoutBazelRegistry function signature Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Clones the Bazel Central Registry repository (depth 1) into the cache directory, or refreshes it if it already exists. Returns the registry and an error wrapping git failures. ```go func CheckoutBazelRegistry(config BazelRegistryConfig) (BazelRegistry, error) ``` -------------------------------- ### CheckoutBazelRegistry Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Clones or refreshes the Bazel Central Registry repository into the cache directory and returns a BazelRegistry client. ```APIDOC ## CheckoutBazelRegistry ### Description Clones https://github.com/bazelbuild/bazel-central-registry (depth 1) into /bazel-central-registry, or refreshes it if it already exists. Returns a BazelRegistry and error. ### Method FUNCTION ### Endpoint CheckoutBazelRegistry(config BazelRegistryConfig) (BazelRegistry, error) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (BazelRegistryConfig) - Required - Configuration for the registry checkout. ### Request Example ```go cfg := bcr.NewBazelRegistryConfig() client, err := bcr.CheckoutBazelRegistry(cfg) ``` ### Response #### Success Response - **BazelRegistry** - The registry client. - **error** - Error wrapping git failures (clone or refresh). #### Response Example ```go client, err := bcr.CheckoutBazelRegistry(cfg) if err != nil { log.Fatalf("checkout failed: %v", err) } ``` ``` -------------------------------- ### NextToken method signature Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/lexer.md Returns the next token from the remaining input, advancing the lexer state. Returns `TokenEOF` when no input remains. ```go func (lx *Lexer) NextToken() Token ``` -------------------------------- ### BazelRegistry and BazelRegistryConfig struct definitions Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/types.md Defines BazelRegistry and its configuration struct with fields for cache directory, verbosity, and source handling. ```go type BazelRegistry struct { Config BazelRegistryConfig RepositoryPath string httpClient http.Client } type BazelRegistryConfig struct { CacheDir string Verbose bool KeepSources bool RecomputeBad bool CacheBad bool } ``` -------------------------------- ### Set methods Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/collections.md Methods on `Set[T]` for adding, checking, joining, diffing, intersecting, and iterating. Methods like `Add`, `Join`, and `Diff` return the set for chaining. ```go func (s Set[T]) Add(elem T) Set[T] // insert, returns s func (s Set[T]) AddSeq(elems iter.Seq[T]) Set[T] func (s Set[T]) AddSlice(elems []T) Set[T] func (s Set[T]) Contains(elem T) bool func (s Set[T]) Join(other Set[T]) Set[T] // union, returns s func (s Set[T]) Diff(other Set[T]) Set[T] // elements in s not in other func (s Set[T]) Intersect(other Set[T]) Set[T] func (s Set[T]) Intersects(other Set[T]) bool // any common element func (s Set[T]) All() iter.Seq[T] // unordered func (s Set[T]) Values() []T // unordered slice func (s Set[T]) SortedValues(cmp func(l, r T) int) []T ``` -------------------------------- ### Cursor String method Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/lexer.md Renders the cursor position as a string. Returns "EOF" for CursorEOF, otherwise returns "line:column". ```go func (c Cursor) String() string ``` -------------------------------- ### func ConfiguredQuery(cwd string, query string, opts QueryConfig) (proto.QueryResult, error) Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Executes the query in `cwd`, unmarshalling the protobuf output into a `proto.QueryResult`. If the command fails with exit code other than 3 (no targets) and `KeepGoing` is false, the error is returned. ```APIDOC ## func ConfiguredQuery(cwd string, query string, opts QueryConfig) (proto.QueryResult, error) ### Description Executes the query in `cwd`, unmarshalling the protobuf output into a `proto.QueryResult`. If the command fails with exit code other than 3 (no targets) and `KeepGoing` is false, the error is returned. ### Parameters - **cwd** (string) - Required - The working directory in which to run the query. - **query** (string) - Required - The Bazel query expression to execute. - **opts** (QueryConfig) - Required - Configuration options for the query, including `KeepGoing`. ### Returns - **proto.QueryResult** - The parsed query result. - **error** - An error if the query fails. ``` -------------------------------- ### ResolveModuleInfo method signature Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/bcr.md Resolves a module's C++ targets for a given version. Empty version means latest non-yanked. Returns a ResolveModuleInfoResult. ```go func (bcr *BazelRegistry) ResolveModuleInfo(moduleName string, version string) ResolveModuleInfoResult ``` -------------------------------- ### Module struct definition Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/indexer.md Defines the Module type with Repository and Targets fields. Repository is the external repo name or empty string for same-repo targets. ```go type Module struct { Repository string // external repo name, or "" for same-repo targets Targets []Target } ``` -------------------------------- ### IndexableIncludePaths(header label.Label, target Target) []string Source: https://github.com/engflow/gazelle_cc/blob/main/_autodocs/api-reference/indexer.md Returns all possible #include paths under which the given header may be accessed when compiling against target, considering strip_include_prefix, include_prefix, and includes. ```APIDOC ## IndexableIncludePaths(header label.Label, target Target) []string ### Description Returns all possible #include paths under which the given header may be accessed when compiling against target, considering strip_include_prefix, include_prefix, and includes. Returns a set of path strings (order not guaranteed). ### Method IndexableIncludePaths ### Signature func IndexableIncludePaths(header label.Label, target Target) []string ### Parameters - **header** (label.Label) - Required - The header label. - **target** (Target) - Required - The target that exposes the header. ### Returns - **[]string** - A set of include path strings. ```