Skip to main content

Configuring code scanning

You can configure how GitHub scans the code in your project for vulnerabilities and errors.

Who can use this feature

People with write permissions to a repository can configure code scanning for the repository.

Code scanning is available for all public repositories on GitHub.com. To use code scanning in a private repository owned by an organization, you must have a license for GitHub Advanced Security. 詳細については、「GitHub Advanced Security について」を参照してください。

About code scanning configuration

You can run code scanning on GitHub Enterprise Cloud, using GitHub Actions, or from your continuous integration (CI) system. For more information, see "About GitHub Actions" or "About CodeQL code scanning in your CI system."

This article is about running code scanning on GitHub Enterprise Cloud using actions.

Before you can configure code scanning for a repository, you must set up code scanning by adding a GitHub Actions workflow to the repository. For more information, see "Setting up code scanning for a repository."

通常、code scanning のデフォルトのワークフローを編集する必要はありません。 ただし、必要な場合にはワークフローを編集して設定の一部をカスタマイズできます。 たとえば、GitHubのCodeQL analysis workflowを編集して、スキャンの頻度、スキャンする言語やディレクトリ、CodeQL code scanningがコード中で探すものを指定できます。 コードのコンパイルに特定のコマンドセットを使っている場合にも、CodeQL analysis workflowを編集する必要があるかもしれません。

CodeQL analysis is just one type of code scanning you can do in GitHub. GitHub Marketplace contains other code scanning workflows you can use. You can find a selection of these on the "Get started with code scanning" page, which you can access from the Security tab. The specific examples given in this article relate to the CodeQL analysis workflow file.

Editing a code scanning workflow

GitHub saves workflow files in the .github/workflows directory of your repository. You can find a workflow you have added by searching for its file name. For example, by default, the workflow file for CodeQL code scanning is called codeql-analysis.yml.

  1. In your repository, browse to the workflow file you want to edit.
  2. In the upper right corner of the file view, to open the workflow editor, click . Edit workflow file button
  3. After you have edited the file, click Start commit and complete the "Commit changes" form. You can choose to commit directly to the current branch, or create a new branch and start a pull request. Commit update to codeql.yml workflow

For more information about editing workflow files, see "Learn GitHub Actions."

Configuring frequency

You can configure the CodeQL analysis workflow to scan code on a schedule or when specific events occur in a repository.

Scanning code when someone pushes a change, and whenever a pull request is created, prevents developers from introducing new vulnerabilities and errors into the code. Scanning code on a schedule informs you about the latest vulnerabilities and errors that GitHub, security researchers, and the community discover, even when developers aren't actively maintaining the repository.

Scanning on push

By default, the CodeQL analysis workflow uses the on.push event to trigger a code scan on every push to the default branch of the repository and any protected branches. For code scanning to be triggered on a specified branch, the workflow must exist in that branch. For more information, see "Workflow syntax for GitHub Actions."

If you scan on push, then the results appear in the Security tab for your repository. For more information, see "Managing code scanning alerts for your repository."

Additionally, when an on:push scan returns results that can be mapped to an open pull request, these alerts will automatically appear on the pull request in the same places as other pull request alerts. The alerts are identified by comparing the existing analysis of the head of the branch to the analysis for the target branch. For more information on code scanning alerts in pull requests, see "Triaging code scanning alerts in pull requests."

Scanning pull requests

The default CodeQL analysis workflow uses the pull_request event to trigger a code scan on pull requests targeted against the default branch. If a pull request is from a private fork, the pull_request event will only be triggered if you've selected the "Run workflows from fork pull requests" option in the repository settings. For more information, see "Managing GitHub Actions settings for a repository."

For more information about the pull_request event, see "Events that trigger workflows."

If you scan pull requests, then the results appear as alerts in a pull request check. For more information, see "Triaging code scanning alerts in pull requests."

Using the pull_request trigger, configured to scan the pull request's merge commit rather than the head commit, will produce more efficient and accurate results than scanning the head of the branch on each push. However, if you use a CI/CD system that cannot be configured to trigger on pull requests, you can still use the on:push trigger and code scanning will map the results to open pull requests on the branch and add the alerts as annotations on the pull request. For more information, see "Scanning on push."

Defining the severities causing pull request check failure

