Compare commits

...

275 Commits

Author SHA1 Message Date
Michael B. Gale
bd015c2686 Ensure consistent apiDetails in getReleaseByVersion and getProxyBinaryPath 2026-10-14 13:54:39 +01:00
Michael B. Gale
8c32ebe976 Add InstanceApiClient and incorporate getAuthorizationHeaderFor into it 2026-10-14 13:54:38 +01:00
Michael B. Gale
e8380e65bd Include apiDetails in CodeQLDownloadSource 2026-10-14 13:54:38 +01:00
Michael B. Gale
5145363789 Pass apiDetails to getApiClient in uploadBundledDatabase 2026-10-14 13:54:38 +01:00
Michael B. Gale
26da964813 Use instance in DownloadSource and pass it on to getApiClient 2026-10-14 13:54:37 +01:00
Michael B. Gale
899eb844e5 Use DownloadSource for potentialDownloadSources 2026-10-14 13:54:37 +01:00
Michael B. Gale
b8990f74f6 Use "asset" in comment 2026-10-14 13:54:37 +01:00
Michael B. Gale
21ce56dffc Add and use RepositoryNwoStr type 2026-10-14 13:54:36 +01:00
Michael B. Gale
4a9e4edc72 Refactor getCodeQLBundleDownloadURL out of setup-codeql 2026-10-14 13:54:34 +01:00
Michael B. Gale
e4cda076ab Use ActionState for getCodeQLActionRepository 2026-10-14 13:53:36 +01:00
Michael B. Gale
1a9bda9528 Refactor getCodeQLActionRepository out of setup-codeql 2026-10-14 13:53:36 +01:00
Michael B. Gale
dedc55ad0e Add getDotcomApiDetails 2026-10-14 13:53:36 +01:00
Michael B. Gale
03f016a892 Add very basic getApiClientWithExternalAuth test 2026-10-14 13:53:35 +01:00
Michael B. Gale
6315034db1 Add very basic getApiClientWithExternalAuth test 2026-10-14 13:52:27 +01:00
Michael B. Gale
f4d1fd4519 Check token value in uploadBundledDatabase 2026-10-14 13:52:27 +01:00
Michael B. Gale
d6f4244c4b Check auth value in getAuthorizationHeaderFor
Also add some tests for it
2026-10-14 13:52:26 +01:00
Michael B. Gale
ccac407b4e Guard against blank auth value
This shouldn't be possible, but was previously handled by the library
2026-10-14 13:52:26 +01:00
Michael B. Gale
f09e27bdf4 Make externalRepoAuth check more consistent 2026-10-14 13:52:26 +01:00
Michael B. Gale
3ccff0b63b Use getCurrentInstance() 2026-10-14 13:52:25 +01:00
Michael B. Gale
8feed81de0 Make auth property on GitHubApiDetails optional 2026-10-14 13:52:25 +01:00
Michael B. Gale
1d407759fe Move GitHubApiDetails to github.ts 2026-10-14 13:52:25 +01:00
Michael B. Gale
a06da1322b Add functions to get the current and dotcom instance 2026-10-14 13:52:24 +01:00
Michael B. Gale
7538fa2081 Move some definitions out of util.ts into a new github.ts module 2026-10-14 13:52:24 +01:00
Michael B. Gale
752e8025e9 Improve GitHubApiDetails types and documentation 2026-10-14 13:52:24 +01:00
Henry Mercer
2b07ff4ed2 Merge pull request #4208 from github/dependabot/npm_and_yarn/octokit/plugin-paginate-rest-16.0.0
Bump @octokit/plugin-paginate-rest from 15.0.0 to 16.0.0
2026-10-14 10:22:18 +00:00
Henry Mercer
85944e0b34 Merge pull request #4234 from github/dependabot/npm_and_yarn/npm-minor-2d4d2c9463
Bump the npm-minor group across 1 directory with 7 updates
2026-10-14 10:21:43 +00:00
github-actions[bot]
25fe42ad78 Rebuild 2026-10-14 09:51:41 +00:00
dependabot[bot]
efdb69c1d7 Bump the npm-minor group across 1 directory with 7 updates
Bumps the npm-minor group with 7 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@actions/cache](https://github.com/actions/toolkit/tree/HEAD/packages/cache) | `5.2.0` | `5.3.0` |
| [follow-redirects](https://github.com/follow-redirects/follow-redirects) | `1.16.0` | `1.16.1` |
| [js-yaml](https://github.com/nodeca/js-yaml) | `5.4.2` | `5.4.3` |
| [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc) | `65.0.1` | `65.2.0` |
| [globals](https://github.com/sindresorhus/globals) | `17.12.0` | `17.13.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.70.1` | `8.71.1` |
| [mdast-util-from-markdown](https://github.com/syntax-tree/mdast-util-from-markdown) | `2.0.3` | `2.1.0` |



Updates `@actions/cache` from 5.2.0 to 5.3.0
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/cache/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/cache)

Updates `follow-redirects` from 1.16.0 to 1.16.1
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.16.0...v1.16.1)

Updates `js-yaml` from 5.4.2 to 5.4.3
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/5.4.2...5.4.3)

Updates `eslint-plugin-jsdoc` from 65.0.1 to 65.2.0
- [Release notes](https://github.com/gajus/eslint-plugin-jsdoc/releases)
- [Commits](https://github.com/gajus/eslint-plugin-jsdoc/compare/v65.0.1...v65.2.0)

Updates `globals` from 17.12.0 to 17.13.0
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v17.12.0...v17.13.0)

Updates `typescript-eslint` from 8.70.1 to 8.71.1
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.71.1/packages/typescript-eslint)

Updates `mdast-util-from-markdown` from 2.0.3 to 2.1.0
- [Release notes](https://github.com/syntax-tree/mdast-util-from-markdown/releases)
- [Commits](https://github.com/syntax-tree/mdast-util-from-markdown/compare/2.0.3...2.1.0)

---
updated-dependencies:
- dependency-name: "@actions/cache"
  dependency-version: 5.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-minor
- dependency-name: follow-redirects
  dependency-version: 1.16.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor
- dependency-name: js-yaml
  dependency-version: 5.4.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor
- dependency-name: eslint-plugin-jsdoc
  dependency-version: 65.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor
- dependency-name: globals
  dependency-version: 17.13.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor
- dependency-name: typescript-eslint
  dependency-version: 8.71.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor
- dependency-name: mdast-util-from-markdown
  dependency-version: 2.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-14 09:49:53 +00:00
Michael B. Gale
a5e9aebc25 Merge branch 'main' into dependabot/npm_and_yarn/octokit/plugin-paginate-rest-16.0.0 2026-10-14 10:45:53 +01:00
Michael B. Gale
eb94de7c5c Merge pull request #4225 from github/mbg/reduce-config-requirements
Store and restore "failed" configuration if `init` step aborts
2026-10-13 09:34:24 +00:00
Michael B. Gale
9645acc2ff Revert config === undefined condition 2026-10-12 22:54:47 +01:00
Michael B. Gale
6a9f7e7fc3 Log if returning early from recordOverlayStatus due to no languages 2026-10-12 22:50:11 +01:00
Michael B. Gale
67f44bc916 Use Logger for printDebugLogs and log when returning early 2026-10-12 22:48:21 +01:00
Michael B. Gale
26c6f91e6b Throw if aborted config functions are called incorrectly 2026-10-12 22:42:38 +01:00
Michael B. Gale
e3aeabd8f1 Fix example in comment 2026-10-12 22:40:25 +01:00
Michael B. Gale
be78e02f2d Fix comment 2026-10-12 22:39:34 +01:00
Michael B. Gale
bed4cc0475 Add log message for !config.dbLocation case 2026-10-12 22:39:08 +01:00
Michael B. Gale
ac8654a8f2 Add printDebugLogs tests 2026-10-12 13:08:08 +01:00
Michael B. Gale
ecfc96e0a9 Add getDisplayActionName tests 2026-10-12 13:08:01 +01:00
Michael B. Gale
409be01136 Replace deprecated functions in init-action.post.ts 2026-10-12 13:07:55 +01:00
Michael B. Gale
f4a15a13fd Try to load failed config if normal config is unavailable
Adapt relevant functions by narrowing their types or skipping steps that would otherwise have been skipped as well
2026-10-12 13:07:48 +01:00
Michael B. Gale
4fdbb71b54 Use runInActions for init-post 2026-10-12 13:07:38 +01:00
Michael B. Gale
5136039854 Store partial configuration when init is aborted 2026-10-12 13:07:36 +01:00
Michael B. Gale
19445ddfed Reduce Config requirements for tryUploadSarifIfRunFailed 2026-10-12 13:07:13 +01:00
Michael B. Gale
317f264e1f Change diagnosticsExport to not require full Config 2026-10-12 13:07:06 +01:00
Michael B. Gale
309f6af89b Change getGeneratedCodeScanningConfigPath to not require full Config 2026-10-12 13:06:59 +01:00
Michael B. Gale
cf8f7b9787 Add ActionConfig type 2026-10-12 13:06:43 +01:00
Henry Mercer
0db2f2b4a5 Merge pull request #4205 from github/henrymercer/require-codeql-2-20-7
Bump minimum CodeQL CLI version to 2.20.7
2026-10-12 10:04:43 +00:00
Henry Mercer
ae96eed5bb Merge remote-tracking branch 'origin/main' into henrymercer/require-codeql-2-20-7
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-12 10:11:02 +01:00
Mario Campos
e4e9b269fe Merge pull request #4211 from github/mario-campos/document-changenotes
Document change-notes process
2026-10-09 23:05:41 +00:00
Michael B. Gale
6e7fe2e990 Merge pull request #4220 from github/mbg/fix-action-state-type-inference
Fix type inference for `ActionState`
2026-10-09 22:31:18 +00:00
Mario Campos
fa56eef12f Delete unnecessary filename/frontmatter validation instructions 2026-10-09 16:48:00 -05:00
Michael B. Gale
71f2680f85 Merge pull request #4209 from github/dependabot/npm_and_yarn/eslint-plugin-jsdoc-65.0.1
Bump eslint-plugin-jsdoc from 64.5.4 to 65.0.1
2026-10-09 17:59:37 +00:00
Michael B. Gale
3b399fec34 Merge branch 'main' into dependabot/npm_and_yarn/eslint-plugin-jsdoc-65.0.1 2026-10-09 18:47:49 +01:00
Mario Campos
5532d8e11e Merge pull request #4218 from github/mario-campos/loosen-changenote-validation
Do not validate change-note file names or frontmatter
2026-10-09 17:45:19 +00:00
Michael B. Gale
68f5b579fa Merge pull request #4212 from github/mbg/tests/fix-export-variable-2
Do not use `core.exportVariable` in unit tests (2nd attempt)
2026-10-09 17:38:52 +00:00
Mario Campos
45cda5b577 Delete unused path import 2026-10-09 08:57:09 -05:00
Michael B. Gale
e57c0e65dd Fix type inference for ActionState 2026-10-09 14:21:47 +01:00
Mario Campos
1ced68ed2f Do not validate change-note file names or frontmatter
Presently, the strict filename or frontmatter are not being used; so we're validating them unnecessarily. So, for now, remove these checks until we decide to either do something with them, or delete the code entirely.
2026-10-08 15:11:43 -05:00
Mario Campos
13b1321685 Refine misc. wording of unreleased-change-notes/README.md
Co-authored-by: Michael B. Gale <mbg@github.com>
2026-10-08 15:01:05 -05:00
Mario Campos
cc826bb8e3 Delete unnecessary guidance for change-note body 2026-10-08 14:57:03 -05:00
Mario Campos
40d76bc727 Use actual CHANGELOG.md entries for example change-note 2026-10-08 14:55:23 -05:00
Michael B. Gale
bd97dda6bf Add and use __CODEQL_ACTION_TEST_ENV__ in tests 2026-10-08 20:23:37 +01:00
Michael B. Gale
d6196d8703 Rename exportVariable wrapper to exportEnvVar 2026-10-08 20:06:51 +01:00
Mario Campos
3acc10a2ce Exclude README.md from change-note validation and assembly 2026-10-08 12:53:37 -05:00
Mario Campos
2a935ca93d Move change-note documentation to unreleased-change-notes/README.md 2026-10-08 12:48:24 -05:00
Mads Navntoft
5aa5056e2d Merge pull request #4215 from github/mergeback/v4.38.3-to-main-24c54180
Mergeback v4.38.3 refs/heads/releases/v4 into main
2026-10-08 13:58:42 +00:00
Henry Mercer
768784f193 Merge branch 'main' into henrymercer/require-codeql-2-20-7 2026-10-08 14:29:21 +01:00
github-actions[bot]
ea60dc6408 Rebuild 2026-10-08 13:01:10 +00:00
github-actions[bot]
ce3f825b1d Update changelog and version after v4.38.3 2026-10-08 13:01:02 +00:00
Mads Navntoft
24c54180a6 Merge pull request #4214 from github/update-v4.38.3-e0b52dbdc
Merge main into releases/v4
2026-10-08 14:59:30 +02:00
Henry Mercer
69e87c56c1 Add changelog note for #4184 2026-10-08 13:42:32 +01:00
github-actions[bot]
23b682830b Update changelog for v4.38.3 2026-10-08 12:02:08 +00:00
Mario Campos
38fee79b02 Specify allowed characters in change-note filename 2026-10-07 15:21:38 -05:00
Michael B. Gale
ebd711ff66 Deprecate isInTestMode in favour of a more clearly named method 2026-10-07 20:12:01 +01:00
Michael B. Gale
75ea4cb2e4 Add NODE_ENV as safe environment variable 2026-10-07 20:12:01 +01:00
Michael B. Gale
59ff83ecef Add basic eslint enforcement 2026-10-07 20:12:01 +01:00
Michael B. Gale
1728f0c676 Add wrapper around core.exportVariable 2026-10-07 20:12:00 +01:00
Michael B. Gale
63c5299790 Move isInTestMode to environment.ts 2026-10-07 20:12:00 +01:00
Henry Mercer
e0b52dbdc5 Merge pull request #4210 from github/henrymercer/pin-python-for-older-clis-in-ci
Pin Python 3.13.15 for older CLI versions in the multi-language check
2026-10-07 18:12:41 +00:00
Mario Campos
39f1b3fa8d Document change-notes process 2026-10-07 13:11:34 -05:00
Henry Mercer
6b99698c8c Pin Python 3.13.15 for older CLI versions in multi-language check
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 18:58:17 +01:00
dependabot[bot]
d5b1e793ce Bump eslint-plugin-jsdoc from 64.5.4 to 65.0.1
Bumps [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc) from 64.5.4 to 65.0.1.
- [Release notes](https://github.com/gajus/eslint-plugin-jsdoc/releases)
- [Commits](https://github.com/gajus/eslint-plugin-jsdoc/compare/v64.5.4...v65.0.1)

---
updated-dependencies:
- dependency-name: eslint-plugin-jsdoc
  dependency-version: 65.0.1
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-07 17:55:31 +00:00
dependabot[bot]
a36029cea2 Bump @octokit/plugin-paginate-rest from 15.0.0 to 16.0.0
Bumps [@octokit/plugin-paginate-rest](https://github.com/octokit/plugin-paginate-rest.js) from 15.0.0 to 16.0.0.
- [Release notes](https://github.com/octokit/plugin-paginate-rest.js/releases)
- [Commits](https://github.com/octokit/plugin-paginate-rest.js/compare/v15.0.0...v16.0.0)

---
updated-dependencies:
- dependency-name: "@octokit/plugin-paginate-rest"
  dependency-version: 16.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-07 17:55:12 +00:00
Henry Mercer
5d90bea8a6 Add PR number to changelog entry and list it first
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:44:12 +01:00
Henry Mercer
8e7104f197 Clarify the oldest-version comment in the Rust PR check
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:41:20 +01:00
Henry Mercer
0b5c1fb069 Remove redundant CLI version requirement from CppDependencyInstallation
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:41:15 +01:00
Henry Mercer
a8c7110b26 Remove unreachable minimum version check for Rust analysis
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:41:09 +01:00
Henry Mercer
3c1b1b65a3 Remove CodeQL version check from debug artifact upload
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:41:03 +01:00
Henry Mercer
10e415aae1 Remove Kotlin version limit workaround for CodeQL CLI 2.20.3
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:40:58 +01:00
Henry Mercer
b97fbb3711 Remove CODEQL_PROXY_* workaround for CLIs older than 2.20.7
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:40:52 +01:00
Henry Mercer
17e7897d6c Add CodeQL 2.25.6 to the PR check matrix
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:40:49 +01:00
Henry Mercer
74aeac99e7 Stop testing CodeQL versions older than 2.20.7 in PR checks
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:40:46 +01:00
Henry Mercer
05d28f2f71 Bump version to 4.39.0
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:40:38 +01:00
Henry Mercer
772ffcd999 Bump minimum CodeQL CLI version to 2.20.7
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-07 14:40:35 +01:00
Mads Navntoft
63d3d632fc Merge pull request #4203 from github/update-bundle/codeql-bundle-v2.27.2
Update default bundle to 2.27.2
2026-10-07 10:00:42 +00:00
github-actions[bot]
7377a10091 Add changelog note 2026-10-07 09:39:57 +00:00
github-actions[bot]
c1a30cda11 Update default bundle to codeql-bundle-v2.27.2 2026-10-07 09:39:50 +00:00
Michael B. Gale
d208ec71e3 Merge pull request #4200 from github/mbg/esm/migrate-pr-checks
Fully migrate `pr-checks` to ESM
2026-10-06 19:24:52 +00:00
Michael B. Gale
a71b0c6684 Replace __dirname in sync.ts 2026-10-06 18:29:58 +01:00
Michael B. Gale
0a44f18dc2 Remove .mts patterns from configurations 2026-10-06 18:28:44 +01:00
Michael B. Gale
0f3412f832 Replace .mts with .ts in comments and workflows 2026-10-06 18:28:05 +01:00
Michael B. Gale
a2374c3d1c Replace __dirname in sync-back.ts 2026-10-06 18:23:42 +01:00
Michael B. Gale
4c932d9948 Replace .mts extensions 2026-10-06 18:21:35 +01:00
Michael B. Gale
1b38bb12c6 Set type: module for pr-checks 2026-10-06 18:19:33 +01:00
Michael B. Gale
f5b4c32a4e Replace require check with import.meta.main 2026-10-06 18:19:20 +01:00
Michael B. Gale
b813f91953 Add compatibility definitions to config.ts 2026-10-06 18:16:25 +01:00
Michael B. Gale
4c98a0bfb7 Add nvmrc for pr-checks 2026-10-06 18:03:52 +01:00
Michael B. Gale
36f377b9f2 Bump @types/node to v24 for pr-checks
All scripts in `pr-checks` are run with Node24
2026-10-06 18:03:20 +01:00
Michael B. Gale
f455295c9b Merge pull request #4169 from github/mbg/improve-release-workflow
Improve job naming for the release workflow
2026-10-06 16:15:00 +00:00
Henry Mercer
7265309f7a Merge pull request #4188 from github/update-supported-enterprise-server-versions
Update supported GitHub Enterprise Server versions
2026-10-06 14:45:57 +00:00
Henry Mercer
d1ca36fda6 Update CHANGELOG.md
Co-authored-by: Michael B. Gale <mbg@github.com>
2026-10-06 14:09:40 +01:00
Henry Mercer
2c8d410c03 Merge pull request #4184 from github/henrymercer/per-language-pr-check-failures
Use the combined bundle when queries may need other languages' library packs
2026-10-06 12:06:49 +00:00
Henry Mercer
118af5959a Remove unsupported GHES versions from compatibility table
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 17:57:06 +01:00
Henry Mercer
61c3b54338 Update CodeQL deprecation warning for GHES 3.17
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 17:55:31 +01:00
Henry Mercer
12db63b222 Explain why the config input test compares with a separate object
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:02 +01:00
Henry Mercer
55e4091e2b Describe what parseUserConfig accepts, returns and throws more precisely
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:02 +01:00
Henry Mercer
8e6b600bd0 Compare originalUserInput with a separate object in the config input test
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:01 +01:00
Henry Mercer
9d3242ebc0 Say that parseUserConfig's pathInput may not be a file path
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:01 +01:00
Henry Mercer
e0b8480262 Parse the config input in init without the parseConfigInput wrapper
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:01 +01:00
Henry Mercer
6cb83faca6 Construct UserConfig objects directly in the config-utils tests
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:01 +01:00
Henry Mercer
a4a04dc476 Explain that the config input is written to disk without merging
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:01 +01:00
Henry Mercer
966f3c3593 Say that the Default Setup config schema reflects what Default Setup is known to send
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:01 +01:00
Henry Mercer
711f3bffae Remove the checkDefaultSetupConfig wrapper around checkSchema
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:01 +01:00
Henry Mercer
ac4b9b891d Return early from parseQueriesFromInput when there are no queries
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:00 +01:00
Henry Mercer
c1e7769cf5 Reword the JSDoc for parseQueriesFromInput
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-05 14:24:00 +01:00
Henry Mercer
1767808e11 Merge pull request #4196 from github/dependabot/github_actions/dot-github/workflows/actions-minor-e631a66382
Bump ruby/setup-ruby from 1.326.0 to 1.327.0 in /.github/workflows in the actions-minor group across 1 directory
2026-10-05 10:37:35 +00:00
Michael B. Gale
aeafd00d94 Merge pull request #4197 from github/mbg/vscode/workspace-improvements
Minor VSCode workspace settings changes
2026-10-05 10:32:44 +00:00
Michael B. Gale
363d874905 Exclude "tests" folder from workspace 2026-10-05 11:11:58 +01:00
Michael B. Gale
fa90489493 Replace deprecated config key 2026-10-05 11:08:19 +01:00
Henry Mercer
d8251b8572 Merge pull request #4191 from github/henrymercer/ci-job-failure-investigation
Fix merge conflict handling in the rebuild workflow
2026-10-05 09:46:01 +00:00
Michael B. Gale
b6d38e563b Merge pull request #4192 from github/mbg/project-changes
Check `package-lock.json` for wrong addresses
2026-10-02 17:50:29 +00:00
Michael B. Gale
b948c4d91e Normalise feed URLs in package-lock.json 2026-10-02 18:38:04 +01:00
Michael B. Gale
894842692f Install newer npm in Node 20 workflows 2026-10-02 18:31:31 +01:00
Michael B. Gale
62b0dd96ff Add check for non-public feed URLs 2026-10-02 18:31:30 +01:00
Henry Mercer
c275b4a69e Merge branch 'main' into henrymercer/per-language-pr-check-failures 2026-10-02 17:53:12 +01:00
github-actions[bot]
4d9cd8c21b Rebuild 2026-10-02 16:50:10 +00:00
dependabot[bot]
412197a0f3 Bump ruby/setup-ruby
Bumps the actions-minor group with 1 update in the /.github/workflows directory: [ruby/setup-ruby](https://github.com/ruby/setup-ruby).


Updates `ruby/setup-ruby` from 1.326.0 to 1.327.0
- [Release notes](https://github.com/ruby/setup-ruby/releases)
- [Changelog](https://github.com/ruby/setup-ruby/blob/master/release.rb)
- [Commits](762794c140...14594264cd)

---
updated-dependencies:
- dependency-name: ruby/setup-ruby
  dependency-version: 1.327.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-02 16:48:21 +00:00
Michael B. Gale
0cd78b35d9 Merge pull request #4194 from github/mbg/dependency/downgrade-cache
Downgrade `@actions/cache` for now
2026-10-02 16:31:11 +00:00
Michael B. Gale
c26ee0ca71 Merge pull request #4193 from github/mbg/dependabot/uniform-cooldown
Dependabot: Apply `cooldown` uniformly
2026-10-02 16:30:54 +00:00
Michael B. Gale
6ce88f6aaf Downgrade @actions/cache 2026-10-02 17:17:40 +01:00
Michael B. Gale
1f8080af29 Add min-release-age=7 to .npmrc 2026-10-02 17:12:09 +01:00
Henry Mercer
56b0d5f02c Fix the rebuild workflow failing when merging the base branch conflicts
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-02 17:11:55 +01:00
Michael B. Gale
b804ae96cc Dependabot: Apply cooldown uniformly
Remove exceptions for Actions dependencies
2026-10-02 17:09:26 +01:00
copilot-swe-agent[bot]
a47cc9ff16 Merge remote-tracking branch 'origin/main' into henrymercer/per-language-pr-check-failures
# Conflicts:
#	lib/entry-points.js

Co-authored-by: henrymercer <14129055+henrymercer@users.noreply.github.com>
2026-10-02 15:36:15 +00:00
Henry Mercer
27c60c532d Fix detection of merge conflicts outside lib in the rebuild workflow
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-02 16:06:06 +01:00
Michael B. Gale
c535168544 Merge pull request #4189 from github/dependabot/npm_and_yarn/brace-expansion-1.1.21
Bump brace-expansion from 1.1.18 to 1.1.21
2026-10-02 14:21:51 +00:00
Michael B. Gale
488027b53c Update comment 2026-10-02 15:11:42 +01:00
Michael B. Gale
dc1f3ac122 Merge remote-tracking branch 'origin/main' into mbg/improve-release-workflow 2026-10-02 15:10:36 +01:00
Michael B. Gale
05d2a1a6fb Trigger workflows 2026-10-02 15:09:03 +01:00
Henry Mercer
f6a7f00613 Point to the Default Setup config schema from the per-language bundle check
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-02 14:42:42 +01:00
Henry Mercer
113b18e688 Parse the config input once
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-02 14:42:42 +01:00
Henry Mercer
e869836b5a Share the check of the properties that Default Setup sets in the config input
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-02 14:24:04 +01:00
Henry Mercer
1c0814d7d2 Parse lists of queries with a single function
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-02 14:22:24 +01:00
Henry Mercer
ce28f3e445 Explain why the file baseline PR check uses the combined bundle
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-02 13:53:53 +01:00
Michael B. Gale
f24d88130e Merge pull request #4183 from github/dependabot/github_actions/dot-github/workflows/actions-minor-f389ef8e3c
Bump ruby/setup-ruby from 1.323.0 to 1.326.0 in /.github/workflows in the actions-minor group across 1 directory
2026-10-02 12:19:56 +00:00
Michael B. Gale
f45aab1a23 Trigger workflows 2026-10-02 13:08:36 +01:00
github-actions[bot]
d036b81d95 Rebuild 2026-10-02 09:57:43 +00:00
dependabot[bot]
f306a93590 Bump brace-expansion from 1.1.18 to 1.1.21
Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 1.1.18 to 1.1.21.
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.18...v1.1.21)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.21
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-02 09:55:58 +00:00
Michael B. Gale
ffc4a0cd10 Merge pull request #4182 from github/dependabot/npm_and_yarn/npm-minor-e4df014d00
Bump the npm-minor group across 1 directory with 4 updates
2026-10-02 09:41:59 +00:00
github-actions[bot]
d06baaa128 Update supported GitHub Enterprise Server versions 2026-10-02 00:27:53 +00:00
Henry Mercer
a6cd2a544a Check what the config input sets instead of exempting dynamic workflows
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-01 18:10:03 +01:00
Henry Mercer
1bb99cb5c7 Explain what a reason to use the combined bundle means where it's checked
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-01 17:59:09 +01:00
Henry Mercer
725421c272 Explain that the config input can configure queries
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-01 17:59:09 +01:00
Henry Mercer
70897a78fe Reuse the parsing of query inputs when choosing a bundle
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-01 17:59:08 +01:00
Henry Mercer
a4fbe39872 Extract parsing of the queries input and the extra queries repository property
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-01 17:59:08 +01:00
Henry Mercer
a98f604084 Read the config and queries inputs once in init
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-01 17:44:31 +01:00
Henry Mercer
2da0d298e0 Omit the feature flag name from the per-language bundle debug log
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-01 12:00:27 +01:00
Henry Mercer
87a1923fea Use a new feature flag for per-language bundles
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-10-01 11:48:55 +01:00
github-actions[bot]
222d54a705 Rebuild 2026-09-30 17:57:51 +00:00
dependabot[bot]
cbe61e2f00 Bump ruby/setup-ruby
Bumps the actions-minor group with 1 update in the /.github/workflows directory: [ruby/setup-ruby](https://github.com/ruby/setup-ruby).


Updates `ruby/setup-ruby` from 1.323.0 to 1.326.0
- [Release notes](https://github.com/ruby/setup-ruby/releases)
- [Changelog](https://github.com/ruby/setup-ruby/blob/master/release.rb)
- [Commits](984c0c8908...762794c140)

---
updated-dependencies:
- dependency-name: ruby/setup-ruby
  dependency-version: 1.326.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-30 17:56:03 +00:00
github-actions[bot]
f1b8b0f7b3 Rebuild 2026-09-30 17:55:56 +00:00
dependabot[bot]
99522b4961 Bump the npm-minor group across 1 directory with 4 updates
Bumps the npm-minor group with 4 updates in the / directory: [@actions/cache](https://github.com/actions/toolkit/tree/HEAD/packages/cache), [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc), [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) and [tsx](https://github.com/privatenumber/tsx).


Updates `@actions/cache` from 5.2.0 to 5.3.0
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/cache/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/cache)

Updates `eslint-plugin-jsdoc` from 64.5.2 to 64.5.4
- [Release notes](https://github.com/gajus/eslint-plugin-jsdoc/releases)
- [Commits](https://github.com/gajus/eslint-plugin-jsdoc/compare/v64.5.2...v64.5.4)

Updates `typescript-eslint` from 8.70.0 to 8.70.1
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.70.1/packages/typescript-eslint)

Updates `tsx` from 4.23.13 to 4.23.15
- [Release notes](https://github.com/privatenumber/tsx/releases)
- [Changelog](https://github.com/privatenumber/tsx/blob/master/release.config.cjs)
- [Commits](https://github.com/privatenumber/tsx/compare/v4.23.13...v4.23.15)

---
updated-dependencies:
- dependency-name: "@actions/cache"
  dependency-version: 5.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-minor
- dependency-name: eslint-plugin-jsdoc
  dependency-version: 64.5.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor
- dependency-name: typescript-eslint
  dependency-version: 8.70.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor
- dependency-name: tsx
  dependency-version: 4.23.15
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-30 17:54:15 +00:00
Henry Mercer
7816c33354 Fix the docs for the languages and analysis-kinds inputs of setup-codeql
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-30 16:21:00 +01:00
Henry Mercer
d8b6f2a09b Always use the combined bundle in setup-codeql
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-30 15:50:56 +01:00
Henry Mercer
1609a51ab7 Avoid per-language bundles when queries may need other languages' library packs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-30 15:50:55 +01:00
Henry Mercer
5e3132db95 Move defaultSuites to config/db-config.ts
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-29 19:32:48 +01:00
Henry Mercer
b5a476b47f Disable per-language bundles in the file baseline PR check
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-29 19:31:48 +01:00
Michael B. Gale
61817fadad Merge pull request #4181 from github/mbg/start-proxy/linux-arm64
Support `linux-arm64` assets in `start-proxy`
2026-09-29 17:31:06 +00:00
Michael B. Gale
cd1a7c16f0 Use test tags in rollback-release.yml workflow 2026-09-29 17:03:57 +01:00
Michael B. Gale
8e838ff396 Add tests 2026-09-29 16:02:55 +01:00
Michael B. Gale
10e476ce02 Fix values used in log message 2026-09-29 16:02:49 +01:00
Michael B. Gale
fc2d2f7d2d Make ActionState available to getDownloadUrl 2026-09-28 19:33:02 +01:00
Michael B. Gale
62a2268b34 Use getBundlePlatform in getDownloadUrl 2026-09-28 19:18:38 +01:00
Michael B. Gale
97a91d9861 Make platform+arch available in BaseState 2026-09-28 19:18:37 +01:00
Michael B. Gale
85c0c095cb Merge pull request #4178 from github/mbg/use-api-error-classification-more
Use `wrapApiConfigurationError` more for `init-action-post`
2026-09-28 15:26:45 +00:00
Michael B. Gale
503e2f62a9 Add test for repeated wrapApiConfigurationError 2026-09-28 10:38:14 +01:00
Michael B. Gale
260cb2adcf Break up wrapApiConfigurationError tests 2026-09-28 10:20:27 +01:00
Michael B. Gale
31252c2639 Change wrapApiConfigurationError to not be serial 2026-09-28 10:11:34 +01:00
Michael B. Gale
1991d2001e Use wrapApiConfigurationError in init-action-post error handler 2026-09-25 18:21:45 +01:00
Michael B. Gale
0af3281195 Use gitHubVersion from config if available in init-action-post 2026-09-25 18:17:29 +01:00
Michael B. Gale
8dfe937b99 Use wrapApiConfigurationError for getGitHubVersionFromApi 2026-09-25 18:14:47 +01:00
Michael B. Gale
8102666a8c Improve return type for wrapApiConfigurationError and add docs 2026-09-25 18:12:23 +01:00
Michael B. Gale
7b6a151fb5 Merge pull request #4177 from github/mbg/version-check/recommend-dependabot-grouping
Point at Dependabot `groups` docs in version mismatch error
2026-09-25 15:14:03 +00:00
Michael B. Gale
29b01b6799 Point at Dependabot groups docs in version mismatch error 2026-09-25 15:59:36 +01:00
Michael B. Gale
fa2bea7c7a Merge pull request #4176 from github/mbg/start-proxy/improve-post-githubversion-logic
Remove unnecessary check in `start-proxy-action-post`
2026-09-25 14:39:40 +00:00
Michael B. Gale
9fb2fa5f46 Avoid duplicate getApiDetails in getGitHubVersion 2026-09-25 15:02:13 +01:00
Michael B. Gale
054b25e1c2 Remove unnecessary config check 2026-09-25 14:58:43 +01:00
Michael B. Gale
fa8392b7e5 Merge pull request #4161 from github/mbg/improve-json-failures
Add context to JSON parse errors
2026-09-24 11:18:23 +00:00
Michael B. Gale
38c1d74ffa Merge remote-tracking branch 'origin/main' into mbg/improve-json-failures 2026-09-24 12:06:30 +01:00
Michael B. Gale
19aa55de51 Log error in getTracerConfigForCluster instead of re-throwing it 2026-09-24 12:06:01 +01:00
Michael B. Gale
a7334dd080 Merge pull request #4170 from github/mergeback/v4.38.2-to-main-2892aa5e
Mergeback v4.38.2 refs/heads/releases/v4 into main
2026-09-24 10:45:39 +00:00
Michael B. Gale
aa2cb993a1 Merge remote-tracking branch 'origin/main' into mbg/improve-json-failures 2026-09-24 11:42:41 +01:00
Henry Mercer
9c970806c4 Merge pull request #4167 from github/henrymercer/move-bundle-helpers
Move bundle types and helpers out of setup-codeql.ts
2026-09-24 10:40:36 +00:00
Michael B. Gale
415d925fee Fix formatting of mergeback checklist 2026-09-24 11:36:37 +01:00
Michael B. Gale
b5f938c947 Log error in restoreInputs instead of re-throwing it 2026-09-24 11:34:56 +01:00
github-actions[bot]
73dc34459c Rebuild 2026-09-24 10:28:01 +00:00
github-actions[bot]
266e866100 Update changelog and version after v4.38.2 2026-09-24 10:27:53 +00:00
Michael B. Gale
2892aa5e19 Merge pull request #4168 from github/update-v4.38.2-a6ef2c96f
Merge main into releases/v4
2026-09-24 11:26:28 +01:00
Michael B. Gale
8ad03a333e Trigger workflows 2026-09-24 11:15:21 +01:00
Michael B. Gale
b435ce4361 Disambiguate "Prepare release" job naming 2026-09-24 11:12:09 +01:00
Michael B. Gale
477ba697e3 Name unnamed jobs in release workflow 2026-09-24 11:09:45 +01:00
github-actions[bot]
98af865db5 Update changelog for v4.38.2 2026-09-24 10:01:43 +00:00
Henry Mercer
6aa6d5553a Remove the getCodeQLBundleName wrapper from setup-codeql.ts
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-24 10:09:24 +01:00
Henry Mercer
f42df5b5c1 Move bundle types and helpers out of setup-codeql.ts
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-24 09:52:32 +01:00
Michael B. Gale
a6ef2c96fc Merge pull request #4156 from github/mario-campos/fix-validate-cmd
Fix path-resolution bug in `changenotes.mts validate` by using `getChangenotes`
2026-09-24 08:16:09 +00:00
Michael B. Gale
1ef28a1b76 Merge pull request #4166 from github/dependabot/github_actions/dot-github/workflows/actions-minor-4c9e3e8b22
Bump ruby/setup-ruby from 1.321.0 to 1.323.0 in /.github/workflows in the actions-minor group across 1 directory
2026-09-24 08:02:30 +00:00
Michael B. Gale
26cb08bab0 Merge pull request #4163 from github/mbg/fix-getCommitOid-stubs
Fix `getCommitOid` stubs
2026-09-24 07:07:29 +00:00
Michael B. Gale
f035ce3a98 Merge pull request #4165 from github/dependabot/npm_and_yarn/npm-minor-8eaed9c323
Bump the npm-minor group across 1 directory with 3 updates
2026-09-23 18:11:21 +00:00
github-actions[bot]
5e4e2550b4 Rebuild 2026-09-23 17:57:57 +00:00
dependabot[bot]
b13f5f47d5 Bump ruby/setup-ruby
Bumps the actions-minor group with 1 update in the /.github/workflows directory: [ruby/setup-ruby](https://github.com/ruby/setup-ruby).


Updates `ruby/setup-ruby` from 1.321.0 to 1.323.0
- [Release notes](https://github.com/ruby/setup-ruby/releases)
- [Changelog](https://github.com/ruby/setup-ruby/blob/master/release.rb)
- [Commits](95ef2b042f...984c0c8908)

---
updated-dependencies:
- dependency-name: ruby/setup-ruby
  dependency-version: 1.323.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-23 17:56:05 +00:00
github-actions[bot]
c87fe5756c Rebuild 2026-09-23 17:55:50 +00:00
dependabot[bot]
becb485c9f Bump the npm-minor group across 1 directory with 3 updates
Bumps the npm-minor group with 3 updates in the / directory: [js-yaml](https://github.com/nodeca/js-yaml), [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc) and [yaml](https://github.com/eemeli/yaml).


Updates `js-yaml` from 5.4.1 to 5.4.2
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/5.4.1...5.4.2)

Updates `eslint-plugin-jsdoc` from 64.3.8 to 64.5.2
- [Release notes](https://github.com/gajus/eslint-plugin-jsdoc/releases)
- [Commits](https://github.com/gajus/eslint-plugin-jsdoc/compare/v64.3.8...v64.5.2)

Updates `yaml` from 2.9.0 to 2.9.1
- [Release notes](https://github.com/eemeli/yaml/releases)
- [Commits](https://github.com/eemeli/yaml/compare/v2.9.0...v2.9.1)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 5.4.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor
- dependency-name: eslint-plugin-jsdoc
  dependency-version: 64.5.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor
- dependency-name: yaml
  dependency-version: 2.9.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-23 17:54:02 +00:00
Michael B. Gale
42277414c7 Stub getCommitOid correctly and check calls 2026-09-23 13:38:53 +01:00
Michael B. Gale
9c9e4b034d Fix getCommitOid stubs 2026-09-23 13:31:48 +01:00
Michael B. Gale
f0064b219d Merge pull request #4162 from github/mbg/cli/disable-perfdata
Disable `UsePerfData` for `resolveExtractor`
2026-09-23 12:17:25 +00:00
Michael B. Gale
9691115b1c Disable UsePerfData for resolveExtractor 2026-09-23 11:29:17 +01:00
Michael B. Gale
fa4712895b Restore previous restoreInputs behaviour 2026-09-22 19:09:07 +01:00
Michael B. Gale
660f7c5f24 Fix formatting 2026-09-22 18:58:17 +01:00
Michael B. Gale
41a4b9a4cd Merge pull request #4160 from github/update-bundle/codeql-bundle-v2.27.1
Update default bundle to 2.27.1
2026-09-22 17:53:51 +00:00
Michael B. Gale
fe0a932a6a Wrap JSON parse errors in readSarifFile with context 2026-09-22 18:53:03 +01:00
Michael B. Gale
8e36092a16 Wrap JSON parse errors in cloneObject with context 2026-09-22 18:52:03 +01:00
Michael B. Gale
2294a7a8b1 Wrap JSON parse errors in parseMatrixInput with context 2026-09-22 18:46:55 +01:00
Michael B. Gale
c0369726ee Wrap JSON parse errors in getTracerConfigForCluster with context 2026-09-22 18:43:26 +01:00
Michael B. Gale
a5c2338ec0 Wrap JSON parse errors in restoreInputs with context 2026-09-22 18:41:31 +01:00
Michael B. Gale
f042742baf Wrap JSON parse errors in resolveExtractor with context 2026-09-22 18:40:37 +01:00
Henry Mercer
33141e5cce Merge pull request #4159 from github/henrymercer/pr-4146-follow-ups
Address per-language bundle review follow-ups
2026-09-22 17:17:15 +00:00
github-actions[bot]
81fb67799a Add changelog note 2026-09-22 17:12:17 +00:00
github-actions[bot]
53162242d5 Update default bundle to codeql-bundle-v2.27.1 2026-09-22 17:12:09 +00:00
Henry Mercer
3bacfe2c5b Remove trailing whitespace from nightly comment
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-22 16:56:15 +01:00
Henry Mercer
e574ef13a6 Merge main into per-language bundle follow-ups
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-22 16:54:25 +01:00
Henry Mercer
48321b2d48 Update src/per-language-bundles.ts
Co-authored-by: Michael B. Gale <mbg@github.com>
2026-09-22 16:49:21 +01:00
Henry Mercer
f2ec2f6267 Tweak comment for latest nightly version check
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-09-22 16:23:55 +01:00
Henry Mercer
a9a8cd1aec Explain the nightly bundle version-check exception
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-22 16:07:10 +01:00
Henry Mercer
dba87a18dc Clarify elapsed-time helper documentation
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-22 16:07:10 +01:00
Henry Mercer
06344e2ba1 Stub nightly release listing directly
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-22 16:07:09 +01:00
Henry Mercer
07dc94940e Use default state in per-language bundle tests
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-09-22 16:07:07 +01:00
Michael B. Gale
416ff0dea1 Merge pull request #4157 from github/mbg/refactor/checkout-path
Refactor how the `checkout_path` input is obtained
2026-09-22 14:04:08 +00:00
Mario Campos
738bd62186 Refactor changenotes validate to use helper getChangenotes
This reduces duplicate code between `assemble` and `validate`. It also has the benefit of fixing a bug in the current implementation of `validate`, where `isValidChangenoteFile` receives a relative file name where it should receive an absolute one.
2026-09-22 09:01:46 -05:00
Mario Campos
6dd161bc76 Merge pull request #4155 from github/mario-campos/merge-changenotes
Add `changenotes.mts assemble` command to move changenotes to CHANGELOG.md
2026-09-22 12:52:41 +00:00
Michael B. Gale
8a88af6849 Refactor cleanupAndUploadDatabases querying checkout_path itself 2026-09-22 11:17:02 +01:00
Michael B. Gale
ada4e83349 Refactor cleanupAndUploadOverlayBaseDatabaseToCache querying checkout_path itself 2026-09-22 10:54:07 +01:00
Michael B. Gale
3a30b151d6 Refactor setupDiffInformedQueryRun querying checkout_path itself 2026-09-22 10:53:49 +01:00
Michael B. Gale
669351e880 Replace getRequiredEnvParam calls in init and setup-codeql action 2026-09-22 10:53:27 +01:00
Mario Campos
b1668d6234 Flesh out a comment 2026-09-21 16:40:26 -05:00
Mario Campos
c0bd54fdf4 Replace JSDoc text with @throws 2026-09-21 16:36:10 -05:00
Mario Campos
0263122209 Format code with npm run lint-fix 2026-09-21 16:32:44 -05:00
Mario Campos
c496c6cceb Rename name to absolutePath for clarity 2026-09-21 16:31:55 -05:00
Mario Campos
598cda36cf Apply suggestion from @mbg
Co-authored-by: Michael B. Gale <mbg@github.com>
2026-09-21 16:28:52 -05:00
Mario Campos
771560691a Update JSDoc comment with parameter lines
Co-authored-by: Michael B. Gale <mbg@github.com>
2026-09-21 16:28:36 -05:00
Mario Campos
a92f7fb688 Refactor changenote file listing into function to D.R.Y. 2026-09-18 15:02:17 -05:00
Mario Campos
7f54212a01 Rename flush command to assemble 2026-09-18 13:49:18 -05:00
Mario Campos
977b29b897 Replace splice with push and pop 2026-09-18 13:47:06 -05:00
Mario Campos
bc0efd6d91 Simplify addBodyLinesToUnreleasedSection 2026-09-18 12:35:41 -05:00
Mario Campos
128614ad8b Simplify getHeader to operate on ChangelogSections 2026-09-18 12:24:19 -05:00
Mario Campos
d63b2a40db Assume '[UNRELEASED]' section is first section 2026-09-18 11:42:46 -05:00
Mario Campos
b246e56069 Use ExitCode instead of 0/1 2026-09-18 11:28:17 -05:00
Mario Campos
bffae1c4b8 Use withChangelog I/O helper 2026-09-18 11:24:26 -05:00
Mario Campos
1ee3265262 Add changenotes.mts flush command
This command will "flush" or move the changenotes in the `unreleased-change-notes` directory to the `[UNRELEASED]` section of the CHANGELOG.md file.
2026-09-18 11:14:49 -05:00
Mario Campos
bb1dc5460b Add CHANGELOG function addBodyLinesToUnreleasedSection
This will be used by the `pr-checks/changenotes.mts` script to "compile" the latest release entry of CHANGELOG.md.
2026-09-18 11:14:48 -05:00
Mario Campos
47d607e2c1 Add changelog parsing helper getHeader 2026-09-18 11:14:48 -05:00
Mario Campos
cb31eabcd8 Do not include trailing newlines in NO_CHANGES_STR
Changing `NO_CHANGES_STR` to just be the text will make it easier to insert/use. To not break anything, I added the deleted newlines to the locations where `NO_CHANGES_STR` was used.
2026-09-18 09:35:44 -05:00
Michael B. Gale
a7afe0a2d7 Merge pull request #4153 from github/mergeback/v4.38.1-to-main-1c5b6756
Mergeback v4.38.1 refs/heads/releases/v4 into main
2026-09-18 13:40:20 +00:00
github-actions[bot]
f8b1c08e6d Rebuild 2026-09-18 13:11:23 +00:00
github-actions[bot]
ba80880079 Update changelog and version after v4.38.1 2026-09-18 13:11:14 +00:00
125 changed files with 39372 additions and 13521 deletions

View File

@@ -92,8 +92,7 @@ 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
)

View File

@@ -8,8 +8,6 @@ updates:
interval: weekly
cooldown:
default-days: 7
exclude:
- "@actions/*"
labels:
- Rebuild
# Ignore incompatible dependency updates
@@ -33,8 +31,6 @@ updates:
interval: weekly
cooldown:
default-days: 7
exclude:
- "actions/*"
labels:
- Rebuild
groups:

View File

@@ -51,6 +51,8 @@ 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

View File

@@ -124,4 +124,5 @@ 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

View File

@@ -44,8 +44,6 @@ jobs:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
version: stable-v2.19.4
- os: ubuntu-latest
version: stable-v2.20.7
- os: ubuntu-latest
@@ -56,6 +54,8 @@ jobs:
version: stable-v2.23.9
- os: ubuntu-latest
version: stable-v2.24.3
- os: ubuntu-latest
version: stable-v2.25.6
- os: ubuntu-latest
version: default
- os: ubuntu-latest

View File

@@ -44,8 +44,6 @@ jobs:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
version: stable-v2.19.4
- os: ubuntu-latest
version: stable-v2.20.7
- os: ubuntu-latest
@@ -56,6 +54,8 @@ jobs:
version: stable-v2.23.9
- os: ubuntu-latest
version: stable-v2.24.3
- os: ubuntu-latest
version: stable-v2.25.6
- os: ubuntu-latest
version: default
- os: ubuntu-latest

View File

@@ -44,8 +44,6 @@ jobs:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
version: stable-v2.19.4
- os: ubuntu-latest
version: stable-v2.20.7
- os: ubuntu-latest
@@ -56,6 +54,8 @@ jobs:
version: stable-v2.23.9
- os: ubuntu-latest
version: stable-v2.24.3
- os: ubuntu-latest
version: stable-v2.25.6
- os: ubuntu-latest
version: default
- os: ubuntu-latest

View File

@@ -54,10 +54,6 @@ jobs:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
version: stable-v2.19.4
- os: macos-15-xlarge
version: stable-v2.19.4
- os: ubuntu-latest
version: stable-v2.20.7
- os: macos-15-xlarge
@@ -78,6 +74,10 @@ jobs:
version: stable-v2.24.3
- os: macos-latest-xlarge
version: stable-v2.24.3
- os: ubuntu-latest
version: stable-v2.25.6
- os: macos-latest-xlarge
version: stable-v2.25.6
- os: ubuntu-latest
version: default
- os: macos-latest-xlarge
@@ -116,13 +116,14 @@ jobs:
version: ${{ matrix.version }}
use-all-platform-bundle: 'false'
setup-kotlin: 'true'
- 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.
- 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.
# 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'
python-version: '3.13.15'
- name: Use Xcode 16
# Only the older CodeQL CLI versions need Xcode 16, and these run on macOS 15.

View File

@@ -84,6 +84,8 @@ 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

View File

@@ -84,6 +84,8 @@ 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

View File

@@ -84,6 +84,8 @@ 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

View File

@@ -84,6 +84,8 @@ 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

View File

@@ -54,7 +54,7 @@ jobs:
use-all-platform-bundle: 'false'
setup-kotlin: 'true'
- name: Set up Ruby
uses: ruby/setup-ruby@95ef2b042f9d7a56d8268cba8559e2842e2ad01b # v1.321.0
uses: ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8 # v1.327.0
with:
ruby-version: 2.6
- name: Install Code Scanning integration

2
.github/workflows/__rust.yml generated vendored
View File

@@ -35,7 +35,7 @@ jobs:
matrix:
include:
- os: ubuntu-latest
version: stable-v2.19.4
version: stable-v2.20.7
- os: ubuntu-latest
version: stable-v2.22.1
- os: ubuntu-latest

View File

@@ -30,7 +30,7 @@ jobs:
fail-fast: false
matrix:
version:
- stable-v2.20.3
- stable-v2.20.7
- default
- linked
- nightly-latest

View File

@@ -29,7 +29,7 @@ jobs:
fail-fast: false
matrix:
version:
- stable-v2.20.3
- stable-v2.20.7
- default
- linked
- nightly-latest
@@ -85,7 +85,7 @@ jobs:
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- name: Check expected artifacts exist
run: |
VERSIONS="stable-v2.20.3 default linked nightly-latest"
VERSIONS="stable-v2.20.7 default linked nightly-latest"
LANGUAGES="cpp csharp go java javascript python"
for version in $VERSIONS; do
pushd "./my-debug-artifacts-${version//./}"

View File

@@ -47,6 +47,12 @@ jobs:
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
- name: Install dependencies
run: |
# Use the system Bash shell to ensure we can run commands like `npm ci`
@@ -95,6 +101,14 @@ 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:
@@ -114,9 +128,9 @@ jobs:
working-directory: pr-checks
run: npx tsx --test
- name: Run `pr-checks/changenotes.mts` to ensure that all unreleased change notes are valid
- 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.mts validate
run: npx tsx pr-checks/changenotes.ts validate
- name: Verify all Actions use the same Node version
id: head-version

View File

@@ -28,7 +28,7 @@ defaults:
jobs:
prepare:
name: "Prepare release"
name: "Release info"
runs-on: ubuntu-latest
if: github.repository == 'github/codeql-action'

View File

@@ -54,32 +54,27 @@ jobs:
run: |
git fetch origin "$BASE_BRANCH"
# Allow merge conflicts in `lib`, since rebuilding should resolve them.
git merge "origin/$BASE_BRANCH"
MERGE_RESULT=$?
if [ "$MERGE_RESULT" -eq 0 ]; then
# 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
echo "Merge succeeded cleanly."
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
elif git rev-parse --verify MERGE_HEAD >/dev/null 2>&1; then
echo "Merge conflicts detected, continuing."
echo "merge-in-progress=true" >> $GITHUB_OUTPUT
# 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
# 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
echo "Merge conflicts were detected outside of the lib directory. Please resolve them manually."
git -c core.whitespace=-trailing-space diff --check | grep --invert-match '^lib/' || true
echo "$CONFLICTS_OUTSIDE_LIB"
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

View File

@@ -10,8 +10,7 @@ on:
required: true
# Only for dry-runs of changes to the workflow.
push:
# Don't run dry-run on release branches, to avoid an issue where the
# "new" tag determined by the "Prepare release" job already exists.
# Don't run dry-run on release branches, since that's unnecessary.
branches-ignore:
- releases/v*
paths:
@@ -24,7 +23,7 @@ defaults:
jobs:
prepare:
name: "Prepare release"
name: "Prepare"
if: github.repository == 'github/codeql-action'
permissions:
@@ -107,8 +106,10 @@ 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' }}
RELEASE_TAG: ${{ needs.prepare.outputs.version }}
MAJOR_VERSION_TAG: ${{ needs.prepare.outputs.major_version }}
# 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') }}
run: |
git checkout "refs/tags/${ROLLBACK_TAG}"
git tag --annotate "${RELEASE_TAG}" --message "${RELEASE_TAG}"
@@ -184,4 +185,3 @@ 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' }}"

View File

@@ -16,15 +16,15 @@ defaults:
shell: bash
jobs:
prepare:
name: "Prepare release"
name: "Prepare"
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,6 +77,7 @@ jobs:
--conductor ${GITHUB_ACTOR}
backport:
name: "Create backport"
timeout-minutes: 45
runs-on: ubuntu-latest
environment: Automation

1
.npmrc
View File

@@ -1 +1,2 @@
lockfile-version=3
min-release-age=7

View File

@@ -7,6 +7,10 @@
// 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,
@@ -18,7 +22,7 @@
"git.ignoreLimitWarning": true,
// Use the vendored TypeScript version to have a consistent development experience across
// machines.
"typescript.tsdk": "node_modules/typescript/lib",
"js/ts.tsdk.path": "node_modules/typescript/lib",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},

View File

@@ -2,6 +2,20 @@
See the [releases page](https://github.com/github/codeql-action/releases) for the relevant changes to the CodeQL CLI and language packs.
## [UNRELEASED]
- _Breaking change_: Bump the minimum required CodeQL bundle version to 2.20.7. [#4205](https://github.com/github/codeql-action/pull/4205)
## 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)

View File

@@ -53,6 +53,7 @@ Here are a few things you can do that will increase the likelihood of your pull
- Write tests.
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
- Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
- For user-facing changes, add a change-note file. See [unreleased-change-notes/README.md](unreleased-change-notes/README.md).
## Releasing (write access required)

View File

@@ -72,12 +72,11 @@ 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).

View File

@@ -1,3 +1,4 @@
import pkg from "./package.json" with { type: "json" };
globalThis.__CODEQL_ACTION_VERSION__ = pkg.version;
globalThis.__CODEQL_ACTION_TEST_ENV__ = "unit-test";

View File

@@ -78,7 +78,7 @@ const UPLOAD_LIB_SRC = "./src/upload-lib";
*
* The virtual module additionally re-exports `upload-lib` under the `uploadLib` namespace so that
* external consumers can access it via the small `lib/upload-lib.js` stub emitted below.
*
*
* A tiny stub file is emitted for each Action entrypoint, and one for `upload-lib`. Each stub
* imports the shared bundle and calls/re-exports from the respective entry point.
*
@@ -212,6 +212,7 @@ const context = await esbuild.context({
target: ["node20"],
define: {
__CODEQL_ACTION_VERSION__: JSON.stringify(pkg.version),
__CODEQL_ACTION_TEST_ENV__: JSON.stringify(""),
},
metafile: true,
});

View File

@@ -140,6 +140,17 @@ export default [
"no-async-foreach/no-async-foreach": "error",
"no-sequences": "error",
"no-shadow": "off",
// A basic check that we don't use `exportVariable` from `@actions/core`.
"no-restricted-syntax": [
"error",
{
selector: "MemberExpression[property.name='exportVariable']",
message:
"Use the `export` method of an `Env` instance or `exportEnvVar` from `environment.ts` instead.",
},
],
// This is overly restrictive with unsetting `EnvVar`s
"@typescript-eslint/no-dynamic-delete": "off",
"@typescript-eslint/no-shadow": "error",
@@ -158,7 +169,16 @@ export default [
},
},
{
files: ["**/*.ts", "**/*.js", "**/*.mts"],
files: ["src/environment.ts"],
// We allow `exportVariable` from `@actions/core` to be used in this file
// since it defines the wrapper around it that other modules use.
rules: {
"no-restricted-syntax": "off",
},
},
{
files: ["**/*.ts", "**/*.js"],
rules: {
"@typescript-eslint/no-explicit-any": "off",
@@ -180,7 +200,7 @@ export default [
},
},
{
files: ["pr-checks/**/*.ts", "pr-checks/**/*.mts"],
files: ["pr-checks/**/*.ts"],
languageOptions: {
parserOptions: {

View File

@@ -1,6 +1,6 @@
{
"bundleVersion": "codeql-bundle-v2.27.0",
"cliVersion": "2.27.0",
"priorBundleVersion": "codeql-bundle-v2.26.4",
"priorCliVersion": "2.26.4"
"bundleVersion": "codeql-bundle-v2.27.2",
"cliVersion": "2.27.2",
"priorBundleVersion": "codeql-bundle-v2.27.1",
"priorCliVersion": "2.27.1"
}

47836
lib/entry-points.js generated

File diff suppressed because one or more lines are too long

513
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "codeql",
"version": "4.38.1",
"version": "4.39.0",
"private": true,
"description": "CodeQL action",
"scripts": {
@@ -22,7 +22,7 @@
"dependencies": {
"@actions/artifact": "^5.0.3",
"@actions/artifact-legacy": "npm:@actions/artifact@^1.1.2",
"@actions/cache": "^5.2.0",
"@actions/cache": "^5.3.0",
"@actions/core": "^2.0.3",
"@actions/exec": "^2.0.0",
"@actions/github": "^8.0.1",
@@ -31,21 +31,20 @@
"@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-paginate-rest": "^16.0.0",
"@octokit/plugin-rest-endpoint-methods": "^18.0.0",
"@octokit/plugin-retry": "^8.1.1",
"archiver": "^8.0.0",
"fast-deep-equal": "^3.1.3",
"follow-redirects": "^1.16.0",
"follow-redirects": "^1.16.1",
"get-folder-size": "^5.0.0",
"https-proxy-agent": "^7.0.6",
"js-yaml": "^5.4.1",
"js-yaml": "^5.4.3",
"jsonschema": "1.5.0",
"long": "^5.3.2",
"node-forge": "^1.4.0",
"semver": "^7.8.5",
"uuid": "^14.0.2",
"undici": "^6.28.0"
"undici": "^6.28.0",
"uuid": "^14.0.2"
},
"devDependencies": {
"@ava/typescript": "6.0.0",
@@ -66,14 +65,14 @@
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-github": "^6.1.2",
"eslint-plugin-import-x": "^4.17.1",
"eslint-plugin-jsdoc": "^64.3.8",
"eslint-plugin-jsdoc": "^65.2.0",
"eslint-plugin-no-async-foreach": "^0.1.1",
"glob": "^13.0.6",
"globals": "^17.12.0",
"globals": "^17.13.0",
"nock": "^14.0.17",
"sinon": "^22.1.0",
"typescript": "^6.0.3",
"typescript-eslint": "^8.70.0"
"typescript-eslint": "^8.71.1"
},
"overrides": {
"@actions/tool-cache": {

1
pr-checks/.nvmrc Normal file
View File

@@ -0,0 +1 @@
24

View File

@@ -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.trim()));
assert.ok(!result.includes(NO_CHANGES_STR));
});
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.trim()));
assert.ok(result.includes(NO_CHANGES_STR));
});
await it("throws if there are no sections", async () => {

View File

@@ -122,6 +122,6 @@ function main() {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
process.exit(main());
}

View File

@@ -43,6 +43,6 @@ async function main() {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
void main();
}

View File

@@ -9,17 +9,46 @@ 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");
@@ -70,3 +99,73 @@ 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),
);
});
});

View File

@@ -6,14 +6,16 @@ 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.\n\n";
export const NO_CHANGES_STR = "No user facing changes.";
/** 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.
@@ -31,6 +33,13 @@ 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", {
@@ -125,6 +134,42 @@ 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.
*/
@@ -204,7 +249,7 @@ export function processChangelogForBackports(
// Add an entry if we didn't keep any.
if (!foundContent) {
section.bodyLines.push(NO_CHANGES_STR.trim());
section.bodyLines.push(NO_CHANGES_STR);
}
}

View File

@@ -1,18 +1,15 @@
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as path from "node:path";
import { describe, it } from "node:test";
import { withTmpDir, withTmpFile } from "../../src/util";
import { withTmpFile } from "../../src/util";
import {
hasValidChangenoteCategory,
isValidAllChangenoteFiles,
isValidChangenoteContent,
isValidChangenoteFile,
isValidChangenoteFilename,
VALID_CHANGE_NOTE_CATEGORIES,
} from "./validate.mjs";
} from "./validate";
await describe("isValidChangenoteContent", async () => {
await it("recognizes an unordered Markdown list", () => {
@@ -157,26 +154,6 @@ await describe("isValidChangenoteFile", 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",
@@ -187,39 +164,3 @@ await describe("isValidChangenoteFile", async () => {
);
});
});
await describe("isValidAllChangenoteFiles", async () => {
await it("accepts list of file paths of valid change-notes", async () => {
await withTmpDir(async (tmpDir) => {
const fileName1 = path.join(tmpDir, "2026-01-01-fix-bug.md");
const fileName2 = path.join(tmpDir, "2026-01-02-add-feature.md");
fs.writeFileSync(fileName1, "---\ncategory: fix\n---\n- Fixed a bug\n");
fs.writeFileSync(
fileName2,
"---\ncategory: feature\n---\n- Added a feature\n",
);
assert.equal(isValidAllChangenoteFiles([fileName1, fileName2]), true);
});
});
await it("accepts the empty list", async () => {
assert.equal(isValidAllChangenoteFiles([]), true);
});
await it("accepts list of .gitkeep", async () => {
assert.equal(isValidAllChangenoteFiles([".gitkeep"]), true);
});
await it("rejects list containing a file path to an invalid change-note", async () => {
await withTmpDir(async (tmpDir) => {
const fileName1 = path.join(tmpDir, "2026-01-01-fix-bug.md");
const fileName2 = path.join(tmpDir, "2026-01-02-wrong-category.md");
fs.writeFileSync(fileName1, "---\ncategory: fix\n---\n- Fixed a bug\n");
fs.writeFileSync(
fileName2,
"---\ncategory: foobar\n---\n- Added a feature\n",
);
assert.equal(isValidAllChangenoteFiles([fileName1, fileName2]), false);
});
});
});

View File

@@ -1,5 +1,4 @@
import * as fs from "node:fs";
import * as path from "node:path";
import { matter } from "lite-matter";
import type { List, ListItem } from "mdast";
@@ -95,21 +94,7 @@ export function isValidChangenoteFile(filename: string): boolean {
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}`,
);
}
const { content } = matter(fileData);
if (!isValidChangenoteContent(content)) {
isValid = false;
console.error(
@@ -119,14 +104,3 @@ export function isValidChangenoteFile(filename: string): boolean {
return isValid;
}
/**
* Validates the change-note files of the given list of file paths, ignoring ".gitkeep".
* @param filepaths A list of filepaths to validate
* @returns True if all the paths are valid, false otherwise.
*/
export function isValidAllChangenoteFiles(filepaths: string[]): boolean {
return filepaths
.filter((f) => f !== ".gitkeep")
.reduce((r, filePath) => r && isValidChangenoteFile(filePath), true);
}

View File

@@ -1,56 +0,0 @@
#!/usr/bin/env npx tsx
import * as fs from "node:fs";
import { pathToFileURL } from "node:url";
import { parseArgs } from "node:util";
import { isValidAllChangenoteFiles } from "./changelog/validate.mjs";
import { CHANGENOTES_DIR } from "./config";
const entryPoint = process.argv[1];
if (entryPoint && import.meta.url === pathToFileURL(entryPoint).href) {
try {
process.exit(main());
} catch (error) {
console.error(error);
process.exit(1);
}
}
function main(): number {
const { positionals } = parseArgs({
allowPositionals: true,
strict: true,
});
const [command] = positionals;
switch (command) {
case undefined:
case "help":
return usage();
case "validate":
return validate();
default:
console.error(`Unknown command: ${command}`);
return 1;
}
}
function usage(): number {
console.log(`Usage: changenotes.mts validate`);
return 0;
}
function validate(): number {
try {
if (isValidAllChangenoteFiles(fs.readdirSync(CHANGENOTES_DIR))) {
console.log(`All changenotes in '${CHANGENOTES_DIR}' are valid.`);
return 0;
}
} catch (error) {
console.error(
`Failed to read changenotes directory '${CHANGENOTES_DIR}'`,
error,
);
}
return 1;
}

134
pr-checks/changenotes.ts Executable file
View File

@@ -0,0 +1,134 @@
#!/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" and "README.md").
* */
function listUnreleasedChangenoteDir(): string[] {
return fs
.readdirSync(CHANGENOTES_DIR)
.filter((name) => ![".gitkeep", "README.md"].includes(name))
.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;
}

View File

@@ -218,6 +218,6 @@ async function run(): Promise<void> {
}
}
if (require.main === module) {
if (import.meta.main) {
void run();
}

View File

@@ -11,6 +11,10 @@ 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

View File

@@ -10,7 +10,6 @@ operatingSystems:
- os: macos
runner-image: macos-15-xlarge
codeql-versions:
- stable-v2.19.4
- stable-v2.20.7
- stable-v2.21.4
- stable-v2.22.4
@@ -20,13 +19,14 @@ env:
installGo: true
installDotNet: true
steps:
- 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.
- 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.
# 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"
python-version: "3.13.15"
- name: Use Xcode 16
# Only the older CodeQL CLI versions need Xcode 16, and these run on macOS 15.

View File

@@ -5,7 +5,7 @@ versions:
- default
steps:
- name: Set up Ruby
uses: ruby/setup-ruby@95ef2b042f9d7a56d8268cba8559e2842e2ad01b # v1.321.0
uses: ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8 # v1.327.0
with:
ruby-version: 2.6
- name: Install Code Scanning integration

View File

@@ -1,8 +1,8 @@
name: "Rust analysis"
description: "Tests creation of a Rust database"
versions:
# experimental rust support introduced, requires action to set `CODEQL_ENABLE_EXPERIMENTAL_FEATURES`
- stable-v2.19.4
# oldest CodeQL version supported by the Action, where Rust support is experimental and requires the Action to set `CODEQL_ENABLE_EXPERIMENTAL_FEATURES`
- stable-v2.20.7
# first public preview version
- stable-v2.22.1
- linked

View File

@@ -1,4 +1,9 @@
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;

View File

@@ -5,6 +5,8 @@ contains:
- "test-setup-python-scripts"
- "update"
- "Update"
# Matrix-ed job; the name starts with this
- "Create backport"
is:
- "Agent"
- "check-expected-release-files"
@@ -15,4 +17,6 @@ is:
- "Label PR with size"
- "Post repo size comment"
- "Prepare"
- "Release info"
- "Upload results"
- "Update release branch"

View File

@@ -1,19 +1,20 @@
{
"private": true,
"description": "Dependencies for codeql-action scripts",
"type": "module",
"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-paginate-rest": ">=16.0.0",
"@octokit/plugin-rest-endpoint-methods": "^18.0.0",
"lite-matter": "^0.1.2",
"mdast-util-from-markdown": "^2.0.3",
"mdast-util-from-markdown": "^2.1.0",
"semver": "^7.8.5",
"yaml": "^2.9.0"
"yaml": "^2.9.1"
},
"devDependencies": {
"@types/node": "^20.19.43",
"tsx": "^4.23.13"
"@types/node": "^24.19.0",
"tsx": "^4.23.15"
}
}

View File

@@ -77,6 +77,6 @@ function main() {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
process.exit(main());
}

View File

@@ -116,6 +116,6 @@ async function main() {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
void main();
}

View File

@@ -79,6 +79,6 @@ function main() {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
process.exit(main());
}

View File

@@ -21,10 +21,11 @@ import * as fs from "fs";
import { parseArgs } from "node:util";
import * as path from "path";
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");
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");
/**
* Scan generated workflow files to extract the latest action versions.
@@ -232,6 +233,6 @@ function main(): number {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
process.exit(main());
}

View File

@@ -342,6 +342,6 @@ async function main(): Promise<void> {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
void main();
}

View File

@@ -7,6 +7,8 @@ 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.
@@ -134,8 +136,6 @@ type LanguageSetups = Partial<Record<BuiltInLanguage, LanguageSetup>>;
// The default set of CodeQL Bundle versions to use for the PR checks.
const defaultTestVersions = [
// The oldest supported CodeQL version. If bumping, update `CODEQL_MINIMUM_VERSION` in `codeql.ts`
"stable-v2.19.4",
// The last CodeQL release in the 2.20 series.
"stable-v2.20.7",
// The last CodeQL release in the 2.21 series.
"stable-v2.21.4",
@@ -145,6 +145,8 @@ const defaultTestVersions = [
"stable-v2.23.9",
// The last CodeQL release in the 2.24 series.
"stable-v2.24.3",
// The last CodeQL release in the 2.25 series.
"stable-v2.25.6",
// The default version of CodeQL for Dotcom, as determined by feature flags.
"default",
// The version of CodeQL shipped with the Action in `defaults.json`. During the release process
@@ -221,6 +223,12 @@ 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",
@@ -306,9 +314,8 @@ const languageSetups: LanguageSetups = {
// See https://github.com/github/codeql-action/pull/3423
const YQ_VERSION = "v4.50.1";
const THIS_DIR = __dirname;
const CHECKS_DIR = path.join(THIS_DIR, "checks");
const OUTPUT_DIR = path.join(THIS_DIR, "..", ".github", "workflows");
const CHECKS_DIR = path.join(PR_CHECKS_DIR, "checks");
const OUTPUT_DIR = path.join(REPO_ROOT, ".github", "workflows");
/**
* Loads and parses a YAML file.

View File

@@ -8,6 +8,6 @@
"sourceMap": false,
"noEmit": true
},
"include": ["./**/*.ts", "./**/*.mts", "../src/**/*.ts"],
"include": ["./**/*.ts", "../src/**/*.ts"],
"exclude": ["node_modules"]
}

View File

@@ -238,6 +238,6 @@ function main() {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
main();
}

View File

@@ -835,6 +835,6 @@ async function main(): Promise<void> {
}
// Only call `main` if this script was run directly.
if (require.main === module) {
if (import.meta.main) {
void main();
}

View File

@@ -23,7 +23,8 @@ predicate isSafeForDefaultSetup(string envVar) {
"GITHUB_BASE_REF", "GITHUB_EVENT_NAME", "GITHUB_JOB", "GITHUB_RUN_ATTEMPT", "GITHUB_RUN_ID",
"GITHUB_SHA", "GITHUB_REPOSITORY", "GITHUB_SERVER_URL", "GITHUB_TOKEN", "GITHUB_WORKFLOW",
"GITHUB_WORKSPACE", "GOFLAGS", "ImageVersion", "JAVA_TOOL_OPTIONS", "RUNNER_ARCH",
"RUNNER_ENVIRONMENT", "RUNNER_NAME", "RUNNER_OS", "RUNNER_TEMP", "RUNNER_TOOL_CACHE"
"RUNNER_ENVIRONMENT", "RUNNER_NAME", "RUNNER_OS", "RUNNER_TEMP", "RUNNER_TOOL_CACHE",
"NODE_ENV"
]
}

View File

@@ -21,19 +21,16 @@ inputs:
required: false
languages:
description: >-
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`.
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.
required: false
analysis-kinds:
description: >-
[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`.
[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.
Available options are the same as for the `analysis-kinds` input on the `init` Action.
default: 'code-scanning'

View File

@@ -19,6 +19,24 @@ import { getErrorMessage } from "./util";
setupTests(test);
for (const [key, displayName] of Object.entries(
statusReport.ACTION_DISPLAY_NAMES,
)) {
test(`getDisplayActionName - '${displayName}' instead of '${key}'`, (t) => {
t.is(statusReport.getDisplayActionName(key as ActionName), displayName);
});
}
test("getDisplayActionName - returns action name", (t) => {
for (const actionName of Object.values(ActionName)) {
if (statusReport.ACTION_DISPLAY_NAMES[actionName]) {
continue;
}
t.is(statusReport.getDisplayActionName(actionName), actionName);
}
});
interface RunInActionsTestOpts {
runFn?: () => Promise<any>;
expectedErrorMessage?: string;

View File

@@ -19,6 +19,10 @@ 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. */
@@ -52,6 +56,29 @@ export interface FeatureState {
/** Identifies a type of state an Action may have. */
export type StateFeature = keyof FeatureState;
/**
* The `Env` feature implies the availability of the `ReadOnlyEnv` feature.
*
* If `T` is `Env`, this returns `Env | ReadOnlyEnv`.
* Otherwise, it is the identity and returns T.
*/
type ImpliedFeatures<T extends StateFeature> = T extends "Env"
? "Env" | "ReadOnlyEnv"
: T;
/**
* Given an object type `Obj`, this tries to lookup a corresponding `StateFeature`
* to which the object type belongs in `FeatureState`. Resolves to `never` if there
* is no match.
*/
type FeatureNameFor<Obj extends object> = {
[K in StateFeature]: [Obj] extends [FeatureState[K]]
? [FeatureState[K]] extends [Obj]
? K
: never
: never;
}[StateFeature];
/** Constructs the intersection of all state types identifies by `Fs`. */
export type FieldsOf<Fs extends readonly StateFeature[]> = Fs extends []
? Record<never, never>
@@ -62,8 +89,54 @@ export type FieldsOf<Fs extends readonly StateFeature[]> = Fs extends []
? FeatureState[Head] & FieldsOf<Tail>
: never;
/**
* Symbol used for a field in `ActionState` that carries the type array of state features.
* This is a Symbol so that it doesn't clash with any property names we might want to have.
*/
const stateFeatures = Symbol();
/** Describes the state of an Action that has access to the state corresponding to `Fs`. */
export type ActionState<Fs extends readonly StateFeature[]> = FieldsOf<Fs>;
export type ActionState<Fs extends readonly StateFeature[]> = FieldsOf<Fs> & {
/**
* When given a chance, TypeScript will simplify an `ActionState<Fs>` type as much as possible,
* which results in a concrete object type that doesn't mention `Fs`.
*
* That causes problems for functions which accept `ActionState<Fs>` values, but need to know the
* feature keys `Fs`. This property here explicitly captures `Fs` in the concrete object type
* that results from simplifying `ActionState<Fs>`.
*
* This is a function rather than a field, because we want to be able to provide values of type
* `ActionState<Fs>` to functions expecting `ActionState<As>` where `As` is a subset of `Fs`.
*
* Since function types are contravariant in the types of their parameters, using a function
* type here allows that to happen.
*
* Because the field is optional, we don't have to explicitly provide a value
* for it anywhere while the type is still inferred.
*
* `Fs[number]` returns the union of all features in `Fs`. We wrap it in `ImpliedFeatures`
* so that `Env` is expanded into `Env | ReadOnlyEnv`, allowing functions that expect the
* `ReadOnlyEnv` feature to be provided with an `ActionState` that has the `Env` feature
* without requiring this to be made explicit.
*/
readonly [stateFeatures]?: (ts: ImpliedFeatures<Fs[number]>) => void;
};
/** Extends `state` with an `extra` feature. */
export function extendActionState<
// In first position, so that it can be explicitly provided if `FeatureNameFor`
// should not work on `extra`.
F extends StateFeature,
Fs extends readonly StateFeature[],
E extends FeatureState[F],
>(
state: ActionState<Fs>,
extra: E,
): ActionState<[...Fs, FeatureNameFor<E> & F]> {
return { ...state, ...extra } as unknown as ActionState<
[...Fs, FeatureNameFor<E> & F]
>;
}
/** The type of an Action's main entry point. This is a function that is provided
* with a basic `ActionState` object with features that are always available.
@@ -98,6 +171,8 @@ export async function runInActions(action: Action) {
const actionState = {
name: action.name,
startedAt,
platform: process.platform,
arch: process.arch,
logger,
env,
actions: actionsEnv,

View File

@@ -7,12 +7,13 @@ import {
isAnalyzingPullRequest,
isDefaultSetup,
isDynamicWorkflow,
printDebugLogs,
} from "./actions-util";
import { computeAutomationID } from "./api-client";
import { EnvVar } from "./environment";
import { getRunnerLogger } from "./logging";
import { setupTests } from "./testing-utils";
import { initializeEnvironment } from "./util";
import { RecordingLogger, setupTests } from "./testing-utils";
import { initializeEnvironment, withTmpDir } from "./util";
setupTests(test);
@@ -100,6 +101,21 @@ test("computeAutomationID()", async (t) => {
);
});
test("printDebugLogs - doesn't throw when config doesn't have needed properties", async (t) => {
const logger = new RecordingLogger();
await t.notThrowsAsync(printDebugLogs(logger, {}));
await t.notThrowsAsync(printDebugLogs(logger, { languages: [] }));
await t.notThrowsAsync(printDebugLogs(logger, { dbLocation: "nowhere" }));
});
test("printDebugLogs - doesn't throw when language db doesn't exist", async (t) =>
withTmpDir(async (tmpDir) => {
const logger = new RecordingLogger();
await t.notThrowsAsync(
printDebugLogs(logger, { dbLocation: tmpDir, languages: ["javascript"] }),
);
}));
test.serial("getPullRequestBranches() with pull request context", (t) => {
withMockedContext(
{

View File

@@ -6,7 +6,7 @@ import * as toolrunner from "@actions/exec/lib/toolrunner";
import * as github from "@actions/github";
import * as io from "@actions/io";
import type { Config } from "./config-utils";
import { hasConfigKey, type Config } from "./config/action-config";
import { Env, EnvVar, ActionsEnvVars, ReadOnlyEnv } from "./environment";
import { Logger } from "./logging";
import {
@@ -14,6 +14,7 @@ import {
getCodeQLDatabasePath,
ConfigurationError,
getEnv,
getErrorMessage,
} from "./util";
/**
@@ -29,7 +30,6 @@ declare const __CODEQL_ACTION_VERSION__: string;
export interface ActionsEnv {
getRequiredInput: (name: string) => string;
getOptionalInput: (name: string) => string | undefined;
exportVariable: (name: string, value: string) => void;
}
/**
@@ -39,7 +39,6 @@ export function getActionsEnv(): ActionsEnv {
return {
getRequiredInput,
getOptionalInput,
exportVariable: core.exportVariable,
};
}
@@ -102,7 +101,7 @@ export function getWorkflowEventName(env: Env = getEnv()) {
* Returns whether the current workflow is executing a local copy of the Action, e.g. we're running
* a workflow on the codeql-action repo itself.
*/
export function isRunningLocalAction(env: Env = getEnv()): boolean {
export function isRunningLocalAction(env: ReadOnlyEnv = getEnv()): boolean {
const relativeScriptPath = getRelativeScriptPath(env);
return (
relativeScriptPath.startsWith("..") || path.isAbsolute(relativeScriptPath)
@@ -114,7 +113,7 @@ export function isRunningLocalAction(env: Env = getEnv()): boolean {
*
* This can be used to get the Action's name or tell if we're running a local Action.
*/
function getRelativeScriptPath(env: Env): string {
function getRelativeScriptPath(env: ReadOnlyEnv): string {
const runnerTemp = env.getRequired(ActionsEnvVars.RUNNER_TEMP);
const actionsDirectory = path.join(path.dirname(runnerTemp), "_actions");
return path.relative(actionsDirectory, __filename);
@@ -132,28 +131,38 @@ export function getWorkflowEvent(env: Env = getEnv()): any {
}
}
export async function printDebugLogs(config: Config) {
export async function printDebugLogs(logger: Logger, config: Partial<Config>) {
if (
!hasConfigKey(config, "languages") ||
!hasConfigKey(config, "dbLocation")
) {
logger.debug(
`Not printing debug logs, because the configuration does not include the 'languages' or 'dbLocation' fields.`,
);
return;
}
for (const language of config.languages) {
const databaseDirectory = getCodeQLDatabasePath(config, language);
const logsDirectory = path.join(databaseDirectory, "log");
if (!doesDirectoryExist(logsDirectory)) {
core.info(`Directory ${logsDirectory} does not exist.`);
logger.info(`Directory ${logsDirectory} does not exist.`);
continue; // Skip this language database.
}
const walkLogFiles = (dir: string) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
if (entries.length === 0) {
core.info(`No debug logs found at directory ${logsDirectory}.`);
logger.info(`No debug logs found at directory ${logsDirectory}.`);
}
for (const entry of entries) {
if (entry.isFile()) {
const absolutePath = path.resolve(dir, entry.name);
core.startGroup(
logger.startGroup(
`CodeQL Debug Logs - ${language} - ${entry.name} from file at path ${absolutePath}`,
);
process.stdout.write(fs.readFileSync(absolutePath));
core.endGroup();
logger.info(fs.readFileSync(absolutePath, "utf-8"));
logger.endGroup();
} else if (entry.isDirectory()) {
walkLogFiles(path.resolve(dir, entry.name));
}
@@ -412,14 +421,23 @@ export const persistInputs = function (env: Env = getEnv()) {
/**
* Restores all inputs to the action from the persisted state.
*/
export const restoreInputs = function () {
const persistedInputs = core.getState(persistedInputsKey);
if (persistedInputs) {
for (const [name, value] of JSON.parse(persistedInputs)) {
process.env[name] = value;
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;
}
}
} 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;

View File

@@ -9,7 +9,6 @@ import * as core from "@actions/core";
import * as actionsUtil from "./actions-util";
import { getGitHubVersion } from "./api-client";
import { getCodeQL } from "./codeql";
import { getConfig } from "./config-utils";
import * as debugArtifacts from "./debug-artifacts";
import {
@@ -25,8 +24,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,12 +37,9 @@ export async function runWrapper() {
logger,
);
if (config !== undefined) {
const codeql = await getCodeQL(logger, config.codeQLCmd);
const version = await codeql.getVersion();
await debugArtifacts.uploadCombinedSarifArtifacts(
logger,
config.gitHubVersion.type,
version.version,
);
}
}

View File

@@ -212,7 +212,12 @@ async function runAutobuildIfLegacyGoWorkflow(config: Config, logger: Logger) {
await runAutobuild(config, BuiltInLanguage.go, logger);
}
async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
async function run({
startedAt,
env,
logger,
actions,
}: ActionState<["Base", "Env", "Logger", "Actions"]>) {
// To capture errors appropriately, keep as much code within the try-catch as
// possible, and only use safe functions outside.
@@ -263,17 +268,6 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
);
}
// Unset the CODEQL_PROXY_* environment variables when using older CodeQL
// CLIs, as they are not needed and can cause issues.
if (
process.env.CODEQL_PROXY_HOST === "" &&
!(await util.codeQlVersionAtLeast(codeql, "2.20.7"))
) {
delete process.env.CODEQL_PROXY_HOST;
delete process.env.CODEQL_PROXY_PORT;
delete process.env.CODEQL_PROXY_CA_CERTIFICATE;
}
if (actionsUtil.getOptionalInput("cleanup-level")) {
logger.info(
"The 'cleanup-level' input is ignored since the CodeQL Action now automatically " +
@@ -283,7 +277,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
const apiDetails = getApiDetails();
const outputDir = actionsUtil.getRequiredInput("output");
core.exportVariable(EnvVar.SARIF_RESULTS_OUTPUT_DIR, outputDir);
env.export(EnvVar.SARIF_RESULTS_OUTPUT_DIR, outputDir);
const threads = util.getThreadsFlag(
actionsUtil.getOptionalInput("threads") || process.env["CODEQL_THREADS"],
logger,
@@ -307,8 +301,13 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
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);
const diffRangePackDir = await setupDiffInformedQueryRun(
logger,
checkoutPath,
);
await warnIfGoInstalledAfterInit(config, logger);
await runAutobuildIfLegacyGoWorkflow(config, logger);
@@ -354,7 +353,6 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
actionsUtil.getOptionalInput("upload"),
);
if (runStats) {
const checkoutPath = actionsUtil.getRequiredInput("checkout_path");
const category = actionsUtil.getOptionalInput("category");
uploadResults = await postProcessAndUploadSarif(
@@ -388,18 +386,23 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
// 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);
await cleanupAndUploadOverlayBaseDatabaseToCache(
codeql,
config,
logger,
checkoutPath,
);
// 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,
features,
logger,
checkoutPath,
);
// Possibly upload the TRAP caches for later re-use
@@ -443,7 +446,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
`expect-error input was set to true but no error was thrown.`,
);
}
core.exportVariable(EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY, "true");
env.export(EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY, "true");
} catch (unwrappedError) {
const error = util.wrapError(unwrappedError);
if (

View File

@@ -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";

View File

@@ -5,10 +5,12 @@ import { performance } from "perf_hooks";
import * as io from "@actions/io";
import * as yaml from "js-yaml";
import { getTemporaryDirectory, getRequiredInput } from "./actions-util";
import { getTemporaryDirectory } from "./actions-util";
import * as analyses from "./analyses";
import { setupCppAutobuild } from "./autobuild";
import { type CodeQL } from "./codeql";
import type { ActionConfig } from "./config/action-config";
import { defaultSuites } from "./config/db-config";
import * as configUtils from "./config-utils";
import {
getCsharpTempDependencyDir,
@@ -123,7 +125,7 @@ export async function runExtraction(
language === BuiltInLanguage.cpp &&
config.buildMode === BuildMode.Autobuild
) {
await setupCppAutobuild(codeql, logger);
await setupCppAutobuild(logger);
}
// The Java and C# `build-mode: none` extractors place dependencies in the
@@ -170,7 +172,7 @@ async function shouldExtractLanguage(
}
export function dbIsFinalized(
config: configUtils.Config,
config: ActionConfig<"dbLocation">,
language: Language,
logger: Logger,
) {
@@ -233,6 +235,7 @@ async function finalizeDatabaseCreation(
*/
export async function setupDiffInformedQueryRun(
logger: Logger,
checkoutPath: string,
): Promise<string | undefined> {
return await withGroupAsync(
"Generating diff range extension pack",
@@ -245,7 +248,6 @@ export async function setupDiffInformedQueryRun(
return undefined;
}
const checkoutPath = getRequiredInput("checkout_path");
const packDir = writeDiffRangeDataExtensionPack(
logger,
diffRanges,
@@ -357,15 +359,6 @@ 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.

View File

@@ -1,5 +1,6 @@
import * as github from "@actions/github";
import * as githubUtils from "@actions/github/lib/utils";
import * as retry from "@octokit/plugin-retry";
import test from "ava";
import * as sinon from "sinon";
import { ProxyAgent } from "undici";
@@ -8,7 +9,14 @@ import * as actionsUtil from "./actions-util";
import * as api from "./api-client";
import { DO_NOT_RETRY_STATUSES } from "./api-client";
import { ActionsEnvVars, RegistryProxyVars } from "./environment";
import { callee, getTestEnv, setupTests } from "./testing-utils";
import { GITHUB_DOTCOM_API_URL, GITHUB_DOTCOM_URL } from "./github";
import {
callee,
getTestEnv,
RecordingLogger,
SAMPLE_DOTCOM_API_DETAILS,
setupTests,
} from "./testing-utils";
import * as util from "./util";
setupTests(test);
@@ -111,103 +119,115 @@ test.serial("getGitHubVersion for GHEC-DR", async (t) => {
t.deepEqual({ type: util.GitHubVariant.GHEC_DR }, gheDotcom);
});
test.serial(
"wrapApiConfigurationError correctly wraps specific configuration errors",
(t) => {
test("wrapApiConfigurationError doesn't wrap errors it isn't supposed to", (t) => {
const unwrappedErrors = [
// We don't reclassify arbitrary errors
const arbitraryError = new Error("arbitrary error");
let res = api.wrapApiConfigurationError(arbitraryError);
t.is(res, arbitraryError);
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),
];
// 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(
for (const unwrappedError of unwrappedErrors) {
const res = api.wrapApiConfigurationError(unwrappedError);
t.is(
res,
new util.ConfigurationError(
"ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest",
),
unwrappedError,
`${util.getErrorMessage(unwrappedError)} should not be wrapped by wrapApiConfigurationError`,
);
}
});
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"),
);
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 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);
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);
t.deepEqual(res, new util.ConfigurationError(tokenSuggestionMessage));
}
});
const notFoundError = new util.HTTPError("Not Found", 404);
res = api.wrapApiConfigurationError(notFoundError);
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 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),
),
);
}
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),
),
);
}
},
);
}
});
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();
@@ -272,3 +292,62 @@ test("makeProxyRequestOptions - returns fetch with custom proxy", async (t) => {
githubUtils.defaults.request,
);
});
test.serial(
"getApiClientWithExternalAuth constructs clients with or without tokens",
(t) => {
t.notThrows(() => {
api.getApiClientWithExternalAuth(SAMPLE_DOTCOM_API_DETAILS);
api.getApiClientWithExternalAuth({
...SAMPLE_DOTCOM_API_DETAILS,
auth: undefined,
});
});
},
);
test("getAuthorizationHeaderFor - returns undefined if there's no token", (t) => {
const logger = new RecordingLogger();
for (const authValue of [undefined, "", " "]) {
const client = new api.InstanceApiClient({
...SAMPLE_DOTCOM_API_DETAILS,
auth: authValue,
});
t.is(
client.getAuthorizationHeaderFor(logger, `${GITHUB_DOTCOM_URL}/github`),
undefined,
);
}
});
test("getAuthorizationHeaderFor - returns header value with token if url is allowed", (t) => {
const logger = new RecordingLogger();
const client = new api.InstanceApiClient({
...SAMPLE_DOTCOM_API_DETAILS,
});
for (const url of [
`${GITHUB_DOTCOM_URL}/github`,
`${GITHUB_DOTCOM_API_URL}/github`,
]) {
t.is(
client.getAuthorizationHeaderFor(logger, url),
`token ${SAMPLE_DOTCOM_API_DETAILS.auth}`,
);
}
});
test("getAuthorizationHeaderFor - returns undefined if url is not allowed", (t) => {
const logger = new RecordingLogger();
const client = new api.InstanceApiClient({
...SAMPLE_DOTCOM_API_DETAILS,
});
for (const url of [
`https://localhost/github`,
`https://api.localhost/github`,
]) {
t.is(client.getAuthorizationHeaderFor(logger, url), undefined);
}
});

View File

@@ -1,5 +1,6 @@
import * as core from "@actions/core";
import * as githubUtils from "@actions/github/lib/utils";
import type { OctokitOptions } from "@octokit/core";
import * as retry from "@octokit/plugin-retry";
import { RequestRequestOptions } from "@octokit/types";
import {
@@ -12,25 +13,34 @@ import {
import type { ActionState } from "./action-common";
import { getActionVersion, getRequiredInput } from "./actions-util";
import {
ActionsEnvVars,
EnvVar,
ReadOnlyEnv,
RegistryProxyVars,
getEnv,
exportEnvVar,
ActionsEnvVars,
} from "./environment";
import {
getCurrentInstance,
getDotcomInstance,
GITHUB_DOTCOM_URL,
parseGitHubUrl,
type GitHubApiCombinedDetails,
type GitHubApiDetails,
} from "./github";
import { Logger } from "./logging";
import { getRepositoryNwo, RepositoryNwo } from "./repository";
import {
asHTTPError,
ConfigurationError,
getRequiredEnvParam,
GITHUB_DOTCOM_URL,
GitHubVariant,
GitHubVersion,
parseGitHubUrl,
parseMatrixInput,
} from "./util";
export type { GitHubApiDetails, GitHubApiCombinedDetails } from "./github";
const GITHUB_ENTERPRISE_VERSION_HEADER = "x-github-enterprise-version";
/**
@@ -42,21 +52,6 @@ const GITHUB_ENTERPRISE_VERSION_HEADER = "x-github-enterprise-version";
*/
export const DO_NOT_RETRY_STATUSES = [400, 410, 422, 451];
export type GitHubApiCombinedDetails = GitHubApiDetails &
GitHubApiExternalRepoDetails;
export interface GitHubApiDetails {
auth: string;
url: string;
apiURL: string | undefined;
}
export interface GitHubApiExternalRepoDetails {
externalRepoAuth?: string;
url: string;
apiURL: string | undefined;
}
/**
* Gets the configuration for the private registry authentication proxy,
* if it is available in the environment.
@@ -127,6 +122,61 @@ export function makeProxyRequestOptions(
/** The type of GitHub API client we use. */
export type ApiClient = InstanceType<typeof githubUtils.GitHub>;
/**
* Encapsulates a {@link GitHubApiCombinedDetails} along with operations which ensure that any credentials
* are only used with the GitHub instance that is represented by the {@link GitHubApiCombinedDetails} value.
*/
export class InstanceApiClient {
private readonly client: ApiClient;
private readonly apiDetails: GitHubApiCombinedDetails;
private readonly authorizationHeader: string | undefined;
constructor(
apiDetails: GitHubApiCombinedDetails,
clientOptions: CreateApiClientOptions = {},
) {
this.apiDetails = apiDetails;
this.client = createApiClientWithDetails(apiDetails, clientOptions);
// Compute the Authorization header value if we have a token.
const token = this.apiDetails.auth?.trim();
if (token !== undefined && token !== "") {
this.authorizationHeader = `token ${token}`;
}
}
/**
* Gets a value for the `Authorization` header for a request to `url`; or `undefined` if the
* `Authorization` header should not be set for `url`.
*
* @param logger The logger to use for debugging messages.
* @param url The URL for which we want to add an `Authorization` header.
*/
public getAuthorizationHeaderFor(
logger: Logger,
url: string,
): string | undefined {
// We don't have to check the `url` if we don't have a token to begin with.
if (this.authorizationHeader === undefined) {
return undefined;
}
// We only want to provide an authorization header if we are downloading
// from the same GitHub instance the Action is running on.
// This avoids leaking Enterprise tokens to dotcom.
if (
url.startsWith(`${this.apiDetails.url}/`) ||
(this.apiDetails.apiURL && url.startsWith(`${this.apiDetails.apiURL}/`))
) {
logger.debug(`Providing an authorization token.`);
return this.authorizationHeader;
}
logger.debug(`Not using an authorization token.`);
return undefined;
}
}
/** Options for `createApiClientWithDetails`. */
interface CreateApiClientOptions {
allowExternal?: boolean;
@@ -138,37 +188,71 @@ function createApiClientWithDetails(
{ allowExternal = false, proxy = undefined }: CreateApiClientOptions = {},
): ApiClient {
const auth =
(allowExternal && apiDetails.externalRepoAuth) || apiDetails.auth;
allowExternal && apiDetails.externalRepoAuth !== undefined
? apiDetails.externalRepoAuth
: apiDetails.auth;
const retryingOctokit = githubUtils.GitHub.plugin(retry.retry);
const requestOptions = makeProxyRequestOptions(proxy);
return new retryingOctokit(
githubUtils.getOctokitOptions(auth, {
baseUrl: apiDetails.apiURL,
userAgent: `CodeQL-Action/${getActionVersion()}`,
log: {
debug: core.debug,
info: core.info,
warn: core.warning,
error: core.error,
},
request: requestOptions,
retry: {
doNotRetry: DO_NOT_RETRY_STATUSES,
},
}),
);
const opts: OctokitOptions = {
auth:
auth !== undefined && auth.trim() !== "" ? `token ${auth}` : undefined,
baseUrl: apiDetails.apiURL,
userAgent: `CodeQL-Action/${getActionVersion()}`,
log: {
debug: core.debug,
info: core.info,
warn: core.warning,
error: core.error,
},
request: requestOptions,
retry: {
doNotRetry: DO_NOT_RETRY_STATUSES,
},
};
return new retryingOctokit(opts);
}
/**
* Gets a `GitHubApiDetails` object describing the GitHub instance we are currently running on.
*
* @param env The environment variables to read.
*/
export function getApiDetails(env: ReadOnlyEnv = getEnv()): GitHubApiDetails {
return {
auth: getRequiredInput("token"),
url: env.getRequired(ActionsEnvVars.GITHUB_SERVER_URL),
apiURL: env.getRequired(ActionsEnvVars.GITHUB_API_URL),
...getCurrentInstance(env),
};
}
export function getApiClient(env: ReadOnlyEnv = getEnv()) {
return createApiClientWithDetails(getApiDetails(env));
/**
* Gets a `GitHubApiDetails` object describing the GitHub Dotcom instance.
*
* @param env The environment variables to read.
*/
export function getDotcomApiDetails(env: ReadOnlyEnv): GitHubApiDetails {
// If we are currently running on dotcom, then just call `getApiDetails` which will
// construct the appropriate `GitHubApiDetails` from the environment and include the
// value of the `token` input. The `token` input relates to the GitHub instance that
// we are running on only. Therefore, if we are not currently running on dotcom,
// then we construct `GitHubApiDetails` without the `token` value and using the
// hard-coded instance and API URLs.
if (env.getRequired(ActionsEnvVars.GITHUB_SERVER_URL) === GITHUB_DOTCOM_URL) {
return getApiDetails(env);
} else {
return {
auth: undefined,
...getDotcomInstance(),
};
}
}
export function getApiClient(
env: ReadOnlyEnv = getEnv(),
apiDetails?: GitHubApiDetails,
) {
return createApiClientWithDetails(apiDetails ?? getApiDetails(env));
}
export function getApiClientWithExternalAuth(
@@ -178,36 +262,6 @@ export function getApiClientWithExternalAuth(
return createApiClientWithDetails(apiDetails, { allowExternal: true, proxy });
}
/**
* Gets a value for the `Authorization` header for a request to `url`; or `undefined` if the
* `Authorization` header should not be set for `url`.
*
* @param logger The logger to use for debugging messages.
* @param apiDetails Details of the GitHub API we are using.
* @param url The URL for which we want to add an `Authorization` header.
*
* @returns The value for the `Authorization` header or `undefined` if it shouldn't be populated.
*/
export function getAuthorizationHeaderFor(
logger: Logger,
apiDetails: GitHubApiDetails,
url: string,
): string | undefined {
// We only want to provide an authorization header if we are downloading
// from the same GitHub instance the Action is running on.
// This avoids leaking Enterprise tokens to dotcom.
if (
url.startsWith(`${apiDetails.url}/`) ||
(apiDetails.apiURL && url.startsWith(`${apiDetails.apiURL}/`))
) {
logger.debug(`Providing an authorization token.`);
return `token ${apiDetails.auth}`;
}
logger.debug(`Not using an authorization token.`);
return undefined;
}
let cachedGitHubVersion: GitHubVersion | undefined = undefined;
export async function getGitHubVersionFromApi(
@@ -219,25 +273,31 @@ export async function getGitHubVersionFromApi(
return { type: GitHubVariant.DOTCOM };
}
// 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();
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();
// 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 };
// 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);
}
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 };
}
/**
@@ -249,9 +309,10 @@ export async function getGitHubVersionFromApi(
*/
export async function getGitHubVersion(): Promise<GitHubVersion> {
if (cachedGitHubVersion === undefined) {
const apiDetails = getApiDetails();
cachedGitHubVersion = await getGitHubVersionFromApi(
getApiClient(),
getApiDetails(),
createApiClientWithDetails(apiDetails),
apiDetails,
);
}
return cachedGitHubVersion;
@@ -309,7 +370,7 @@ export async function getAnalysisKey(): Promise<string> {
const jobName = getRequiredEnvParam("GITHUB_JOB");
analysisKey = `${workflowPath}:${jobName}`;
core.exportVariable(EnvVar.ANALYSIS_KEY, analysisKey);
exportEnvVar(EnvVar.ANALYSIS_KEY, analysisKey);
return analysisKey;
}
@@ -414,7 +475,14 @@ export function getFeatureEnablementError(message: string): string {
return `Please verify that the necessary features are enabled: ${message}`;
}
export function wrapApiConfigurationError(e: unknown) {
/**
* 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 {
const httpError = asHTTPError(e);
if (httpError !== undefined) {
if (

View File

@@ -1 +1 @@
{"maximumVersion":"3.23","minimumVersion":"3.17"}
{"maximumVersion":"3.23","minimumVersion":"3.18"}

View File

@@ -68,7 +68,11 @@ async function sendCompletedStatusReport(
}
}
async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
async function run({
startedAt,
env,
logger,
}: ActionState<["Base", "Env", "Logger"]>) {
// To capture errors appropriately, keep as much code within the try-catch as
// possible, and only use safe functions outside.
@@ -135,7 +139,7 @@ async function run({ startedAt, logger }: ActionState<["Base", "Logger"]>) {
return;
}
core.exportVariable(EnvVar.AUTOBUILD_DID_COMPLETE_SUCCESSFULLY, "true");
env.export(EnvVar.AUTOBUILD_DID_COMPLETE_SUCCESSFULLY, "true");
await sendCompletedStatusReport(config, logger, startedAt, languages ?? []);
}

View File

@@ -1,11 +1,9 @@
import * as core from "@actions/core";
import { getTemporaryDirectory, getWorkflowEventName } from "./actions-util";
import { getGitHubVersion } from "./api-client";
import { CodeQL, getCodeQL } from "./codeql";
import * as configUtils from "./config-utils";
import { DocUrl } from "./doc-url";
import { ActionsEnvVars, EnvVar } from "./environment";
import { ActionsEnvVars, EnvVar, exportEnvVar } from "./environment";
import { Feature, featureConfig, initFeatures } from "./feature-flags";
import { BuiltInLanguage, Language } from "./languages";
import { Logger } from "./logging";
@@ -112,7 +110,7 @@ export async function determineAutobuildLanguages(
return languages;
}
export async function setupCppAutobuild(codeql: CodeQL, logger: Logger) {
export async function setupCppAutobuild(logger: Logger) {
const envVar = featureConfig[Feature.CppDependencyInstallation].envVar;
const featureName = "C++ automatic installation of dependencies";
const gitHubVersion = await getGitHubVersion();
@@ -123,7 +121,7 @@ export async function setupCppAutobuild(codeql: CodeQL, logger: Logger) {
getTemporaryDirectory(),
logger,
);
if (await features.getValue(Feature.CppDependencyInstallation, codeql)) {
if (await features.getValue(Feature.CppDependencyInstallation)) {
// disable autoinstall on self-hosted runners unless explicitly requested
if (
process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] === "self-hosted" &&
@@ -136,16 +134,16 @@ export async function setupCppAutobuild(codeql: CodeQL, logger: Logger) {
: ""
}`,
);
core.exportVariable(envVar, "false");
exportEnvVar(envVar, "false");
} else {
logger.info(
`Enabling ${featureName}. This can be disabled by setting the ${envVar} environment variable to 'false'. See ${DocUrl.DEFINE_ENV_VARIABLES} for more information.`,
);
core.exportVariable(envVar, "true");
exportEnvVar(envVar, "true");
}
} else {
logger.info(`Disabling ${featureName}.`);
core.exportVariable(envVar, "false");
exportEnvVar(envVar, "false");
}
}
@@ -157,7 +155,7 @@ export async function runAutobuild(
logger.startGroup(`Attempting to automatically build ${language} code`);
const codeQL = await getCodeQL(logger, config.codeQLCmd);
if (language === BuiltInLanguage.cpp) {
await setupCppAutobuild(codeQL, logger);
await setupCppAutobuild(logger);
}
if (config.buildMode) {
await codeQL.extractUsingBuildMode(config, language);
@@ -165,7 +163,7 @@ export async function runAutobuild(
await codeQL.runAutobuild(config, language);
}
if (language === BuiltInLanguage.go) {
core.exportVariable(EnvVar.DID_AUTOBUILD_GOLANG, "true");
exportEnvVar(EnvVar.DID_AUTOBUILD_GOLANG, "true");
}
logger.endGroup();
}

View File

@@ -1,7 +1,26 @@
import test from "ava";
import { getCodeQLBundleFromUrl } from "./codeql-bundle";
import { getCodeQLBundleFromUrl, getCodeQLBundleName } from "./codeql-bundle";
import { BuiltInLanguage } from "./languages";
import { BundlePlatform } from "./platform";
test("getCodeQLBundleName returns a per-language bundle name only when a language is specified", (t) => {
t.is(
getCodeQLBundleName("zstd", BundlePlatform.Linux64, BuiltInLanguage.java),
"codeql-bundle-java-linux64.tar.zst",
);
t.is(
getCodeQLBundleName("zstd", BundlePlatform.Linux64),
"codeql-bundle-linux64.tar.zst",
);
});
test("getCodeQLBundleName names the Swift bundle for macOS", (t) => {
t.is(
getCodeQLBundleName("zstd", BundlePlatform.Osx64, BuiltInLanguage.swift),
"codeql-bundle-swift-osx64.tar.zst",
);
});
for (const [assetName, language] of [
["codeql-bundle-java-linux64.tar.zst", BuiltInLanguage.java],

View File

@@ -1,4 +1,7 @@
import type { GitHubApiDetails } from "./github";
import { BuiltInLanguage, parseBuiltInLanguage } from "./languages";
import { BundlePlatform } from "./platform";
import type { CompressionMethod } from "./tar";
/** Describes the contents and location of a downloadable CodeQL bundle. */
export type CodeQLBundle =
@@ -11,6 +14,44 @@ export type CodeQLBundle =
combinedBundleURL?: string;
};
/** A resolved download, including its bundle identity and version. */
export interface CodeQLDownloadSource {
/** Distinguishes downloads from local archives and cached installations. */
sourceType: "download";
/** Information about the GitHub instance that contains the asset. */
apiDetails: GitHubApiDetails;
/** The bundle to download. */
bundle: CodeQLBundle;
/** The compression format of the bundle archive. */
compressionMethod: CompressionMethod;
/** Bundle version of the tools, if known. */
bundleVersion?: string;
/** Requested CLI version, if known. */
cliVersion?: string;
/** Resolved version for telemetry, independent of whether the bundle can be cached. */
toolsVersion: string;
}
/** Returns the exact bundle asset name for a platform and optional language. */
export function getCodeQLBundleName(
compressionMethod: CompressionMethod,
platform: BundlePlatform | undefined,
language?: BuiltInLanguage,
): string {
const extensions: Record<CompressionMethod, string> = {
gzip: ".tar.gz",
zstd: ".tar.zst",
};
const extension = extensions[compressionMethod];
if (platform === undefined) {
return `codeql-bundle${extension}`;
}
if (language !== undefined) {
return `codeql-bundle-${language}-${platform}${extension}`;
}
return `codeql-bundle-${platform}${extension}`;
}
const PER_LANGUAGE_BUNDLE_NAME =
/^codeql-bundle-(.+)-(?:linux64|osx64|win64)\.tar\.(?:gz|zst)$/;

View File

@@ -34,6 +34,7 @@ import {
makeVersionInfo,
createTestConfig,
makeMacro,
mockApiDetails,
} from "./testing-utils";
import { ToolsDownloadStatusReport } from "./tools-download";
import * as util from "./util";
@@ -99,6 +100,7 @@ async function installIntoToolcache({
? { enabledVersions: [{ cliVersion, tagName }] }
: SAMPLE_DEFAULT_CLI_VERSION,
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
createFeatures([]),
getRunnerLogger(true),
@@ -125,19 +127,6 @@ function mockReleaseApi({
});
}
function mockApiDetails(apiDetails: GitHubApiDetails) {
// This is a workaround to mock `api.getApiDetails()` since it doesn't seem to be possible to
// mock this directly. The difficulty is that `getApiDetails()` is called locally in
// `api-client.ts`, but `sinon.stub(api, "getApiDetails")` only affects calls to
// `getApiDetails()` via an imported `api` module.
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("token")
.returns(apiDetails.auth);
process.env["GITHUB_SERVER_URL"] = apiDetails.url;
process.env["GITHUB_API_URL"] = apiDetails.apiURL || "";
}
async function stubCodeql(): Promise<codeql.CodeQL> {
const codeqlObject = await codeql.getCodeQLForTesting();
sinon.stub(codeqlObject, "getVersion").resolves(makeVersionInfo("2.17.6"));
@@ -172,6 +161,7 @@ test.serial(
util.GitHubVariant.DOTCOM,
SAMPLE_DEFAULT_CLI_VERSION,
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),
@@ -207,6 +197,7 @@ test.serial(
util.GitHubVariant.DOTCOM,
SAMPLE_DEFAULT_CLI_VERSION,
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),
@@ -246,6 +237,7 @@ test.serial(
util.GitHubVariant.DOTCOM,
SAMPLE_DEFAULT_CLI_VERSION,
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),
@@ -286,6 +278,7 @@ for (const { cliVersion, tagName, expectedToolcacheVersion } of [
async (t) => {
await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
mockApiDetails(SAMPLE_DOTCOM_API_DETAILS);
const result = await installIntoToolcache({
cliVersion,
@@ -355,6 +348,7 @@ for (const {
util.GitHubVariant.DOTCOM,
SAMPLE_DEFAULT_CLI_VERSION,
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),
@@ -397,6 +391,7 @@ for (const toolcacheVersion of [
util.GitHubVariant.DOTCOM,
SAMPLE_DEFAULT_CLI_VERSION,
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),
@@ -441,6 +436,7 @@ test.serial(
],
},
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),
@@ -463,6 +459,7 @@ test.serial(
await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
mockApiDetails(SAMPLE_DOTCOM_API_DETAILS);
await installIntoToolcache({
tagName: "codeql-bundle-20200601",
@@ -487,6 +484,7 @@ test.serial(
],
},
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),
@@ -509,6 +507,7 @@ test.serial(
await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
mockApiDetails(SAMPLE_DOTCOM_API_DETAILS);
await installIntoToolcache({
tagName: "codeql-bundle-20200601",
@@ -526,6 +525,7 @@ test.serial(
util.GitHubVariant.DOTCOM,
SAMPLE_DEFAULT_CLI_VERSION,
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),
@@ -567,6 +567,7 @@ test.serial(
util.GitHubVariant.DOTCOM,
SAMPLE_DEFAULT_CLI_VERSION,
undefined, // rawLanguages
undefined, // otherLanguagePacksReason
false, // useOverlayAwareDefaultCliVersion
features,
getRunnerLogger(true),

View File

@@ -15,9 +15,10 @@ import * as api from "./api-client";
import * as outputCache from "./cli/output-cache";
import type { VersionInfo } from "./cli/types";
import { CliError, wrapCliConfigurationError } from "./cli-errors";
import type { ActionConfig } from "./config/action-config";
import { appendExtraQueryExclusions, type Config } from "./config-utils";
import { DocUrl } from "./doc-url";
import { EnvVar, getEnv } from "./environment";
import { EnvVar, getEnv, exportEnvVar } from "./environment";
import {
CodeQLDefaultVersionInfo,
Feature,
@@ -197,7 +198,7 @@ export interface CodeQL {
diagnosticsExport(
sarifFile: string,
automationDetailsId: string | undefined,
config: Config,
config: ActionConfig<"tempDir">,
): Promise<void>;
/** Get the location of an extractor for the specified language. */
resolveExtractor(language: Language): Promise<string>;
@@ -253,22 +254,22 @@ let cachedCodeQL: CodeQL | undefined = undefined;
* The version flags below can be used to conditionally enable certain features
* on versions newer than this.
*/
const CODEQL_MINIMUM_VERSION = "2.19.4";
const CODEQL_MINIMUM_VERSION = "2.20.7";
/**
* This version will shortly become the oldest version of CodeQL that the Action will run with.
*/
const CODEQL_NEXT_MINIMUM_VERSION = "2.20.7";
const CODEQL_NEXT_MINIMUM_VERSION = "2.21.3";
/**
* This is the version of GHES that was most recently deprecated.
*/
const GHES_VERSION_MOST_RECENTLY_DEPRECATED = "3.16";
const GHES_VERSION_MOST_RECENTLY_DEPRECATED = "3.17";
/**
* This is the deprecation date for the version of GHES that was most recently deprecated.
*/
const GHES_MOST_RECENT_DEPRECATION_DATE = "2026-07-01";
const GHES_MOST_RECENT_DEPRECATION_DATE = "2026-09-24";
/** The CLI verbosity level to use for extraction in debug mode. */
const EXTRACTION_DEBUG_MODE_VERBOSITY = "progress++";
@@ -302,6 +303,9 @@ export function isDiskConfigurationError(e: unknown): boolean {
* @param variant
* @param defaultCliVersion
* @param rawLanguages Raw set of languages.
* @param otherLanguagePacksReason Why the CodeQL CLI may need packs for languages other than
* `rawLanguages`, or `undefined` if it won't. If defined, the combined bundle is used. See
* `PerLanguageBundleOptions.otherLanguagePacksReason`.
* @param useOverlayAwareDefaultCliVersion Whether to select an overlay-aware default CLI version.
* @param features Information about the features that are enabled.
* @param logger
@@ -316,6 +320,7 @@ export async function setupCodeQL(
variant: util.GitHubVariant,
defaultCliVersion: CodeQLDefaultVersionInfo,
rawLanguages: string[] | undefined,
otherLanguagePacksReason: string | undefined,
useOverlayAwareDefaultCliVersion: boolean,
features: FeatureEnablement,
logger: Logger,
@@ -339,6 +344,7 @@ export async function setupCodeQL(
variant,
defaultCliVersion,
rawLanguages,
otherLanguagePacksReason,
useOverlayAwareDefaultCliVersion,
features,
logger,
@@ -908,7 +914,7 @@ async function getCodeQLForCmd(
async diagnosticsExport(
sarifFile: string,
automationDetailsId: string | undefined,
config: Config,
config: ActionConfig<"tempDir">,
): Promise<void> {
const args = [
"diagnostics",
@@ -937,6 +943,7 @@ async function getCodeQLForCmd(
"--format=json",
`--language=${language}`,
"--extractor-include-aliases",
"-J-XX:-UsePerfData",
...getExtraOptionsFromEnv(["resolve", "extractor"]),
],
{
@@ -951,7 +958,13 @@ async function getCodeQLForCmd(
},
},
).exec();
return JSON.parse(extractorPath) as string;
try {
return JSON.parse(extractorPath) as string;
} catch (err) {
throw new Error(
`Failed to parse extractor path for '${language}' from CLI: ${getErrorMessage(err)}\nOutput was: ${extractorPath}`,
);
}
},
async resolveQueriesStartingPacks(queries: string[]): Promise<string[]> {
const codeqlArgs = [
@@ -1042,7 +1055,7 @@ async function getCodeQLForCmd(
}' by 'github/codeql-action/*@v${getActionVersion()}' in your code scanning workflow to ` +
"continue using this version of the CodeQL Action.",
);
core.exportVariable(EnvVar.SUPPRESS_DEPRECATED_SOON_WARNING, "true");
exportEnvVar(EnvVar.SUPPRESS_DEPRECATED_SOON_WARNING, "true");
}
return codeql;
}
@@ -1225,7 +1238,9 @@ export async function getTrapCachingExtractorConfigArgsForLang(
*
* This will not exist if the configuration is being parsed in the Action.
*/
function getGeneratedCodeScanningConfigPath(config: Config): string {
function getGeneratedCodeScanningConfigPath(
config: ActionConfig<"tempDir">,
): string {
return path.resolve(config.tempDir, "user-config.yaml");
}

View File

@@ -473,6 +473,12 @@ const simpleConfigFileContents = `
queries:
- uses: ./foo_file`;
/** The configuration in `simpleConfigFileContents`. */
const simpleConfigInput: UserConfig = {
name: "my config",
queries: [{ uses: "./foo_file" }],
};
/** A less minimal configuration file. */
const otherConfigFileContents = `
name: my config
@@ -558,16 +564,14 @@ test.serial(
tempDir,
);
const configInput = `
name: my config
queries:
- uses: ./foo
packs:
javascript:
- a/b@1.2.3
python:
- c/d@1.2.3
`;
const configInput: UserConfig = {
name: "my config",
queries: [{ uses: "./foo" }],
packs: {
javascript: ["a/b@1.2.3"],
python: ["c/d@1.2.3"],
},
};
fs.mkdirSync(path.join(tempDir, "foo"));
@@ -598,7 +602,16 @@ test.serial(
}),
);
t.deepEqual(config.originalUserInput, yaml.load(configInput));
// Compare with a separate object rather than `configInput` itself, so that the test catches
// changes made to the input in place.
t.deepEqual(config.originalUserInput, {
name: "my config",
queries: [{ uses: "./foo" }],
packs: {
javascript: ["a/b@1.2.3"],
python: ["c/d@1.2.3"],
},
});
});
},
);
@@ -2413,7 +2426,7 @@ test("determineUserConfig - loads config input", async (t) => {
const expectedConfigPath = configUtils.userConfigFromActionPath(tmpDir);
const inputs = createTestInitConfigInputs({
configInput: simpleConfigFileContents,
configInput: simpleConfigInput,
configFile: undefined,
workspacePath: tmpDir,
});
@@ -2423,17 +2436,15 @@ test("determineUserConfig - loads config input", async (t) => {
await target
// The input source and path of the generated config file should have been logged.
.logs(
t,
"Using config from action input:",
`Using configuration file: ${expectedConfigPath}`,
)
// The message about no configuration input and
// the warning about both inputs should not have been logged.
.logs(t, `Using config from action input: ${expectedConfigPath}`)
// The message about no configuration input and the warning about both inputs should not have
// been logged. The generated config file isn't loaded, since the `config` input has already
// been parsed.
.notLogs(
t,
"No configuration file was provided",
"Both a config file and config input were provided. Ignoring config file.",
`Using configuration file: ${expectedConfigPath}`,
)
// The loaded configuration should match `simpleConfigFileContents`.
.passes(t.deepEqual, {
@@ -2452,7 +2463,7 @@ test("determineUserConfig - ignores config file input when both specified", asyn
const expectedConfigPath = configUtils.userConfigFromActionPath(tmpDir);
const inputs = createTestInitConfigInputs({
configInput: simpleConfigFileContents,
configInput: simpleConfigInput,
configFile: configFilePath,
workspacePath: tmpDir,
});
@@ -2466,10 +2477,14 @@ test("determineUserConfig - ignores config file input when both specified", asyn
.logs(
t,
`Using config from action input: ${expectedConfigPath}`,
`Using configuration file: ${expectedConfigPath}`,
"Both a config file and config input were provided. Ignoring config file.",
)
.notLogs(t, "No configuration file was provided")
// The generated config file isn't loaded, since the `config` input has already been parsed.
.notLogs(
t,
"No configuration file was provided",
`Using configuration file: ${expectedConfigPath}`,
)
// The loaded configuration should match `simpleConfigFileContents`.
.passes(t.deepEqual, {
name: "my config",
@@ -2482,11 +2497,14 @@ test("determineUserConfig - ignores config file input when both specified", asyn
});
/** A `config` input that we might get from Default Setup. */
const defaultSetupConfigInput = `
threat-models: [local, remote]
default-setup:
org:
model-packs: [foo, bar]`;
const defaultSetupConfigInput: UserConfig = {
"threat-models": ["local", "remote"],
"default-setup": {
org: {
"model-packs": ["foo", "bar"],
},
},
};
test("determineUserConfig - merges configs if FF is enabled in Default Setup", async (t) => {
await withTmpDir(async (tmpDir) => {
@@ -2555,7 +2573,7 @@ test("determineUserConfig - ignores config file input in Default Setup if FF is
.withArgs(
tmpDir,
createTestInitConfigInputs({
configInput: simpleConfigFileContents,
configInput: simpleConfigInput,
configFile: configFilePath,
workspacePath: tmpDir,
}),
@@ -2565,10 +2583,14 @@ test("determineUserConfig - ignores config file input in Default Setup if FF is
.logs(
t,
`Using config from action input: ${expectedConfigPath}`,
`Using configuration file: ${expectedConfigPath}`,
"Both a config file and config input were provided. Ignoring config file.",
)
.notLogs(t, "No configuration file was provided")
// The generated config file isn't loaded, since the `config` input has already been parsed.
.notLogs(
t,
"No configuration file was provided",
`Using configuration file: ${expectedConfigPath}`,
)
.passes(t.deepEqual, {
name: "my config",
queries: [{ uses: "./foo_file" }],
@@ -2587,7 +2609,7 @@ test("determineUserConfig - ignores config file input outside Default Setup if F
.withArgs(
tmpDir,
createTestInitConfigInputs({
configInput: simpleConfigFileContents,
configInput: simpleConfigInput,
configFile: configFilePath,
workspacePath: tmpDir,
}),
@@ -2597,10 +2619,14 @@ test("determineUserConfig - ignores config file input outside Default Setup if F
.logs(
t,
`Using config from action input: ${expectedConfigPath}`,
`Using configuration file: ${expectedConfigPath}`,
"Both a config file and config input were provided. Ignoring config file.",
)
.notLogs(t, "No configuration file was provided")
// The generated config file isn't loaded, since the `config` input has already been parsed.
.notLogs(
t,
"No configuration file was provided",
`Using configuration file: ${expectedConfigPath}`,
)
.passes(t.deepEqual, {
name: "my config",
queries: [{ uses: "./foo_file" }],

View File

@@ -2,7 +2,6 @@ import * as fs from "fs";
import * as path from "path";
import { performance } from "perf_hooks";
import * as core from "@actions/core";
import * as yaml from "js-yaml";
import { ActionState } from "./action-common";
@@ -22,7 +21,11 @@ import {
import * as api from "./api-client";
import { getCachingKind } from "./caching-utils";
import { type CodeQL } from "./codeql";
import { type Config } from "./config/action-config";
import {
type AbortedInitConfig,
type ActionConfig,
type Config,
} from "./config/action-config";
import {
calculateAugmentation,
ExcludeQueryFilter,
@@ -46,7 +49,7 @@ import {
makeTelemetryDiagnostic,
} from "./diagnostics";
import { prepareDiffInformedAnalysis } from "./diff-informed-analysis-utils";
import { EnvVar } from "./environment";
import { EnvVar, exportEnvVar } from "./environment";
import * as errorMessages from "./error-messages";
import { Feature, FeatureEnablement, FeatureWithoutCLI } from "./feature-flags";
import {
@@ -72,6 +75,7 @@ import {
import { OverlayDatabaseMode } from "./overlay/overlay-database-mode";
import { shouldSkipOverlayAnalysis } from "./overlay/status";
import { RepositoryNwo } from "./repository";
import { ActionName } from "./status-report";
import { ToolsFeature } from "./tools-features";
import { downloadTrapCaches } from "./trap-caching";
import {
@@ -337,7 +341,8 @@ export interface InitConfigInputs {
packsInput: string | undefined;
configFile: string | undefined;
dbLocation: string | undefined;
configInput: string | undefined;
/** The configuration from the `config` input. */
configInput: UserConfig | undefined;
buildModeInput: string | undefined;
ramInput: string | undefined;
dependencyCachingEnabled: string | undefined;
@@ -964,10 +969,10 @@ async function setCppTrapCachingEnvironmentVariables(
);
} else if (config.trapCaches[BuiltInLanguage.cpp]) {
logger.info("Enabling TRAP caching for C/C++.");
core.exportVariable(envVar, "true");
exportEnvVar(envVar, "true");
} else {
logger.debug(`Disabling TRAP caching for C/C++.`);
core.exportVariable(envVar, "false");
exportEnvVar(envVar, "false");
}
}
}
@@ -1057,17 +1062,13 @@ export async function determineUserConfig(
tempDir: string,
inputs: InitConfigInputs,
): Promise<UserConfig> {
const validateConfig = await action.features.getValue(
Feature.ValidateDbConfig,
);
// We have the following cases:
// 1. A `config` or `config-file` input is provided, but not both: use the provided one.
// 2. Both are provided and we are in an advanced workflow: ignore the `config-file` input.
// 3. Both are provided and we are in Default Setup: the `config` input uses a limited
// set of options, which are supported by `mergeDefaultSetupAndUserConfigs`,
// and we merge the two configs.
if (inputs.configInput) {
if (inputs.configInput !== undefined) {
const computedConfigPath = userConfigFromActionPath(tempDir);
// Get a function which enables us to determine whether the FF that allows us to
@@ -1084,12 +1085,6 @@ export async function determineUserConfig(
) {
// If the FF is enabled and we are in Default Setup, combine the supported
// configuration file properties and write the result to disk.
const fromConfigInput = parseUserConfig(
action.logger,
"`config` input",
inputs.configInput,
validateConfig,
);
const fromConfigFile = await loadUserConfig(
action,
inputs.configFile,
@@ -1102,7 +1097,7 @@ export async function determineUserConfig(
// the CLI or other CodeQL Action steps.
const mergedConfig = mergeDefaultSetupAndUserConfigs(
action.logger,
fromConfigInput,
inputs.configInput,
fromConfigFile,
);
fs.writeFileSync(computedConfigPath, yaml.dump(mergedConfig));
@@ -1122,12 +1117,13 @@ export async function determineUserConfig(
);
}
// Write the `config` input straight to disk.
fs.writeFileSync(computedConfigPath, inputs.configInput);
// Write the `config` input to disk without merging it with a configuration file.
fs.writeFileSync(computedConfigPath, yaml.dump(inputs.configInput));
inputs.configFile = computedConfigPath;
action.logger.debug(
`Using config from action input: ${inputs.configFile}`,
);
return inputs.configInput;
}
}
@@ -1388,31 +1384,86 @@ export function getPathToParsedConfigFile(tempDir: string): string {
return path.join(tempDir, "config");
}
function getPathToFailedConfigFile(tempDir: string): string {
return path.join(tempDir, "failed-config");
}
/**
* Store the given config to the path returned from getPathToParsedConfigFile.
* Writes {@link config} to {@link configFilePath}.
*
* This function is not intended to be called, other than by
* {@link saveConfig} and {@link saveAbortedInitConfig} below.
*/
export async function saveConfig(config: Config, logger: Logger) {
function saveConfigFile(
logger: Logger,
configFilePath: string,
config: Partial<Config>,
) {
const configString = JSON.stringify(config);
const configFile = getPathToParsedConfigFile(config.tempDir);
fs.mkdirSync(path.dirname(configFile), { recursive: true });
fs.writeFileSync(configFile, configString, "utf8");
fs.mkdirSync(path.dirname(configFilePath), { recursive: true });
fs.writeFileSync(configFilePath, configString, "utf8");
logger.debug("Saved config:");
logger.debug(configString);
}
/**
* Get the config that has been saved to the given temp dir.
* If the config could not be found then returns undefined.
* Store the given config to the path returned from getPathToParsedConfigFile.
*/
export async function getConfig(
tempDir: string,
export async function saveConfig(config: Config, logger: Logger) {
const configFile = getPathToParsedConfigFile(config.tempDir);
saveConfigFile(logger, configFile, config);
}
/**
* Store parts of {@link config} as a failed configuration file.
*
* The file will only contain parts of {@link config} that are relevant to
* the `init-post` step in the workflow.
*/
export function saveAbortedInitConfig(
action: ActionState<["Base", "Logger"]>,
config: Config,
) {
// Should only be called by init.
if (action.name !== ActionName.Init) {
throw new Error(
`Internal error: 'saveAbortedInitConfig' should only be called by '${ActionName.Init}', but was called by '${action.name}'.`,
);
}
// Create a copy of the input `Config` that only contains the keys we want.
const failedConfig: AbortedInitConfig = {
version: config.version,
tempDir: config.tempDir,
codeQLCmd: config.codeQLCmd,
debugMode: config.debugMode,
gitHubVersion: config.gitHubVersion,
languages: config.languages,
analysisKinds: config.analysisKinds,
};
action.logger.debug(`Saving config for failed init step.`);
saveConfigFile(
action.logger,
getPathToFailedConfigFile(config.tempDir),
failedConfig,
);
}
/**
* Attempts to read a {@link Config} from {@link configFilePath}.
*
* This function is not intended to be called, other than by
* {@link getConfig} and {@link getAbortedInitConfig} below.
*/
function readConfigFile(
logger: Logger,
): Promise<Config | undefined> {
const configFile = getPathToParsedConfigFile(tempDir);
if (!fs.existsSync(configFile)) {
configFilePath: string,
): Config | undefined {
if (!fs.existsSync(configFilePath)) {
return undefined;
}
const configString = fs.readFileSync(configFile, "utf8");
const configString = fs.readFileSync(configFilePath, "utf8");
logger.debug("Loaded config:");
logger.debug(configString);
@@ -1425,13 +1476,50 @@ export async function getConfig(
}
if (config.version !== getActionVersion()) {
throw new ConfigurationError(
`Loaded a configuration file for version '${config.version}', but running version '${getActionVersion()}'`,
[
`Loaded a configuration file for version '${config.version}', but running version '${getActionVersion()}'.`,
"All steps in a workflow that use `github/codeql-action` must use the same version to work correctly.",
"If you are using Dependabot to manage dependency updates, you can configure a dependency group to update all `github/codeql-action` steps at the same time.",
"For more information, see https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#groups--",
].join(" "),
);
}
return config as Config;
}
/**
* Get the config that has been saved to the given temp dir.
* If the config could not be found then returns undefined.
*/
export async function getConfig(
tempDir: string,
logger: Logger,
): Promise<Config | undefined> {
const configFile = getPathToParsedConfigFile(tempDir);
return readConfigFile(logger, configFile);
}
/**
* Loads a {@link AbortedInitConfig} from a failed `init` step if it exists.
*
* The result will only contain parts of a {@link Config} that are relevant to
* the `init-post` step in the workflow.
*/
export function getAbortedInitConfig(
action: ActionState<["Base", "Logger"]>,
tempDir: string,
): AbortedInitConfig | undefined {
// Only intended to be called by the `init-post` action.
if (action.name !== ActionName.InitPost) {
throw new Error(
`Internal error: 'getAbortedInitConfig' should only be called by '${ActionName.InitPost}', but was called by '${action.name}'.`,
);
}
return readConfigFile(action.logger, getPathToFailedConfigFile(tempDir));
}
/**
* Generate a `qlconfig.yml` file from the `registries` input.
* This file is used by the CodeQL CLI to list the registries to use for each
@@ -1622,21 +1710,27 @@ export function appendExtraQueryExclusions(
/**
* Returns `true` if Code Scanning analysis is enabled, or `false` if not.
*/
export function isCodeScanningEnabled(config: Config): boolean {
export function isCodeScanningEnabled(
config: ActionConfig<"analysisKinds">,
): boolean {
return config.analysisKinds.includes(AnalysisKind.CodeScanning);
}
/**
* Returns `true` if Code Quality analysis is enabled, or `false` if not.
*/
export function isCodeQualityEnabled(config: Config): boolean {
export function isCodeQualityEnabled(
config: ActionConfig<"analysisKinds">,
): boolean {
return config.analysisKinds.includes(AnalysisKind.CodeQuality);
}
/**
* Returns `true` if Code Scanning Risk Assessment analysis is enabled, or `false` if not.
*/
export function isRiskAssessmentEnabled(config: Config): boolean {
export function isRiskAssessmentEnabled(
config: ActionConfig<"analysisKinds">,
): boolean {
return config.analysisKinds.includes(AnalysisKind.RiskAssessment);
}

View File

@@ -126,3 +126,38 @@ export interface Config {
*/
enableFileCoverageInformation: boolean;
}
/** Properties available in `Config`. */
export type ActionConfigProperties = keyof Config;
/**
* The CodeQL Action configuration state that is persisted
* between steps of the CodeQL Action in a CodeQL workflow.
*
* By default, this is equivalent to `Config`. By explicitly
* providing required property names for `T` this can be restricted
* to requiring only those. For example, in `ActionConfig<"codeQLCmd">`
* all properties except `codeqlCmd` are optional.
*/
export type ActionConfig<
T extends ActionConfigProperties = ActionConfigProperties,
> = Partial<Config> & Pick<Config, T>;
/** Helper function to check whether `config` has `key` to narrow the type of `config`. */
export function hasConfigKey<Key extends ActionConfigProperties>(
config: Partial<Config>,
key: Key,
): config is ActionConfig<Key> {
return config[key] !== undefined;
}
/** A minimal configuration that we can make available even when `init` aborts. */
export type AbortedInitConfig = ActionConfig<
| "version"
| "tempDir"
| "gitHubVersion"
| "debugMode"
| "languages"
| "analysisKinds"
| "codeQLCmd"
>;

View File

@@ -625,3 +625,73 @@ test("mergeDefaultSetupAndUserConfigs - warns about invalid keys from Default Se
`Invalid keys in Default Setup configuration: ${expectedInvalidKeys}`,
]);
});
/** Parses `contents` as a configuration without validating it. */
function parseUnvalidatedConfig(contents: string): dbConfig.UserConfig {
return dbConfig.parseUserConfig(
getRunnerLogger(true),
"test",
contents,
false,
);
}
test("matchesDefaultSetupConfigSchema - returns true for configurations that only use Default Setup properties", (t) => {
for (const contents of [
[
"default-setup:",
" org:",
" model-packs: [ github/immutable-actions-list@0.0.1 ]",
"threat-models: [ ]",
].join("\n"),
"threat-models: [ local ]",
"{}",
]) {
t.true(
dbConfig.matchesDefaultSetupConfigSchema(
parseUnvalidatedConfig(contents),
),
contents,
);
}
});
test("matchesDefaultSetupConfigSchema - returns false for configurations that use other properties", (t) => {
for (const contents of [
"queries: [ { uses: ./queries/show_ifs.ql } ]",
"paths-ignore: [ tests ]",
"default-setup: { org: { model-packs: [], queries: [] } }",
]) {
t.false(
dbConfig.matchesDefaultSetupConfigSchema(
parseUnvalidatedConfig(contents),
),
contents,
);
}
});
test("matchesDefaultSetupConfigSchema - returns false for invalid Default Setup properties", (t) => {
for (const contents of [
"threat-models: local",
"default-setup: { org: { model-packs: [ 1 ] } }",
]) {
t.false(
dbConfig.matchesDefaultSetupConfigSchema(
parseUnvalidatedConfig(contents),
),
contents,
);
}
});
test("matchesDefaultSetupConfigSchema - returns false for configurations that aren't mappings", (t) => {
for (const contents of ["- threat-models", "local", "null"]) {
t.false(
dbConfig.matchesDefaultSetupConfigSchema(
parseUnvalidatedConfig(contents),
),
contents,
);
}
});

View File

@@ -33,6 +33,15 @@ export interface QuerySpec {
uses: string;
}
// 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",
]);
const ORG_SCHEMA = {
/** An array of model pack names. */
"model-packs": json.optional(json.array(json.string)),
@@ -77,7 +86,11 @@ export interface UserConfig {
"default-setup"?: DefaultSetupConfig;
}
/** A subset of the `UserConfig` schema that is used by Default Setup. */
/**
* A subset of the `UserConfig` schema that is known to be used by Default Setup. None of these
* properties may add queries, since a per-language CodeQL bundle can be used with a `config` input
* that only sets them.
*/
const DEFAULT_SETUP_CONFIG_SCHEMA = {
"threat-models": json.optional(json.array(json.string)),
"default-setup": json.optional<DefaultSetupConfig>(
@@ -85,6 +98,24 @@ const DEFAULT_SETUP_CONFIG_SCHEMA = {
),
} as const satisfies json.Schema;
/**
* Returns whether `config` matches what we expect Default Setup to send in the `config` input: a
* mapping that only sets properties in `DEFAULT_SETUP_CONFIG_SCHEMA`, with values of the expected
* types.
*/
export function matchesDefaultSetupConfigSchema(config: UserConfig): boolean {
// Unless validation is enabled, `parseUserConfig` doesn't check that the YAML is a mapping.
if (!json.isObject(config)) {
return false;
}
const result = json.checkSchema(
DEFAULT_SETUP_CONFIG_SCHEMA,
config as json.UnvalidatedObject<any>,
);
// `valid` doesn't account for unknown properties.
return result.valid && result.unknownKeys.length === 0;
}
/**
* Merges supported properties from two configuration files. This is intended only for
* use with merging the `config` input provided by Default Setup with a potentially
@@ -437,63 +468,60 @@ export async function calculateAugmentation(
languages,
packsInputCombines,
);
const queriesInputCombines = shouldCombine(rawQueriesInput);
const queriesInput = parseQueriesFromInput(
rawQueriesInput,
queriesInputCombines,
const queries = parseQueriesFromInput(rawQueriesInput);
const repoPropertyQueries = parseQueriesFromInput(
repositoryProperties[RepositoryPropertyName.EXTRA_QUERIES],
RepositoryPropertyName.EXTRA_QUERIES,
);
const repoExtraQueries =
repositoryProperties[RepositoryPropertyName.EXTRA_QUERIES];
const repoExtraQueriesCombines = shouldCombine(repoExtraQueries);
const repoPropertyQueries = {
combines: repoExtraQueriesCombines,
input: parseQueriesFromInput(
repoExtraQueries,
repoExtraQueriesCombines,
new ConfigurationError(
errorMessages.getRepoPropertyError(
RepositoryPropertyName.EXTRA_QUERIES,
errorMessages.getEmptyCombinesError(),
),
),
),
};
return {
packsInputCombines,
packsInput: packsInput?.[languages[0]],
queriesInput,
queriesInputCombines,
queriesInput: queries.input,
queriesInputCombines: queries.combines,
repoPropertyQueries,
};
}
function parseQueriesFromInput(
rawQueriesInput: string | undefined,
queriesInputCombines: boolean,
errorToThrow?: ConfigurationError,
) {
if (!rawQueriesInput) {
return undefined;
/**
* Parses a comma-separated list of queries, which may have a '+' prefix. Entries aren't validated,
* so an empty entry becomes `{ uses: "" }`.
*
* @param value The list of queries.
* @param repositoryProperty The repository property that `value` comes from, if any. Error messages
* refer to this property, or to the `queries` input if no property is given.
* @returns An `Augmentation` containing the parsed queries and whether `value` has a '+' prefix.
* The queries are `undefined` if `value` is unset or empty.
* @throws A `ConfigurationError` if `value` is a '+' with no queries after it.
*/
export function parseQueriesFromInput(
value: string | undefined,
repositoryProperty?: RepositoryPropertyName,
): Augmentation<QuerySpec[]> {
if (!value) {
return { combines: false, input: undefined };
}
const trimmedInput = queriesInputCombines
? rawQueriesInput.trim().slice(1).trim()
: (rawQueriesInput?.trim() ?? "");
if (queriesInputCombines && trimmedInput.length === 0) {
if (errorToThrow) {
throw errorToThrow;
}
const combines = shouldCombine(value);
const trimmedInput = combines ? value.trim().slice(1).trim() : value.trim();
if (combines && trimmedInput.length === 0) {
throw new ConfigurationError(
errorMessages.getConfigFilePropertyError(
undefined,
"queries",
"A '+' was used in the 'queries' input to specify that you wished to add some packs to your CodeQL analysis. However, no packs were specified. Please either remove the '+' or specify some packs.",
),
repositoryProperty !== undefined
? errorMessages.getRepoPropertyError(
repositoryProperty,
errorMessages.getEmptyCombinesError(),
)
: errorMessages.getConfigFilePropertyError(
undefined,
"queries",
"A '+' was used in the 'queries' input to specify that you wished to add some packs to your CodeQL analysis. However, no packs were specified. Please either remove the '+' or specify some packs.",
),
);
}
return trimmedInput.split(",").map((query) => ({ uses: query.trim() }));
return {
combines,
input: trimmedInput.split(",").map((query) => ({ uses: query.trim() })),
};
}
/**
@@ -610,11 +638,13 @@ export function generateCodeScanningConfig(
* Attempts to parse `contents` into a `UserConfig` value.
*
* @param logger The logger to use.
* @param pathInput The path to the file where `contents` was obtained from, for use in error messages.
* @param contents The string contents of a YAML file to try and parse as a `UserConfig`.
* @param validateConfig Whether to validate the configuration file against the schema.
* @returns The `UserConfig` corresponding to `contents`, if parsing was successful.
* @throws A `ConfigurationError` if parsing failed.
* @param pathInput Where `contents` came from, such as the path to a file, for use in error messages.
* @param contents The YAML to try and parse as a `UserConfig`.
* @param validateConfig Whether to validate the configuration against the schema.
* @returns The `UserConfig` corresponding to `contents`, if parsing was successful. Unless
* `validateConfig` is set, the result might not be a mapping.
* @throws A `ConfigurationError` if `contents` isn't valid YAML or, when `validateConfig` is set,
* isn't a valid configuration.
*/
export function parseUserConfig(
logger: Logger,

View File

@@ -20,8 +20,9 @@ import {
checkExpectedLogMessages,
createFeatures,
createTestConfig,
getRecordingLogger,
LoggedMessage,
getTestEnv,
initAllState,
RecordingLogger,
setupActionsVars,
setupTests,
} from "./testing-utils";
@@ -90,23 +91,24 @@ test.serial(
"Abort database upload if 'upload-database' input set to false",
async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("false");
sinon.stub(gitUtils, "isAnalyzingDefaultBranch").resolves(true);
const loggedMessages: LoggedMessage[] = [];
const logger = new RecordingLogger();
await cleanupAndUploadDatabases(
initAllState({ env, logger }),
testRepoName,
getCodeQL(),
getTestConfig(tmpDir),
testApiDetails,
createFeatures([]),
getRecordingLogger(loggedMessages),
"",
);
checkExpectedLogMessages(t, loggedMessages, [
checkExpectedLogMessages(t, logger.messages, [
"Database upload disabled in workflow. Skipping upload.",
]);
});
@@ -117,7 +119,8 @@ test.serial(
"Abort database upload if 'analysis-kinds: code-scanning' is not enabled",
async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -126,8 +129,9 @@ test.serial(
await mockHttpRequests(201);
const loggedMessages: LoggedMessage[] = [];
const logger = new RecordingLogger();
await cleanupAndUploadDatabases(
initAllState({ env, logger }),
testRepoName,
getCodeQL(),
{
@@ -135,10 +139,9 @@ test.serial(
analysisKinds: [AnalysisKind.CodeQuality],
},
testApiDetails,
createFeatures([]),
getRecordingLogger(loggedMessages),
"",
);
checkExpectedLogMessages(t, loggedMessages, [
checkExpectedLogMessages(t, logger.messages, [
"Not uploading database because 'analysis-kinds: code-scanning' is not enabled.",
]);
});
@@ -147,7 +150,8 @@ test.serial(
test.serial("Abort database upload if running against GHES", async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -157,16 +161,16 @@ test.serial("Abort database upload if running against GHES", async (t) => {
const config = getTestConfig(tmpDir);
config.gitHubVersion = { type: GitHubVariant.GHES, version: "3.0" };
const loggedMessages: LoggedMessage[] = [];
const logger = new RecordingLogger();
await cleanupAndUploadDatabases(
initAllState({ env, logger }),
testRepoName,
getCodeQL(),
config,
testApiDetails,
createFeatures([]),
getRecordingLogger(loggedMessages),
"",
);
checkExpectedLogMessages(t, loggedMessages, [
checkExpectedLogMessages(t, logger.messages, [
"Not running against github.com or GHEC-DR. Skipping upload.",
]);
});
@@ -176,23 +180,24 @@ test.serial(
"Abort database upload if not analyzing default branch",
async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("true");
sinon.stub(gitUtils, "isAnalyzingDefaultBranch").resolves(false);
const loggedMessages: LoggedMessage[] = [];
const logger = new RecordingLogger();
await cleanupAndUploadDatabases(
initAllState({ env, logger }),
testRepoName,
getCodeQL(),
getTestConfig(tmpDir),
testApiDetails,
createFeatures([]),
getRecordingLogger(loggedMessages),
"",
);
checkExpectedLogMessages(t, loggedMessages, [
checkExpectedLogMessages(t, logger.messages, [
"Not analyzing default branch. Skipping upload.",
]);
});
@@ -203,7 +208,8 @@ test.serial(
"Don't crash if uploading a database fails with a non-retryable error",
async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -212,17 +218,17 @@ test.serial(
const databaseUploadSpy = await mockHttpRequests(422);
const loggedMessages: LoggedMessage[] = [];
const logger = new RecordingLogger();
await cleanupAndUploadDatabases(
initAllState({ env, logger }),
testRepoName,
getCodeQL(),
getTestConfig(tmpDir),
testApiDetails,
createFeatures([]),
getRecordingLogger(loggedMessages),
"",
);
checkExpectedLogMessages(t, loggedMessages, [
checkExpectedLogMessages(t, logger.messages, [
"Failed to upload database for javascript: some error message",
]);
@@ -236,7 +242,8 @@ test.serial(
"Don't crash if uploading a database fails with a retryable error",
async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -251,17 +258,17 @@ test.serial(
.stub(global, "setTimeout")
.callsFake((fn: () => void) => originalSetTimeout(fn, 0));
const loggedMessages: LoggedMessage[] = [];
const logger = new RecordingLogger();
await cleanupAndUploadDatabases(
initAllState({ env, logger }),
testRepoName,
getCodeQL(),
getTestConfig(tmpDir),
testApiDetails,
createFeatures([]),
getRecordingLogger(loggedMessages),
"",
);
checkExpectedLogMessages(t, loggedMessages, [
checkExpectedLogMessages(t, logger.messages, [
"Failed to upload database for javascript: some error message",
]);
@@ -279,7 +286,8 @@ test.serial(
test.serial("Successfully uploading a database to github.com", async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -288,16 +296,16 @@ test.serial("Successfully uploading a database to github.com", async (t) => {
await mockHttpRequests(201);
const loggedMessages: LoggedMessage[] = [];
const logger = new RecordingLogger();
await cleanupAndUploadDatabases(
initAllState({ env, logger }),
testRepoName,
getCodeQL(),
getTestConfig(tmpDir),
testApiDetails,
createFeatures([]),
getRecordingLogger(loggedMessages),
"",
);
checkExpectedLogMessages(t, loggedMessages, [
checkExpectedLogMessages(t, logger.messages, [
"Successfully uploaded database for javascript",
]);
});
@@ -305,7 +313,8 @@ test.serial("Successfully uploading a database to github.com", async (t) => {
test.serial("Successfully uploading a database to GHEC-DR", async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -314,8 +323,9 @@ test.serial("Successfully uploading a database to GHEC-DR", async (t) => {
const databaseUploadSpy = await mockHttpRequests(201);
const loggedMessages: LoggedMessage[] = [];
const logger = new RecordingLogger();
await cleanupAndUploadDatabases(
initAllState({ env, logger }),
testRepoName,
getCodeQL(),
getTestConfig(tmpDir),
@@ -324,10 +334,9 @@ test.serial("Successfully uploading a database to GHEC-DR", async (t) => {
url: "https://tenant.ghe.com",
apiURL: undefined,
},
createFeatures([]),
getRecordingLogger(loggedMessages),
"",
);
checkExpectedLogMessages(t, loggedMessages, [
checkExpectedLogMessages(t, logger.messages, [
"Successfully uploaded database for javascript",
]);
t.assert(
@@ -343,7 +352,8 @@ test.serial(
"Records overlay and clear cleanup sizes when uploading an overlay-base database",
async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -375,14 +385,16 @@ test.serial(
const config = getTestConfig(tmpDir);
config.overlayDatabaseMode = OverlayDatabaseMode.OverlayBase;
const loggedMessages: LoggedMessage[] = [];
const results = await cleanupAndUploadDatabases(
initAllState({
env,
features: createFeatures([Feature.UploadOverlayDbToApi]),
}),
testRepoName,
codeql,
config,
testApiDetails,
createFeatures([Feature.UploadOverlayDbToApi]),
getRecordingLogger(loggedMessages),
"",
);
// The database should be cleaned up at the `overlay` level for the upload
@@ -402,7 +414,8 @@ test.serial(
"Does not measure clear cleanup size for a regular (non-overlay-base) upload",
async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -422,12 +435,15 @@ test.serial(
});
const results = await cleanupAndUploadDatabases(
initAllState({
env,
features: createFeatures([Feature.UploadOverlayDbToApi]),
}),
testRepoName,
codeql,
getTestConfig(tmpDir),
testApiDetails,
createFeatures([Feature.UploadOverlayDbToApi]),
getRecordingLogger([]),
"",
);
// A regular upload is cleaned only once, at the `clear` level.
@@ -441,7 +457,8 @@ test.serial(
test.serial("Does not measure clear cleanup size in debug mode", async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -465,12 +482,15 @@ test.serial("Does not measure clear cleanup size in debug mode", async (t) => {
config.debugMode = true;
const results = await cleanupAndUploadDatabases(
initAllState({
env,
features: createFeatures([Feature.UploadOverlayDbToApi]),
}),
testRepoName,
codeql,
config,
testApiDetails,
createFeatures([Feature.UploadOverlayDbToApi]),
getRecordingLogger([]),
"",
);
// In debug mode we clean up at the `overlay` level for the upload but skip
@@ -486,7 +506,8 @@ test.serial(
"Does not record a clear cleanup duration when the clear cleanup fails",
async (t) => {
await withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const env = getTestEnv();
setupActionsVars(tmpDir, tmpDir, {}, env);
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
@@ -510,12 +531,15 @@ test.serial(
config.overlayDatabaseMode = OverlayDatabaseMode.OverlayBase;
const results = await cleanupAndUploadDatabases(
initAllState({
env,
features: createFeatures([Feature.UploadOverlayDbToApi]),
}),
testRepoName,
codeql,
config,
testApiDetails,
createFeatures([Feature.UploadOverlayDbToApi]),
getRecordingLogger([]),
"",
);
// When the `clear` cleanup fails, no size is measured, so we should not

View File

@@ -1,5 +1,6 @@
import * as fs from "fs";
import { ActionState } from "./action-common";
import * as actionsUtil from "./actions-util";
import { AnalysisKind } from "./analyses";
import {
@@ -9,13 +10,14 @@ import {
} from "./api-client";
import { type CodeQL } from "./codeql";
import { Config } from "./config-utils";
import { Feature, FeatureEnablement } from "./feature-flags";
import { Feature } from "./feature-flags";
import * as gitUtils from "./git-utils";
import { parseGitHubUrl } from "./github";
import { Logger, withGroupAsync } from "./logging";
import { OverlayDatabaseMode } from "./overlay/overlay-database-mode";
import { RepositoryNwo } from "./repository";
import * as util from "./util";
import { asHTTPError, bundleDb, CleanupLevel, parseGitHubUrl } from "./util";
import { asHTTPError, bundleDb, CleanupLevel } from "./util";
/** Information about a database upload. */
export interface DatabaseUploadResult {
@@ -45,13 +47,15 @@ export interface DatabaseUploadResult {
}
export async function cleanupAndUploadDatabases(
action: ActionState<["Logger", "FeatureFlags"]>,
repositoryNwo: RepositoryNwo,
codeql: CodeQL,
config: Config,
apiDetails: GitHubApiDetails,
features: FeatureEnablement,
logger: Logger,
checkoutPath: string,
): Promise<DatabaseUploadResult[]> {
const logger = action.logger;
if (actionsUtil.getRequiredInput("upload-database") !== "true") {
logger.debug("Database upload disabled in workflow. Skipping upload.");
return [];
@@ -87,7 +91,7 @@ export async function cleanupAndUploadDatabases(
// If config.overlayDatabaseMode is OverlayBase, then we have overlay base databases for all languages.
const shouldUploadOverlayBase =
config.overlayDatabaseMode === OverlayDatabaseMode.OverlayBase &&
(await features.getValue(Feature.UploadOverlayDbToApi, codeql));
(await action.features.getValue(Feature.UploadOverlayDbToApi, codeql));
const cleanupLevel = shouldUploadOverlayBase
? CleanupLevel.Overlay
: CleanupLevel.Clear;
@@ -110,9 +114,7 @@ export async function cleanupAndUploadDatabases(
includeDiagnostics: false,
});
bundledDbSize = fs.statSync(bundledDb).size;
const commitOid = await gitUtils.getCommitOid(
actionsUtil.getRequiredInput("checkout_path"),
);
const commitOid = await gitUtils.getCommitOid(checkoutPath);
// Upload with manual retry logic. We disable Octokit's built-in retries
// because the request body is a ReadStream, which can only be consumed
// once.
@@ -265,7 +267,10 @@ async function uploadBundledDatabase(
bundledDbSize: number,
apiDetails: GitHubApiDetails,
): Promise<number> {
const client = getApiClient();
// Ensure that the `apiDetails` that `getApiClient` uses match the ones we were given here,
// because we use `apiDetails.auth` below which must be used with the same instance that
// `apiDetails` refers to.
const client = getApiClient(util.getEnv(), apiDetails);
const uploadsUrl = new URL(parseGitHubUrl(apiDetails.url));
uploadsUrl.hostname = `uploads.${uploadsUrl.hostname}`;
@@ -277,6 +282,10 @@ async function uploadBundledDatabase(
uploadsBaseUrl = uploadsBaseUrl.slice(0, -1);
}
const token = apiDetails.auth?.trim();
const hasToken = token !== undefined && token !== "";
const authorization = hasToken ? `token ${token}` : undefined;
const bundledDbReadStream = fs.createReadStream(bundledDb);
try {
const startTime = performance.now();
@@ -291,7 +300,7 @@ async function uploadBundledDatabase(
commit_oid: commitOid,
data: bundledDbReadStream,
headers: {
authorization: `token ${apiDetails.auth}`,
authorization,
"Content-Type": "application/zip",
"Content-Length": bundledDbSize,
},

View File

@@ -55,25 +55,20 @@ test("getArtifactSuffix", (t) => {
}
});
// These next tests check the correctness of the logic to determine whether or not
// artifacts are uploaded in debug mode. Since it's not easy to mock the actual
// call to upload an artifact, we just check that we get an "upload-failed" result,
// instead of actually uploading the artifact.
//
// For tests where we expect artifact upload to be blocked, we check for a different
// response from the function.
// These next tests check whether `uploadArtifacts` attempts to upload an artifact. Since it's not
// easy to mock the actual call to upload an artifact, we check that we get an "upload-failed"
// result, instead of actually uploading the artifact.
test("uploadDebugArtifacts when artifacts empty should emit 'no-artifacts-to-upload'", async (t) => {
test("uploadArtifacts returns 'no-artifacts-to-upload' when there are no files to upload", async (t) => {
// Test that no error is thrown if artifacts list is empty.
const logger = getActionsLogger();
await t.notThrowsAsync(async () => {
const uploaded = await debugArtifacts.uploadDebugArtifacts(
const uploaded = await debugArtifacts.uploadArtifacts(
logger,
[],
"i-dont-exist",
"artifactName",
GitHubVariant.DOTCOM,
undefined,
);
t.is(
uploaded,
@@ -83,17 +78,15 @@ test("uploadDebugArtifacts when artifacts empty should emit 'no-artifacts-to-upl
});
});
test("uploadDebugArtifacts when no codeql version is used should invoke artifact upload", async (t) => {
// Test that the artifact is uploaded.
test("uploadArtifacts attempts an upload when there are files to upload", async (t) => {
const logger = getActionsLogger();
await t.notThrowsAsync(async () => {
const uploaded = await debugArtifacts.uploadDebugArtifacts(
const uploaded = await debugArtifacts.uploadArtifacts(
logger,
["hucairz"],
"i-dont-exist",
"artifactName",
GitHubVariant.DOTCOM,
undefined,
);
t.is(
uploaded,
@@ -103,44 +96,3 @@ test("uploadDebugArtifacts when no codeql version is used should invoke artifact
);
});
});
test("uploadDebugArtifacts when new codeql version is used should invoke artifact upload", async (t) => {
// Test that the artifact is uploaded.
const logger = getActionsLogger();
await t.notThrowsAsync(async () => {
const uploaded = await debugArtifacts.uploadDebugArtifacts(
logger,
["hucairz"],
"i-dont-exist",
"artifactName",
GitHubVariant.DOTCOM,
"2.20.3",
);
t.is(
uploaded,
// The failure is expected since we don't want to actually upload any artifacts in unit tests.
"upload-failed",
"Expect failure to upload artifacts since root dir does not exist",
);
});
});
test("uploadDebugArtifacts when old codeql is used should avoid trying to upload artifacts", async (t) => {
// Test that the artifact is not uploaded.
const logger = getActionsLogger();
await t.notThrowsAsync(async () => {
const uploaded = await debugArtifacts.uploadDebugArtifacts(
logger,
["hucairz"],
"i-dont-exist",
"artifactName",
GitHubVariant.DOTCOM,
"2.20.2",
);
t.is(
uploaded,
"upload-not-supported",
"Expected artifact upload to be blocked because of old CodeQL version",
);
});
});

View File

@@ -10,15 +10,11 @@ import { getOptionalInput, getTemporaryDirectory } from "./actions-util";
import { dbIsFinalized } from "./analyze";
import { scanArtifactsForTokens } from "./artifact-scanner";
import { type CodeQL } from "./codeql";
import { Config } from "./config-utils";
import { EnvVar } from "./environment";
import type { ActionConfig } from "./config/action-config";
import { EnvVar, exportEnvVar } from "./environment";
import * as json from "./json";
import { Language } from "./languages";
import { Logger, withGroup } from "./logging";
import {
isSafeArtifactUpload,
SafeArtifactUploadVersion,
} from "./tools-features";
import {
bundleDb,
doesDirectoryExist,
@@ -40,7 +36,6 @@ export function sanitizeArtifactName(name: string): string {
export async function uploadCombinedSarifArtifacts(
logger: Logger,
gitHubVariant: GitHubVariant,
codeQlVersion: string | undefined,
) {
const tempDir = getTemporaryDirectory();
@@ -70,13 +65,12 @@ export async function uploadCombinedSarifArtifacts(
}
try {
await uploadDebugArtifacts(
await uploadArtifacts(
logger,
toUpload,
baseTempDir,
"combined-sarif-artifacts",
gitHubVariant,
codeQlVersion,
);
} catch (e) {
logger.warning(
@@ -95,7 +89,7 @@ export async function uploadCombinedSarifArtifacts(
* @return The path to that debug artifact, or undefined if an error occurs.
*/
function tryPrepareSarifDebugArtifact(
config: Config,
config: ActionConfig<"dbLocation">,
language: Language,
logger: Logger,
): string | undefined {
@@ -137,7 +131,7 @@ function tryPrepareSarifDebugArtifact(
*/
async function tryBundleDatabase(
codeql: CodeQL,
config: Config,
config: ActionConfig<"dbLocation">,
language: Language,
logger: Logger,
): Promise<string | undefined> {
@@ -163,6 +157,11 @@ async function tryBundleDatabase(
}
}
/** The minimal configuration needed for `tryUploadAllAvailableDebugArtifacts`. */
export type UploadDebugArtifactsConfig = ActionConfig<
"languages" | "gitHubVersion" | "dbLocation" | "debugArtifactName"
>;
/**
* Attempt to upload all available debug artifacts.
*
@@ -170,9 +169,8 @@ async function tryBundleDatabase(
*/
export async function tryUploadAllAvailableDebugArtifacts(
codeql: CodeQL,
config: Config,
config: UploadDebugArtifactsConfig,
logger: Logger,
codeQlVersion: string | undefined,
) {
const filesToUpload: string[] = [];
try {
@@ -231,13 +229,12 @@ export async function tryUploadAllAvailableDebugArtifacts(
try {
await withGroup("Uploading debug artifacts", async () =>
uploadDebugArtifacts(
uploadArtifacts(
logger,
filesToUpload,
config.dbLocation,
config.debugArtifactName,
config.gitHubVersion.type,
codeQlVersion,
),
);
} catch (e) {
@@ -283,26 +280,6 @@ export type UploadArtifactsResult =
| "upload-successful"
| "upload-failed";
export async function uploadDebugArtifacts(
logger: Logger,
toUpload: string[],
rootDir: string,
artifactName: string,
ghVariant: GitHubVariant,
codeQlVersion: string | undefined,
): Promise<UploadArtifactsResult | "upload-not-supported"> {
const uploadSupported = isSafeArtifactUpload(codeQlVersion);
if (!uploadSupported) {
core.info(
`Skipping debug artifact upload because the current CLI does not support safe upload. Please upgrade to CLI v${SafeArtifactUploadVersion} or later.`,
);
return "upload-not-supported";
}
return uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVariant);
}
/**
* Uploads the specified files as a single workflow artifact.
*
@@ -330,7 +307,7 @@ export async function uploadArtifacts(
// some issues early.
if (isInTestMode()) {
await scanArtifactsForTokens(toUpload, logger);
core.exportVariable("CODEQL_ACTION_ARTIFACT_SCAN_FINISHED", "true");
exportEnvVar("CODEQL_ACTION_ARTIFACT_SCAN_FINISHED", "true");
}
const suffix = getArtifactSuffix(getOptionalInput("matrix"));
@@ -381,7 +358,7 @@ export async function getArtifactUploaderClient(
* all files in the database folder and return the path.
*/
async function createPartialDatabaseBundle(
config: Config,
config: ActionConfig<"dbLocation">,
language: Language,
): Promise<string> {
const databasePath = getCodeQLDatabasePath(config, language);
@@ -422,7 +399,7 @@ async function createPartialDatabaseBundle(
*/
async function createDatabaseBundleCli(
codeql: CodeQL,
config: Config,
config: ActionConfig<"dbLocation">,
language: Language,
): Promise<string> {
const databaseBundlePath = await bundleDb(

View File

@@ -1,6 +1,6 @@
{
"bundleVersion": "codeql-bundle-v2.27.0",
"cliVersion": "2.27.0",
"priorBundleVersion": "codeql-bundle-v2.26.4",
"priorCliVersion": "2.26.4"
"bundleVersion": "codeql-bundle-v2.27.2",
"cliVersion": "2.27.2",
"priorBundleVersion": "codeql-bundle-v2.27.1",
"priorCliVersion": "2.27.1"
}

12
src/environment.test.ts Normal file
View File

@@ -0,0 +1,12 @@
import test from "ava";
import { Env, ReadOnlyEnv } from "./environment";
import { getTestEnv, setupTests } from "./testing-utils";
setupTests(test);
test("isTestingEnv() is true", (t) => {
t.true(new ReadOnlyEnv(process.env).isTestingEnv());
t.true(new Env(process.env).isTestingEnv());
t.true(getTestEnv().isTestingEnv());
});

View File

@@ -1,3 +1,10 @@
import * as core from "@actions/core";
/**
* This constant is set in `ava.setup.mjs` for tests.
*/
declare const __CODEQL_ACTION_TEST_ENV__: string | undefined;
/**
* Environment variables used by Default Setup to communicate the private registry proxy configuration.
*/
@@ -211,8 +218,20 @@ export enum ActionsEnvVars {
RUNNER_TOOL_CACHE = "RUNNER_TOOL_CACHE",
}
/** Environment variables which are not specific to CodeQL. */
export enum SystemEnvVar {
/**
* Used by Node and related tools to indicate what kind of environment we are running in.
*/
NODE_ENV = "NODE_ENV",
}
/** A type representing all known environment variables. */
export type KnownEnvVar = EnvVar | ActionsEnvVars | RegistryProxyVars;
export type KnownEnvVar =
| EnvVar
| ActionsEnvVars
| RegistryProxyVars
| SystemEnvVar;
/**
* Gets an environment variable, but throws an error if it is not set.
@@ -289,6 +308,26 @@ export class ReadOnlyEnv<T extends string | undefined = string | undefined> {
public entries(): Array<[string, T]> {
return Object.entries(this.vars);
}
/**
* Gets a value indicating whether we should skip uploads of
* all kinds (SARIF results, status reports, DBs, ...).
*
* This is not guaranteed to be set in all test environments.
*/
public isSkippingUploadsInTests(): boolean {
return this.getOptional(EnvVar.TEST_MODE) === "true";
}
/**
* Gets a value indicative of whether we are in a testing environment
* by testing whether the value of the `NODE_ENV` variable is "test".
* This is expected to be the case if e.g. `ava` is running the tests
* or if this instance was constructed by `getTestEnv`.
*/
public isTestingEnv(): boolean {
return __CODEQL_ACTION_TEST_ENV__ === "unit-test";
}
}
/**
@@ -307,6 +346,26 @@ export class Env<
this.changed = true;
}
/**
* Wrapper around `core.exportVariable` which does not call `core.exportVariable`
* when running unit tests. This is important, because otherwise `core.exportVariable`
* sets environment variables for other steps in a workflow when we run unit tests in CI.
*
* @param name The name of the environment variable to set and export.
* @param val The value to set and export for the environment variable.
*/
public export(name: string, val: T): void {
// Setting the environment variable for this instance is always OK, including
// in tests, since we use fresh `Env` instances whenever needed. This allows
// tests to pass that rely on that part of the `core.exportVariable` behaviour.
this.set(name, val);
// Call `core.exportVariable` whenever we are not in a test environment.
if (!this.isTestingEnv()) {
core.exportVariable(name, val);
}
}
/** Gets a value indicating whether `set` was called at least once. */
public hasChanged(): boolean {
return this.changed;
@@ -317,3 +376,34 @@ export class Env<
export function getEnv(env: NodeJS.ProcessEnv = process.env): Env {
return new Env(env);
}
/**
* Returns whether we are in test mode. This is used by CodeQL Action PR checks.
*
* In test mode, we skip several uploads (SARIF results, status reports, DBs, ...).
*
* @deprecated
* The purpose of this function is ambiguous. Use `isSkippingUploadsInTests` on
* a `ReadOnlyEnv` instance instead for equivalent behaviour. Use `isTestingEnv`
* to determine if we are running in a unit test.
*/
export function isInTestMode(): boolean {
return getEnv().isSkippingUploadsInTests();
}
/**
* Wrapper around `core.exportVariable` which does not call `core.exportVariable`
* when running unit tests. This is important, because otherwise `core.exportVariable`
* sets environment variables for other steps in a workflow when we run unit tests in CI.
*
* @deprecated Use `export` on an `Env` instance instead.
*/
export function exportEnvVar(name: string, val: any): void {
const env = getEnv();
if (typeof val === "string") {
env.export(name, val);
} else {
env.export(name, JSON.stringify(val));
}
}

View File

@@ -168,7 +168,7 @@ export enum Feature {
* Controls whether we may download a bundle containing only the single language being analysed,
* rather than the combined bundle that contains every language.
*/
PerLanguageBundles = "per_language_bundles",
PerLanguageBundles = "per_language_bundles_v2",
QaTelemetryEnabled = "qa_telemetry_enabled",
/** Routes (some) API requests through the registry proxy. */
ProxyApiRequests = "proxy_api_requests",
@@ -240,7 +240,7 @@ export const featureConfig = {
defaultValue: false,
envVar: "CODEQL_EXTRACTOR_CPP_AUTOINSTALL_DEPENDENCIES",
legacyApi: true,
minimumVersion: "2.15.0",
minimumVersion: undefined,
},
[Feature.CsharpCacheBuildModeNone]: {
defaultValue: false,

View File

@@ -29,10 +29,13 @@ test.serial(
process.env["GITHUB_SHA"] = currentSha;
const callback = sinon.stub(gitUtils, "getCommitOid");
callback.withArgs("HEAD").resolves(currentSha);
callback.withArgs(sinon.match.string, "HEAD").resolves(currentSha);
const actualRef = await gitUtils.getRef();
t.deepEqual(actualRef, expectedRef);
t.is(callback.callCount, 1);
t.true(callback.calledOnceWith(tmpDir, "HEAD"));
});
},
);
@@ -48,11 +51,17 @@ test.serial(
const sha = "a".repeat(40);
const callback = sinon.stub(gitUtils, "getCommitOid");
callback.withArgs("refs/remotes/pull/1/merge").resolves(sha);
callback.withArgs("HEAD").resolves(sha);
callback
.withArgs(sinon.match.string, "refs/remotes/pull/1/merge")
.resolves(sha);
callback.withArgs(sinon.match.any, "HEAD").resolves(sha);
const actualRef = await gitUtils.getRef();
t.deepEqual(actualRef, expectedRef);
t.is(callback.callCount, 2);
t.true(callback.calledWith(tmpDir, "HEAD"));
t.true(callback.calledWith(tmpDir, "refs/remotes/pull/1/merge"));
});
},
);
@@ -66,11 +75,18 @@ test.serial(
process.env["GITHUB_SHA"] = "a".repeat(40);
const callback = sinon.stub(gitUtils, "getCommitOid");
callback.withArgs(tmpDir, "refs/pull/1/merge").resolves("a".repeat(40));
callback
.withArgs(tmpDir, "refs/remotes/pull/1/merge")
.resolves("a".repeat(40));
callback.withArgs(tmpDir, "HEAD").resolves("b".repeat(40));
callback.throws(new Error("Unexpected getCommitOid call in test."));
const actualRef = await gitUtils.getRef();
t.deepEqual(actualRef, "refs/pull/1/head");
t.is(callback.callCount, 2);
t.true(callback.calledWith(tmpDir, "refs/remotes/pull/1/merge"));
t.true(callback.calledWith(tmpDir, "HEAD"));
});
},
);
@@ -92,11 +108,14 @@ test.serial(
process.env["GITHUB_SHA"] = "a".repeat(40);
const callback = sinon.stub(gitUtils, "getCommitOid");
callback.withArgs("refs/pull/1/merge").resolves("b".repeat(40));
callback.withArgs("HEAD").resolves("b".repeat(40));
callback.withArgs(tmpDir, "refs/pull/1/merge").resolves("b".repeat(40));
callback.withArgs(sinon.match.any, "HEAD").resolves("b".repeat(40));
const actualRef = await gitUtils.getRef();
t.deepEqual(actualRef, "refs/pull/2/merge");
// getCommitOid shouldn't be called, because the ref should be taken from the input
t.is(callback.callCount, 0);
});
},
);

111
src/github.test.ts Normal file
View File

@@ -0,0 +1,111 @@
import test from "ava";
import { ActionsEnvVars } from "./environment";
import * as github from "./github";
import { getTestEnv, setupTests } from "./testing-utils";
setupTests(test);
test("parseGitHubUrl", (t) => {
t.deepEqual(github.parseGitHubUrl("github.com"), "https://github.com");
t.deepEqual(
github.parseGitHubUrl("https://github.com"),
"https://github.com",
);
t.deepEqual(
github.parseGitHubUrl("https://api.github.com"),
"https://github.com",
);
t.deepEqual(
github.parseGitHubUrl("https://github.com/foo/bar"),
"https://github.com",
);
t.deepEqual(
github.parseGitHubUrl("github.example.com"),
"https://github.example.com/",
);
t.deepEqual(
github.parseGitHubUrl("https://github.example.com"),
"https://github.example.com/",
);
t.deepEqual(
github.parseGitHubUrl("https://api.github.example.com"),
"https://github.example.com/",
);
t.deepEqual(
github.parseGitHubUrl("https://github.example.com/api/v3"),
"https://github.example.com/",
);
t.deepEqual(
github.parseGitHubUrl("https://github.example.com:1234"),
"https://github.example.com:1234/",
);
t.deepEqual(
github.parseGitHubUrl("https://api.github.example.com:1234"),
"https://github.example.com:1234/",
);
t.deepEqual(
github.parseGitHubUrl("https://github.example.com:1234/api/v3"),
"https://github.example.com:1234/",
);
t.deepEqual(
github.parseGitHubUrl("https://github.example.com/base/path"),
"https://github.example.com/base/path/",
);
t.deepEqual(
github.parseGitHubUrl("https://github.example.com/base/path/api/v3"),
"https://github.example.com/base/path/",
);
t.throws(() => github.parseGitHubUrl(""), {
message: '"" is not a valid URL',
});
t.throws(() => github.parseGitHubUrl("ssh://github.com"), {
message: '"ssh://github.com" is not a http or https URL',
});
t.throws(() => github.parseGitHubUrl("http:///::::433"), {
message: '"http:///::::433" is not a valid URL',
});
});
test("getCurrentInstance throws if required env vars aren't set", (t) => {
t.throws(() => github.getCurrentInstance(getTestEnv()));
t.throws(() => {
const env = getTestEnv({
[ActionsEnvVars.GITHUB_SERVER_URL]: "https://localhost",
});
github.getCurrentInstance(env);
});
t.throws(() => {
const env = getTestEnv({
[ActionsEnvVars.GITHUB_API_URL]: "https://api.localhost",
});
github.getCurrentInstance(env);
});
});
test("getCurrentInstance constructs instance from environment", (t) => {
const url = "https://localhost";
const apiUrl = "https://api.localhost";
const env = getTestEnv({
[ActionsEnvVars.GITHUB_SERVER_URL]: url,
[ActionsEnvVars.GITHUB_API_URL]: apiUrl,
});
const instance = github.getCurrentInstance(env);
t.is(instance.url, url);
t.is(instance.apiURL, apiUrl);
});
test("getCurrentInstance constructs dotcom instance with dotcom env vars", (t) => {
const env = getTestEnv({
[ActionsEnvVars.GITHUB_SERVER_URL]: github.GITHUB_DOTCOM_URL,
[ActionsEnvVars.GITHUB_API_URL]: github.GITHUB_DOTCOM_API_URL,
});
const instance = github.getCurrentInstance(env);
const dotcomInstance = github.getDotcomInstance();
t.deepEqual(dotcomInstance, instance);
});

110
src/github.ts Normal file
View File

@@ -0,0 +1,110 @@
import { ActionsEnvVars, type ReadOnlyEnv } from "./environment";
import { ConfigurationError } from "./util";
/** A string representing a GitHub instance address. */
export type InstanceURL = string;
/**
* The URL for github.com.
*/
export const GITHUB_DOTCOM_URL: InstanceURL = "https://github.com";
/** A string representing a GitHub API instance address. */
export type InstanceApiURL = string;
/**
* The URL for api.github.com.
*/
export const GITHUB_DOTCOM_API_URL: InstanceApiURL = "https://api.github.com";
/**
* Represents information about a GitHub instance, how to authenticate to it,
* and how to authenticate to other repos on it.
*/
export type GitHubApiCombinedDetails = GitHubApiDetails &
GitHubApiExternalRepoDetails;
/** Represents information about a GitHub instance. */
export type GitHubInstance = {
/** The base URL of the GitHub instance, such as `https://github.com`. */
url: string;
/**
* The API base URL of the GitHub instance, such as `https://api.github.com`.
* Typically this is the `api.` subdomain of the `url` domain.
*/
apiURL: string | undefined;
};
/** Represents a {@link GitHubInstance} with a token for accessing the API. */
export type GitHubApiDetails = GitHubInstance & {
/** The token to use for accessing the API of the GitHub instance. */
auth?: string;
};
/**
* Represents information for accessing a repository on the same GitHub instance as the Action
* is currently running on.
*/
export type GitHubApiExternalRepoDetails = {
/** An optional token for accessing repo(s) on the same GitHub instance. */
externalRepoAuth?: string;
};
/**
* Parses user input of a github.com or GHES URL to a canonical form.
* Removes any API prefix or suffix if one is present.
*/
export function parseGitHubUrl(inputUrl: string): string {
const originalUrl = inputUrl;
if (inputUrl.indexOf("://") === -1) {
inputUrl = `https://${inputUrl}`;
}
if (!inputUrl.startsWith("http://") && !inputUrl.startsWith("https://")) {
throw new ConfigurationError(`"${originalUrl}" is not a http or https URL`);
}
let url: URL;
try {
url = new URL(inputUrl);
} catch {
throw new ConfigurationError(`"${originalUrl}" is not a valid URL`);
}
// If we detect this is trying to be to github.com
// then return with a fixed canonical URL.
if (url.hostname === "github.com" || url.hostname === "api.github.com") {
return GITHUB_DOTCOM_URL;
}
// Remove the API prefix if it's present
if (url.pathname.indexOf("/api/v3") !== -1) {
url.pathname = url.pathname.substring(0, url.pathname.indexOf("/api/v3"));
}
// Also consider subdomain isolation on GHES
if (url.hostname.startsWith("api.")) {
url.hostname = url.hostname.substring(4);
}
// Normalise path to having a trailing slash for consistency
if (!url.pathname.endsWith("/")) {
url.pathname = `${url.pathname}/`;
}
return url.toString();
}
/** Retrieves a {@link GitHubInstance} describing the instance we are running on. */
export function getCurrentInstance(env: ReadOnlyEnv): GitHubInstance {
return {
url: env.getRequired(ActionsEnvVars.GITHUB_SERVER_URL),
apiURL: env.getRequired(ActionsEnvVars.GITHUB_API_URL),
};
}
/** Retrieves a {@link GitHubInstance} describing the GitHub.com instance. */
export function getDotcomInstance(): GitHubInstance {
return {
url: GITHUB_DOTCOM_URL,
apiURL: GITHUB_DOTCOM_API_URL,
};
}

View File

@@ -7,6 +7,11 @@ import * as actionsUtil from "./actions-util";
import { CodeScanning, RiskAssessment } from "./analyses";
import { getApiClient, getGitHubVersion } from "./api-client";
import { CodeQL, getCodeQL } from "./codeql";
import {
hasConfigKey,
type AbortedInitConfig,
type ActionConfig,
} from "./config/action-config";
import {
Config,
isCodeScanningEnabled,
@@ -16,6 +21,7 @@ import {
getArtifactSuffix,
getArtifactUploaderClient,
sanitizeArtifactName,
type UploadDebugArtifactsConfig,
} from "./debug-artifacts";
import * as dependencyCaching from "./dependency-caching";
import { EnvVar, ReadOnlyEnv } from "./environment";
@@ -86,6 +92,11 @@ interface FailedSarifInfo {
checkoutPath: string;
}
/** The minimal Action configuration required to prepare and upload a failed SARIF. */
export type FailedSarifConfig = ActionConfig<
"codeQLCmd" | "tempDir" | "analysisKinds" | "languages"
>;
/**
* Tries to prepare a SARIF file that contains information about a failed analysis.
*
@@ -94,7 +105,7 @@ interface FailedSarifInfo {
async function prepareFailedSarif(
logger: Logger,
features: FeatureEnablement,
config: Config,
config: FailedSarifConfig,
): Promise<Result<FailedSarifInfo, UploadFailedSarifResult>> {
if (!config.codeQLCmd) {
return new Failure({
@@ -160,7 +171,7 @@ async function prepareFailedSarif(
async function generateFailedSarif(
logger: Logger,
features: FeatureEnablement,
config: Config,
config: ActionConfig<"codeQLCmd" | "tempDir">,
category: string | undefined,
checkoutPath: string,
sarifFile?: string,
@@ -192,7 +203,7 @@ async function generateFailedSarif(
* category for the workflow.
*/
async function maybeUploadFailedSarif(
config: Config,
config: FailedSarifConfig,
repositoryNwo: RepositoryNwo,
features: FeatureEnablement,
logger: Logger,
@@ -227,7 +238,7 @@ async function maybeUploadFailedSarif(
/** Uploads a failed SARIF file as workflow artifact, if it can be generated. */
async function maybeUploadFailedSarifArtifact(
config: Config,
config: FailedSarifConfig,
features: FeatureEnablement,
logger: Logger,
): Promise<UploadFailedSarifResult> {
@@ -267,7 +278,7 @@ async function maybeUploadFailedSarifArtifact(
* @returns The results of uploading the SARIF file for the failure.
*/
export async function tryUploadSarifIfRunFailed(
config: Config,
config: FailedSarifConfig,
repositoryNwo: RepositoryNwo,
features: FeatureEnablement,
logger: Logger,
@@ -324,13 +335,12 @@ export async function tryUploadSarifIfRunFailed(
export async function uploadFailureInfo(
uploadAllAvailableDebugArtifacts: (
codeql: CodeQL,
config: Config,
config: UploadDebugArtifactsConfig,
logger: Logger,
codeQlVersion: string,
) => Promise<void>,
printDebugLogs: (config: Config) => Promise<void>,
printDebugLogs: (logger: Logger, config: Partial<Config>) => Promise<void>,
codeql: CodeQL,
config: Config,
config: Config | AbortedInitConfig,
repositoryNwo: RepositoryNwo,
features: FeatureEnablement,
jobStatus: string | undefined,
@@ -377,21 +387,15 @@ export async function uploadFailureInfo(
}
// Upload appropriate Actions artifacts for debugging
if (config.debugMode) {
if (config.debugMode && hasConfigKey(config, "dbLocation")) {
logger.info(
"Debug mode is on. Uploading available database bundles and logs as Actions debugging artifacts...",
);
const version = await codeql.getVersion();
await uploadAllAvailableDebugArtifacts(
codeql,
config,
logger,
version.version,
);
await printDebugLogs(config);
await uploadAllAvailableDebugArtifacts(codeql, config, logger);
await printDebugLogs(logger, config);
}
if (actionsUtil.isSelfHostedRunner()) {
if (actionsUtil.isSelfHostedRunner() && config.dbLocation) {
try {
fs.rmSync(config.dbLocation, {
recursive: true,
@@ -406,6 +410,10 @@ export async function uploadFailureInfo(
`Failed to clean up database cluster directory ${config.dbLocation}. Details: ${e}`,
);
}
} else if (config.dbLocation === undefined) {
logger.debug(
"Skipping cleanup of database cluster directory since the configuration does not include a database path.",
);
} else {
logger.debug(
"Skipping cleanup of database cluster directory since we are running on a GitHub-hosted " +
@@ -454,7 +462,7 @@ function isConclusiveJobStatus(jobStatus: string | undefined): boolean {
*/
async function recordOverlayStatus(
codeql: CodeQL,
config: Config,
config: Partial<Config>,
features: FeatureEnablement,
jobStatus: string | undefined,
env: ReadOnlyEnv,
@@ -466,6 +474,11 @@ async function recordOverlayStatus(
!(await features.getValue(Feature.OverlayAnalysisStatusSave))
) {
return;
} else if (config.languages === undefined) {
logger.debug(
"Not recording overlay status, because the configuration contains no 'languages'.",
);
return;
}
// Only record a failure when the job outcome tells us something about the analysis. A cancelled

View File

@@ -6,31 +6,35 @@
import * as core from "@actions/core";
import { runInActions, type Action, type ActionState } from "./action-common";
import {
restoreInputs,
getOptionalInput,
getTemporaryDirectory,
printDebugLogs,
} from "./actions-util";
import { getGitHubVersion } from "./api-client";
import { getGitHubVersion, wrapApiConfigurationError } from "./api-client";
import { CachingKind } from "./caching-utils";
import { getCodeQL } from "./codeql";
import { type Config, getConfig } from "./config-utils";
import {
hasConfigKey,
type AbortedInitConfig,
type Config,
} from "./config/action-config";
import { getAbortedInitConfig, getConfig } from "./config-utils";
import * as debugArtifacts from "./debug-artifacts";
import {
DependencyCachingUsageReport,
getDependencyCacheUsage,
} from "./dependency-caching";
import { EnvVar, getEnv } from "./environment";
import { EnvVar, type ReadOnlyEnv } from "./environment";
import { initFeatures } from "./feature-flags";
import * as gitUtils from "./git-utils";
import * as initActionPostHelper from "./init-action-post-helper";
import { getActionsLogger } from "./logging";
import { getRepositoryNwo } from "./repository";
import {
StatusReportBase,
sendStatusReport,
sendUnhandledErrorStatusReport,
createStatusReportBase,
getActionsStatus,
ActionName,
@@ -45,16 +49,17 @@ interface InitPostStatusReport
initActionPostHelper.JobStatusReport,
initActionPostHelper.DependencyCachingUsageReport {}
async function run(startedAt: Date) {
async function run(action: ActionState<["Base", "Logger", "Env"]>) {
// To capture errors appropriately, keep as much code within the try-catch as
// possible, and only use safe functions outside.
const logger = action.logger;
const logger = getActionsLogger();
let config: Config | undefined;
let config: Config | AbortedInitConfig | undefined;
let uploadFailedSarifResult:
| initActionPostHelper.UploadFailedSarifResult
| undefined;
let dependencyCachingUsage: DependencyCachingUsageReport | undefined;
try {
// Read the job status before restoring inputs, since it is provided by the Actions runtime
// environment for this step and would otherwise be overwritten by the value that the `init`
@@ -62,9 +67,19 @@ async function run(startedAt: Date) {
const jobStatus = getOptionalInput("job-status");
// Restore inputs from `init` Action.
restoreInputs();
restoreInputs(logger);
const gitHubVersion = await getGitHubVersion();
const tmpDir = getTemporaryDirectory();
config = await getConfig(tmpDir, logger);
// If we weren't able to read the normal configuration file, the `init` step failed before it could write it.
// Try to load the "failed" configuration file instead which may have been written by the `init` step
// with a minimal configuration for this post-action.
if (config === undefined) {
config = getAbortedInitConfig(action, tmpDir);
}
const gitHubVersion = config?.gitHubVersion ?? (await getGitHubVersion());
checkGitHubVersionInRange(gitHubVersion, logger);
const repositoryNwo = getRepositoryNwo();
@@ -75,7 +90,6 @@ async function run(startedAt: Date) {
logger,
);
config = await getConfig(getTemporaryDirectory(), logger);
if (config === undefined) {
logger.warning(
"Debugging artifacts are unavailable since the 'init' Action failed before it could produce any.",
@@ -91,7 +105,7 @@ async function run(startedAt: Date) {
repositoryNwo,
features,
jobStatus,
getEnv(),
action.env,
logger,
);
@@ -101,19 +115,20 @@ async function run(startedAt: Date) {
// and where caching may not be enabled.
if (
(await gitUtils.isAnalyzingDefaultBranch()) &&
hasConfigKey(config, "dependencyCachingEnabled") &&
config.dependencyCachingEnabled !== CachingKind.None
) {
dependencyCachingUsage = await getDependencyCacheUsage(logger);
}
}
} catch (unwrappedError) {
const error = wrapError(unwrappedError);
const error = wrapApiConfigurationError(wrapError(unwrappedError));
core.setFailed(error.message);
const statusReportBase = await createStatusReportBase(
ActionName.InitPost,
action.name,
getActionsStatus(error),
startedAt,
action.startedAt,
config,
await checkDiskUsage(logger),
logger,
@@ -125,13 +140,13 @@ async function run(startedAt: Date) {
}
return;
}
const jobStatus = getFinalJobStatus(config);
const jobStatus = getFinalJobStatus(action, config);
logger.info(`CodeQL job status was ${getJobStatusDisplayName(jobStatus)}.`);
const statusReportBase = await createStatusReportBase(
ActionName.InitPost,
action.name,
"success",
startedAt,
action.startedAt,
config,
await checkDiskUsage(logger),
logger,
@@ -156,16 +171,21 @@ async function run(startedAt: Date) {
* Otherwise, we determine the job status based on whether the analyze step
* completed successfully and whether we have a valid CodeQL config.
*/
function getFinalJobStatus(config: Config | undefined): JobStatus {
const existingJobStatus = getJobStatusFromEnvironment();
function getFinalJobStatus(
action: ActionState<["Env"]>,
config: Partial<Config> | undefined,
): JobStatus {
const existingJobStatus = getJobStatusFromEnvironment(action.env);
if (existingJobStatus !== undefined) {
return existingJobStatus;
}
let jobStatus: JobStatus;
if (process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY] === "true") {
core.exportVariable(EnvVar.JOB_STATUS, JobStatus.SuccessStatus);
if (
action.env.getOptional(EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY) === "true"
) {
action.env.export(EnvVar.JOB_STATUS, JobStatus.SuccessStatus);
jobStatus = JobStatus.SuccessStatus;
} else if (config !== undefined) {
// - We have computed a CodeQL config
@@ -190,7 +210,7 @@ function getFinalJobStatus(config: Config | undefined): JobStatus {
// This shouldn't be necessary, but in the odd case that we run more than one
// `init` post step, ensure the job status is consistent between them.
core.exportVariable(EnvVar.JOB_STATUS, jobStatus);
action.env.export(EnvVar.JOB_STATUS, jobStatus);
return jobStatus;
}
@@ -199,8 +219,8 @@ function getFinalJobStatus(config: Config | undefined): JobStatus {
*
* If the job status is invalid, return `UnknownStatus`.
*/
function getJobStatusFromEnvironment(): JobStatus | undefined {
const jobStatusFromEnvironment = process.env[EnvVar.JOB_STATUS];
function getJobStatusFromEnvironment(env: ReadOnlyEnv): JobStatus | undefined {
const jobStatusFromEnvironment = env.getOptional(EnvVar.JOB_STATUS);
if (jobStatusFromEnvironment !== undefined) {
// Validate the job status from the environment. If it is invalid, return unknown.
@@ -215,18 +235,11 @@ function getJobStatusFromEnvironment(): JobStatus | undefined {
return undefined;
}
const initPost: Action = {
name: ActionName.InitPost,
run,
};
export async function runWrapper() {
const startedAt = new Date();
const logger = getActionsLogger();
try {
await run(startedAt);
} catch (error) {
core.setFailed(`init post action failed: ${wrapError(error).message}`);
await sendUnhandledErrorStatusReport(
ActionName.InitPost,
startedAt,
error,
logger,
);
}
return await runInActions(initPost);
}

View File

@@ -5,7 +5,12 @@ import * as core from "@actions/core";
import * as io from "@actions/io";
import * as semver from "semver";
import { Action, ActionState, runInActions } from "./action-common";
import {
Action,
ActionState,
extendActionState,
runInActions,
} from "./action-common";
import {
FileCmdNotFoundError,
getActionVersion,
@@ -23,6 +28,7 @@ import {
shouldRestoreCache,
} from "./caching-utils";
import { CodeQL } from "./codeql";
import { parseUserConfig } from "./config/db-config";
import { getConfigFileInput } from "./config/file";
import { ComputedInput, getToolsInput } from "./config/inputs";
import * as configUtils from "./config-utils";
@@ -38,9 +44,13 @@ import {
makeDiagnostic,
makeTelemetryDiagnostic,
} from "./diagnostics";
import { EnvVar } from "./environment";
import { ActionsEnvVars, EnvVar } from "./environment";
import { Feature, FeatureEnablement, initFeatures } from "./feature-flags";
import { loadRepositoryProperties } from "./feature-flags/properties";
import {
loadRepositoryProperties,
RepositoryPropertyName,
} from "./feature-flags/properties";
import * as github from "./github";
import {
checkInstallPython311,
checkPacksForOverlayCompatibility,
@@ -58,6 +68,7 @@ import {
OverlayBaseDatabaseDownloadStats,
} from "./overlay/caching";
import { OverlayDatabaseMode } from "./overlay/overlay-database-mode";
import { getOtherLanguagePacksReason } from "./per-language-bundles";
import { getRepositoryNwo } from "./repository";
import { ToolsSource } from "./setup-codeql";
import {
@@ -81,7 +92,6 @@ import {
DEFAULT_DEBUG_ARTIFACT_NAME,
DEFAULT_DEBUG_DATABASE_NAME,
getCodeQLMemoryLimit,
getRequiredEnvParam,
getThreadsFlagValue,
initializeEnvironment,
ConfigurationError,
@@ -89,7 +99,6 @@ import {
checkActionVersion,
getErrorMessage,
BuildMode,
getOptionalEnvVar,
} from "./util";
import { checkWorkflow } from "./workflow";
@@ -225,8 +234,7 @@ async function run(
apiDetails = {
auth: getRequiredInput("token"),
externalRepoAuth: getOptionalInput("external-repository-token"),
url: getRequiredEnvParam("GITHUB_SERVER_URL"),
apiURL: getRequiredEnvParam("GITHUB_API_URL"),
...github.getCurrentInstance(actionState.env),
};
const gitHubVersion = await getGitHubVersion();
@@ -249,13 +257,13 @@ async function run(
);
const repositoryProperties = repositoryPropertiesResult.orElse({});
core.exportVariable(EnvVar.INIT_ACTION_HAS_RUN, "true");
actionState.env.export(EnvVar.INIT_ACTION_HAS_RUN, "true");
// path.resolve() respects the intended semantics of source-root. If
// source-root is relative, it is relative to the GITHUB_WORKSPACE. If
// source-root is absolute, it is used as given.
sourceRoot = path.resolve(
getRequiredEnvParam("GITHUB_WORKSPACE"),
actionState.env.getRequired(ActionsEnvVars.GITHUB_WORKSPACE),
getOptionalInput("source-root") || "",
);
@@ -274,7 +282,9 @@ async function run(
}
// Compute the value of the `config-file` input.
const actionStateWithFeatures = { ...actionState, features };
const actionStateWithFeatures = extendActionState(actionState, {
features,
});
configFile = await getConfigFileInput(
actionStateWithFeatures,
repositoryProperties,
@@ -303,6 +313,24 @@ async function run(
const rawLanguages = configUtils.getRawLanguagesNoAutodetect(
getOptionalInput("languages"),
);
const rawConfigInput = getOptionalInput("config");
const configInput =
rawConfigInput === undefined
? undefined
: parseUserConfig(
logger,
"`config` input",
rawConfigInput,
await features.getValue(Feature.ValidateDbConfig),
);
const queriesInput = getOptionalInput("queries");
const otherLanguagePacksReason = getOtherLanguagePacksReason({
configFile,
configInput,
queriesInput,
extraQueriesProperty:
repositoryProperties[RepositoryPropertyName.EXTRA_QUERIES],
});
const useOverlayAwareDefaultCliVersion =
analysisKinds?.length === 1 &&
analysisKinds[0] === AnalysisKind.CodeScanning;
@@ -313,6 +341,7 @@ async function run(
gitHubVersion.type,
codeQLDefaultVersionInfo,
rawLanguages,
otherLanguagePacksReason,
useOverlayAwareDefaultCliVersion,
features,
logger,
@@ -326,7 +355,7 @@ async function run(
// to the workflow log. No exceptions are thrown.
await checkWorkflow(logger, codeql);
// Set CODEQL_ENABLE_EXPERIMENTAL_FEATURES for Rust if between 2.19.3 (included) and 2.22.1 (excluded)
// Set CODEQL_ENABLE_EXPERIMENTAL_FEATURES for Rust if the CLI is older than 2.22.1.
// We need to set this environment variable before initializing the config, otherwise Rust
// analysis will not be enabled (experimental language packs are only active with that environment
// variable set to `true`).
@@ -337,16 +366,10 @@ async function run(
.getRawLanguagesNoAutodetect(getOptionalInput("languages"))
.includes(BuiltInLanguage.rust)
) {
const experimental = "2.19.3";
const publicPreview = "2.22.1";
const actualVer = (await codeql.getVersion()).version;
if (semver.lt(actualVer, experimental)) {
throw new ConfigurationError(
`Rust analysis is supported by CodeQL CLI version ${experimental} or higher, but found version ${actualVer}`,
);
}
if (semver.lt(actualVer, publicPreview)) {
core.exportVariable(EnvVar.EXPERIMENTAL_FEATURES, "true");
actionState.env.export(EnvVar.EXPERIMENTAL_FEATURES, "true");
logger.info("Experimental Rust analysis enabled");
}
}
@@ -363,13 +386,13 @@ async function run(
config = await initConfig(actionStateWithFeatures, {
analysisKinds,
languagesInput: getOptionalInput("languages"),
queriesInput: getOptionalInput("queries"),
queriesInput,
packsInput: getOptionalInput("packs"),
buildModeInput: getOptionalInput("build-mode"),
ramInput: getOptionalInput("ram"),
configFile,
dbLocation: getOptionalInput("db-location"),
configInput: getOptionalInput("config"),
configInput,
dependencyCachingEnabled: getDependencyCachingEnabled(),
// Debug mode is enabled if:
// - The `init` Action is passed `debug: true`.
@@ -383,7 +406,9 @@ async function run(
repository: repositoryNwo,
tempDir: getTemporaryDirectory(),
codeql,
workspacePath: getRequiredEnvParam("GITHUB_WORKSPACE"),
workspacePath: actionState.env.getRequired(
ActionsEnvVars.GITHUB_WORKSPACE,
),
sourceRoot,
githubVersion: gitHubVersion,
apiDetails,
@@ -432,6 +457,18 @@ async function run(
await checkInstallPython311(config.languages, codeql);
} catch (unwrappedError) {
// If we have initialised the Action state, then try to save a subset of it for use by the `init-post` action
// so that it can try to create and upload additional diagnostic information.
if (config !== undefined) {
try {
configUtils.saveAbortedInitConfig(actionState, config);
} catch (configSaveError) {
logger.warning(
`Unable to save configuration for '${ActionName.InitPost}' step: ${getErrorMessage(configSaveError)}`,
);
}
}
const error = wrapError(unwrappedError);
core.setFailed(error.message);
const statusReportBase = await createStatusReportBase(
@@ -492,9 +529,9 @@ async function run(
}
// Forward Go flags
const goFlags = process.env["GOFLAGS"];
const goFlags = actionState.env.getOptional("GOFLAGS");
if (goFlags) {
core.exportVariable("GOFLAGS", goFlags);
actionState.env.export("GOFLAGS", goFlags);
core.warning(
"Passing the GOFLAGS env parameter to the init action is deprecated. Please move this to the analyze action.",
);
@@ -540,7 +577,7 @@ async function run(
// Store the original location of our wrapper script somewhere where we can
// later retrieve it from and cross-check that it hasn't been changed.
core.exportVariable(EnvVar.GO_BINARY_LOCATION, goWrapperPath);
actionState.env.export(EnvVar.GO_BINARY_LOCATION, goWrapperPath);
} catch (e) {
logger.warning(
`Analyzing Go on Linux, but failed to install wrapper script. Tracing custom builds may fail: ${e}`,
@@ -549,7 +586,7 @@ async function run(
} else {
// Store the location of the original Go binary, so we can check that no setup tasks were performed after the
// `init` Action ran.
core.exportVariable(EnvVar.GO_BINARY_LOCATION, goBinaryPath);
actionState.env.export(EnvVar.GO_BINARY_LOCATION, goBinaryPath);
}
} catch (e) {
logger.warning(
@@ -584,12 +621,12 @@ async function run(
// threads it would ask extractors to use. See help text for the "--ram" and "--threads"
// options at https://codeql.github.com/docs/codeql-cli/manual/database-trace-command/
// for details.
core.exportVariable(
actionState.env.export(
"CODEQL_RAM",
process.env["CODEQL_RAM"] ||
getCodeQLMemoryLimit(getOptionalInput("ram"), logger).toString(),
);
core.exportVariable(
actionState.env.export(
"CODEQL_THREADS",
process.env["CODEQL_THREADS"] ||
getThreadsFlagValue(getOptionalInput("threads"), logger).toString(),
@@ -597,21 +634,15 @@ async function run(
// Disable Kotlin extractor if feature flag set
if (await features.getValue(Feature.DisableKotlinAnalysisEnabled)) {
core.exportVariable("CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN", "true");
actionState.env.export(
"CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN",
"true",
);
}
// Emergency override to force the CodeQL CLI back to the JGit-based Git backend.
if (await features.getValue(Feature.ForceJGit)) {
core.exportVariable("CODEQL_GIT_BACKEND", "jgit");
}
const kotlinLimitVar =
"CODEQL_EXTRACTOR_KOTLIN_OVERRIDE_MAXIMUM_VERSION_LIMIT";
if (
(await codeQlVersionAtLeast(codeql, "2.20.3")) &&
!(await codeQlVersionAtLeast(codeql, "2.20.4"))
) {
core.exportVariable(kotlinLimitVar, "2.1.20");
actionState.env.export("CODEQL_GIT_BACKEND", "jgit");
}
// Restore dependency cache(s), if they exist.
@@ -660,7 +691,7 @@ async function run(
config.buildMode === BuildMode.None &&
config.languages.includes(BuiltInLanguage.java)
) {
core.exportVariable(
actionState.env.export(
EnvVar.JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS,
"true",
);
@@ -715,10 +746,10 @@ async function run(
);
}
const tracerConfig = await getCombinedTracerConfig(codeql, config);
const tracerConfig = await getCombinedTracerConfig(logger, codeql, config);
if (tracerConfig !== undefined) {
for (const [key, value] of Object.entries(tracerConfig.env)) {
core.exportVariable(key, value);
actionState.env.export(key, value);
}
}
@@ -726,10 +757,10 @@ async function run(
if (await features.getValue(Feature.JavaNetworkDebugging)) {
// Get the existing value of `JAVA_TOOL_OPTIONS`, if any.
const existingJavaToolOptions =
getOptionalEnvVar(JavaEnvVars.JAVA_TOOL_OPTIONS) || "";
actionState.env.getOptional(JavaEnvVars.JAVA_TOOL_OPTIONS) ?? "";
// Add the network debugging options.
core.exportVariable(
actionState.env.export(
JavaEnvVars.JAVA_TOOL_OPTIONS,
`${existingJavaToolOptions} -Djavax.net.debug=all`,
);

View File

@@ -1,14 +1,13 @@
import * as fs from "fs";
import path from "path";
import * as core from "@actions/core";
import * as github from "@actions/github";
import test, { ExecutionContext } from "ava";
import * as sinon from "sinon";
import * as actionsUtil from "./actions-util";
import { createStubCodeQL } from "./codeql";
import { ActionsEnvVars } from "./environment";
import * as environment from "./environment";
import { Feature } from "./feature-flags";
import {
checkPacksForOverlayCompatibility,
@@ -85,7 +84,7 @@ for (const { runnerEnv, ErrorConstructor, message } of [
`cleanupDatabaseClusterDirectory throws a ${ErrorConstructor.name} when cleanup fails on ${runnerEnv} runner`,
async (t) => {
await withTmpDir(async (tmpDir: string) => {
process.env[ActionsEnvVars.RUNNER_ENVIRONMENT] = runnerEnv;
process.env[environment.ActionsEnvVars.RUNNER_ENVIRONMENT] = runnerEnv;
const dbLocation = path.resolve(tmpDir, "dbs");
fs.mkdirSync(dbLocation, { recursive: true });
@@ -546,7 +545,7 @@ test.serial(
test.serial(
"file coverage deprecation warning for org-owned repo with default setup recommends repo property",
(t) => {
const exportVariableStub = sinon.stub(core, "exportVariable");
const exportEnvVarStub = sinon.stub(environment, "exportEnvVar");
sinon.stub(actionsUtil, "isDefaultSetup").returns(true);
github.context.payload = {
repository: {
@@ -566,14 +565,14 @@ test.serial(
'with the name `github-codeql-file-coverage-on-prs` and the type "True/false", then set this property to ' +
"`true` in the repository's settings.",
);
t.true(exportVariableStub.calledOnce);
t.true(exportEnvVarStub.calledOnce);
},
);
test.serial(
"file coverage deprecation warning for org-owned repo with advanced setup recommends env var and repo property",
(t) => {
const exportVariableStub = sinon.stub(core, "exportVariable");
const exportEnvVarStub = sinon.stub(environment, "exportEnvVar");
sinon.stub(actionsUtil, "isDefaultSetup").returns(false);
github.context.payload = {
repository: {
@@ -594,14 +593,14 @@ test.serial(
'with the name `github-codeql-file-coverage-on-prs` and the type "True/false", then set this property to ' +
"`true` in the repository's settings.",
);
t.true(exportVariableStub.calledOnce);
t.true(exportEnvVarStub.calledOnce);
},
);
test.serial(
"file coverage deprecation warning for user-owned repo with default setup recommends advanced setup",
(t) => {
const exportVariableStub = sinon.stub(core, "exportVariable");
const exportEnvVarStub = sinon.stub(environment, "exportEnvVar");
sinon.stub(actionsUtil, "isDefaultSetup").returns(true);
github.context.payload = {
repository: {
@@ -620,14 +619,14 @@ test.serial(
"To opt out of this change, switch to an advanced setup workflow and " +
"set the `CODEQL_ACTION_FILE_COVERAGE_ON_PRS` environment variable to `true`.",
);
t.true(exportVariableStub.calledOnce);
t.true(exportEnvVarStub.calledOnce);
},
);
test.serial(
"file coverage deprecation warning for user-owned repo with advanced setup recommends env var",
(t) => {
const exportVariableStub = sinon.stub(core, "exportVariable");
const exportEnvVarStub = sinon.stub(environment, "exportEnvVar");
sinon.stub(actionsUtil, "isDefaultSetup").returns(false);
github.context.payload = {
repository: {
@@ -645,14 +644,14 @@ test.serial(
"to improve analysis performance. File coverage information will still be computed on non-PR analyses.\n\n" +
"To opt out of this change, set the `CODEQL_ACTION_FILE_COVERAGE_ON_PRS` environment variable to `true`.",
);
t.true(exportVariableStub.calledOnce);
t.true(exportEnvVarStub.calledOnce);
},
);
test.serial(
"file coverage deprecation warning for unknown owner type with default setup recommends advanced setup",
(t) => {
const exportVariableStub = sinon.stub(core, "exportVariable");
const exportEnvVarStub = sinon.stub(environment, "exportEnvVar");
sinon.stub(actionsUtil, "isDefaultSetup").returns(true);
github.context.payload = { repository: undefined };
const messages: LoggedMessage[] = [];
@@ -666,14 +665,14 @@ test.serial(
"To opt out of this change, switch to an advanced setup workflow and " +
"set the `CODEQL_ACTION_FILE_COVERAGE_ON_PRS` environment variable to `true`.",
);
t.true(exportVariableStub.calledOnce);
t.true(exportEnvVarStub.calledOnce);
},
);
test.serial(
"file coverage deprecation warning for unknown owner type with advanced setup recommends env var",
(t) => {
const exportVariableStub = sinon.stub(core, "exportVariable");
const exportEnvVarStub = sinon.stub(environment, "exportEnvVar");
sinon.stub(actionsUtil, "isDefaultSetup").returns(false);
github.context.payload = { repository: undefined };
const messages: LoggedMessage[] = [];
@@ -686,7 +685,7 @@ test.serial(
"to improve analysis performance. File coverage information will still be computed on non-PR analyses.\n\n" +
"To opt out of this change, set the `CODEQL_ACTION_FILE_COVERAGE_ON_PRS` environment variable to `true`.",
);
t.true(exportVariableStub.calledOnce);
t.true(exportEnvVarStub.calledOnce);
},
);
@@ -695,10 +694,10 @@ test.serial(
(t) => {
process.env["CODEQL_ACTION_DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION"] =
"true";
const exportVariableStub = sinon.stub(core, "exportVariable");
const exportEnvVarStub = sinon.stub(environment, "exportEnvVar");
const messages: LoggedMessage[] = [];
logFileCoverageOnPrsDeprecationWarning(getRecordingLogger(messages));
t.is(messages.length, 0);
t.true(exportVariableStub.notCalled);
t.true(exportEnvVarStub.notCalled);
},
);

View File

@@ -1,7 +1,6 @@
import * as fs from "fs";
import * as path from "path";
import * as core from "@actions/core";
import * as toolrunner from "@actions/exec/lib/toolrunner";
import * as github from "@actions/github";
import * as io from "@actions/io";
@@ -17,7 +16,7 @@ import {
import { GitHubApiDetails } from "./api-client";
import { CodeQL, setupCodeQL } from "./codeql";
import * as configUtils from "./config-utils";
import { EnvVar } from "./environment";
import { EnvVar, exportEnvVar } from "./environment";
import {
CodeQLDefaultVersionInfo,
Feature,
@@ -40,6 +39,7 @@ export async function initCodeQL(
variant: util.GitHubVariant,
defaultCliVersion: CodeQLDefaultVersionInfo,
rawLanguages: string[] | undefined,
otherLanguagePacksReason: string | undefined,
useOverlayAwareDefaultCliVersion: boolean,
features: FeatureEnablement,
logger: Logger,
@@ -58,6 +58,7 @@ export async function initCodeQL(
variant,
defaultCliVersion,
rawLanguages,
otherLanguagePacksReason,
useOverlayAwareDefaultCliVersion,
features,
logger,
@@ -409,5 +410,5 @@ export function logFileCoverageOnPrsDeprecationWarning(logger: Logger): void {
}
logger.warning(message);
core.exportVariable(EnvVar.DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION, "true");
exportEnvVar(EnvVar.DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION, "true");
}

Some files were not shown because too many files have changed in this diff Show More