{"meta":{"title":"为 CodeQL 分析准备代码","intro":"可以生成 CodeQL 数据库，其中包含分析代码所需的数据。","product":"安全性和代码质量","breadcrumbs":[{"href":"/zh/code-security","title":"安全性和代码质量"},{"href":"/zh/code-security/tutorials","title":"Tutorials"},{"href":"/zh/code-security/tutorials/customize-code-scanning","title":"自定义代码扫描"},{"href":"/zh/code-security/tutorials/customize-code-scanning/preparing-your-code-for-codeql-analysis","title":"为分析准备代码"}],"documentType":"article"},"body":"# 为 CodeQL 分析准备代码\n\n可以生成 CodeQL 数据库，其中包含分析代码所需的数据。\n\n<!--The CodeQL CLI man pages include a link to a section in this article. If you rename this article,\nmake sure that you also update the MS short link: https://aka.ms/codeql-docs/indirect-tracing.-->\n\n## 关于为分析准备代码\n\n在使用 CodeQL 分析代码之前，需要创建一个 CodeQL 数据库，其中包含对代码运行查询所需的所有数据。 可以使用 CodeQL 自行创建 CodeQL CLI 数据库。\n\nCodeQL 分析依赖于从代码中提取关系数据，并使用它来生成 [CodeQL 数据库](https://codeql.github.com/docs/codeql-overview/codeql-glossary/#codeql-database)。 CodeQL 数据库包含有关代码库的所有重要信息，可通过执行 CodeQL 查询对其进行分析。\n\n在生成 CodeQL 数据库之前，需要：\n\n1. 安装并设置 CodeQL CLI。 有关详细信息，请参阅“[设置 CodeQL CLI](/zh/code-security/codeql-cli/getting-started-with-the-codeql-cli/setting-up-the-codeql-cli)”。\n2. 查看要分析的代码：\n   * 对于分支，请查看要分析的分支的头。\n   * 对于拉取请求，请签出拉取请求的头部提交，或签出 GitHub 生成的拉取请求的合并提交。\n3. 设置代码库的环境，确保所有依赖项都可用。\n4. 若要编译语言获得最佳结果，请查找适用于代码库的生成命令（如果有）。 通常可在 CI 系统的配置文件中找到。\n\n代码库准备就绪后，可以运行 `codeql database create` 以创建数据库。 有关详细信息，请参阅[为非编译语言创建数据库](#creating-databases-for-non-compiled-languages)和[为编译语言创建数据库](#creating-databases-for-compiled-languages)。\n\n## 正在运行 `codeql database create`\n\nCodeQL 数据库是通过从项目的签出根目录运行以下命令创建的：\n\n```shell\ncodeql database create <database> --language=<language-identifier>\n```\n\n必须指定以下内容：\n\n* `<database>`：要创建的新数据库的路径。 执行命令时将创建此目录，无法指定现有目录。\n* `--language`：要为其创建数据库的语言的标识符。 与 `--db-cluster` 一起使用时，该选项接受逗号分隔的列表，也可以多次指定。 CodeQL 支持为以下语言创建数据库：\n\n  | 语言    | Identifier | 可选替代标识符（如果有） |\n  | ----- | ---------- | ------------ |\n  | C/C++ | `c-cpp`    |              |\n\n  ```\n              `c` 或 `cpp` |\n  ```\n\n  \\| C# | `csharp` |\n  \\|  |\n  GitHub Actions 工作流程 | `actions`\n  |\n  \\| Go | `go` |\n  \\| Java/Kotlin | `java-kotlin` |\n  `java` 或 `kotlin` |\n  \\| JavaScript/TypeScript | `javascript-typescript` |\n  `javascript` 或 `typescript` |\n  \\| Python | `python` |\n  \\| Ruby | `ruby` |\n  \\|  |\n  Rust | `rust`\n  |\n  \\| Swift | `swift` |\n\n  > \\[!NOTE]\n  > 如果指定替代标识符之一，则等效于使用标准语言标识符。 例如，指定 `javascript` 而不是 `javascript-typescript` 不排除对 TypeScript 代码的分析。 可以改用 `--codescanning-config` CLI 选项加载配置文件，该配置文件指定要使用 `paths-ignore` 配置密钥排除的文件。 请参阅“[代码扫描的工作流配置选项](/zh/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning#custom-configuration-files)”。\n  >\n  > 或者，对于支持它的语言，请使用仅生成要扫描的文件的自定义生成命令。 请参阅[为已编译语言创建数据库](/zh/code-security/codeql-cli/getting-started-with-the-codeql-cli/preparing-your-code-for-codeql-analysis#creating-databases-for-compiled-languages)。\n\n如果你的代码库中有调用构建过程的构建命令或脚本，我们建议你也指定该命令或脚本：\n\n```shell\n   codeql database create <database> --command <build> \\\n         --language=<language-identifier>\n```\n\n### 用于创建数据库的选项\n\n如果需要编译代码，以及如果要为多种语言创建 CodeQL 数据库，可以根据源文件的位置指定其他选项。\n\n| 选项                                                                |                                                                                                                                                                                                               必选                                                                                                                                                                                                               | Usage                                                                                                                                                                                                              |\n| ----------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `<database>`                                                      |                                                    <svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-check\" aria-label=\"check icon\" role=\"img\"><path d=\"M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z\"></path></svg>                                                   | 指定要为 CodeQL 数据库创建的目录的名称和位置。 如果尝试覆盖现有目录，则该命令将失败。 如果还指定 `--db-cluster`，则这是父目录，并且会为分析的每种语言创建一个子目录。                                                                                                                    |\n| <code><span style=\"white-space: nowrap;\">--language</span></code> |                                                    <svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-check\" aria-label=\"check icon\" role=\"img\"><path d=\"M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z\"></path></svg>                                                   | 指定要为其创建数据库的语言的标识符，以下之一：`c-cpp`、`csharp`、`go`、`java-kotlin`、`javascript-typescript`、`python`、`ruby`、`rust`和`swift`。 与<code><span style=\"white-space: nowrap;\">--db-cluster</span></code>一起使用时，该选项接受逗号分隔的列表，也可以多次指定。 |\n| <code><span style=\"white-space: nowrap;\">--command</span></code>  | <svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-x\" aria-label=\"Optional\" role=\"img\"><path d=\"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z\"></path></svg> |                                                                                                                                                                                                                    |\n\n```\n          **\n          **建议 用于指定为代码库调用生成过程的生成命令或脚本。 命令从当前文件夹运行，或者从定义的位置<code><span style=\"white-space: nowrap;\">--source-root</span></code>运行。 不需要对 Python 和 JavaScript/TypeScript 进行分析。 |\n```\n\n\\| <code><span style=\"white-space: nowrap;\">--build-mode</span></code> | <svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-x\" aria-label=\"Optional\" role=\"img\"><path d=\"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z\"></path></svg> |\n\\*\\*\n\\*\\*建议 当未提供 `--command` 指定是否在没有生成 (`none`) 的情况下创建 CodeQL 数据库，或尝试检测生成命令 (`autobuild`) 时，供 C/C++、C#， Java 和 Rust 使用。 默认情况下，使用自动生成检测。 有关生成模式的比较，请参阅 [CodeQL 生成模式](/zh/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#codeql-build-modes)。 |\n\\| <code><span style=\"white-space: nowrap;\">--db-cluster</span></code> | <svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-x\" aria-label=\"Optional\" role=\"img\"><path d=\"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z\"></path></svg> | 在多语言代码库中使用，为<code><span style=\"white-space: nowrap;\">--language</span></code>指定的每种语言生成一个数据库。 |\n\\| <code><span style=\"white-space: nowrap;\">--no-run-unnecessary-builds</span></code> | <svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-x\" aria-label=\"Optional\" role=\"img\"><path d=\"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z\"></path></svg> |\n\\*\\*\n\\*\\*建议 用于抑制 CodeQL CLI 不需要监视生成的语言的生成命令（例如，Python 和 JavaScript/TypeScript）。 |\n\\| <code><span style=\"white-space: nowrap;\">--source-root</span></code> | <svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-x\" aria-label=\"Optional\" role=\"img\"><path d=\"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z\"></path></svg> | 如果在存储库的检出根目录之外运行 CLI，请使用此选项。 默认情况下，`database create` 命令假定当前目录是源文件的根目录，使用此选项可指定其他位置。 |\n\\| <code><span style=\"white-space: nowrap;\">--codescanning-config</span></code> | <svg version=\"1.1\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" class=\"octicon octicon-x\" aria-label=\"Optional\" role=\"img\"><path d=\"M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z\"></path></svg> | 高级。 如果具有指定如何创建 CodeQL 数据库以及后续步骤中要运行的查询的配置文件，请进行使用。 有关详细信息，请参阅 [代码扫描的工作流配置选项](/zh/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning#custom-configuration-files) 和 [数据库创建](/zh/code-security/codeql-cli/codeql-cli-manual/database-create#--codescanning-configfile)。 |\n\n可以指定提取程序选项来自定义创建 CodeQL 数据库的提取程序的行为。 有关详细信息，请参阅“[抽取器选项](/zh/code-security/codeql-cli/using-the-advanced-functionality-of-the-codeql-cli/extractor-options)”。\n\n有关创建数据库时可以使用的所有选项的完整详细信息，请参阅[数据库创建](/zh/code-security/codeql-cli/codeql-cli-manual/database-create)。\n\n### 单语言示例\n\n此示例在 `/checkouts/example-repo` 为签出的存储库创建单个 CodeQL 数据库。 它使用 JavaScript 提取器在存储库中创建 JavaScript 和 TypeScript 代码的分层表示形式。 生成的数据库存储在 `/codeql-dbs/example-repo` 中。\n\n```shell\n$ codeql database create /codeql-dbs/example-repo --language=javascript-typescript \\\n    --source-root /checkouts/example-repo\n\n> Initializing database at /codeql-dbs/example-repo.\n> Running command [/codeql-home/codeql/javascript/tools/autobuild.cmd]\n    in /checkouts/example-repo.\n> [build-stdout] Single-threaded extraction.\n> [build-stdout] Extracting\n...\n> Finalizing database at /codeql-dbs/example-repo.\n> Successfully created database at /codeql-dbs/example-repo.\n```\n\n### 多语言示例\n\n此示例在 `/checkouts/example-repo-multi` 为签出的存储库创建两个 CodeQL 数据库。 它使用：\n\n* `--db-cluster` 用于请求分析多种语言。\n* `--language` 用于指定要为其创建数据库的语言。\n* `--command` 用于告知工具代码库的生成命令，此处为 `make`。\n* `--no-run-unnecessary-builds`，告知工具跳过不需要的语言的生成命令（如Python）。\n\n生成的数据库存储在 `python` 的 `cpp` 和 `/codeql-dbs/example-repo-multi` 子目录中。\n\n```shell\n$ codeql database create /codeql-dbs/example-repo-multi \\\n    --db-cluster --language python,c-cpp \\\n    --command make --no-run-unnecessary-builds \\\n    --source-root /checkouts/example-repo-multi\nInitializing databases at /codeql-dbs/example-repo-multi.\nRunning build command: [make]\n[build-stdout] Calling python3 /codeql-bundle/codeql/python/tools/get_venv_lib.py\n[build-stdout] Calling python3 -S /codeql-bundle/codeql/python/tools/python_tracer.py -v -z all -c /codeql-dbs/example-repo-multi/python/working/trap_cache -p ERROR: 'pip' not installed.\n[build-stdout] /usr/local/lib/python3.6/dist-packages -R /checkouts/example-repo-multi\n[build-stdout] [INFO] Python version 3.6.9\n[build-stdout] [INFO] Python extractor version 5.16\n[build-stdout] [INFO] [2] Extracted file /checkouts/example-repo-multi/hello.py in 5ms\n[build-stdout] [INFO] Processed 1 modules in 0.15s\n[build-stdout] <output from calling 'make' to build the C/C++ code>\nFinalizing databases at /codeql-dbs/example-repo-multi.\nSuccessfully created databases at /codeql-dbs/example-repo-multi.\n$\n```\n\n## 进度和结果\n\n如果指定的选项存在任何问题，将报告错误。 对于解释语言以及为 C/C++、C#， Java 和 Rust 指定 `--build-mode none` 时，提取过程显示在控制台中。 对于每个源文件，控制台显示提取是成功还是失败。 如果生成已编译的语言，控制台将显示生成系统的输出。\n\n成功创建数据库后，会在命令中指定的路径处找到一个新目录。 如果使用 `--db-cluster` 选项创建多个数据库，则会为每种语言创建一个子目录。 每个 CodeQL 数据库目录包含许多子目录，包括关系数据（分析所需）以及用于显示分析结果的源存档（创建数据库时制作的源文件的副本）。\n\n## 为非编译语言创建数据库\n\nCodeQL CLI 包括为非编译语言（特别是 JavaScript（和 TypeScript）、Python 和 Ruby）创建数据库的提取程序。 在执行 `--language` 时，当选择 JavaScript、Python 或 Ruby 作为 `database create` 选项时，将自动调用这些提取程序。 为这些语言创建数据库时，必须确保所有其他依赖项都可用。\n\n> \\[!NOTE]\n> 为 JavaScript、TypeScript、Python 和 Ruby 运行 `database create` 时，不应指定 `--command` 选项。 否则，此操作将替代正常的提取程序调用，将创建一个空数据库。 如果为多种语言创建数据库，并且其中一种语言为已编译语言，请使用 `--no-run-unnecessary-builds` 选项跳过不需要编译的语言的命令。\n\n### JavaScript 和 TypeScript\n\n创建 JavaScript 数据库不需要其他依赖项，但如果项目包含 TypeScript 文件，则必须安装 Node.js 14 或更高版本并在 `PATH` 上作为 `node` 提供。 在命令行中，可以指定 `--language=javascript-typescript` 提取 JavaScript 和 TypeScript 文件：\n\n```shell\ncodeql database create --language=javascript-typescript --source-root <folder-to-extract> <output-folder>/javascript-database\n```\n\n此处，我们指定了一个 `--source-root` 路径，该路径是执行数据库创建的位置，但不一定是代码库的签出根。\n\n默认情况下，不会提取 `node_modules` 和 `bower_components` 目录中的文件。\n\n### Python\n\n为Python创建数据库时，必须确保：\n\n* 已安装 Python 3，并可用于 CodeQL 提取程序。\n* 你已安装了你的代码使用的Python版本。\n\n在命令行中，必须指定 `--language=python`。 例如：\n\n```shell\ncodeql database create --language=python <output-folder>/python-database\n```\n\n这会从代码的签出根目录执行 `database create` 子命令，在 `<output-folder>/python-database` 生成新的Python数据库。\n\n### Ruby\n\n为 Ruby 创建数据库不需要额外的依赖项。 在命令行中，必须指定 `--language=ruby`。 例如：\n\n```shell\ncodeql database create --language=ruby --source-root <folder-to-extract> <output-folder>/ruby-database\n```\n\n此处，我们指定了一个 `--source-root` 路径，该路径是执行数据库创建的位置，但不一定是代码库的签出根。\n\n## 为已编译语言创建数据库\n\n对于大多数已编译语言，CodeQL 需要调用所需的生成系统来生成数据库，因此生成方法必须可用于 CLI。 此方法会创建包含生成的代码的数据库。 CodeQL 有两种方法来生成代码库：\n\n* [自动生成检测（自动生成）](#automatically-detecting-the-build-system)\n* [用户指定的生成命令](/zh/code-security/codeql-cli/getting-started-with-the-codeql-cli/preparing-your-code-for-codeql-analysis#specifying-build-commands)\n\n此外，对于 C/C++、C#， Java 和 Rust，可以选择生成数据库而不生成代码。 如果要为多个存储库启用 code scanning，此选项尤其有用。 有关详细信息，请参阅 [CodeQL 生成模式](/zh/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#codeql-build-modes)。\n\n### 自动检测生成系统\n\nCodeQL CLI 包含用于 C/C++、C#、Go、Java、Kotlin 和 Swift 代码的自动构建工具。 CodeQL 自动生成程序允许为编译语言生成项目，而无需指定任何生成命令。 调用自动生成程序时，CodeQL 检查源以获取生成系统的证据，并尝试运行提取数据库所需的最佳命令集。 有关详细信息，请参阅“[对编译语言进行 CodeQL 代码扫描](/zh/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#about-autobuild)”。\n\n执行编译语言的 `codeql database create` 时，如果不包含 `--command` 选项或设置 `--build-mode none`，则会自动调用自动编译器。 例如，对于 Swift 代码库，只需运行：\n\n```shell\ncodeql database create --language=swift <output-folder>/swift-database\n```\n\n如果代码库使用标准生成系统，则依赖于自动生成程序通常是创建数据库的最简单方法。 对于需要非标准生成步骤的源，可能需要在命令行中显式定义每个步骤。\n\n> \\[!NOTE]\n>\n> * 如果要生成 Go 数据库，请安装 Go 工具链（版本 1.11 或更高版本），如果有依赖项，则相应的依赖项管理器（如 [dep](https://golang.github.io/dep/)）。\n> * Go 自动生成程序尝试自动检测在存储库中用 Go 编写的代码，并且仅在尝试提取依赖项时运行生成脚本。 若要强制 CodeQL 将提取限制为由生成脚本编译的文件，请设置环境变量 `CODEQL_EXTRACTOR_GO_BUILD_TRACING=on` 或使用 `--command` 选项指定生成命令。\n\n### 指定生成命令\n\n以下示例旨在让你了解可为编译语言指定的一些生成命令。\n\n> \\[!NOTE]\n\n```\n          `--command` 选项接受单个参数，如果需要使用多个命令，请多次指定 `--command`。 如果需要传递子命令和选项，则需要引用整个参数才能正确解释。\n```\n\n* 使用 `make` 生成的 C/C++ 项目：\n\n  ```shell\n  # Disable parallel execution via `-j1` or other techniques: https://www.gnu.org/software/make/manual/make.html#Parallel-Execution\n  codeql database create cpp-database --language=c-cpp --command=make\n  ```\n\n* 使用 `dotnet build` 生成的 C# 项目：\n\n  最好添加 `/t:rebuild` 以确保生成所有代码，或者先执行 `dotnet clean`（未生成的代码不会包含在 CodeQL 数据库中）：\n\n  ```shell\n  codeql database create csharp-database --language=csharp --command='dotnet build /t:rebuild'\n  ```\n\n* 使用 `CODEQL_EXTRACTOR_GO_BUILD_TRACING=on` 环境变量生成的 Go 项目：\n\n  ```shell\n  CODEQL_EXTRACTOR_GO_BUILD_TRACING=on codeql database create go-database --language=go\n  ```\n\n* 使用自定义生成脚本生成的 Go 项目：\n\n  ```shell\n  codeql database create go-database --language=go --command='./scripts/build.sh'\n  ```\n\n* 使用 Gradle 生成的Java项目：\n\n  ```shell\n  # Use `--no-daemon` because a build delegated to an existing daemon cannot be detected by CodeQL.\n  # To ensure isolated builds without caching, add `--no-build-cache` on persistent machines.\n  codeql database create java-database --language=java-kotlin --command='gradle --no-daemon clean test'\n  ```\n\n* 使用 Maven 生成的Java项目：\n\n  ```shell\n  codeql database create java-database --language=java-kotlin --command='mvn clean install'\n  ```\n\n* 使用 Ant 生成的Java项目：\n\n  ```shell\n  codeql database create java-database --language=java-kotlin --command='ant -f build.xml'\n  ```\n\n* 使用 Cargo 生成的 Rust 项目：\n\n  ```shell\n  codeql database create rust-database --language=rust\n  ```\n\n* 从 Xcode 项目或工作区生成的 Swift 项目。 默认情况下，将生成最大的 Swift 目标：\n\n  最好确保项目处于干净状态，并且没有可用的生成项目。\n\n  ```shell\n  xcodebuild clean -all\n  codeql database create -l swift swift-database\n  ```\n\n* 使用 `swift build` 生成的 Swift 项目：\n\n  ```shell\n  codeql database create -l swift -c \"swift build\" swift-database\n  ```\n\n* 使用 `xcodebuild` 生成的 Swift 项目：\n\n  ```shell\n  codeql database create -l swift -c \"xcodebuild build -target your-target\" swift-database\n  ```\n\n  可以将 `archive` 和 `test` 选项传递给 `xcodebuild`。 但是，建议使用标准 `xcodebuild` 命令，因为它应该是最快的命令，并且应该是 CodeQL 成功扫描所需的全部命令。\n\n* 使用自定义生成脚本生成的 Swift 项目：\n\n  ```shell\n  codeql database create -l swift -c \"./scripts/build.sh\" swift-database\n  ```\n\n* 使用 Bazel 生成的项目：\n\n  ```shell\n  # Navigate to the Bazel workspace.\n\n  # Before building, remove cached objects\n  # and stop all running Bazel server processes.\n  bazel clean --expunge\n\n  # Build using the following Bazel flags, to help CodeQL detect the build:\n  # `--spawn_strategy=local`: build locally, instead of using a distributed build\n  # `--nouse_action_cache`: turn off build caching, which might prevent recompilation of source code\n  # `--noremote_accept_cached`, `--noremote_upload_local_results`: avoid using a remote cache\n  # `--disk_cache=`: avoid using a disk cache. Note that a disk cache is no longer considered a remote cache as of Bazel 6.\n  codeql database create new-database --language=<language> \\\n  --command='bazel build --spawn_strategy=local --nouse_action_cache --noremote_accept_cached --noremote_upload_local_results --disk_cache= //path/to/package:target'\n\n  # After building, stop all running Bazel server processes.\n  # This ensures future build commands start in a clean Bazel server process\n  # without CodeQL attached.\n  bazel shutdown\n  ```\n\n> \\[!NOTE]\n> 目前不支持 Go 的 Bazel 构建。\n\n* 使用自定义生成脚本生成的项目：\n\n  ```shell\n  codeql database create new-database --language=<language> --command='./scripts/build.sh'\n  ```\n\n此命令运行包含生成项目所需的所有命令的自定义脚本。\n\n<!-- Anchor to maintain the CodeQL CLI manual pages link: https://aka.ms/codeql-docs/indirect-tracing -->\n\n<a name=\"using-indirect-build-tracing\"></a>\n\n### 使用间接生成跟踪\n\n如果编译语言的 CodeQL CLI 自动生成程序不适用于 CI 工作流，并且无法使用 `codeql database trace-command` 包装生成命令的调用，可以使用间接生成跟踪来创建 CodeQL 数据库。 若要使用间接生成跟踪，CI 系统必须能够为每个生成操作设置自定义环境变量。\n\n若要使用间接生成跟踪创建 CodeQL 数据库，请从项目的签出根目录运行以下命令：\n\n```shell\ncodeql database init ... --begin-tracing <database>\n```\n\n必须指定以下内容：\n\n* `<database>`：要创建的新数据库的路径。 执行命令时将创建此目录，无法指定现有目录。\n* `--begin-tracing`：创建可用于设置环境的脚本，将在该环境中跟踪生成命令。\n\n可以像平常一样为 `codeql database init` 命令指定其他选项。\n\n> \\[!NOTE]\n> 如果生成在 Windows 上运行，则必须设置 `--trace-process-level <number>` 或 `--trace-process-name <parent process name>`，以便该选项指向父 CI 进程，该进程将观察所分析代码的所有生成步骤。\n\n```\n          `codeql database init` 命令将输出消息：\n```\n\n```shell\nCreated skeleton <database>. This in-progress database is ready to be populated by an extractor. In order to initialise tracing, some environment variables need to be set in the shell your build will run in. A number of scripts to do this have been created in <database>/temp/tracingEnvironment. Please run one of these scripts before invoking your build command.\n\nBased on your operating system, we recommend you run: ...\n```\n\n```\n          `codeql database init` 命令使用包含环境变量和值的文件创建 `<database>/temp/tracingEnvironment`，这些环境变量和值将启用 CodeQL 跟踪一系列生成步骤。 这些文件名为 `start-tracing.{json,sh,bat,ps1}`。 将其中一个文件与 CI 系统的机制结合使用，以便为将来的步骤设置环境变量。 您可以：\n```\n\n* 读取 JSON 文件，对其进行处理，然后以 CI 系统所需的格式输出环境变量。 例如，Azure DevOps需要 `echo \"##vso[task.setvariable variable=NAME]VALUE\"`。\n* 或者，如果 CI 系统保留该环境，请获取适当的 `start-tracing` 脚本以在 CI 系统的 shell 环境中设置 CodeQL 变量。\n\n生成代码；（可选）使用存储 `end-tracing.{json,sh,bat,ps1}` 脚本的目录中的 `start-tracing` 脚本取消设置环境变量；然后运行命令 `codeql database finalize <database>`。\n\n使用间接生成跟踪创建 CodeQL 数据库后，可以像使用任何其他 CodeQL 数据库一样使用该数据库。 例如，如果使用的是代码扫描，请分析数据库并将结果上传到 GitHub。\n\n### 使用间接生成跟踪创建 CodeQL 数据库的示例\n\n> \\[!NOTE]\n> 如果使用 Azure DevOps 管道，创建 CodeQL 数据库的最简单方法是使用 GitHub Advanced Security for Azure DevOps。 有关文档，请参阅 Microsoft Learn 中的[配置 GitHub Advanced Security for Azure DevOps](https://learn.microsoft.com/en-us/azure/devops/repos/security/configure-github-advanced-security-features)。\n\n以下示例演示如何在 Azure DevOps 管道中使用间接生成跟踪来创建 CodeQL 数据库：\n\n```yaml\nsteps:\n    # Download the CodeQL CLI and query packs...\n    # Check out the repository ...\n\n    # Run any pre-build tasks, for example, restore NuGet dependencies...\n\n    # Initialize the CodeQL database.\n    # In this example, the CodeQL CLI has been downloaded and placed on the PATH.\n    - task: CmdLine@1\n       displayName: Initialize CodeQL database\n      inputs:\n          # Assumes the source code is checked out to the current working directory.\n          # Creates a database at `<current working directory>/db`.\n          # Running on Windows, so specifies a trace process level.\n          script: \"codeql database init --language csharp --trace-process-name Agent.Worker.exe --source-root . --begin-tracing db\"\n\n    # Read the generated environment variables and values,\n    # and set them so they are available for subsequent commands\n    # in the build pipeline. This is done in PowerShell in this example.\n    - task: PowerShell@1\n       displayName: Set CodeQL environment variables\n       inputs:\n          targetType: inline\n          script: >\n             $json = Get-Content $(System.DefaultWorkingDirectory)/db/temp/tracingEnvironment/start-tracing.json | ConvertFrom-Json\n             $json.PSObject.Properties | ForEach-Object {\n                 $template = \"##vso[task.setvariable variable=\"\n                 $template += $_.Name\n                 $template += \"]\"\n                 $template += $_.Value\n                 echo \"$template\"\n             }\n\n    # Execute the pre-defined build step. Note the `msbuildArgs` variable.\n    - task: VSBuild@1\n        inputs:\n          solution: '**/*.sln'\n          msbuildArgs: /p:OutDir=$(Build.ArtifactStagingDirectory)\n          platform: Any CPU\n          configuration: Release\n          # Execute a clean build, in order to remove any existing build artifacts prior to the build.\n          clean: True\n       displayName: Visual Studio Build\n\n    # Read and set the generated environment variables to end build tracing. This is done in PowerShell in this example.\n    - task: PowerShell@1\n       displayName: Clear CodeQL environment variables\n       inputs:\n          targetType: inline\n          script: >\n             $json = Get-Content $(System.DefaultWorkingDirectory)/db/temp/tracingEnvironment/end-tracing.json | ConvertFrom-Json\n             $json.PSObject.Properties | ForEach-Object {\n                 $template = \"##vso[task.setvariable variable=\"\n                 $template += $_.Name\n                 $template += \"]\"\n                 $template += $_.Value\n                 echo \"$template\"\n             }\n\n    - task: CmdLine@2\n       displayName: Finalize CodeQL database\n       inputs:\n          script: 'codeql database finalize db'\n\n    # Other tasks go here, for example:\n    # `codeql database analyze`\n    # then `codeql github upload-results` ...\n```\n\n## 后续步骤\n\n* 若要了解如何使用 CodeQL CLI 分析从代码创建的数据库，请参阅[使用 CodeQL 查询分析代码](/zh/code-security/codeql-cli/getting-started-with-the-codeql-cli/analyzing-your-code-with-codeql-queries)。"}