By default, only alerts with the severity level of Error or security severity level of Critical or High will cause a pull request check failure, and a check will still succeed with alerts of lower severities. You can change the levels of alert severities and of security severities that will cause a pull request check failure in your repository settings. For more information about severity levels, see "About code scanning alerts."

  1. GitHub.com で、リポジトリのメイン ページへ移動します。

  2. リポジトリ名の下の [ 設定] をクリックします。 リポジトリの設定ボタン

  3. In the "Security" section of the sidebar, click Code security and analysis.

  4. Under "Code scanning", to the right of "Check Failure", use the drop-down menu to select the level of severity you would like to cause a pull request check failure. Check failure setting

Avoiding unnecessary scans of pull requests

You might want to avoid a code scan being triggered on specific pull requests targeted against the default branch, irrespective of which files have been changed. You can configure this by specifying on:pull_request:paths-ignore or on:pull_request:paths in the code scanning workflow. For example, if the only changes in a pull request are to files with the file extensions .md or .txt you can use the following paths-ignore array.

on:
  push:
    branches: [main, protected]
  pull_request:
    branches: [main]
    paths-ignore:
      - '**/*.md'
      - '**/*.txt'

Notes

  • on:pull_request:paths-ignore and on:pull_request:paths set conditions that determine whether the actions in the workflow will run on a pull request. They don't determine what files will be analyzed when the actions are run. When a pull request contains any files that are not matched by on:pull_request:paths-ignore or on:pull_request:paths, the workflow runs the actions and scans all of the files changed in the pull request, including those matched by on:pull_request:paths-ignore or on:pull_request:paths, unless the files have been excluded. For information on how to exclude files from analysis, see "Specifying directories to scan."
  • For CodeQL code scanning workflow files, don't use the paths-ignore or paths keywords with the on:push event as this is likely to cause missing analyses. For accurate results, CodeQL code scanning needs to be able to compare new changes with the analysis of the previous commit.

For more information about using on:pull_request:paths-ignore and on:pull_request:paths to determine when a workflow will run for a pull request, see "Workflow syntax for GitHub Actions."

Scanning on a schedule

If you use the default CodeQL analysis workflow, the workflow will scan the code in your repository once a week, in addition to the scans triggered by events. To adjust this schedule, edit the cron value in the workflow. For more information, see "Workflow syntax for GitHub Actions."

Note: GitHub only runs scheduled jobs that are in workflows on the default branch. Changing the schedule in a workflow on any other branch has no effect until you merge the branch into the default branch.

Example

The following example shows a CodeQL analysis workflow for a particular repository that has a default branch called main and one protected branch called protected.

on:
  push:
    branches: [main, protected]
  pull_request:
    branches: [main]
  schedule:
    - cron: '20 14 * * 1'

This workflow scans:

  • Every push to the default branch and the protected branch
  • Every pull request to the default branch
  • The default branch every Monday at 14:20 UTC

Specifying an operating system

If your code requires a specific operating system to compile, you can configure the operating system in your CodeQL analysis workflow. Edit the value of jobs.analyze.runs-on to specify the operating system for the machine that runs your code scanning actions.

jobs:
  analyze:
    name: Analyze
    runs-on: [ubuntu-latest]

If you choose to use a self-hosted runner for code scanning, you can specify an operating system by using an appropriate label as the second element in a two-element array, after self-hosted.

jobs:
  analyze:
    name: Analyze
    runs-on: [self-hosted, ubuntu-latest]

CodeQL code scanning supports the latest versions of Ubuntu, Windows, and macOS. Typical values for this setting are therefore: ubuntu-latest, windows-latest, and macos-latest. For more information, see "Choosing the runner for a job" and "Using labels with self-hosted runners."

If you use a self-hosted runner, you must ensure that Git is in the PATH variable. For more information, see "About self-hosted runners" and "Adding self-hosted runners."

For recommended specifications (RAM, CPU cores, and disk) for running CodeQL analysis on self-hosted machines, see "Recommended hardware resources for running CodeQL."

Specifying the location for CodeQL databases

In general, you do not need to worry about where the CodeQL analysis workflow places CodeQL databases since later steps will automatically find databases created by previous steps. However, if you are writing a custom workflow step that requires the CodeQL database to be in a specific disk location, for example to upload the database as a workflow artifact, you can specify that location using the db-location parameter under the init action.

