mirror of
https://github.com/github/codeql-action
synced 2026-10-09 05:05:21 +03:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e36708483 | ||
|
|
fccc166683 | ||
|
|
f8f91fb336 | ||
|
|
58f39a7d42 | ||
|
|
40b3f0c1bc | ||
|
|
6e32e882a9 |
@@ -54,16 +54,15 @@ runs:
|
||||
env:
|
||||
CODEQL_ACTION_TEST_MODE: 'true'
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: npm install --location=global ts-node js-yaml
|
||||
|
||||
- name: Check config
|
||||
working-directory: ${{ github.action_path }}
|
||||
shell: bash
|
||||
env:
|
||||
EXPECTED_CONFIG_FILE_CONTENTS: '${{ inputs.expected-config-file-contents }}'
|
||||
run: ts-node ./index.ts "$RUNNER_TEMP/user-config.yaml" "$EXPECTED_CONFIG_FILE_CONTENTS"
|
||||
run: |
|
||||
npx tsx ../action/pr-checks/check-cs-config.ts \
|
||||
--file "$RUNNER_TEMP/user-config.yaml" \
|
||||
--expected-contents "$EXPECTED_CONFIG_FILE_CONTENTS"
|
||||
|
||||
- name: Clean up
|
||||
shell: bash
|
||||
if: always()
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
|
||||
import * as core from '@actions/core'
|
||||
import * as yaml from 'js-yaml'
|
||||
import * as fs from 'fs'
|
||||
import * as assert from 'assert'
|
||||
|
||||
const actualConfig = loadActualConfig()
|
||||
|
||||
function sortConfigArrays(config) {
|
||||
for (const key of Object.keys(config)) {
|
||||
const value = config[key];
|
||||
if (key === 'queries' && Array.isArray(value)) {
|
||||
config[key] = value.sort();
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
const rawExpectedConfig = process.argv[3].trim()
|
||||
if (!rawExpectedConfig) {
|
||||
core.setFailed('No expected configuration provided')
|
||||
} else {
|
||||
core.startGroup('Expected generated user config')
|
||||
core.info(yaml.dump(JSON.parse(rawExpectedConfig)))
|
||||
core.endGroup()
|
||||
}
|
||||
|
||||
const expectedConfig = rawExpectedConfig ? JSON.parse(rawExpectedConfig) : undefined;
|
||||
|
||||
assert.deepStrictEqual(
|
||||
sortConfigArrays(actualConfig),
|
||||
sortConfigArrays(expectedConfig),
|
||||
'Expected configuration does not match actual configuration'
|
||||
);
|
||||
|
||||
|
||||
function loadActualConfig() {
|
||||
if (!fs.existsSync(process.argv[2])) {
|
||||
core.info('No configuration file found')
|
||||
return undefined
|
||||
} else {
|
||||
const rawActualConfig = fs.readFileSync(process.argv[2], 'utf8')
|
||||
core.startGroup('Actual generated user config')
|
||||
core.info(rawActualConfig)
|
||||
core.endGroup()
|
||||
|
||||
return yaml.load(rawActualConfig)
|
||||
}
|
||||
}
|
||||
@@ -16,5 +16,23 @@ inputs:
|
||||
Comma separated list of query ids that should NOT be included in this SARIF file.
|
||||
|
||||
runs:
|
||||
using: node24
|
||||
main: index.js
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Run `check-sarif.ts`
|
||||
shell: bash
|
||||
env:
|
||||
SARIF_FILE: ${{ inputs.sarif-file }}
|
||||
QUERIES_RUN: ${{ inputs.queries-run }}
|
||||
QUERIES_NOT_RUN: ${{ inputs.queries-not-run }}
|
||||
run: |
|
||||
if [[ -d pr-checks ]]; then
|
||||
npx tsx ./pr-checks/check-sarif.ts \
|
||||
--sarif-file "$SARIF_FILE" \
|
||||
--queries-run "$QUERIES_RUN" \
|
||||
--queries-not-run "$QUERIES_NOT_RUN"
|
||||
else
|
||||
npx tsx ../action/pr-checks/check-sarif.ts \
|
||||
--sarif-file "$SARIF_FILE" \
|
||||
--queries-run "$QUERIES_RUN" \
|
||||
--queries-not-run "$QUERIES_NOT_RUN"
|
||||
fi
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const core = require('@actions/core')
|
||||
const fs = require('fs')
|
||||
|
||||
const sarif = JSON.parse(fs.readFileSync(core.getInput('sarif-file'), 'utf8'))
|
||||
const rules = sarif.runs[0].tool.extensions.flatMap(ext => ext.rules || [])
|
||||
const ruleIds = rules.map(rule => rule.id)
|
||||
|
||||
// Check that all the expected queries ran
|
||||
const expectedQueriesRun = getQueryIdsInput('queries-run')
|
||||
const queriesThatShouldHaveRunButDidNot = expectedQueriesRun.filter(queryId => !ruleIds.includes(queryId))
|
||||
|
||||
if (queriesThatShouldHaveRunButDidNot.length > 0) {
|
||||
core.setFailed(`The following queries were expected to run but did not: ${queriesThatShouldHaveRunButDidNot.join(', ')}`)
|
||||
}
|
||||
|
||||
// Check that all the unexpected queries did not run
|
||||
const expectedQueriesNotRun = getQueryIdsInput('queries-not-run')
|
||||
|
||||
const queriesThatShouldNotHaveRunButDid = expectedQueriesNotRun.filter(queryId => ruleIds.includes(queryId))
|
||||
|
||||
if (queriesThatShouldNotHaveRunButDid.length > 0) {
|
||||
core.setFailed(`The following queries were NOT expected to have run but did: ${queriesThatShouldNotHaveRunButDid.join(', ')}`)
|
||||
}
|
||||
|
||||
|
||||
core.startGroup('All queries run')
|
||||
rules.forEach(rule => {
|
||||
core.info(`${rule.id}: ${(rule.properties && rule.properties.name) || rule.name}`)
|
||||
})
|
||||
core.endGroup()
|
||||
|
||||
core.startGroup('Full SARIF')
|
||||
core.info(JSON.stringify(sarif, null, 2))
|
||||
core.endGroup()
|
||||
|
||||
function getQueryIdsInput(name) {
|
||||
return core.getInput(name)
|
||||
.split(',')
|
||||
.map(q => q.trim())
|
||||
.filter(q => q.length > 0)
|
||||
}
|
||||
@@ -92,7 +92,8 @@ runs:
|
||||
Please do the following:
|
||||
|
||||
- [ ] Approve running the full set of PR checks.
|
||||
- [ ] Approve and merge the PR. When merging the PR, make sure "Create a merge commit" is selected rather than "Squash and merge" or "Rebase and merge".
|
||||
- [ ] Approve and merge the PR. When merging the PR, make sure "Create a merge commit" is
|
||||
selected rather than "Squash and merge" or "Rebase and merge".
|
||||
EOF
|
||||
)
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
name: Update default CodeQL bundle
|
||||
description: Updates 'src/defaults.json' to point to a new CodeQL bundle release.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install ts-node
|
||||
shell: bash
|
||||
run: npm install -g ts-node
|
||||
|
||||
- name: Run update script
|
||||
working-directory: ${{ github.action_path }}
|
||||
shell: bash
|
||||
run: ts-node ./index.ts
|
||||
@@ -1,67 +0,0 @@
|
||||
import * as fs from 'fs';
|
||||
import * as github from '@actions/github';
|
||||
|
||||
interface BundleInfo {
|
||||
bundleVersion: string;
|
||||
cliVersion: string;
|
||||
}
|
||||
|
||||
interface Defaults {
|
||||
bundleVersion: string;
|
||||
cliVersion: string;
|
||||
priorBundleVersion: string;
|
||||
priorCliVersion: string;
|
||||
}
|
||||
|
||||
function getCodeQLCliVersionForRelease(release): string {
|
||||
// We do not currently tag CodeQL bundles based on the CLI version they contain.
|
||||
// Instead, we use a marker file `cli-version-<version>.txt` to record the CLI version.
|
||||
// This marker file is uploaded as a release asset for all new CodeQL bundles.
|
||||
const cliVersionsFromMarkerFiles = release.assets
|
||||
.map((asset) => asset.name.match(/cli-version-(.*)\.txt/)?.[1])
|
||||
.filter((v) => v)
|
||||
.map((v) => v as string);
|
||||
if (cliVersionsFromMarkerFiles.length > 1) {
|
||||
throw new Error(
|
||||
`Release ${release.tag_name} has multiple CLI version marker files.`
|
||||
);
|
||||
} else if (cliVersionsFromMarkerFiles.length === 0) {
|
||||
throw new Error(
|
||||
`Failed to find the CodeQL CLI version for release ${release.tag_name}.`
|
||||
);
|
||||
}
|
||||
return cliVersionsFromMarkerFiles[0];
|
||||
}
|
||||
|
||||
async function getBundleInfoFromRelease(release): Promise<BundleInfo> {
|
||||
return {
|
||||
bundleVersion: release.tag_name,
|
||||
cliVersion: getCodeQLCliVersionForRelease(release)
|
||||
};
|
||||
}
|
||||
|
||||
async function getNewDefaults(currentDefaults: Defaults): Promise<Defaults> {
|
||||
const release = github.context.payload.release;
|
||||
console.log('Updating default bundle as a result of the following release: ' +
|
||||
`${JSON.stringify(release)}.`)
|
||||
|
||||
const bundleInfo = await getBundleInfoFromRelease(release);
|
||||
return {
|
||||
bundleVersion: bundleInfo.bundleVersion,
|
||||
cliVersion: bundleInfo.cliVersion,
|
||||
priorBundleVersion: currentDefaults.bundleVersion,
|
||||
priorCliVersion: currentDefaults.cliVersion
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const previousDefaults: Defaults = JSON.parse(fs.readFileSync('../../../src/defaults.json', 'utf8'));
|
||||
const newDefaults = await getNewDefaults(previousDefaults);
|
||||
// Update the source file in the repository. Calling workflows should subsequently rebuild
|
||||
// the Action to update `lib/defaults.json`.
|
||||
fs.writeFileSync('../../../src/defaults.json', JSON.stringify(newDefaults, null, 2) + "\n");
|
||||
}
|
||||
|
||||
// Ideally, we'd await main() here, but that doesn't work well with `ts-node`.
|
||||
// So instead we rely on the fact that Node won't exit until the event loop is empty.
|
||||
main();
|
||||
@@ -1,33 +1,14 @@
|
||||
# CodeQL Action - Copilot Instructions
|
||||
|
||||
The CodeQL Action is used in GitHub Actions workflows to run CodeQL scans using the CodeQL CLI.
|
||||
|
||||
## Overview
|
||||
|
||||
- The repository contains two TypeScript projects.
|
||||
- The main TypeScript codebase is in the `src` directory, with accompanying unit tests in `.test.ts` files in the same directory.
|
||||
- The main codebase is compiled to bundled JavaScript code, which is also contained in the repository in the `lib` directory.
|
||||
- A secondary TypeScript codebase with scripts that are only used for development purposes or by CI is in the `pr-checks` directory. This codebase is not compiled to bundled JavaScript. It is executed directly with `tsx`, which handles compilation internally.
|
||||
|
||||
## Review instructions
|
||||
|
||||
- When wording review comments, be helpful and friendly. Assume that the PR author has written the code with the best of intentions. Word your comments constructively as suggestions for improvements. Do not word suggestions as commands.
|
||||
- If you want to comment on a change that you believe will fail a CI check, do not present the CI failure you expect as a fact. Instead, write that you think a change "may" lead to a failure in CI. Suggest that, if such a failure manifests, the changes you are commenting on may be the place responsible for the failure and are worth looking at.
|
||||
- If a suggestion you make is suitable for a follow-up, such as a refactoring that doesn't change the behaviour or fixing a typo in a comment, mention that it can be addressed in a later PR rather than blocking this one.
|
||||
- If a change is a net improvement, for example because it improves on an existing limitation of existing code, do not complain about pre-existing problems that remain. You may comment on them, but you should make it clear that the thing you are commenting on is not new by writing e.g. "Not new in this PR, but [..]" followed by your description of the issue and a suggestion that it could be improved at the same time with e.g. "Consider whether this is worth addressing as part of this PR as well."
|
||||
|
||||
## Generated code
|
||||
|
||||
The main codebase of the CodeQL Action is written in TypeScript and compiled to JavaScript. Both the TypeScript sources and the **generated** JavaScript code are contained in this repository. The TypeScript sources are contained in the `src` directory and the JavaScript code is contained in the `lib` directory. A GitHub Actions workflow checks that the JavaScript code in `lib` is up-to-date. Therefore, you should not review any changes to the contents of the `lib` folder and it is expected that the JavaScript code in `lib` closely mirrors the TypeScript code it is generated from. The secondary TypeScript codebase has sources in the `pr-checks` directory, which are executed directly with `tsx` and not compiled to JavaScript in the `lib` folder.
|
||||
The CodeQL Action is written in TypeScript and compiled to JavaScript. Both the TypeScript sources and the **generated** JavaScript code are contained in this repository. The TypeScript sources are contained in the `src` directory and the JavaScript code is contained in the `lib` directory. A GitHub Actions workflow checks that the JavaScript code in `lib` is up-to-date. Therefore, you should not review any changes to the contents of the `lib` folder and it is expected that the JavaScript code in `lib` closely mirrors the TypeScript code it is generated from.
|
||||
|
||||
GitHub Actions workflows in the `.github/workflows` directory whose filenames start with two underscores (e.g. `__all-platform-bundle.yml`) are automatically generated using the `pr-checks/sync.sh` script from template files in the `pr-checks/checks` directory. Therefore, you do not need to review files in the `.github/workflows` directory that start with two underscores. However, you should review changes to the `pr-checks` directory as well as workflows in the `.github/workflows` directory that do not start with underscores.
|
||||
|
||||
## Release process
|
||||
|
||||
Changes that are merged to the `main` branch are not used in production straight away. Instead, changes from `main` must first be released using the release process, which has to be manually triggered by a staff member. Therefore, it is possible for further changes to be made to the code after some changes have been merged to `main` but before they are released. Once the release process automation is started, a series of PRs are automatically generated:
|
||||
|
||||
- A release-PR is a PR which matches all of the following patterns:
|
||||
|
||||
- PR title starts with the exact prefix: `Merge main into releases/v`
|
||||
- Equivalent regex: `^Merge main into releases\/v`
|
||||
- AND head (source) branch matches the update-branch pattern:
|
||||
@@ -36,5 +17,5 @@ Changes that are merged to the `main` branch are not used in production straight
|
||||
- Regex: `^releases\/v` (e.g. `releases/v3`)
|
||||
|
||||
- Consider all files in release-PRs to have already been reviewed and do not review them, except for the following two files:
|
||||
- `CHANGELOG.md`
|
||||
- `package.json`
|
||||
- `CHANGELOG.md`
|
||||
- `package.json`
|
||||
|
||||
@@ -8,6 +8,8 @@ updates:
|
||||
interval: weekly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
exclude:
|
||||
- "@actions/*"
|
||||
labels:
|
||||
- Rebuild
|
||||
# Ignore incompatible dependency updates
|
||||
@@ -31,6 +33,8 @@ updates:
|
||||
interval: weekly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
exclude:
|
||||
- "actions/*"
|
||||
labels:
|
||||
- Rebuild
|
||||
groups:
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
applyTo: "CHANGELOG.md,src/defaults.json,lib/defaults.json,src/api-compatibility.json"
|
||||
---
|
||||
|
||||
# Merging release, mergeback, and backport PRs
|
||||
|
||||
The release process creates a cascade of PRs (`main` → `releases/vN`, then
|
||||
`releases/vN` → `main` mergeback, then `releases/vN` → `releases/v(N-1)`
|
||||
backport). These PRs reliably touch `CHANGELOG.md`, `src/defaults.json` /
|
||||
`lib/defaults.json` (bundle/CLI version bump), and `src/api-compatibility.json`.
|
||||
|
||||
Such PRs **must be merged with a merge commit**. Never squash or rebase, as
|
||||
that breaks the branch linkage the release automation relies on.
|
||||
|
||||
When arming auto-merge on these PRs, use `--merge` (e.g. `gh pr merge --merge`),
|
||||
not `--squash` or `--rebase`.
|
||||
+1
-1
@@ -56,7 +56,7 @@ jobs:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- os: macos-latest-xlarge
|
||||
- os: macos-latest
|
||||
version: nightly-latest
|
||||
- os: windows-latest
|
||||
version: nightly-latest
|
||||
|
||||
@@ -63,7 +63,7 @@ jobs:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install Java
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
|
||||
with:
|
||||
java-version: ${{ inputs.java-version || '17' }}
|
||||
distribution: temurin
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ jobs:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install Java
|
||||
uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
|
||||
with:
|
||||
java-version: ${{ inputs.java-version || '17' }}
|
||||
distribution: temurin
|
||||
|
||||
Generated
+1
-2
@@ -80,8 +80,7 @@ jobs:
|
||||
- id: init
|
||||
uses: ./../action/init
|
||||
with:
|
||||
# Request multiple languages so this check uses the combined bundle.
|
||||
languages: javascript,python
|
||||
languages: javascript
|
||||
tools: ${{ steps.prepare-test.outputs.tools-url }}
|
||||
- uses: ./../action/analyze
|
||||
with:
|
||||
|
||||
Generated
-2
@@ -51,8 +51,6 @@ jobs:
|
||||
with:
|
||||
node-version: 20.x
|
||||
cache: npm
|
||||
- name: Install newer npm
|
||||
run: npm install -g npm@11.19.1
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Prepare test
|
||||
|
||||
@@ -124,5 +124,4 @@ jobs:
|
||||
env:
|
||||
CODEQL_ACTION_SKIP_FILE_COVERAGE_ON_PRS: false
|
||||
CODEQL_ACTION_SUBLANGUAGE_FILE_COVERAGE: true
|
||||
CODEQL_ACTION_PER_LANGUAGE_BUNDLES: false
|
||||
CODEQL_ACTION_TEST_MODE: true
|
||||
|
||||
Generated
-106
@@ -1,106 +0,0 @@
|
||||
# Warning: This file is generated automatically, and should not be modified.
|
||||
# Instead, please modify the template in the pr-checks directory and run:
|
||||
# pr-checks/sync.sh
|
||||
# to regenerate this file.
|
||||
|
||||
name: PR Check - Linux Arm64
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GO111MODULE: auto
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- releases/v*
|
||||
pull_request: {}
|
||||
merge_group:
|
||||
types:
|
||||
- checks_requested
|
||||
schedule:
|
||||
- cron: '0 5 * * *'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dotnet-version:
|
||||
type: string
|
||||
description: The version of .NET to install
|
||||
required: false
|
||||
default: 9.x
|
||||
go-version:
|
||||
type: string
|
||||
description: The version of Go to install
|
||||
required: false
|
||||
default: '>=1.21.0'
|
||||
workflow_call:
|
||||
inputs:
|
||||
dotnet-version:
|
||||
type: string
|
||||
description: The version of .NET to install
|
||||
required: false
|
||||
default: 9.x
|
||||
go-version:
|
||||
type: string
|
||||
description: The version of Go to install
|
||||
required: false
|
||||
default: '>=1.21.0'
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
concurrency:
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || false }}
|
||||
group: linux-arm64-${{github.ref}}-${{inputs.dotnet-version}}-${{inputs.go-version}}
|
||||
jobs:
|
||||
linux-arm64:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-24.04-arm
|
||||
version: nightly-latest
|
||||
name: Linux Arm64
|
||||
if: github.triggering_actor != 'dependabot[bot]'
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: read
|
||||
timeout-minutes: 45
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install .NET
|
||||
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
|
||||
with:
|
||||
dotnet-version: ${{ inputs.dotnet-version || '9.x' }}
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: ${{ inputs.go-version || '>=1.21.0' }}
|
||||
cache: false
|
||||
- name: Prepare test
|
||||
id: prepare-test
|
||||
uses: ./.github/actions/prepare-test
|
||||
with:
|
||||
version: ${{ matrix.version }}
|
||||
use-all-platform-bundle: 'false'
|
||||
setup-kotlin: 'true'
|
||||
- uses: ./../action/init
|
||||
with:
|
||||
languages: ${{ env.LANGUAGES }}
|
||||
tools: ${{ steps.prepare-test.outputs.tools-url }}
|
||||
- name: Build code
|
||||
run: ./build.sh
|
||||
- uses: ./../action/analyze
|
||||
with:
|
||||
upload-database: false
|
||||
- name: Assert databases exist
|
||||
run: |
|
||||
cd "$RUNNER_TEMP/codeql_databases"
|
||||
for lang in ${LANGUAGES//,/ }; do
|
||||
if [[ ! -d "$lang" ]]; then
|
||||
echo "Did not find a database for $lang"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found database for $lang"
|
||||
done
|
||||
env:
|
||||
LANGUAGES: cpp,csharp,go,java,javascript,python,ruby
|
||||
CODEQL_ACTION_TEST_MODE: true
|
||||
+3
-5
@@ -116,14 +116,13 @@ jobs:
|
||||
version: ${{ matrix.version }}
|
||||
use-all-platform-bundle: 'false'
|
||||
setup-kotlin: 'true'
|
||||
- name: Install Python 3.13.15 for older CLI versions
|
||||
# Older CLI versions don't work with Python 3.13.16 or newer because their Python extractor
|
||||
# imports `importlib._bootstrap._ERR_MSG`, which those Python versions no longer define.
|
||||
- name: Install Python 3.13 for older CLI versions
|
||||
# We need Python 3.13 for older CLI versions because they are not compatible with Python 3.14 or newer.
|
||||
# See https://github.com/github/codeql-action/pull/3212
|
||||
if: matrix.version != 'nightly-latest' && matrix.version != 'linked'
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: '3.13.15'
|
||||
python-version: '3.13'
|
||||
|
||||
- name: Use Xcode 16
|
||||
# Only the older CodeQL CLI versions need Xcode 16, and these run on macOS 15.
|
||||
@@ -192,6 +191,5 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
env:
|
||||
CODEQL_ACTION_CLEANUP_TOOLCACHE_BUNDLES: true
|
||||
CODEQL_ACTION_RESOLVE_SUPPORTED_LANGUAGES_USING_CLI: true
|
||||
CODEQL_ACTION_TEST_MODE: true
|
||||
|
||||
@@ -84,8 +84,6 @@ jobs:
|
||||
with:
|
||||
node-version: 20.x
|
||||
cache: npm
|
||||
- name: Install newer npm
|
||||
run: npm install -g npm@11.19.1
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Prepare test
|
||||
|
||||
@@ -84,8 +84,6 @@ jobs:
|
||||
with:
|
||||
node-version: 20.x
|
||||
cache: npm
|
||||
- name: Install newer npm
|
||||
run: npm install -g npm@11.19.1
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Prepare test
|
||||
|
||||
-2
@@ -84,8 +84,6 @@ jobs:
|
||||
with:
|
||||
node-version: 20.x
|
||||
cache: npm
|
||||
- name: Install newer npm
|
||||
run: npm install -g npm@11.19.1
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Prepare test
|
||||
|
||||
-2
@@ -84,8 +84,6 @@ jobs:
|
||||
with:
|
||||
node-version: 20.x
|
||||
cache: npm
|
||||
- name: Install newer npm
|
||||
run: npm install -g npm@11.19.1
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Prepare test
|
||||
|
||||
-164
@@ -1,164 +0,0 @@
|
||||
# Warning: This file is generated automatically, and should not be modified.
|
||||
# Instead, please modify the template in the pr-checks directory and run:
|
||||
# pr-checks/sync.sh
|
||||
# to regenerate this file.
|
||||
|
||||
name: PR Check - Per-language bundles
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GO111MODULE: auto
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- releases/v*
|
||||
pull_request: {}
|
||||
merge_group:
|
||||
types:
|
||||
- checks_requested
|
||||
schedule:
|
||||
- cron: '0 5 * * *'
|
||||
workflow_dispatch:
|
||||
inputs: {}
|
||||
workflow_call:
|
||||
inputs: {}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
concurrency:
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || false }}
|
||||
group: per-language-bundle-validation-${{github.ref}}
|
||||
jobs:
|
||||
per-language-bundle-validation:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- language: actions
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
expected-extractors: actions javascript
|
||||
- language: cpp
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
build-mode: manual
|
||||
build-command: gcc -o main main.c
|
||||
- language: csharp
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
build-mode: none
|
||||
- language: go
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
build-mode: autobuild
|
||||
- language: java
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
build-mode: none
|
||||
- language: javascript
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- language: python
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- language: ruby
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- language: rust
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- language: swift
|
||||
os: macos-latest-xlarge
|
||||
version: nightly-latest
|
||||
build-mode: autobuild
|
||||
name: Per-language bundles
|
||||
if: github.triggering_actor != 'dependabot[bot]'
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: read
|
||||
timeout-minutes: 45
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Prepare test
|
||||
id: prepare-test
|
||||
uses: ./.github/actions/prepare-test
|
||||
with:
|
||||
version: ${{ matrix.version }}
|
||||
use-all-platform-bundle: 'false'
|
||||
setup-kotlin: 'true'
|
||||
- uses: ./../action/init
|
||||
id: init
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix['build-mode'] }}
|
||||
tools: ${{ steps.prepare-test.outputs.tools-url }}
|
||||
- name: Check that the bundle contains only the expected extractors
|
||||
env:
|
||||
CODEQL_PATH: ${{ steps.init.outputs.codeql-path }}
|
||||
LANGUAGE: ${{ matrix.language }}
|
||||
EXPECTED_EXTRACTORS: ${{ matrix['expected-extractors'] || matrix.language }}
|
||||
run: |
|
||||
extractors="$("$CODEQL_PATH" resolve languages --format=json | jq -r 'keys[]')"
|
||||
echo "Extractors in the bundle:"
|
||||
echo "$extractors"
|
||||
echo "Expected: $EXPECTED_EXTRACTORS"
|
||||
|
||||
for expected in $EXPECTED_EXTRACTORS; do
|
||||
if ! echo "$extractors" | grep -qx "$expected"; then
|
||||
echo "::error::The ${LANGUAGE} bundle does not contain the ${expected} extractor."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# If the bundle contained extractors beyond those the language needs, then it would not
|
||||
# have been trimmed, and this job would be silently validating the combined bundle.
|
||||
for other in actions cpp csharp go java javascript python ruby rust swift; do
|
||||
if echo "$EXPECTED_EXTRACTORS" | grep -qw "$other"; then
|
||||
continue
|
||||
fi
|
||||
if echo "$extractors" | grep -qx "$other"; then
|
||||
echo "::error::The ${LANGUAGE} bundle also contains the ${other} extractor, so it is not trimmed."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
- name: Check that the bundle was not added to the toolcache
|
||||
env:
|
||||
CODEQL_PATH: ${{ steps.init.outputs.codeql-path }}
|
||||
run: |
|
||||
# A bundle that is missing most of its extractors must never be left in the toolcache,
|
||||
# where a later job analyzing a different language could pick it up. The runner image
|
||||
# ships with its own CodeQL in the toolcache, so check where this bundle was extracted to
|
||||
# rather than whether the toolcache contains CodeQL at all.
|
||||
echo "CodeQL is at $CODEQL_PATH"
|
||||
if [[ "$CODEQL_PATH" == "$RUNNER_TOOL_CACHE"/* ]]; then
|
||||
echo "::error::The per-language bundle was added to the toolcache at $CODEQL_PATH."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CODEQL_PATH" != "$RUNNER_TEMP"/* ]]; then
|
||||
echo "::error::Expected the per-language bundle to be extracted under $RUNNER_TEMP, but found it at $CODEQL_PATH."
|
||||
exit 1
|
||||
fi
|
||||
- name: Build code
|
||||
if: matrix['build-command']
|
||||
run: ${{ matrix['build-command'] }}
|
||||
- uses: ./../action/analyze
|
||||
id: analysis
|
||||
with:
|
||||
upload-database: false
|
||||
- name: Check that a database was created for the language
|
||||
env:
|
||||
DB_LOCATIONS: ${{ steps.analysis.outputs.db-locations }}
|
||||
LANGUAGE: ${{ matrix.language }}
|
||||
run: |
|
||||
database="$(echo "$DB_LOCATIONS" | jq -r --arg lang "$LANGUAGE" '.[$lang] // empty')"
|
||||
if [ -z "$database" ] || [ ! -d "$database" ]; then
|
||||
echo "::error::No CodeQL database was created for ${LANGUAGE}."
|
||||
echo "Databases: $DB_LOCATIONS"
|
||||
exit 1
|
||||
fi
|
||||
echo "Created a ${LANGUAGE} database at ${database}."
|
||||
env:
|
||||
CODEQL_ACTION_PER_LANGUAGE_BUNDLES: true
|
||||
CODEQL_ACTION_TEST_MODE: true
|
||||
+1
-1
@@ -54,7 +54,7 @@ jobs:
|
||||
use-all-platform-bundle: 'false'
|
||||
setup-kotlin: 'true'
|
||||
- name: Set up Ruby
|
||||
uses: ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8 # v1.327.0
|
||||
uses: ruby/setup-ruby@95ef2b042f9d7a56d8268cba8559e2842e2ad01b # v1.321.0
|
||||
with:
|
||||
ruby-version: 2.6
|
||||
- name: Install Code Scanning integration
|
||||
|
||||
+3
-3
@@ -54,11 +54,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: macos-latest-xlarge
|
||||
- os: macos-latest
|
||||
version: linked
|
||||
- os: macos-latest-xlarge
|
||||
- os: macos-latest
|
||||
version: default
|
||||
- os: macos-latest-xlarge
|
||||
- os: macos-latest
|
||||
version: nightly-latest
|
||||
name: Swift analysis using a custom build command
|
||||
if: github.triggering_actor != 'dependabot[bot]'
|
||||
|
||||
@@ -75,8 +75,7 @@ jobs:
|
||||
uses: ./../action/.github/actions/check-codescanning-config
|
||||
with:
|
||||
expected-config-file-contents: "{}"
|
||||
# Request multiple languages so later checks can reuse the combined bundle.
|
||||
languages: javascript,python
|
||||
languages: javascript
|
||||
tools: ${{ steps.prepare-test.outputs.tools-url }}
|
||||
|
||||
- name: Packs from input
|
||||
|
||||
@@ -45,13 +45,7 @@ jobs:
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "npm"
|
||||
|
||||
# Install a new enough version of `npm` to understand `min-release-age`
|
||||
# that is still compatible with Node 20.
|
||||
- name: Install newer npm
|
||||
if: matrix.node-version == 20
|
||||
run: npm install -g npm@11.19.1
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
@@ -61,7 +55,7 @@ jobs:
|
||||
npm ci
|
||||
|
||||
- name: Verify compiled JS up to date
|
||||
run: .github/workflows/script/check-js.sh
|
||||
run: npx tsx pr-checks/check-js.ts
|
||||
|
||||
- name: Run unit tests
|
||||
if: always()
|
||||
@@ -73,12 +67,7 @@ jobs:
|
||||
|
||||
- name: Upload sarif
|
||||
uses: ./upload-sarif
|
||||
# The merge queue deletes its `gh-readonly-queue` ref as soon as the queue entry resolves,
|
||||
# so uploading against it races with that deletion. Both the `merge_group` run and the
|
||||
# paired `push` run that the queue branch creates use that ref, so gate on the ref itself
|
||||
# rather than the event. The same results are uploaded by the `pull_request` run and again
|
||||
# by the `push` run on `main`.
|
||||
if: matrix.os == 'ubuntu-latest' && matrix.node-version == 24 && !startsWith(github.ref, 'refs/heads/gh-readonly-queue/')
|
||||
if: matrix.os == 'ubuntu-latest' && matrix.node-version == 24
|
||||
with:
|
||||
sarif_file: eslint.sarif
|
||||
category: eslint
|
||||
@@ -101,19 +90,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Check for incorrect addresses in package-lock.json
|
||||
run: |
|
||||
if git grep -nE '(pkgs\.visualstudio\.com|pkgs\.dev\.azure\.com|packagefeedproxy\.microsoft\.io)' -- \
|
||||
'package-lock.json'; then
|
||||
echo "::error::package-lock.json contains internal package feed URLs. Replace them with public registry URLs."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: "npm"
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
id: install-deps
|
||||
@@ -128,10 +109,6 @@ jobs:
|
||||
working-directory: pr-checks
|
||||
run: npx tsx --test
|
||||
|
||||
- name: Run `pr-checks/changenotes.ts` to ensure that all unreleased change notes are valid
|
||||
if: ${{ !cancelled() && steps.install-deps.outcome == 'success' }}
|
||||
run: npx tsx pr-checks/changenotes.ts validate
|
||||
|
||||
- name: Verify all Actions use the same Node version
|
||||
id: head-version
|
||||
run: |
|
||||
@@ -181,14 +158,14 @@ jobs:
|
||||
path: ${{ runner.temp }}/repo-size/
|
||||
if-no-files-found: error
|
||||
|
||||
- name: "Backport: Check out base ref"
|
||||
- name: 'Backport: Check out base ref'
|
||||
id: checkout-base
|
||||
if: ${{ startsWith(github.head_ref, 'backport-') }}
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.base_ref }}
|
||||
|
||||
- name: "Backport: Verify Node versions unchanged"
|
||||
- name: 'Backport: Verify Node versions unchanged'
|
||||
if: steps.checkout-base.outcome == 'success'
|
||||
env:
|
||||
HEAD_VERSION: ${{ steps.head-version.outputs.node_version }}
|
||||
|
||||
@@ -28,7 +28,7 @@ defaults:
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
name: "Release info"
|
||||
name: "Prepare release"
|
||||
runs-on: ubuntu-latest
|
||||
if: github.repository == 'github/codeql-action'
|
||||
|
||||
|
||||
@@ -54,27 +54,32 @@ jobs:
|
||||
run: |
|
||||
git fetch origin "$BASE_BRANCH"
|
||||
|
||||
# Allow merge conflicts in `lib`, since rebuilding should resolve them. Conflicts leave the
|
||||
# merge in progress, so check for `MERGE_HEAD` to tell them apart from failures that don't.
|
||||
if git merge "origin/$BASE_BRANCH"; then
|
||||
# Allow merge conflicts in `lib`, since rebuilding should resolve them.
|
||||
git merge "origin/$BASE_BRANCH"
|
||||
MERGE_RESULT=$?
|
||||
|
||||
if [ "$MERGE_RESULT" -eq 0 ]; then
|
||||
echo "Merge succeeded cleanly."
|
||||
elif git rev-parse --verify MERGE_HEAD >/dev/null 2>&1; then
|
||||
echo "Merge conflicts detected, continuing."
|
||||
elif [ "$MERGE_RESULT" -eq 1 ]; then
|
||||
echo "Merge conflicts detected (exit code $MERGE_RESULT), continuing."
|
||||
else
|
||||
echo "git merge failed with unexpected exit code $MERGE_RESULT."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$MERGE_RESULT" -ne 0 ]; then
|
||||
echo "merge-in-progress=true" >> $GITHUB_OUTPUT
|
||||
|
||||
# Check for merge conflicts outside of `lib`.
|
||||
CONFLICTS_OUTSIDE_LIB=$(git diff --name-only --diff-filter=U | grep --invert-match '^lib/' || true)
|
||||
if [ -n "$CONFLICTS_OUTSIDE_LIB" ]; then
|
||||
# Check for merge conflicts outside of `lib`. Disable git diff's trailing whitespace check
|
||||
# since `node_modules/@types/semver/README.md` fails it.
|
||||
if git -c core.whitespace=-trailing-space diff --check | grep --invert-match '^lib/'; then
|
||||
echo "Merge conflicts were detected outside of the lib directory. Please resolve them manually."
|
||||
echo "$CONFLICTS_OUTSIDE_LIB"
|
||||
git -c core.whitespace=-trailing-space diff --check | grep --invert-match '^lib/' || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "No merge conflicts found outside the lib directory. We should be able to resolve all of" \
|
||||
"these by rebuilding the Action."
|
||||
else
|
||||
echo "git merge failed for a reason other than merge conflicts."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Compile TypeScript
|
||||
|
||||
@@ -10,7 +10,8 @@ on:
|
||||
required: true
|
||||
# Only for dry-runs of changes to the workflow.
|
||||
push:
|
||||
# Don't run dry-run on release branches, since that's unnecessary.
|
||||
# Don't run dry-run on release branches, to avoid an issue where the
|
||||
# "new" tag determined by the "Prepare release" job already exists.
|
||||
branches-ignore:
|
||||
- releases/v*
|
||||
paths:
|
||||
@@ -23,7 +24,7 @@ defaults:
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
name: "Prepare"
|
||||
name: "Prepare release"
|
||||
if: github.repository == 'github/codeql-action'
|
||||
|
||||
permissions:
|
||||
@@ -106,10 +107,8 @@ jobs:
|
||||
# We usually expect to checkout `inputs.rollback-tag` (required for `workflow_dispatch`),
|
||||
# but use `v0.0.0` for testing.
|
||||
ROLLBACK_TAG: ${{ inputs.rollback-tag || 'v0.0.0' }}
|
||||
# Use `needs.prepare.outputs.version` for actual runs and `v0.0.1` for testing.
|
||||
RELEASE_TAG: ${{ case(github.event_name == 'workflow_dispatch', needs.prepare.outputs.version, 'v0.0.1') }}
|
||||
# Use `needs.prepare.outputs.major_version` for actual runs and `v0` for testing.
|
||||
MAJOR_VERSION_TAG: ${{ case(github.event_name == 'workflow_dispatch', needs.prepare.outputs.major_version, 'v0') }}
|
||||
RELEASE_TAG: ${{ needs.prepare.outputs.version }}
|
||||
MAJOR_VERSION_TAG: ${{ needs.prepare.outputs.major_version }}
|
||||
run: |
|
||||
git checkout "refs/tags/${ROLLBACK_TAG}"
|
||||
git tag --annotate "${RELEASE_TAG}" --message "${RELEASE_TAG}"
|
||||
@@ -185,3 +184,4 @@ jobs:
|
||||
# Setting this to `true` for non-workflow_dispatch events will
|
||||
# still push the `branch`, but won't create a corresponding PR
|
||||
dry-run: "${{ github.event_name != 'workflow_dispatch' }}"
|
||||
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -eu
|
||||
|
||||
# Sanity check that repo is clean to start with
|
||||
if [ ! -z "$(git status --porcelain)" ]; then
|
||||
# If we get a fail here then this workflow needs attention...
|
||||
>&2 echo "Failed: Repo should be clean before testing!"
|
||||
exit 1
|
||||
fi
|
||||
# Wipe the lib directory in case there are extra unnecessary files in there
|
||||
rm -rf lib
|
||||
# Generate the JavaScript files
|
||||
npm run-script build
|
||||
# Check that repo is still clean
|
||||
if [ ! -z "$(git status --porcelain)" ]; then
|
||||
# If we get a fail here then the PR needs attention
|
||||
>&2 echo "Failed: JavaScript files are not up to date. Run 'rm -rf lib && npm run-script build' to update"
|
||||
git status
|
||||
|
||||
echo "### Transpiled JS diff" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo '```diff' >> $GITHUB_STEP_SUMMARY
|
||||
git diff --output="$RUNNER_TEMP/js.diff"
|
||||
cat "$RUNNER_TEMP/js.diff" >> $GITHUB_STEP_SUMMARY
|
||||
echo '```' >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
# Reset bundled files to allow other checks to test for changes
|
||||
git checkout lib
|
||||
|
||||
# Fail this check
|
||||
exit 1
|
||||
fi
|
||||
echo "Success: JavaScript files are up to date"
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
run: npm ci
|
||||
|
||||
- name: Update bundle
|
||||
uses: ./.github/actions/update-bundle
|
||||
run: npx tsx pr-checks/update-bundle.ts
|
||||
|
||||
- name: Set up CodeQL CLI from new bundle
|
||||
id: setup-codeql
|
||||
|
||||
@@ -16,15 +16,15 @@ defaults:
|
||||
shell: bash
|
||||
|
||||
jobs:
|
||||
|
||||
prepare:
|
||||
name: "Prepare"
|
||||
name: "Prepare release"
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
uses: ./.github/workflows/prepare-release.yml
|
||||
|
||||
update:
|
||||
name: "Update release branch"
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
@@ -77,7 +77,6 @@ jobs:
|
||||
--conductor ${GITHUB_ACTOR}
|
||||
|
||||
backport:
|
||||
name: "Create backport"
|
||||
timeout-minutes: 45
|
||||
runs-on: ubuntu-latest
|
||||
environment: Automation
|
||||
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: github/enterprise-releases
|
||||
token: ${{ secrets.CODEQL_CI_ENTERPRISE_RELEASE_PAT }}
|
||||
token: ${{ secrets.ENTERPRISE_RELEASE_TOKEN }}
|
||||
path: ${{ github.workspace }}/enterprise-releases/
|
||||
sparse-checkout: releases.json
|
||||
|
||||
|
||||
Vendored
+1
-5
@@ -7,10 +7,6 @@
|
||||
// transpiled JavaScript
|
||||
"build": true,
|
||||
"lib": true,
|
||||
|
||||
// exclude "tests" by default because it causes VSCode to start language-specific extensions
|
||||
// that are not typically needed during development (or indeed may not work correctly)
|
||||
"tests": true
|
||||
},
|
||||
"search.exclude": {
|
||||
"**/node_modules": true,
|
||||
@@ -22,7 +18,7 @@
|
||||
"git.ignoreLimitWarning": true,
|
||||
// Use the vendored TypeScript version to have a consistent development experience across
|
||||
// machines.
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib",
|
||||
"typescript.tsdk": "node_modules/typescript/lib",
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
},
|
||||
|
||||
@@ -6,46 +6,6 @@ See the [releases page](https://github.com/github/codeql-action/releases) for th
|
||||
|
||||
No user facing changes.
|
||||
|
||||
## 4.38.3 - 08 Oct 2026
|
||||
|
||||
- _Upcoming breaking change_: CodeQL version 2.21.2 and earlier were discontinued on 24 September 2026 alongside GitHub Enterprise Server 3.17, and will be unsupported by the next minor release of the CodeQL Action. Added a deprecation warning for customers using these versions of CodeQL. [#4188](https://github.com/github/codeql-action/pull/4188)
|
||||
- Update default CodeQL bundle version to [2.27.2](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.27.2). [#4203](https://github.com/github/codeql-action/pull/4203)
|
||||
- Fixed a bug where the decision of whether to use a per-language bundle did not account for custom configurations that reference queries outside of compiled CodeQL packs. This issue was caught during internal testing and did not affect any customer repositories. We will resume the roll out of per-language bundles in the coming weeks. [#4184](https://github.com/github/codeql-action/pull/4184)
|
||||
|
||||
## 4.38.2 - 24 Sept 2026
|
||||
|
||||
- Update default CodeQL bundle version to [2.27.1](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.27.1). [#4160](https://github.com/github/codeql-action/pull/4160)
|
||||
|
||||
## 4.38.1 - 18 Sept 2026
|
||||
|
||||
- The CodeQL Action now has experimental support for CodeQL releases for which per-language bundles are available. Per-language bundles support analysis for a single language and are therefore smaller than the combined bundles that allow analysis for all supported languages. As a result, per-language bundles take up less space on disk and are faster to download. We expect to roll this change out to everyone in the coming weeks. [#4146](https://github.com/github/codeql-action/pull/4146)
|
||||
|
||||
## 4.38.0 - 09 Sept 2026
|
||||
|
||||
- On GitHub-hosted runners, the CodeQL Action now deletes unused CodeQL bundles from the toolcache before downloading a different bundle, which frees up disk space for the analysis. We expect to roll this change out to everyone in September. [#4124](https://github.com/github/codeql-action/pull/4124)
|
||||
- The CodeQL Action now supports CodeQL releases that are compatible with Linux Arm64 and downloads the native `linux-arm64` CodeQL bundle when available. [#4072](https://github.com/github/codeql-action/pull/4072)
|
||||
- Update default CodeQL bundle version to [2.27.0](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.27.0). [#4129](https://github.com/github/codeql-action/pull/4129)
|
||||
|
||||
## 4.37.9 - 26 Aug 2026
|
||||
|
||||
- Update default CodeQL bundle version to [2.26.4](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.26.4). [#4106](https://github.com/github/codeql-action/pull/4106)
|
||||
|
||||
## 4.37.8 - 21 Aug 2026
|
||||
|
||||
No user facing changes.
|
||||
|
||||
## 4.37.7 - 13 Aug 2026
|
||||
|
||||
- Update default CodeQL bundle version to [2.26.3](https://github.com/github/codeql-action/releases/tag/codeql-bundle-v2.26.3). [#4085](https://github.com/github/codeql-action/pull/4085)
|
||||
|
||||
## 4.37.6 - 04 Aug 2026
|
||||
|
||||
- Changed the default filepath for the new remote file address format that was introduced in CodeQL Action 4.37.0 / 3.37.0 to `.github/codeql-config.yml` to align it with the suggested path that is used elsewhere. [#4070](https://github.com/github/codeql-action/pull/4070)
|
||||
|
||||
## 4.37.5 - 03 Aug 2026
|
||||
|
||||
- Fixed a bug where a network error while streaming the download of the CodeQL bundle could terminate the `init` Action instead of falling back to downloading the bundle before extracting it. [#4061](https://github.com/github/codeql-action/pull/4061)
|
||||
|
||||
## 4.37.4 - 29 Jul 2026
|
||||
|
||||
- This version of the CodeQL Action adds support for the `tools` input for the `codeql-action/init` step to be specified using a `github-codeql-tools` [repository property](https://docs.github.com/en/organizations/managing-organization-settings/managing-custom-properties-for-repositories-in-your-organization). This feature will gradually be rolled out following the release of this version. Once rolled out, this allows for the CodeQL CLI version that is used in GitHub-managed workflows, such as Default Setup, to be set to a custom value. For example, customers who run into issues with rate limits when a new CodeQL CLI version is released can set the value to `toolcache` to always use the CodeQL CLI version that is available in the runner toolcache. For Advanced Setup workflows, the value provided for `tools` in the workflow definition always takes precedence unless the value of the repository property starts with `!`. [#4037](https://github.com/github/codeql-action/pull/4037)
|
||||
|
||||
+2
-5
@@ -60,13 +60,10 @@ Here are a few things you can do that will increase the likelihood of your pull
|
||||
This workflow goes through the pull requests that have been merged to `main` since the last release, creates a changelog, then opens a pull request to merge the changes since the last release into the `releases/v3` release branch.
|
||||
|
||||
You can start a release by triggering this workflow via [workflow dispatch](https://github.com/github/codeql-action/actions/workflows/update-release-branch.yml).
|
||||
1. The workflow run will open a pull request titled "Merge main into releases/v3". Follow the steps on the checklist in the pull request. Once you've checked off all but the last two of these, approve the PR and automerge it **with a merge commit** (`gh pr merge --merge`).
|
||||
1. The workflow run will open a pull request titled "Merge main into releases/v3". Follow the steps on the checklist in the pull request. Once you've checked off all but the last two of these, approve the PR and automerge it.
|
||||
1. When the "Merge main into releases/v3" pull request is merged into the `releases/v3` branch, a mergeback pull request to `main` will be automatically created. This mergeback pull request incorporates the changelog updates into `main`, tags the release using the merge commit of the "Merge main into releases/v3" pull request, and bumps the patch version of the CodeQL Action.
|
||||
1. If a backport to an older major version is required, a pull request targeting that version's branch will also be automatically created.
|
||||
1. Approve the mergeback and backport pull request (if applicable) and automerge them **with a merge commit** (`gh pr merge --merge`).
|
||||
|
||||
> [!NOTE]
|
||||
> The release, mergeback, and backport pull requests must always be merged with a merge commit — **never squash or rebase**. The mergeback tags the release using the merge commit of the "Merge main into releases/v3" pull request, so squashing or rebasing breaks tagging and the branch linkage the release automation relies on.
|
||||
1. Approve the mergeback and backport pull request (if applicable) and automerge them.
|
||||
|
||||
Once the mergeback and backport pull request have been merged, the release is complete.
|
||||
|
||||
|
||||
@@ -72,11 +72,12 @@ We typically release new minor versions of the CodeQL Action and Bundle when a n
|
||||
|
||||
| Minimum CodeQL Action | Minimum CodeQL Bundle Version | GitHub Environment | Notes |
|
||||
|-----------------------|-------------------------------|--------------------|-------|
|
||||
| `v4.36.2` | `2.25.6` | Enterprise Server 3.22 | |
|
||||
| `v4.33.0` | `2.24.3` | Enterprise Server 3.21 | |
|
||||
| `v4.31.10` | `2.23.9` | Enterprise Server 3.20 | |
|
||||
| `v3.29.11` | `2.22.4` | Enterprise Server 3.19 | |
|
||||
| `v3.28.21` | `2.21.3` | Enterprise Server 3.18 | |
|
||||
| `v3.28.12` | `2.20.7` | Enterprise Server 3.17 | |
|
||||
| `v3.28.6` | `2.20.3` | Enterprise Server 3.16 | |
|
||||
|
||||
See the full list of GHES release and deprecation dates at [GitHub Enterprise Server releases](https://docs.github.com/en/enterprise-server/admin/all-releases#releases-of-github-enterprise-server).
|
||||
|
||||
|
||||
@@ -164,13 +164,6 @@ inputs:
|
||||
[Internal] The ID of the check run, as provided by the Actions runtime environment. Do not set this value manually.
|
||||
default: ${{ job.check_run_id }}
|
||||
required: false
|
||||
job-status:
|
||||
description: >-
|
||||
[Internal] The status of the job, as provided by the Actions runtime environment. This is how the
|
||||
post step learns whether the job as a whole succeeded, failed, or was cancelled. Do not set this
|
||||
value manually.
|
||||
default: ${{ job.status }}
|
||||
required: false
|
||||
outputs:
|
||||
codeql-path:
|
||||
description: The path of the CodeQL binary used for analysis
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"bundleVersion": "codeql-bundle-v2.27.2",
|
||||
"cliVersion": "2.27.2",
|
||||
"priorBundleVersion": "codeql-bundle-v2.27.1",
|
||||
"priorCliVersion": "2.27.1"
|
||||
"bundleVersion": "codeql-bundle-v2.26.2",
|
||||
"cliVersion": "2.26.2",
|
||||
"priorBundleVersion": "codeql-bundle-v2.26.1",
|
||||
"priorCliVersion": "2.26.1"
|
||||
}
|
||||
|
||||
Generated
+13883
-39338
File diff suppressed because one or more lines are too long
Generated
+530
-1239
File diff suppressed because it is too large
Load Diff
+18
-18
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "codeql",
|
||||
"version": "4.38.4",
|
||||
"version": "4.37.5",
|
||||
"private": true,
|
||||
"description": "CodeQL action",
|
||||
"scripts": {
|
||||
@@ -30,50 +30,50 @@
|
||||
"@actions/http-client": "^3.0.0",
|
||||
"@actions/io": "^2.0.0",
|
||||
"@actions/tool-cache": "^3.0.1",
|
||||
"@octokit/core": "^7.0.8",
|
||||
"@octokit/plugin-paginate-rest": "^15.0.0",
|
||||
"@octokit/plugin-rest-endpoint-methods": "^18.0.0",
|
||||
"@octokit/plugin-retry": "^8.1.1",
|
||||
"@octokit/core": "^7.0.6",
|
||||
"@octokit/plugin-paginate-rest": "^14.0.0",
|
||||
"@octokit/plugin-rest-endpoint-methods": "^17.0.0",
|
||||
"@octokit/plugin-retry": "^8.1.0",
|
||||
"archiver": "^8.0.0",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"follow-redirects": "^1.16.0",
|
||||
"get-folder-size": "^5.0.0",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"js-yaml": "^5.4.2",
|
||||
"js-yaml": "^5.2.1",
|
||||
"jsonschema": "1.5.0",
|
||||
"long": "^5.3.2",
|
||||
"node-forge": "^1.4.0",
|
||||
"semver": "^7.8.5",
|
||||
"undici": "^6.28.0",
|
||||
"uuid": "^14.0.2"
|
||||
"uuid": "^14.0.1",
|
||||
"undici": "^6.24.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ava/typescript": "6.0.0",
|
||||
"@eslint/compat": "^2.1.1",
|
||||
"@eslint/compat": "^2.1.0",
|
||||
"@microsoft/eslint-formatter-sarif": "^3.1.0",
|
||||
"@octokit/types": "^18.0.0",
|
||||
"@octokit/types": "^16.0.0",
|
||||
"@types/archiver": "^8.0.0",
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/sarif": "^2.1.7",
|
||||
"@types/semver": "^7.8.0",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@types/sinon": "^22.0.0",
|
||||
"ava": "^6.4.1",
|
||||
"esbuild": "^0.28.2",
|
||||
"esbuild": "^0.28.1",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-import-resolver-typescript": "^4.4.5",
|
||||
"eslint-plugin-github": "^6.1.2",
|
||||
"eslint-plugin-github": "^6.1.1",
|
||||
"eslint-plugin-import-x": "^4.17.1",
|
||||
"eslint-plugin-jsdoc": "^64.5.4",
|
||||
"eslint-plugin-jsdoc": "^62.9.0",
|
||||
"eslint-plugin-no-async-foreach": "^0.1.1",
|
||||
"glob": "^13.0.6",
|
||||
"globals": "^17.12.0",
|
||||
"nock": "^14.0.17",
|
||||
"globals": "^17.7.0",
|
||||
"nock": "^14.0.16",
|
||||
"sinon": "^22.1.0",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.70.1"
|
||||
"typescript-eslint": "^8.65.0"
|
||||
},
|
||||
"overrides": {
|
||||
"@actions/tool-cache": {
|
||||
@@ -95,6 +95,6 @@
|
||||
"semver": ">=6.3.1"
|
||||
},
|
||||
"glob": "^13.0.6",
|
||||
"undici": "^6.28.0"
|
||||
"undici": "^6.24.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
24
|
||||
@@ -1,7 +1,10 @@
|
||||
import * as githubUtils from "@actions/github/lib/utils";
|
||||
import { type Octokit } from "@octokit/core";
|
||||
import { type PaginateInterface } from "@octokit/plugin-paginate-rest";
|
||||
import { type Api } from "@octokit/plugin-rest-endpoint-methods";
|
||||
|
||||
/** The type of the Octokit client. */
|
||||
export type ApiClient = InstanceType<typeof githubUtils.GitHub>;
|
||||
export type ApiClient = Octokit & Api & { paginate: PaginateInterface };
|
||||
|
||||
/** Constructs an `ApiClient` using `token` for authentication. */
|
||||
export function getApiClient(token: string): ApiClient {
|
||||
|
||||
@@ -112,7 +112,7 @@ ${NO_CHANGES_STR}`;
|
||||
describe("updateChangelog", async () => {
|
||||
await it("removes `NO_CHANGES_STR` if present in [UNRELEASED] section", async () => {
|
||||
const result = updateChangelog(EMPTY_CHANGELOG, "");
|
||||
assert.ok(!result.includes(NO_CHANGES_STR));
|
||||
assert.ok(!result.includes(NO_CHANGES_STR.trim()));
|
||||
});
|
||||
|
||||
await it("doesn't remove `NO_CHANGES_STR` if present in versioned section", async () => {
|
||||
@@ -120,7 +120,7 @@ describe("updateChangelog", async () => {
|
||||
EMPTY_CHANGELOG.replace(UNRELEASED_PLACEHOLDER, "1.2.3"),
|
||||
"",
|
||||
);
|
||||
assert.ok(result.includes(NO_CHANGES_STR));
|
||||
assert.ok(result.includes(NO_CHANGES_STR.trim()));
|
||||
});
|
||||
|
||||
await it("throws if there are no sections", async () => {
|
||||
|
||||
@@ -122,6 +122,6 @@ function main() {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
process.exit(main());
|
||||
}
|
||||
|
||||
@@ -43,6 +43,6 @@ async function main() {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
void main();
|
||||
}
|
||||
|
||||
@@ -9,46 +9,17 @@ import * as fs from "node:fs";
|
||||
import { describe, it } from "node:test";
|
||||
|
||||
import {
|
||||
addBodyLinesToUnreleasedSection,
|
||||
ChangelogSection,
|
||||
EMPTY_CHANGELOG,
|
||||
getHeader,
|
||||
getReleaseDateString,
|
||||
NO_CHANGES_STR,
|
||||
parseChangelog,
|
||||
processChangelogForBackports,
|
||||
renderChangelog,
|
||||
setVersionAndDate,
|
||||
UNRELEASED_PLACEHOLDER,
|
||||
} from "./changelog";
|
||||
import { CHANGELOG_FILE } from "./config";
|
||||
|
||||
const testDate = new Date(2026, 7, 14);
|
||||
|
||||
describe("getHeader", async () => {
|
||||
function Section(headerLine: string): ChangelogSection {
|
||||
return {
|
||||
headerLine,
|
||||
bodyLines: [],
|
||||
};
|
||||
}
|
||||
await it("returns non-headers unchanged", () => {
|
||||
assert.equal("foo", getHeader(Section("foo")));
|
||||
assert.equal("- bar", getHeader(Section("- bar")));
|
||||
});
|
||||
await it("strips octothorpes", async () => {
|
||||
assert.equal("foo", getHeader(Section("# foo")));
|
||||
assert.equal("foo", getHeader(Section("## foo")));
|
||||
assert.equal("foo", getHeader(Section("### foo")));
|
||||
assert.equal("foo", getHeader(Section("#### foo")));
|
||||
assert.equal("foo", getHeader(Section("##### foo")));
|
||||
assert.equal("foo", getHeader(Section("###### foo")));
|
||||
});
|
||||
await it("strips whitespace", async () => {
|
||||
assert.equal("foo", getHeader(Section("# foo ")));
|
||||
});
|
||||
});
|
||||
|
||||
describe("getReleaseDateString", async () => {
|
||||
await it("formats dates as expected", async () => {
|
||||
assert.equal(getReleaseDateString(testDate), "14 Aug 2026");
|
||||
@@ -99,73 +70,3 @@ describe("processChangelogForBackports", async () => {
|
||||
assert.deepEqual(result.split("\n"), testChangelogResult.split("\n"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("addBodyLinesToUnreleasedSection", async () => {
|
||||
function newChangelogWithSections(sections: ChangelogSection[]) {
|
||||
return {
|
||||
preamble: [],
|
||||
sections,
|
||||
};
|
||||
}
|
||||
|
||||
await it("throws error if '[UNRELEASED]' section is not first", async () => {
|
||||
const invalidChangelog = newChangelogWithSections([
|
||||
{
|
||||
headerLine: "## Release 1.0.0",
|
||||
bodyLines: [],
|
||||
},
|
||||
{
|
||||
headerLine: `## ${UNRELEASED_PLACEHOLDER}`,
|
||||
bodyLines: [],
|
||||
},
|
||||
]);
|
||||
assert.throws(() =>
|
||||
addBodyLinesToUnreleasedSection(invalidChangelog, ["foo"]),
|
||||
);
|
||||
});
|
||||
|
||||
await it("overwrites 'No user facing changes.'", async () => {
|
||||
const changelog = newChangelogWithSections([
|
||||
{
|
||||
headerLine: `## ${UNRELEASED_PLACEHOLDER}`,
|
||||
bodyLines: ["", NO_CHANGES_STR, ""],
|
||||
},
|
||||
]);
|
||||
|
||||
addBodyLinesToUnreleasedSection(changelog, ["- foo"]);
|
||||
|
||||
assert.equal(changelog.sections[0].bodyLines.length, 3);
|
||||
assert.deepEqual(changelog.sections[0].bodyLines, ["", "- foo", ""]);
|
||||
});
|
||||
|
||||
await it("does nothing if lines is empty", async () => {
|
||||
const changelog = newChangelogWithSections([
|
||||
{
|
||||
headerLine: `## ${UNRELEASED_PLACEHOLDER}`,
|
||||
bodyLines: ["", NO_CHANGES_STR, ""],
|
||||
},
|
||||
]);
|
||||
const changelogClone = structuredClone(changelog);
|
||||
|
||||
addBodyLinesToUnreleasedSection(changelog, []);
|
||||
|
||||
assert.deepEqual(changelog, changelogClone);
|
||||
});
|
||||
|
||||
await it("inserts a line", async () => {
|
||||
const changelog = newChangelogWithSections([
|
||||
{
|
||||
headerLine: `## ${UNRELEASED_PLACEHOLDER}`,
|
||||
bodyLines: ["", "- Added a new dependency.", ""],
|
||||
},
|
||||
]);
|
||||
const lineToInsert = "- foo";
|
||||
|
||||
addBodyLinesToUnreleasedSection(changelog, [lineToInsert]);
|
||||
|
||||
assert.equal(changelog.sections[0].bodyLines.length, 4);
|
||||
assert.ok(
|
||||
changelog.sections[0].bodyLines.some((line) => line === lineToInsert),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+3
-48
@@ -6,16 +6,14 @@ import { CHANGELOG_FILE, DryRunOption } from "./config";
|
||||
export const UNRELEASED_PLACEHOLDER = "[UNRELEASED]";
|
||||
|
||||
/** The default contents for a section in the changelog. */
|
||||
export const NO_CHANGES_STR = "No user facing changes.";
|
||||
export const NO_CHANGES_STR = "No user facing changes.\n\n";
|
||||
|
||||
/** Placeholder changelog content for a new release. */
|
||||
export const EMPTY_CHANGELOG = `# CodeQL Action Changelog
|
||||
|
||||
## ${UNRELEASED_PLACEHOLDER}
|
||||
|
||||
${NO_CHANGES_STR}
|
||||
|
||||
`;
|
||||
${NO_CHANGES_STR}`;
|
||||
|
||||
/**
|
||||
* Represents sections in a changelog.
|
||||
@@ -33,13 +31,6 @@ export interface Changelog {
|
||||
sections: ChangelogSection[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the text of the header (without the '## ' prefix) of the given section.
|
||||
* */
|
||||
export function getHeader(section: ChangelogSection): string {
|
||||
return section.headerLine.replace(/^#+\s+/, "").trimEnd();
|
||||
}
|
||||
|
||||
/** Returns `date` formatted as `DD Mon YYYY`. */
|
||||
export function getReleaseDateString(today: Date = new Date()): string {
|
||||
return today.toLocaleDateString("en-GB", {
|
||||
@@ -134,42 +125,6 @@ export function parseChangelog(content: string): Changelog {
|
||||
return { preamble, sections };
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the changenotes `lines` in the `[UNRELEASED]` section of `changelog`.
|
||||
* If the section contains the stock message {@link NO_CHANGES_STR}, then
|
||||
* `lines` will be inserted in place and the stock message will be deleted.
|
||||
*
|
||||
* @throws Error -- if the [UNRELEASED] section does not exist.
|
||||
*
|
||||
* @param changelog The CHANGELOG object to modify.
|
||||
* @param lines The changenotes to insert.
|
||||
*/
|
||||
export function addBodyLinesToUnreleasedSection(
|
||||
changelog: Changelog,
|
||||
lines: string[],
|
||||
) {
|
||||
// Do nothing if there is nothing to insert.
|
||||
if (lines.length === 0) return;
|
||||
|
||||
const unreleasedSection = changelog.sections[0];
|
||||
if (getHeader(unreleasedSection) !== UNRELEASED_PLACEHOLDER) {
|
||||
throw Error(
|
||||
`'${UNRELEASED_PLACEHOLDER}' is not the first section of 'CHANGELOG.md'`,
|
||||
);
|
||||
}
|
||||
|
||||
if (unreleasedSection.bodyLines.includes(NO_CHANGES_STR)) {
|
||||
unreleasedSection.bodyLines = ["", ...lines, ""];
|
||||
return;
|
||||
}
|
||||
|
||||
// The last body line should be a blank line (for spacing).
|
||||
// Remove it so that we can add `lines` and then add the blank line back.
|
||||
unreleasedSection.bodyLines.pop();
|
||||
unreleasedSection.bodyLines.push(...lines);
|
||||
unreleasedSection.bodyLines.push("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Combines an array of lines into a single string by adding line breaks.
|
||||
*/
|
||||
@@ -249,7 +204,7 @@ export function processChangelogForBackports(
|
||||
|
||||
// Add an entry if we didn't keep any.
|
||||
if (!foundContent) {
|
||||
section.bodyLines.push(NO_CHANGES_STR);
|
||||
section.bodyLines.push(NO_CHANGES_STR.trim());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
|
||||
import { withTmpFile } from "../../src/util";
|
||||
|
||||
import {
|
||||
hasValidChangenoteCategory,
|
||||
isValidChangenoteContent,
|
||||
isValidChangenoteFile,
|
||||
isValidChangenoteFilename,
|
||||
VALID_CHANGE_NOTE_CATEGORIES,
|
||||
} from "./validate";
|
||||
|
||||
await describe("isValidChangenoteContent", async () => {
|
||||
await it("recognizes an unordered Markdown list", () => {
|
||||
const inputs = [
|
||||
"- One changenote entry",
|
||||
"- First item\n- Second item",
|
||||
"\n\n\n\n- Fixed a bug\n- Added a feature",
|
||||
];
|
||||
|
||||
for (const input of inputs) {
|
||||
assert.equal(isValidChangenoteContent(input), true);
|
||||
}
|
||||
});
|
||||
|
||||
await it("does not recognize non-Markdown text", () => {
|
||||
const inputs = [
|
||||
"This is not a list.",
|
||||
'["this", "is", "JSON"]',
|
||||
"---",
|
||||
"***",
|
||||
"___",
|
||||
"paragraph",
|
||||
];
|
||||
|
||||
for (const input of inputs) {
|
||||
assert.equal(isValidChangenoteContent(input), false);
|
||||
}
|
||||
});
|
||||
|
||||
await it("does not recognize ordered Markdown lists", () => {
|
||||
const inputs = [
|
||||
"1. First item\n2. Second item",
|
||||
"\n\n\n1. First item\n1. Second item",
|
||||
];
|
||||
|
||||
for (const input of inputs) {
|
||||
assert.equal(isValidChangenoteContent(input), false);
|
||||
}
|
||||
});
|
||||
|
||||
await it("requires all list items to use a hyphen bullet", () => {
|
||||
const inputs = [
|
||||
"* Fixed a bug\n* Added feature",
|
||||
"+ Fixed a bug\n+ Added feature",
|
||||
"- Fixed a bug\n* Added feature",
|
||||
"- Fixed a bug\n+ Added feature",
|
||||
"- Fixed a bug\n * Added feature\n + Updated docs",
|
||||
"\n\n\n* Fixed a bug",
|
||||
"\n\n\n+ Fixed a bug",
|
||||
"---\n* Fixed a bug\n* Added feature",
|
||||
] as const;
|
||||
|
||||
for (const input of inputs) {
|
||||
assert.equal(isValidChangenoteContent(input), false);
|
||||
}
|
||||
});
|
||||
|
||||
await it("does not contain other Markdown elements", () => {
|
||||
const inputs = [
|
||||
"- Fixed a bug\n\nParagraph of text",
|
||||
"- Fixed a bug\n\n* Added a feature",
|
||||
"# Header\n- Fixed a bug",
|
||||
"- Fixed a bug\n## Subheader",
|
||||
];
|
||||
|
||||
for (const input of inputs) {
|
||||
assert.equal(isValidChangenoteContent(input), false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await describe("isValidChangenoteFilename", async () => {
|
||||
await it("accepts valid filenames", () => {
|
||||
const inputs = [
|
||||
"2023-01-01-fix-bug.md",
|
||||
"2023-12-31-add-feature.md",
|
||||
"2023-06-15-update-docs.md",
|
||||
];
|
||||
|
||||
for (const input of inputs) {
|
||||
assert.equal(isValidChangenoteFilename(input), true);
|
||||
}
|
||||
});
|
||||
|
||||
await it("rejects invalid filenames", () => {
|
||||
const inputs = [
|
||||
"missing-date-from-filename.md",
|
||||
"2021-01-01.md",
|
||||
"2026-12-19-wrong-file-name-extension.txt",
|
||||
];
|
||||
|
||||
for (const input of inputs) {
|
||||
assert.equal(isValidChangenoteFilename(input), false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await describe("hasValidChangenoteCategory", async () => {
|
||||
await it("accepts valid categories", () => {
|
||||
for (const category of Object.keys(VALID_CHANGE_NOTE_CATEGORIES)) {
|
||||
const frontmatter = { category };
|
||||
assert.equal(hasValidChangenoteCategory(frontmatter), true);
|
||||
}
|
||||
});
|
||||
|
||||
await it("rejects invalid categories", () => {
|
||||
const inputs = [
|
||||
"",
|
||||
"invalid-category",
|
||||
"bug-fix",
|
||||
"new-feature",
|
||||
"security-patch",
|
||||
"miscellaneous",
|
||||
"documentation",
|
||||
];
|
||||
|
||||
for (const category of inputs) {
|
||||
const frontmatter = { category };
|
||||
assert.equal(hasValidChangenoteCategory(frontmatter), false);
|
||||
}
|
||||
});
|
||||
|
||||
await it("reject missing category", () => {
|
||||
assert.equal(hasValidChangenoteCategory({}), false);
|
||||
assert.equal(hasValidChangenoteCategory({ category: null }), false);
|
||||
assert.equal(hasValidChangenoteCategory({ category: undefined }), false);
|
||||
});
|
||||
});
|
||||
|
||||
await describe("isValidChangenoteFile", async () => {
|
||||
await it("accepts a valid change-note file", async () => {
|
||||
await withTmpFile(
|
||||
"2026-01-01-fix-bug.md",
|
||||
"---\ncategory: fix\n---\n- Fixed a bug\n",
|
||||
(filePath) => {
|
||||
assert.equal(isValidChangenoteFile(filePath), true);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
await it("rejects a non-existent path", async () => {
|
||||
assert.equal(isValidChangenoteFile("non-existent-file.md"), false);
|
||||
});
|
||||
|
||||
await it("rejects invalid filename", async () => {
|
||||
await withTmpFile(
|
||||
"fix-bug.md",
|
||||
"---\ncategory: fix\n---\n- Fixed a bug\n",
|
||||
(filePath) => {
|
||||
assert.equal(isValidChangenoteFile(filePath), false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
await it("rejects missing frontmatter", async () => {
|
||||
await withTmpFile(
|
||||
"2026-01-01-fix-bug.md",
|
||||
"- Fixed a bug\n",
|
||||
(filePath) => {
|
||||
assert.equal(isValidChangenoteFile(filePath), false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
await it("rejects invalid Markdown", async () => {
|
||||
await withTmpFile(
|
||||
"2026-01-01-fix-bug.md",
|
||||
"---\ncategory: fix\n---\n* Fixed a bug\n",
|
||||
(filePath) => {
|
||||
assert.equal(isValidChangenoteFile(filePath), false);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
import { matter } from "lite-matter";
|
||||
import type { List, ListItem } from "mdast";
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
|
||||
// Regex for filename: YYYY-MM-DD-id.md
|
||||
const VALID_CHANGE_NOTE_FILENAME_PATTERN =
|
||||
/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])-([a-z0-9]+(?:-[a-z0-9]+)*)\.md$/;
|
||||
|
||||
export const VALID_CHANGE_NOTE_CATEGORIES = {
|
||||
breaking: "Breaking Changes",
|
||||
feature: "New Features",
|
||||
improvement: "Improvements",
|
||||
securityFix: "Security Fixes",
|
||||
fix: "Bug Fixes",
|
||||
unship: "Removed Features",
|
||||
deprecation: "Deprecations",
|
||||
knownIssue: "Known Issues",
|
||||
misc: "Miscellaneous",
|
||||
};
|
||||
|
||||
/**
|
||||
* Validates that the given Markdown string meets the criteria for a change-note, which is:
|
||||
* - A single unordered list
|
||||
* - Each list item must start with a hyphen (-)
|
||||
* - No other Markdown elements are allowed
|
||||
* @param content The Markdown string to validate
|
||||
* @returns True if the string is a valid change-note, false otherwise
|
||||
*/
|
||||
export function isValidChangenoteContent(content: string): boolean {
|
||||
const ast = fromMarkdown(content);
|
||||
const lines = content.split("\n");
|
||||
|
||||
function listHasHyphenBullets(node: List | ListItem): boolean {
|
||||
if (node.type === "list") {
|
||||
return node.children.every(listHasHyphenBullets);
|
||||
}
|
||||
|
||||
const line = lines[node.position!.start.line - 1].trim();
|
||||
return (
|
||||
line.startsWith("-") &&
|
||||
node.children.every(
|
||||
(child) => child.type !== "list" || listHasHyphenBullets(child),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
ast.children.length === 1 &&
|
||||
ast.children[0].type === "list" &&
|
||||
ast.children[0].ordered === false &&
|
||||
listHasHyphenBullets(ast.children[0])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the given filename meets the criteria for a change-note filename.
|
||||
* @param filename The name of the change-note file to validate.
|
||||
* @returns True if the filename is valid, false otherwise.
|
||||
*/
|
||||
export function isValidChangenoteFilename(filename: string): boolean {
|
||||
return filename.match(VALID_CHANGE_NOTE_FILENAME_PATTERN) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the given frontmatter has a valid change-note category.
|
||||
* @param frontmatter The frontmatter object to validate.
|
||||
* @returns True if the frontmatter has a valid category, false otherwise.
|
||||
*/
|
||||
export function hasValidChangenoteCategory(
|
||||
frontmatter: Record<string, unknown>,
|
||||
): boolean {
|
||||
const category = frontmatter["category"];
|
||||
return (
|
||||
typeof category === "string" &&
|
||||
Object.hasOwn(VALID_CHANGE_NOTE_CATEGORIES, category)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the given change-note file meets all of the criteria for a change-note.
|
||||
* @param filename The name of the change-note file to validate.
|
||||
* @returns True if the file is a valid change-note, false otherwise.
|
||||
*/
|
||||
export function isValidChangenoteFile(filename: string): boolean {
|
||||
let isValid: boolean = true;
|
||||
|
||||
let fileData: string | undefined;
|
||||
try {
|
||||
fileData = fs.readFileSync(filename, "utf8");
|
||||
} catch (error) {
|
||||
console.error(`${filename}: failed to read file`, error);
|
||||
return false;
|
||||
}
|
||||
|
||||
const { data: frontmatter, content } = matter(fileData);
|
||||
|
||||
if (!isValidChangenoteFilename(path.basename(filename))) {
|
||||
isValid = false;
|
||||
console.error(
|
||||
`${filename}: invalid filename; must match pattern YYYY-MM-DD-id.md`,
|
||||
);
|
||||
}
|
||||
if (!hasValidChangenoteCategory(frontmatter)) {
|
||||
isValid = false;
|
||||
const categories = Object.keys(VALID_CHANGE_NOTE_CATEGORIES).join(", ");
|
||||
console.error(
|
||||
`${filename}: invalid category; must be one of: ${categories}`,
|
||||
);
|
||||
}
|
||||
if (!isValidChangenoteContent(content)) {
|
||||
isValid = false;
|
||||
console.error(
|
||||
`${filename}: invalid Markdown; content must be a single unordered list with hyphen bullets and no other Markdown elements`,
|
||||
);
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
#!/usr/bin/env npx tsx
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { parseArgs } from "node:util";
|
||||
import path from "path";
|
||||
|
||||
import { ExitCode } from "@actions/core";
|
||||
import { matter } from "lite-matter";
|
||||
|
||||
import {
|
||||
addBodyLinesToUnreleasedSection,
|
||||
parseChangelog,
|
||||
renderChangelog,
|
||||
withChangelog,
|
||||
} from "./changelog";
|
||||
import { isValidChangenoteFile } from "./changelog/validate";
|
||||
import { CHANGENOTES_DIR } from "./config";
|
||||
|
||||
/**
|
||||
* Describes a changenote file, including its file path, frontmatter, and content.
|
||||
*/
|
||||
interface ChangenoteFile {
|
||||
absolutePath: string;
|
||||
data: Record<string, any>;
|
||||
content: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute file paths of all files in
|
||||
* {@link CHANGENOTES_DIR} (except ".gitkeep").
|
||||
* */
|
||||
function listUnreleasedChangenoteDir(): string[] {
|
||||
return fs
|
||||
.readdirSync(CHANGENOTES_DIR)
|
||||
.filter((name) => name !== ".gitkeep")
|
||||
.map((name) => path.join(CHANGENOTES_DIR, name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans the {@link CHANGENOTES_DIR} directory for changenote files
|
||||
* and returns a parsed listing of those changenote files.
|
||||
*/
|
||||
function getChangenotes(): ChangenoteFile[] {
|
||||
return listUnreleasedChangenoteDir().map((absolutePath) => {
|
||||
return {
|
||||
absolutePath,
|
||||
...matter(fs.readFileSync(absolutePath, "utf-8")),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const entryPoint = process.argv[1];
|
||||
if (entryPoint && import.meta.url === pathToFileURL(entryPoint).href) {
|
||||
try {
|
||||
process.exit(main());
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
process.exit(ExitCode.Failure);
|
||||
}
|
||||
}
|
||||
|
||||
function main(): ExitCode {
|
||||
const { positionals } = parseArgs({
|
||||
allowPositionals: true,
|
||||
strict: true,
|
||||
});
|
||||
const [command] = positionals;
|
||||
switch (command) {
|
||||
case undefined:
|
||||
case "help":
|
||||
return usage();
|
||||
case "assemble":
|
||||
return assemble();
|
||||
case "validate":
|
||||
return validate();
|
||||
default:
|
||||
console.error(`Unknown command: ${command}`);
|
||||
return ExitCode.Failure;
|
||||
}
|
||||
}
|
||||
|
||||
function usage(): ExitCode {
|
||||
const message =
|
||||
"Usage: changenotes.ts assemble\n" +
|
||||
" changenotes.ts validate\n" +
|
||||
" changenotes.ts help";
|
||||
console.log(message);
|
||||
return ExitCode.Success;
|
||||
}
|
||||
|
||||
function assemble(): ExitCode {
|
||||
try {
|
||||
const changenotes = getChangenotes();
|
||||
const changenoteBodies = changenotes.map((c) => c.content);
|
||||
const changenotePaths = changenotes.map((c) => c.absolutePath);
|
||||
|
||||
withChangelog((contents) => {
|
||||
const changelog = parseChangelog(contents);
|
||||
addBodyLinesToUnreleasedSection(changelog, changenoteBodies);
|
||||
return renderChangelog(changelog);
|
||||
}, {});
|
||||
|
||||
// Delete changenotes only after successful processing.
|
||||
for (const p of changenotePaths) {
|
||||
fs.unlinkSync(p);
|
||||
}
|
||||
|
||||
return ExitCode.Success;
|
||||
} catch (e) {
|
||||
console.error("Failed to assemble changenotes to 'CHANGELOG.md'", e);
|
||||
}
|
||||
|
||||
return ExitCode.Failure;
|
||||
}
|
||||
|
||||
function validate(): ExitCode {
|
||||
try {
|
||||
const allChangenotesValid = getChangenotes().reduce(
|
||||
(r, changenote) => r && isValidChangenoteFile(changenote.absolutePath),
|
||||
true,
|
||||
);
|
||||
if (allChangenotesValid) {
|
||||
console.log(`All changenotes in '${CHANGENOTES_DIR}' are valid.`);
|
||||
return ExitCode.Success;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Failed to read changenotes directory '${CHANGENOTES_DIR}'`,
|
||||
error,
|
||||
);
|
||||
}
|
||||
return ExitCode.Failure;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Tests for `check-cs-config.ts`.
|
||||
*/
|
||||
|
||||
import * as assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
|
||||
import type { UserConfig } from "../src/config/db-config";
|
||||
|
||||
import { checkConfiguration } from "./check-cs-config";
|
||||
|
||||
describe("checkConfiguration", async () => {
|
||||
await it("passes when actual and expected configs match", () => {
|
||||
const actual: UserConfig = { name: "test-config", paths: ["src"] };
|
||||
const expected = JSON.stringify(actual);
|
||||
assert.doesNotThrow(() => checkConfiguration(actual, expected));
|
||||
});
|
||||
|
||||
await it("passes when queries arrays match after sorting", () => {
|
||||
const actual: UserConfig = { paths: ["b", "a", "c"] };
|
||||
const expected = JSON.stringify(actual);
|
||||
assert.doesNotThrow(() => checkConfiguration(actual, expected));
|
||||
});
|
||||
|
||||
await it("throws when actual config does not match expected", () => {
|
||||
const actual: UserConfig = { name: "actual-name" };
|
||||
const expected = JSON.stringify({
|
||||
name: "expected-name",
|
||||
} satisfies UserConfig);
|
||||
assert.throws(() => checkConfiguration(actual, expected), {
|
||||
message: /Expected configuration does not match actual configuration/,
|
||||
});
|
||||
});
|
||||
|
||||
await it("throws when expected contents are empty", () => {
|
||||
assert.throws(() => checkConfiguration({}, ""), {
|
||||
message: /No expected configuration provided/,
|
||||
});
|
||||
});
|
||||
|
||||
await it("throws when expected contents are only whitespace", () => {
|
||||
assert.throws(() => checkConfiguration({}, " "), {
|
||||
message: /No expected configuration provided/,
|
||||
});
|
||||
});
|
||||
|
||||
await it("passes with complex config", () => {
|
||||
const actual: UserConfig = {
|
||||
name: "complex",
|
||||
"disable-default-queries": true,
|
||||
paths: ["src", "lib"],
|
||||
"paths-ignore": ["test"],
|
||||
"threat-models": ["remote"],
|
||||
};
|
||||
const expected = JSON.stringify(actual);
|
||||
assert.doesNotThrow(() => checkConfiguration(actual, expected));
|
||||
});
|
||||
|
||||
await it("trims whitespace from expected contents before parsing", () => {
|
||||
const actual: UserConfig = { name: "trimmed" };
|
||||
const expected = ` ${JSON.stringify(actual)} `;
|
||||
assert.doesNotThrow(() => checkConfiguration(actual, expected));
|
||||
});
|
||||
|
||||
await it("passes when both configs are empty objects", () => {
|
||||
assert.doesNotThrow(() => checkConfiguration({}, "{}"));
|
||||
});
|
||||
});
|
||||
Executable
+100
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env npx tsx
|
||||
|
||||
/**
|
||||
* Checks the code scanning configuration file generated by the
|
||||
* action to ensure it contains the expected contents
|
||||
*/
|
||||
|
||||
import * as assert from "node:assert";
|
||||
import * as fs from "node:fs";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
import * as core from "@actions/core";
|
||||
import * as yaml from "yaml";
|
||||
|
||||
import type { UserConfig } from "../src/config/db-config";
|
||||
|
||||
import { getErrorMessage } from "./util";
|
||||
|
||||
function sortConfigArrays(config: UserConfig) {
|
||||
for (const key of Object.keys(config)) {
|
||||
const value = config[key];
|
||||
if (key === "queries" && Array.isArray(value)) {
|
||||
config[key] = value.sort();
|
||||
}
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function loadActualConfig(configPath: string) {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
throw new Error("No configuration file found");
|
||||
} else {
|
||||
const rawActualConfig = fs.readFileSync(configPath, "utf8");
|
||||
core.startGroup("Actual generated user config");
|
||||
core.info(rawActualConfig);
|
||||
core.endGroup();
|
||||
|
||||
return yaml.parse(rawActualConfig) as UserConfig;
|
||||
}
|
||||
}
|
||||
|
||||
export function checkConfiguration(
|
||||
actualConfig: UserConfig,
|
||||
expectedContents: string,
|
||||
) {
|
||||
const rawExpectedConfig = expectedContents.trim();
|
||||
if (!rawExpectedConfig) {
|
||||
throw new Error("No expected configuration provided");
|
||||
}
|
||||
|
||||
const expectedConfig = JSON.parse(rawExpectedConfig) as UserConfig;
|
||||
|
||||
core.startGroup("Expected generated user config");
|
||||
core.info(yaml.stringify(expectedConfig));
|
||||
core.endGroup();
|
||||
|
||||
assert.deepStrictEqual(
|
||||
sortConfigArrays(actualConfig),
|
||||
sortConfigArrays(expectedConfig),
|
||||
"Expected configuration does not match actual configuration",
|
||||
);
|
||||
}
|
||||
|
||||
function main() {
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
// The path of the configuration file to check.
|
||||
file: {
|
||||
type: "string",
|
||||
},
|
||||
// The expected contents of the file.
|
||||
"expected-contents": {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
strict: true,
|
||||
});
|
||||
|
||||
if (values.file === undefined) {
|
||||
throw new Error("The '--file' input is required.");
|
||||
}
|
||||
if (values["expected-contents"] === undefined) {
|
||||
throw new Error("The '--expected-contents' input is required.");
|
||||
}
|
||||
|
||||
const actualConfig = loadActualConfig(values.file);
|
||||
|
||||
try {
|
||||
checkConfiguration(actualConfig, values["expected-contents"]);
|
||||
} catch (err) {
|
||||
core.error(getErrorMessage(err));
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
process.exit(main());
|
||||
}
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env npx tsx
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
import * as core from "@actions/core";
|
||||
|
||||
import { runCommand, runGit } from "./command";
|
||||
import { LIB_ROOT, PR_CHECKS_DIR, REPO_ROOT } from "./config";
|
||||
import { getErrorMessage } from "./util";
|
||||
|
||||
function main() {
|
||||
// Sanity check that repo is clean to start with
|
||||
try {
|
||||
runGit(["diff", "--exit-code"], { allowNonZeroExitCode: false });
|
||||
console.info("Repository is clean.");
|
||||
} catch (err) {
|
||||
// If we get a fail here then this workflow needs attention...
|
||||
console.error(getErrorMessage(err));
|
||||
console.error("Failed: Repo should be clean before testing!");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Wipe the lib directory in case there are extra unnecessary files in there
|
||||
console.info(`Removing ${LIB_ROOT}...`);
|
||||
fs.rmSync(LIB_ROOT, { recursive: true, force: true });
|
||||
|
||||
// Generate the JavaScript files
|
||||
runCommand("npm", ["run", "build"], { execOptions: { shell: true } });
|
||||
|
||||
// Check that repo is still clean
|
||||
try {
|
||||
runGit(["diff", "--exit-code"], { allowNonZeroExitCode: false });
|
||||
console.info("Repository is clean.");
|
||||
} catch (err) {
|
||||
// If we get a fail here then the PR needs attention
|
||||
console.error(getErrorMessage(err));
|
||||
console.error("Failed: JavaScript files are not up to date.");
|
||||
console.error("Run 'rm -rf lib && npm run build' to update.");
|
||||
|
||||
const diffFile = path.join(
|
||||
process.env["RUNNER_TEMP"] ?? PR_CHECKS_DIR,
|
||||
"js.diff",
|
||||
);
|
||||
runCommand("git", ["status"]);
|
||||
runCommand("git", ["diff", `--output=${diffFile}`], {
|
||||
execOptions: { cwd: REPO_ROOT },
|
||||
});
|
||||
|
||||
core.summary.addHeading("Transpiled JS diff", 3);
|
||||
core.summary.addCodeBlock(fs.readFileSync(diffFile, "utf-8"), "diff");
|
||||
|
||||
fs.rmSync(diffFile);
|
||||
|
||||
// Reset bundled files to allow other checks to test for changes
|
||||
runCommand("git", ["checkout", "lib"]);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
console.info("Success: JavaScript files are up to date");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
process.exit(main());
|
||||
}
|
||||
@@ -218,6 +218,6 @@ async function run(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
void run();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Tests for `check-sarif.ts`.
|
||||
*/
|
||||
|
||||
import * as assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
|
||||
import type { Log } from "sarif";
|
||||
|
||||
import { checkSarif } from "./check-sarif";
|
||||
|
||||
/** Builds a minimal SARIF Log with the given rule IDs spread across extensions. */
|
||||
function buildSarifLog(ruleIds: string[]): Log {
|
||||
return {
|
||||
version: "2.1.0",
|
||||
$schema:
|
||||
"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",
|
||||
runs: [
|
||||
{
|
||||
tool: {
|
||||
driver: { name: "CodeQL" },
|
||||
extensions: [
|
||||
{
|
||||
name: "test-pack",
|
||||
rules: ruleIds.map((id) => ({ id })),
|
||||
},
|
||||
],
|
||||
},
|
||||
results: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("checkSarif", async () => {
|
||||
await it("returns 0 when all expected queries ran and no unexpected queries ran", () => {
|
||||
const sarif = buildSarifLog(["js/sql-injection", "js/xss"]);
|
||||
const exitCode = checkSarif(sarif, {
|
||||
sarifFile: "test.sarif",
|
||||
queriesRun: "js/sql-injection, js/xss",
|
||||
queriesNotRun: "js/hardcoded-credentials",
|
||||
});
|
||||
assert.equal(exitCode, 0);
|
||||
});
|
||||
|
||||
await it("returns -2 when an expected query did not run", () => {
|
||||
const sarif = buildSarifLog(["js/sql-injection"]);
|
||||
const exitCode = checkSarif(sarif, {
|
||||
sarifFile: "test.sarif",
|
||||
queriesRun: "js/sql-injection, js/xss",
|
||||
queriesNotRun: "",
|
||||
});
|
||||
assert.equal(exitCode, -2);
|
||||
});
|
||||
|
||||
await it("returns -2 when an unexpected query ran", () => {
|
||||
const sarif = buildSarifLog(["js/sql-injection", "js/xss"]);
|
||||
const exitCode = checkSarif(sarif, {
|
||||
sarifFile: "test.sarif",
|
||||
queriesRun: "js/sql-injection",
|
||||
queriesNotRun: "js/xss",
|
||||
});
|
||||
assert.equal(exitCode, -2);
|
||||
});
|
||||
|
||||
await it("handles empty queries-run and queries-not-run inputs", () => {
|
||||
const sarif = buildSarifLog(["js/sql-injection"]);
|
||||
const exitCode = checkSarif(sarif, {
|
||||
sarifFile: "test.sarif",
|
||||
queriesRun: "",
|
||||
queriesNotRun: "",
|
||||
});
|
||||
assert.equal(exitCode, 0);
|
||||
});
|
||||
|
||||
await it("handles multiple extensions with rules", () => {
|
||||
const sarif: Log = {
|
||||
version: "2.1.0",
|
||||
$schema:
|
||||
"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",
|
||||
runs: [
|
||||
{
|
||||
tool: {
|
||||
driver: { name: "CodeQL" },
|
||||
extensions: [
|
||||
{
|
||||
name: "pack-a",
|
||||
rules: [{ id: "js/sql-injection" }],
|
||||
},
|
||||
{
|
||||
name: "pack-b",
|
||||
rules: [{ id: "js/xss" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
results: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
const exitCode = checkSarif(sarif, {
|
||||
sarifFile: "test.sarif",
|
||||
queriesRun: "js/sql-injection, js/xss",
|
||||
queriesNotRun: "",
|
||||
});
|
||||
assert.equal(exitCode, 0);
|
||||
});
|
||||
|
||||
await it("handles extensions with no rules", () => {
|
||||
const sarif: Log = {
|
||||
version: "2.1.0",
|
||||
$schema:
|
||||
"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",
|
||||
runs: [
|
||||
{
|
||||
tool: {
|
||||
driver: { name: "CodeQL" },
|
||||
extensions: [
|
||||
{ name: "empty-pack" },
|
||||
{
|
||||
name: "pack-with-rules",
|
||||
rules: [{ id: "js/xss" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
results: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
const exitCode = checkSarif(sarif, {
|
||||
sarifFile: "test.sarif",
|
||||
queriesRun: "js/xss",
|
||||
queriesNotRun: "js/sql-injection",
|
||||
});
|
||||
assert.equal(exitCode, 0);
|
||||
});
|
||||
|
||||
await it("throws when tool extensions are undefined", () => {
|
||||
const sarif: Log = {
|
||||
version: "2.1.0",
|
||||
$schema:
|
||||
"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",
|
||||
runs: [
|
||||
{
|
||||
tool: { driver: { name: "CodeQL" } },
|
||||
results: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
assert.throws(
|
||||
() =>
|
||||
checkSarif(sarif, {
|
||||
sarifFile: "test.sarif",
|
||||
queriesRun: "js/xss",
|
||||
queriesNotRun: "",
|
||||
}),
|
||||
{ message: /Couldn't find tool extensions/ },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env npx tsx
|
||||
|
||||
/** Checks a SARIF file to see if certain queries were run and others were not run. */
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
import * as core from "@actions/core";
|
||||
import type { ReportingDescriptor, Log } from "sarif";
|
||||
|
||||
import { getErrorMessage } from "./util";
|
||||
|
||||
type Options = { sarifFile: string; queriesRun: string; queriesNotRun: string };
|
||||
|
||||
function getOptions(): Options {
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
// The path of the SARIF file to check.
|
||||
"sarif-file": {
|
||||
type: "string",
|
||||
},
|
||||
// The query ids to check are present.
|
||||
"queries-run": {
|
||||
type: "string",
|
||||
},
|
||||
// The query ids to check are absent.
|
||||
"queries-not-run": {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
strict: true,
|
||||
});
|
||||
|
||||
if (values["sarif-file"] === undefined) {
|
||||
throw new Error("The '--sarif-file' input is required.");
|
||||
}
|
||||
if (values["queries-run"] === undefined) {
|
||||
throw new Error("The '--queries-run' input is required.");
|
||||
}
|
||||
if (values["queries-not-run"] === undefined) {
|
||||
throw new Error("The '--queries-not-run' input is required.");
|
||||
}
|
||||
|
||||
return {
|
||||
sarifFile: values["sarif-file"],
|
||||
queriesRun: values["queries-run"],
|
||||
queriesNotRun: values["queries-not-run"],
|
||||
};
|
||||
}
|
||||
|
||||
function parseQueryIdsInput(queriesRun: string): string[] {
|
||||
return queriesRun
|
||||
.split(",")
|
||||
.map((q) => q.trim())
|
||||
.filter((q) => q.length > 0);
|
||||
}
|
||||
|
||||
export function checkSarif(sarif: Log, options: Options) {
|
||||
if (sarif.runs[0].tool.extensions === undefined) {
|
||||
throw new Error(`Couldn't find tool extensions in the SARIF file.`);
|
||||
}
|
||||
|
||||
let exitCode = 0;
|
||||
|
||||
// Extract the rule ids from the SARIF file.
|
||||
const rules: ReportingDescriptor[] = sarif.runs[0].tool.extensions.flatMap(
|
||||
(ext) => ext.rules || [],
|
||||
);
|
||||
const ruleIds: string[] = rules.map((rule) => rule.id);
|
||||
|
||||
// Check that all the expected queries ran
|
||||
const expectedQueriesRun = parseQueryIdsInput(options.queriesRun);
|
||||
const queriesThatShouldHaveRunButDidNot = expectedQueriesRun.filter(
|
||||
(queryId) => !ruleIds.includes(queryId),
|
||||
);
|
||||
|
||||
if (queriesThatShouldHaveRunButDidNot.length > 0) {
|
||||
core.error(
|
||||
`The following queries were expected to run but did not: ${queriesThatShouldHaveRunButDidNot.join(", ")}`,
|
||||
);
|
||||
exitCode = -2;
|
||||
}
|
||||
|
||||
// Check that all the unexpected queries did not run
|
||||
const expectedQueriesNotRun = parseQueryIdsInput(options.queriesNotRun);
|
||||
|
||||
const queriesThatShouldNotHaveRunButDid = expectedQueriesNotRun.filter(
|
||||
(queryId) => ruleIds.includes(queryId),
|
||||
);
|
||||
|
||||
if (queriesThatShouldNotHaveRunButDid.length > 0) {
|
||||
core.error(
|
||||
`The following queries were NOT expected to have run but did: ${queriesThatShouldNotHaveRunButDid.join(", ")}`,
|
||||
);
|
||||
exitCode = -2;
|
||||
}
|
||||
|
||||
core.startGroup("All queries that ran");
|
||||
for (const rule of rules) {
|
||||
core.info(`${rule.id}: ${rule.properties?.name || rule.name}`);
|
||||
}
|
||||
core.endGroup();
|
||||
|
||||
core.startGroup("Full SARIF");
|
||||
core.info(JSON.stringify(sarif, null, 2));
|
||||
core.endGroup();
|
||||
|
||||
return exitCode;
|
||||
}
|
||||
|
||||
function main() {
|
||||
try {
|
||||
const options = getOptions();
|
||||
const sarif: Log = JSON.parse(fs.readFileSync(options.sarifFile, "utf8"));
|
||||
|
||||
return checkSarif(sarif, options);
|
||||
} catch (err) {
|
||||
core.error(`Failed to check SARIF file: ${getErrorMessage(err)}`);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
process.exit(main());
|
||||
}
|
||||
@@ -2,8 +2,7 @@ name: "All-platform bundle"
|
||||
description: "Tests using an all-platform CodeQL Bundle"
|
||||
operatingSystems:
|
||||
- ubuntu
|
||||
- os: macos
|
||||
runner-image: macos-latest-xlarge
|
||||
- macos
|
||||
- windows
|
||||
versions:
|
||||
- nightly-latest
|
||||
|
||||
@@ -30,8 +30,7 @@ steps:
|
||||
- id: init
|
||||
uses: ./../action/init
|
||||
with:
|
||||
# Request multiple languages so this check uses the combined bundle.
|
||||
languages: javascript,python
|
||||
languages: javascript
|
||||
tools: ${{ steps.prepare-test.outputs.tools-url }}
|
||||
- uses: ./../action/analyze
|
||||
with:
|
||||
|
||||
@@ -11,10 +11,6 @@ installDotNet: true
|
||||
env:
|
||||
CODEQL_ACTION_SKIP_FILE_COVERAGE_ON_PRS: false
|
||||
CODEQL_ACTION_SUBLANGUAGE_FILE_COVERAGE: true
|
||||
# To balance speed and coverage, we analyze only a single language (JavaScript), but use the
|
||||
# combined bundle so we can test that baseline information is reported for each language in the
|
||||
# multi-language source directory.
|
||||
CODEQL_ACTION_PER_LANGUAGE_BUNDLES: false
|
||||
steps:
|
||||
- uses: ./../action/init
|
||||
id: init
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
name: "Linux Arm64"
|
||||
description: "An end-to-end integration test running on a Linux Arm64 runner, checking that the native linux-arm64 CodeQL bundle is downloaded and can analyze interpreted and compiled code"
|
||||
operatingSystems:
|
||||
- os: ubuntu
|
||||
runner-image: ubuntu-24.04-arm
|
||||
# The native linux-arm64 CodeQL bundle is only available in recent CLI releases, so we restrict this
|
||||
# check to `nightly-latest`, which is guaranteed to ship it. Older stable versions do not have an
|
||||
# arm64 asset, and `prepare-test` would resolve an x64 bundle URL for them on this runner.
|
||||
versions:
|
||||
- nightly-latest
|
||||
installGo: true
|
||||
installDotNet: true
|
||||
# The set of languages CodeQL supports on this platform, excluding Swift (macOS only).
|
||||
env:
|
||||
LANGUAGES: cpp,csharp,go,java,javascript,python,ruby
|
||||
steps:
|
||||
- uses: ./../action/init
|
||||
with:
|
||||
languages: ${{ env.LANGUAGES }}
|
||||
tools: ${{ steps.prepare-test.outputs.tools-url }}
|
||||
- name: Build code
|
||||
run: ./build.sh
|
||||
- uses: ./../action/analyze
|
||||
with:
|
||||
upload-database: false
|
||||
- name: Assert databases exist
|
||||
run: |
|
||||
cd "$RUNNER_TEMP/codeql_databases"
|
||||
for lang in ${LANGUAGES//,/ }; do
|
||||
if [[ ! -d "$lang" ]]; then
|
||||
echo "Did not find a database for $lang"
|
||||
exit 1
|
||||
fi
|
||||
echo "Found database for $lang"
|
||||
done
|
||||
@@ -15,19 +15,17 @@ operatingSystems:
|
||||
- stable-v2.21.4
|
||||
- stable-v2.22.4
|
||||
env:
|
||||
CODEQL_ACTION_CLEANUP_TOOLCACHE_BUNDLES: true
|
||||
CODEQL_ACTION_RESOLVE_SUPPORTED_LANGUAGES_USING_CLI: true
|
||||
installGo: true
|
||||
installDotNet: true
|
||||
steps:
|
||||
- name: Install Python 3.13.15 for older CLI versions
|
||||
# Older CLI versions don't work with Python 3.13.16 or newer because their Python extractor
|
||||
# imports `importlib._bootstrap._ERR_MSG`, which those Python versions no longer define.
|
||||
- name: Install Python 3.13 for older CLI versions
|
||||
# We need Python 3.13 for older CLI versions because they are not compatible with Python 3.14 or newer.
|
||||
# See https://github.com/github/codeql-action/pull/3212
|
||||
if: matrix.version != 'nightly-latest' && matrix.version != 'linked'
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.13.15"
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Use Xcode 16
|
||||
# Only the older CodeQL CLI versions need Xcode 16, and these run on macOS 15.
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
name: Per-language bundles
|
||||
description: Validates extraction and analysis using each per-language CodeQL bundle.
|
||||
# TODO: Use a released bundle once releases include per-language bundles.
|
||||
matrix:
|
||||
include:
|
||||
- language: actions
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
# Actions also needs the JavaScript extractor.
|
||||
expected-extractors: actions javascript
|
||||
- language: cpp
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
build-mode: manual
|
||||
build-command: gcc -o main main.c
|
||||
- language: csharp
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
build-mode: none
|
||||
- language: go
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
build-mode: autobuild
|
||||
- language: java
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
build-mode: none
|
||||
- language: javascript
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- language: python
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- language: ruby
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- language: rust
|
||||
os: ubuntu-latest
|
||||
version: nightly-latest
|
||||
- language: swift
|
||||
os: macos-latest-xlarge
|
||||
version: nightly-latest
|
||||
build-mode: autobuild
|
||||
env:
|
||||
CODEQL_ACTION_PER_LANGUAGE_BUNDLES: true
|
||||
steps:
|
||||
- uses: ./../action/init
|
||||
id: init
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix['build-mode'] }}
|
||||
tools: ${{ steps.prepare-test.outputs.tools-url }}
|
||||
- name: Check that the bundle contains only the expected extractors
|
||||
env:
|
||||
CODEQL_PATH: ${{ steps.init.outputs.codeql-path }}
|
||||
LANGUAGE: ${{ matrix.language }}
|
||||
EXPECTED_EXTRACTORS: ${{ matrix['expected-extractors'] || matrix.language }}
|
||||
run: |
|
||||
extractors="$("$CODEQL_PATH" resolve languages --format=json | jq -r 'keys[]')"
|
||||
echo "Extractors in the bundle:"
|
||||
echo "$extractors"
|
||||
echo "Expected: $EXPECTED_EXTRACTORS"
|
||||
|
||||
for expected in $EXPECTED_EXTRACTORS; do
|
||||
if ! echo "$extractors" | grep -qx "$expected"; then
|
||||
echo "::error::The ${LANGUAGE} bundle does not contain the ${expected} extractor."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# If the bundle contained extractors beyond those the language needs, then it would not
|
||||
# have been trimmed, and this job would be silently validating the combined bundle.
|
||||
for other in actions cpp csharp go java javascript python ruby rust swift; do
|
||||
if echo "$EXPECTED_EXTRACTORS" | grep -qw "$other"; then
|
||||
continue
|
||||
fi
|
||||
if echo "$extractors" | grep -qx "$other"; then
|
||||
echo "::error::The ${LANGUAGE} bundle also contains the ${other} extractor, so it is not trimmed."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
- name: Check that the bundle was not added to the toolcache
|
||||
env:
|
||||
CODEQL_PATH: ${{ steps.init.outputs.codeql-path }}
|
||||
run: |
|
||||
# A bundle that is missing most of its extractors must never be left in the toolcache,
|
||||
# where a later job analyzing a different language could pick it up. The runner image
|
||||
# ships with its own CodeQL in the toolcache, so check where this bundle was extracted to
|
||||
# rather than whether the toolcache contains CodeQL at all.
|
||||
echo "CodeQL is at $CODEQL_PATH"
|
||||
if [[ "$CODEQL_PATH" == "$RUNNER_TOOL_CACHE"/* ]]; then
|
||||
echo "::error::The per-language bundle was added to the toolcache at $CODEQL_PATH."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$CODEQL_PATH" != "$RUNNER_TEMP"/* ]]; then
|
||||
echo "::error::Expected the per-language bundle to be extracted under $RUNNER_TEMP, but found it at $CODEQL_PATH."
|
||||
exit 1
|
||||
fi
|
||||
- name: Build code
|
||||
if: matrix['build-command']
|
||||
run: ${{ matrix['build-command'] }}
|
||||
- uses: ./../action/analyze
|
||||
id: analysis
|
||||
with:
|
||||
upload-database: false
|
||||
- name: Check that a database was created for the language
|
||||
env:
|
||||
DB_LOCATIONS: ${{ steps.analysis.outputs.db-locations }}
|
||||
LANGUAGE: ${{ matrix.language }}
|
||||
run: |
|
||||
database="$(echo "$DB_LOCATIONS" | jq -r --arg lang "$LANGUAGE" '.[$lang] // empty')"
|
||||
if [ -z "$database" ] || [ ! -d "$database" ]; then
|
||||
echo "::error::No CodeQL database was created for ${LANGUAGE}."
|
||||
echo "Databases: $DB_LOCATIONS"
|
||||
exit 1
|
||||
fi
|
||||
echo "Created a ${LANGUAGE} database at ${database}."
|
||||
@@ -5,7 +5,7 @@ versions:
|
||||
- default
|
||||
steps:
|
||||
- name: Set up Ruby
|
||||
uses: ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8 # v1.327.0
|
||||
uses: ruby/setup-ruby@95ef2b042f9d7a56d8268cba8559e2842e2ad01b # v1.321.0
|
||||
with:
|
||||
ruby-version: 2.6
|
||||
- name: Install Code Scanning integration
|
||||
|
||||
@@ -5,8 +5,7 @@ versions:
|
||||
- default
|
||||
- nightly-latest
|
||||
operatingSystems:
|
||||
- os: macos
|
||||
runner-image: macos-latest-xlarge
|
||||
- macos
|
||||
installGo: true
|
||||
installDotNet: true
|
||||
env:
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { execFileSync, ExecFileSyncOptions } from "node:child_process";
|
||||
|
||||
import { DryRunOption, REPO_ROOT } from "./config";
|
||||
|
||||
/** Options for {@link runCommand}. */
|
||||
export interface RunCommandOptions extends DryRunOption {
|
||||
/** Options for `execFileSync`. */
|
||||
execOptions?: ExecFileSyncOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a command, streaming output to the console by default.
|
||||
*
|
||||
* @param command The name of the command to run.
|
||||
* @param args The arguments for the command.
|
||||
* @throws When the process exits with a non-zero exit code.
|
||||
* @param options How to run the command.
|
||||
*/
|
||||
export function runCommand(
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: RunCommandOptions,
|
||||
) {
|
||||
if (!options?.dryRun) {
|
||||
console.log(`Running \`${command} ${args.join(" ")}\`.`);
|
||||
return execFileSync(command, args, {
|
||||
stdio: "inherit",
|
||||
cwd: REPO_ROOT,
|
||||
...options?.execOptions,
|
||||
});
|
||||
} else {
|
||||
console.info(
|
||||
`[DRY RUN] Would have executed '${command} ${args.join(" ")}'`,
|
||||
);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** Options for {@link runGit}. */
|
||||
export interface RunGitOptions extends DryRunOption {
|
||||
/** When true, non-zero exit codes will not throw. */
|
||||
allowNonZeroExitCode?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `git` with the given `args` and returns the stdout.
|
||||
*
|
||||
* @param args - Arguments to pass to `git`.
|
||||
* @param options - Optional settings.
|
||||
* @throws If `git` does not exit successfully, unless
|
||||
* `options.allowNonZeroExitCode` is `true`.
|
||||
* @returns The trimmed stdout output.
|
||||
*/
|
||||
export function runGit(args: string[], options?: RunGitOptions): string {
|
||||
const execOptions: ExecFileSyncOptions = {
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
};
|
||||
|
||||
try {
|
||||
const result = runCommand("git", args, {
|
||||
dryRun: options?.dryRun,
|
||||
execOptions,
|
||||
}) as string;
|
||||
return result.trimEnd();
|
||||
} catch (error: unknown) {
|
||||
if (options?.allowNonZeroExitCode) {
|
||||
// execFileSync throws an object with `stdout` when the process exits
|
||||
// with a non-zero code.
|
||||
const execError = error as { stdout?: Buffer | string };
|
||||
if (typeof execError.stdout === "string") {
|
||||
return execError.stdout.trimEnd();
|
||||
}
|
||||
if (Buffer.isBuffer(execError.stdout)) {
|
||||
return execError.stdout.toString("utf8").trimEnd();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
+7
-9
@@ -1,9 +1,4 @@
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
// For backwards-compatibility.
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
/** The oldest supported major version of the CodeQL Action. */
|
||||
export const OLDEST_SUPPORTED_MAJOR_VERSION = 3;
|
||||
@@ -23,14 +18,17 @@ export const PACKAGE_JSON = path.join(REPO_ROOT, "package.json");
|
||||
/** The path of the changelog. */
|
||||
export const CHANGELOG_FILE = path.join(REPO_ROOT, "CHANGELOG.md");
|
||||
|
||||
/** The path to the unreleased change-notes directory. */
|
||||
export const CHANGENOTES_DIR = path.join(REPO_ROOT, "unreleased-change-notes");
|
||||
|
||||
/** The path to the esbuild metadata file. */
|
||||
export const BUNDLE_METADATA_FILE = path.join(REPO_ROOT, "meta.json");
|
||||
|
||||
/** The `src` directory. */
|
||||
const SOURCE_ROOT = path.join(REPO_ROOT, "src");
|
||||
export const SOURCE_ROOT = path.join(REPO_ROOT, "src");
|
||||
|
||||
/** The `src` directory. */
|
||||
export const LIB_ROOT = path.join(REPO_ROOT, "lib");
|
||||
|
||||
/** The path to `defaults.json`. */
|
||||
export const DEFAULTS_FILE = path.join(SOURCE_ROOT, "defaults.json");
|
||||
|
||||
/** The path to the built-in languages file. */
|
||||
export const BUILTIN_LANGUAGES_FILE = path.join(
|
||||
|
||||
@@ -5,8 +5,6 @@ contains:
|
||||
- "test-setup-python-scripts"
|
||||
- "update"
|
||||
- "Update"
|
||||
# Matrix-ed job; the name starts with this
|
||||
- "Create backport"
|
||||
is:
|
||||
- "Agent"
|
||||
- "check-expected-release-files"
|
||||
@@ -17,6 +15,4 @@ is:
|
||||
- "Label PR with size"
|
||||
- "Post repo size comment"
|
||||
- "Prepare"
|
||||
- "Release info"
|
||||
- "Upload results"
|
||||
- "Update release branch"
|
||||
|
||||
+7
-10
@@ -1,20 +1,17 @@
|
||||
{
|
||||
"private": true,
|
||||
"description": "Dependencies for codeql-action scripts",
|
||||
"type": "module",
|
||||
"description": "Dependencies for the sync.ts",
|
||||
"dependencies": {
|
||||
"@actions/core": "^2.0.3",
|
||||
"@actions/github": "^8.0.1",
|
||||
"@octokit/core": "^7.0.8",
|
||||
"@octokit/plugin-paginate-rest": ">=15.0.0",
|
||||
"@octokit/plugin-rest-endpoint-methods": "^18.0.0",
|
||||
"lite-matter": "^0.1.2",
|
||||
"mdast-util-from-markdown": "^2.0.3",
|
||||
"@octokit/core": "^7.0.6",
|
||||
"@octokit/plugin-paginate-rest": ">=9.2.2",
|
||||
"@octokit/plugin-rest-endpoint-methods": "^17.0.0",
|
||||
"semver": "^7.8.5",
|
||||
"yaml": "^2.9.1"
|
||||
"yaml": "^2.9.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.19.0",
|
||||
"tsx": "^4.23.15"
|
||||
"@types/node": "^20.19.43",
|
||||
"tsx": "^4.23.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +77,6 @@ function main() {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
process.exit(main());
|
||||
}
|
||||
|
||||
@@ -116,6 +116,6 @@ async function main() {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
void main();
|
||||
}
|
||||
|
||||
@@ -79,6 +79,6 @@ function main() {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
process.exit(main());
|
||||
}
|
||||
|
||||
@@ -21,11 +21,10 @@ import * as fs from "fs";
|
||||
import { parseArgs } from "node:util";
|
||||
import * as path from "path";
|
||||
|
||||
import { PR_CHECKS_DIR, REPO_ROOT } from "./config";
|
||||
|
||||
const CHECKS_DIR = path.join(PR_CHECKS_DIR, "checks");
|
||||
const WORKFLOW_DIR = path.join(REPO_ROOT, ".github", "workflows");
|
||||
const SYNC_TS_PATH = path.join(PR_CHECKS_DIR, "sync.ts");
|
||||
const THIS_DIR = __dirname;
|
||||
const CHECKS_DIR = path.join(THIS_DIR, "checks");
|
||||
const WORKFLOW_DIR = path.join(THIS_DIR, "..", ".github", "workflows");
|
||||
const SYNC_TS_PATH = path.join(THIS_DIR, "sync.ts");
|
||||
|
||||
/**
|
||||
* Scan generated workflow files to extract the latest action versions.
|
||||
@@ -233,6 +232,6 @@ function main(): number {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
process.exit(main());
|
||||
}
|
||||
|
||||
@@ -342,6 +342,6 @@ async function main(): Promise<void> {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
void main();
|
||||
}
|
||||
|
||||
+2
-9
@@ -4,19 +4,12 @@ set -e
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
# Run `npm ci` in CI or `npm install` otherwise.
|
||||
#
|
||||
# `pr-checks` is an npm workspace of the repository root and the two share a single hoisted
|
||||
# `node_modules` directory. Running npm from this directory puts it in workspace mode, where it
|
||||
# ignores the root project's own dependencies by default. `npm ci` would then rebuild the shared
|
||||
# `node_modules` with only this workspace's dependencies, removing the root's ones, which breaks
|
||||
# anything that imports from `src` (such as `sync.ts` itself). `--include-workspace-root` keeps the
|
||||
# root project's dependencies in the installed tree.
|
||||
if [ "$GITHUB_ACTIONS" = "true" ]; then
|
||||
echo "In Actions, running 'npm ci' for 'sync.ts'..."
|
||||
npm ci --include-workspace-root
|
||||
npm ci
|
||||
else
|
||||
echo "Running 'npm install' for 'sync.ts'..."
|
||||
npm install --no-audit --no-fund --include-workspace-root
|
||||
npm install --no-audit --no-fund
|
||||
fi
|
||||
|
||||
npx tsx sync.ts
|
||||
|
||||
+10
-16
@@ -7,8 +7,6 @@ import * as yaml from "yaml";
|
||||
|
||||
import { BuiltInLanguage } from "../src/languages";
|
||||
|
||||
import { PR_CHECKS_DIR, REPO_ROOT } from "./config";
|
||||
|
||||
/**
|
||||
* Returns a `uses` value for `action` pinned to a commit SHA, with the
|
||||
* human-readable version recorded in a trailing comment.
|
||||
@@ -81,8 +79,6 @@ interface Specification extends JobSpecification {
|
||||
useAllPlatformBundle?: string;
|
||||
/** Values for the `analysis-kinds` matrix dimension. */
|
||||
analysisKinds?: string[];
|
||||
/** Overrides the generated job matrix using GitHub Actions matrix syntax. */
|
||||
matrix?: Record<string, unknown>;
|
||||
|
||||
/** Container image configuration for the job. */
|
||||
container?: any;
|
||||
@@ -223,12 +219,6 @@ const languageSetups: LanguageSetups = {
|
||||
cache: "npm",
|
||||
},
|
||||
},
|
||||
// Install a new enough version of `npm` to understand `min-release-age`
|
||||
// that is still compatible with Node 20.
|
||||
{
|
||||
name: "Install newer npm",
|
||||
run: "npm install -g npm@11.19.1",
|
||||
},
|
||||
{
|
||||
name: "Install dependencies",
|
||||
run: "npm ci",
|
||||
@@ -263,8 +253,8 @@ const languageSetups: LanguageSetups = {
|
||||
name: "Install Java",
|
||||
uses: pinnedUses(
|
||||
"actions/setup-java",
|
||||
"de7274f081f381c8f8158605e0321c36c376e2e6",
|
||||
"v6.0.1",
|
||||
"03ad4de0992f5dab5e18fcb136590ce7c4a0ac95",
|
||||
"v5.6.0",
|
||||
),
|
||||
with: {
|
||||
"java-version": `\${{ inputs.java-version || '${defaultLanguageVersions.java}' }}`,
|
||||
@@ -314,8 +304,9 @@ const languageSetups: LanguageSetups = {
|
||||
// See https://github.com/github/codeql-action/pull/3423
|
||||
const YQ_VERSION = "v4.50.1";
|
||||
|
||||
const CHECKS_DIR = path.join(PR_CHECKS_DIR, "checks");
|
||||
const OUTPUT_DIR = path.join(REPO_ROOT, ".github", "workflows");
|
||||
const THIS_DIR = __dirname;
|
||||
const CHECKS_DIR = path.join(THIS_DIR, "checks");
|
||||
const OUTPUT_DIR = path.join(THIS_DIR, "..", ".github", "workflows");
|
||||
|
||||
/**
|
||||
* Loads and parses a YAML file.
|
||||
@@ -521,6 +512,9 @@ function generateJob(
|
||||
specDocument: yaml.Document,
|
||||
checkSpecification: Specification,
|
||||
) {
|
||||
const matrix: Array<Record<string, any>> =
|
||||
generateJobMatrix(checkSpecification);
|
||||
|
||||
const useAllPlatformBundle = checkSpecification.useAllPlatformBundle
|
||||
? checkSpecification.useAllPlatformBundle
|
||||
: "false";
|
||||
@@ -573,8 +567,8 @@ function generateJob(
|
||||
const checkJob: Record<string, any> = {
|
||||
strategy: {
|
||||
"fail-fast": false,
|
||||
matrix: checkSpecification.matrix ?? {
|
||||
include: generateJobMatrix(checkSpecification),
|
||||
matrix: {
|
||||
include: matrix,
|
||||
},
|
||||
},
|
||||
name: checkSpecification.name,
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
"module": "preserve",
|
||||
"rootDir": "..",
|
||||
"sourceMap": false,
|
||||
"noEmit": true
|
||||
"noEmit": true,
|
||||
},
|
||||
"include": ["./**/*.ts", "../src/**/*.ts"],
|
||||
"include": ["./*.ts", "../src/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Tests for the update-bundle.ts script.
|
||||
*/
|
||||
|
||||
import * as assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
|
||||
import { Defaults, getNewDefaults } from "./update-bundle";
|
||||
|
||||
const testDefaults: Defaults = {
|
||||
bundleVersion: "codeql-bundle-v2.26.2",
|
||||
cliVersion: "2.26.2",
|
||||
priorBundleVersion: "codeql-bundle-v2.26.1",
|
||||
priorCliVersion: "2.26.1",
|
||||
};
|
||||
|
||||
describe("getNewDefaults", async () => {
|
||||
await it("throws if there is no cli-version-*.txt asset", async () => {
|
||||
assert.throws(
|
||||
() => getNewDefaults({ tag_name: "foo", assets: [] }, testDefaults),
|
||||
{ message: "Failed to find the CodeQL CLI version for release foo." },
|
||||
);
|
||||
});
|
||||
|
||||
await it("throws if there are multiple cli-version-*.txt assets", async () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
getNewDefaults(
|
||||
{
|
||||
tag_name: "foo",
|
||||
assets: [
|
||||
{ name: "cli-version-foo.txt" },
|
||||
{ name: "cli-version-bar.txt" },
|
||||
],
|
||||
},
|
||||
testDefaults,
|
||||
),
|
||||
{ message: "Release foo has multiple CLI version marker files." },
|
||||
);
|
||||
});
|
||||
|
||||
await it("finds the new bundle info", async () => {
|
||||
const newDefaults = getNewDefaults(
|
||||
{
|
||||
tag_name: "foo",
|
||||
assets: [{ name: "cli-version-1.2.3.txt" }],
|
||||
},
|
||||
testDefaults,
|
||||
);
|
||||
|
||||
assert.deepEqual(newDefaults, {
|
||||
bundleVersion: "foo",
|
||||
cliVersion: "1.2.3",
|
||||
priorBundleVersion: testDefaults.bundleVersion,
|
||||
priorCliVersion: testDefaults.cliVersion,
|
||||
} satisfies Defaults);
|
||||
});
|
||||
});
|
||||
Executable
+93
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env npx tsx
|
||||
|
||||
/** Updates 'src/defaults.json' to point to a new CodeQL bundle release. */
|
||||
|
||||
import * as fs from "fs";
|
||||
|
||||
import * as github from "@actions/github";
|
||||
|
||||
import * as defaults from "../src/defaults.json";
|
||||
|
||||
import { DEFAULTS_FILE } from "./config";
|
||||
|
||||
interface BundleInfo {
|
||||
bundleVersion: string;
|
||||
cliVersion: string;
|
||||
}
|
||||
|
||||
export type Defaults = typeof defaults;
|
||||
|
||||
interface Release {
|
||||
tag_name: string;
|
||||
assets: Array<{
|
||||
name: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function getCodeQLCliVersionForRelease(release: Release): string {
|
||||
// We do not currently tag CodeQL bundles based on the CLI version they contain.
|
||||
// Instead, we use a marker file `cli-version-<version>.txt` to record the CLI version.
|
||||
// This marker file is uploaded as a release asset for all new CodeQL bundles.
|
||||
const cliVersionsFromMarkerFiles = release.assets
|
||||
.map((asset) => asset.name.match(/cli-version-(.*)\.txt/)?.[1])
|
||||
.filter((v) => v)
|
||||
.map((v) => v as string);
|
||||
if (cliVersionsFromMarkerFiles.length > 1) {
|
||||
throw new Error(
|
||||
`Release ${release.tag_name} has multiple CLI version marker files.`,
|
||||
);
|
||||
} else if (cliVersionsFromMarkerFiles.length === 0) {
|
||||
throw new Error(
|
||||
`Failed to find the CodeQL CLI version for release ${release.tag_name}.`,
|
||||
);
|
||||
}
|
||||
return cliVersionsFromMarkerFiles[0];
|
||||
}
|
||||
|
||||
function getBundleInfoFromRelease(release: Release): BundleInfo {
|
||||
return {
|
||||
bundleVersion: release.tag_name,
|
||||
cliVersion: getCodeQLCliVersionForRelease(release),
|
||||
};
|
||||
}
|
||||
|
||||
export function getNewDefaults(
|
||||
release: Release,
|
||||
currentDefaults: Defaults,
|
||||
): Defaults {
|
||||
console.log(
|
||||
"Updating default bundle as a result of the following release: " +
|
||||
`${JSON.stringify(release)}.`,
|
||||
);
|
||||
|
||||
const bundleInfo = getBundleInfoFromRelease(release);
|
||||
|
||||
return {
|
||||
bundleVersion: bundleInfo.bundleVersion,
|
||||
cliVersion: bundleInfo.cliVersion,
|
||||
priorBundleVersion: currentDefaults.bundleVersion,
|
||||
priorCliVersion: currentDefaults.cliVersion,
|
||||
};
|
||||
}
|
||||
|
||||
function main() {
|
||||
const release: Release = github.context.payload.release;
|
||||
|
||||
if (release === undefined) {
|
||||
console.error(`Release payload is undefined.`);
|
||||
return -1;
|
||||
}
|
||||
|
||||
const previousDefaults = defaults;
|
||||
const newDefaults = getNewDefaults(release, previousDefaults);
|
||||
|
||||
// Update the source file in the repository. Calling workflows should subsequently rebuild
|
||||
// the Action to update `lib/defaults.json`.
|
||||
fs.writeFileSync(DEFAULTS_FILE, `${JSON.stringify(newDefaults, null, 2)}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
process.exit(main());
|
||||
}
|
||||
@@ -238,6 +238,6 @@ function main() {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
main();
|
||||
}
|
||||
|
||||
@@ -18,12 +18,12 @@
|
||||
* [--dry-run]
|
||||
*/
|
||||
|
||||
import { execFileSync, type ExecFileSyncOptions } from "node:child_process";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
import { type ApiClient, getApiClient } from "./api-client";
|
||||
import * as changelog from "./changelog";
|
||||
import { DryRunOption, REPO_ROOT } from "./config";
|
||||
import { runCommand, runGit } from "./command";
|
||||
import {
|
||||
getCurrentVersion,
|
||||
replaceVersionInPackageJson,
|
||||
@@ -65,84 +65,6 @@ export function getGitHubToken(): string {
|
||||
throw new Error("Missing GitHub token. Set GITHUB_TOKEN or GH_TOKEN.");
|
||||
}
|
||||
|
||||
/** Options for {@link runCommand}. */
|
||||
export interface RunCommandOptions extends DryRunOption {
|
||||
/** Options for `execFileSync`. */
|
||||
execOptions?: ExecFileSyncOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a command, streaming output to the console by default.
|
||||
*
|
||||
* @param command The name of the command to run.
|
||||
* @param args The arguments for the command.
|
||||
* @throws When the process exits with a non-zero exit code.
|
||||
* @param options How to run the command.
|
||||
*/
|
||||
export function runCommand(
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: RunCommandOptions,
|
||||
) {
|
||||
if (!options?.dryRun) {
|
||||
console.log(`Running \`${command} ${args.join(" ")}\`.`);
|
||||
return execFileSync(command, args, {
|
||||
stdio: "inherit",
|
||||
cwd: REPO_ROOT,
|
||||
...options?.execOptions,
|
||||
});
|
||||
} else {
|
||||
console.info(
|
||||
`[DRY RUN] Would have executed '${command} ${args.join(" ")}'`,
|
||||
);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** Options for {@link runGit}. */
|
||||
export interface RunGitOptions extends DryRunOption {
|
||||
/** When true, non-zero exit codes will not throw. */
|
||||
allowNonZeroExitCode?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `git` with the given `args` and returns the stdout.
|
||||
*
|
||||
* @param args - Arguments to pass to `git`.
|
||||
* @param options - Optional settings.
|
||||
* @throws If `git` does not exit successfully, unless
|
||||
* `options.allowNonZeroExitCode` is `true`.
|
||||
* @returns The trimmed stdout output.
|
||||
*/
|
||||
export function runGit(args: string[], options?: RunGitOptions): string {
|
||||
const execOptions: ExecFileSyncOptions = {
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
};
|
||||
|
||||
try {
|
||||
const result = runCommand("git", args, {
|
||||
dryRun: options?.dryRun,
|
||||
execOptions,
|
||||
}) as string;
|
||||
return result.trimEnd();
|
||||
} catch (error: unknown) {
|
||||
if (options?.allowNonZeroExitCode) {
|
||||
// execFileSync throws an object with `stdout` when the process exits
|
||||
// with a non-zero code.
|
||||
const execError = error as { stdout?: Buffer | string };
|
||||
if (typeof execError.stdout === "string") {
|
||||
return execError.stdout.trimEnd();
|
||||
}
|
||||
if (Buffer.isBuffer(execError.stdout)) {
|
||||
return execError.stdout.toString("utf8").trimEnd();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns true if the given branch exists on the origin remote. */
|
||||
export function branchExistsOnRemote(branchName: string): boolean {
|
||||
const result = runGit(["ls-remote", "--heads", ORIGIN, branchName]);
|
||||
@@ -835,6 +757,6 @@ async function main(): Promise<void> {
|
||||
}
|
||||
|
||||
// Only call `main` if this script was run directly.
|
||||
if (import.meta.main) {
|
||||
if (require.main === module) {
|
||||
void main();
|
||||
}
|
||||
|
||||
+10
-7
@@ -21,16 +21,19 @@ inputs:
|
||||
required: false
|
||||
languages:
|
||||
description: >-
|
||||
A comma-separated list of CodeQL languages that the installed CodeQL CLI will be used to
|
||||
analyze. If specified, the Action may use this list to select a CodeQL CLI version that is
|
||||
best suited to analyzing those languages, for example by preferring a version that has a
|
||||
cached overlay-base database for the specified languages.
|
||||
A comma-separated list of CodeQL languages that will be analyzed in subsequent
|
||||
`github/codeql-action/init` and `github/codeql-action/analyze` invocations. If specified, the
|
||||
Action may use this list to select a CodeQL CLI version that is best suited to analyzing those
|
||||
languages, for example by preferring a version that has a cached overlay-base database for the
|
||||
specified languages. This input is not remembered and must also be passed to
|
||||
`github/codeql-action/init`.
|
||||
required: false
|
||||
analysis-kinds:
|
||||
description: >-
|
||||
[Internal] A comma-separated list of analysis kinds that the installed CodeQL CLI will be used
|
||||
for. If specified, the Action may use this list to select a CodeQL CLI version that is best
|
||||
suited to those analysis kinds.
|
||||
[Internal] A comma-separated list of analysis kinds that subsequent
|
||||
`github/codeql-action/init` invocations will enable. If specified, the Action may use this
|
||||
list to select a CodeQL CLI version that is best suited to those analysis kinds. This input is
|
||||
not remembered and must also be passed to `github/codeql-action/init`.
|
||||
|
||||
Available options are the same as for the `analysis-kinds` input on the `init` Action.
|
||||
default: 'code-scanning'
|
||||
|
||||
@@ -19,10 +19,6 @@ export interface BaseState {
|
||||
name: ActionName;
|
||||
/** When the Action was started. */
|
||||
startedAt: Date;
|
||||
/** The platform the Action is running on. */
|
||||
platform: NodeJS.Platform;
|
||||
/** The architecture of the host. */
|
||||
arch: NodeJS.Architecture;
|
||||
}
|
||||
|
||||
/** Describes different state features that an Action may have. */
|
||||
@@ -102,8 +98,6 @@ export async function runInActions(action: Action) {
|
||||
const actionState = {
|
||||
name: action.name,
|
||||
startedAt,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
logger,
|
||||
env,
|
||||
actions: actionsEnv,
|
||||
|
||||
+7
-30
@@ -7,14 +7,13 @@ import * as github from "@actions/github";
|
||||
import * as io from "@actions/io";
|
||||
|
||||
import type { Config } from "./config-utils";
|
||||
import { Env, EnvVar, ActionsEnvVars, ReadOnlyEnv } from "./environment";
|
||||
import { Env, EnvVar, ActionsEnvVars } from "./environment";
|
||||
import { Logger } from "./logging";
|
||||
import {
|
||||
doesDirectoryExist,
|
||||
getCodeQLDatabasePath,
|
||||
ConfigurationError,
|
||||
getEnv,
|
||||
getErrorMessage,
|
||||
} from "./util";
|
||||
|
||||
/**
|
||||
@@ -284,19 +283,6 @@ export function isSelfHostedRunner(env: Env = getEnv()) {
|
||||
return env.getOptional(ActionsEnvVars.RUNNER_ENVIRONMENT) === "self-hosted";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the job is running on a runner that GitHub hosts, and whose toolcache is therefore thrown
|
||||
* away once the job has finished.
|
||||
*
|
||||
* Unlike `looksLikeHostedRunner`, this is based on what the service reports for the job rather than
|
||||
* on how the runner's filesystem happens to be laid out, so it does not match self-hosted runners
|
||||
* that are configured to resemble hosted ones, such as those that mount a persistent volume at
|
||||
* `/opt/hostedtoolcache`.
|
||||
*/
|
||||
export function isGitHubHostedRunner(env: ReadOnlyEnv = getEnv()) {
|
||||
return env.getOptional(ActionsEnvVars.RUNNER_ENVIRONMENT) === "github-hosted";
|
||||
}
|
||||
|
||||
/** Determines whether the workflow trigger is `dynamic`. */
|
||||
export function isDynamicWorkflow(env: Env = getEnv()): boolean {
|
||||
return getWorkflowEventName(env) === "dynamic";
|
||||
@@ -413,23 +399,14 @@ export const persistInputs = function (env: Env = getEnv()) {
|
||||
/**
|
||||
* Restores all inputs to the action from the persisted state.
|
||||
*/
|
||||
export function restoreInputs(logger: Logger) {
|
||||
try {
|
||||
const persistedInputsValue = core.getState(persistedInputsKey);
|
||||
if (persistedInputsValue) {
|
||||
const persistedInputs = JSON.parse(persistedInputsValue);
|
||||
|
||||
for (const [name, value] of persistedInputs) {
|
||||
process.env[name] = value;
|
||||
}
|
||||
export const restoreInputs = function () {
|
||||
const persistedInputs = core.getState(persistedInputsKey);
|
||||
if (persistedInputs) {
|
||||
for (const [name, value] of JSON.parse(persistedInputs)) {
|
||||
process.env[name] = value;
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(`Unable to restore inputs: ${getErrorMessage(err)}`);
|
||||
throw new Error(
|
||||
"Failed to restore inputs from the state set by this action's main execution.",
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export interface PullRequestBranches {
|
||||
base: string;
|
||||
|
||||
@@ -25,8 +25,8 @@ export async function runWrapper() {
|
||||
// possible, and only use safe functions outside.
|
||||
|
||||
try {
|
||||
actionsUtil.restoreInputs();
|
||||
const logger = getActionsLogger();
|
||||
actionsUtil.restoreInputs(logger);
|
||||
const gitHubVersion = await getGitHubVersion();
|
||||
checkGitHubVersionInRange(gitHubVersion, logger);
|
||||
|
||||
@@ -38,7 +38,7 @@ export async function runWrapper() {
|
||||
logger,
|
||||
);
|
||||
if (config !== undefined) {
|
||||
const codeql = await getCodeQL(logger, config.codeQLCmd);
|
||||
const codeql = await getCodeQL(config.codeQLCmd);
|
||||
const version = await codeql.getVersion();
|
||||
await debugArtifacts.uploadCombinedSarifArtifacts(
|
||||
logger,
|
||||
|
||||
+7
-20
@@ -212,11 +212,7 @@ async function runAutobuildIfLegacyGoWorkflow(config: Config, logger: Logger) {
|
||||
await runAutobuild(config, BuiltInLanguage.go, logger);
|
||||
}
|
||||
|
||||
async function run({
|
||||
startedAt,
|
||||
logger,
|
||||
actions,
|
||||
}: ActionState<["Base", "Logger", "Actions"]>) {
|
||||
async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
|
||||
// To capture errors appropriately, keep as much code within the try-catch as
|
||||
// possible, and only use safe functions outside.
|
||||
|
||||
@@ -259,7 +255,7 @@ async function run({
|
||||
);
|
||||
}
|
||||
|
||||
const codeql = await getCodeQL(logger, config.codeQLCmd);
|
||||
const codeql = await getCodeQL(config.codeQLCmd);
|
||||
|
||||
if (hasBadExpectErrorInput()) {
|
||||
throw new util.ConfigurationError(
|
||||
@@ -311,13 +307,8 @@ async function run({
|
||||
logger,
|
||||
);
|
||||
|
||||
const checkoutPath = actions.getRequiredInput("checkout_path");
|
||||
|
||||
// Setup diff informed analysis if needed (based on whether init created the file)
|
||||
const diffRangePackDir = await setupDiffInformedQueryRun(
|
||||
logger,
|
||||
checkoutPath,
|
||||
);
|
||||
const diffRangePackDir = await setupDiffInformedQueryRun(logger);
|
||||
|
||||
await warnIfGoInstalledAfterInit(config, logger);
|
||||
await runAutobuildIfLegacyGoWorkflow(config, logger);
|
||||
@@ -363,6 +354,7 @@ async function run({
|
||||
actionsUtil.getOptionalInput("upload"),
|
||||
);
|
||||
if (runStats) {
|
||||
const checkoutPath = actionsUtil.getRequiredInput("checkout_path");
|
||||
const category = actionsUtil.getOptionalInput("category");
|
||||
|
||||
uploadResults = await postProcessAndUploadSarif(
|
||||
@@ -396,23 +388,18 @@ async function run({
|
||||
// Possibly upload the overlay-base database to actions cache.
|
||||
// Note: Take care with the ordering of this call since databases may be cleaned up
|
||||
// at the `overlay` level.
|
||||
await cleanupAndUploadOverlayBaseDatabaseToCache(
|
||||
codeql,
|
||||
config,
|
||||
logger,
|
||||
checkoutPath,
|
||||
);
|
||||
await cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger);
|
||||
|
||||
// Possibly upload the database bundles for remote queries.
|
||||
// Note: Take care with the ordering of this call since databases may be cleaned up
|
||||
// at the `overlay` or `clear` level.
|
||||
databaseUploadResults = await cleanupAndUploadDatabases(
|
||||
{ logger, features },
|
||||
repositoryNwo,
|
||||
codeql,
|
||||
config,
|
||||
apiDetails,
|
||||
checkoutPath,
|
||||
features,
|
||||
logger,
|
||||
);
|
||||
|
||||
// Possibly upload the TRAP caches for later re-use
|
||||
|
||||
+1
-1
@@ -7,12 +7,12 @@ import * as sinon from "sinon";
|
||||
import { CodeQuality, CodeScanning, RiskAssessment } from "./analyses";
|
||||
import {
|
||||
runQueries,
|
||||
defaultSuites,
|
||||
resolveQuerySuiteAlias,
|
||||
addSarifExtension,
|
||||
diffRangeExtensionPackContents,
|
||||
} from "./analyze";
|
||||
import { createStubCodeQL } from "./codeql";
|
||||
import { defaultSuites } from "./config/db-config";
|
||||
import { Feature } from "./feature-flags";
|
||||
import { BuiltInLanguage } from "./languages";
|
||||
import { getRunnerLogger } from "./logging";
|
||||
|
||||
+11
-3
@@ -5,11 +5,10 @@ import { performance } from "perf_hooks";
|
||||
import * as io from "@actions/io";
|
||||
import * as yaml from "js-yaml";
|
||||
|
||||
import { getTemporaryDirectory } from "./actions-util";
|
||||
import { getTemporaryDirectory, getRequiredInput } from "./actions-util";
|
||||
import * as analyses from "./analyses";
|
||||
import { setupCppAutobuild } from "./autobuild";
|
||||
import { type CodeQL } from "./codeql";
|
||||
import { defaultSuites } from "./config/db-config";
|
||||
import * as configUtils from "./config-utils";
|
||||
import {
|
||||
getCsharpTempDependencyDir,
|
||||
@@ -234,7 +233,6 @@ async function finalizeDatabaseCreation(
|
||||
*/
|
||||
export async function setupDiffInformedQueryRun(
|
||||
logger: Logger,
|
||||
checkoutPath: string,
|
||||
): Promise<string | undefined> {
|
||||
return await withGroupAsync(
|
||||
"Generating diff range extension pack",
|
||||
@@ -247,6 +245,7 @@ export async function setupDiffInformedQueryRun(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const checkoutPath = getRequiredInput("checkout_path");
|
||||
const packDir = writeDiffRangeDataExtensionPack(
|
||||
logger,
|
||||
diffRanges,
|
||||
@@ -358,6 +357,15 @@ dataExtensions:
|
||||
return diffRangeDir;
|
||||
}
|
||||
|
||||
// A set of default query suite names that are understood by the CLI.
|
||||
export const defaultSuites: Set<string> = new Set([
|
||||
"security-experimental",
|
||||
"security-extended",
|
||||
"security-and-quality",
|
||||
"code-quality",
|
||||
"code-scanning",
|
||||
]);
|
||||
|
||||
/**
|
||||
* If `maybeSuite` is the name of a default query suite, it is resolved into the corresponding
|
||||
* query suite name for the given `language`. Otherwise, `maybeSuite` is returned as is.
|
||||
|
||||
+87
-99
@@ -111,115 +111,103 @@ test.serial("getGitHubVersion for GHEC-DR", async (t) => {
|
||||
t.deepEqual({ type: util.GitHubVariant.GHEC_DR }, gheDotcom);
|
||||
});
|
||||
|
||||
test("wrapApiConfigurationError doesn't wrap errors it isn't supposed to", (t) => {
|
||||
const unwrappedErrors = [
|
||||
test.serial(
|
||||
"wrapApiConfigurationError correctly wraps specific configuration errors",
|
||||
(t) => {
|
||||
// We don't reclassify arbitrary errors
|
||||
new Error("arbitrary error"),
|
||||
// Same goes for arbitrary strings
|
||||
"arbitrary error",
|
||||
// If an HTTP error doesn't contain a specific error message, we don't wrap it.
|
||||
new util.HTTPError("arbitrary HTTP error", 456),
|
||||
];
|
||||
const arbitraryError = new Error("arbitrary error");
|
||||
let res = api.wrapApiConfigurationError(arbitraryError);
|
||||
t.is(res, arbitraryError);
|
||||
|
||||
for (const unwrappedError of unwrappedErrors) {
|
||||
const res = api.wrapApiConfigurationError(unwrappedError);
|
||||
t.is(
|
||||
// Same goes for arbitrary errors
|
||||
const configError = new util.ConfigurationError("arbitrary error");
|
||||
res = api.wrapApiConfigurationError(configError);
|
||||
t.is(res, configError);
|
||||
|
||||
// If an HTTP error doesn't contain a specific error message, we don't
|
||||
// wrap is an an API error.
|
||||
const httpError = new util.HTTPError("arbitrary HTTP error", 456);
|
||||
res = api.wrapApiConfigurationError(httpError);
|
||||
t.is(res, httpError);
|
||||
|
||||
// For other HTTP errors, we wrap them as Configuration errors if they contain
|
||||
// specific error messages.
|
||||
const httpNotFoundError = new util.HTTPError("commit not found", 404);
|
||||
res = api.wrapApiConfigurationError(httpNotFoundError);
|
||||
t.deepEqual(res, new util.ConfigurationError("commit not found"));
|
||||
|
||||
const refNotFoundError = new util.HTTPError(
|
||||
"ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest",
|
||||
404,
|
||||
);
|
||||
res = api.wrapApiConfigurationError(refNotFoundError);
|
||||
t.deepEqual(
|
||||
res,
|
||||
unwrappedError,
|
||||
`${util.getErrorMessage(unwrappedError)} should not be wrapped by wrapApiConfigurationError`,
|
||||
new util.ConfigurationError(
|
||||
"ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest",
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("wrapApiConfigurationError correctly wraps specific configuration errors", (t) => {
|
||||
// For other HTTP errors, we wrap them as Configuration errors if they contain
|
||||
// specific error messages.
|
||||
const httpNotFoundError = new util.HTTPError("commit not found", 404);
|
||||
const refNotFoundError = new util.HTTPError(
|
||||
"ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest",
|
||||
404,
|
||||
);
|
||||
const apiRateLimitError = new util.HTTPError(
|
||||
"API rate limit exceeded for installation",
|
||||
403,
|
||||
);
|
||||
const resourceNotAccessibleError = new util.HTTPError(
|
||||
"Resource not accessible by integration",
|
||||
403,
|
||||
);
|
||||
const errorsToWrap = [
|
||||
httpNotFoundError,
|
||||
refNotFoundError,
|
||||
apiRateLimitError,
|
||||
resourceNotAccessibleError,
|
||||
];
|
||||
const apiRateLimitError = new util.HTTPError(
|
||||
"API rate limit exceeded for installation",
|
||||
403,
|
||||
);
|
||||
res = api.wrapApiConfigurationError(apiRateLimitError);
|
||||
t.deepEqual(
|
||||
res,
|
||||
new util.ConfigurationError("API rate limit exceeded for installation"),
|
||||
);
|
||||
|
||||
for (const errorToWrap of errorsToWrap) {
|
||||
const res = api.wrapApiConfigurationError(errorToWrap);
|
||||
t.deepEqual(res, new util.ConfigurationError(errorToWrap.message));
|
||||
}
|
||||
});
|
||||
|
||||
test("wrapApiConfigurationError wraps token errors", async (t) => {
|
||||
const tokenSuggestionMessage =
|
||||
"Please check that your token is valid and has the required permissions: contents: read, security-events: write";
|
||||
const badCredentialsError = new util.HTTPError("Bad credentials", 401);
|
||||
const notFoundError = new util.HTTPError("Not Found", 404);
|
||||
const errorsToWrap = [badCredentialsError, notFoundError];
|
||||
|
||||
for (const errorToWrap of errorsToWrap) {
|
||||
const res = api.wrapApiConfigurationError(errorToWrap);
|
||||
const tokenSuggestionMessage =
|
||||
"Please check that your token is valid and has the required permissions: contents: read, security-events: write";
|
||||
const badCredentialsError = new util.HTTPError("Bad credentials", 401);
|
||||
res = api.wrapApiConfigurationError(badCredentialsError);
|
||||
t.deepEqual(res, new util.ConfigurationError(tokenSuggestionMessage));
|
||||
}
|
||||
});
|
||||
|
||||
test("wrapApiConfigurationError wraps enablement errors", async (t) => {
|
||||
// Enablement errors.
|
||||
const enablementErrorMessages = [
|
||||
"Code Security must be enabled for this repository to use code scanning",
|
||||
"Advanced Security must be enabled for this repository to use code scanning",
|
||||
"Code Scanning is not enabled for this repository. Please enable code scanning in the repository settings.",
|
||||
"Code quality is not enabled for this repository. Please enable code quality in the repository settings.",
|
||||
];
|
||||
const transforms = [
|
||||
(msg: string) => msg,
|
||||
(msg: string) => msg.toLowerCase(),
|
||||
(msg: string) => msg.toLocaleUpperCase(),
|
||||
];
|
||||
const notFoundError = new util.HTTPError("Not Found", 404);
|
||||
res = api.wrapApiConfigurationError(notFoundError);
|
||||
t.deepEqual(res, new util.ConfigurationError(tokenSuggestionMessage));
|
||||
|
||||
for (const enablementErrorMessage of enablementErrorMessages) {
|
||||
for (const transform of transforms) {
|
||||
const enablementError = new util.HTTPError(
|
||||
transform(enablementErrorMessage),
|
||||
403,
|
||||
);
|
||||
const res = api.wrapApiConfigurationError(enablementError);
|
||||
t.deepEqual(
|
||||
res,
|
||||
new util.ConfigurationError(
|
||||
api.getFeatureEnablementError(enablementError.message),
|
||||
),
|
||||
);
|
||||
const resourceNotAccessibleError = new util.HTTPError(
|
||||
"Resource not accessible by integration",
|
||||
403,
|
||||
);
|
||||
res = api.wrapApiConfigurationError(resourceNotAccessibleError);
|
||||
t.deepEqual(
|
||||
res,
|
||||
new util.ConfigurationError("Resource not accessible by integration"),
|
||||
);
|
||||
|
||||
// Enablement errors.
|
||||
const enablementErrorMessages = [
|
||||
"Code Security must be enabled for this repository to use code scanning",
|
||||
"Advanced Security must be enabled for this repository to use code scanning",
|
||||
"Code Scanning is not enabled for this repository. Please enable code scanning in the repository settings.",
|
||||
"Code quality is not enabled for this repository. Please enable code quality in the repository settings.",
|
||||
];
|
||||
const transforms = [
|
||||
(msg: string) => msg,
|
||||
(msg: string) => msg.toLowerCase(),
|
||||
(msg: string) => msg.toLocaleUpperCase(),
|
||||
];
|
||||
|
||||
for (const enablementErrorMessage of enablementErrorMessages) {
|
||||
for (const transform of transforms) {
|
||||
const enablementError = new util.HTTPError(
|
||||
transform(enablementErrorMessage),
|
||||
403,
|
||||
);
|
||||
res = api.wrapApiConfigurationError(enablementError);
|
||||
t.deepEqual(
|
||||
res,
|
||||
new util.ConfigurationError(
|
||||
api.getFeatureEnablementError(enablementError.message),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("wrapApiConfigurationError doesn't double-wrap errors", async (t) => {
|
||||
// This test checks that errors don't get wrapped a second time if `wrapApiConfigurationError`
|
||||
// is called on an error that was already wrapped by a previous call to `wrapApiConfigurationError`.
|
||||
// Start by calling `wrapApiConfigurationError` on an unwrapped error that should be wrapped:
|
||||
const unwrappedError = new util.HTTPError("commit not found", 404);
|
||||
const wrappedError = api.wrapApiConfigurationError(unwrappedError);
|
||||
|
||||
// Sanity-check that it was wrapped, as expected.
|
||||
t.deepEqual(
|
||||
wrappedError,
|
||||
new util.ConfigurationError(unwrappedError.message),
|
||||
);
|
||||
|
||||
// The result of the second call should be exactly `wrappedError`:
|
||||
t.is(api.wrapApiConfigurationError(wrappedError), wrappedError);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test("getRegistryProxy - returns undefined if the proxy is not configured", async (t) => {
|
||||
const target = callee(api.getRegistryProxy).withArgs();
|
||||
|
||||
+24
-35
@@ -1,5 +1,8 @@
|
||||
import * as core from "@actions/core";
|
||||
import * as githubUtils from "@actions/github/lib/utils";
|
||||
import { type Octokit } from "@octokit/core";
|
||||
import { type PaginateInterface } from "@octokit/plugin-paginate-rest";
|
||||
import { type Api } from "@octokit/plugin-rest-endpoint-methods";
|
||||
import * as retry from "@octokit/plugin-retry";
|
||||
import { RequestRequestOptions } from "@octokit/types";
|
||||
import {
|
||||
@@ -125,7 +128,7 @@ export function makeProxyRequestOptions(
|
||||
}
|
||||
|
||||
/** The type of GitHub API client we use. */
|
||||
export type ApiClient = InstanceType<typeof githubUtils.GitHub>;
|
||||
export type ApiClient = Octokit & Api & { paginate: PaginateInterface };
|
||||
|
||||
/** Options for `createApiClientWithDetails`. */
|
||||
interface CreateApiClientOptions {
|
||||
@@ -219,31 +222,25 @@ export async function getGitHubVersionFromApi(
|
||||
return { type: GitHubVariant.DOTCOM };
|
||||
}
|
||||
|
||||
try {
|
||||
// Doesn't strictly have to be the meta endpoint as we're only
|
||||
// using the response headers which are available on every request.
|
||||
//
|
||||
// See https://docs.github.com/en/rest/meta/meta#get-github-meta-information.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
const response = await apiClient.rest.meta.get();
|
||||
// Doesn't strictly have to be the meta endpoint as we're only
|
||||
// using the response headers which are available on every request.
|
||||
//
|
||||
// See https://docs.github.com/en/rest/meta/meta#get-github-meta-information.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
const response = await apiClient.rest.meta.get();
|
||||
|
||||
// This happens on dotcom, although we expect to have already returned in that
|
||||
// case. This can also serve as a fallback in cases we haven't foreseen.
|
||||
if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === undefined) {
|
||||
return { type: GitHubVariant.DOTCOM };
|
||||
}
|
||||
|
||||
if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === "ghe.com") {
|
||||
return { type: GitHubVariant.GHEC_DR };
|
||||
}
|
||||
|
||||
const version = response.headers[
|
||||
GITHUB_ENTERPRISE_VERSION_HEADER
|
||||
] as string;
|
||||
return { type: GitHubVariant.GHES, version };
|
||||
} catch (err) {
|
||||
throw wrapApiConfigurationError(err);
|
||||
// This happens on dotcom, although we expect to have already returned in that
|
||||
// case. This can also serve as a fallback in cases we haven't foreseen.
|
||||
if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === undefined) {
|
||||
return { type: GitHubVariant.DOTCOM };
|
||||
}
|
||||
|
||||
if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === "ghe.com") {
|
||||
return { type: GitHubVariant.GHEC_DR };
|
||||
}
|
||||
|
||||
const version = response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] as string;
|
||||
return { type: GitHubVariant.GHES, version };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -255,10 +252,9 @@ export async function getGitHubVersionFromApi(
|
||||
*/
|
||||
export async function getGitHubVersion(): Promise<GitHubVersion> {
|
||||
if (cachedGitHubVersion === undefined) {
|
||||
const apiDetails = getApiDetails();
|
||||
cachedGitHubVersion = await getGitHubVersionFromApi(
|
||||
createApiClientWithDetails(apiDetails),
|
||||
apiDetails,
|
||||
getApiClient(),
|
||||
getApiDetails(),
|
||||
);
|
||||
}
|
||||
return cachedGitHubVersion;
|
||||
@@ -421,14 +417,7 @@ export function getFeatureEnablementError(message: string): string {
|
||||
return `Please verify that the necessary features are enabled: ${message}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether `e` is a known error returned by the GitHub API that we should
|
||||
* classify as a `ConfigurationError`.
|
||||
*
|
||||
* @param e The error to classify.
|
||||
* @returns Either `e` or a corresponding `ConfigurationError`.
|
||||
*/
|
||||
export function wrapApiConfigurationError<T>(e: T): T | ConfigurationError {
|
||||
export function wrapApiConfigurationError(e: unknown) {
|
||||
const httpError = asHTTPError(e);
|
||||
if (httpError !== undefined) {
|
||||
if (
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"maximumVersion":"3.23","minimumVersion":"3.18"}
|
||||
{"maximumVersion": "3.22", "minimumVersion": "3.17"}
|
||||
|
||||
@@ -99,7 +99,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
|
||||
);
|
||||
}
|
||||
|
||||
const codeql = await getCodeQL(logger, config.codeQLCmd);
|
||||
const codeql = await getCodeQL(config.codeQLCmd);
|
||||
|
||||
languages = await determineAutobuildLanguages(codeql, config, logger);
|
||||
if (languages !== undefined) {
|
||||
|
||||
+1
-1
@@ -155,7 +155,7 @@ export async function runAutobuild(
|
||||
logger: Logger,
|
||||
) {
|
||||
logger.startGroup(`Attempting to automatically build ${language} code`);
|
||||
const codeQL = await getCodeQL(logger, config.codeQLCmd);
|
||||
const codeQL = await getCodeQL(config.codeQLCmd);
|
||||
if (language === BuiltInLanguage.cpp) {
|
||||
await setupCppAutobuild(codeQL, logger);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as core from "@actions/core";
|
||||
import { getOptionalInput, isDefaultSetup } from "./actions-util";
|
||||
import { EnvVar } from "./environment";
|
||||
import { Logger } from "./logging";
|
||||
import { looksLikeHostedRunner, tryGetFolderBytes } from "./util";
|
||||
import { isHostedRunner, tryGetFolderBytes } from "./util";
|
||||
|
||||
/**
|
||||
* Returns the total size of all the specified paths.
|
||||
@@ -109,7 +109,7 @@ export function getDependencyCachingEnabled(): CachingKind {
|
||||
if (dependencyCaching !== undefined) return getCachingKind(dependencyCaching);
|
||||
|
||||
// On self-hosted runners which may have dependencies installed centrally, disable caching by default
|
||||
if (!looksLikeHostedRunner()) return CachingKind.None;
|
||||
if (!isHostedRunner()) return CachingKind.None;
|
||||
|
||||
// Disable in advanced workflows by default.
|
||||
if (!isDefaultSetup()) return CachingKind.None;
|
||||
|
||||
+14
-27
@@ -128,6 +128,7 @@ test("CliError constructor with empty stderr", (t) => {
|
||||
|
||||
for (const [platform, arch] of [
|
||||
["weird_plat", "x64"],
|
||||
["linux", "arm64"],
|
||||
["win32", "arm64"],
|
||||
]) {
|
||||
test.serial(
|
||||
@@ -156,34 +157,20 @@ for (const [platform, arch] of [
|
||||
);
|
||||
}
|
||||
|
||||
for (const [platform, arch] of [
|
||||
["linux", "x64"],
|
||||
["linux", "arm64"],
|
||||
["win32", "x64"],
|
||||
["darwin", "x64"],
|
||||
["darwin", "arm64"],
|
||||
]) {
|
||||
test.serial(
|
||||
`wrapCliConfigurationError - ${platform}/${arch} supported`,
|
||||
(t) => {
|
||||
sinon.stub(process, "platform").value(platform);
|
||||
sinon.stub(process, "arch").value(arch);
|
||||
const commandError = new CommandInvocationError(
|
||||
"codeql",
|
||||
["version"],
|
||||
1,
|
||||
"Some error",
|
||||
);
|
||||
const cliError = new CliError(commandError);
|
||||
|
||||
const wrappedError = wrapCliConfigurationError(cliError);
|
||||
|
||||
// Should return the original error since the platform is supported, rather
|
||||
// than replacing it with the unsupported-platform ConfigurationError.
|
||||
t.is(wrappedError, cliError);
|
||||
},
|
||||
test("wrapCliConfigurationError - supported platform", (t) => {
|
||||
const commandError = new CommandInvocationError(
|
||||
"codeql",
|
||||
["version"],
|
||||
1,
|
||||
"Some error",
|
||||
);
|
||||
}
|
||||
const cliError = new CliError(commandError);
|
||||
|
||||
const wrappedError = wrapCliConfigurationError(cliError);
|
||||
|
||||
// Should return the original error since platform is supported
|
||||
t.is(wrappedError, cliError);
|
||||
});
|
||||
|
||||
test("wrapCliConfigurationError - autobuild error", (t) => {
|
||||
const commandError = new CommandInvocationError(
|
||||
|
||||
@@ -8,7 +8,6 @@ import { ConfigurationError } from "./util";
|
||||
|
||||
const SUPPORTED_PLATFORMS = [
|
||||
["linux", "x64"],
|
||||
["linux", "arm64"],
|
||||
["win32", "x64"],
|
||||
["darwin", "x64"],
|
||||
["darwin", "arm64"],
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
import * as fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import test from "ava";
|
||||
|
||||
import { getRunnerLogger } from "../logging";
|
||||
import { setupTests } from "../testing-utils";
|
||||
import * as util from "../util";
|
||||
|
||||
import { getCachedCodeQlVersion } from "./output-cache";
|
||||
|
||||
setupTests(test);
|
||||
|
||||
const logger = getRunnerLogger(true);
|
||||
|
||||
test.serial(
|
||||
"getCachedCodeQlVersion reuses a version persisted by an earlier step",
|
||||
async (t) => {
|
||||
await util.withTmpDir(async (tmpDir: string) => {
|
||||
const cacheFilePath = path.join(tmpDir, "cache.json");
|
||||
|
||||
fs.writeFileSync(
|
||||
cacheFilePath,
|
||||
JSON.stringify({
|
||||
cmd: "/path/to/codeql",
|
||||
entries: { version: { version: "2.20.0" } },
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
t.deepEqual(
|
||||
getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"),
|
||||
{
|
||||
version: "2.20.0",
|
||||
},
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test.serial(
|
||||
"getCachedCodeQlVersion ignores a persisted version from a different CLI",
|
||||
async (t) => {
|
||||
await util.withTmpDir(async (tmpDir: string) => {
|
||||
const cacheFilePath = path.join(tmpDir, "cache.json");
|
||||
fs.writeFileSync(
|
||||
cacheFilePath,
|
||||
JSON.stringify({
|
||||
cmd: "/path/to/other-codeql",
|
||||
entries: { version: { version: "2.20.0" } },
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
t.is(
|
||||
getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test.serial(
|
||||
"getCachedCodeQlVersion ignores a malformed persisted value",
|
||||
async (t) => {
|
||||
await util.withTmpDir(async (tmpDir: string) => {
|
||||
const cacheFilePath = path.join(tmpDir, "cache.json");
|
||||
fs.writeFileSync(cacheFilePath, "not valid json", "utf8");
|
||||
t.is(
|
||||
getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test.serial(
|
||||
"getCachedCodeQlVersion ignores a persisted value with the wrong structure",
|
||||
async (t) => {
|
||||
await util.withTmpDir(async (tmpDir: string) => {
|
||||
const cacheFilePath = path.join(tmpDir, "cache.json");
|
||||
const testValues = [
|
||||
{ cmd: "/path/to/codeql" },
|
||||
{ entries: { version: { version: "2.20.0" } } },
|
||||
{ cmd: "/path/to/codeql", entries: {} },
|
||||
{ cmd: "/path/to/codeql", entries: null },
|
||||
{ cmd: "/path/to/codeql", entries: { version: {} } },
|
||||
{ cmd: "/path/to/codeql", entries: { version: null } },
|
||||
{ cmd: "/path/to/codeql", entries: { version: "2.20.0" } },
|
||||
{ cmd: "/path/to/codeql", entries: { version: { version: null } } },
|
||||
{ cmd: "/path/to/codeql", entries: { version: { version: 2.2 } } },
|
||||
{ cmd: "/path/to/codeql", entries: { version: { version: 2 } } },
|
||||
{
|
||||
cmd: "/path/to/codeql",
|
||||
entries: { version: { version: "2.20.0", overlayVersion: "1" } },
|
||||
},
|
||||
{
|
||||
cmd: "/path/to/codeql",
|
||||
entries: { version: { version: "2.20.0", features: "nope" } },
|
||||
},
|
||||
].map((v) => JSON.stringify(v));
|
||||
|
||||
for (const value of testValues) {
|
||||
fs.writeFileSync(cacheFilePath, value, "utf8");
|
||||
t.is(
|
||||
getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"),
|
||||
undefined,
|
||||
value,
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test.serial("getCachedCodeQlVersion ignores non-existent file", async (t) => {
|
||||
await util.withTmpDir(async (tmpDir: string) => {
|
||||
const cacheFilePath = path.join(tmpDir, "cache.json");
|
||||
t.notThrows(() => {
|
||||
t.is(
|
||||
getCachedCodeQlVersion(logger, cacheFilePath, "/path/to/codeql"),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user