- uses: github/codeql-action/init@v2
  with:
    db-location: '${{ github.workspace }}/codeql_dbs'

The CodeQL analysis workflow will expect the path provided in db-location to be writable, and either not exist, or be an empty directory. When using this parameter in a job running on a self-hosted runner or using a Docker container, it's the responsibility of the user to ensure that the chosen directory is cleared between runs, or that the databases are removed once they are no longer needed. This is not necessary for jobs running on GitHub-hosted runners, which obtain a fresh instance and a clean filesystem each time they run. For more information, see "About GitHub-hosted runners."

If this parameter is not used, the CodeQL analysis workflow will create databases in a temporary location of its own choice.

Changing the languages that are analyzed

CodeQL code scanning automatically detects code written in the supported languages.

  • C/C++
  • C#
  • Go
  • Java
  • JavaScript/TypeScript
  • Python
  • Ruby

Note: CodeQL analysis for Ruby is currently in beta. During the beta, analysis of Ruby will be less comprehensive than CodeQL analysis of other languages.

For more information, see the documentation on the CodeQL website: "Supported languages and frameworks."

The default CodeQL analysis workflow file contains a matrix called language which lists the languages in your repository that are analyzed. CodeQL automatically populates this matrix when you add code scanning to a repository. Using the language matrix optimizes CodeQL to run each analysis in parallel. We recommend that all workflows adopt this configuration due to the performance benefits of parallelizing builds. For more information about matrices, see "Using a matrix for your jobs."

サポートされている 1 つ以上の言語のコードがリポジトリに含まれている場合は、分析する言語を選択できます。 言語が分析されないようにする理由は、いくつかあります。 たとえば、プロジェクトで、コードの本体に対する依存関係が別の言語の中にあり、それらの依存関係のアラートを表示したくない場合が考えられます。

If your workflow uses the language matrix then CodeQL is hardcoded to analyze only the languages in the matrix. To change the languages you want to analyze, edit the value of the matrix variable. You can remove a language to prevent it being analyzed or you can add a language that was not present in the repository when code scanning was set up. For example, if the repository initially only contained JavaScript when code scanning was set up, and you later added Python code, you will need to add python to the matrix.

jobs:
  analyze:
    name: Analyze
    ...
    strategy:
      fail-fast: false
      matrix:
        language: ['javascript', 'python']

If your workflow does not contain a matrix called language, then CodeQL is configured to run analysis sequentially. If you don't specify languages in the workflow, CodeQL automatically detects, and attempts to analyze, any supported languages in the repository. If you want to choose which languages to analyze, without using a matrix, you can use the languages parameter under the init action.

- uses: github/codeql-action/init@v2
  with:
    languages: cpp, csharp, python

Analyzing Python dependencies

For GitHub-hosted runners that use Linux only, the CodeQL analysis workflow will try to auto-install Python dependencies to give more results for the CodeQL analysis. You can control this behavior by specifying the setup-python-dependencies parameter for the action called by the "Initialize CodeQL" step. By default, this parameter is set to true:

  • If the repository contains code written in Python, the "Initialize CodeQL" step installs the necessary dependencies on the GitHub-hosted runner. If the auto-install succeeds, the action also sets the environment variable CODEQL_PYTHON to the Python executable file that includes the dependencies.

  • If the repository doesn't have any Python dependencies, or the dependencies are specified in an unexpected way, you'll get a warning and the action will continue with the remaining jobs. The action can run successfully even when there are problems interpreting dependencies, but the results may be incomplete.

Alternatively, you can install Python dependencies manually on any operating system. You will need to add setup-python-dependencies and set it to false, as well as set CODEQL_PYTHON to the Python executable that includes the dependencies, as shown in this workflow extract:

jobs:
  CodeQL-Build:
    runs-on: ubuntu-latest
    permissions:
      security-events: write
      actions: read

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.x'
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          if [ -f requirements.txt ];
          then pip install -r requirements.txt;
          fi
          # Set the `CODEQL-PYTHON` environment variable to the Python executable
          # that includes the dependencies
          echo "CODEQL_PYTHON=$(which python)" >> $GITHUB_ENV
      - name: Initialize CodeQL
        uses: github/codeql-action/init@v2
        with:
          languages: python
          # Override the default behavior so that the action doesn't attempt
          # to auto-install Python dependencies
          setup-python-dependencies: false

Configuring a category for the analysis

Use category to distinguish between multiple analyses for the same tool and commit, but performed on different languages or different parts of the code. The category you specify in your workflow will be included in the SARIF results file.

This parameter is particularly useful if you work with monorepos and have multiple SARIF files for different components of the monorepo.

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v2
      with:
        # Optional. Specify a category to distinguish between multiple analyses
        # for the same tool and ref. If you don't use `category` in your workflow,
        # GitHub will generate a default category name for you
        category: "my_category"

If you don't specify a category parameter in your workflow, GitHub Enterprise Cloud will generate a category name for you, based on the name of the workflow file triggering the action, the action name, and any matrix variables. For example:

  • The .github/workflows/codeql-analysis.yml workflow and the analyze action will produce the category .github/workflows/codeql.yml:analyze.
  • The .github/workflows/codeql-analysis.yml workflow, the analyze action, and the {language: javascript, os: linux} matrix variables will produce the category .github/workflows/codeql-analysis.yml:analyze/language:javascript/os:linux.

The category value will appear as the <run>.automationDetails.id property in SARIF v2.1.0. For more information, see "SARIF support for code scanning."

Your specified category will not overwrite the details of the runAutomationDetails object in the SARIF file, if included.

Running additional queries

コードをスキャンするためにCodeQLを使う場合、CodeQL分析エンジンはコードからデータベースを生成し、それに対してクエリを実行します。 CodeQLの分析はデフォルトのクエリセットを使いますが、デフォルトのクエリに加えてもっと多くのクエリを実行するよう指定することもできます。

また、分析から除外するクエリを指定したり、分析に含めたりすることもできます。 これには、カスタム構成ファイルを使用する必要があります。 詳しくは、以下の「カスタム構成ファイルの使用」および「分析からの特定のクエリの除外」を参照してください。

追加のクエリは、GitHub Container registry に公開される CodeQL パック (ベータ版)、またはリポジトリに格納される QL の一部である場合に、実行できます。 詳細については、「code scanning と CodeQL について」を参照してください。

追加で実行したいクエリを指定するのに使用できるオプションは、次のとおりです。

  • packs。1 つまたは複数の CodeQL クエリ パック (ベータ版) をインストールし、それらのパックに対して既定のクエリ スイートまたはクエリを実行します。
  • queries。1 つの .ql ファイル、複数の .ql ファイルを含むディレクトリ、 .qls クエリ スイート定義ファイル、または任意の組み合わせを指定します。 クエリ スイート定義の詳細については、「CodeQL クエリ スイートの作成」を参照してください。

同じワークフローで packsqueries の両方を使用できます。

github/codeql/cpp/ql/src@main のように、github/codeql リポジトリから直接クエリ スイートを参照することはお勧めしません。 このようなクエリは再コンパイルする必要があり、現在 GitHub Actions でアクティブになっている CodeQL のバージョンと互換性がないため、分析中にエラーが発生する可能性があります。

Using CodeQL query packs

注: CodeQL パッケージ管理機能 (CodeQL パックを含む) は現在ベータ版であり、変更される可能性があります。

To add one or more CodeQL query packs (beta), add a with: packs: entry within the uses: github/codeql-action/init@v2 section of the workflow. Within packs you specify one or more packages to use and, optionally, which version to download. Where you don't specify a version, the latest version is downloaded. If you want to use packages that are not publicly available, you need to set the GITHUB_TOKEN environment variable to a secret that has access to the packages. For more information, see "Authentication in a workflow" and "Encrypted secrets."

Note: For workflows that generate CodeQL databases for multiple languages, you must instead specify the CodeQL query packs in a configuration file. For more information, see "Specifying CodeQL query packs" below.

In the example below, scope is the organization or personal account that published the package. When the workflow runs, the four CodeQL query packs are downloaded from GitHub Enterprise Cloud and the default queries or query suite for each pack run:

  • The latest version of pack1 is downloaded and all default queries are run.
  • Version 1.2.3 of pack2 is downloaded and all default queries are run.
  • The latest version of pack3 that is compatible with version 3.2.1 is downloaded and all queries are run.
  • Version 4.5.6 of pack4 is downloaded and only the queries found in path/to/queries are run.
- uses: github/codeql-action/init@v2
  with:
    # Comma-separated list of packs to download
    packs: scope/pack1,scope/pack2@1.2.3,scope/pack3@~3.2.1,scope/pack4@4.5.6:path/to/queries

Downloading CodeQL packs from GitHub Enterprise Server

If your workflow uses packs that are published on a GitHub Enterprise Server installation, you need to tell your workflow where to find them. You can do this by using the registries input of the github/codeql-action/init@v2 action. This input accepts a list of url, packages, and token properties as shown below.

- uses: github/codeql-action/init@v2
  with:
    registries: |
      # URL to the container registry, usually in this format
      - url: https://containers.GHEHOSTNAME1/v2/

        # List of package glob patterns to be found at this registry
        packages:
          - my-company/*
          - my-company2/*

        # Token, which should be stored as a secret
        token: ${{ secrets.GHEHOSTNAME1_TOKEN }}

      # URL to the default container registry
      - url: https://ghcr.io/v2/
        # Packages can also be a string
        packages: "*/*"
        token: ${{ secrets.GHCR_TOKEN }}

    

The package patterns in the registries list are examined in order, so you should generally place the most specific package patterns first. The values for token must be a personal access token generated by the GitHub instance you are downloading from with the read:packages permission.

Notice the | after the registries property name. This is important since GitHub Actions inputs can only accept strings. Using the | converts the subsequent text to a string, which is parsed later by the github/codeql-action/init@v2 action.

Using queries in QL packs

To add one or more queries, add a with: queries: entry within the uses: github/codeql-action/init@v2 section of the workflow. If the queries are in a private repository, use the external-repository-token parameter to specify a token that has access to checkout the private repository.

- uses: github/codeql-action/init@v2
  with:
    queries: COMMA-SEPARATED LIST OF PATHS
    # Optional. Provide a token to access queries stored in private repositories.
    external-repository-token: ${{ secrets.ACCESS_TOKEN }}

You can also specify query suites in the value of queries. Query suites are collections of queries, usually grouped by purpose or language.

以下のクエリスイートはCodeQL code scanningに組み込まれており、利用可能です。

クエリ スイート説明
security-extended既定のスイートからのクエリ、および重要度と精度の低いクエリ
security-and-qualitysecurity-extended からのクエリに加え、保守性および信頼性のクエリ。

クエリ スイートを指定すると、CodeQL の分析エンジンでは、既定の一連のクエリと、追加のクエリ スイートで定義されている追加クエリが実行されます。 JavaScript の security-extended クエリ スイートと security-and-quality クエリ スイートには、試験的なクエリが含まれています。 詳細については、「code scanning アラートについて」を参照してください。

Working with custom configuration files

If you also use a configuration file for custom settings, any additional packs or queries specified in your workflow are used instead of those specified in the configuration file. If you want to run the combined set of additional packs or queries, prefix the value of packs or queries in the workflow with the + symbol. For more information, see "Using a custom configuration file."

In the following example, the + symbol ensures that the specified additional packs and queries are used together with any specified in the referenced configuration file.

- uses: github/codeql-action/init@v2
  with:
    config-file: ./.github/codeql/codeql-config.yml
    queries: +security-and-quality,octo-org/python-qlpack/show_ifs.ql@main
    packs: +scope/pack1,scope/pack2@1.2.3,scope/pack3@4.5.6:path/to/queries

Using a custom configuration file

A custom configuration file is an alternative way to specify additional packs and queries to run. You can also use the file to disable the default queries, exclude or include specific queries, and to specify which directories to scan during analysis.

In the workflow file, use the config-file parameter of the init action to specify the path to the configuration file you want to use. This example loads the configuration file ./.github/codeql/codeql-config.yml.

- uses: github/codeql-action/init@v2
  with:
    config-file: ./.github/codeql/codeql-config.yml

構成ファイルは、分析するリポジトリ内、または外部リポジトリ内に格納できます。 外部リポジトリを使用すると、1 つの場所の複数のリポジトリに対して構成オプションを指定できます。 外部リポジトリにある構成ファイルを参照する場合は、 OWNER/REPOSITORY/FILENAME@BRANCH 構文を使用できます。 たとえば、 octo-org/shared/codeql-config.yml@main です。

If the configuration file is located in an external private repository, use the external-repository-token parameter of the init action to specify a token that has access to the private repository.

- uses: github/codeql-action/init@v2
  with:
    external-repository-token: ${{ secrets.ACCESS_TOKEN }}

The settings in the configuration file are written in YAML format.

Specifying CodeQL query packs

注: CodeQL パッケージ管理機能 (CodeQL パックを含む) は現在ベータ版であり、変更される可能性があります。

You specify CodeQL query packs in an array. Note that the format is different from the format used by the workflow file.

packs:
  # Use the latest version of 'pack1' published by 'scope'
  - scope/pack1
  # Use version 1.2.3 of 'pack2'
  - scope/pack2@1.2.3
  # Use the latest version of 'pack3' compatible with 3.2.1
  - scope/pack3@~3.2.1
  # Use pack4 and restrict it to queries found in the 'path/to/queries' directory
  - scope/pack4:path/to/queries
  # Use pack5 and restrict it to the query 'path/to/single/query.ql'
  - scope/pack5:path/to/single/query.ql
  # Use pack6 and restrict it to the query suite 'path/to/suite.qls'
  - scope/pack6:path/to/suite.qls

The full format for specifying a query pack is scope/name[@version][:path]. Both version and path are optional. version is semver version range. If it is missing, the latest version is used. For more information about semver ranges, see the semver docs on npm.

If you have a workflow that generates more than one CodeQL database, you can specify any CodeQL query packs to run in a custom configuration file using a nested map of packs.

packs:
  # Use these packs for JavaScript analysis
  javascript:
    - scope/js-pack1
    - scope/js-pack2
  # Use these packs for Java analysis
  java:
    - scope/java-pack1
    - scope/java-pack2@v1.0.0

Specifying additional queries

You specify additional queries in a queries array. Each element of the array contains a uses parameter with a value that identifies a single query file, a directory containing query files, or a query suite definition file.

queries:
  - uses: ./my-basic-queries/example-query.ql
  - uses: ./my-advanced-queries
  - uses: ./query-suites/my-security-queries.qls

Optionally, you can give each array element a name, as shown in the example configuration files below. For more information about additional queries, see "Running additional queries" above.

Disabling the default queries

If you only want to run custom queries, you can disable the default security queries by using disable-default-queries: true.

Excluding specific queries from analysis

You can add exclude and include filters to your custom configuration file, to specify the queries you want to exclude or include in the analysis.

This is useful if you want to exclude, for example:

  • Specific queries from the default suites (security, security-extended and security-and-quality).
  • Specific queries whose results do not interest you.
  • All the queries that generate warnings and recommendations.

You can use exclude filters similar to those in the configuration file below to exclude queries that you want to remove from the default analysis. In the example of configuration file below, both the js/redundant-assignment and the js/useless-assignment-to-local queries are excluded from analysis.

query-filters:
  - exclude:
      id: js/redundant-assignment
  - exclude:
      id: js/useless-assignment-to-local

To find the id of a query, you can click the alert in the list of alerts in the Security tab. This opens the alert details page. The Rule ID field contains the query id. For more information about the alert details page, see "About code scanning alerts."

Tips:

  • The order of the filters is important. The first filter instruction that appears after the instructions about the queries and query packs determines whether the queries are included or excluded by default.
  • Subsequent instructions are executed in order and the instructions that appear later in the file take precedence over the earlier instructions.

You can find another example illustrating the use of these filters in the "Example configuration files" section.

For more information about using exclude and include filters in your custom configuration file, see "Creating CodeQL query suites." For information on the query metadata you can filter on, see "Metadata for CodeQL queries."

Specifying directories to scan

For the interpreted languages that CodeQL supports (Python and JavaScript/TypeScript), you can restrict code scanning to files in specific directories by adding a paths array to the configuration file. You can exclude the files in specific directories from analysis by adding a paths-ignore array.

paths:
  - src
paths-ignore:
  - src/node_modules
  - '**/*.test.js'

Note:

  • The paths and paths-ignore keywords, used in the context of the code scanning configuration file, should not be confused with the same keywords when used for on.<push|pull_request>.paths in a workflow. When they are used to modify on.<push|pull_request> in a workflow, they determine whether the actions will be run when someone modifies code in the specified directories. For more information, see "Workflow syntax for GitHub Actions."
  • The filter pattern characters ?, +, [, ], and ! are not supported and will be matched literally.
  • ** characters can only be at the start or end of a line, or surrounded by slashes, and you can't mix ** and other characters. For example, foo/**, **/foo, and foo/**/bar are all allowed syntax, but **foo isn't. However you can use single stars along with other characters, as shown in the example. You'll need to quote anything that contains a * character.

For compiled languages, if you want to limit code scanning to specific directories in your project, you must specify appropriate build steps in the workflow. The commands you need to use to exclude a directory from the build will depend on your build system. For more information, see "Configuring the CodeQL workflow for compiled languages."

You can quickly analyze small portions of a monorepo when you modify code in specific directories. You'll need to both exclude directories in your build steps and use the paths-ignore and paths keywords for on.<push|pull_request> in your workflow.

Example configuration files

この構成ファイルは、コードのスキャン時に CodeQL によって実行されるクエリのリストに security-and-quality クエリ スイートを追加します。 使用できるクエリ スイートの詳細については、「追加のクエリを実行する」を参照してください。

name: "My CodeQL config"

queries:
  - uses: security-and-quality

以下の設定ファイルはデフォルトのクエリを無効化し、その代わりに実行するカスタムクエリのセットを指定します。 また、CodeQL が、src/node_modules ディレクトリと .test.js で名前が終わるファイルを除く、src ディレクトリ (ルートに対する相対) 内のファイルをスキャンするようにも設定します。 src/node_modules 内のファイルと末尾が .test.js で終わる名前のファイルは、分析から除外されます。

name: "My CodeQL config"

disable-default-queries: true

queries:
  - name: Use an in-repository QL pack (run queries in the my-queries directory)
    uses: ./my-queries
  - name: Use an external JavaScript QL pack (run queries from an external repo)
    uses: octo-org/javascript-qlpack@main
  - name: Use an external query (run a single query from an external QL pack)
    uses: octo-org/python-qlpack/show_ifs.ql@main
  - name: Use a query suite file (run queries from a query suite in this repo)
    uses: ./codeql-qlpacks/complex-python-qlpack/rootAndBar.qls

paths:
  - src 
paths-ignore: 
  - src/node_modules
  - '**/*.test.js'

次の構成ファイルを使用すると、重大度エラーのアラートを生成するクエリのみが実行されます。 構成では、最初にすべての既定のクエリ、./my-queries 内のすべてのクエリ、および codeql/java-queries 内の既定のスイートを選んでから、警告または推奨事項を生成するすべてのクエリを除外します。

queries:
  - name: Use an in-repository QL pack (run queries in the my-queries directory)
    uses: ./my-queries
packs:
  - codeql/java-queries
query-filters:
- exclude:
    problem.severity:
      - warning
      - recommendation

Configuring code scanning for compiled languages

サポートされているコンパイル言語の場合、CodeQL analysis workflow の autobuild アクションを使用してコードをビルドできます。 これにより、C/C++、C#、Java についての明示的なビルド コマンドを指定する必要がなくなります。 CodeQLは、プロジェクトをセットアップするためにGoのプロジェクトのビルドも実行します。 ただし、他のコンパイル済み言語と対照的に、ビルドされたものだけでなく、リポジトリ内のすべての Go ファイルが抽出されます。 カスタム ビルド コマンドを使用すると、ビルドによって使用されない Go ファイルの抽出をスキップできます。

リポジトリ内の C/C++、C#、または Java コードに非標準のビルド プロセスがあると、autobuild が失敗するおそれがあります。 ワークフローから autobuild ステップを削除し、手動でビルド ステップを追加する必要があります。 リポジトリのGoのファイルで展開するものを指定したい場合には、ビルドのステップを追加しなければなりません。 For more information about how to configure CodeQL code scanning for compiled languages, see "Configuring the CodeQL workflow for compiled languages."

Uploading code scanning data to GitHub

GitHub can display code analysis data generated externally by a third-party tool. You can upload code analysis data with the upload-sarif action. For more information, see "Uploading a SARIF file to GitHub."