Compare commits

...

1407 Commits

Author SHA1 Message Date
Edoardo Pirovano
84173b94c9 Merge pull request #621 from github/update-v1.0.6-3c8ba717
Merge main into v1
2021-07-19 10:32:25 +01:00
Edoardo Pirovano
8cbe2f5527 Update CHANGELOG.md
Minor formatting improvement.
2021-07-19 10:08:29 +01:00
github-actions[bot]
c302d35e73 1.0.6 2021-07-19 09:01:53 +00:00
Andrew Eisenberg
3c8ba71769 Merge pull request #619 from github/aeisenberg/fix-vulnerabilities
Fix dependabot vulnerabilities
2021-07-14 19:53:52 -07:00
Andrew Eisenberg
ae97d8f96d Fix dependabot vulnerabilities
This adds some forced resolutions to ensure that vulnerable versions
of packages are not installed.
2021-07-14 14:40:10 -07:00
Aditya Sharad
14deaf67e9 Merge pull request #610 from github/aibaars/refactor-checkout-path
Replace checkoutPath variable with sourceRoot/workspacePath variables
2021-07-14 08:14:27 -07:00
Aditya Sharad
d7dcff944e Merge branch 'main' into aibaars/refactor-checkout-path 2021-07-14 07:58:23 -07:00
Robert
4aa2d05c6b Merge pull request #612 from github/robertbrignull/databases_url
Update databases URL
2021-07-14 15:30:40 +01:00
Robert
d09d89f419 Merge branch 'main' into robertbrignull/databases_url 2021-07-14 15:15:50 +01:00
Arthur Baars
f94f1ed663 Rename checkoutPath to either workspacePath or sourceRoot 2021-07-14 13:39:45 +02:00
Edoardo Pirovano
1137e7db3e Merge pull request #618 from edoardopirovano/python-deps
Install Python tools on self-hosted runners
2021-07-13 17:56:13 +01:00
Edoardo Pirovano
cc14f298d6 Install Python tools on self-hosted runners 2021-07-13 17:24:11 +01:00
Robert
96edcdfd20 use templating for language param 2021-07-13 17:05:40 +01:00
Robert
b0b9ab80cc Update databases URL 2021-07-13 14:09:56 +01:00
Arthur Baars
3b017efdfe Merge pull request #607 from mario-campos/source-root-input
Add a 'source-root' input to the init Action
2021-07-13 13:26:14 +02:00
Arthur Baars
993205272b Merge branch 'main' into source-root-input 2021-07-13 13:13:27 +02:00
Andrew Eisenberg
27e3080228 Merge pull request #617 from github/mergeback/v1.0.5-to-main-500dad96
Mergeback v1.0.5 refs/heads/v1 into main
2021-07-12 16:16:04 -07:00
github-actions[bot]
92df23808d 1.0.6 2021-07-12 23:03:41 +00:00
github-actions[bot]
a10ed6c610 Update changelog and version after v1.0.5 2021-07-12 23:03:39 +00:00
Aditya Sharad
500dad96d7 Merge pull request #616 from github/update-v1.0.5-1c26d408
Merge main into v1
2021-07-12 16:03:11 -07:00
github-actions[bot]
aa03f9b023 1.0.5 2021-07-12 21:54:31 +00:00
Mario Campos
a4a91a8631 Merge branch 'main' into source-root-input 2021-07-02 16:20:05 -05:00
Mario Campos
06c6845442 Add analyze step to 'source-root' input test case
Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>
2021-07-02 14:50:52 -05:00
Henning Makholm
1c26d40826 Merge pull request #613 from github/hmakholm/pr/2.5.7
Update CodeQL bundle to 20210702 / 2.5.7
2021-07-02 15:25:27 +02:00
Mario Campos
b9217ca238 Test presence of database instead of results of analysis
This is for PR #607, 'source-root' input test case.
2021-07-02 08:07:06 -05:00
Henning Makholm
870e8e38d5 Update CodeQL bundle to 20210702 / 2.5.7 2021-07-02 14:32:46 +02:00
Mario Campos
2c0da4bcc7 Remove build.sh step from 'source-root' test
As this test is using only JS, it's not necessary to compile or analyze the other languages.
2021-07-01 18:43:10 -05:00
Mario Campos
12f1cff212 Rename CodeQL action paths in 'source-root' test to reflect repo paths 2021-07-01 18:39:37 -05:00
Mario Campos
2ca807cf16 Merge branch 'source-root-input' of github.com:mario-campos/codeql-action into source-root-input 2021-07-01 18:37:07 -05:00
Mario Campos
1c69fae407 Avoid moving repo files out of \$GITHUB_WORKSPACE in 'source-root' test
Moving the files into ../action was causing the job to fail because it couldn't find the test directory anymore. According to @adityasharad, these 'mv's should
not be necessary. Removing these means changing the path to the actions.

I'm also removing the 'config-file' input to keep the test minimal. I think this will mean that CodeQL will use the default query suite, so I hope that this doesn't change the results.
2021-07-01 18:34:34 -05:00
Mario Campos
67d6f7929f Delete 'packaing' from source-root test job name
The test is not related to packaging.

Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>
2021-07-01 18:31:50 -05:00
Mario Campos
028f98f5ea Use different config file for testing 'source-root' input
This config file 'ought to have some queries good for testing!
2021-07-01 16:12:15 -05:00
Mario Campos
c78fb87659 Add test case for 'source-root' input to 'init' Action 2021-07-01 15:26:04 -05:00
Mario Campos
45c0f11af2 Clarify 'source-root' description to include default path
This addresses @adityasharad's suggestions in PR #607.
2021-07-01 12:24:36 -05:00
Aditya Sharad
c6728b6769 Merge branch 'main' into source-root-input 2021-07-01 09:36:10 -07:00
Andrew Eisenberg
fd614e5792 Merge pull request #609 from github/aeisenberg/use-default-tools
Remove a TODO and use defautl tools option
2021-06-30 13:56:10 -07:00
Andrew Eisenberg
0792832682 Remove a TODO and use defautl tools option 2021-06-30 12:43:20 -07:00
Mario Campos
a607042aab Recompile code after accepting suggestions from PR #607 review 2021-06-30 12:36:51 -05:00
Mario Campos
35e1b55411 Use path.resolve instead of path.join for sourceRoot
Thanks to @aibaars, `path.resolve()` should will nicely handle more use-cases, namely absolute paths better than `path.join()`.

Co-authored-by: Arthur Baars <aibaars@github.com>
2021-06-30 12:34:12 -05:00
Mario Campos
66df091046 Refer to $GITHUB_WORKSPACE specifically in source-root description
Previously, I had tried to refer to '${{ github.workspace }}', but that caused a problem in Actions. Trying to avoid the issue, I changed this to "the workspace," but this gives up quite a bit of specificity.

Co-authored-by: Arthur Baars <aibaars@github.com>
2021-06-30 12:32:07 -05:00
Andrew Eisenberg
c6b33b9ec1 Merge pull request #608 from github/aeisenberg/baseline-message
Clarify missing LoC baseline message
2021-06-30 09:27:04 -07:00
Andrew Eisenberg
d939c4b8d3 Update CHANGELOG 2021-06-30 09:13:29 -07:00
Andrew Eisenberg
68f742b0d4 Clarify missing LoC baseline message 2021-06-30 09:11:15 -07:00
Mario Campos
e1cd5244c8 Recompile JS files to bring JS inline with TS for PR #607 2021-06-29 16:17:28 -05:00
Mario Campos
57f584a881 Update CHANGELOG for PR #607 2021-06-29 16:14:47 -05:00
Mario Campos
a05a7f9cb1 Remove '${{ github.workspace }}' from action.yml
It causes the action to break (or rather that context being unavailable causes it to fail), despite it being in the description field.
2021-06-29 16:05:45 -05:00
Mario Campos
337ae83a84 Make 'source-root' init input relative to github.workspace
In the previous commit, the default value of the input is ${{ github.workspace }}
which means that most uses of this input would probably prefix their paths with
${{ github.workspace }}, especially since actions/checkout's 'path' input
must be under ${{ github.workspace }}. Therefore, it doesn't make much sense for
this to be an absolute file path.

Instead, it's more intuitive to make this relative to the repository.
2021-06-29 16:00:55 -05:00
Mario Campos
42babdf2c1 Add 'source-root' input to init action
This input is exposed in the CodeQL CLI as the flag --source-root, allowing
users of the CLI to set --source-root different from --working-dir. However,
in codeql-action, these two paths are conflated and it poses problems for
users with complicated build environments, in which a source root may be
a child of the working directory.

Most users should not notice this, as the default value is
${{ github.workspace }}, as it is implied now (`path.resolve()`).
2021-06-29 15:16:32 -05:00
Edoardo Pirovano
c357ca73e4 Merge pull request #606 from edoardopirovano/local-bundle
Allow local instead of downloaded CodeQL
2021-06-29 00:03:59 +01:00
Edoardo Pirovano
d9050f49a3 Merge branch 'main' into local-bundle 2021-06-28 23:53:41 +01:00
Edoardo Pirovano
a7dac5c3db Address PR comment. 2021-06-28 23:52:53 +01:00
Edoardo Pirovano
53cf5d984d Merge pull request #602 from edoardopirovano/split-create-analysis
Support splitting of DB creation and query execution
2021-06-28 18:43:05 +01:00
Edoardo Pirovano
93214eca2e Merge branch 'main' into split-create-analysis 2021-06-28 18:25:01 +01:00
Edoardo Pirovano
8f4c2c76ad Allow local instead of downloaded CodeQL 2021-06-28 18:11:13 +01:00
Edoardo Pirovano
24ef87cfc3 Merge pull request #600 from edoardopirovano/integration-test
Run tests against nightly CLI bundles
2021-06-28 18:08:36 +01:00
Edoardo Pirovano
954700187b Run tests against nightly CLI bundles 2021-06-28 17:47:10 +01:00
Edoardo Pirovano
4a7cc176ac Merge pull request #605 from github/aeisenberg/pr-checks-dispatch
Allow  to be run on workflow_dispatch
2021-06-28 17:45:56 +01:00
Andrew Eisenberg
a6891153f0 Allow to be run on workflow_dispatch 2021-06-28 09:17:32 -07:00
Edoardo Pirovano
ef852c006a Support splitting of DB creation and query execution 2021-06-28 17:14:22 +01:00
Edoardo Pirovano
1e61ecb0c1 Merge pull request #603 from github/mergeback/v1.0.4-to-main-03450ff6
Mergeback v1.0.4 refs/heads/v1 into main
2021-06-28 16:57:01 +01:00
Edoardo Pirovano
8cccc0664b Merge branch 'main' into mergeback/v1.0.4-to-main-03450ff6 2021-06-28 16:42:39 +01:00
Andrew Eisenberg
3a8e1847c5 Merge pull request #599 from github/aeisenberg/readme-missing-analysis
Update readme to include section on missing analysis
2021-06-28 08:30:15 -07:00
github-actions[bot]
5c3c29fd3f 1.0.5 2021-06-28 15:23:49 +00:00
github-actions[bot]
d11b2ce6a3 Update changelog and version after v1.0.4 2021-06-28 15:23:47 +00:00
Edoardo Pirovano
03450ff6ed Merge pull request #601 from github/update-v1.0.4-7726ece0
Merge main into v1
2021-06-28 16:23:20 +01:00
Andrew Eisenberg
571fe400df Merge branch 'main' into aeisenberg/readme-missing-analysis 2021-06-28 08:18:18 -07:00
Edoardo Pirovano
440ccbd910 Prepare CHANGELOG for 1.0.4 2021-06-28 16:06:44 +01:00
github-actions[bot]
6017205208 1.0.4 2021-06-28 16:05:56 +01:00
Andrew Eisenberg
7726ece0ab Merge pull request #591 from github/aeisenberg/pack-in-inputs
Add new `packs` input to init action
2021-06-25 10:52:19 -07:00
Andrew Eisenberg
7c391e9640 Update readme to include section on missing analysis
Fixes #598
2021-06-25 10:44:47 -07:00
Andrew Eisenberg
67312df7cf Merge branch 'main' into aeisenberg/pack-in-inputs 2021-06-25 10:30:24 -07:00
Andrew Eisenberg
4087f37d90 Add extra integration test for packaging
Also, update the options and inputs documentation.
2021-06-25 10:07:51 -07:00
Edoardo Pirovano
85ac9fe26e Remove misleading comment. 2021-06-25 14:28:43 +01:00
Edoardo Pirovano
40852fa52a Improve error messages from CLI invocations 2021-06-24 23:38:13 +01:00
Andrew Eisenberg
db80a9a7c3 Merge pull request #594 from github/simon-engledew/fix-runner-temp-missing
Restore original getCodeQLActionRepository behaviour
2021-06-24 13:58:42 -07:00
Andrew Eisenberg
af32a29f03 Merge branch 'main' into simon-engledew/fix-runner-temp-missing 2021-06-24 13:48:45 -07:00
Arthur Baars
590c245b56 Merge pull request #593 from github/aibaars/ruby-is-interpreted
Add Ruby to 'isInterpretedLanguage'
2021-06-24 19:23:57 +02:00
Arthur Baars
a1f71cfecf Add Ruby to 'isInterpretedLanguage' 2021-06-24 19:13:05 +02:00
Simon Engledew
26ade03b50 Just reverse test case 2021-06-24 18:00:10 +01:00
Simon Engledew
9200db3ec4 Restore original getCodeQLActionRepository behaviour 2021-06-24 17:52:48 +01:00
Andrew Eisenberg
ac402bf222 Merge pull request #586 from edoardopirovano/csharp-loc
Fix C# line counting and add test
2021-06-23 17:29:02 -07:00
Andrew Eisenberg
9f37000f6b Fix dependencies 2021-06-23 16:38:32 -07:00
Andrew Eisenberg
c5434c91d8 Merge branch 'main' into csharp-loc 2021-06-23 16:22:14 -07:00
Andrew Eisenberg
e38356b367 Update lock file 2021-06-23 16:11:57 -07:00
Andrew Eisenberg
6e577cfca3 Add new packs input to init action
This input allows users to specify which packs to run. It works in
unison with the packs block of the config file and it is similar to
how `queries` works. They both use `+` in the same way.

Note that the `#TODO` in the pr check is still around, but the CLI
is available. I will remove the TODO in the next commit.
2021-06-23 16:08:35 -07:00
Edoardo Pirovano
68b68732c6 Fix C# line counting and add test 2021-06-23 23:39:44 +01:00
Andrew Eisenberg
7729b51956 Merge pull request #588 from github/mergeback/v1.0.3-to-main-cf6e0194
Mergeback v1.0.3 refs/heads/v1 into main
2021-06-23 08:23:18 -07:00
Andrew Eisenberg
c98b43187d Merge branch 'main' into mergeback/v1.0.3-to-main-cf6e0194 2021-06-23 08:08:49 -07:00
Chris Gavin
e684c09260 Merge pull request #587 from github/toolcache-upgrade
Upgrade the tool cache library and use it to download the CodeQL bundle.
2021-06-23 16:07:26 +01:00
github-actions[bot]
1496843315 1.0.4 2021-06-23 14:56:35 +00:00
github-actions[bot]
f5a5d3ad5f Update changelog and version after v1.0.3 2021-06-23 14:56:23 +00:00
Andrew Eisenberg
cf6e019480 Merge pull request #585 from github/update-v1.0.3-d623a7a3
Merge main into v1
2021-06-23 07:55:54 -07:00
Chris Gavin
59560e54ac Replace custom tool download method with the one in the tool cache library. 2021-06-23 14:28:37 +01:00
Chris Gavin
476f13ea18 Upgrade Actions Tool Cache. 2021-06-23 14:28:33 +01:00
github-actions[bot]
a12bb22724 1.0.3 2021-06-23 09:42:14 +00:00
Andrew Eisenberg
d623a7a3f7 Merge pull request #583 from github/aeisenberg/changelog-template
Update changelog template
2021-06-22 14:40:52 -07:00
Andrew Eisenberg
629f582c03 Update changelog template
The changelog for an empty version will now be:

```
No user facing changes.
```

And this will appear in the final changelog when there is an actual release.
The benefits are that users will see regular release cycles and know
how old versions are even if there's no changes for a particular version

If we find that we are going months without any user facing changes, but
we have non-visible changes, then we can rethink this strategy.
But I think this is nicer than having empty sections for a version.
2021-06-22 14:25:06 -07:00
Henning Makholm
9821b8c68c Merge pull request #582 from github/hmakholm/pr/2.5.6
Update CodeQL bundle to 20210622 / 2.5.6
2021-06-22 18:43:19 +02:00
Henry Mercer
1cd2cd12b4 Merge branch 'main' into hmakholm/pr/2.5.6 2021-06-22 17:12:00 +01:00
Robert
171619a51a Merge pull request #578 from github/upload-database
Upload CodeQL databases - mk2
2021-06-22 17:09:46 +01:00
Henning Makholm
8d50a5fd90 Update CodeQL bundle to 20210622 / 2.5.6 2021-06-22 17:27:16 +02:00
Robert
00791d5d56 remove old lib file 2021-06-22 13:45:47 +01:00
Robert
146c897909 Upload CodeQL databases 2021-06-22 13:05:12 +01:00
Andrew Eisenberg
b2d10b39b0 Merge pull request #571 from github/mergeback/v1.0.2-to-main-37f75f17
Mergeback v1.0.2 refs/heads/v1 into main
2021-06-21 08:42:17 -07:00
Andrew Eisenberg
b2e7277fb1 Merge branch 'main' into mergeback/v1.0.2-to-main-37f75f17 2021-06-21 08:29:15 -07:00
Robert
dbc4fdad80 Merge pull request #577 from github/revert-573-upload-database
Revert "Upload CodeQL databases"
2021-06-21 10:58:55 +01:00
Robert
d893508e3a Revert "Upload CodeQL databases" 2021-06-21 10:26:02 +01:00
Robert
f6d1bad81b Merge pull request #573 from github/upload-database
Upload CodeQL databases
2021-06-21 08:45:03 +01:00
Robert
f3cd5fa001 Add workflow input to disable uploads 2021-06-18 09:56:15 +01:00
Robert
33ac512514 Merge branch 'main' into upload-database 2021-06-18 09:50:05 +01:00
Andrew Eisenberg
6a7c2369bf Merge pull request #569 from github/aeisenberg/add-codeowners
Add a CODEOWNERS file
2021-06-17 11:36:23 -07:00
github-actions[bot]
4954c371d1 1.0.3 2021-06-17 18:01:57 +00:00
github-actions[bot]
c35646fe13 Update changelog and version after v1.0.2 2021-06-17 18:01:56 +00:00
Andrew Eisenberg
37f75f1702 Merge pull request #570 from github/update-v1.0.2-0b1f4a01
Merge main into v1
2021-06-17 11:01:25 -07:00
github-actions[bot]
028a76e6db 1.0.2 2021-06-17 10:39:32 -07:00
Andrew Eisenberg
9c28349a87 Merge branch 'main' into aeisenberg/add-codeowners 2021-06-17 10:27:42 -07:00
Andrew Eisenberg
0b1f4a016a Merge pull request #566 from github/aeisenberg/update-release-branch-fix
Fix update-release-branch-fix.py
2021-06-17 10:22:26 -07:00
Andrew Eisenberg
b4914d76a2 Add a CODEOWNERS file 2021-06-17 10:19:01 -07:00
Robert
69c30da5ad Merge pull request #565 from github/robertbrignull/upload_ghes
Only attempt to upload on dotcom
2021-06-17 12:42:23 +01:00
Robert
6fc1280a3c Merge pull request #564 from github/robertbrignull/workflow_event_error
Provide a better error message
2021-06-17 09:36:47 +01:00
Andrew Eisenberg
efea9238bc Fix custom version of CLI to use for package testing
This can be removed when 2.5.6 is released.
2021-06-16 14:56:52 -07:00
Andrew Eisenberg
d16268b273 Fix update-release-branch-fix.py
This change ensures that the the script can handle
commits with no committer in them. This will happen
for some commits that are auto-generated during
PRs.
2021-06-16 10:38:18 -07:00
Robert
b985a67b97 Only attempt to upload on dotcom 2021-06-16 17:24:26 +01:00
Robert
c989ee7b39 Provide a better error message 2021-06-16 17:00:26 +01:00
Robert
366b68eda0 Merge pull request #563 from github/robertbrignull/check_default_branch
Check if on default branch before uploading database
2021-06-16 15:11:45 +01:00
Robert
d693b3cb0d Check if on default branch before uploading database 2021-06-16 14:43:42 +01:00
Andrew Eisenberg
e284efba72 Merge pull request #545 from github/aeisenberg/pack-run
Allow the codeql-action to run packages
2021-06-10 11:24:56 -07:00
Andrew Eisenberg
20aafcd90c Remove unnecessary type assertions 2021-06-10 11:15:03 -07:00
Robin Neatherway
429471162a Update cleanup to bundle 2021-06-10 17:09:58 +01:00
Robert
2a9a602a5e Upload databases from analyze action 2021-06-10 16:09:58 +01:00
Andrew Eisenberg
6a1c0700c3 Avoid running mergeback workflow on PR
This was causing the workflow to run and create tags after merging
main into a branch.
2021-06-09 14:38:09 -07:00
Andrew Eisenberg
23cdd6bab6 Remove two log entries
Cleans up the output logs even more. These entries don't add any more
information since everything is grouped now.
2021-06-09 14:32:08 -07:00
Andrew Eisenberg
a2e96a4c78 Add pack download to its own log group
Also, make the baseline count message less awkward sounding.
2021-06-09 14:13:05 -07:00
Andrew Eisenberg
96e7de35af Use nullish conversion for packs
Slightly simplifies the `parsePacks` function.
2021-06-09 13:18:27 -07:00
Andrew Eisenberg
49b2220f92 Refactor codeql.ts
Extract a `runTool` function that captures the stdout and returns it.
A small refactoring that reduces copied code.
2021-06-09 13:17:25 -07:00
Andrew Eisenberg
db01c78de0 Remove unneeded action input in PR check 2021-06-09 13:10:57 -07:00
Andrew Eisenberg
82388fd94a Merge remote-tracking branch 'upstream/main' into aeisenberg/pack-run 2021-06-09 12:43:17 -07:00
Edoardo Pirovano
babcc1b793 Add --finalize-dataset to database finalize call 2021-06-09 16:52:39 +01:00
Edoardo Pirovano
06df98a513 Add new log grouping for DB cleanup 2021-06-09 16:10:22 +01:00
Edoardo Pirovano
0ea20c5b32 Add intepret-results timings to status reports 2021-06-09 10:40:15 +01:00
Andrew Eisenberg
d42f654f7a Add an integration test for packaging
Uses two pre-existing packages to run some simple queries on a javascript
database.
2021-06-08 12:34:07 -07:00
Andrew Eisenberg
1cc5f1d5dd Packaging: Address review comments
1. Better malformed data guard for PackDownloadOutput
2. Fix Packs type
3. Remove TODO in init-action
2021-06-08 10:00:22 -07:00
Edoardo Pirovano
2cc885d66e Replace analyze with run-queries and interpret-results 2021-06-08 09:25:17 +01:00
Edoardo Pirovano
c09500540c Some refactoring in fingerprint computation 2021-06-08 00:09:27 +01:00
Andrew Eisenberg
9c13fefc68 Merge pull request #554 from github/mergeback/v1.0.1-to-main-ece2addc
Mergeback v1.0.1 refs/heads/v1 into main
2021-06-07 14:14:54 -07:00
Andrew Eisenberg
a69f472ee9 Merge branch 'main' into mergeback/v1.0.1-to-main-ece2addc 2021-06-07 14:01:04 -07:00
github-actions[bot]
fbb9046bf6 1.0.2 2021-06-07 20:59:15 +00:00
github-actions[bot]
9e6b46a9e6 Update changelog and version after v1.0.1 2021-06-07 20:59:13 +00:00
Andrew Eisenberg
ece2addcff Merge pull request #553 from github/aeisenberg/no-quotes
Remove quotes around `$DRAFT` argument
2021-06-07 13:54:37 -07:00
Andrew Eisenberg
74764ac0eb Remove quotes around $DRAFT argument
gh will complain if there is an empty `""`, which is the case if
`$DRAFT` is unset.
2021-06-07 13:53:47 -07:00
Chris Gavin
675843d09a Merge pull request #549 from github/update-v1.0.1-242fd828
Merge main into v1
2021-06-07 16:26:37 +01:00
Chris Gavin
511fe43abe Empty commit to trigger CI. 2021-06-07 16:14:10 +01:00
Edoardo Pirovano
02e8dcfe9c Fix out of memory in hash computation 2021-06-07 15:12:45 +01:00
github-actions[bot]
68d7c5f620 1.0.1 2021-06-07 09:30:01 +00:00
Chris Gavin
242fd828aa Merge pull request #547 from github/retrying-fix
Add back retrying.
2021-06-07 08:04:21 +01:00
Chris Gavin
48efe6e282 Merge branch 'main' into retrying-fix 2021-06-07 07:47:18 +01:00
Chris Gavin
f8c65b775d Fix stub in tests. 2021-06-07 07:14:44 +01:00
Andrew Eisenberg
d87945e9fd Run the pack download command 2021-06-06 09:27:52 -07:00
Edoardo Pirovano
1644ade514 Add --sarif-group-rules-by-pack flag 2021-06-06 09:56:54 +01:00
Andrew Eisenberg
06687e95c8 Avoid using SemVer instances
Use strings instead. They are easier to serialize and deserialize.
2021-06-04 13:34:55 -07:00
Andrew Eisenberg
9b5753ab00 Fix logic for calculating if there are queries to run
During the analyze phase.
2021-06-04 13:23:35 -07:00
Edoardo Pirovano
ddb83a462d Cleanup CodeQL DBs and output their location for later steps 2021-06-04 18:54:15 +01:00
Andrew Eisenberg
6cee818bf3 Add better comments and error messages for pack-related changes 2021-06-04 10:18:24 -07:00
Chris Gavin
41dff7fce3 Add back retrying. 2021-06-04 15:51:51 +01:00
Andrew Eisenberg
86a804f9a7 Allow the codeql-action to run packages
This commit adds a `packs` option to the codeql-config.yml file. Users
can specify a list of ql packs to include in the analysis.

For a single language analysis, the packs property looks like this:

```yaml
packs:
  - pack-scope/pack-name1@1.2.3
  - pack-scope/pack-name2   # no explicit version means download the latest
```

For multi-language analysis, you must key the packs block by lanaguage:

```yaml
packs:
  cpp:
    - pack-scope/pack-name1@1.2.3
    - pack-scope/pack-name2
  java:
    - pack-scope/pack-name3@1.2.3
    - pack-scope/pack-name4
```

This implementation adds a new analysis run (alongside custom and 
builtin runs). The unit tests indicate that the correct commands are
being run, but I have not actually tried this with a real CLI.

Also, convert `instanceof Array` to `Array.isArray` since that is
sightly better in some situations. See:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#instanceof_vs_isarray
2021-06-03 15:46:40 -07:00
Andrew Eisenberg
cbdf0df97b Merge pull request #539 from github/aeisenberg/env-vars
Add environment variables to signal feature and version to the CLI
2021-06-03 15:35:17 -07:00
Andrew Eisenberg
f60ef170b0 Cleaning up comments around env vars
Also, move `getTemporaryDirectory` back to `actions-util`.
2021-06-03 11:33:20 -07:00
Andrew Eisenberg
cc0733fd12 Fix Unguarded actions library use code scanning error
Must access the env var directly in order to avoid recursive calls to 
`getRequiredEnvParam`.
2021-06-02 11:55:32 -07:00
Andrew Eisenberg
082575fbc3 Merge branch 'main' into aeisenberg/env-vars 2021-06-02 11:40:40 -07:00
Andrew Eisenberg
2c2ebdc5c5 Remove local environment running
This is a functionality that never worked perfectly and hasn't been
used for a while.

This allows developers to run the action on their local machine, but
the run was always flaky and never 100% mirrored what was happening on
the actions runner.
2021-06-02 11:26:11 -07:00
Andrew Eisenberg
3708898bf2 Add environment variables to signal feature and version to the CLI
This PR ensures environment variables are set before any invocation of
the CLI.  Here is a list of vars that are set:

https://github.com/github/codeql-coreql-team/issues/1124#issuecomment-852463521

This ensures the CLI knows the features and versions of the containing
actions/runner.

Additionally:

- Fix the user agent so that it more closely aligns with user agent
  spec
- Refactor environment variable initialization so that it all happens in
  one place and call.
- Move Mode, getRequiredEnvParam, setMode, getMode out of actions-util
  and into util. actions-util is meant for utils only called by the
  action, not the runner.

The `prepareLocalRunEnvironment()` method is most likely deprecated and
should be removed. I originally added it because I had a way of working
where I would run the action from my local machine to test out changes,
but this was always a little flaky. So, I no longer use this way of
working. I will probably remove it soon.
2021-06-02 11:06:02 -07:00
Aditya Sharad
1ec2fd7ea1 Merge pull request #542 from github/robertbrignull/import-actions-lib
Update unguarded-action-lib.ql to catch uses of actions-util.ts
2021-06-02 09:56:37 -07:00
Robert
61b561867b Update unguarded-action-lib.ql 2021-06-02 16:51:30 +01:00
Andrew Eisenberg
4ac9009dfe Merge pull request #541 from github/update-supported-enterprise-server-versions
Update supported GitHub Enterprise Server versions.
2021-06-02 08:28:15 -07:00
Andrew Eisenberg
e8486b0d6c Merge branch 'main' into update-supported-enterprise-server-versions 2021-06-02 08:14:19 -07:00
Edoardo Pirovano
0cbd4b56d3 Add some dependencies for uploading artifacts 2021-06-02 10:32:48 +01:00
Andrew Eisenberg
739e14d879 Merge branch 'main' into update-supported-enterprise-server-versions 2021-06-01 22:40:01 -07:00
Andrew Eisenberg
1d05ad7576 Merge pull request #536 from github/aeisenberg/commander
Use commander preAction hook for setMode
2021-06-01 18:35:01 -07:00
GitHub
2fee1242f4 Update supported GitHub Enterprise Server versions. 2021-06-02 00:23:42 +00:00
Andrew Eisenberg
539d968ad7 Use commander preAction hook for setMode
Hooks are new to commander v8. We can use hooks to ensure that `setMode`
is called before every command is invoked.
2021-06-01 11:17:49 -07:00
Andrew Eisenberg
4b4a5ee9d1 Merge pull request #534 from github/aeisenberg/mergeback-fix
Fix the mergeback workflow
2021-06-01 10:35:47 -07:00
Andrew Eisenberg
f0e82b7d63 1.0.1 2021-05-31 10:56:52 -07:00
Andrew Eisenberg
c02d8cc7a9 Fix EOF newlines after npm version patch
The removeNPMAbsolutePaths check requires no newlines at the
end of the file. This ensures that the version update mimics
the behavior.
2021-05-31 10:37:07 -07:00
Andrew Eisenberg
a94829cc53 Manually update the CHANGELOG
This should have happened in a mergeback PR, but the workflow to
generate this was broken.
2021-05-31 10:11:08 -07:00
Andrew Eisenberg
7d701d23e3 Merge remote-tracking branch 'upstream/v1' into aeisenberg/mergeback-fix 2021-05-31 10:09:13 -07:00
Andrew Eisenberg
981b5cb012 Fix the mergeback workflow
We need to tag and mergeback if the tag does _not_ already exist.
2021-05-31 10:08:10 -07:00
Andrew Eisenberg
ca9450846f Merge pull request #516 from github/aeisenberg/user-agent
Send version and mode to code scanning via user agent
2021-05-31 09:49:44 -07:00
Andrew Eisenberg
1a4cdd35b9 Use the version from package.json in the runner 2021-05-31 09:35:13 -07:00
Andrew Eisenberg
4164096c0d Use the version from package.json in the runner
Update the ql queries to account for change in how we look for runner

Previously, we guarded blocks of code to be run by the runner or the
action using if statements like this:

```js
if (mode === "actions") ...
```

We are no longer doing this. And now, the `unguarded-action-lib.ql`
query is out of date. This query checks that runner code does not
unintentionally access actions-only methods in the libraries.

With these changes, we now ensure that code scanning is happy.
2021-05-31 09:34:41 -07:00
Andrew Eisenberg
47588796b4 Send the version and mode with the user agent
This commit changes the way the action determines if running in action
or runner mode. There is now an environment variable that is set at the
beginning of the process and elsewhere in the process, we can check to
see if the variable is set.
2021-05-31 09:03:29 -07:00
Andrew Eisenberg
fad7cc482d Merge pull request #438 from okyanusoz/patch-1
Fix wording in README
2021-05-31 09:02:45 -07:00
Andrew Eisenberg
4917d3c7e8 Merge pull request #533 from github/update-v1.0.0-ff75ec7f
Merge main into v1
2021-05-31 08:13:07 -07:00
Andrew Eisenberg
dd66f4484d Remove leading newline
Minor change.
2021-05-31 08:12:29 -07:00
github-actions[bot]
cf57db7e1f 1.0.0 2021-05-31 09:24:10 +00:00
Andrew Eisenberg
d9a17baf2f Merge branch 'main' into patch-1 2021-05-28 15:29:27 -07:00
Henry Mercer
ff75ec7f7d Merge pull request #532 from github/henrymercer/analysis-summaries-custom-queries
Analyze: Log analysis summaries for custom queries
2021-05-28 21:48:16 +01:00
Henry Mercer
1362396c57 Add changelog note 2021-05-28 20:19:55 +01:00
Henry Mercer
2338fe5db5 Analyze: Log analysis summaries for custom queries 2021-05-28 19:36:21 +01:00
Andrew Eisenberg
2ccefaccfe Merge pull request #510 from github/aeisenberg/update-changelog-on-release
Add release and mergeback workflows
2021-05-27 13:22:14 -07:00
Andrew Eisenberg
8b0110800e Merge branch 'main' into aeisenberg/update-changelog-on-release 2021-05-27 13:12:26 -07:00
Andrew Eisenberg
ea89b06c41 Add bump runner version whenever action is versioned
Ensures that the runner version is bumped along with the action version.
2021-05-27 12:31:58 -07:00
Arthur Baars
12b2dc68b9 Merge pull request #513 from github/aibaars-patch-1
Add Ruby as a possible language
2021-05-26 07:40:23 +02:00
Arthur Baars
213f5407e2 Merge branch 'main' into aibaars-patch-1 2021-05-26 07:30:01 +02:00
Aditya Sharad
f4e2dc747e Merge pull request #531 from github/adityasharad/actions/enterprise-versions-upstream-only
Actions: Run enterprise versions workflow only on the parent repo
2021-05-25 19:02:45 -07:00
Andrew Eisenberg
6764ac6d01 Merge pull request #527 from github/update-v1-eeaefb60
Merge main into v1
2021-05-25 19:00:39 -07:00
Aditya Sharad
a55e7e1f67 Actions: Run enterprise versions workflow only on the parent repo
Don't run the cron workflow on forks, since they lack the necessary secrets.
2021-05-25 17:48:14 -07:00
Arthur Baars
44c6b33642 Address comments 2021-05-24 11:00:02 +02:00
Arthur Baars
4f51b8c47e Check available languages 2021-05-23 21:14:07 +02:00
Andrew Eisenberg
800a951427 Add release and mergeback workflows
This commit ensures that the changelog is updated before a release with
the correct date and version.

Also, after a release, a mergeback PR is created to ensure that the
changelog update and version bump is available in main.
2021-05-21 11:04:38 -07:00
Arthur Baars
91700099ba Fix unit test 2021-05-21 18:45:08 +02:00
Arthur Baars
c3633dc9bd Add Ruby as a possible language 2021-05-21 18:45:08 +02:00
Andrew Eisenberg
eeaefb6054 Merge pull request #517 from github/aibaars-additional-packs
Use --additional-packs instead of --search-path
2021-05-21 09:31:17 -07:00
Andrew Eisenberg
c3e0f887ab Merge branch 'main' into aibaars-additional-packs 2021-05-21 09:21:54 -07:00
Arthur Baars
1ad5a6c1be Merge pull request #518 from github/aibaars-no-queries
Ensure queries[language] objects are initialized
2021-05-21 12:54:23 +02:00
Arthur Baars
6a14accb41 Fix tests 2021-05-21 12:41:35 +02:00
Arthur Baars
84bec4d116 Check queries in initConfig 2021-05-21 12:23:00 +02:00
Arthur Baars
9aca271fbb Remove superfluous if 2021-05-21 12:07:30 +02:00
Arthur Baars
ec011ddfdb Ensure queries[language] objects are initialized 2021-05-21 10:42:14 +02:00
Arthur Baars
69cc3550c8 Use --additional-packs instead of --search-path 2021-05-21 10:40:06 +02:00
Aditya Sharad
8fa2ef886e Merge pull request #515 from adityasharad/analyze/summary-logging
Analyze: Improve log grouping and log the analysis summary in its own group
2021-05-20 15:49:26 -07:00
Aditya Sharad
f84cc5e6f1 Fix trailing newline in package.json
As produced by npm ci && npm run removeNPMAbsolutePaths.
2021-05-20 14:12:37 -07:00
Aditya Sharad
512d4671bc Decode CodeQL stdout as UTF-8 2021-05-20 14:08:29 -07:00
Aditya Sharad
741bd73e8e Changelog: Add note for grouping of analysis logs 2021-05-20 12:32:10 -07:00
Aditya Sharad
031ec8753a Group log messages while uploading results 2021-05-20 12:32:10 -07:00
Aditya Sharad
19fe63f821 Analyze: Log the analysis summary in its own group
Fix grouping of the analysis logs, so that custom query logs also get grouped.
Capture the stdout of codeql database analyze, which contains the analysis summary
from summary and diagnostic queries.
Log this output in its own group, along with the baseline computed in the Action.
2021-05-20 12:32:09 -07:00
Andrew Eisenberg
6a9815718a Merge pull request #514 from github/aeisenberg/first-changelog-entry
Add the first changelog entry
2021-05-20 10:47:51 -07:00
Andrew Eisenberg
7ae8d165a6 Add the first changelog entry
(Adding the changelog itself.)
2021-05-20 09:24:30 -07:00
Andrew Eisenberg
06b386ac6c Merge pull request #507 from github/aeisenberg/changelog
Add a changelog
2021-05-19 15:41:37 -07:00
Andrew Eisenberg
1b3a351d6d Merge branch 'main' into aeisenberg/changelog 2021-05-19 15:28:21 -07:00
Andrew Eisenberg
1564a6d863 Fix typo in changelog
Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>
2021-05-19 15:28:15 -07:00
Andrew Eisenberg
8566f9b061 Add a changelog
Adds an empty changelog file and a reminder to update it when opening
pull requests.

Also, adds a 1.0.0 version number in the package.json, which is what
we _could_ use for version numbering.
2021-05-19 15:19:36 -07:00
Andrew Eisenberg
bc39b2101e Merge pull request #487 from RA80533/chore/--build
Use `--build`
2021-05-19 13:41:01 -07:00
Andrew Eisenberg
98104d89d9 Merge branch 'main' into chore/--build 2021-05-19 12:44:31 -07:00
RA80533
781da98328 Remove final newline 2021-05-19 15:12:54 -04:00
Henning Makholm
88f6e15932 Merge pull request #508 from github/update-v1-79c79f1b
Merge main into v1
2021-05-19 15:11:11 +02:00
Edoardo Pirovano
79c79f1be5 Add configuration option to set CodeQL DB location 2021-05-18 00:13:36 +01:00
Henning Makholm
feccdcb876 Merge pull request #506 from github/hmakholm/pr/2.5.5
Update CodeQL bundle to 20210517 / 2.5.5
2021-05-17 21:02:51 +02:00
Henning Makholm
95f5a25b5d Update CodeQL bundle to 20210517 / 2.5.5 2021-05-17 20:38:22 +02:00
Andrew Eisenberg
b393038372 Merge pull request #504 from github/update-v1-21830ef0
Merge main into v1
2021-05-17 08:44:48 -07:00
Andrew Eisenberg
e94d93ad78 Merge branch 'main' into patch-1 2021-05-17 08:30:13 -07:00
Henning Makholm
21830ef0c1 Merge pull request #503 from github/hmakholm/pr/warn-magic-names
Add warnings about CLI hack to codeql.ts
2021-05-14 21:57:44 +02:00
Henning Makholm
e7d4215894 Add warnings about CLI hack to codeql.ts
These warnings refer to a hack that was added to the CLI in
https://github.com/github/semmle-code/pull/39335

They can be removed again once the CLI has a more principled way for
the CLI to recognize that it's being invoked by the runner/action.
2021-05-14 21:23:13 +02:00
Andrew Eisenberg
97887fe996 Merge pull request #501 from github/aeisenberg/add-task
Add a tasks.json
2021-05-13 12:35:33 -07:00
Andrew Eisenberg
da06f4f01b Merge branch 'main' into aeisenberg/add-task 2021-05-13 12:25:54 -07:00
Andrew Eisenberg
6a0bd27159 Merge pull request #500 from github/aeisenberg/paths-include
Change include path for lines of code counting
2021-05-13 12:25:42 -07:00
Andrew Eisenberg
8e61fc214a Change include path for lines of code counting
Previously, we were always using `**` in the include path. the
effect of this was to always count lines in the entire
repository unless explicitly added to the paths-ignore. This
was incorrect behaviour. Now we only using `**` if the include
path is otherwise empty.
2021-05-13 12:05:01 -07:00
Andrew Eisenberg
a77f6b0a58 Merge pull request #502 from github/aeisenberg/metric-id
Use the prefix id for keying into metrics rules
2021-05-13 12:03:01 -07:00
Andrew Eisenberg
8c963ea445 Merge branch 'main' into aeisenberg/metric-id 2021-05-13 11:12:15 -07:00
Andrew Eisenberg
e8b2a9884b Use the prefix id for keying into metrics rules
Fixes a bug where we were looking for incorrect keys for metrics rules.
Previously, we were using full language names in the keys. Now, we use
the short language names in the metric ids. This is done through a
simplification of the code.

Also, this change does two smaller things:

1. Prints out the baseline count to the logs
2. Adds the `assertNever` function to ensure we never miss a case in
   a switch statement. This function is borrowed from vscode-codeql.
2021-05-13 11:11:13 -07:00
Andrew Eisenberg
a924f03118 Merge pull request #499 from github/aeisenberg/non-parallel-loc
Update loc count library
2021-05-13 10:10:39 -07:00
Andrew Eisenberg
38c131a270 Add a tasks.json
This is just a helpful way to ensure you can run `tsc --watch` from
inside vscode.
2021-05-13 16:40:19 +00:00
Andrew Eisenberg
ddcb299283 Update loc count library
This version will count lines of code in each file serially. It still
runs all file system operations asynchronously. The only difference now
is that it will only count one file at a time. It is slower, but it
is able to count large repositories without running out of memory.
2021-05-12 16:33:05 -07:00
Aditya Sharad
4c0671c518 Merge pull request #495 from edoardopirovano/windows-env-file
Output environment file for Windows
2021-05-10 14:01:50 -07:00
Edoardo Pirovano
84b6ff05df Merge branch 'main' into windows-env-file 2021-05-10 21:24:44 +01:00
Andrew Eisenberg
458b7913fc Merge pull request #494 from github/aeisenberg/audit-fix
Fix security vulnerabilities
2021-05-10 12:56:41 -07:00
Edoardo Pirovano
a5506d82e4 Output environment file for Windows 2021-05-10 20:43:49 +01:00
Andrew Eisenberg
22d1f7f619 Merge branch 'main' into aeisenberg/audit-fix 2021-05-10 11:49:23 -07:00
Andrew Eisenberg
ef38c532f3 Merge pull request #493 from github/aeisenberg/contributing2
Fix information about `npm ci`
2021-05-10 11:49:07 -07:00
Andrew Eisenberg
22d495fd60 Merge branch 'main' into aeisenberg/contributing2 2021-05-10 10:25:42 -07:00
Andrew Eisenberg
a9cdff830d Remove confusing words
Co-authored-by: Robert <robertbrignull@github.com>
2021-05-10 10:25:31 -07:00
Aditya Sharad
a56e777fe4 Merge pull request #482 from github/robertbrignull/python-deps-test
Make matrix run all cases of the python-deps tests
2021-05-10 10:19:38 -07:00
Andrew Eisenberg
489dbb0e02 Fix security vulnerabilities
Ran `npm audit fix`.

Even though this fixes a "high" severity vulnerability, all affected
packages are dev packages only.
2021-05-10 10:14:48 -07:00
Andrew Eisenberg
793b3772ec Fix information about npm ci 2021-05-10 10:05:30 -07:00
Aditya Sharad
d2ef04e4b0 Merge branch 'main' into robertbrignull/python-deps-test 2021-05-10 09:48:56 -07:00
Andrew Eisenberg
224195bd22 Merge pull request #492 from github/aeisenberg/contributing
Update contributing guide
2021-05-10 09:20:03 -07:00
Andrew Eisenberg
3280a85376 Update contributing guide
This adds a section on checking in compiled artifacts.
2021-05-10 09:04:59 -07:00
Robert
3c96019556 fix windows hopefully 2021-05-10 16:24:52 +01:00
Robert
f742f910aa put matrix vars in env vars for whitespace safety 2021-05-10 16:19:38 +01:00
Andrew Eisenberg
4a083a45c2 Merge pull request #491 from github/update-v1-f00bafbd
Merge main into v1
2021-05-10 08:07:39 -07:00
David Verdeguer
cf682cf1c2 Merge pull request #463 from github/daverlo/categoryInput
Add category input
2021-05-10 15:35:35 +02:00
David Verdeguer
ea18d47a2b Merge branch 'main' into daverlo/categoryInput 2021-05-10 14:54:09 +02:00
RA80533
db6341a36c Use --build 2021-05-07 20:15:12 -04:00
Andrew Eisenberg
f00bafbde1 Merge pull request #483 from github/aeisenberg/fix-language
Fix lines of code mapping
2021-05-07 11:02:25 -07:00
Andrew Eisenberg
b6ae33fbe6 Fix lines of code mapping
We were inadvertently using codeql language ids instead of the action's
language ids. There is now a 3-way mapping between the ids used by
the lines counter library, the action, and codeql.
2021-05-07 10:46:21 -07:00
Robert
603c47cb50 make matrix run all cases 2021-05-07 10:21:05 +01:00
Andrew Eisenberg
35a83b92ca Merge pull request #477 from github/hmakholm/pr/fix-escaping
fix value escaping in codeql-env.sh
2021-05-06 09:09:01 -07:00
Henning Makholm
ad98dc69ff Merge branch 'main' into hmakholm/pr/fix-escaping 2021-05-06 17:08:10 +02:00
Robert
418fcd5826 Merge pull request #480 from github/robertbrignull/logging_typo
Fix typos in logging
2021-05-06 13:56:08 +01:00
Robert
031dc506df fix typos in logging 2021-05-06 09:26:42 +01:00
Henning Makholm
ee062d3e85 Merge branch 'main' into hmakholm/pr/fix-escaping 2021-05-06 02:25:37 +02:00
Andrew Eisenberg
a7d3945ab4 Merge pull request #479 from github/aeisenberg/directory-fingerprint
Avoid fingerprinting directories
2021-05-05 13:54:11 -07:00
Andrew Eisenberg
f584f94f3d Avoid fingerprinting directories 2021-05-05 13:37:17 -07:00
Andrew Eisenberg
b477190a33 Merge branch 'main' into hmakholm/pr/fix-escaping 2021-05-05 12:09:07 -07:00
Henning Makholm
a6ebb19b5b Update src/runner.ts
Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2021-05-05 11:50:51 -07:00
Andrew Eisenberg
53210459f6 Merge pull request #475 from github/aeisenberg/warning-message
Clarify the missing baseline lines of code warning message
2021-05-05 11:20:13 -07:00
Henning Makholm
e7e64d59be fix value escaping in codeql-env.sh 2021-05-05 19:57:44 +02:00
Henry Mercer
c2ec5a225a Merge branch 'main' into aeisenberg/warning-message 2021-05-05 18:32:29 +01:00
Henry Mercer
46d0d277ef Merge pull request #476 from github/henrymercer/log-queries-during-interpretation
Log each query as it's interpreted when calling codeql database analyze
2021-05-05 18:30:32 +01:00
Henry Mercer
2c0a85753e Log each query as it's interpreted when calling codeql database analyze 2021-05-05 18:12:16 +01:00
Andrew Eisenberg
e04c62bb3c Clarify the missing baseline lines of code warning message 2021-05-05 09:29:20 -07:00
David Verdeguer
0c0bc0e6c6 Fix undefined environment 2021-05-05 15:46:49 +02:00
David Verdeguer
a1176686f1 Merge branch 'main' into daverlo/categoryInput 2021-05-05 12:31:11 +02:00
David Verdeguer
cd7eedd4a5 Address comments 2021-05-05 12:30:20 +02:00
Andrew Eisenberg
925cef7601 Merge pull request #474 from github/aeisenberg/change-metric-id
Change from `metric` to `rule`
2021-05-04 11:20:18 -07:00
Andrew Eisenberg
a2312a0bf3 Change from metric to rule
The SARIF that we are interpreting has moved away from using `metric`
to the more general term, `rule`. We need to adapt our baseline lines of
code counting to use `rule` as well.
2021-05-04 10:06:16 -07:00
Aditya Sharad
9a415429a9 Merge pull request #473 from github/update-v1-8e3540bb
Merge main into v1
2021-05-03 15:29:45 -07:00
Aditya Sharad
8e3540bb01 Merge pull request #472 from github/adityasharad/pr/2.5.4
Update CodeQL bundle to 20210503 / 2.5.4
2021-05-03 15:14:07 -07:00
Aditya Sharad
c3e98fb528 Update CodeQL bundle to 20210503 / 2.5.4 2021-05-03 14:41:51 -07:00
David Verdeguer
aa53f64b85 Use the category on the runner 2021-05-03 19:58:30 +02:00
David Verdeguer
3b741b35ad Use actionsUtil.computeAutomationID on upload-lib 2021-05-03 19:56:04 +02:00
David Verdeguer
c93cbc943a Forward category input to codeql cli 2021-05-03 19:41:53 +02:00
David Verdeguer
519d0771c7 Add actions-util.getAutomationID() 2021-05-03 19:36:32 +02:00
Henning Makholm
6b86057d79 Merge pull request #471 from github/update-v1-cb581084
Merge main into v1
2021-04-30 19:18:44 +02:00
Henning Makholm
cb5810848d Merge pull request #470 from github/hmakholm/pr/2.5.3
update bundle to 20210430
2021-04-30 19:02:00 +02:00
Henning Makholm
7ab95f642d update bundle to 20210430 2021-04-30 18:26:08 +02:00
Chris Gavin
33bb16c8b4 Merge pull request #457 from github/restrict-permissions
Restrict Actions token permissions in CodeQL workflow.
2021-04-30 14:19:45 +01:00
Chris Gavin
d879f4b84e Merge branch 'main' into restrict-permissions 2021-04-30 13:55:34 +01:00
Chris Gavin
e305db89c2 Fix the token permissions for private copies of the CodeQL Action, and for runs that are not from pull requests. 2021-04-30 13:47:54 +01:00
David Verdeguer
c6e734ccc5 Add category option to runner 2021-04-29 14:59:36 +02:00
David Verdeguer
76f5ada659 Don't use getOptionalInput on the runner codepath 2021-04-29 08:00:19 +02:00
Andrew Eisenberg
1585462c63 Merge pull request #465 from github/aeisenberg/lines-of-code-trim
Avoid analyzing excluded language files for line counting
2021-04-28 16:41:55 -07:00
Andrew Eisenberg
ee2346270d Avoid analyzing excluded language files for line counting
This change passes in a list of file types to the line counting
analysis. These are the languages for the databases being analyzed.
Line count analysis is restricted to these files.
2021-04-28 16:07:55 -07:00
Andrew Eisenberg
5c0a38d7e4 Update github-linguist dependency
This version adds a larger list of auto-excluded binary files.
And allows for the passing of a list of file types to restrict
analysis to.
2021-04-28 14:55:17 -07:00
David Verdeguer
40fb1f3f00 Add category input 2021-04-28 14:32:16 +02:00
Andrew Eisenberg
03f029c2a1 Merge pull request #459 from github/aeisenberg/add-linguist-data
Add baseline metrics for lines of code
2021-04-26 14:23:31 -07:00
Andrew Eisenberg
998f472183 Add baseline metrics for lines of code
This commit uses a third party library to estimate the lines of code in
a database that is to be analyzed by codeql.

The estimate uses the same includes and excludes globs for determining
which files should be counted.

The lines of code count is returned by language and injected into the
SARIF as `baseline` property in the `${language}/summary/lines-of-code`
metric.
2021-04-26 14:09:38 -07:00
Andrew Eisenberg
83b730ea82 Merge pull request #461 from github/update-v1-7c5b1287
Merge main into v1
2021-04-26 09:05:53 -07:00
Andrew Eisenberg
7c5b1287d5 Merge pull request #460 from github/dependabot/npm_and_yarn/runner/ssri-6.0.2
Bump ssri from 6.0.1 to 6.0.2 in /runner
2021-04-23 14:19:20 -07:00
dependabot[bot]
e2d70d6a0b Bump ssri from 6.0.1 to 6.0.2 in /runner
Bumps [ssri](https://github.com/npm/ssri) from 6.0.1 to 6.0.2.
- [Release notes](https://github.com/npm/ssri/releases)
- [Changelog](https://github.com/npm/ssri/blob/v6.0.2/CHANGELOG.md)
- [Commits](https://github.com/npm/ssri/compare/v6.0.1...v6.0.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-23 18:01:34 +00:00
Andrew Eisenberg
e266dfb63e Merge pull request #458 from github/aeisenberg/add-github-linguist
Add the github-linguist package
2021-04-23 10:59:56 -07:00
Andrew Eisenberg
b6b197e0ad Merge branch 'main' into aeisenberg/add-github-linguist 2021-04-23 10:54:04 -07:00
Robert
ba64dfb959 Merge pull request #456 from github/robertbrignull/toolcache-interface
Introduce our own toolcache implementation for use by the runnner
2021-04-23 16:24:04 +01:00
Robert
27bf3a208d fix typo 2021-04-23 10:01:50 +01:00
Robert
8207018b75 make query more robust 2021-04-23 10:01:28 +01:00
Robert
ce467e7e36 use safeWhich 2021-04-23 09:59:23 +01:00
Andrew Eisenberg
c4a84a93d4 Add the github-linguist package
This commit only adds a single package and all of its transitive
dependencies. The github-linguist package will be used for counting
lines of code as a baseline for databases we are analyzing.
2021-04-22 15:59:49 -07:00
Chris Gavin
643bc6e3ed Remove spurious blank line. 2021-04-22 17:26:26 +01:00
Chris Gavin
7e85b5d66a Restrict Actions token permissions in CodeQL workflow. 2021-04-22 17:07:03 +01:00
Robert
8c91ba83e2 Introduce our own toolcache implementation for use by the runnner 2021-04-22 15:31:15 +01:00
Henning Makholm
429ece1037 Merge pull request #455 from github/update-v1-896b4ff1
Merge main into v1
2021-04-21 20:50:55 +02:00
Henning Makholm
896b4ff181 Merge pull request #454 from github/hmakholm/pr/2.5.2
update bundle to 20210421 (CLI 2.5.2)
2021-04-21 20:24:18 +02:00
Henning Makholm
cb4c96ba60 Merge remote-tracking branch 'origin/main' into hmakholm/pr/2.5.2 2021-04-21 18:56:33 +02:00
Edoardo Pirovano
578f9fc99e Add external git repositories to search path for custom queries 2021-04-21 17:40:56 +01:00
Henning Makholm
46517cfb47 update bundle to 20210421 (CLI 2.5.2) 2021-04-21 17:31:57 +02:00
David Verdeguer
75dbb28e2f Merge pull request #453 from github/update-v1-1fa35632
Merge main into v1
2021-04-20 14:27:30 +02:00
David Verdeguer
1fa35632f2 Merge pull request #452 from github/daverlo/category
Ignore non-string values in populateRunAutomationDetails
2021-04-20 13:31:19 +02:00
David Verdeguer
496bf0ec11 Ignore non-string values in populateRunAutomationDetails 2021-04-20 12:53:16 +02:00
Andrew Eisenberg
9db4c5714e Merge pull request #449 from github/update-v1-8bd2b351
Merge main into v1
2021-04-19 08:33:23 -07:00
David Verdeguer
8bd2b3516b Merge pull request #446 from github/daverlo/runAutomationDetails
Add automationdetails id to runs
2021-04-19 11:30:53 +02:00
David Verdeguer
bc14da99c5 Merge branch 'main' into daverlo/runAutomationDetails 2021-04-19 10:47:18 +02:00
David Verdeguer
351d36fd18 Add test for existing automationDetails 2021-04-19 09:04:58 +02:00
Andrew Eisenberg
c87ee1c65a [Runner] Throw error on unknown option in init command
And explicitly document the advanced --trace-process-name and
--trace-process-level args.
2021-04-16 12:09:26 -07:00
David Verdeguer
0ece0d074b Fix populateRunAutomationDetails for null environments 2021-04-16 09:24:34 +02:00
David Verdeguer
de611b2de3 Prevent the automationDetails to be regenerated if it already exists 2021-04-16 07:47:42 +02:00
David Verdeguer
47755f0910 Add automationdetails id to runs 2021-04-15 16:20:49 +02:00
Andrew Eisenberg
6aebd1b98a Fixes a regex for language and locale recognition
See https://github.com/oasis-tcs/sarif-spec/pull/490
See #418

Note that this changes the sarif spec file. Unless this
change is actually merged in the sarif spec repo, the
version used by the action will be slightly different.
2021-04-14 08:10:56 -07:00
Andrew Eisenberg
af641b2d26 Use externalRepoAuth when getting a remote config
This allows users to specify a different token for retrieving the
codeql config from a different repository.

Fixes https://github.com/github/advanced-security-field/issues/185
2021-04-12 08:02:30 -07:00
Aditya Sharad
8a00ebe607 Code scanning: Compare the default and latest CodeQL tools bundles
Create a prerequisite job that runs the init step twice, with `tools: null` and `tools: latest`.
Use the outputs of these steps to compare the two CodeQL versions.
Pass the list of distinct tool versions for the analysis job to matrix over.
This lets us test the analysis against both versions, while avoiding duplication
when they are actually the same version.
2021-04-12 08:02:30 -07:00
Aditya Sharad
6b4df91bd2 PR checks: Compare the default and latest CodeQL tools bundles
Create a prerequisite job that runs the init step twice, with `tools: null` and `tools: latest`.
Use the outputs of these steps to compare the two CodeQL versions.
Pass the list of distinct tool versions for the integration tests to use in their matrix strategy.
This avoids redundant test jobs when the default and latest bundles are actually the same version of CodeQL.

`~` is accepted by JSON but not by the Actions context language, so we use `null` to indicate the default version.
2021-04-12 08:02:30 -07:00
Aditya Sharad
757ff9962f PR checks: Run integration tests against both tools: null and tools: latest
Always test against both the default and latest CodeQL bundle.

This improves test coverage shortly after a CodeQL bundle release, where the latest bundle
may not yet be built into the Actions VM image as the default bundle.

It also saves a manual step during bundle release testing,
since we no longer need to temporarily change the PR checks to `tools: latest`.

There is some redundancy when the latest bundle is the same as the default bundle on the VM image,
but this can be considered a test for the `tools: latest` configuration.
2021-04-12 08:02:30 -07:00
Aditya Sharad
0c2281fb06 Merge pull request #441 from adityasharad/tests/matrix-tools-latest
PR checks: Run integration tests against both `tools: null` and `tools: latest`
2021-04-09 16:24:56 -07:00
Aditya Sharad
fcf0863613 Merge branch 'main' into tests/matrix-tools-latest 2021-04-09 16:11:35 -07:00
Andrew Eisenberg
534192fa05 Use externalRepoAuth when getting a remote config
This allows users to specify a different token for retrieving the
codeql config from a different repository.

Fixes https://github.com/github/advanced-security-field/issues/185
2021-04-09 15:00:57 -07:00
Aditya Sharad
64b50fa2a6 Code scanning: Compare the default and latest CodeQL tools bundles
Create a prerequisite job that runs the init step twice, with `tools: null` and `tools: latest`.
Use the outputs of these steps to compare the two CodeQL versions.
Pass the list of distinct tool versions for the analysis job to matrix over.
This lets us test the analysis against both versions, while avoiding duplication
when they are actually the same version.
2021-04-09 14:51:18 -07:00
Aditya Sharad
51b1d7d81f PR checks: Compare the default and latest CodeQL tools bundles
Create a prerequisite job that runs the init step twice, with `tools: null` and `tools: latest`.
Use the outputs of these steps to compare the two CodeQL versions.
Pass the list of distinct tool versions for the integration tests to use in their matrix strategy.
This avoids redundant test jobs when the default and latest bundles are actually the same version of CodeQL.

`~` is accepted by JSON but not by the Actions context language, so we use `null` to indicate the default version.
2021-04-09 13:38:30 -07:00
Aditya Sharad
f9a19da7bf PR checks: Run integration tests against both tools: null and tools: latest
Always test against both the default and latest CodeQL bundle.

This improves test coverage shortly after a CodeQL bundle release, where the latest bundle
may not yet be built into the Actions VM image as the default bundle.

It also saves a manual step during bundle release testing,
since we no longer need to temporarily change the PR checks to `tools: latest`.

There is some redundancy when the latest bundle is the same as the default bundle on the VM image,
but this can be considered a test for the `tools: latest` configuration.
2021-04-08 13:39:01 -07:00
Aditya Sharad
ed446be54b Merge pull request #439 from github/update-v1-7f9fb10a
Merge main into v1
2021-04-05 12:02:07 -07:00
okyanusoz
8a1d7c290f Fix wording in README 2021-04-03 21:55:03 +03:00
Aditya Sharad
7f9fb10a74 Merge pull request #437 from github/dependabot/npm_and_yarn/runner/y18n-4.0.1
Bump y18n from 4.0.0 to 4.0.1 in /runner
2021-04-01 14:57:41 -07:00
Aditya Sharad
2f9f143d73 Merge branch 'main' into dependabot/npm_and_yarn/runner/y18n-4.0.1 2021-04-01 14:18:52 -07:00
Aditya Sharad
356d7a0637 Merge pull request #436 from github/dependabot/npm_and_yarn/y18n-4.0.1
Bump y18n from 4.0.0 to 4.0.1
2021-04-01 14:18:21 -07:00
Robert
def266fc62 update node modules 2021-04-01 10:37:02 +01:00
dependabot[bot]
5c715f3945 Bump y18n from 4.0.0 to 4.0.1 in /runner
Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.1.
- [Release notes](https://github.com/yargs/y18n/releases)
- [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md)
- [Commits](https://github.com/yargs/y18n/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-01 06:56:53 +00:00
dependabot[bot]
d0b1259bbe Bump y18n from 4.0.0 to 4.0.1
Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.1.
- [Release notes](https://github.com/yargs/y18n/releases)
- [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md)
- [Commits](https://github.com/yargs/y18n/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-31 22:46:11 +00:00
Aditya Sharad
8f0d3f7541 Merge pull request #435 from github/robertbrignull/dependabot_error
Add special error message case for dependabot
2021-03-31 07:47:05 -07:00
Robert
ca27066d09 fix grammar / punctuation 2021-03-31 11:05:30 +01:00
Robert
2f93805cef check push event 2021-03-30 16:53:02 +01:00
Robert
d4edded3ea Add special dependabot error message 2021-03-30 14:09:06 +01:00
Henning Makholm
f8f120e93b Merge pull request #434 from github/update-v1-bf8daada
Merge main into v1
2021-03-26 20:18:38 +01:00
Henning Makholm
bf8daada40 Merge pull request #433 from github/hmakholm/pr/2.5.0
Update CodeQL bundle to 20210326
2021-03-26 19:16:50 +01:00
Henning Makholm
996a90bf48 Revert "Temporarily use the latest version for testing"
This reverts commit d8216decae.
2021-03-26 18:06:32 +01:00
Robin Neatherway
d8216decae Temporarily use the latest version for testing 2021-03-26 15:17:17 +01:00
Henning Makholm
1d93ad95c1 Update CodeQL bundle to 20210326 2021-03-26 15:03:49 +01:00
Simon Engledew
bb012c4070 Merge pull request #432 from github/simon-engledew/fix-ref-check
Fix rev-parse errors
2021-03-25 14:02:01 +00:00
Simon Engledew
ba14abbca7 Rewrite the ref to correctly point to refs/remotes
Fixes the rev-parse issues caused by https://github.com/github/codeql-action/pull/428
2021-03-25 13:08:55 +00:00
Simon Engledew
972dc3e3f9 Merge pull request #428 from github/simon-engledew/detect-merge
Fix race condition with actions/checkout@v1
2021-03-23 06:18:28 +00:00
Simon Engledew
9165099103 Skip doing work if it is not necessary 2021-03-22 15:50:04 +00:00
Simon Engledew
36a9516acc PR feedback 2021-03-22 15:09:33 +00:00
Aditya Sharad
687b7b73f7 Merge pull request #429 from github/update-v1-5d467d01
Merge main into v1
2021-03-22 07:42:13 -07:00
Simon Engledew
ef92c5ac5f Count the number of parents of the current commit to check it is still a merge
Work around a race condition in actions where sometimes GITHUB_SHA != git rev-parse head
2021-03-22 12:05:00 +00:00
Aditya Sharad
5d467d014b Merge pull request #427 from github/hmakholm/pr/2.4.6 2021-03-20 15:52:17 -07:00
Henning Makholm
f8e31274f4 Revert "Temporarily use the latest version for testing"
This reverts commit e700075082.
2021-03-20 01:13:11 +01:00
Robin Neatherway
e700075082 Temporarily use the latest version for testing 2021-03-20 00:35:46 +01:00
Henning Makholm
d2f4021928 Update CodeQL bundle to 20210319 2021-03-20 00:30:46 +01:00
Josh Soref
c4fced7348 Fix spelling errors
spelling: executable
spelling: github
spelling: javascript
spelling: latest
spelling: occurred
spelling: parameter

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>
2021-03-18 09:40:47 -07:00
Andrew Eisenberg
08fae3caba Display better error message on invalid sarif
Specifically, some third party tools do not include a `results`
block for runs when there is an error. This change adds a more
explicit error message for this situation.
2021-03-18 09:03:42 -07:00
Andrew Eisenberg
ffd96b38fb Ensure error correct error message on 403 error 2021-03-17 07:55:21 -07:00
Robert
0f834639e4 Merge pull request #423 from github/robertbrignull/toolcache-query-safety
Make unguarded-action-lib better at ignoring uses of toolcache
2021-03-16 16:13:33 +00:00
Robert
5004a54ed3 Merge branch 'main' into robertbrignull/toolcache-query-safety 2021-03-16 15:29:47 +00:00
Robert
8373707722 Merge pull request #422 from github/robertbrignull/getActionsCodeQLActionRepository
Make control flow cleaer to fix unguarded-action-lib alert
2021-03-16 15:22:37 +00:00
Robert
378f30f95d call setupActionsVars in the tests too 2021-03-16 13:43:28 +00:00
Robert
d698cb3d2b Make unguarded-action-lib better at ignoring uses of toolcache 2021-03-16 13:14:17 +00:00
Robert
09024e50d4 make control flow cleaer to fix query alert 2021-03-16 12:07:00 +00:00
Chris Gavin
daff33213e Merge pull request #417 from github/dependabot/npm_and_yarn/runner/elliptic-6.5.4
Bump elliptic from 6.5.3 to 6.5.4 in /runner
2021-03-16 10:11:36 +00:00
Chris Gavin
4c3c9b0d41 Merge branch 'main' into dependabot/npm_and_yarn/runner/elliptic-6.5.4 2021-03-16 09:52:57 +00:00
Chris Gavin
0ed969c530 Merge pull request #419 from github/update-v1-cfec2bbc
Merge main into v1
2021-03-15 10:22:24 +00:00
dependabot[bot]
4df078eec5 Bump elliptic from 6.5.3 to 6.5.4 in /runner
Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.3 to 6.5.4.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](https://github.com/indutny/elliptic/compare/v6.5.3...v6.5.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-11 04:41:48 +00:00
Chris Gavin
cfec2bbc35 Merge pull request #409 from github/check-ghae-endpoint-first-only-on-ghae
When downloading the CodeQL bundle, only use the GitHub AE endpoint on GitHub AE, and check it first.
2021-03-10 13:03:16 +00:00
Chris Gavin
18f6367c46 Merge branch 'main' into check-ghae-endpoint-first-only-on-ghae 2021-03-10 12:23:15 +00:00
Aditya Sharad
df9359871e Merge pull request #415 from github/update-v1-2fcc4eb0
Merge main into v1
2021-03-09 11:12:08 -08:00
Aditya Sharad
2fcc4eb030 Merge pull request #414 from github/hmakholm/pr/2.4.5
Update CodeQL bundle to 20210308
2021-03-09 10:35:53 -08:00
Henning Makholm
27ed6ac804 Revert "Temporarily use the latest version for testing"
This reverts commit c78d81fa3e.
2021-03-09 19:03:10 +01:00
Robin Neatherway
c78d81fa3e Temporarily use the latest version for testing 2021-03-09 18:21:32 +01:00
Henning Makholm
bcca43b391 Update CodeQL bundle to 20210308 2021-03-09 17:43:35 +01:00
Aditya Sharad
5c4e11807d Merge pull request #413 from github/update-v1-6ddfab14
Merge main into v1
2021-03-08 11:35:14 -08:00
Aditya Sharad
6ddfab14f6 Merge pull request #412 from github/fix-pip-url
Fix the Pip download URL.
2021-03-08 10:51:58 -08:00
Chris Gavin
039625a3ce Fix the Pip download URL. 2021-03-08 18:27:42 +00:00
Aditya Sharad
ce6b93eb0a Merge pull request #408 from github/adityasharad/bundle/20210304
Update CodeQL bundle to 20210304 / CLI 2.4.4
2021-03-08 07:53:39 -08:00
Simon Engledew
145b51c270 Merge pull request #410 from github/update-v1-bde489c6
Merge main into v1
2021-03-08 15:50:17 +00:00
Chris Gavin
bb51ece0b4 When downloading the CodeQL bundle, only use the GitHub AE endpoint on GitHub AE, and check it first. 2021-03-07 11:18:54 +00:00
Aditya Sharad
fb01860db6 Revert "Temporarily use the latest version for testing"
This reverts commit 2f4f48f767.
2021-03-04 13:33:26 -08:00
Aditya Sharad
2f4f48f767 Temporarily use the latest version for testing 2021-03-04 13:20:54 -08:00
Aditya Sharad
0ff9c449b7 Update CodeQL bundle to 20210304 / CLI 2.4.4 2021-03-04 13:05:37 -08:00
Simon Engledew
bde489c632 Merge pull request #406 from github/simon-engledew/go-module
Check if this mitigates the go 1.16 issue
2021-03-01 13:20:17 +00:00
Simon Engledew
324d987bc6 Check if this mitigates the go 1.16 issue 2021-03-01 13:01:56 +00:00
Chris Gavin
e40d00393d Merge pull request #405 from github/update-v1-964ae012
Merge main into v1
2021-03-01 10:57:06 +00:00
Chris Gavin
964ae01287 Merge pull request #400 from github/no-update-release-branch-on-forks
Don't run update release branch workflow on forks.
2021-02-24 09:28:41 +00:00
Chris Gavin
fdf2494cfa Don't run update release branch workflow on forks. 2021-02-23 11:44:38 +00:00
Robert
d00607bc7b Merge pull request #399 from github/update-v1-bcd7b2de
Merge main into v1
2021-02-22 10:37:31 +00:00
Robert
7f1d7b8bda Merge pull request #398 from github/update-supported-enterprise-server-versions
Update supported GitHub Enterprise Server versions.
2021-02-22 10:34:38 +00:00
GitHub
760681b052 Update supported GitHub Enterprise Server versions. 2021-02-20 00:26:14 +00:00
Aditya Sharad
bcd7b2de1d Merge pull request #396 from github/adityasharad/ram-threshold
Increase the default amount of RAM reserved for the OS
2021-02-17 12:05:25 -08:00
Aditya Sharad
fd0ad84431 Merge branch 'main' into adityasharad/ram-threshold 2021-02-17 11:29:15 -08:00
Robert
41b73e168c Merge pull request #397 from github/robertbrignull/runner_auth
Set externalRepoAuth
2021-02-17 16:53:23 +00:00
Robert
a2653534db set externalRepoAuth 2021-02-17 08:30:35 -08:00
Chris Gavin
f84e342ff3 Merge pull request #393 from github/ghae-endpoint
Also look for the CodeQL bundle at the custom GitHub AE endpoint.
2021-02-17 08:41:39 +00:00
Chris Gavin
2b1c88c014 Merge branch 'main' into ghae-endpoint 2021-02-17 08:29:36 +00:00
Aditya Sharad
0ab754c698 Merge pull request #395 from github/aeisenberg/remove-external-token
Remove --external-repository-token option from runner
2021-02-16 15:12:54 -08:00
Aditya Sharad
4c94e29f1b Increase the default amount of RAM reserved for the OS
Mitigation for OOM errors (137/SIGKILL) seen by users when we overcommit the available memory.
For Unix, reserve 1GB.
For Windows, reserve 1.5GB, as the OS needs more memory and estimates inaccurately.
2021-02-16 15:10:19 -08:00
Andrew Eisenberg
58defc0652 Remove --external-repository-token option from runner
Specifying a token as a cli input leads to a potential for leaking the
token on CI logs. This commit removes the option. Instead, users
should specify a single GitHub token through `--github-auth-stdin` or
by setting the `GITHUB_TOKEN` environment variable. This token should be
created with enough privileges to access the required repository.
2021-02-16 11:28:25 -08:00
Andrew Eisenberg
88714e3a60 Add capability to specify auth from env var or stdin
This commit adds two new ways of specifying GitHub auth:

1. from the GITHUB_TOKEN environment variable
2. from standard input

This commit does not include any documentation changes and the
descriptions of new command line options will need to be tweaked.
2021-02-16 11:26:39 -08:00
Chris Gavin
3c63623824 Merge branch 'main' into ghae-endpoint 2021-02-16 10:17:25 +00:00
Chris Gavin
1d92248672 Merge pull request #394 from github/lock-bundler-version
Lock bundler version to 2.2.9.
2021-02-16 10:16:31 +00:00
Chris Gavin
c6390afb59 Merge branch 'main' into lock-bundler-version 2021-02-16 10:07:00 +00:00
Chris Gavin
f2896eb08a Lock bundler version to 2.2.9. 2021-02-15 19:50:32 +00:00
Chris Gavin
f8c5dacab5 Also look for the CodeQL bundle at the custom GitHub AE endpoint. 2021-02-15 19:41:41 +00:00
Chris Gavin
49cb962d82 Merge pull request #385 from github/allow-override-temp
Allow overriding path of temporary files.
2021-02-15 19:39:15 +00:00
Chris Gavin
04d2b0018e Merge branch 'main' into allow-override-temp 2021-02-15 16:20:45 +00:00
Chris Gavin
3568e4afcc Merge pull request #392 from github/detect-ghae
Add detection for GitHub AE.
2021-02-15 12:11:09 +00:00
Chris Gavin
7b72f1c330 Merge main into allow-override-temp. 2021-02-15 11:45:08 +00:00
Chris Gavin
6452109691 Treat empty CODEQL_ACTION_TEMP the same as it not being set. 2021-02-15 11:44:44 +00:00
Chris Gavin
c9ca4ec1bd Convert GitHub variant to an enum. 2021-02-15 09:30:16 +00:00
Chris Gavin
0656b2c1ad Add detection for GitHub AE. 2021-02-13 11:06:03 +00:00
Chris Gavin
21026345ae Merge pull request #388 from github/update-v1-781e3bc5
Merge main into v1
2021-02-08 11:37:49 +00:00
Sam Partington
781e3bc540 Merge pull request #380 from github/remove-uploadFromActions-params
Remove parameters from uploadFromActions
2021-02-02 11:53:08 +00:00
Sam Partington
10a2f1b1aa Merge branch 'main' into remove-uploadFromActions-params 2021-02-02 11:34:02 +00:00
Simon Engledew
c4084e1c1a Merge pull request #386 from github/simon-engledew/warning-undefined
Do not report warning: undefined
2021-02-02 10:17:59 +00:00
Simon Engledew
f3f5dfd3df Merge branch 'main' into simon-engledew/warning-undefined 2021-02-02 10:06:49 +00:00
Simon Engledew
169b9f804b Fix lint errors 2021-02-02 09:59:06 +00:00
Chris Gavin
3d8b1cb7ea Merge pull request #387 from github/asymmetric-log-release-branch
Use an asymmetric Git log when updating the release branch.
2021-02-02 08:18:19 +00:00
Chris Gavin
8fef3928ba Use an asymmetric Git log when updating the release branch. 2021-02-01 18:03:39 +00:00
Aditya Sharad
db540f07f0 Merge pull request #381 from github/adityasharad/fix/python2-pip-url
Python setup: Fix URL for Python 2.7 pip install
2021-02-01 09:36:57 -08:00
Aditya Sharad
80a8f97b9c Merge branch 'main' into adityasharad/fix/python2-pip-url 2021-02-01 09:15:29 -08:00
Simon Engledew
1f07e287da Do not report warning: undefined 2021-02-01 16:32:13 +00:00
Chris Gavin
ed751ece83 Allow overriding path of temporary files. 2021-02-01 15:34:13 +00:00
Robin Neatherway
0dcd795b4c Merge pull request #384 from github/update-v1-6408d722
Merge main into v1
2021-02-01 10:29:19 +00:00
Simon Engledew
6408d72268 Merge pull request #367 from github/simon-engledew/remove-january-warning
Remove date specific pull request warnings
2021-01-29 10:47:59 +00:00
Simon Engledew
44ed1c6ce1 Remove pull request warnings 2021-01-29 10:42:37 +00:00
Aditya Sharad
bfa9dfe827 Python setup: Fix URL for Python 2.7 pip install
This URL changed upstream. Fix it by using the same upstream URL as the LGTM Python image.
We can revisit separately whether to drop the Python 2 pip installation entirely.
2021-01-28 16:52:16 -08:00
Sam Partington
19fe854945 Remove intermediate variables 2021-01-28 15:40:42 +00:00
Sam Partington
c2377b2e49 Remove parameters from uploadFromActions
Retrieve the relevant values in the method itself instead.
2021-01-28 15:37:09 +00:00
Robin Neatherway
74004631ca Merge pull request #379 from github/rneatherway/codeql-bundle-20210127
Update default CodeQL to 20210127
2021-01-28 12:13:38 +00:00
Robin Neatherway
07943dcc5d Revert "Temporarily use the latest version for testing"
This reverts commit 2c62543901.
2021-01-27 14:50:45 +00:00
Robin Neatherway
2c62543901 Temporarily use the latest version for testing 2021-01-27 11:51:55 +00:00
Robin Neatherway
18f9eb6b55 Update default CodeQL to 20210127 2021-01-27 11:31:51 +00:00
Chris Gavin
0dc37c7260 Merge pull request #377 from github/fix-version-in-message
Fix the formatting of a warning message.
2021-01-26 17:43:05 +00:00
Chris Gavin
f109c77463 Merge branch 'main' into fix-version-in-message 2021-01-26 17:24:58 +00:00
Chris Gavin
601dc8486f Merge pull request #376 from github/fix-deduplication-sources
Fix deduplication of bundle download sources.
2021-01-26 17:22:03 +00:00
Chris Gavin
d182a0e3aa Fix deduplication of bundle download sources. 2021-01-26 16:56:43 +00:00
Chris Gavin
5261491807 Fix the formatting of a warning message. 2021-01-26 16:52:43 +00:00
Chris Gavin
24872f608c Merge pull request #374 from github/automatic-upload-debug-logs
Upload debug logs automatically when `ACTIONS_STEP_DEBUG` is enabled.
2021-01-26 10:11:17 +00:00
Chris Gavin
94b32884f9 Dump logs to stdout instead of stderr to avoid synchronization problems. 2021-01-26 09:47:31 +00:00
Chris Gavin
8705aaff32 Walk log filex manually rather than using the Actions globber. 2021-01-26 09:21:38 +00:00
Chris Gavin
219142571c Upload debug logs automatically when ACTIONS_STEP_DEBUG is enabled. 2021-01-25 15:44:31 +00:00
Robert
3a205cc343 Merge pull request #372 from github/update-v1-7a340d32
Merge main into v1
2021-01-25 10:56:12 +00:00
Simon Engledew
7a340d32a1 Merge pull request #370 from github/simon-engledew/hide-workflow-not-found
Do not warn users if a workflow cannot be read
2021-01-25 09:21:11 +00:00
Simon Engledew
ee4d06713e Fix wonky comment 2021-01-22 14:08:43 +00:00
Simon Engledew
6be1f5ce0e Add more granular exception handling 2021-01-22 13:52:04 +00:00
Simon Engledew
8a9922df92 Disambiguate report messages 2021-01-22 13:52:04 +00:00
Simon Engledew
795b1923ec Swap method naming to account for new functionality 2021-01-22 13:52:03 +00:00
Simon Engledew
28e2860afb Correctly report WorkflowMissing 2021-01-22 13:51:45 +00:00
Simon Engledew
4547749a2f Do not warn users if a workflow cannot be read
This will still send a LintFailed message status report.
2021-01-22 13:51:19 +00:00
Robert
484a9ad67e Merge pull request #368 from github/robertbrignull/external-token-fix
Only insert external repos token if supplied
2021-01-22 12:50:17 +00:00
Robert
1013277382 Merge branch 'main' into robertbrignull/external-token-fix 2021-01-22 12:08:26 +00:00
Robert
504cb5e7a2 Merge pull request #371 from github/robertbrignull/pr-checks-workflow
Move .github/workflows back where it was
2021-01-21 18:26:50 +00:00
Robert
cfdf2eaf7a move .github/workflows back where it was 2021-01-21 16:06:26 +00:00
Robert
a1bfa7609f Merge pull request #369 from felicitymay/patch-1
Update description to include limit on number of results
2021-01-19 17:57:15 +00:00
Felicity Chapman
a3a8231e64 Update upload-sarif/action.yml
Co-authored-by: hubwriter <hubwriter@github.com>
2021-01-19 17:17:45 +00:00
Felicity Chapman
d0ac97e33f Add results limit to description 2021-01-19 17:02:31 +00:00
Robert
cb574a7d60 only insert external repos token if supplied 2021-01-19 15:42:57 +00:00
Robert
ce35c1c3a5 Merge pull request #366 from github/update-v1-8659fb33
Merge main into v1
2021-01-18 10:22:40 +00:00
Robert
b0adc415a0 Merge pull request #364 from ericcornelissen/eslint/no-unused-vars
Update code so "@typescript-eslint/no-unused-vars" passes
2021-01-18 10:01:59 +00:00
Eric Cornelissen
946779f5b6 Run npm run-script build 2021-01-15 18:40:06 +01:00
Eric Cornelissen
9a753aa409 Removed unused vars in config-utils.test.ts 2021-01-15 18:25:29 +01:00
Eric Cornelissen
2a6d6c52d7 Update ESLint configuration
Remove the line to disable the "github/no-unused-vars"  rule.
2021-01-15 18:20:07 +01:00
Robin Neatherway
8659fb33f9 Merge pull request #362 from github/rneatherway/merge-workflows
Merge pr-check and integration-testing workflows
2021-01-15 16:26:34 +00:00
Robin Neatherway
137e614f23 Merge branch 'main' into rneatherway/merge-workflows 2021-01-15 15:59:36 +00:00
Simon Engledew
4bdcd08344 Merge pull request #363 from github/simon-engledew/fix-incorrect-branch-warning
Fix overzealous warnings when PR scanning is not required
2021-01-15 10:59:19 +00:00
Simon Engledew
b6fc7138bf Merge branch 'main' into simon-engledew/fix-incorrect-branch-warning 2021-01-15 10:41:33 +00:00
Simon Engledew
1a6f6a27b3 Implement PR feedback 2021-01-15 08:28:21 +00:00
Robert
f86e200d13 Merge pull request #357 from github/robertbrignull/external-token-option
Introduce external repository token
2021-01-14 17:41:30 +00:00
Robert
c8abbce0a2 Merge branch 'main' into robertbrignull/external-token-option 2021-01-14 17:27:33 +00:00
Robin Neatherway
3d63fa4dad Merge pull request #361 from github/rneatherway/status-base
Correct typo in setting of PR upload base ref
2021-01-14 10:28:34 +00:00
Simon Engledew
0853901c0d Fix overzealous warning when PR scanning is not required 2021-01-13 12:28:24 +00:00
Robin Neatherway
369cad8272 Use the fully qualified ref name 2021-01-13 12:16:10 +00:00
Robin Neatherway
9ace6974f2 Merge pr-check and integration-testing workflows
These had some minor overlap checking that the JS is up to date and
there isn't any benefit in having them separate as the jobs are run in
parallel anyway.
2021-01-13 12:10:34 +00:00
Robin Neatherway
884ee1d129 Correct typo in setting upload base ref 2021-01-13 12:00:33 +00:00
Robin Neatherway
a7f3c648eb Update test to check base ref/sha values 2021-01-13 11:57:55 +00:00
Robert
087e7a3a1a Merge pull request #360 from github/robertbrignull/preload_tracer_env_var
Output path to preload_tracer in env file
2021-01-13 10:15:31 +00:00
Robert
97a70e6013 include missing changes 2021-01-12 12:09:22 +00:00
Robert
90d1a31dd4 Introduce external repository token 2021-01-12 12:07:03 +00:00
Robert
70733e4ae5 add call operator 2021-01-12 11:44:25 +00:00
Robert
a432f684f7 Use CODEQL_RUNNER env var in integration tests 2021-01-12 11:29:42 +00:00
Robert
2f9814894f Add tests of CODEQL_RUNNER env var 2021-01-12 11:29:30 +00:00
Robert
c796788c33 move CODEQL_RUNNER population to tracer-config.ts 2021-01-12 10:49:08 +00:00
Robert
cd2eafc8e3 switch to using runner instead of preload_tracer 2021-01-12 10:43:06 +00:00
Robert
5a03a14bfb use CODEQL_PLATFORM 2021-01-12 10:24:25 +00:00
Robert
dbd8007298 Output path to preload_tracer 2021-01-11 11:15:53 +00:00
Robert
32a206ea17 Merge pull request #359 from github/update-v1-a0c4707d
Merge main into v1
2021-01-11 10:11:38 +00:00
Sam Partington
a0c4707dcc Merge pull request #323 from github/split-upload-method
Split upload method into two mode-specific ones
2021-01-06 12:02:34 +00:00
Sam Partington
c7275a75ce Don't re-retrieve GitHub version when already have it
54e0c67332 (r45693026)
54e0c67332 (r45693030)
2021-01-06 11:40:16 +00:00
Sam Partington
023add5df0 Fix linter violations 2021-01-06 11:19:50 +00:00
Sam Partington
4e46a490ae Merge branch 'main' into split-upload-method 2021-01-06 11:13:51 +00:00
Sam Partington
54e0c67332 Revert "Retrieve GitHubVersion when used rather than passing around"
This reverts commit 6de1b753c2.

https://github.com/github/codeql-action/pull/323#discussion_r551960301
2021-01-06 11:06:01 +00:00
Sam Partington
4bc186cf34 Move type definition to where it's used
https://github.com/github/codeql-action/pull/323#discussion_r551951925
2021-01-06 10:58:32 +00:00
Sam Partington
1da4ce5a03 Ensure stats get sent when not uploading results
https://github.com/github/codeql-action/pull/323#discussion_r551948732
2021-01-06 10:52:16 +00:00
Robert
20d8f91819 Merge pull request #358 from github/robertbrignull/recursive_sarif_test
Add test of finding SARIF files recursively
2021-01-04 15:34:11 +00:00
Robert
3792ed8ceb Merge branch 'main' into robertbrignull/recursive_sarif_test 2021-01-04 15:15:44 +00:00
Simon Engledew
b1e0b46970 Merge pull request #348 from github/simon-engledew/checkout-wrong-heads
Only report the first CheckoutWrongHead lint error
2021-01-04 14:19:05 +00:00
Simon Engledew
034bf318b8 Merge branch 'main' into simon-engledew/checkout-wrong-heads 2021-01-04 13:37:11 +00:00
Robert
bd4e3adfd9 Add test of finding SARIF files recursively 2021-01-04 13:12:30 +00:00
Robert
230cb9b734 Merge pull request #352 from chao2zhang/main
Support find .sarif files recursively
2021-01-04 12:58:36 +00:00
Simon Engledew
456cd431ff Improve test coverage 2021-01-04 12:05:37 +00:00
Simon Engledew
1511db33b3 Only check the steps of the job currently being run 2021-01-04 12:00:15 +00:00
Chris Gavin
bb9d573cf9 Merge pull request #354 from github/update-v1-094554cf
Merge main into v1
2021-01-04 11:10:06 +00:00
Chao Zhang
55eae6652f Support find .sarif files recursively 2020-12-22 23:24:51 -08:00
Chris Gavin
c2dc86575a Merge pull request #350 from github/prevent-accidental-analysis-of-get-pip-v1
Prevent accidental analysis of the `get-pip.py` script. [v1 cherry-pick]
2020-12-22 15:12:10 +00:00
Chris Gavin
094554cf89 Merge pull request #349 from github/prevent-accidental-analysis-of-get-pip
Prevent accidental analysis of the `get-pip.py` script.
2020-12-22 14:48:15 +00:00
Chris Gavin
b8f3d839cc Prevent accidental analysis of the get-pip.py script. 2020-12-22 14:36:09 +00:00
Chris Gavin
3c494fdd7a Prevent accidental analysis of the get-pip.py script. 2020-12-22 14:16:57 +00:00
Sam Partington
6de1b753c2 Retrieve GitHubVersion when used rather than passing around 2020-12-22 11:49:42 +00:00
Sam Partington
45dd5ee97d Fix linter violations 2020-12-22 11:28:08 +00:00
Sam Partington
82a8fa443e Merge branch 'main' into split-upload-method 2020-12-22 11:23:49 +00:00
Simon Engledew
e89a24b8cb Only report the first CheckoutWrongHead lint error 2020-12-21 11:08:49 +00:00
Simon Engledew
dc999c55d0 Merge pull request #346 from github/simon-engledew/fix-numerical-branches
Fix for numerical branch names
2020-12-21 09:17:09 +00:00
Simon Engledew
2d00e8c6f7 Fix for numerical branch names 2020-12-18 10:23:46 +00:00
Robin Neatherway
9f7bdecc04 Merge pull request #341 from github/rneatherway/gate-integration-testing
Gate execution of expensive tests on JS being up to date
2020-12-16 11:06:41 +00:00
Robin Neatherway
cea5932aad Merge branch 'main' into rneatherway/gate-integration-testing 2020-12-15 18:16:25 +00:00
Chris Gavin
4d262138e1 Merge pull request #345 from github/update-v1-8cbc02a4
Merge main into v1
2020-12-14 11:42:02 +00:00
Robert
cbd120ea91 Merge pull request #343 from github/dependabot/npm_and_yarn/ini-1.3.8
Bump ini from 1.3.5 to 1.3.8
2020-12-14 10:42:35 +00:00
Robert
71c7759fac update node_modules 2020-12-14 10:25:05 +00:00
Robert
9435055597 Merge branch 'main' into dependabot/npm_and_yarn/ini-1.3.8 2020-12-14 10:24:17 +00:00
Robert
5d77983efc Merge pull request #344 from github/dependabot/npm_and_yarn/runner/ini-1.3.8
Bump ini from 1.3.5 to 1.3.8 in /runner
2020-12-14 10:23:46 +00:00
dependabot[bot]
1fd28a0d4c Bump ini from 1.3.5 to 1.3.8 in /runner
Bumps [ini](https://github.com/isaacs/ini) from 1.3.5 to 1.3.8.
- [Release notes](https://github.com/isaacs/ini/releases)
- [Commits](https://github.com/isaacs/ini/compare/v1.3.5...v1.3.8)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-13 05:06:37 +00:00
dependabot[bot]
46c74bba1d Bump ini from 1.3.5 to 1.3.8
Bumps [ini](https://github.com/isaacs/ini) from 1.3.5 to 1.3.8.
- [Release notes](https://github.com/isaacs/ini/releases)
- [Commits](https://github.com/isaacs/ini/compare/v1.3.5...v1.3.8)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-12 17:32:00 +00:00
Robin Neatherway
3e176f8293 Gate execution of expensive tests on JS being up to date 2020-12-08 16:53:35 +00:00
Chris Gavin
8cbc02a4c2 Merge pull request #339 from github/split-python2-python3-install
Install Python 3 tools before installing Python 2 tools.
2020-12-07 15:55:57 +00:00
Chris Gavin
222b57e35b Merge branch 'main' into split-python2-python3-install 2020-12-07 14:40:04 +00:00
Chris Gavin
6156eb9557 Install Python 3 tools before installing Python 2 tools. 2020-12-07 13:59:49 +00:00
Robin Neatherway
682158920d Merge pull request #329 from github/robertbrignull/meta
Send base_sha and base_ref when appropriate
2020-12-07 12:47:11 +00:00
Robin Neatherway
7afd3334e3 Adjust type annotations on payload 2020-12-07 12:35:48 +00:00
Robin Neatherway
d0d858c809 Merge branch 'main' into robertbrignull/meta 2020-12-07 12:34:21 +00:00
Robert
049e10c079 Merge pull request #338 from github/update-v1-494945f7
Merge main into v1
2020-12-07 09:51:43 +00:00
Robert
494945f710 Merge pull request #337 from github/robertbrignull/merge-v1
Merge v1 into main to fix conflicts
2020-12-04 17:01:18 +00:00
Robert
e9152c326e Merge remote-tracking branch 'origin/v1' into robertbrignull/merge-v1 2020-12-04 16:44:17 +00:00
Simon Engledew
a43ce966aa Merge pull request #332 from github/simon-engledew/string-branches
Handle the case where branches may be strings, wildcards
2020-12-04 16:27:00 +00:00
Simon Engledew
18c6a7d6d1 fix another edge case 2020-12-04 15:18:22 +00:00
Simon Engledew
1dc40ba165 Merge remote-tracking branch 'origin/main' into simon-engledew/string-branches 2020-12-04 12:36:42 +00:00
Simon Engledew
7100f22932 Add a bunch of tests cases and harden the function aganst malformed workflows 2020-12-03 13:41:55 +00:00
Simon Engledew
7310a508e1 Merge pull request #335 from github/simon-engledew/backport-v1
Backport v1 into main
2020-12-02 16:54:52 +00:00
Simon Engledew
f3c9aee686 Hide an warning that is confusing on GHES 2020-12-02 16:49:54 +00:00
Simon Engledew
107fe8422f Add advanced test case 2020-12-02 08:48:34 +00:00
Simon Engledew
ec8015bc03 Merge branch 'main' into simon-engledew/string-branches 2020-12-02 08:35:11 +00:00
Simon Engledew
78b9d23d09 Remove unecessary if statement 2020-12-02 08:34:18 +00:00
Simon Engledew
1dd265aef3 Merge pull request #333 from github/simon-engledew/hide-warnings-v1
Hide a warning that is confusing on GHES
2020-12-02 08:31:48 +00:00
Simon Engledew
698e2a5487 Just convert the pattern into a RegExp... 2020-12-01 20:56:07 +00:00
Simon Engledew
4d862616ce First iteration on feedback 2020-12-01 20:08:41 +00:00
Simon Engledew
56b1ead679 Do not show lint failed in the UX if it happens 2020-12-01 17:23:00 +00:00
Simon Engledew
b1be00db57 Test the branch patterns work both ways 2020-12-01 17:16:33 +00:00
Simon Engledew
c3a9325bd8 Hide an warning that is confusing on GHES 2020-12-01 16:59:15 +00:00
Simon Engledew
f99af1c014 Have a catch all coded error for lint failures 2020-12-01 15:41:04 +00:00
Simon Engledew
145a3c1ed9 Add more wildcard examples 2020-12-01 15:33:27 +00:00
Simon Engledew
14719432ef Add more test cases 2020-12-01 15:30:11 +00:00
Simon Engledew
c8ee1f4ef3 Handle wildcard branches 2020-12-01 15:21:30 +00:00
Simon Engledew
ac1c081de8 Handle the case where branches may be strings, including "*" 2020-12-01 12:03:50 +00:00
Robin Neatherway
e6174fc6cf Merge pull request #326 from github/rneatherway/on-push-notice
Add an explicit deprecation date
2020-12-01 11:28:15 +00:00
Robin Neatherway
1010b1f743 Merge branch 'main' into rneatherway/on-push-notice 2020-12-01 11:12:14 +00:00
Robin Neatherway
8e0e34a3e6 Add an explicit deprecation date
So that we can remove support for the beta configuration of
`on: push`-only we should communicate a date after which this
will not work.
2020-12-01 11:10:20 +00:00
Chris Gavin
f65e6c40fa Merge pull request #330 from github/check-files-on-release
Add a check to ensure expected CodeQL release files exist.
2020-12-01 10:56:58 +00:00
Chris Gavin
fb2a3bf840 Add a check to ensure expected CodeQL release files exist. 2020-12-01 09:26:05 +00:00
Robin Neatherway
d99e994194 Fix test to be immune to running on Actions 2020-11-30 18:35:55 +00:00
Robin Neatherway
836cbe0784 Remove output files for deleted source 2020-11-30 18:31:21 +00:00
Robin Neatherway
9de6863c74 Correct base ref to include prefix 2020-11-30 18:30:02 +00:00
Robin Neatherway
dff118f7ad Use version information to construct payload 2020-11-30 16:45:18 +00:00
Robert
c6dbd5a9bf Merge pull request #324 from github/robertbrignull/go_autobuild
Test Go autobuild
2020-11-30 13:00:21 +00:00
Robert
32878b75b8 Merge branch 'main' into robertbrignull/go_autobuild 2020-11-30 12:47:38 +00:00
Robert
b1fd75309c Update .github/workflows/integration-testing.yml
Co-authored-by: Chris Gavin <chris@chrisgavin.me>
2020-11-30 12:28:26 +00:00
Chris Gavin
90e780524b Merge pull request #325 from github/update-bundle
Update the default bundle to `codeql-bundle-20201127`.
2020-11-30 10:49:56 +00:00
Chris Gavin
1110f7be49 Merge branch 'main' into update-bundle 2020-11-30 10:30:59 +00:00
Robin Neatherway
d73e5cefb0 Merge pull request #327 from github/rneatherway-patch-1
Only analyze PRs against main and v1
2020-11-30 10:18:36 +00:00
Robin Neatherway
38ed96450e Only analyze PRs against main and v1
We can only analyze PRs against those branches we are analyzing on push.
2020-11-27 17:37:32 +00:00
Sam Partington
ff28c8d403 Move uploading side-effect out of runAnalyze
https://github.com/github/codeql-action/pull/323#discussion_r530978010
2020-11-27 12:27:10 +00:00
Chris Gavin
0c33f016fa Update the default bundle to codeql-bundle-20201127. 2020-11-27 12:04:35 +00:00
Robert
7174a81563 test Go autobuild 2020-11-27 11:34:02 +00:00
Robert
81a21bfa1e Request meta endpoint at the start of execution 2020-11-26 17:54:46 +00:00
Simon Engledew
8d18e347a7 Merge pull request #319 from github/simon-engledew/lint-workspace
Validate the codeql-action workspace for common errors
2020-11-26 16:36:46 +00:00
Simon Engledew
92df38732c Merge branch 'main' into simon-engledew/lint-workspace 2020-11-26 15:22:22 +00:00
Simon Engledew
be09fb3e99 Implement feedback 2020-11-26 15:20:38 +00:00
Robert
7d74882aaf Merge pull request #321 from ericcornelissen/eslint/github-no-then
Update code so "github/no-then" passes
2020-11-26 14:35:51 +00:00
Sam Partington
9532bda6e4 Use better comparison operator 2020-11-26 11:57:34 +00:00
Sam Partington
57514f31db Split upload method into two mode-specific ones 2020-11-26 11:50:57 +00:00
Sam Partington
7ae9b0db35 Extract filepath retrieval to a method 2020-11-26 11:18:00 +00:00
Eric Cornelissen
e6ea8cbae0 Run npm run build 2020-11-25 22:46:30 +01:00
Eric Cornelissen
cd727934bf Update source so github/no-then passes 2020-11-25 22:45:53 +01:00
Eric Cornelissen
35fd0a93b1 Update ESLint configuration
Remove the line to disable the "github/no-then"  rule.
2020-11-25 22:44:45 +01:00
Simon Engledew
378f1f95d7 Merge pull request #320 from github/simon-engledew/fix-DEP0005-buffer
Fix deprecated method Buffer.new
2020-11-25 16:25:07 +00:00
Simon Engledew
eed314143b Add paths-ignore case 2020-11-25 14:23:21 +00:00
Simon Engledew
253d46ac97 Better copy for PathsSpecified, suggested by @sampart 2020-11-25 13:30:32 +00:00
Simon Engledew
c5f58f3ee7 Markdown is not supported - roll back and fix typo 2020-11-25 13:06:51 +00:00
Simon Engledew
94b10dbb8f See if markdown is supported 2020-11-25 12:46:37 +00:00
Simon Engledew
85aefe5fa4 Signpost the latest documentation in the warning 2020-11-25 12:45:13 +00:00
Simon Engledew
582f792089 Fix deprecated method Buffer.new 2020-11-25 12:38:45 +00:00
Simon Engledew
8d468d67de Improve linting hints 2020-11-25 12:36:59 +00:00
Simon Engledew
c06dcf8fa2 Update source 2020-11-25 11:03:48 +00:00
Simon Engledew
cb3b3a8cb5 Comment the lint cases to make maintaining easier 2020-11-25 10:55:06 +00:00
Simon Engledew
92ffb08081 Tidy up ready for review 2020-11-24 17:21:25 +00:00
Simon Engledew
1020df5700 Merge branch 'main' into simon-engledew/lint-workspace 2020-11-24 14:55:54 +00:00
Simon Engledew
fd16298746 Revert an accidental change to make testing quicker 2020-11-24 14:28:08 +00:00
Simon Engledew
2ac22e8935 Send short codes that do not need URL encoding for better splunk tracing 2020-11-24 12:43:08 +00:00
Sam Partington
27520b94c4 Merge pull request #318 from github/api-param-object
Introduce parameter object for API params that travel together
2020-11-24 12:10:47 +00:00
Sam Partington
3ee4739b13 Make anonymous objects into variables for readability 2020-11-24 11:23:53 +00:00
Sam Partington
ab9b1a72db Fix tests
Previously, most tests were using https://github.com and only the first was using https://github.example.com. As it happens, https://github.com works for all of them.
2020-11-24 11:10:25 +00:00
Simon Engledew
6df1fc5e38 Do not fail if the workflow has been deleted 2020-11-24 10:51:31 +00:00
Simon Engledew
754f502a84 Workflow triggers are null if unspecified 2020-11-24 10:25:58 +00:00
Simon Engledew
c0bd7b0b2b Handle relative workflow paths 2020-11-24 09:56:10 +00:00
Simon Engledew
33bb87523e Write a warning if there is an error with the workflow 2020-11-24 09:51:00 +00:00
Simon Engledew
7eb9dfcc60 Add a function that can lint a CodeQL action workflow 2020-11-23 17:29:19 +00:00
Sam Partington
20567b5888 Introduce parameter object for API params that travel together 2020-11-23 14:39:01 +00:00
David Verdeguer
4dcb3202d8 Merge pull request #317 from github/update-v1-b15854c9
Merge main into v1
2020-11-23 15:01:13 +01:00
David Verdeguer
b15854c9af Merge pull request #316 from The-Compiler/patch-1
Make sure a Python 2 pip is installed
2020-11-20 17:28:05 +01:00
Florian Bruhin
b168eee469 Make sure a Python 2 pip is installed
In the README of this repo, it's suggested to use the `ubuntu-latest` environment.
That environment will soon be upgraded to Ubuntu 20.04: https://github.com/actions/virtual-environments/issues/1816

As pointed out in that issue, the updated image comes without a Python 2 pip preinstalled:

    Setup Python dependencies
    /home/runner/work/_actions/github/codeql-action/v1/python-setup/install_tools.sh
    [...]
      + python2 -m pip install --user --upgrade pip setuptools wheel
      /usr/bin/python2: No module named pip
    Warning: Unable to download and extract the tools needed for installing the python dependecies. You can call this action with 'setup-python-dependencies: false' to disable this process.
2020-11-20 16:48:43 +01:00
Chris Gavin
7589c051a9 Merge pull request #313 from github/query-binary-planting
Add a query to detect binary planting vulnerabilities.
2020-11-20 15:25:01 +00:00
Chris Gavin
f5e028fd83 Merge branch 'main' into query-binary-planting 2020-11-20 15:04:10 +00:00
Robert
c4b7211148 Merge pull request #311 from ericcornelissen/fix-typos
Fix typos in source code, logging, comments, and config files
2020-11-20 13:42:37 +00:00
Eric Cornelissen
6aaf0483f0 Merge branch 'main' into fix-typos 2020-11-20 14:32:12 +01:00
Chris Gavin
c5d599ecb2 Merge pull request #310 from ericcornelissen/eslint-rule/no-shadow
Update code so "no-shadow" passes
2020-11-20 13:23:13 +00:00
Eric Cornelissen
6ed5c82bb9 Merge branch 'main' into fix-typos 2020-11-20 13:59:16 +01:00
Eric Cornelissen
82ba92f462 Update spelling for autobuild to auto-built 2020-11-20 13:58:20 +01:00
Chris Gavin
7091b81414 Merge branch 'main' into eslint-rule/no-shadow 2020-11-20 12:44:18 +00:00
Chris Gavin
6d232b4ec8 Merge pull request #314 from github/skip-integration-tests-prs-from-forks
Skip Runner integration tests on pull requests from forks.
2020-11-20 12:27:46 +00:00
Chris Gavin
b59d204bbe Merge branch 'main' into skip-integration-tests-prs-from-forks 2020-11-20 12:18:45 +00:00
Chris Gavin
0a05e95b52 Merge pull request #312 from ericcornelissen/fix-minor-code-mistakes
Two minor code fixes
2020-11-20 11:48:19 +00:00
Chris Gavin
fd36bec497 Skip Runner integration tests on pull requests from forks. 2020-11-20 11:47:43 +00:00
Chris Gavin
a04d948b04 Merge branch 'main' into fix-minor-code-mistakes 2020-11-20 11:37:27 +00:00
Chris Gavin
b03b9fe641 Add a query to detect binary planting vulnerabilities. 2020-11-20 11:34:33 +00:00
Eric Cornelissen
35b050652a Run npm run build 2020-11-20 11:48:25 +01:00
Simon Engledew
31872f129b Merge pull request #308 from github/simon-engledew/fast-fail
Abort CodeQL action if the status cannot be reported
2020-11-20 10:45:40 +00:00
Eric Cornelissen
5416d4f3b5 Run npm run build 2020-11-20 11:35:59 +01:00
Eric Cornelissen
cf8c79ca35 Fix unused sorted value in update-release-branch
Fix a minor issue in the update-release-branch.py script that performs a
call to `sorted` but doesn't use the output. Since `sorted` does not
operate in place, the call is currently useless. As a result, the function
`get_pr_for_commit` does not currently work as exected. I.e. it is
expected to return the "first" (i.e. lowest PR number), but actually it
returns the first in the list provided by GitHub.
2020-11-20 11:20:45 +01:00
Eric Cornelissen
4e8634c29c Remove duplicate statement in tracer-config test
The tracer-config.test.js file contained a duplicate of the statement:

  process.env["SEMMLE_DEPTRACE_SOCKET"] = "abc";

one line apart. This removes the second instance of this statement.
2020-11-20 11:14:08 +01:00
Eric Cornelissen
512c07d9a3 Fix typos in Action config files 2020-11-20 11:11:17 +01:00
Eric Cornelissen
85ea24bd20 Fix typos in src
- Rename "toolrunnner" (three 'n') to "toolrunner"
- Rename "relativeFilepaht" to "relativeFilepath"
- Fix various typos in documentation & comments
- Fix typos in logs and test names
2020-11-20 11:00:55 +01:00
Simon Engledew
6a45994b42 Merge branch 'main' into simon-engledew/fast-fail 2020-11-20 09:21:26 +00:00
Eric Cornelissen
992a0cf8f2 Merge branch 'main' into eslint-rule/no-shadow 2020-11-19 23:41:11 +01:00
Eric Cornelissen
847f4ef293 Run npm run build 2020-11-19 23:03:45 +01:00
Eric Cornelissen
483c94b974 Fix no shadow issues in upload-lib.ts
Rename one instance of "path"  to avoid shadowing.
2020-11-19 22:54:48 +01:00
Eric Cornelissen
74559947b1 Fix no shadow issues in fingerprints.ts
Rename various instances of "hash", shadowing the function with that
name.
2020-11-19 22:54:05 +01:00
Eric Cornelissen
ffe94681e4 Fix no shadow issues in fingerprints.test.ts
Rename shadowing "uri" argument to the more explicit "artifactURI".
2020-11-19 22:51:29 +01:00
Eric Cornelissen
2a2910e693 Fix no shadow issues in config-utils.ts
Rename throwaway variable "suite" to "found" when assigned from "find".

Rename local variable "path" to "newPath" as it is a modification of
the "originalPath" provided to `validateAndSanitisePath`.

Rename instances of "path" to more explicit varients "ignorePath" and
"includePath". Maybe "ignoredPath" and "includedPath" are better names?
2020-11-19 22:50:02 +01:00
Eric Cornelissen
06e99f1523 Fix no shadow issues in config-utils.test.ts
Rename "queries" variable in test cases to "testQueries" to avoid
shadowing it in a subsequent helper function call (4 times).

Rename "path" twice in a hlper function to "validPath" and "invalidPath"
to avoid shadowing "path". The new names are more explicit.
2020-11-19 22:47:32 +01:00
Eric Cornelissen
98ad63b240 Fix no shadow issues in codeql.ts
Two simple variable renames from "path" to "paths" since the types are
arrays of strings (not just one string).

One function definition inside a function moved outside that function
to avoid shadowing the "options" argument.
2020-11-19 22:45:15 +01:00
Eric Cornelissen
b54c2aab11 Fix no shadow issues in api-client.ts
Duplicate use of "_" placeholder argument name. This change may conflict
with #192.
2020-11-19 22:42:13 +01:00
Eric Cornelissen
22f779c5e6 Update ESLint configuration
Remove the "no-shadow": "off" override and replace it by enabling
"@typescript-eslint/no-shadow" in the "rules" section, following the
typescript-eslint docs:
https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-shadow.md#how-to-use
2020-11-19 22:38:38 +01:00
Robert
aafb457527 Merge pull request #222 from github/robertbrignull/go_build_trace
Check CODEQL_EXTRACTOR_GO_TRACE and treat Go as a traced language
2020-11-19 18:01:53 +00:00
Robert
0b0bc35050 Merge branch 'main' into robertbrignull/go_build_trace 2020-11-19 17:20:54 +00:00
Simon Engledew
eb4226ede4 Scanning endpoint failures should not halt the scan 2020-11-19 15:49:46 +00:00
Simon Engledew
7fda765d49 Merge remote-tracking branch 'origin/main' into simon-engledew/fast-fail 2020-11-19 13:55:47 +00:00
Chris Gavin
0924fb6b26 Merge pull request #309 from github/safe-which
Ensure unqualified program names are present on `PATH` before executing them.
2020-11-19 13:52:57 +00:00
Simon Engledew
17d4671d60 Fail processing on a 422 as well
Until there is a more robust versioning system it is probably safest to require endpoint compatiblity and not continue the action if there is a mismatch.
2020-11-19 13:14:45 +00:00
Simon Engledew
f3ff4c84ba Implement review feedback 2020-11-19 12:39:57 +00:00
Chris Gavin
726cfc8441 Ensure unqualified program names are present on PATH before executing them. 2020-11-18 22:20:13 +00:00
Simon Engledew
68dedeaa57 Do not run CodeQL if code scanning is not enabled
Put more fine grained logic around which errors we ignore and process.
Re-instate status reporting in Enterprise.
Abort the code scanning process the status endpoint reports it is not configured.
2020-11-18 17:21:57 +00:00
Robert
dc80b016b6 Merge pull request #301 from github/robertbrignull/tools_version
Send action ref and tool version in status reports
2020-11-18 11:38:26 +00:00
Robert
0d960df08a Merge branch 'main' into robertbrignull/tools_version 2020-11-18 11:25:46 +00:00
Chris Gavin
10b43b815a Merge pull request #231 from github/add-multi-cause-markdown-flag
Enable the CodeQL SARIF multi-cause markdown flag.
2020-11-18 08:39:30 +00:00
Chris Gavin
f94e06a382 Merge main into add-multi-cause-markdown-flag. 2020-11-18 08:26:39 +00:00
Robert
577fc451dd Merge pull request #306 from github/update-v1-d4eb1e36
Merge main into v1
2020-11-16 12:03:04 +00:00
Robert
d4eb1e36af Merge pull request #302 from github/robertbrignull/no_tracing
Don't use the word "trace" in log messages
2020-11-13 15:27:37 +00:00
Robert
54c857ce0a update build command 2020-11-13 15:15:58 +00:00
Robert
3f2a7abc7b change voicing 2020-11-13 15:04:54 +00:00
Robert
e3a9a7a91c Update init/action.yml
Co-authored-by: Sam Partington <sampart@github.com>
2020-11-13 12:51:25 +00:00
Robert
4d8912d269 Don't use the word "trace" in log messages 2020-11-13 12:01:07 +00:00
Robert
af27146b64 Merge branch 'main' into robertbrignull/go_build_trace 2020-11-13 10:24:37 +00:00
Robert
1737b806ff check if running locally 2020-11-12 14:18:58 +00:00
Robert
80b43ca9d3 send action ref and tool version in status reports 2020-11-12 12:27:31 +00:00
Robert
acacf9bbd5 Merge pull request #299 from github/azure_pipelines
Detect Agent.Worker.exe
2020-11-11 10:28:25 +00:00
Robert
9a7b7cb035 Merge branch 'main' into azure_pipelines 2020-11-11 10:12:56 +00:00
Chris Gavin
fdb0d486b6 Merge pull request #298 from github/use-github-action-repository-variable
Make use of the `GITHUB_ACTION_REPOSITORY` environment variable if it is set.
2020-11-10 18:13:50 +00:00
Chris Gavin
241fca876b Merge branch 'main' into use-github-action-repository-variable 2020-11-10 17:55:13 +00:00
Robert
aae4713a4d detect Agent.Worker.exe 2020-11-10 16:16:58 +00:00
Robin Neatherway
d3285a0ea2 Merge pull request #297 from github/rneatherway-patch-1
Change suggested workflow to analyse merge commit
2020-11-10 14:46:28 +00:00
Chris Gavin
bf30ea69d6 Make use of the GITHUB_ACTION_REPOSITORY environment variable if it is set. 2020-11-10 13:30:20 +00:00
Robin Neatherway
988704e971 Change suggested workflow to analyse merge commit 2020-11-10 12:10:07 +00:00
Robert
409b71a3d0 Merge pull request #296 from 0xflotus/patch-1
fix: small typo in import-action-entrypoint.ql
2020-11-10 09:34:24 +00:00
0xflotus
1870040fac fix: small typo in import-action-entrypoint.ql 2020-11-10 00:38:46 +01:00
Robin Neatherway
1de54f1d3b Merge pull request #295 from github/main
Update v1 with new CodeQL bundle
2020-11-09 15:42:20 +00:00
Robin Neatherway
4b301bd34e Merge pull request #294 from github/rneatherway/bump-codeql-20201106
Update default CodeQL bundle version
2020-11-09 14:05:10 +00:00
Robin Neatherway
ab40235d88 Update default CodeQL bundle version 2020-11-09 13:00:43 +00:00
Simon Engledew
e3bfd25a41 Merge pull request #293 from github/update-v1-f13bd452
Merge main into v1
2020-11-09 10:22:41 +00:00
Simon Engledew
f13bd452d7 Merge pull request #291 from github/simon-engledew/output-codeql-path
Add a codeql-path output to the init action
2020-11-05 10:22:10 +00:00
Simon Engledew
f76124122e Remove output from README
As this is an advanced usage it makes more sense to work to getting this included in the documentation instead.
2020-11-05 08:31:35 +00:00
Simon Engledew
c87f3021d4 Expand readme to include codeql-path output example
Also add example from README into workflow to confirm it is accurate.
2020-11-04 19:35:19 +00:00
Simon Engledew
54f3e52e8f Move setOutput into try block in case it errors 2020-11-04 19:29:06 +00:00
Simon Engledew
ff6db59d5a Fix indentation for action output
Co-authored-by: Chris Gavin <chris@chrisgavin.me>
2020-11-04 19:16:09 +00:00
Simon Engledew
77f914a4ba Add codeql-path to README (wip) 2020-11-04 17:22:32 +00:00
Simon Engledew
c213a7c7c9 Use codeql-path output in python-deps workflow 2020-11-04 17:22:32 +00:00
Simon Engledew
854109fe92 Report the path of CodeQL as an output 2020-11-04 15:38:31 +00:00
Simon Engledew
0ed3207eb5 Merge pull request #289 from github/simon-engledew/fix-act-local
Fix invalid API call when running locally
2020-11-04 14:30:51 +00:00
Simon Engledew
df843a2867 Merge branch 'main' into simon-engledew/fix-act-local 2020-11-04 12:47:38 +00:00
Robert
82e3812a35 Merge branch 'main' into robertbrignull/go_build_trace 2020-11-04 11:07:46 +00:00
Simon Engledew
1c8d72e0c2 Remove unnecessary env manipulation
testing-utils.ts / setupTests() already stores and restores the env
2020-11-04 10:59:35 +00:00
Simon Engledew
5c0e2f93f1 Fix invalid API call when running locally
The method getAnalysisKey would call getWorkflowPath and raise an API Error.

This change follows the pattern in prepareLocalRunEnvironment to set a dummy value for the required environment variable, therefore shortcutting the API request.
2020-11-04 09:58:09 +00:00
Chris Gavin
b6989db81e Merge pull request #288 from github/tweak-bump-supported-versions
Make a few small tweaks to the update-supported-enterprise-server-versions script.
2020-11-04 09:48:05 +00:00
Chris Gavin
813b5235a1 Merge branch 'main' into tweak-bump-supported-versions 2020-11-04 09:08:27 +00:00
Andrew Eisenberg
bc1ee1620f Add the --threads config option to finalize db (#281)
This flag is already being used for `runQueries`, so let's use it for
finalize as well.
2020-11-03 08:25:40 -08:00
Simon Engledew
a6c99e6b5b Merge pull request #287 from github/disable-gpgsign-in-tests
Disable gpg key signing in tests
2020-11-03 15:08:31 +00:00
Simon Engledew
d7bd6e39e3 Merge branch 'main' into disable-gpgsign-in-tests 2020-11-03 14:47:39 +00:00
Chris Gavin
4ffed2603e Only increase the newest supported release, never reduce it. 2020-11-03 13:58:07 +00:00
Chris Gavin
beac9d5621 Fix a copy and pasted job name. 2020-11-03 13:57:41 +00:00
Chris Gavin
1364a74a5d Merge pull request #285 from github/check-api-version
Log a warning if the API version is not supported.
2020-11-03 13:36:53 +00:00
Chris Gavin
b16110e60e Log the version warning a second time if a request fails unexpectedly. 2020-11-03 12:57:15 +00:00
Simon Engledew
efc3797e30 Disable gpg key signing in tests
This avoids a popup appearing if your GPG key has a passphrase and ensures the tests still pass even if GPG is misconfigured.
2020-11-03 11:05:49 +00:00
David Verdeguer
935dd4041f Merge pull request #286 from github/update-v1-9a0139ee
Merge main into v1
2020-11-03 11:27:07 +01:00
Chris Gavin
5e2fa08dae Merge main into check-api-version. 2020-11-02 09:02:05 +00:00
Chris Gavin
1a4385d516 Only log the version warning once on Actions even if the Action is invoked multiple times. 2020-11-02 09:01:36 +00:00
Chris Gavin
865b4bd832 Pass a logger in to getApiClient() rather than constructing one there. 2020-11-02 08:53:25 +00:00
Chris Gavin
1f7bae7ab8 Use an undefined check rather than hasOwnProperty. 2020-11-02 08:47:11 +00:00
Robert
9a0139eee2 Merge pull request #274 from github/jhutchings1-patch-1
Change to the latest support link
2020-10-30 17:51:26 +00:00
Robert
736f65db3e Merge branch 'main' into jhutchings1-patch-1 2020-10-30 17:28:53 +00:00
Robert Brignull
2e550bba7f Check CODEQL_EXTRACTOR_GO_BUILD_TRACING
Co-authored-by: Max Schaefer <54907921+max-schaefer@users.noreply.github.com>
2020-10-30 16:44:11 +00:00
Robert
7d5b76a81b Merge pull request #272 from sonicdoe/patch-1
Fix alignment of cron comment
2020-10-30 16:36:12 +00:00
Robert
fb10307267 Merge branch 'main' into patch-1 2020-10-30 16:24:53 +00:00
David Verdeguer
f0c568a42f Merge pull request #284 from github/daverlo/min-disk-free
Add min disk free flag to database analyze:
2020-10-30 16:17:54 +01:00
Chris Gavin
1220ae5bfd Log a warning if the API version is not supported. 2020-10-30 12:20:06 +00:00
David Verdeguer
04e7c3cfe7 Merge branch 'main' into daverlo/min-disk-free 2020-10-30 11:25:55 +01:00
David Verdeguer
7b571208e1 Merge pull request #280 from github/daverlo/update-codeql
Use codeql 20201028
2020-10-29 11:42:57 +01:00
David Verdeguer
d96ee1a48c Fix python tests 2020-10-28 16:31:15 +01:00
David Verdeguer
f46875dae9 Use codeql 20201028 2020-10-28 15:18:46 +01:00
David Verdeguer
253ef425f9 Merge pull request #279 from github/update-v1-46110c36
Merge main into v1
2020-10-28 11:38:54 +01:00
Chris Gavin
2d75893188 Enable the CodeQL SARIF multi-cause markdown flag. 2020-10-27 13:50:40 +00:00
David Verdeguer
46110c361b Merge pull request #278 from github/daverlo/setup-python-dependencies
Use setup-python-dependencies input
2020-10-27 14:36:20 +01:00
David Verdeguer
8db7d74c10 Merge branch 'main' into daverlo/setup-python-dependencies 2020-10-27 11:47:00 +01:00
Chris Gavin
abe6b7b085 Merge pull request #276 from github/fix-ci
Fix Python CI jobs.
2020-10-27 10:20:15 +00:00
David Verdeguer
4575212a76 Use setup-python-dependencies input 2020-10-27 10:06:17 +01:00
Chris Gavin
85c65cd6bf Always use the latest CodeQL in the Python dependencies tests. 2020-10-26 14:17:11 +00:00
Chris Gavin
65efaf83e9 Fix Python CI jobs. 2020-10-26 08:31:09 +00:00
Justin Hutchings
762078e765 Change to the latest support link
Support is recommending we redirect users to a new page for formal support requests.
2020-10-23 13:22:06 -07:00
Jakob Krigovsky
ea5ae18876 Fix alignment of cron comment 2020-10-22 18:29:58 +02:00
David Verdeguer
fb7d0f72e5 Merge pull request #270 from github/daverlo/python-mac
Port python deps setup to mac
2020-10-22 15:09:38 +02:00
David Verdeguer
e23b3ef342 Merge branch 'main' into daverlo/python-mac 2020-10-22 14:01:07 +02:00
David Verdeguer
bf20a55f26 Combine python deps tests workflows 2020-10-22 14:00:51 +02:00
David Verdeguer
badb2863db Merge pull request #271 from github/daverlo/fail-analyze
Fail the analyze action when some language fails to run the queries
2020-10-22 12:28:37 +02:00
David Verdeguer
d6287621f6 Fail the analyze action when some language fails to run the queries 2020-10-22 10:22:27 +02:00
Robin Neatherway
6ac5978b44 Merge pull request #266 from github/robertbrignull/runner_workflow
Add a workflow to build and upload the runner
2020-10-21 10:17:00 +01:00
Robin Neatherway
59913e8e05 Merge remote-tracking branch 'origin/robertbrignull/runner_workflow' into robertbrignull/runner_workflow 2020-10-20 15:04:56 +01:00
Robin Neatherway
269b8b9bae Update for review comments 2020-10-20 15:04:04 +01:00
Robin Neatherway
b6e9407b12 Merge branch 'main' into robertbrignull/runner_workflow 2020-10-20 11:59:11 +01:00
Robin Neatherway
c1e2c53b95 Remove push trigger now that I've tested it works 2020-10-20 11:58:20 +01:00
Robin Neatherway
d91d2d2873 Upload the runner to the release directly 2020-10-20 11:00:00 +01:00
David Verdeguer
1c789715a7 Address comments 2020-10-20 10:49:48 +02:00
Robin Neatherway
7507a5a9b1 Merge pull request #269 from github/update-v1-c8b8c041
Merge main into v1
2020-10-19 12:38:26 +01:00
David Verdeguer
ce8418a2ed Only run tests on main and v1 2020-10-19 13:08:20 +02:00
David Verdeguer
2391771a3f Allow installing python deps on mac 2020-10-19 12:45:33 +02:00
David Verdeguer
04f2f600bc Adapt true for mac 2020-10-19 12:36:34 +02:00
David Verdeguer
8e516b1d36 Run tests 2020-10-19 12:21:58 +02:00
David Verdeguer
c860191a1a Run python deps tests on mac 2020-10-19 12:21:21 +02:00
David Verdeguer
c8b8c0415e Merge pull request #257 from github/daverlo/python-windows
Port python deps setup to windows
2020-10-15 14:48:25 +02:00
David Verdeguer
e0f78380e3 Merge branch 'main' into daverlo/python-windows 2020-10-15 12:12:50 +02:00
David Verdeguer
a41d1bd815 Merge pull request #261 from github/rasmuswl/python-update-setenv
Don't use ::set-env in python-setup
2020-10-15 11:59:37 +02:00
David Verdeguer
7d1f309c39 Address comments 2020-10-15 11:56:40 +02:00
Rasmus Wriedt Larsen
bc72944cba Merge branch 'main' into rasmuswl/python-update-setenv 2020-10-15 10:37:45 +02:00
David Verdeguer
2c3dafc162 Use sys.executable 2020-10-14 10:54:41 +02:00
Robert
3f8927dbc5 Merge pull request #259 from andymckay/patch-1
Change time in template
2020-10-13 17:20:16 +01:00
Robert
345bcba3ea Merge branch 'main' into patch-1 2020-10-13 16:47:00 +01:00
David Verdeguer
e63596efd3 Merge branch 'main' into daverlo/python-windows 2020-10-13 17:44:16 +02:00
David Verdeguer
0d97ea8f14 Call pipenv and poetry through python 2020-10-13 17:38:53 +02:00
Robin Neatherway
cdfffe8ff7 Merge pull request #264 from github/rneatherway-patch-1
Start analysing merge commit for PRs
2020-10-13 15:11:55 +01:00
Robin Neatherway
f813ad0ce2 Merge branch 'main' into rneatherway-patch-1 2020-10-13 14:26:01 +01:00
Robin Neatherway
bc196131af Merge pull request #260 from github/rneatherway/codeql-bundle-20201008
Update default CodeQL version to codeql-bundle-20201008
2020-10-13 11:14:48 +01:00
Robert Brignull
ffaa8aa197 add workflow to build runner 2020-10-13 10:56:07 +01:00
Robin Neatherway
f79717f3c3 Start analysing merge commit for PRs 2020-10-13 10:19:15 +01:00
Rasmus Wriedt Larsen
64ebf10c1d Don't use ::set-env in python-setup
Is now deprecated as described in
https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/
2020-10-08 16:12:40 +02:00
David Verdeguer
72e430fc65 Merge branch 'main' into daverlo/python-windows 2020-10-08 15:53:50 +02:00
Robin Neatherway
2da5fbf0d4 Update default CodeQL version to codeql-bundle-20201008 2020-10-08 14:48:20 +01:00
David Verdeguer
9bc8c56ef0 Add missing [ 2020-10-08 12:17:28 +02:00
David Verdeguer
e3d2d4afc4 Add call to py 2020-10-08 12:14:41 +02:00
David Verdeguer
735ec7d414 Add powershell to call 2020-10-08 12:06:29 +02:00
David Verdeguer
424a9cfa1c Apply suggestions from code review
Co-authored-by: Arthur Baars <aibaars@github.com>
2020-10-08 11:59:35 +02:00
Andy McKay
da5edaf1b4 Change time in template
This template proposes a time which is our peak load for Actions, would this time work better for our customers? Fixes https://github.com/github/codeql-action/issues/258
2020-10-07 09:59:53 -07:00
Marco Gario
4a270064ab Merge pull request #256 from github/update-v1-b1e2c9b8
Merge main into v1
2020-10-07 13:31:57 +02:00
David Verdeguer
e97bdbdfac Combine auto_install scripts 2020-10-07 12:55:02 +02:00
David Verdeguer
526dac0f91 Only run tests on main and v1 2020-10-06 14:47:20 +02:00
David Verdeguer
0f2fa46e3c Update installPythonDeps for windows 2020-10-06 14:37:35 +02:00
David Verdeguer
2748e6c5c1 Update python-deps-windows test_dir paths 2020-10-06 14:21:10 +02:00
David Verdeguer
74afd3c373 Port python deps setup to windows 2020-10-06 14:14:12 +02:00
David Verdeguer
b1e2c9b8bd Merge pull request #255 from github/daverlo/guard-python
Guard python deps install
2020-10-06 12:38:40 +02:00
David Verdeguer
d81cc671c0 Guard python deps install 2020-10-06 11:30:05 +02:00
Robert
3630a78d1a Merge pull request #235 from github/robertbrignull/subdomain
Make URL parsing more robust, and handle subdomain isolation
2020-10-05 17:53:43 +01:00
Robert Brignull
b185050563 Use GITHUB_DOTCOM_URL so URL deduplication works 2020-10-05 16:44:43 +01:00
Chris Raynor
5dc2db0028 Merge pull request #252 from github/update-v1-a1fc3a5e
Merge main into v1
2020-10-05 16:29:49 +01:00
Robert Brignull
28a5b954e7 Merge branch 'main' into robertbrignull/subdomain 2020-10-05 13:36:12 +01:00
Chris Gavin
5cdfcab4d4 Merge pull request #236 from github/ignore-temp-dir
Exclude the temporary directory from scanning.
2020-10-05 13:07:02 +01:00
Chris Gavin
11c1460003 Run npm run lint-fix. 2020-10-05 12:44:58 +01:00
Chris Gavin
14192f8248 Merge branch 'main' into ignore-temp-dir 2020-10-05 12:41:49 +01:00
Chris Raynor
d0afe926eb Merge pull request #238 from github/cbraynor/fix201
Resolve violations of import/no-extraneous-dependencies lint
2020-10-05 10:43:32 +01:00
Chris Raynor
0907cd5a41 Merge branch 'main' into cbraynor/fix201 2020-10-05 10:35:27 +01:00
David Verdeguer
a1fc3a5e79 Merge pull request #155 from github/daverlo/python
Python deps setup
2020-10-05 08:34:05 +02:00
David Verdeguer
55eb02cb0a Merge branch 'main' into daverlo/python 2020-10-05 08:05:16 +02:00
David Verdeguer
4ce302bdb9 Use find in python-des tests 2020-10-05 00:04:20 +02:00
Chris Raynor
1a91a0716f Merge pull request #242 from thaJeztah/cron_hint
README: document cron fields in example
2020-10-04 11:26:53 +01:00
Chris Raynor
319881ca28 Merge branch 'main' into cron_hint 2020-10-04 11:23:44 +01:00
Chris Raynor
a89f5ee6fd Fixing excess whitespace 2020-10-04 11:21:23 +01:00
Chris Raynor
31e2458574 Using standard format from docs
Updating the format slightly to match [the docs](https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows#schedule) precisely
2020-10-04 11:20:31 +01:00
Chris Raynor
fe8c48ed50 Merge pull request #243 from github/dependabot/npm_and_yarn/actions/core-1.2.6
Bump @actions/core from 1.2.0 to 1.2.6
2020-10-03 13:27:39 +01:00
Chris Raynor
f49e963057 Updating node_modules 2020-10-03 12:55:40 +01:00
dependabot[bot]
4290eabf33 Bump @actions/core from 1.2.0 to 1.2.6
Bumps [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) from 1.2.0 to 1.2.6.
- [Release notes](https://github.com/actions/toolkit/releases)
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/core/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/core)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-01 17:36:26 +00:00
Sebastiaan van Stijn
7073967e9a README: document cron fields in example
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2020-10-01 16:52:44 +02:00
Chris Raynor
bf60ce880e Merge branch 'main' into cbraynor/fix201 2020-10-01 12:24:03 +01:00
Chris Raynor
4ff6c0d0c9 Merge pull request #237 from github/cbraynor/fix206
Resolve violations of sort-imports lint
2020-10-01 12:22:14 +01:00
Chris Raynor
6d01157d11 Merge branch 'cbraynor/fix206' into cbraynor/fix201 2020-10-01 11:17:59 +01:00
Chris Raynor
10479a214a Merge branch 'main' into cbraynor/fix206 2020-10-01 11:09:05 +01:00
Chris Raynor
122c9b7f24 Switching to import/order instead of sort-imports 2020-10-01 11:03:46 +01:00
Marco Gario
b9e933968b Merge pull request #240 from github/marcogario/platform-bundle
Platform specific bundle
2020-10-01 11:29:53 +02:00
Chris Gavin
62f25fda9b Ignore the tools directory as well and remove the warning. 2020-10-01 10:03:45 +01:00
Marco Gario
d5029a8680 Platform specific bundle 2020-10-01 10:04:48 +02:00
Chris Gavin
dbecf76db8 Use a relative path to ignore the runner temporary directory. 2020-09-29 15:43:37 +01:00
Chris Raynor
47fa956a52 Updating node_modules 2020-09-29 15:05:16 +01:00
Chris Raynor
8200c137dc Resolve violations of import/no-extraneous-dependencies lint
Fixes #201
2020-09-29 15:03:21 +01:00
Chris Raynor
228546a1e5 Resolve violations of sort-imports lint
Resolves #206
2020-09-29 14:43:37 +01:00
Robin Neatherway
bb6fa8ee6d Merge pull request #217 from github/rneatherway/optional-merge
Do not always overwrite the GITHUB_REF for PRs
2020-09-29 13:17:39 +01:00
Robin Neatherway
2d6f6077bf Merge branch 'main' into rneatherway/optional-merge 2020-09-29 13:02:37 +01:00
Robert
8ea621e2e3 Merge pull request #234 from github/update-v1-f2e557e7
Merge main into v1
2020-09-29 10:34:59 +01:00
David Verdeguer
4e39b768c7 Remove tests that should fail 2020-09-29 10:33:25 +02:00
David Verdeguer
5e2245cc23 Add x permission to the test scripts 2020-09-29 10:06:06 +02:00
David Verdeguer
67ddca1d9c Add workflow for testing python setup 2020-09-29 09:57:29 +02:00
Chris Gavin
206e34cbb4 Exclude the temporary directory from scanning. 2020-09-28 21:43:19 +01:00
Robert Brignull
c4dc1b0438 Make URL parsing more robust 2020-09-28 18:39:56 +01:00
Chris Raynor
2841489ddf Merge pull request #233 from miqh/fix/205
Resolve violations of no-useless-escape lint
2020-09-28 11:49:40 +01:00
Chris Raynor
a2931d32c7 Merge branch 'main' into fix/205 2020-09-28 11:20:31 +01:00
Chris Raynor
bcf29b3c36 Merge pull request #232 from miqh/fix/204
Resolve violations of no-throw-literal lint
2020-09-28 11:18:23 +01:00
Michael Huynh
c68c97e2bd Resolve violations of no-useless-escape lint
Resolves #205
2020-09-28 10:55:58 +08:00
Rasmus Wriedt Larsen
18312707fe Explain get_extractor_version for python setup scripts 2020-09-25 12:07:22 +02:00
Michael Huynh
476bf863f2 Resolve violations of no-throw-literal lint
Resolves #204
2020-09-25 17:39:25 +08:00
David Verdeguer
5419fcd735 Improve warning message 2020-09-25 11:28:57 +02:00
Rasmus Wriedt Larsen
dffce9945c Minor fixes to python installation scripts based on code review 2020-09-24 15:43:34 +02:00
Rasmus Wriedt Larsen
6645c550ef Apply suggestions from code review
Co-authored-by: Marco Gario  <marcogario@github.com>
2020-09-24 15:36:00 +02:00
David Verdeguer
7753dec413 Add min disk free flag to database analyze: 2020-09-24 11:42:21 +02:00
David Verdeguer
34955967b7 Fix python string 2020-09-23 18:06:08 +02:00
David Verdeguer
147734591c Check platform before installing python tools 2020-09-23 17:49:39 +02:00
Robert
f2e557e77f Merge pull request #228 from miqh/fix/197
Resolve violations of eslint-comments/no-use lint
2020-09-23 15:20:37 +01:00
Robert
5d00d5b4e8 Merge branch 'main' into fix/197 2020-09-23 14:28:21 +01:00
Robert
d9f39334ae Merge pull request #229 from miqh/fix/203
Resolve violations of no-sparse-arrays lint
2020-09-23 14:27:27 +01:00
Michael Huynh
38363a1043 Resolve violations of no-sparse-arrays lint
Resolves #203
2020-09-23 21:02:03 +08:00
Michael Huynh
80b408e704 Resolve violations of eslint-comments/no-use lint
Resolves #197
2020-09-23 20:25:45 +08:00
Chris Raynor
481f3ce214 Merge pull request #227 from github/cbraynor/cache-pinning
Prioritizing pre-downloaded CodeQL bundle in some circumstances
2020-09-23 11:58:35 +01:00
Chris Raynor
2f4ca98eb6 Reducing the number of new builds significantly while keeping coverage 2020-09-23 11:54:42 +01:00
David Verdeguer
23a1a65b43 Merge branch 'main' into daverlo/python-v2 2020-09-23 09:27:54 +02:00
Chris Raynor
3b90db98f9 Integration tests now both rely on pre-downloaded and latest codeql bundles 2020-09-22 14:42:23 +01:00
Chris Raynor
41464b1396 Allowing a cached version of the CodeQL bundle sometimes
To save time downloading the CodeQL bundle we're pre-downloading it into the
hosted Actions runner, but because the release schedule is different there may
be some version drift. This change allows a different version of the bundle
to be used than the default if a version isn't explicitly specified, there's
only one version downloaded, and it's been marked as a 'pinned-version' -
otherwise it reverts to the prior behavior.
2020-09-22 14:38:27 +01:00
Chris Gavin
367ad73efb Merge pull request #226 from github/octokit-retry
Fix retrying uploads by using Octokit retry plugin.
2020-09-22 12:39:47 +01:00
Chris Gavin
8d26f6175d Merge branch 'main' into octokit-retry 2020-09-22 12:26:34 +01:00
Chris Gavin
31c2eca167 Fix retrying uploads by using Octokit retry plugin. 2020-09-21 19:15:19 +01:00
Marco Gario
427c79f43f Merge pull request #216 from github/split_bundle
Workflow to split the bundle into components
2020-09-21 18:19:03 +02:00
Marco Gario
c36848d44b Merge branch 'main' into split_bundle 2020-09-21 18:12:53 +02:00
Marco Gario
590fdcd891 Apply suggestions from code review
Co-authored-by: Robert <robertbrignull@github.com>
2020-09-21 18:12:23 +02:00
Chris Gavin
e67ba57e65 Merge pull request #221 from github/update-actions-github
Update to the latest version of `@actions/github`.
2020-09-21 16:06:30 +01:00
Chris Gavin
bba73b6d4e Merge main into update-actions-github. 2020-09-21 15:25:08 +01:00
Chris Gavin
cc0eb452c7 Use getOctokit(...) when getting the GitHub API client. 2020-09-21 15:21:05 +01:00
Chris Raynor
a8a62974b3 Merge pull request #223 from miqh/fix/199
Resolve violations of github/array-foreach lint
2020-09-21 11:11:07 +01:00
Robert
c7c948adb9 Merge pull request #224 from github/update-v1-b2dfa6e6
Merge main into v1
2020-09-21 11:04:47 +01:00
Marco Gario
d265935d24 Update split.yml 2020-09-21 12:00:29 +02:00
Marco Gario
47eb668155 Update split.yml 2020-09-21 12:00:00 +02:00
Marco Gario
1154bf6df9 Update split.yml 2020-09-21 10:13:23 +02:00
Michael Huynh
4666a0eed0 Resolve violations of github/array-foreach lint
Resolves #199
2020-09-20 17:41:27 +08:00
Robert
b2dfa6e690 Merge pull request #219 from github/robertbrignull/init_status_queries
Include workflow queries in status report
2020-09-18 16:56:03 +01:00
Robert
def00916ce Merge branch 'main' into robertbrignull/init_status_queries 2020-09-18 16:36:17 +01:00
Chris Gavin
9ed519fa12 Update to the latest version of @actions/github. 2020-09-18 16:06:20 +01:00
Robert
55458a1ab1 Merge pull request #179 from github/split_builtin_custom_queries
Split up builtin and custom queries
2020-09-18 10:06:50 +01:00
Robert Brignull
1dc1029baf Merge branch 'main' into split_builtin_custom_queries 2020-09-18 09:52:44 +01:00
Marco Gario
5166e750e9 Merge pull request #218 from github/marcogario/reduce_ci_jobs
Reduce triggers in workflows
2020-09-17 18:36:18 +02:00
Robert Brignull
875a8da7e3 include workflow queries in status report 2020-09-17 17:29:45 +01:00
Marco Gario
ade519b950 Reduce triggers in workflows
See #182. Workflows are now triggered on all PRs but only on push on the main and v1 branch
2020-09-17 14:39:18 +02:00
Robin Neatherway
7795860c11 Do not always overwrite the GITHUB_REF for PRs
As we move towards analysing the merge commit for pull requests by
default, we should stop sending `/refs/pull/n/head` rather than
`refs/pull/n/merge` _unless_ the checked-out SHA has actually changed.
Here we assume that any change (compared to GITHUB_SHA) indicates that
`git checkout HEAD^2` has been run earlier. This may sometimes be
incorrect (e.g. `git checkout mybranch`), but in that case the ref
would be wrong either way.
2020-09-17 13:11:06 +01:00
Marco Gario
b4a8cfa05c Add instructions 2020-09-17 13:42:19 +02:00
Marco Gario
7da583bcb3 Workflow to split the bundle into components 2020-09-17 13:36:26 +02:00
Robert
c9b06117cb Merge pull request #211 from github/robertbrignull/consistent_inputs
Make inputs consistent between action and runner
2020-09-17 10:06:43 +01:00
Robert
4b4f9e8e6a Merge branch 'main' into robertbrignull/consistent_inputs 2020-09-17 09:36:51 +01:00
Robert
2c94a7f61f Merge pull request #215 from github/main-v1
Mergeback v1 to main
2020-09-17 09:33:39 +01:00
Marco Gario
5f592775cc Merge branch 'main' into main-v1 2020-09-16 18:37:11 +02:00
Robert
ef3b75cbdb Update action.yml 2020-09-16 16:23:11 +02:00
Robert Brignull
090a7013dd add explanation to query 2020-09-16 11:03:19 +01:00
Robert Brignull
4c4114f2d8 add an extra getRequiredInput 2020-09-16 11:03:13 +01:00
Robert Brignull
7be1a410c2 Merge branch 'main' into robertbrignull/consistent_inputs 2020-09-16 10:50:54 +01:00
Robert Brignull
c1cee53da5 Add getOptionalInput and getRequiredInput 2020-09-15 18:47:50 +01:00
Robert Brignull
d88fa5cef6 Add queries 2020-09-15 18:33:37 +01:00
Robert
f6894d6610 Merge pull request #210 from github/robertbrignull/disable-snippets
Disable snippets by default
2020-09-15 18:25:28 +01:00
Robert
3d5127d682 Update action.yml 2020-09-15 17:45:34 +01:00
Marco Gario
4076e23ec5 Merge pull request #209 from github/remove_file
Remove unused files
2020-09-15 18:02:05 +02:00
Nick Fyson
0da3e94867 Merge branch 'main' into remove_file 2020-09-15 15:16:05 +01:00
Marco Gario
3325da8a15 Remove unused files 2020-09-15 15:51:27 +02:00
Robert
1ca9d4c096 Merge pull request #207 from github/robertbrignull/replace_all
Replace all occurrences instead of just the first
2020-09-15 14:47:05 +01:00
Robert Brignull
121fd331cd Introduce actions-util.ts 2020-09-15 14:01:21 +01:00
Chris Raynor
50d46f662f Merge pull request #184 from github/update-v1-6567bffc
Merge main into v1
2020-09-15 09:09:40 +01:00
Robert Brignull
89dad149ed Replace all occurrences 2020-09-14 18:13:33 +01:00
Nick Fyson
245c02cf7d Merge pull request #174 from github/nickfyson/error_wrapper
add error-catching wrapper around calls to toolrunner
2020-09-14 13:59:39 +01:00
Nick Fyson
e5e9aad174 Merge branch 'main' into nickfyson/error_wrapper
# Conflicts:
#	lib/codeql.js
#	lib/codeql.js.map
#	src/codeql.ts
2020-09-14 13:30:37 +01:00
Chris Raynor
698eab0c5f Merge pull request #181 from github/cbraynor/eslint
Switching to ESLint
2020-09-14 10:59:19 +01:00
Chris Raynor
7bdf90af87 Adding super simple lint Action 2020-09-14 10:51:29 +01:00
Chris Raynor
cb51c857fc Adding temporary overrides to allow the linter to pass 2020-09-14 10:49:02 +01:00
Chris Raynor
a184d50a26 Running lint-fix 2020-09-14 10:44:43 +01:00
Chris Raynor
c96f84308a Regenerating node_modules 2020-09-14 10:42:37 +01:00
Chris Raynor
09b4a82c83 Removing the tslint config 2020-09-14 10:37:55 +01:00
Chris Raynor
06765f9340 Adding ESLint config and required dev dependencies 2020-09-14 10:32:24 +01:00
Nick Fyson
814840b1de Merge branch 'main' into nickfyson/error_wrapper 2020-09-14 10:28:03 +01:00
Chris Raynor
6567bffcb9 Merge pull request #183 from github/dependabot/npm_and_yarn/node-fetch-2.6.1
Bump node-fetch from 2.6.0 to 2.6.1
2020-09-13 11:22:52 +01:00
Chris Raynor
0579b4d27d Vendoring node_modules 2020-09-13 10:27:23 +01:00
dependabot[bot]
0b64878cfe Bump node-fetch from 2.6.0 to 2.6.1
Bumps [node-fetch](https://github.com/bitinn/node-fetch) from 2.6.0 to 2.6.1.
- [Release notes](https://github.com/bitinn/node-fetch/releases)
- [Changelog](https://github.com/node-fetch/node-fetch/blob/master/docs/CHANGELOG.md)
- [Commits](https://github.com/bitinn/node-fetch/compare/v2.6.0...v2.6.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-09-12 20:20:25 +00:00
Nick Fyson
b104d6e035 Merge branch 'main' into nickfyson/error_wrapper
# Conflicts:
#	lib/codeql.js.map
2020-09-11 19:04:05 +01:00
Nick Fyson
b3b99014eb make ErrorMatcher an object rather than a tuple 2020-09-11 18:30:07 +01:00
Nick Fyson
1fb7c81099 tweak in response to reviewer comments 2020-09-11 18:25:23 +01:00
Nick Fyson
57ef26cffe Merge pull request #178 from github/nickfyson/include-snippets
add optional workflow input to specify whether snippets are added to sarif
2020-09-11 14:11:14 +01:00
Nick Fyson
be681d444e Merge branch 'main' into nickfyson/include-snippets 2020-09-11 13:58:53 +01:00
David Verdeguer
4ab5cbcc8a Merge pull request #173 from github/rasmuswl/update-python-scripts
Update Python scripts for "Python deps setup"
2020-09-11 12:41:31 +02:00
Rasmus Wriedt Larsen
1b20fa78be Handle error in poetry 1.0.10 2020-09-11 12:40:40 +02:00
Rasmus Wriedt Larsen
7fc41c62be Update python scripts to handle setup.py 2020-09-11 12:40:40 +02:00
David Verdeguer
5701037850 Add python scripts 2020-09-11 12:25:47 +02:00
Robert
a2cdfc8031 Merge pull request #180 from ericcornelissen/patch-1
Fix "Using a custom configuration" link in the README
2020-09-11 10:13:31 +01:00
David Verdeguer
52274f1815 Setup python extractor for installed deps 2020-09-11 11:07:27 +02:00
David Verdeguer
8cea21575c Install python deps on init 2020-09-11 10:53:41 +02:00
Eric Cornelissen
ea3706d88f Fix "Using a custom configuration" link in README
Fix the "Using a custom configuration" link the README. The actual ID of the header on the page is "using-a-custom-configuration-file", so I updated both the link and the link test to match. (as far as I can tell all other links in the README work as expected)
2020-09-10 20:58:39 +03:00
Nick Fyson
77f767cb34 add optional workflow input to specify whether snippets are added to sarif output 2020-09-10 18:26:58 +01:00
Robert Brignull
0539269665 split up builtin and custom queries 2020-09-10 18:17:03 +01:00
Robert
75af0bf309 Merge pull request #177 from github/external_queries_test
Make a local repo for checkoutExternalQueries
2020-09-10 11:43:03 +01:00
Robert
d4f40db368 Merge branch 'main' into external_queries_test 2020-09-10 11:24:22 +01:00
Robert
c5f77d0bfd Merge pull request #175 from github/runner-integration-tests
Add more integration tests for the runner
2020-09-10 11:23:28 +01:00
Robert
e6083671c7 Merge branch 'main' into runner-integration-tests 2020-09-10 10:57:16 +01:00
Robert
4d8719bb73 Merge pull request #176 from github/fingerprint_test
Add another fingerprinting test
2020-09-10 10:24:01 +01:00
Robert Brignull
3be0e89804 make a local repo for checkoutExternalQueries 2020-09-09 18:30:57 +01:00
Robert Brignull
3db0a253ed add another fingerprinting test 2020-09-09 17:37:53 +01:00
Robert
d82e34bb43 Merge branch 'main' into runner-integration-tests 2020-09-09 17:31:35 +01:00
Robert
67246cd645 Update integration-testing.yml 2020-09-09 17:31:20 +01:00
Sam Partington
028706c3a2 Merge pull request #165 from github/allow-additive-queries-in-workflow
Allow "additive" queries in workflow by prefixing with "+"
2020-09-09 16:41:55 +01:00
Sam Partington
4ad13dff42 Merge branch 'main' into allow-additive-queries-in-workflow 2020-09-09 15:32:20 +01:00
Robert Brignull
e4b0068a9d add more integration tests for the runner 2020-09-08 18:32:52 +01:00
Robert
506e641669 Merge pull request #167 from github/windows_tracing
Fix tracing on windows for the runner, and when using multiple self-hosted actions runners
2020-09-08 11:28:42 +01:00
Sam Partington
18cd03ab62 Make variable name less ambiguous 2020-09-08 10:14:51 +01:00
Sam Partington
d677f16692 Merge branch 'main' into allow-additive-queries-in-workflow 2020-09-08 10:00:16 +01:00
Nick Fyson
88951d6193 renames to reflect the switch to using toolrunner 2020-09-08 00:01:04 +01:00
Nick Fyson
3cd41279f2 Merge branch 'main' into nickfyson/error_wrapper
# Conflicts:
#	lib/codeql.js
#	lib/codeql.js.map
#	src/codeql.ts
2020-09-07 23:55:32 +01:00
Nick Fyson
c4f579a4db remove the intentionally failing matcher integration tests 2020-09-07 23:12:12 +01:00
Nick Fyson
30bb37a5c7 restore all default workflow triggers and integration tests 2020-09-07 23:11:10 +01:00
Nick Fyson
cc2dfaf5d8 clean up and rename things to follow proper conventions 2020-09-07 23:02:58 +01:00
Nick Fyson
3e6d23928b add test for initial error matcher 2020-09-07 22:50:37 +01:00
Nick Fyson
7dbaff09b6 move error matcher definition into dedicated file 2020-09-07 18:37:51 +01:00
Robert Brignull
7d9c81f55c Print final process we choose 2020-09-07 17:23:35 +01:00
Robert Brignull
212f4484d3 Merge branch 'main' into windows_tracing 2020-09-07 17:08:59 +01:00
Robert
556aed46b0 Merge pull request #170 from github/windows_message
Print path to file instead of file contents
2020-09-07 16:23:49 +01:00
Robert Brignull
c68937100c Merge branch 'main' into windows_message 2020-09-07 16:01:09 +01:00
Nick Fyson
1f3ce75844 add initial suite of tests for exec_wrapper 2020-09-07 15:17:43 +01:00
Nick Fyson
9701a93bf1 ensure exec_wrapper always captures exit code of called process 2020-09-07 15:17:19 +01:00
Robert
8c43427531 Merge pull request #169 from github/codeql_download_info
Print that we are downloading codeql and it may take a while
2020-09-07 14:32:37 +01:00
Robert
1a772a2b9e Merge branch 'main' into codeql_download_info 2020-09-07 13:37:20 +01:00
Robert Brignull
694fa2d961 add options to specify process name or level to trace 2020-09-07 13:36:47 +01:00
Robert Brignull
789059e604 Merge branch 'main' into windows_tracing 2020-09-07 12:49:20 +01:00
Robert
0e9b8f4a47 Merge pull request #168 from github/runner_refs
make inputting refs easier
2020-09-07 12:19:56 +01:00
Robert
3901848a2f Merge pull request #171 from github/update-v1-68c6069f
Merge main into v1
2020-09-07 11:42:15 +01:00
Nick Fyson
dd4e841441 remove spurious use of exec_wrapper 2020-09-03 17:01:51 +01:00
Nick Fyson
6a43a6178d ensure matchers not applied if exit code is zero 2020-09-03 16:42:56 +01:00
Robert Brignull
9782622366 Print path to file instead of file contents 2020-09-02 19:58:03 +01:00
Robert Brignull
32eb1c4c34 Print that we are downloading codeql and it may take a while 2020-09-02 18:02:49 +01:00
Robert Brignull
ebb41156ee make inputting refs easier 2020-09-02 18:00:46 +01:00
Nick Fyson
231537b08e refactor to handle exec.exec return values together 2020-09-02 16:32:28 +01:00
Robert Brignull
48df01325b add alternative script for in runner mode 2020-09-02 15:50:37 +01:00
Robert Brignull
5c0bd22d01 set -ExecutionPolicy Bypass 2020-09-02 15:50:23 +01:00
Robert Brignull
2dbd7e8dc1 Fix tracing when there are multiple self-hosted runners 2020-09-02 15:28:50 +01:00
Nick Fyson
6ef533485e wrap more codeql calls in the error catcher wrapper 2020-09-01 16:51:39 +01:00
Nick Fyson
7b7e0e12b7 update error_wrapper to take matcher array 2020-09-01 16:35:08 +01:00
Robert
68c6069f0b Merge pull request #162 from github/runner_analyze
Convert init, autobuild, and analyze actions to CLI / runner mode
2020-09-01 15:01:36 +01:00
Robert Brignull
b4d142e980 whitelist @actions/exec/lib/toolrunner 2020-09-01 14:44:38 +01:00
Robert Brignull
4c00c68d14 Add --ram and --threads args 2020-09-01 14:27:56 +01:00
Robert Brignull
09fb3ec514 Remove a call to getActionsApiClient 2020-09-01 14:01:21 +01:00
Robert Brignull
8a821a9c35 Add logger to checkoutExternalRepository 2020-09-01 13:53:59 +01:00
Robert
b8f7e0ff0f Merge pull request #166 from github/update-v1-5bd2832b
Merge main into v1
2020-09-01 13:30:36 +01:00
Robert Brignull
1548b771cb Merge remote-tracking branch 'origin/main' into runner_analyze 2020-08-28 17:28:14 +01:00
Robert Brignull
a0b54fc7ab fix tests 2020-08-28 17:28:05 +01:00
Robert Brignull
aa7e2fe91b automatically import env in autobuild 2020-08-28 17:22:26 +01:00
Sam Partington
abf5854149 Extract more common test code to function 2020-08-28 17:20:40 +01:00
Sam Partington
23cf700e38 Extract common test code to a function
https://github.com/github/codeql-action/pull/165#discussion_r479396850
2020-08-28 17:13:06 +01:00
Robert Brignull
c3d6602e8a use ToolRunner directly instead of exec wrapper 2020-08-28 16:59:34 +01:00
Sam Partington
831c686d9b Add details of queries property to README 2020-08-28 16:58:15 +01:00
Robert
5bd2832b32 Merge pull request #164 from github/npm_test_os
Run `npm test` on linux and macos
2020-08-28 16:57:28 +01:00
Sam Partington
ab8d9eccc9 Add a test which combines workflow queries and disabling the defaults 2020-08-28 16:53:11 +01:00
Sam Partington
82000c26c8 Allow "additive" queries in workflow by prefixing with "+"
See discussion on https://github.com/github/code-scanning/issues/1446
2020-08-28 16:45:57 +01:00
Robert
b1d719eeeb fix tests on non-linux 2020-08-28 15:13:14 +01:00
Robert
da1c00f5c8 Run npm test on all operating systems 2020-08-28 15:10:47 +01:00
Robert Brignull
80e2c4fe4a improve error message when config is not found 2020-08-28 09:43:25 +01:00
Robert Brignull
37bac22443 Make runner arg descriptions more consistent 2020-08-28 09:35:37 +01:00
Robert Brignull
57f03d3bd0 Remove hash from temp dir 2020-08-28 09:27:28 +01:00
Robert Brignull
6c8f96d781 Log that we're clearing the temp dir 2020-08-27 16:45:41 +01:00
Robert Brignull
3dfaa88a1d Remove process of auth 2020-08-27 16:45:28 +01:00
Robert Brignull
1fd45d7407 address review comments 2020-08-27 16:34:09 +01:00
Robert Brignull
6f422a4303 add debug mode to limit output 2020-08-27 14:26:44 +01:00
Robert Brignull
f80d660e33 check environment before running autobuild or analyze 2020-08-27 14:22:16 +01:00
Robert Brignull
a542021200 make --language optional to autobuild and detect dominant language 2020-08-27 14:08:54 +01:00
Robert Brignull
b42ed69542 Update temp dir and tools dir 2020-08-27 14:08:41 +01:00
Marco Gario
8229390c1d Merge pull request #163 from github/codeql_bundle_20200826
CodeQL Bundle: 20200826
2020-08-27 14:54:09 +02:00
Robert Brignull
39b361ed69 Remove dependence of GITHUB_REPOSITORY env var 2020-08-27 11:06:14 +01:00
Robert Brignull
688df282cd fix exporting env vars on linux 2020-08-26 16:40:58 +01:00
Robert Brignull
e9bfa56061 inline inject-tracer.ps1 2020-08-26 16:20:36 +01:00
Robert Brignull
1f2bd10757 add newline to output 2020-08-26 16:20:36 +01:00
Robert Brignull
1c004b9275 inline tracer-env.js 2020-08-26 16:20:36 +01:00
Robert Brignull
f5d645fc73 Fix use of wrong URL 2020-08-26 16:20:36 +01:00
Robert Brignull
3ffe4b7421 Add code to output required env to files 2020-08-26 16:20:36 +01:00
Robert Brignull
217483dfd6 Convert rest of the actions 2020-08-26 16:20:36 +01:00
Marco Gario
b1aa99c6de Merge branch 'main' into codeql_bundle_20200826 2020-08-26 16:42:16 +02:00
Marco Gario
7e207743ab Update defaults.json 2020-08-26 16:28:44 +02:00
Robert
aac5eb2aea Merge pull request #159 from github/rename_cli
Rename CLI to CodeQL runner
2020-08-26 15:03:23 +01:00
Robert Brignull
09677dada5 rename CLI to runner 2020-08-25 17:44:30 +01:00
Robert
fe756603d9 Merge pull request #152 from github/vercel/pkg
Add vercel/pkg to create standalone CLI
2020-08-25 17:42:54 +01:00
Robert Brignull
80a22f43d8 Merge branch 'main' into vercel/pkg 2020-08-25 15:58:59 +01:00
Robert
c039c3b7a4 Merge pull request #158 from github/tracer-config
Break out tracer-config.ts to its own file
2020-08-25 15:20:36 +01:00
Robert
2df51e04f7 Merge branch 'main' into tracer-config 2020-08-25 15:05:15 +01:00
Sam Partington
abddb8bf00 Merge pull request #127 from github/query-overriding
Allow queries to be specified in the workflow configuration, overriding those set in the config file
2020-08-25 14:29:40 +01:00
Sam Partington
e997bdf637 Merge branch 'main' into query-overriding 2020-08-25 14:21:33 +01:00
Sam Partington
ab4e7216d3 Don't refer to config file in contexts where it's not relevant
https://github.com/github/codeql-action/pull/127#discussion_r476366221
2020-08-25 14:19:16 +01:00
Robert Brignull
1fb8d3b712 fix test workflow again 2020-08-25 12:00:04 +01:00
Robert Brignull
c3c86d82ae Merge remote-tracking branch 'origin/main' into vercel/pkg
the commit.
2020-08-25 11:49:44 +01:00
Esben Sparre Andreasen
ab457bef49 Merge pull request #139 from github/support-multiple-checkouts
Support checkout of multiple refs for a single repository
2020-08-25 12:48:09 +02:00
Robert Brignull
d6daa45d0b update test workflow 2020-08-25 11:46:13 +01:00
Robert Brignull
0bb8872e19 remove build-cli from top-level package.json 2020-08-25 11:45:01 +01:00
Esben Sparre Andreasen
c562bfbd92 Merge branch 'main' into support-multiple-checkouts 2020-08-25 12:35:47 +02:00
Robert Brignull
8efabe9ec9 Merge branch 'main' into tracer-config 2020-08-25 11:35:22 +01:00
Robert
e05e9e6b5d Merge pull request #160 from github/rename_entrypoints
Rename the action entrypoint files
2020-08-25 11:31:17 +01:00
Esben Sparre Andreasen
05f620754e Merge branch 'main' into support-multiple-checkouts 2020-08-25 12:25:42 +02:00
Robert
85c7ad0ecd Merge branch 'main' into rename_entrypoints 2020-08-25 11:10:22 +01:00
Robert
570a0d7142 Merge pull request #161 from github/lib_clean
Clean up the lib directory
2020-08-25 11:10:11 +01:00
Robert Brignull
82fb31ed5e make tests clearer 2020-08-25 11:09:07 +01:00
Nick Fyson
cd22abcda8 add example regex match for stdout/err string 2020-08-25 10:54:54 +01:00
Sam Partington
bdfd48264f Merge branch 'main' into query-overriding 2020-08-25 10:39:53 +01:00
Esben Sparre Andreasen
eecc25f914 build typescript 2020-08-25 11:22:11 +02:00
Esben Sparre Andreasen
45b9e967ef support checkout of multiple refs for a single repository 2020-08-25 11:22:08 +02:00
Sam Partington
129713f1a0 Handle errors in workflow queries correctly 2020-08-25 10:17:54 +01:00
Nick Fyson
45e00a8e6a match existing behaviour when custom listeners defined 2020-08-24 18:35:22 +01:00
Sam Partington
7f19f9198a Refactor common code to function and add missing test 2020-08-24 15:53:24 +01:00
Robert Brignull
9c015b7e83 cleanup lib 2020-08-24 15:18:26 +01:00
Robert Brignull
4bc0c2b0e7 clean the lib dir before building 2020-08-24 15:18:01 +01:00
Robert Brignull
9e342a9b83 rename the action entrypoint files 2020-08-24 15:15:26 +01:00
Sam Partington
c6f02973ac Prevent queries in workflow overriding default queries
https://github.com/github/codeql-action/pull/127#pullrequestreview-463207781
2020-08-24 14:42:05 +01:00
Robert Brignull
88d9e95da6 add minimal instructions for building CLI 2020-08-24 14:04:29 +01:00
Robert Brignull
3c5b7fba82 update node_modules 2020-08-24 14:02:55 +01:00
Robert Brignull
a6e6d4b72b move dependencies needed to build CLI to separate package.json 2020-08-24 14:02:49 +01:00
Robert
06fb4821bc Merge pull request #157 from github/update-v1-bd54c20d
Merge main into v1
2020-08-24 13:46:18 +01:00
Robert Brignull
407ef0ac11 Break out tracer-config.ts 2020-08-24 12:53:09 +01:00
Nick Fyson
2b27c68c84 add exec_wrapper function 2020-08-24 11:22:25 +01:00
Robert
bd54c20d3e Merge pull request #153 from github/add_env_to_config
Add tempDir and codeQLCmd fields to the config
2020-08-21 11:00:48 +01:00
Robert Brignull
0e8b30af75 Merge branch 'main' into add_env_to_config 2020-08-21 10:32:58 +01:00
Robert
1f5a571dfc Merge pull request #151 from github/action_libs_query
Add query to detect use of actions libs
2020-08-21 10:31:20 +01:00
Robert
d193e5f876 Merge branch 'main' into action_libs_query 2020-08-21 10:07:22 +01:00
Robert
5d49d011a2 Merge pull request #144 from github/language_parsing
Refactor language parsing
2020-08-21 10:07:06 +01:00
Robert Brignull
038c4ebdf7 add CodeQL cmd to config 2020-08-19 15:57:13 +01:00
Robert Brignull
360e77a083 remove direct accesses to RUNNER_TEMP 2020-08-19 15:25:27 +01:00
Robert Brignull
9c29fe283d add tempDir and toolCacheDir to config 2020-08-19 15:11:49 +01:00
Robert Brignull
574b5dc4e9 Merge branch 'main' into language_parsing 2020-08-19 09:40:47 +01:00
Esben Sparre Andreasen
e9e2284547 Merge pull request #138 from github/esbena/additional-codeql-options
Support additional codeql options
2020-08-18 10:35:18 +02:00
Esben Sparre Andreasen
9597f2e889 build typescript 2020-08-18 08:32:33 +02:00
Esben Sparre Andreasen
fd94b16cf5 use template strings instead of concatenations 2020-08-18 08:32:04 +02:00
Esben Sparre Andreasen
288f49eee5 use ExtraOptions in codeql commands 2020-08-18 08:32:03 +02:00
Esben Sparre Andreasen
c2b7b7f977 add getExtraOptions utility 2020-08-18 08:32:03 +02:00
Esben Sparre Andreasen
008b0062c6 add ExtraOptions type for codeql commands 2020-08-18 08:32:03 +02:00
Sam Partington
517d9fad41 Improve description of queries property
Co-authored-by: Alistair Christie <54933897+hubwriter@users.noreply.github.com>
2020-08-17 16:33:47 +01:00
Robert Brignull
d6fbafb242 add tests 2020-08-17 13:34:55 +01:00
Robert Brignull
1943ed432b use enum 2020-08-17 13:34:34 +01:00
Robert Brignull
00eee2b7ee Merge branch 'main' into language_parsing 2020-08-17 13:21:02 +01:00
Robert
c5e07ebfcc Merge pull request #149 from github/max_threads
Use all available threads for analysis
2020-08-17 13:12:30 +01:00
Robert
ce75b488a5 Merge pull request #150 from github/update-v1-e9efcf19
Merge main into v1
2020-08-17 12:52:09 +01:00
Robert Brignull
96ded2b500 Merge remote-tracking branch 'origin/main' into max_threads 2020-08-17 12:47:19 +01:00
Robert Brignull
5eb3736850 move maxThreads outside of loop 2020-08-17 12:46:55 +01:00
Robert Brignull
d49b8673bb fix alerts 2020-08-17 12:42:23 +01:00
Robert Brignull
f92a68048c add query to detect use of actions libs 2020-08-17 12:32:22 +01:00
Chris Gavin
e9efcf1900 Merge pull request #145 from github/chrisgavin/default-bundle-version-json
Store the default CodeQL bundle version in a JSON file.
2020-08-14 16:12:59 +01:00
Chris Gavin
73c73baaa2 Merge branch 'main' into chrisgavin/default-bundle-version-json 2020-08-14 15:53:07 +01:00
Robert Brignull
aaeb9751bb use all available threads for analysis 2020-08-14 14:24:08 +01:00
Robert
2527130a32 Merge pull request #147 from github/upload_cli
Add a CLI interface to the upload-sarif action
2020-08-13 18:05:15 +01:00
Robert Brignull
2828c43ac7 fix file location 2020-08-12 18:08:30 +01:00
Robert Brignull
4b56177c28 Re-throw errors 2020-08-12 18:06:34 +01:00
Robert Brignull
150e07f914 add test action 2020-08-12 17:55:40 +01:00
Robert Brignull
5b0aafadb1 address comments 2020-08-12 17:42:47 +01:00
Chris Gavin
9c5f7640e5 Merge branch 'main' into chrisgavin/default-bundle-version-json 2020-08-11 17:52:34 +01:00
Robert Brignull
cf08f5a9cd remove unused arguments 2020-08-11 13:56:23 +01:00
Robert Brignull
34b372292b commit node_modules and generated files 2020-08-11 12:43:27 +01:00
Robert Brignull
6d7a135fea Add a CLI interface to the upload-sarif action 2020-08-11 12:43:06 +01:00
Robert
bcf676e52d Merge pull request #141 from github/actions_io
Remove direct dependency on @actions/io
2020-08-10 16:14:11 +01:00
Robert Brignull
591359cae6 introduce languages.ts 2020-08-10 16:03:09 +01:00
Robert
7c2a7b236c Merge remote-tracking branch 'origin/main' into actions_io 2020-08-10 15:59:27 +01:00
Robert
0fdcc52338 Merge branch 'main' into actions_io 2020-08-10 15:50:44 +01:00
Robert
d5693a7fd2 Merge pull request #140 from github/remove_some_shared_env
Remove some shared env
2020-08-10 15:46:03 +01:00
Robert
eb4eda5cbe Merge branch 'main' into remove_some_shared_env 2020-08-10 15:28:44 +01:00
Chris Gavin
97eafbc804 Store the default CodeQL bundle version in a JSON file. 2020-08-10 13:41:45 +01:00
Robert
9494a25e76 Merge pull request #143 from github/update-v1-86081052
Merge main into v1
2020-08-10 10:46:27 +01:00
Robert
6e18b27d4d Merge pull request #137 from github/invalid_language
Provide a better error message when languages are not recognised
2020-08-10 10:36:01 +01:00
Robert
de0b59097a remove direct dependency on @actions/io 2020-08-07 18:09:45 +01:00
Robert
d5c453c995 mock API request in test 2020-08-07 17:15:46 +01:00
Robert Brignull
657540584e add tests 2020-08-07 17:02:42 +01:00
Robert
a0660c80bd remove should_abort method 2020-08-07 16:56:04 +01:00
Robert
396f7167d8 remove CODEQL_ACTION_TRACED_LANGUAGES and CODEQL_ACTION_SCANNED_LANGUAGES 2020-08-07 16:55:45 +01:00
Robert
e5ad069f2c remove CODEQL_ACTION_ANALYSIS_KEY 2020-08-07 16:54:58 +01:00
Robert
5b35de62bd remove CODEQL_ACTION_DATABASE_DIR 2020-08-07 16:08:16 +01:00
Robert Brignull
d5853409b4 Provide a better error message when language is not recognised 2020-08-06 17:34:45 +01:00
Robert
8608105240 Merge pull request #136 from github/always_log_error
Always log the full error
2020-08-06 17:33:13 +01:00
Robert
ac66bbe1fe Merge branch 'main' into always_log_error 2020-08-06 16:25:10 +01:00
Robert
3a28cb4ca8 Merge pull request #131 from github/languages_error
Improve error messages when no languages or no queries are specified
2020-08-05 10:01:09 +01:00
Robert Brignull
8127c47bbd always log full error 2020-08-05 09:43:46 +01:00
Robert Brignull
44c88fdd05 fix undefined check 2020-08-05 09:40:12 +01:00
Robert Brignull
6230b36dc2 update error message 2020-08-05 09:23:51 +01:00
Robert Brignull
3d552ba624 Merge branch 'main' into languages_error 2020-08-05 09:22:58 +01:00
Andrew Eisenberg
42235cc048 Allow the codeql-action to be run locally (#117)
* Allow the codeql-action to be run locally

This change allows the codeql-action to be run locally through
[act](https://github.com/nektos/act).

In order to run the action locally, you need to do two things:

1. Add the `CODEQL_LOCAL_RUN: true` environment variable. The only way
   I could figure out how to do this was to add it directly in the
   workflow file in an `env` block. It _should_ be possible to add it
   through a `.env` file and pass it to `act`, but I couldn't get it
   working.
2. Run this command `act -j codeql -s GITHUB_TOKEN=<MY_PAT>`

Setting the `CODEQL_LOCAL_RUN` env var will fill in missing env vars
that the action needs, but isn't set by `act`. It will also avoid
making api calls to github that would fail locally.

This is a refactoring discussed in
https://github.com/github/dsp-codeql/issues/36
2020-08-04 14:35:20 -07:00
Alex Ford
631929a68f Merge pull request #135 from github/revert-dont-send-matrix-vars
revert: 'Don't send `matrix_vars` field in status reports.'
2020-08-04 18:43:59 +01:00
Alex Ford
128c2cf718 revert: 'Don't send field in status reports.' 2020-08-04 18:26:31 +01:00
Chris Gavin
69bf3f24d4 Merge pull request #134 from github/merge-v1
Merge v1 into main.
2020-08-04 16:33:57 +01:00
Chris Gavin
02d3d62def Merge remote-tracking branch v1 into main. 2020-08-04 16:30:51 +01:00
Chris Gavin
f0894d52f3 Merge pull request #132 from github/dont-send-matrix-vars
Don't send `matrix_vars` field in status reports.
2020-08-04 16:28:08 +01:00
Chris Gavin
1fb3aaff6e Don't send matrix_vars field in status reports. 2020-08-04 16:21:58 +01:00
Robert Brignull
dc366899d2 Check that the set of queries is non-empty at init time 2020-08-04 10:39:47 +01:00
Robert Brignull
4896ba51da improve error message when no languages are detected 2020-08-04 10:29:50 +01:00
Robert
30d2cce9f8 Merge pull request #128 from github/enterprise_status_reports
Avoid sending status reports on enterprise
2020-08-03 15:18:02 +01:00
Robert
1ef33b0330 Merge pull request #130 from github/update-v1-e8896a90
Merge main into v1
2020-08-03 11:28:33 +01:00
Sam Partington
443d18adb7 Improve variable name 2020-07-31 11:15:09 +01:00
Sam Partington
d998a87469 Fix typo 2020-07-31 11:13:06 +01:00
Sam Partington
f57bf21879 Tidy up test 2020-07-31 11:11:47 +01:00
Sam Partington
ca2b74f2f8 Make test name more descriptive 2020-07-30 17:05:58 +01:00
Sam Partington
7b0f432c26 Add missing JavaScript
https://github.com/github/codeql-action/pull/127/checks?check_run_id=915325110
2020-07-30 16:49:50 +01:00
Robert Brignull
368c14c502 avoid sending status reports on enterprise 2020-07-30 13:00:35 +01:00
Chris Gavin
e8896a906a Merge pull request #123 from github/search-for-bundle
Search for the CodeQL bundle in multiple places.
2020-07-30 10:56:03 +01:00
Chris Gavin
f5ccce0c86 Merge branch 'main' into search-for-bundle 2020-07-30 10:35:09 +01:00
Sam Partington
f03827d513 Add new input to the init action configuration 2020-07-27 16:50:03 +01:00
Sam Partington
2da457060b Allow multiple overriding queries, comma-separated 2020-07-27 16:50:03 +01:00
Sam Partington
95cef22589 Add support for basic query overriding in action file itself
See https://github.com/github/dsp-code-scanning/issues/1446
2020-07-27 16:50:03 +01:00
Robert
74268130c6 Merge pull request #116 from github/status_reports_v2
Upload much more data in status reports
2020-07-27 15:58:17 +01:00
Robert
ae2d7afe3b Merge branch 'main' into status_reports_v2 2020-07-27 14:58:04 +01:00
Robert
12a37237d2 Merge pull request #124 from github/lodash_update
Update lodash
2020-07-27 14:57:28 +01:00
Robert
b38a014f94 Merge pull request #126 from github/update-v1-93dd64d3
Merge main into v1
2020-07-27 14:56:10 +01:00
Chris Gavin
5587e128ff Add a missing space. 2020-07-27 11:06:36 +01:00
Chris Gavin
74b4d8a6db Remove DEFAULT_ from some constant names. 2020-07-27 11:04:49 +01:00
Chris Gavin
175d681835 Factor out reimplementation of toolcache download into its own method. 2020-07-27 11:02:37 +01:00
Chris Gavin
f4e72f4a09 Add a comment explaining an edge-case. 2020-07-27 10:51:51 +01:00
Chris Gavin
5f057318b6 Fix a typo. 2020-07-27 10:48:00 +01:00
Chris Gavin
0f88c0111f Change INSTANCE_API_URL constant to a method. 2020-07-27 10:47:45 +01:00
Chris Gavin
bfaa0cf943 Restructure code to remove an error that can never be thrown. 2020-07-27 10:43:03 +01:00
Chris Gavin
337dbe5618 Remove an unneeded check. 2020-07-27 10:41:39 +01:00
Robert
6f42543a85 update lodash 2020-07-24 16:50:31 +01:00
Andrew Eisenberg
93dd64d351 Use templated strings for better readability 2020-07-24 08:29:04 -07:00
Robert
87758a1402 Upload much more data in status reports 2020-07-24 15:01:44 +01:00
Chris Gavin
813cb0479f Search for the CodeQL bundle in multiple places. 2020-07-24 14:24:44 +01:00
Robert
9769e4a6df Merge pull request #120 from github/default_queries_fix
Default queries fix + reset env vars in tests
2020-07-21 13:11:49 +01:00
Robert
315a9f4b3c fix typo 2020-07-21 12:46:19 +01:00
Robert
0446cb0aff address comments 2020-07-21 12:19:37 +01:00
Robert
29cf06569d reset environment variables between tests 2020-07-21 11:39:55 +01:00
Robert
ee63f4ee4b fix parsing of disable-default-queries field 2020-07-21 11:05:23 +01:00
Robert
5b4f4e40af introduce tests 2020-07-21 10:53:14 +01:00
Robert
58a0034549 Merge pull request #112 from github/undeclared-action-input
Fix undeclared action inputs
2020-07-20 09:30:31 +01:00
Robert Brignull
c7c1aa8045 fix undeclared action inputs 2020-07-16 14:54:15 +01:00
Robert
b673c57b89 Merge pull request #109 from github/codeql_search_path
Move config parsing earlier + add to codeql search path
2020-07-16 09:17:08 +01:00
Robert Brignull
d138b00811 await promise 2020-07-16 09:04:16 +01:00
Robert Brignull
b86c3701ed address review comments 2020-07-15 17:37:37 +01:00
Robert Brignull
7bb6ac6c60 Merge branch 'main' into codeql_search_path 2020-07-15 17:14:38 +01:00
Robert
e775d4e893 Merge pull request #108 from github/update-v1-c3dcf26e
Merge main into v1
2020-07-14 10:34:40 +01:00
Sam Partington
d1d80761ef Merge pull request #111 from github/vscode-debugging
Add support for debugging from VSCode
2020-07-14 10:32:08 +01:00
Sam Partington
7a78ec0a54 Add support for debugging from VSCode
https://github.com/avajs/ava/blob/master/docs/recipes/debugging-with-vscode.md recommends passing the `debug` option to Ava.  However, in my experience Ava waits indefinitely when this option is used, without actually running any tests.

The increased timeout setting is so that tests won't fail prematurely because you're slowly stepping through code.
2020-07-14 09:49:21 +01:00
Robert Brignull
da3d6d25eb move config parsing earlier + add to codeql search path 2020-07-13 14:49:01 +01:00
Robert
c3dcf26eaf Merge pull request #103 from github/lgtm_filters
Add support for LGTM_INDEX_FILTERS
2020-07-10 15:47:16 +01:00
Robert Brignull
189b6ef4bf ban / as a path 2020-07-10 15:33:03 +01:00
Robert Brignull
1a4c658bbf Merge branch 'main' into lgtm_filters 2020-07-10 15:01:22 +01:00
Robert
ec154779ac Merge pull request #100 from github/github_proxy
Use @actions/github as a wrapper around octokit in order to support proxies
2020-07-10 14:37:22 +01:00
Robert Brignull
ca775cfb2e remove bypass-proxy test 2020-07-10 12:58:18 +01:00
Robert Brignull
fb9f2af49f adjust comments 2020-07-10 11:08:29 +01:00
Robert Brignull
60126bfb39 ban backslashes 2020-07-09 18:27:46 +01:00
Robert Brignull
24367a89b5 move checking to when env vars are constructed 2020-07-09 18:05:54 +01:00
Robert Brignull
70980b9f32 Make characters completely illegal on windows 2020-07-09 17:40:26 +01:00
Robert Brignull
bf5b437adb output better errors 2020-07-09 17:01:53 +01:00
Robert Brignull
b6efd2e6de Merge remote-tracking branch 'origin/main' into github_proxy 2020-07-09 16:37:52 +01:00
Robert Brignull
8a6b404471 add tests 2020-07-09 16:36:49 +01:00
Robert Brignull
d781c667b1 Merge branch 'main' into lgtm_filters 2020-07-09 10:30:20 +01:00
Robert Brignull
56417be251 filter ** paths 2020-07-08 16:33:00 +01:00
Robert Brignull
abf6f239fa trim leading slashes 2020-07-08 16:22:29 +01:00
Robert Brignull
9fb69dda17 clarify error slightly more 2020-07-08 15:11:29 +01:00
Robert Brignull
dcebdd6441 give better error messages 2020-07-08 15:06:45 +01:00
Robert
56e74b9096 Merge pull request #102 from github/exclude-lib
Exclude lib directory from analysis
2020-07-08 10:32:12 +01:00
Robert Brignull
13ee335beb Merge remote-tracking branch 'origin/main' into github_proxy 2020-07-07 18:34:09 +01:00
Robert Brignull
07caa0f5cf pull out mockGetContents method 2020-07-07 18:32:29 +01:00
Robert Brignull
f77ab09bf4 add sinon types 2020-07-07 18:32:18 +01:00
Robert
8d908eeab3 Update codeql-config.yml 2020-07-07 13:09:32 +01:00
Robert
cfcff89771 Merge pull request #101 from github/workflow_dispatch
Add workflow_dispatch event
2020-07-07 11:39:47 +01:00
Robert Brignull
fe3dbb7e64 Add support for LGTM_INDEX_FILTERS 2020-07-07 11:37:56 +01:00
Robert
1aeb7665e7 Add workflow_dispatch event 2020-07-07 10:24:41 +01:00
Robert Brignull
0086c2ecdb use @actions/github 2020-07-06 16:25:26 +01:00
Sam Partington
60fdcc2376 Merge pull request #99 from github/update-v1-8947510a
Merge main into v1
2020-07-06 15:17:26 +01:00
Robert
9da537eb33 Merge pull request #93 from github/codeql_mock
Introduce wrapper around codeql
2020-07-06 10:38:41 +01:00
Robert Brignull
5ab09ae291 Make parameter names more descriptive 2020-07-02 14:45:14 +01:00
Robert Brignull
c41d287cae Introduce wrapper around codeql 2020-07-02 14:25:08 +01:00
Sam Partington
8947510a57 Merge pull request #96 from github/pr-template-test-builds
Remove test builds section of PR template
2020-07-02 14:23:33 +01:00
Sam Partington
5d84e87b3d Merge branch 'main' into pr-template-test-builds 2020-07-02 14:11:18 +01:00
Sam Partington
9bc459c5f1 Merge pull request #95 from github/merge-help
Add details of who will merge (CONTRIBUTING.md)
2020-07-02 13:46:52 +01:00
Sam Partington
77e9a735f6 Merge branch 'main' into merge-help 2020-07-02 13:42:20 +01:00
Sam Partington
57a57713c3 Remove test builds section of PR template
This is covered by the CI checks now
2020-07-02 13:37:46 +01:00
Sam Partington
a0bf50cb7b Add details of who will merge (CONTRIBUTING.md) 2020-07-02 13:35:29 +01:00
Robert
72803c4251 Merge pull request #90 from github/analysis_key_status
add analysis_key to status reports
2020-07-02 11:48:14 +01:00
Robert
eaf6649611 Merge branch 'main' into analysis_key_status 2020-07-02 11:34:08 +01:00
Sam Partington
55a6f9e0a8 Merge pull request #94 from github/developer-docs
Add development instructions to CONTRIBUTING.md
2020-07-02 11:07:06 +01:00
Sam Partington
dfed1f7eea Point people at init/action.yml for node version
https://github.com/github/codeql-action/pull/94#discussion_r448502825
2020-07-02 10:55:00 +01:00
Sam Partington
580e603e94 Add development instructions to CONTRIBUTING.md 2020-07-01 14:32:04 +01:00
Robert
de7ff148e5 Merge pull request #91 from github/codeql-bundle-20200630
Update codeql bundle
2020-07-01 09:55:41 +01:00
Robert
480467971e Merge branch 'main' into codeql-bundle-20200630 2020-06-30 16:03:24 +01:00
Sam Partington
e2a8f32427 Merge pull request #87 from github/support-remote-config
Allow config files to be from a remote repository
2020-06-30 15:19:23 +01:00
Sam Partington
260a93fe06 Merge branch 'main' into support-remote-config 2020-06-30 14:57:35 +01:00
Sam Partington
dc2678801a Use right SHA in integration test
1bb294af6b (r40266717)
2020-06-30 14:37:27 +01:00
Sam Partington
c953f77bb6 Merge pull request #92 from github/use-checkout-v2
Use v2 of checkout action
2020-06-30 14:33:21 +01:00
Sam Partington
aa6c2c5bda Fix URL in integration test
https://github.com/github/codeql-action/runs/822529558?check_suite_focus=true#step:4:43
2020-06-30 14:32:36 +01:00
Sam Partington
a52f1a55ed Fix workflow name 2020-06-30 14:17:37 +01:00
Sam Partington
1bb294af6b Combine integration tests for simplicity
https://github.com/github/codeql-action/pull/87#issuecomment-651757413
2020-06-30 14:15:51 +01:00
Sam Partington
25a0a6baed Use v2 of checkout action 2020-06-30 14:11:08 +01:00
Sam Partington
4b37db72e4 Add integration test for retrieval of remote config
https://github.com/github/codeql-action/pull/87#pullrequestreview-439357075
2020-06-30 12:22:08 +01:00
Robert
04b2540e30 Update codeql bundle 2020-06-30 11:39:56 +01:00
Robert
010117c1b7 Merge pull request #89 from github/update-v1-a08742f1
Merge main into v1
2020-06-30 10:59:34 +01:00
Robert
e0299c3c04 Merge pull request #88 from github/fail-fast
Remove `strategy: fail-fast`
2020-06-29 12:49:28 +01:00
Robert Brignull
0e3f8311ed add analysis_key to status reports 2020-06-29 11:24:04 +01:00
Sam Partington
ca76a2ca94 Add .DS_Store files from node module
https://github.com/github/codeql-action/pull/87/checks?check_run_id=811678038
2020-06-29 09:18:18 +01:00
Robert
aad14bf2cb Remove strategy: fail-fast 2020-06-29 08:49:16 +01:00
Robin Neatherway
a08742f199 Merge pull request #86 from github/correct-test-description
Correct copy/pasted test description
2020-06-26 18:41:17 +01:00
Sam Partington
6afe41036b Update node modules
https://github.com/github/codeql-action/pull/87/checks?check_run_id=811666672
2020-06-26 16:27:11 +01:00
Sam Partington
ee4cc86b19 Merge branch 'main' into support-remote-config 2020-06-26 16:14:32 +01:00
Sam Partington
0607771cc2 Make remote config retrieval more robust 2020-06-26 16:14:15 +01:00
Robin Neatherway
151d531bd0 Correct copy/pasted test description 2020-06-26 16:01:59 +01:00
Sam Partington
51becd2cf8 Bring error message method name inline with others 2020-06-26 15:44:57 +01:00
Sam Partington
a66f2b0b11 Remove redundant comment 2020-06-26 15:44:13 +01:00
Robin Neatherway
504c8cfc6f Merge pull request #85 from github/non-empty-env-vars
getRequiredEnvParams must be non-empty
2020-06-26 15:43:55 +01:00
Robin Neatherway
a0d4330434 Simplify singleton tests by removing the loop 2020-06-26 15:25:32 +01:00
Sam Partington
7c00663f08 Remove tests of internal function now its behaviour has been verified 2020-06-26 14:46:53 +01:00
Sam Partington
f8c87948ab Use new API client
From https://github.com/github/codeql-action/pull/82
2020-06-26 14:45:37 +01:00
Sam Partington
9566d8c220 Merge branch 'main' into support-remote-config 2020-06-26 13:48:59 +01:00
Sam Partington
366d8a32d1 Retrieve remote configuration where specified 2020-06-26 11:49:00 +01:00
Robin Neatherway
bb9ed79f3d getRequiredEnvParams must be non-empty 2020-06-26 11:44:17 +01:00
Chris Gavin
17548064f9 Merge pull request #82 from github/octokit
Use a single Octokit client for everything rather than a bunch of Octokits and an HTTP client.
2020-06-26 11:03:01 +01:00
Chris Gavin
ef507971e7 Merge branch 'main' into octokit 2020-06-26 10:29:51 +01:00
Robert
96d02d50f7 Merge pull request #84 from github/remove_git_dependency
Fall back to GITHUB_SHA env var if git is not available
2020-06-25 16:55:32 +01:00
Robert Brignull
0fdc2c71e4 fall back to GITHUB_SHA env var if git is not available 2020-06-25 15:53:24 +01:00
Robert
28944b580b Merge pull request #83 from github/aborted_completed_at
Include completed_at when action is aborted
2020-06-25 15:11:12 +01:00
Sam Partington
388403b46e Add a test that an Octokit request is made for remote config 2020-06-25 15:10:17 +01:00
Sam Partington
32c9898fa4 Fix regex 2020-06-25 15:10:17 +01:00
Sam Partington
56292b1fa3 Reset mocks in test so they don't leak into later test 2020-06-25 15:10:17 +01:00
Robert Brignull
50a2815790 Include completed_at when action is aborted 2020-06-25 14:10:28 +01:00
Sam Partington
a19d19e0a3 Add validation of remote config location, no retrieval yet 2020-06-25 13:21:46 +01:00
Sam Partington
153a598a97 Add a new function used to determine where to retrieve config from 2020-06-24 16:15:25 +01:00
Sam Partington
f4cf65ca2d Add a test that Octokit isn't used for local config 2020-06-24 14:42:29 +01:00
Sam Partington
b0af5695e6 Add sinon package for mocking 2020-06-24 14:34:08 +01:00
Sam Partington
43c1bea680 Run npm install so have clear baseline 2020-06-24 14:33:14 +01:00
Alex Kalyvitis
6846c702da Merge pull request #81 from github/report-action-aborted
Report that an action has been aborted on configuration failures
2020-06-24 15:06:35 +02:00
Alex Kalyvitis
559e2600c1 Merge branch 'main' into report-action-aborted 2020-06-24 15:04:07 +02:00
Robert
5bb9e6e131 Merge pull request #79 from github/only-output-on-failure
Only output anything from tests when there's a failure
2020-06-24 14:03:30 +01:00
Chris Gavin
464ce1b43a Manually convert response.data to a JSON string. 2020-06-24 13:50:52 +01:00
Alex Kalyvitis
8530f5b76a add missing semicolon 2020-06-24 14:37:12 +02:00
Alex Kalyvitis
a67896b792 fix typo and throw error when languages are not detected 2020-06-24 14:31:06 +02:00
Robert
b3ffa760ab Merge branch 'main' into only-output-on-failure 2020-06-24 13:13:46 +01:00
Alex Kalyvitis
3871ca717b reformat remaining 4 space indentations 2020-06-24 14:12:51 +02:00
Alex Kalyvitis
a091618158 Merge branch 'main' into report-action-aborted 2020-06-24 14:04:46 +02:00
Robert
04adf2bf60 Merge pull request #80 from github/symlinks_test
Make the temporary directory in tests a symlink
2020-06-24 10:23:06 +01:00
Chris Gavin
74c48f71fa Use a single Octokit client for everything rather than a bunch of Octokits and an HTTP client. 2020-06-23 21:40:42 +01:00
Alex Kalyvitis
b8ac06a9c8 run tslint --fix 2020-06-23 18:41:16 +02:00
Robert Brignull
7581ac8b17 make the temporary directory in tests a symlink 2020-06-23 17:40:54 +01:00
Alex Kalyvitis
af252d2f0d report action has aborted 2020-06-23 18:36:08 +02:00
Robert Brignull
cb384e776b fix indentation 2020-06-23 17:29:15 +01:00
Robert Brignull
403832b950 Merge remote-tracking branch 'origin/main' into only-output-on-failure 2020-06-23 17:18:35 +01:00
Robert Brignull
52e52435f7 handle Uint8Array 2020-06-23 17:17:11 +01:00
Robert
bc21c8f6f3 Merge pull request #77 from nickrolfe/nickrolfe/codeql.exe
Call codeql.exe rather than codeql.cmd wrapper on Windows
2020-06-23 16:39:34 +01:00
Nick Rolfe
9a784b1f57 Merge remote-tracking branch 'upstream/main' into nickrolfe/codeql.exe 2020-06-23 16:01:51 +01:00
Chris Gavin
b3c9d6f3a9 Merge pull request #78 from github/fix-indentation
Make indentation consistent.
2020-06-23 15:40:31 +01:00
Robert
f009c4c924 Merge branch 'main' into nickrolfe/codeql.exe 2020-06-23 15:37:34 +01:00
Nick Rolfe
852d99d8e2 Call codeql.exe rather than codeql.cmd wrapper on Windows 2020-06-23 15:25:45 +01:00
Chris Gavin
052d39e909 Fix some strange formatting. 2020-06-23 14:44:40 +01:00
Chris Gavin
107d8ffc4c Fix a line that's too long. 2020-06-23 14:44:40 +01:00
Chris Gavin
88231094bf Convert all 4-space indented files to 2-space. 2020-06-23 14:44:40 +01:00
Chris Gavin
211ad30f72 Update TSLint configuration to detect bad indentation. 2020-06-23 14:44:36 +01:00
Robert Brignull
350bf488da add semicolon 2020-06-23 14:42:52 +01:00
Chris Gavin
a1d945f14f Add a .editorconfig with our chosen formatting options. 2020-06-23 14:38:30 +01:00
Robert Brignull
bd4042802d Merge remote-tracking branch 'origin/main' into only-output-on-failure 2020-06-23 14:36:53 +01:00
Robert Brignull
02776246bf Only output on failing tests 2020-06-23 14:36:40 +01:00
Robert Brignull
66be268a09 run verbose 2020-06-23 14:36:40 +01:00
Robert Brignull
56f06c77fd add calls 2020-06-23 14:36:40 +01:00
Alex Kalyvitis
98f8945cfb Merge pull request #73 from github/add-analyze-threads-flag
Add threads flag to analyze action
2020-06-23 15:03:08 +02:00
Sam Partington
a30a5ba788 Add silencing to additional test files
https://github.com/github/codeql-action/pull/75#issuecomment-648104201
2020-06-23 13:59:58 +01:00
Alex Kalyvitis
9133b2b54d Merge branch 'main' into add-analyze-threads-flag 2020-06-23 14:46:41 +02:00
Robert
8e098cbb87 Merge pull request #72 from github/release-sorting
Fixing sorting of PRs
2020-06-23 13:06:31 +01:00
Alex Kalyvitis
7ae8c32cbe Merge branch 'main' into add-analyze-threads-flag 2020-06-23 13:22:23 +02:00
Robert
beedd317d2 Merge branch 'main' into release-sorting 2020-06-23 12:13:58 +01:00
Sam Partington
8a67191278 Merge pull request #76 from github/update-release-branch-base
Update release branch base
2020-06-23 10:27:04 +01:00
Sam Partington
1ce7f98898 Update other references to master in release script 2020-06-23 10:10:23 +01:00
Sam Partington
6d413dd723 Update release branch script as main branch is now "main".
See https://github.com/github/dsp-code-scanning/issues/1457
2020-06-23 10:08:23 +01:00
Alex Kalyvitis
31996935e6 reformat code and allow negative values for threads 2020-06-22 21:39:09 +02:00
Alex Kalyvitis
bcb5b28954 format code 2020-06-22 18:55:20 +02:00
Sam Partington
8622312249 Update JavaScript with newer comment 2020-06-22 17:20:29 +01:00
Sam Partington
c0c67ce80f Reduce debug output in tests 2020-06-22 17:13:47 +01:00
Alex Kalyvitis
bc9591a12b revert node_modules from master 2020-06-22 17:20:03 +02:00
Alex Kalyvitis
dcba70915d move functions to util.ts 2020-06-22 17:17:25 +02:00
Alex Kalyvitis
2758bd30c8 avoid floating point division of ram 2020-06-22 14:51:18 +02:00
Alex Kalyvitis
f4001a0790 update dependencies 2020-06-22 13:28:23 +02:00
Alex Kalyvitis
d55f711b71 introduce inputs.threads flag to analyze action 2020-06-22 13:27:03 +02:00
Robert
2845a93f4c Fixing sorting of PRs 2020-06-22 11:27:50 +01:00
Robert
7970d85db4 Merge pull request #71 from github/update-v1-74f864b
Merge master into v1
2020-06-22 10:28:42 +01:00
Alex Kalyvitis
74f864bee1 Merge pull request #69 from github/fix-self-hosted-stale-bundle-download
Use bundle URL version as the cache version
2020-06-19 14:33:53 +02:00
Alex Kalyvitis
38c231113e build ts 2020-06-19 13:41:33 +02:00
Alex Kalyvitis
34c941dc31 Use Object.entries() instead of checking hasOwnProperty
Co-authored-by: Robert <robertbrignull@github.com>
2020-06-19 13:27:45 +02:00
Alex Kalyvitis
5eccb79587 improve regex 2020-06-19 12:07:06 +02:00
Alex Kalyvitis
11a9af0387 update deps again 2020-06-18 19:10:34 +02:00
Alex Kalyvitis
6d036cef6f Merge branch 'master' into fix-self-hosted-stale-bundle-download 2020-06-18 19:08:04 +02:00
Alex Kalyvitis
f9768ac4ba update deps 2020-06-18 18:43:30 +02:00
Alex Kalyvitis
3ff198f23b fix tslint errors 2020-06-18 18:29:25 +02:00
Alex Kalyvitis
ff8fe44e0c compiled js 2020-06-18 16:40:02 +02:00
Alex Kalyvitis
3f2a60be8a switch to semver instead of hash 2020-06-18 16:31:39 +02:00
Alex Kalyvitis
4c6749115a update @actions/tool-cache, install semver, nock 2020-06-18 16:31:13 +02:00
Sam Partington
608ed15968 Merge pull request #67 from github/dont-fail-on-symlinks
Ensure config path comparisons don't fail where workspace path is a symlink
2020-06-18 09:21:27 +01:00
Sam Partington
14f179f70b Merge branch 'master' into dont-fail-on-symlinks 2020-06-17 16:14:36 +01:00
Sam Partington
dc4009c7ed Merge pull request #68 from github/ignore-javascript
Configure VSCode to ignore transpiled JavaScript
2020-06-17 16:14:07 +01:00
Sam Partington
14d602cced Fix test failures introduced by making code more robust 2020-06-17 16:00:19 +01:00
Sam Partington
24096a1cb3 Don't fail if query path doesn't exist 2020-06-17 15:55:14 +01:00
Alex Kalyvitis
74d434c5ca fix lint errors 2020-06-17 16:19:00 +02:00
Alex Kalyvitis
fff3de9938 wip: hash bundle url and use it as the cache version 2020-06-17 16:13:58 +02:00
Sam Partington
1aae76b906 Configure VSCode to ignore transpiled JavaScript 2020-06-17 14:57:29 +01:00
Sam Partington
013c02758e Apply realpathSync sooner
Fixes lint: https://github.com/github/codeql-action/pull/67/checks?check_run_id=777215812
2020-06-16 17:04:30 +01:00
Sam Partington
0b53ebbc36 Fix config path comparisons where workspace path is a symlink
Before this change, config-utils.ts › load non-empty input was failing on Mac with:

The configuration file "/var/folders/gx/y8v1507s29d97m1r_5kq0s000000gn/T/codeql-action-oum66d/input" is invalid: property "queries.uses" is invalid as the local path "" is outside of the repository

The reason is that the tmp directory (which is where the config file was put by the test) was a symlink.
2020-06-16 16:59:15 +01:00
Robert
6de3e1cde4 Merge pull request #65 from github/init_missing_matrix
Add matrix input to init action
2020-06-16 13:10:16 +01:00
Robert
c9d0312cb7 Merge branch 'master' into init_missing_matrix 2020-06-16 12:47:50 +01:00
Robert
0cdf645694 Merge pull request #63 from github/add_dispatch_instructions
Add simple instructions for sending repository dispatch event
2020-06-16 09:57:41 +01:00
Robert
d00417a341 Merge branch 'master' into add_dispatch_instructions 2020-06-16 09:34:13 +01:00
Robert
7928587bdf Update .github/workflows/update-release-branch.yml
Co-authored-by: Alex Kalyvitis <1204095+alexkappa@users.noreply.github.com>
2020-06-16 09:34:06 +01:00
Sam Partington
87ecd0d0cc Merge pull request #64 from github/remove-jest-config
Remove jest config as tests use Ava now
2020-06-15 17:04:17 +01:00
Robert
7496ac4fb3 Merge pull request #62 from github/update-v1-042ab54
Merge master into v1
2020-06-15 16:42:59 +01:00
Sam Partington
7e2e297e07 Remove jest config as tests use Ava now
Usage of Jest was removed in https://github.com/github/codeql-action/pull/18
2020-06-15 16:24:34 +01:00
Robert Brignull
b97097aaed add matrix input to init action 2020-06-15 15:52:53 +01:00
Robert
8a8a49d3c5 Merge pull request #39 from github/validate_sarif
Validate sarif against schema before uploading
2020-06-15 14:59:31 +01:00
Robert Brignull
fcb696ec59 Merge branch 'master' into validate_sarif 2020-06-15 14:40:01 +01:00
Robert Brignull
c2d2dfdcdd add instructions 2020-06-15 14:17:16 +01:00
Robert
042ab541fd Merge pull request #61 from github/disable_queries
Add a quick way to disable builtin queries
2020-06-15 14:14:57 +01:00
Robert Brignull
19faafba94 Add ability to disable builtin queries 2020-06-15 12:01:38 +01:00
Robert
c13712badb Merge pull request #60 from github/update-v1-6bd7f17
Merge master into v1
2020-06-15 10:40:53 +01:00
Robert
476c8a44ba Merge pull request #57 from github/fixIsInterpretedLanguage
Fix the login in the isInterpretedLanguage method
2020-06-15 10:06:56 +01:00
Robert
f9ef310b75 Merge branch 'master' into fixIsInterpretedLanguage 2020-06-15 09:56:33 +01:00
Robert
6bd7f17e0e Merge pull request #59 from github/update-release-branch
Add script to open PR for updating release branch
2020-06-12 15:36:00 +01:00
Robert Brignull
582fd14a81 Add script to open PR for updating release branch 2020-06-12 11:15:14 +01:00
Robert Brignull
8425341ae0 change && to || 2020-06-11 13:53:30 +01:00
Robert
1f2cca021a Merge pull request #55 from Marcono1234/patch-1
Update CodeQL link in README
2020-06-10 08:52:45 +01:00
Marcono1234
fa9e0ac2a6 Update CodeQL link in README 2020-06-10 01:03:12 +02:00
Robert
a9de5b50d7 Merge pull request #46 from github/safe-config-parsing
Make config file parsing more strict
2020-06-09 12:36:49 +01:00
Robert Brignull
af4edf6546 fix typos 2020-06-09 10:42:52 +01:00
Robert Brignull
5a97f7e980 Merge branch 'master' into safe-config-parsing 2020-06-09 10:39:49 +01:00
Robert
d4fb7fc762 Merge pull request #54 from github/self-hosted
Fix action when using self-hosted runnners
2020-06-09 10:28:26 +01:00
Robert Brignull
00ebedc522 Merge branch 'master' into self-hosted 2020-06-09 09:43:41 +01:00
Robert
840dc5ee9a Merge pull request #49 from github/always-report-exceptions-v2
Report exceptions during upload
2020-06-08 14:58:17 +01:00
Robert Brignull
c1add46efa Merge branch 'master' into validate_sarif 2020-06-08 13:48:14 +01:00
Robert Brignull
e35c90f53d Merge branch 'master' into safe-config-parsing 2020-06-08 13:40:17 +01:00
Robert Brignull
6db8182349 Merge branch 'master' into always-report-exceptions-v2 2020-06-08 13:24:24 +01:00
Robert
202704856d Merge pull request #27 from github/slim-readme
Reduce duplication between help and readme
2020-06-05 09:49:41 +01:00
Robert Brignull
5ea736059a move all files to the RUNNER_TEMP directory 2020-06-04 12:15:34 +01:00
Robert
a30f8542ee Merge pull request #53 from github/update-v1
Update v1 branch
2020-06-04 09:58:53 +01:00
Robert Brignull
b4610ac367 reduce duplication between readme and docs 2020-06-04 09:54:20 +01:00
Robert
a0d60d5d9e Merge pull request #45 from github/suite_syntax
introduce new syntax for built-in query suites
2020-06-03 11:14:49 +01:00
Robert Brignull
f18fffbea8 pass queries to codeql via a file 2020-06-01 18:14:36 +01:00
Robert Brignull
655c4497ce fix when there are additional suites and custom queries 2020-06-01 13:56:27 +01:00
Robert Brignull
d7a2025f2d run all queries 2020-06-01 13:17:05 +01:00
Robert
aca790b504 Merge pull request #51 from github/update-v1
Update v1
2020-06-01 13:09:45 +01:00
Robert Brignull
22501fd7c8 change method used to check inclusion 2020-06-01 13:06:47 +01:00
Robert Brignull
07e22b1f4a add missing return statement 2020-06-01 12:58:38 +01:00
Robert Brignull
3c2191ffdd fix array inclusion test 2020-06-01 12:45:23 +01:00
Robert Brignull
28abced8ca Merge remote-tracking branch 'origin/master' into suite_syntax 2020-06-01 12:20:08 +01:00
Robert Brignull
50dcaaf00d use the new additional suites 2020-06-01 12:19:24 +01:00
Robert Brignull
30f7117e6a update codeql bundle version 2020-06-01 12:07:23 +01:00
Robert
28a878efc3 Merge pull request #43 from github/integration_test_check
Check integration test results
2020-06-01 10:33:50 +01:00
Robert
d518039a6b Merge branch 'master' into integration_test_check 2020-06-01 10:07:31 +01:00
Robert
855f965205 Merge pull request #50 from github/fix-workflow-indentation
Fix identation in workflow
2020-06-01 10:06:43 +01:00
Robert
2909e97a32 Update codeql.yml 2020-06-01 09:44:48 +01:00
Robert
4997c3ff4d Merge pull request #48 from github/allow_pull_requests
Allow pull requests, and report correct commit oid and ref
2020-06-01 09:39:24 +01:00
Robert
0bd4da3a6c Merge branch 'master' into allow_pull_requests 2020-06-01 09:18:20 +01:00
David Verdeguer
98ad2fc49d Merge pull request #35 from github/issue
Add help link at issue creation
2020-05-29 09:04:40 +02:00
David Verdeguer
3ca3147cd4 Apply suggestions from code review
Co-authored-by: Justin Hutchings <jhutchings1@users.noreply.github.com>
2020-05-29 08:22:30 +02:00
Robert Brignull
96da037d49 report exceptions during upload 2020-05-28 10:40:26 +01:00
Robert Brignull
da1e237d1e Allow pull requests, and report correct commit oid and ref 2020-05-28 09:26:52 +01:00
Robert Brignull
054f867322 make config file parsing more strict 2020-05-26 19:23:28 +01:00
Robert Brignull
1e600686e7 introduce new syntax for built-in query suites 2020-05-26 16:02:22 +01:00
Robert Brignull
cd1625a162 update rubocop version 2020-05-26 10:29:57 +01:00
Ana Armas Romero
8788e5aa59 Merge branch 'master' into issue 2020-05-25 13:22:22 +02:00
Robert Brignull
8fb9090674 fix tests 2020-05-22 17:09:41 +01:00
Robert Brignull
10a2fd615f remove uniqueItems: false 2020-05-22 16:58:00 +01:00
Robert Brignull
ae301902e1 output a better error message 2020-05-22 14:56:20 +01:00
Robert Brignull
ddee374101 validate sarif against schema before uploading 2020-05-22 14:19:16 +01:00
Robert
80a5f3c700 Merge pull request #44 from github/merge-master-v1
Update v1 branch to latest master
2020-05-22 10:20:25 +01:00
Robert Brignull
6d1f969b1c check integration test results 2020-05-18 15:58:42 +01:00
David Verdeguer
58c1abf92e Add help link at issue creation 2020-05-14 15:36:47 +02:00
Robert
999c772fa3 Merge pull request #15 from github/master
Update v1 branch
2020-05-01 17:03:38 +01:00
Arthur Baars
74eb3b3541 Merge pull request #6 from github/master
Merge changes from master into v1
2020-04-29 15:06:15 +02:00
7006 changed files with 744034 additions and 118874 deletions

10
.editorconfig Normal file
View File

@@ -0,0 +1,10 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
indent_style = space
indent_size = 2

5
.eslintignore Normal file
View File

@@ -0,0 +1,5 @@
**/webpack.config.js
lib/**
runner/dist/**
src/testdata/**
tests/**

54
.eslintrc.json Normal file
View File

@@ -0,0 +1,54 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "filenames", "github", "import", "no-async-foreach"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"plugin:github/recommended",
"plugin:github/typescript"
],
"rules": {
"filenames/match-regex": ["error", "^[a-z0-9-]+(\\.test)?$"],
"import/extensions": "error",
"import/no-amd": "error",
"import/no-commonjs": "error",
"import/no-dynamic-require": "error",
"import/no-extraneous-dependencies": ["error"],
"import/no-namespace": "off",
"import/no-unresolved": "error",
"import/no-webpack-loader-syntax": "error",
"import/order": ["error", {
"alphabetize": {"order": "asc"},
"newlines-between": "always"
}],
"no-async-foreach/no-async-foreach": "error",
"no-console": "off",
"no-sequences": "error",
"no-shadow": "off",
"@typescript-eslint/no-shadow": ["error"],
"one-var": ["error", "never"]
},
"overrides": [{
// "temporarily downgraded during transition to eslint
"files": "**",
"rules": {
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/prefer-regexp-exec": "off",
"@typescript-eslint/require-await": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"func-style": "off"
}
}]
}

7
.gitattributes vendored
View File

@@ -1 +1,8 @@
lib/*.js linguist-generated=true
# Reduce incidence of needless merge conflicts on CHANGELOG.md
# The man page at
# https://mirrors.edge.kernel.org/pub/software/scm/git/docs/gitattributes.html
# suggests that this might interleave lines arbitrarily, but empirically
# it keeps added chunks contiguous
CHANGELOG.md merge=union

5
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Contact GitHub Support
url: https://support.github.com/request
about: Contact Support

View File

@@ -2,5 +2,13 @@ name: "CodeQL config"
queries:
- name: Run custom queries
uses: ./queries
# Run all extra query suites, both because we want to
# and because it'll act as extra testing. This is why
# we include both even though one is a superset of the
# other, because we're testing the parsing logic and
# that the suites exist in the codeql bundle.
- uses: security-extended
- uses: security-and-quality
paths-ignore:
- tests
- tests
- lib

View File

@@ -1,7 +1,5 @@
### Merge / deployment checklist
- Run test builds as necessary. Can be on this repository or elsewhere as needed in order to test the change - please include links to tests in other repos!
- [ ] CodeQL using init/analyze actions
- [ ] 3rd party tool using upload action
- [ ] Confirm this change is backwards compatible with existing workflows.
- [ ] Confirm the [readme](https://github.com/github/codeql-action/blob/master/README.md) has been updated if necessary.
- [ ] Confirm the [readme](https://github.com/github/codeql-action/blob/main/README.md) has been updated if necessary.
- [ ] Confirm the [changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) has been updated if necessary.

228
.github/update-release-branch.py vendored Normal file
View File

@@ -0,0 +1,228 @@
import datetime
from github import Github
import random
import requests
import subprocess
import sys
import json
import datetime
import os
EMPTY_CHANGELOG = """# CodeQL Action and CodeQL Runner Changelog
## [UNRELEASED]
No user facing changes.
"""
# The branch being merged from.
# This is the one that contains day-to-day development work.
MAIN_BRANCH = 'main'
# The branch being merged into.
# This is the release branch that users reference.
LATEST_RELEASE_BRANCH = 'v1'
# Name of the remote
ORIGIN = 'origin'
# Runs git with the given args and returns the stdout.
# Raises an error if git does not exit successfully.
def run_git(*args):
cmd = ['git', *args]
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if (p.returncode != 0):
raise Exception('Call to ' + ' '.join(cmd) + ' exited with code ' + str(p.returncode) + ' stderr:' + p.stderr.decode('ascii'))
return p.stdout.decode('ascii')
# Returns true if the given branch exists on the origin remote
def branch_exists_on_remote(branch_name):
return run_git('ls-remote', '--heads', ORIGIN, branch_name).strip() != ''
# Opens a PR from the given branch to the release branch
def open_pr(repo, all_commits, short_main_sha, branch_name):
# Sort the commits into the pull requests that introduced them,
# and any commits that don't have a pull request
pull_requests = []
commits_without_pull_requests = []
for commit in all_commits:
pr = get_pr_for_commit(repo, commit)
if pr is None:
commits_without_pull_requests.append(commit)
elif not any(p for p in pull_requests if p.number == pr.number):
pull_requests.append(pr)
print('Found ' + str(len(pull_requests)) + ' pull requests')
print('Found ' + str(len(commits_without_pull_requests)) + ' commits not in a pull request')
# Sort PRs and commits by age
pull_requests = sorted(pull_requests, key=lambda pr: pr.number)
commits_without_pull_requests = sorted(commits_without_pull_requests, key=lambda c: c.commit.author.date)
# Start constructing the body text
body = []
body.append('Merging ' + short_main_sha + ' into ' + LATEST_RELEASE_BRANCH)
conductor = get_conductor(repo, pull_requests, commits_without_pull_requests)
body.append('')
body.append('Conductor for this PR is @' + conductor)
# List all PRs merged
if len(pull_requests) > 0:
body.append('')
body.append('Contains the following pull requests:')
for pr in pull_requests:
merger = get_merger_of_pr(repo, pr)
body.append('- #' + str(pr.number) + ' - ' + pr.title +' (@' + merger + ')')
# List all commits not part of a PR
if len(commits_without_pull_requests) > 0:
body.append('')
body.append('Contains the following commits not from a pull request:')
for commit in commits_without_pull_requests:
body.append('- ' + commit.sha + ' - ' + get_truncated_commit_message(commit) + ' (@' + commit.author.login + ')')
body.append('')
body.append('Please review the following:')
body.append(' - [ ] The CHANGELOG displays the correct version and date.')
body.append(' - [ ] The CHANGELOG includes all relevant, user-facing changes since the last release.')
body.append(' - [ ] There are no unexpected commits being merged into the ' + LATEST_RELEASE_BRANCH + ' branch.')
body.append(' - [ ] The docs team is aware of any documentation changes that need to be released.')
body.append(' - [ ] The mergeback PR is merged back into ' + MAIN_BRANCH + ' after this PR is merged.')
title = 'Merge ' + MAIN_BRANCH + ' into ' + LATEST_RELEASE_BRANCH
# Create the pull request
pr = repo.create_pull(title=title, body='\n'.join(body), head=branch_name, base=LATEST_RELEASE_BRANCH)
print('Created PR #' + str(pr.number))
# Assign the conductor
pr.add_to_assignees(conductor)
print('Assigned PR to ' + conductor)
# Gets the person who should be in charge of the mergeback PR
def get_conductor(repo, pull_requests, other_commits):
# If there are any PRs then use whoever merged the last one
if len(pull_requests) > 0:
return get_merger_of_pr(repo, pull_requests[-1])
# Otherwise take the author of the latest commit
return other_commits[-1].author.login
# Gets a list of the SHAs of all commits that have happened on main
# since the release branched off.
# This will not include any commits that exist on the release branch
# that aren't on main.
def get_commit_difference(repo):
commits = run_git('log', '--pretty=format:%H', ORIGIN + '/' + LATEST_RELEASE_BRANCH + '..' + ORIGIN + '/' + MAIN_BRANCH).strip().split('\n')
# Convert to full-fledged commit objects
commits = [repo.get_commit(c) for c in commits]
# Filter out merge commits for PRs
return list(filter(lambda c: not is_pr_merge_commit(c), commits))
# Is the given commit the automatic merge commit from when merging a PR
def is_pr_merge_commit(commit):
return commit.committer is not None and commit.committer.login == 'web-flow' and len(commit.parents) > 1
# Gets a copy of the commit message that should display nicely
def get_truncated_commit_message(commit):
message = commit.commit.message.split('\n')[0]
if len(message) > 60:
return message[:57] + '...'
else:
return message
# Converts a commit into the PR that introduced it to the main branch.
# Returns the PR object, or None if no PR could be found.
def get_pr_for_commit(repo, commit):
prs = commit.get_pulls()
if prs.totalCount > 0:
# In the case that there are multiple PRs, return the earliest one
prs = list(prs)
sorted_prs = sorted(prs, key=lambda pr: int(pr.number))
return sorted_prs[0]
else:
return None
# Get the person who merged the pull request.
# For most cases this will be the same as the author, but for PRs opened
# by external contributors getting the merger will get us the GitHub
# employee who reviewed and merged the PR.
def get_merger_of_pr(repo, pr):
return repo.get_commit(pr.merge_commit_sha).author.login
def get_current_version():
with open('package.json', 'r') as f:
return json.load(f)['version']
def get_today_string():
today = datetime.datetime.today()
return '{:%d %b %Y}'.format(today)
def update_changelog(version):
if (os.path.exists('CHANGELOG.md')):
content = ''
with open('CHANGELOG.md', 'r') as f:
content = f.read()
else:
content = EMPTY_CHANGELOG
newContent = content.replace('[UNRELEASED]', version + ' - ' + get_today_string(), 1)
with open('CHANGELOG.md', 'w') as f:
f.write(newContent)
def main():
if len(sys.argv) != 3:
raise Exception('Usage: update-release.branch.py <github token> <repository nwo>')
github_token = sys.argv[1]
repository_nwo = sys.argv[2]
repo = Github(github_token).get_repo(repository_nwo)
version = get_current_version()
# Print what we intend to go
print('Considering difference between ' + MAIN_BRANCH + ' and ' + LATEST_RELEASE_BRANCH)
short_main_sha = run_git('rev-parse', '--short', ORIGIN + '/' + MAIN_BRANCH).strip()
print('Current head of ' + MAIN_BRANCH + ' is ' + short_main_sha)
# See if there are any commits to merge in
commits = get_commit_difference(repo)
if len(commits) == 0:
print('No commits to merge from ' + MAIN_BRANCH + ' to ' + LATEST_RELEASE_BRANCH)
return
# The branch name is based off of the name of branch being merged into
# and the SHA of the branch being merged from. Thus if the branch already
# exists we can assume we don't need to recreate it.
new_branch_name = 'update-v' + version + '-' + short_main_sha
print('Branch name is ' + new_branch_name)
# Check if the branch already exists. If so we can abort as this script
# has already run on this combination of branches.
if branch_exists_on_remote(new_branch_name):
print('Branch ' + new_branch_name + ' already exists. Nothing to do.')
return
# Create the new branch and push it to the remote
print('Creating branch ' + new_branch_name)
run_git('checkout', '-b', new_branch_name, ORIGIN + '/' + MAIN_BRANCH)
print('Updating changelog')
update_changelog(version)
# Create a commit that updates the CHANGELOG
run_git('add', 'CHANGELOG.md')
run_git('commit', '-m', version)
run_git('push', ORIGIN, new_branch_name)
# Open a PR to update the branch
open_pr(repo, commits, short_main_sha, new_branch_name)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,22 @@
name: Check Expected Release Files
on:
pull_request:
paths:
- .github/workflows/check-expected-release-files.yml
- src/defaults.json
jobs:
check-expected-release-files:
runs-on: ubuntu-latest
steps:
- name: Checkout CodeQL Action
uses: actions/checkout@v2
- name: Check Expected Release Files
run: |
bundle_version="$(cat "./src/defaults.json" | jq -r ".bundleVersion")"
set -x
for expected_file in "codeql-bundle.tar.gz" "codeql-bundle-linux64.tar.gz" "codeql-bundle-osx64.tar.gz" "codeql-bundle-win64.tar.gz" "codeql-runner-linux" "codeql-runner-macos" "codeql-runner-win.exe"; do
curl --location --fail --head --request GET "https://github.com/github/codeql-action/releases/download/$bundle_version/$expected_file" > /dev/null
done

View File

@@ -1,18 +1,83 @@
name: "CodeQL action"
on: [push]
on:
push:
branches: [main, v1]
pull_request:
branches: [main, v1]
jobs:
# Identify the CodeQL tool versions to use in the analysis job.
check-codeql-versions:
runs-on: ubuntu-latest
outputs:
versions: ${{ steps.compare.outputs.versions }}
permissions:
actions: read
contents: read
security-events: write
steps:
- uses: actions/checkout@v2
- name: Init with default CodeQL bundle from the VM image
id: init-default
uses: ./init
with:
languages: javascript
- name: Remove empty database
# allows us to run init a second time
run: |
rm -rf "$RUNNER_TEMP/codeql_databases"
- name: Init with latest CodeQL bundle
id: init-latest
uses: ./init
with:
tools: latest
languages: javascript
- name: Compare default and latest CodeQL bundle versions
id: compare
env:
CODEQL_DEFAULT: ${{ steps.init-default.outputs.codeql-path }}
CODEQL_LATEST: ${{ steps.init-latest.outputs.codeql-path }}
run: |
CODEQL_VERSION_DEFAULT="$("$CODEQL_DEFAULT" version --format terse)"
CODEQL_VERSION_LATEST="$("$CODEQL_LATEST" version --format terse)"
echo "Default CodeQL bundle version is $CODEQL_VERSION_DEFAULT"
echo "Latest CodeQL bundle version is $CODEQL_VERSION_LATEST"
if [[ "$CODEQL_VERSION_DEFAULT" == "$CODEQL_VERSION_LATEST" ]]; then
# Just use `tools: null` to avoid duplication in the analysis job.
VERSIONS_JSON='[null]'
else
# Use both `tools: null` and `tools: latest` in the analysis job.
VERSIONS_JSON='[null, "latest"]'
fi
# Output a JSON-encoded list with the distinct versions to test against.
echo "Suggested matrix config for analysis job: $VERSIONS_JSON"
echo "::set-output name=versions::${VERSIONS_JSON}"
build:
needs: [check-codeql-versions]
strategy:
matrix:
os: [ubuntu-latest,windows-latest,macos-latest]
tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }}
runs-on: ${{ matrix.os }}
permissions:
actions: read
contents: read
security-events: write
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
- uses: ./init
id: init
with:
languages: javascript
config-file: ./.github/codeql/codeql-config.yml
tools: ${{ matrix.tools }}
# confirm steps.init.outputs.codeql-path points to the codeql binary
- name: Print CodeQL Version
run: ${{steps.init.outputs.codeql-path}} version --format=json
- uses: ./analyze

View File

@@ -1,120 +0,0 @@
name: "Integration Testing"
on: [push]
jobs:
multi-language-repo_test-autodetect-languages:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
shopt -s dotglob
mv * ../action/
mv ../action/tests/multi-language-repo/* .
- uses: ./../action/init
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
env:
TEST_MODE: true
multi-language-repo_test-custom-queries:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
shopt -s dotglob
mv * ../action/
mv ../action/tests/multi-language-repo/* .
- uses: ./../action/init
with:
languages: cpp,csharp,java,javascript,python
config-file: ./.github/codeql/custom-queries.yml
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
env:
TEST_MODE: true
# Currently is not possible to analyze Go in conjunction with other languages in macos
multi-language-repo_test-go-custom-queries:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/setup-go@v2
if: ${{ matrix.os == 'macos-latest' }}
with:
go-version: '^1.13.1'
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
shopt -s dotglob
mv * ../action/
mv ../action/tests/multi-language-repo/* .
- uses: ./../action/init
with:
languages: go
config-file: ./.github/codeql/custom-queries.yml
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
env:
TEST_MODE: true
multi-language-repo_rubocop:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
shopt -s dotglob
mv * ../action/
mv ../action/tests/multi-language-repo/* .
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 2.6
- name: Install Code Scanning integration
run: bundle add code-scanning-rubocop --version 0.2.0 --skip-install
- name: Install dependencies
run: bundle install
- name: Rubocop run
run: |
bash -c "
bundle exec rubocop --require code_scanning --format CodeScanning::SarifFormatter -o rubocop.sarif
[[ $? -ne 2 ]]
"
- uses: ./../action/upload-sarif
with:
sarif_file: rubocop.sarif
env:
TEST_MODE: true

View File

@@ -0,0 +1,123 @@
# This workflow runs after a release of the action.
# It merges any changes from the release back into the
# main branch. Typically, this is just a single commit
# that updates the changelog.
name: Tag release and merge back
on:
workflow_dispatch:
inputs:
baseBranch:
description: 'The base branch to merge into'
default: main
required: false
push:
branches:
- v1
jobs:
merge-back:
runs-on: ubuntu-latest
if: github.repository == 'github/codeql-action'
env:
BASE_BRANCH: "${{ github.event.inputs.baseBranch || 'main' }}"
HEAD_BRANCH: "${{ github.head_ref || github.ref }}"
steps:
- name: Dump GitHub Event context
env:
GITHUB_EVENT_CONTEXT: "${{ toJson(github.event) }}"
run: echo "$GITHUB_EVENT_CONTEXT"
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- name: Update git config
run: |
git config --global user.email "github-actions@github.com"
git config --global user.name "github-actions[bot]"
- name: Get version and new branch
id: getVersion
run: |
VERSION="v$(jq '.version' -r 'package.json')"
SHORT_SHA="${GITHUB_SHA:0:8}"
echo "::set-output name=version::$VERSION"
NEW_BRANCH="mergeback/${VERSION}-to-${BASE_BRANCH}-${SHORT_SHA}"
echo "::set-output name=newBranch::$NEW_BRANCH"
- name: Dump branches
env:
NEW_BRANCH: "${{ steps.getVersion.outputs.newBranch }}"
run: |
echo "BASE_BRANCH $BASE_BRANCH"
echo "HEAD_BRANCH $HEAD_BRANCH"
echo "NEW_BRANCH $NEW_BRANCH"
- name: Create mergeback branch
env:
NEW_BRANCH: "${{ steps.getVersion.outputs.newBranch }}"
run: |
git checkout -b "$NEW_BRANCH"
- name: Check for tag
id: check
env:
VERSION: "${{ steps.getVersion.outputs.version }}"
run: |
set +e # don't fail on an errored command
git ls-remote --tags origin | grep "$VERSION"
EXISTS="$?"
if [ "$EXISTS" -eq 0 ]; then
echo "Tag $TAG exists. Not going to re-release."
echo "::set-output name=exists::true"
else
echo "Tag $TAG does not exist yet."
fi
# we didn't tag the release during the update-release-branch workflow because the
# commit that actually makes it to the release branch is a merge commit,
# and not yet known during the first workflow. We tag now because we know the correct commit.
- name: Tag release
if: steps.check.outputs.exists != 'true'
env:
VERSION: ${{ steps.getVersion.outputs.version }}
run: |
git tag -a "$VERSION" -m "$VERSION"
git fetch --unshallow # unshallow the repo in order to allow pushes
git push origin --follow-tags "$VERSION"
- name: Create mergeback branch
if: steps.check.outputs.exists != 'true'
env:
VERSION: "${{ steps.getVersion.outputs.version }}"
NEW_BRANCH: "${{ steps.getVersion.outputs.newBranch }}"
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
run: |
set -exu
PR_TITLE="Mergeback $VERSION $HEAD_BRANCH into $BASE_BRANCH"
PR_BODY="Updates version and changelog."
# Update the changelog
perl -i -pe 's/^/## \[UNRELEASED\]\n\nNo user facing changes.\n\n/ if($.==3)' CHANGELOG.md
git add .
git commit -m "Update changelog and version after $VERSION"
npm version patch
# when running this workflow on a PR, this is just a test.
# so put into draft mode.
if [ "$GITHUB_EVENT_NAME" == "pull_request" ]; then
DRAFT="--draft"
else
DRAFT=""
fi
git push origin "$NEW_BRANCH"
gh pr create \
--head "$NEW_BRANCH" \
--base "$BASE_BRANCH" \
--title "$PR_TITLE" \
--body "$PR_BODY" \
${DRAFT:+"$DRAFT"} # no quotes around $DRAFT. gh will error out if there is an empty ""

View File

@@ -1,71 +1,918 @@
name: "PR checks"
on: [push, pull_request]
env:
GO111MODULE: auto
on:
push:
branches: [main, v1]
pull_request:
workflow_dispatch:
jobs:
tslint:
lint-js:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: tslint
- uses: actions/checkout@v2
- name: Run Lint
run: npm run-script lint
check-js:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
- name: Check generated JavaScript
run: |
# Sanity check that repo is clean to start with
if [ ! -z "$(git status --porcelain)" ]; then
# If we get a fail here then this workflow needs attention...
>&2 echo "Failed: Repo should be clean before testing!"
exit 1
fi
# Generate the JavaScript files
npm run-script build
# Check that repo is still clean
if [ ! -z "$(git status --porcelain)" ]; then
# If we get a fail here then the PR needs attention
>&2 echo "Failed: JavaScript files are not up to date. Run 'npm run-script build' to update"
git status
exit 1
fi
echo "Success: JavaScript files are up to date"
run: .github/workflows/script/check-js.sh
check-node-modules:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
- name: Check node modules up to date
run: |
# Sanity check that repo is clean to start with
if [ ! -z "$(git status --porcelain)" ]; then
# If we get a fail here then this workflow needs attention...
>&2 echo "Failed: Repo should be clean before testing!"
exit 1
fi
# Reinstall modules and then clean to remove absolute paths
# Use 'npm ci' instead of 'npm install' as this is intended to be reproducible
npm ci
npm run removeNPMAbsolutePaths
# Check that repo is still clean
if [ ! -z "$(git status --porcelain)" ]; then
# If we get a fail here then the PR needs attention
>&2 echo "Failed: node_modules are not up to date. Run 'npm ci' and 'npm run removeNPMAbsolutePaths' to update"
git status
exit 1
fi
echo "Success: node_modules are up to date"
run: .github/workflows/script/check-node-modules.sh
npm-test:
needs: [check-js, check-node-modules]
strategy:
matrix:
os: [ubuntu-latest,macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: npm run-script test
run: npm run-script test
multi-language-repo_test-autodetect-languages:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: npm run-script test
run: npm run-script test
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
db-location: "${{ runner.temp }}/customDbLocation"
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
id: analysis
env:
TEST_MODE: true
- run: |
CPP_DB=${{ fromJson(steps.analysis.outputs.db-locations).cpp }}
if [[ ! -d $CPP_DB ]] || [[ ! $CPP_DB == ${{ runner.temp }}/customDbLocation/* ]]; then
echo "Did not create a database for CPP, or created it in the wrong location."
exit 1
fi
CSHARP_DB=${{ fromJson(steps.analysis.outputs.db-locations).csharp }}
if [[ ! -d $CSHARP_DB ]] || [[ ! $CSHARP_DB == ${{ runner.temp }}/customDbLocation/* ]]; then
echo "Did not create a database for C Sharp, or created it in the wrong location."
exit 1
fi
GO_DB=${{ fromJson(steps.analysis.outputs.db-locations).go }}
if [[ ! -d $GO_DB ]] || [[ ! $GO_DB == ${{ runner.temp }}/customDbLocation/* ]]; then
echo "Did not create a database for Go, or created it in the wrong location."
exit 1
fi
JAVA_DB=${{ fromJson(steps.analysis.outputs.db-locations).java }}
if [[ ! -d $JAVA_DB ]] || [[ ! $JAVA_DB == ${{ runner.temp }}/customDbLocation/* ]]; then
echo "Did not create a database for Java, or created it in the wrong location."
exit 1
fi
JAVASCRIPT_DB=${{ fromJson(steps.analysis.outputs.db-locations).javascript }}
if [[ ! -d $JAVASCRIPT_DB ]] || [[ ! $JAVASCRIPT_DB == ${{ runner.temp }}/customDbLocation/* ]]; then
echo "Did not create a database for Javascript, or created it in the wrong location."
exit 1
fi
PYTHON_DB=${{ fromJson(steps.analysis.outputs.db-locations).python }}
if [[ ! -d $PYTHON_DB ]] || [[ ! $PYTHON_DB == ${{ runner.temp }}/customDbLocation/* ]]; then
echo "Did not create a database for Python, or created it in the wrong location."
exit 1
fi
# Packaging test that runs against a javascript database
# Specifying packs in the config file.
test-packaging-javascript-config:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
config-file: ".github/codeql/codeql-config-packaging.yml"
languages: javascript
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
with:
output: "${{ runner.temp }}/results"
env:
TEST_MODE: true
- name: Assert Results
run: |
cd "$RUNNER_TEMP/results"
# We should have 3 hits from these rules
EXPECTED_RULES="javascript/example/empty-or-one-block javascript/example/empty-or-one-block javascript/example/two-block"
# use tr to replace newlines with spaces and xargs to trim leading and trailing whitespace
RULES="$(cat javascript.sarif | jq -r '.runs[0].results[].ruleId' | sort | tr "\n" " " | xargs)"
echo "Found matching rules '$RULES'"
if [ "$RULES" != "$EXPECTED_RULES" ]; then
echo "Did not match expected rules '$EXPECTED_RULES'."
exit 1
fi
# Packaging test that runs against a javascript database
# Specifying packs as an input.
test-packaging-javascript-inputs:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
config-file: ".github/codeql/codeql-config-packaging2.yml"
languages: javascript
packs: dsp-testing/codeql-pack1@0.0.4, dsp-testing/codeql-pack2
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
with:
output: "${{ runner.temp }}/results"
env:
TEST_MODE: true
- name: Assert Results
run: |
cd "$RUNNER_TEMP/results"
# We should have 3 hits from these rules
EXPECTED_RULES="javascript/example/empty-or-one-block javascript/example/empty-or-one-block javascript/example/two-block"
# use tr to replace newlines with spaces and xargs to trim leading and trailing whitespace
RULES="$(cat javascript.sarif | jq -r '.runs[0].results[].ruleId' | sort | tr "\n" " " | xargs)"
echo "Found matching rules '$RULES'"
if [ "$RULES" != "$EXPECTED_RULES" ]; then
echo "Did not match expected rules '$EXPECTED_RULES'."
exit 1
fi
# Packaging test that runs against a javascript database
# Specifying packs in the config file and inputs.
test-packaging-javascript-config-and-inputs:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
config-file: ".github/codeql/codeql-config-packaging3.yml"
packs: +dsp-testing/codeql-pack1@0.0.4
languages: javascript
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
with:
output: "${{ runner.temp }}/results"
env:
TEST_MODE: true
- name: Assert Results
run: |
cd "$RUNNER_TEMP/results"
# We should have 3 hits from these rules
EXPECTED_RULES="javascript/example/empty-or-one-block javascript/example/empty-or-one-block javascript/example/two-block"
# use tr to replace newlines with spaces and xargs to trim leading and trailing whitespace
RULES="$(cat javascript.sarif | jq -r '.runs[0].results[].ruleId' | sort | tr "\n" " " | xargs)"
echo "Found matching rules '$RULES'"
if [ "$RULES" != "$EXPECTED_RULES" ]; then
echo "Did not match expected rules '$EXPECTED_RULES'."
exit 1
fi
# Tests a split workflow where database construction and query execution happen in different steps
test-split-workflow:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
config-file: ".github/codeql/codeql-config-packaging3.yml"
packs: +dsp-testing/codeql-pack1@0.0.4
languages: javascript
tools: latest
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
with:
skip-queries: true
output: "${{ runner.temp }}/results"
env:
TEST_MODE: true
- name: Assert No Results
run: |
if [ "$(ls -A $RUNNER_TEMP/results)" ]; then
echo "Expected results directory to be empty after skipping query execution!"
exit 1
fi
- uses: ./../action/analyze
with:
output: "${{ runner.temp }}/results"
env:
TEST_MODE: true
- name: Assert Results
run: |
cd "$RUNNER_TEMP/results"
# We should have 3 hits from these rules
EXPECTED_RULES="javascript/example/empty-or-one-block javascript/example/empty-or-one-block javascript/example/two-block"
# use tr to replace newlines with spaces and xargs to trim leading and trailing whitespace
RULES="$(cat javascript.sarif | jq -r '.runs[0].results[].ruleId' | sort | tr "\n" " " | xargs)"
echo "Found matching rules '$RULES'"
if [ "$RULES" != "$EXPECTED_RULES" ]; then
echo "Did not match expected rules '$EXPECTED_RULES'."
exit 1
fi
# Identify the CodeQL tool versions to integration test against.
check-codeql-versions:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
outputs:
versions: ${{ steps.compare.outputs.versions }}
nightly-url: ${{ steps.get-url.outputs.nightly-url }}
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- name: Init with default CodeQL bundle from the VM image
id: init-default
uses: ./../action/init
with:
languages: javascript
- name: Remove empty database
# allows us to run init a second time
run: |
rm -rf "$RUNNER_TEMP/codeql_databases"
- name: Init with latest CodeQL bundle
id: init-latest
uses: ./../action/init
with:
tools: latest
languages: javascript
- name: Remove empty database
# allows us to run init a third time
run: |
rm -rf "$RUNNER_TEMP/codeql_databases"
- name: Get nightly release URL
id: get-url
env:
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
shell: bash
# This workflow step gets an unstable testing version of the CodeQL CLI. It should not be used outside of these tests.
run: |
export LATEST=`gh release list --repo dsp-testing/codeql-cli-nightlies -L 1 | cut -f 3`
echo "::set-output name=nightly-url::https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/$LATEST/codeql-bundle.tar.gz"
- name: Init with a CodeQL bundle from a nightly release
id: init-nightly
uses: ./../action/init
with:
tools: ${{ steps.get-url.outputs.nightly-url }}
languages: javascript
- name: Compare CodeQL bundle versions
id: compare
env:
CODEQL_DEFAULT: ${{ steps.init-default.outputs.codeql-path }}
CODEQL_LATEST: ${{ steps.init-latest.outputs.codeql-path }}
CODEQL_NIGHTLY: ${{ steps.init-nightly.outputs.codeql-path }}
NIGHTLY_URL: ${{ steps.get-url.outputs.nightly-url }}
run: |
CODEQL_VERSION_DEFAULT="$("$CODEQL_DEFAULT" version --format terse)"
CODEQL_VERSION_LATEST="$("$CODEQL_LATEST" version --format terse)"
CODEQL_VERSION_NIGHTLY="$("$CODEQL_NIGHTLY" version --format terse)"
echo "Default CodeQL bundle version is $CODEQL_VERSION_DEFAULT"
echo "Latest CodeQL bundle version is $CODEQL_VERSION_LATEST"
echo "Nightly CodeQL bundle version is $CODEQL_VERSION_NIGHTLY"
if [[ "$CODEQL_VERSION_DEFAULT" == "$CODEQL_VERSION_LATEST" ]]; then
# Skip `tools: latest` since it would be the same as `tools: null`
VERSIONS_JSON="[null, \"$NIGHTLY_URL\"]"
else
# Run integration tests with all three bundles.
VERSIONS_JSON="[null, \"$NIGHTLY_URL\", \"latest\"]"
fi
# Output a JSON-encoded list with the distinct versions to test against.
echo "Suggested matrix config for integration tests: $VERSIONS_JSON"
echo "::set-output name=versions::${VERSIONS_JSON}"
multi-language-repo_test-custom-queries-and-remote-config:
needs: [check-js, check-node-modules, check-codeql-versions]
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }}
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
tools: ${{ matrix.tools }}
languages: cpp,csharp,java,javascript,python
config-file: github/codeql-action/tests/multi-language-repo/.github/codeql/custom-queries.yml@${{ github.sha }}
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
env:
TEST_MODE: true
# Currently is not possible to analyze Go in conjunction with other languages in macos
multi-language-repo_test-go-custom-queries:
needs: [check-js, check-node-modules, check-codeql-versions]
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }}
runs-on: ${{ matrix.os }}
steps:
- uses: actions/setup-go@v2
if: ${{ matrix.os == 'macos-latest' }}
with:
go-version: '^1.13.1'
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
languages: go
config-file: ./.github/codeql/custom-queries.yml
tools: ${{ matrix.tools }}
- name: Build code
shell: bash
run: ./build.sh
- uses: ./../action/analyze
env:
TEST_MODE: true
go-custom-tracing:
needs: [check-js, check-node-modules, check-codeql-versions]
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }}
runs-on: ${{ matrix.os }}
env:
CODEQL_EXTRACTOR_GO_BUILD_TRACING: "on"
steps:
- uses: actions/setup-go@v2
if: ${{ matrix.os == 'macos-latest' }}
with:
go-version: '^1.13.1'
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
languages: go
tools: ${{ matrix.tools }}
- name: Build code
shell: bash
run: go build main.go
- uses: ./../action/analyze
env:
TEST_MODE: true
go-custom-tracing-autobuild:
needs: [check-js, check-node-modules, check-codeql-versions]
strategy:
fail-fast: false
matrix:
tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }}
# No need to test Go autobuild on multiple OSes since
# we're testing Go custom tracing with a manual build on all OSes.
runs-on: ubuntu-latest
env:
CODEQL_EXTRACTOR_GO_BUILD_TRACING: "on"
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
languages: go
tools: ${{ matrix.tools }}
- uses: ./../action/autobuild
- uses: ./../action/analyze
env:
TEST_MODE: true
- run: |
cd "$RUNNER_TEMP/codeql_databases"
if [[ ! -d go ]]; then
echo "Did not find a Go database"
exit 1
fi
multi-language-repo_rubocop:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 2.6
- name: Install Code Scanning integration
run: bundle add code-scanning-rubocop --version 0.3.0 --skip-install
- name: Install dependencies
run: bundle install
- name: Rubocop run
run: |
bash -c "
bundle exec rubocop --require code_scanning --format CodeScanning::SarifFormatter -o rubocop.sarif
[[ $? -ne 2 ]]
"
- uses: ./../action/upload-sarif
with:
sarif_file: rubocop.sarif
env:
TEST_MODE: true
test-proxy:
needs: [check-js, check-node-modules, check-codeql-versions]
strategy:
fail-fast: false
matrix:
tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }}
runs-on: ubuntu-latest
container:
image: ubuntu:18.04
options: --dns 127.0.0.1
services:
squid-proxy:
image: datadog/squid:latest
ports:
- 3128:3128
env:
https_proxy: http://squid-proxy:3128
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
languages: javascript
tools: ${{ matrix.tools }}
- uses: ./../action/analyze
env:
TEST_MODE: true
runner-analyze-javascript-ubuntu:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build runner
run: |
cd runner
npm install
npm run build-runner
- name: Run init
run: |
# Pass --config-file here, but not for other jobs in this workflow.
# This means we're testing the config file parsing in the runner
# but not slowing down all jobs unnecessarily as it doesn't add much
# testing the parsing on different operating systems and languages.
runner/dist/codeql-runner-linux init --repository $GITHUB_REPOSITORY --languages javascript --config-file ./.github/codeql/codeql-config.yml --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Run analyze
run: |
runner/dist/codeql-runner-linux analyze --repository $GITHUB_REPOSITORY --commit $GITHUB_SHA --ref $GITHUB_REF --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-analyze-javascript-windows:
needs: [check-js, check-node-modules]
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Build runner
run: |
cd runner
npm install
npm run build-runner
- name: Run init
run: |
runner/dist/codeql-runner-win.exe init --repository $Env:GITHUB_REPOSITORY --languages javascript --github-url $Env:GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Run analyze
run: |
runner/dist/codeql-runner-win.exe analyze --repository $Env:GITHUB_REPOSITORY --commit $Env:GITHUB_SHA --ref $Env:GITHUB_REF --github-url $Env:GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-analyze-javascript-macos:
needs: [check-js, check-node-modules]
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- name: Build runner
run: |
cd runner
npm install
npm run build-runner
- name: Run init
run: |
runner/dist/codeql-runner-macos init --repository $GITHUB_REPOSITORY --languages javascript --config-file ./.github/codeql/codeql-config.yml --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Run analyze
run: |
runner/dist/codeql-runner-macos analyze --repository $GITHUB_REPOSITORY --commit $GITHUB_SHA --ref $GITHUB_REF --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-analyze-csharp-ubuntu:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- name: Build runner
run: |
cd ../action/runner
npm install
npm run build-runner
- name: Run init
run: |
../action/runner/dist/codeql-runner-linux init --repository $GITHUB_REPOSITORY --languages csharp --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Build code
run: |
. ./codeql-runner/codeql-env.sh
$CODEQL_RUNNER dotnet build
- name: Run analyze
run: |
../action/runner/dist/codeql-runner-linux analyze --repository $GITHUB_REPOSITORY --commit $GITHUB_SHA --ref $GITHUB_REF --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-analyze-csharp-windows:
needs: [check-js, check-node-modules]
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- name: Build runner
run: |
cd ../action/runner
npm install
npm run build-runner
- name: Run init
run: |
../action/runner/dist/codeql-runner-win.exe init --repository $Env:GITHUB_REPOSITORY --languages csharp --github-url $Env:GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Build code
shell: powershell
# Note we want to make sure that the .win32env file is read correctly, so we unset the CODEQL_EXTRACTOR_CSHARP_ROOT from the .sh file.
run: |
cat ./codeql-runner/codeql-env.sh | Invoke-Expression
$Env:CODEQL_EXTRACTOR_CSHARP_ROOT = ""
& $Env:CODEQL_RUNNER dotnet build
- name: Run analyze
run: |
../action/runner/dist/codeql-runner-win.exe analyze --repository $Env:GITHUB_REPOSITORY --commit $Env:GITHUB_SHA --ref $Env:GITHUB_REF --github-url $Env:GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-analyze-csharp-macos:
needs: [check-js, check-node-modules]
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- name: Build runner
run: |
cd ../action/runner
npm install
npm run build-runner
- name: Run init
run: |
../action/runner/dist/codeql-runner-macos init --repository $GITHUB_REPOSITORY --languages csharp --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Build code
shell: bash
run: |
. ./codeql-runner/codeql-env.sh
$CODEQL_RUNNER dotnet build
- name: Run analyze
run: |
../action/runner/dist/codeql-runner-macos analyze --repository $GITHUB_REPOSITORY --commit $GITHUB_SHA --ref $GITHUB_REF --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-analyze-csharp-autobuild-ubuntu:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- name: Build runner
run: |
cd ../action/runner
npm install
npm run build-runner
- name: Run init
run: |
../action/runner/dist/codeql-runner-linux init --repository $GITHUB_REPOSITORY --languages csharp --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Build code
run: |
../action/runner/dist/codeql-runner-linux autobuild
- name: Run analyze
run: |
../action/runner/dist/codeql-runner-linux analyze --repository $GITHUB_REPOSITORY --commit $GITHUB_SHA --ref $GITHUB_REF --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-analyze-csharp-autobuild-windows:
needs: [check-js, check-node-modules]
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- name: Build runner
run: |
cd ../action/runner
npm install
npm run build-runner
- name: Run init
run: |
../action/runner/dist/codeql-runner-win.exe init --repository $Env:GITHUB_REPOSITORY --languages csharp --github-url $Env:GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Build code
shell: powershell
run: |
../action/runner/dist/codeql-runner-win.exe autobuild
- name: Run analyze
run: |
../action/runner/dist/codeql-runner-win.exe analyze --repository $Env:GITHUB_REPOSITORY --commit $Env:GITHUB_SHA --ref $Env:GITHUB_REF --github-url $Env:GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-analyze-csharp-autobuild-macos:
needs: [check-js, check-node-modules]
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
shell: bash
run: |
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- name: Build runner
run: |
cd ../action/runner
npm install
npm run build-runner
- name: Run init
run: |
../action/runner/dist/codeql-runner-macos init --repository $GITHUB_REPOSITORY --languages csharp --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
- name: Build code
shell: bash
run: |
../action/runner/dist/codeql-runner-macos autobuild
- name: Run analyze
run: |
../action/runner/dist/codeql-runner-macos analyze --repository $GITHUB_REPOSITORY --commit $GITHUB_SHA --ref $GITHUB_REF --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
env:
TEST_MODE: true
runner-upload-sarif:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.base.repo.id == github.event.pull_request.head.repo.id }}
steps:
- uses: actions/checkout@v2
- name: Build runner
run: |
cd runner
npm install
npm run build-runner
- name: Upload with runner
run: |
# Deliberately don't use TEST_MODE here. This is specifically testing
# the compatibility with the API.
runner/dist/codeql-runner-linux upload --sarif-file src/testdata/empty-sarif.sarif --repository $GITHUB_REPOSITORY --commit $GITHUB_SHA --ref $GITHUB_REF --github-url $GITHUB_SERVER_URL --github-auth ${{ github.token }}
multi-language-repo_test-local-codeql:
needs: [check-js, check-node-modules, check-codeql-versions]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Move codeql-action
run: |
wget ${{ needs.check-codeql-versions.outputs.nightly-url }}
mkdir ../action
mv * .github ../action/
mv ../action/tests/multi-language-repo/{*,.github} .
mv ../action/.github/workflows .github
- uses: ./../action/init
with:
tools: ../action/codeql-bundle.tar.gz
- name: Build code
run: ./build.sh
- uses: ./../action/analyze
test-javascript-source-root:
needs: [check-js, check-node-modules]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: ./init
with:
languages: javascript
source-root: tests/multi-language-repo
- uses: ./analyze
with:
skip-queries: true
upload: false
- name: Assert database exists
run: |
cd "$RUNNER_TEMP/codeql_databases"
if [[ ! -d javascript ]]; then
echo "Did not find a JavaScript database"
exit 1
fi

150
.github/workflows/python-deps.yml vendored Normal file
View File

@@ -0,0 +1,150 @@
name: Test Python Package Installation on Linux and Mac
on:
push:
branches: [main, v1]
pull_request:
jobs:
test-setup-python-scripts:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
python_deps_type: [pipenv, poetry, requirements, setup_py]
python_version: [2, 3]
env:
PYTHON_DEPS_TYPE: ${{ matrix.python_deps_type }}
PYTHON_VERSION: ${{ matrix.python_version }}
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- name: Initialize CodeQL
uses: ./init
id: init
with:
tools: latest
languages: python
setup-python-dependencies: false
- name: Test Auto Package Installation
run: |
set -x
$GITHUB_WORKSPACE/python-setup/install_tools.sh
cd $GITHUB_WORKSPACE/python-setup/tests/${PYTHON_DEPS_TYPE}/requests-${PYTHON_VERSION}
case ${{ matrix.os }} in
ubuntu-latest*) basePath="/opt";;
macos-latest*) basePath="/Users/runner";;
esac
echo ${basePath}
$GITHUB_WORKSPACE/python-setup/auto_install_packages.py "$(dirname ${{steps.init.outputs.codeql-path}})"
- name: Setup for extractor
run: |
echo $CODEQL_PYTHON
# only run if $CODEQL_PYTHON is set
if [ ! -z $CODEQL_PYTHON ]; then
$GITHUB_WORKSPACE/python-setup/tests/from_python_exe.py $CODEQL_PYTHON;
fi
- name: Verify packages installed
run: |
$GITHUB_WORKSPACE/python-setup/tests/check_requests_123.sh ${PYTHON_VERSION}
# This one shouldn't fail, but also won't install packages
test-setup-python-scripts-non-standard-location:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- name: Initialize CodeQL
uses: ./init
id: init
with:
tools: latest
languages: python
setup-python-dependencies: false
- name: Test Auto Package Installation
run: |
set -x
$GITHUB_WORKSPACE/python-setup/install_tools.sh
cd $GITHUB_WORKSPACE/python-setup/tests/requirements/non-standard-location
case ${{ matrix.os }} in
ubuntu-latest*) basePath="/opt";;
macos-latest*) basePath="/Users/runner";;
esac
echo ${basePath}
$GITHUB_WORKSPACE/python-setup/auto_install_packages.py "$(dirname ${{steps.init.outputs.codeql-path}})"
- name: Setup for extractor
run: |
echo $CODEQL_PYTHON
# only run if $CODEQL_PYTHON is set
if [ ! -z $CODEQL_PYTHON ]; then
$GITHUB_WORKSPACE/python-setup/tests/from_python_exe.py $CODEQL_PYTHON;
fi
- name: Verify packages installed
run: |
test -z $LGTM_INDEX_IMPORT_PATH
test-setup-python-scripts-windows:
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
python_deps_type: [pipenv, poetry, requirements, setup_py]
python_version: [2, 3]
env:
PYTHON_DEPS_TYPE: ${{ matrix.python_deps_type }}
PYTHON_VERSION: ${{ matrix.python_version }}
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- name: Initialize CodeQL
uses: ./init
with:
tools: latest
languages: python
setup-python-dependencies: false
- name: Test Auto Package Installation
run: |
$cmd = $Env:GITHUB_WORKSPACE + "\\python-setup\\install_tools.ps1"
powershell -File $cmd
cd $Env:GITHUB_WORKSPACE\\python-setup/tests/$Env:PYTHON_DEPS_TYPE/requests-$Env:PYTHON_VERSION
$DefaultsPath = Join-Path (Join-Path $Env:GITHUB_WORKSPACE "src") "defaults.json"
$CodeQLBundleName = (Get-Content -Raw -Path $DefaultsPath | ConvertFrom-Json).bundleVersion
$CodeQLVersion = "0.0.0-" + $CodeQLBundleName.split("-")[-1]
py -3 $Env:GITHUB_WORKSPACE\\python-setup\\auto_install_packages.py C:\\hostedtoolcache\\windows\\CodeQL\\$CodeQLVersion\\x64\\codeql
- name: Setup for extractor
run: |
echo $Env:CODEQL_PYTHON
py -3 $Env:GITHUB_WORKSPACE\\python-setup\\tests\\from_python_exe.py $Env:CODEQL_PYTHON
- name: Verify packages installed
run: |
$cmd = $Env:GITHUB_WORKSPACE + "\\python-setup\\tests\\check_requests_123.ps1"
powershell -File $cmd $Env:PYTHON_VERSION

54
.github/workflows/release-runner.yml vendored Normal file
View File

@@ -0,0 +1,54 @@
name: Release runner
on:
workflow_dispatch:
inputs:
bundle-tag:
description: 'Tag of the bundle release (e.g., "codeql-bundle-20200826")'
required: false
jobs:
release-runner:
runs-on: ubuntu-latest
env:
RELEASE_TAG: "${{ github.event.inputs.bundle-tag }}"
strategy:
matrix:
extension: ["linux", "macos", "win.exe"]
steps:
- uses: actions/checkout@v2
- name: Build runner
run: |
cd runner
npm install
npm run build-runner
- uses: actions/upload-artifact@v2
with:
name: codeql-runner-${{matrix.extension}}
path: runner/dist/codeql-runner-${{matrix.extension}}
- name: Resolve Upload URL for the release
if: ${{ github.event.inputs.bundle-tag != null }}
id: save_url
run: |
UPLOAD_URL=$(curl -sS \
"https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}" \
-H "Accept: application/json" \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" | jq .upload_url | sed s/\"//g)
echo ${UPLOAD_URL}
echo "::set-output name=upload_url::${UPLOAD_URL}"
- name: Upload Platform Package
if: ${{ github.event.inputs.bundle-tag != null }}
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.save_url.outputs.upload_url }}
asset_path: runner/dist/codeql-runner-${{matrix.extension}}
asset_name: codeql-runner-${{matrix.extension}}
asset_content_type: application/octet-stream

21
.github/workflows/script/check-js.sh vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/bash
set -eu
# Sanity check that repo is clean to start with
if [ ! -z "$(git status --porcelain)" ]; then
# If we get a fail here then this workflow needs attention...
>&2 echo "Failed: Repo should be clean before testing!"
exit 1
fi
# Wipe the lib directory incase there are extra unnecessary files in there
rm -rf lib
# Generate the JavaScript files
npm run-script build
# Check that repo is still clean
if [ ! -z "$(git status --porcelain)" ]; then
# If we get a fail here then the PR needs attention
>&2 echo "Failed: JavaScript files are not up to date. Run 'npm run-script build' to update"
git status
exit 1
fi
echo "Success: JavaScript files are up to date"

View File

@@ -0,0 +1,21 @@
#!/bin/bash
set -eu
# Sanity check that repo is clean to start with
if [ ! -z "$(git status --porcelain)" ]; then
# If we get a fail here then this workflow needs attention...
>&2 echo "Failed: Repo should be clean before testing!"
exit 1
fi
# Reinstall modules and then clean to remove absolute paths
# Use 'npm ci' instead of 'npm install' as this is intended to be reproducible
npm ci
npm run removeNPMAbsolutePaths
# Check that repo is still clean
if [ ! -z "$(git status --porcelain)" ]; then
# If we get a fail here then the PR needs attention
>&2 echo "Failed: node_modules are not up to date. Run 'npm ci && npm run removeNPMAbsolutePaths' on a macOS machine to update. Note it is important this command is run on macOS and not any other operating system as there is one dependency (fsevents) that is needed for macOS and may not be installed if the command is run on a Windows or Linux machine."
git status
exit 1
fi
echo "Success: node_modules are up to date"

73
.github/workflows/split.yml vendored Normal file
View File

@@ -0,0 +1,73 @@
#
# Split the CodeQL Bundle into platform bundles
#
# Instructions:
# 1. Upload the new codeql-bundle (codeql-bundle.tar.gz) as an asset of the
# release (codeql-bundle-20200826)
# 2. Take note of the CLI Release used by the bundle (e.g., v2.2.5)
# 3. Manually launch this workflow file (via the Actions UI) specifying
# - The CLI Release (e.g., v2.2.5)
# - The release tag (e.g., codeql-bundle-20200826)
# 4. If everything succeeds you should see 3 new assets.
#
name: Split Bundle
on:
workflow_dispatch:
inputs:
cli-release:
description: 'CodeQL CLI Release (e.g., "v2.2.5")'
required: true
bundle-tag:
description: 'Tag of the bundle release (e.g., "codeql-bundle-20200826")'
required: true
jobs:
build:
runs-on: ubuntu-latest
env:
CLI_RELEASE: "${{ github.event.inputs.cli-release }}"
RELEASE_TAG: "${{ github.event.inputs.bundle-tag }}"
strategy:
fail-fast: false
matrix:
platform: ["linux64", "osx64", "win64"]
steps:
- name: Resolve Upload URL for the release
id: save_url
run: |
UPLOAD_URL=$(curl -sS \
"https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}" \
-H "Accept: application/json" \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" | jq .upload_url | sed s/\"//g)
echo ${UPLOAD_URL}
echo "::set-output name=upload_url::${UPLOAD_URL}"
- name: Download CodeQL CLI and Bundle
run: |
wget --no-verbose "https://github.com/${GITHUB_REPOSITORY}/releases/download/${RELEASE_TAG}/codeql-bundle.tar.gz"
wget --no-verbose "https://github.com/github/codeql-cli-binaries/releases/download/${CLI_RELEASE}/codeql-${{matrix.platform}}.zip"
- name: Create Platform Package
# Replace the codeql-binaries with the platform specific ones
run: |
gunzip codeql-bundle.tar.gz
tar -f codeql-bundle.tar --delete codeql
unzip -q codeql-${{matrix.platform}}.zip
tar -f codeql-bundle.tar --append codeql
gzip codeql-bundle.tar
mv codeql-bundle.tar.gz codeql-bundle-${{matrix.platform}}.tar.gz
du -sh codeql-bundle-${{matrix.platform}}.tar.gz
- name: Upload Platform Package
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.save_url.outputs.upload_url }}
asset_path: ./codeql-bundle-${{matrix.platform}}.tar.gz
asset_name: codeql-bundle-${{matrix.platform}}.tar.gz
asset_content_type: application/tar+gzip

View File

@@ -0,0 +1,38 @@
name: Update release branch
on:
schedule:
- cron: 0 9 * * 1
repository_dispatch:
# Example of how to trigger this:
# curl -H "Authorization: Bearer <token>" -X POST https://api.github.com/repos/github/codeql-action/dispatches -d '{"event_type":"update-release-branch"}'
# Replace <token> with a personal access token from this page: https://github.com/settings/tokens
types: [update-release-branch]
workflow_dispatch:
jobs:
update:
runs-on: ubuntu-latest
if: ${{ github.repository == 'github/codeql-action' }}
steps:
- uses: actions/checkout@v2
with:
# Need full history so we calculate diffs
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install PyGithub==1.51 requests
- name: Update git config
run: |
git config --global user.email "github-actions@github.com"
git config --global user.name "github-actions[bot]"
- name: Update release branch
run: python .github/update-release-branch.py ${{ secrets.GITHUB_TOKEN }} ${{ github.repository }}

View File

@@ -0,0 +1,44 @@
name: Update Supported Enterprise Server Versions
on:
schedule:
- cron: "0 0 * * *"
jobs:
update-supported-enterprise-server-versions:
runs-on: ubuntu-latest
if: ${{ github.repository == 'github/codeql-action' }}
steps:
- name: Setup Python
uses: actions/setup-python@v2
with:
python-version: "3.7"
- name: Checkout CodeQL Action
uses: actions/checkout@v2
- name: Checkout Enterprise Releases
uses: actions/checkout@v2
with:
repository: github/enterprise-releases
ssh-key: ${{ secrets.ENTERPRISE_RELEASES_SSH_KEY }}
path: ${{ github.workspace }}/enterprise-releases/
- name: Update Supported Enterprise Server Versions
run: |
cd ./.github/workflows/update-supported-enterprise-server-versions/
python3 -m pip install pipenv
pipenv install
pipenv run ./update.py
rm --recursive "$ENTERPRISE_RELEASES_PATH"
npm run build
env:
ENTERPRISE_RELEASES_PATH: ${{ github.workspace }}/enterprise-releases/
- name: Commit Changes
uses: peter-evans/create-pull-request@c7f493a8000b8aeb17a1332e326ba76b57cb83eb # v3.4.1
with:
commit-message: Update supported GitHub Enterprise Server versions.
title: Update supported GitHub Enterprise Server versions.
body: ""
author: GitHub <noreply@github.com>
branch: update-supported-enterprise-server-versions
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -0,0 +1,9 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
semver = "*"

View File

@@ -0,0 +1,27 @@
{
"_meta": {
"hash": {
"sha256": "e3ba923dcb4888e05de5448c18a732bf40197e80fabfa051a61c01b22c504879"
},
"pipfile-spec": 6,
"requires": {},
"sources": [
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": true
}
]
},
"default": {
"semver": {
"hashes": [
"sha256:ced8b23dceb22134307c1b8abfa523da14198793d9787ac838e70e29e77458d4",
"sha256:fa0fe2722ee1c3f57eac478820c3a5ae2f624af8264cbdf9000c980ff7f75e3f"
],
"index": "pypi",
"version": "==2.13.0"
}
},
"develop": {}
}

View File

@@ -0,0 +1,43 @@
#!/usr/bin/env python3
import datetime
import json
import os
import pathlib
import semver
_API_COMPATIBILITY_PATH = pathlib.Path(__file__).absolute().parents[3] / "src" / "api-compatibility.json"
_ENTERPRISE_RELEASES_PATH = pathlib.Path(os.environ["ENTERPRISE_RELEASES_PATH"])
_RELEASE_FILE_PATH = _ENTERPRISE_RELEASES_PATH / "releases.json"
_FIRST_SUPPORTED_RELEASE = semver.VersionInfo.parse("2.22.0") # Versions older than this did not include Code Scanning.
def main():
api_compatibility_data = json.loads(_API_COMPATIBILITY_PATH.read_text())
releases = json.loads(_RELEASE_FILE_PATH.read_text())
oldest_supported_release = None
newest_supported_release = semver.VersionInfo.parse(api_compatibility_data["maximumVersion"] + ".0")
for release_version_string, release_data in releases.items():
release_version = semver.VersionInfo.parse(release_version_string + ".0")
if release_version < _FIRST_SUPPORTED_RELEASE:
continue
if release_version > newest_supported_release:
feature_freeze_date = datetime.date.fromisoformat(release_data["feature_freeze"])
if feature_freeze_date < datetime.date.today() + datetime.timedelta(weeks=2):
newest_supported_release = release_version
if oldest_supported_release is None or release_version < oldest_supported_release:
end_of_life_date = datetime.date.fromisoformat(release_data["end"])
if end_of_life_date > datetime.date.today():
oldest_supported_release = release_version
api_compatibility_data = {
"minimumVersion": f"{oldest_supported_release.major}.{oldest_supported_release.minor}",
"maximumVersion": f"{newest_supported_release.major}.{newest_supported_release.minor}",
}
_API_COMPATIBILITY_PATH.write_text(json.dumps(api_compatibility_data, sort_keys=True) + "\n")
if __name__ == "__main__":
main()

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/runner/dist/
/runner/node_modules/

25
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,25 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug AVA test file",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/ava",
"runtimeArgs": [
"${file}",
"--break",
"--serial",
"--timeout=20m"
],
"port": 9229,
"outputCapture": "std",
"skipFiles": [
"<node_internals>/**/*.js"
]
}
]
}

10
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,10 @@
{
"files.exclude": {
// include the defaults from VS Code
"**/.git": true,
"**/.DS_Store": true,
// transpiled JavaScript
"lib": true,
}
}

15
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"option": "watch",
"problemMatcher": [
"$tsc-watch"
],
"group": "build",
"label": "tsc: watch - tsconfig.json"
}
]
}

37
CHANGELOG.md Normal file
View File

@@ -0,0 +1,37 @@
# CodeQL Action and CodeQL Runner Changelog
## 1.0.6 - 19 Jul 2021
- The `init` step of the Action now supports a `source-root` input as a path to the root source-code directory. By default, the path is relative to `$GITHUB_WORKSPACE`. [#607](https://github.com/github/codeql-action/pull/607)
- The `init` step will now try to install a few Python tools needed by this Action when running on a self-hosted runner. [#616](https://github.com/github/codeql-action/pull/616)
## 1.0.5 - 12 Jul 2021
- The `analyze` step of the Action now supports a `skip-queries` option to merely build the CodeQL database without analyzing. This functionality is not present in the runner. Additionally, the step will no longer fail if it encounters a finalized database, and will instead continue with query execution. [#602](https://github.com/github/codeql-action/pull/602)
- Update the warning message when the baseline lines of code count is unavailable. [#608](https://github.com/github/codeql-action/pull/608)
## 1.0.4 - 28 Jun 2021
- Fix `RUNNER_TEMP environment variable must be set` when using runner. [#594](https://github.com/github/codeql-action/pull/594)
- Fix couting of lines of code for C# projects. [#586](https://github.com/github/codeql-action/pull/586)
## 1.0.3 - 23 Jun 2021
No user facing changes.
## 1.0.2 - 17 Jun 2021
- Fix out of memory in hash computation. [#550](https://github.com/github/codeql-action/pull/550)
- Clean up logging during analyze results. [#557](https://github.com/github/codeql-action/pull/557)
- Add `--finalize-dataset` to `database finalize` call, freeing up some disk space after database creation. [#558](https://github.com/github/codeql-action/pull/558)
## 1.0.1 - 07 Jun 2021
- Pass the `--sarif-group-rules-by-pack` argument to CodeQL CLI invocations that generate SARIF. This means the SARIF rule object for each query will now be found underneath its corresponding query pack in `runs[].tool.extensions`. [#546](https://github.com/github/codeql-action/pull/546)
- Output the location of CodeQL databases created in the analyze step. [#543](https://github.com/github/codeql-action/pull/543)
## 1.0.0 - 31 May 2021
- Add this changelog file. [#507](https://github.com/github/codeql-action/pull/507)
- Improve grouping of analysis logs. Add a new log group containing a summary of metrics and diagnostics, if they were produced by CodeQL builtin queries. [#515](https://github.com/github/codeql-action/pull/515)
- Add metrics and diagnostics summaries from custom query suites to the analysis summary log group. [#532](https://github.com/github/codeql-action/pull/532)

1
CODEOWNERS Normal file
View File

@@ -0,0 +1 @@
**/* @github/codeql-action-reviewers

View File

@@ -1,4 +1,4 @@
## Contributing
# Contributing
[fork]: https://github.com/github/codeql-action/fork
[pr]: https://github.com/github/codeql-action/compare
@@ -10,13 +10,47 @@ Contributions to this project are [released](https://help.github.com/articles/gi
Please note that this project is released with a [Contributor Code of Conduct][code-of-conduct]. By participating in this project you agree to abide by its terms.
## Development and Testing
Before you start, ensure that you have a recent version of node (14 or higher) installed, along with a recent version of npm (7 or higher). You can see which version of node is used by the action in `init/action.yml`.
### Common tasks
* Transpile the TypeScript to JavaScript: `npm run build`. Note that the JavaScript files are committed to git.
* Run tests: `npm run test`. Youll need to ensure that the JavaScript files are up-to-date first by running the command above.
* Run the linter: `npm run lint`.
This project also includes configuration to run tests from VSCode (with support for breakpoints) - open the test file you wish to run and choose "Debug AVA test file" from the Run menu in the Run panel.
You may want to run `tsc --watch` from the command line or inside of vscode in order to ensure build artifacts are up to date as you are working.
### Checking in compiled artifacts and `node_modules`
Because CodeQL Action users consume the code directly from this repository, and there can be no build step during an GitHub Actions run, this repository contains all compiled artifacts and node modules. There is a PR check that will fail if any of the compiled artifacts are not up to date. Compiled artifacts are stored in the `lib/` directory. For all day-to-day development purposes, this folder can be ignored.
Only run `npm install` if you are explicitly changing the set of dependencies in `package.json`. The `node_modules` directory should be up to date when you check out, but if for some reason, there is an inconsistency use `npm ci && npm run removeNPMAbsolutePaths` to ensure the directory is in a state consistent with the `package-lock.json`. Note that due to a macOS-specific dependency, this command should be run on a macOS machine. There is a PR check to ensure the consistency of the `node_modules` directory.
### Running the action
To see the effect of your changes and to test them, push your changes in a branch and then look at the [Actions output](https://github.com/github/codeql-action/actions) for that branch. You can also exercise the code locally by running the automated tests.
### Integration tests
As well as the unit tests (see _Common tasks_ above), there are integration tests, defined in `.github/workflows/integration-testing.yml`. These are run by a CI check. Depending on the change youre making, you may want to add a test to this file or extend an existing one.
### Building the CodeQL runner
Navigate to the `runner` directory and run `npm install` to install dependencies needed only for compiling the CodeQL runner. Run `npm run build-runner` to output files to the `runner/dist` directory.
## Submitting a pull request
1. [Fork][fork] and clone the repository
2. Create a new branch: `git checkout -b my-branch-name`
3. Make your change, add tests, and make sure the tests still pass
4. Push to your fork and [submit a pull request][pr]
5. Pat your self on the back and wait for your pull request to be reviewed and merged.
5. Pat yourself on the back and wait for your pull request to be reviewed and merged.
If you're a GitHub staff member, you can merge your own PR once it's approved; for external contributors, GitHub staff will merge your PR once it's approved.
Here are a few things you can do that will increase the likelihood of your pull request being accepted:

120
README.md
View File

@@ -1,6 +1,8 @@
# CodeQL Action
This action runs GitHub's industry-leading static analysis engine, CodeQL, against a repository's source code to find security vulnerabilities. It then automatically uploads the results to GitHub so they can be displayed in the repository's security tab. CodeQL runs an extensible set of [queries](https://github.com/semmle/ql), which have been developed by the community and the [GitHub Security Lab](https://securitylab.github.com/) to find common vulnerabilities in your code.
This action runs GitHub's industry-leading semantic code analysis engine, CodeQL, against a repository's source code to find security vulnerabilities. It then automatically uploads the results to GitHub so they can be displayed in the repository's security tab. CodeQL runs an extensible set of [queries](https://github.com/github/codeql), which have been developed by the community and the [GitHub Security Lab](https://securitylab.github.com/) to find common vulnerabilities in your code.
For a list of recent changes, see the CodeQL Action's [changelog](CHANGELOG.md).
## License
@@ -10,6 +12,8 @@ The underlying CodeQL CLI, used in this action, is licensed under the [GitHub Co
## Usage
This is a short walkthrough, but for more information read [configuring code scanning](https://help.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning).
To get code scanning results from CodeQL analysis on your repo you can use the following workflow as a template:
```yaml
@@ -18,15 +22,21 @@ name: "Code Scanning - Action"
on:
push:
pull_request:
schedule:
- cron: '0 0 * * 0'
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12 or JAN-DEC)
# │ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ │
# * * * * *
- cron: '30 1 * * 0'
jobs:
CodeQL-Build:
strategy:
fail-fast: false
# CodeQL runs on ubuntu-latest, windows-latest, and macos-latest
runs-on: ubuntu-latest
@@ -78,24 +88,9 @@ If you prefer to integrate this within an existing CI workflow, it should end up
uses: github/codeql-action/analyze@v1
```
### Actions triggers
### Configuration file
The CodeQL action should be run on `push` events, and on a `schedule`. `Push` events allow us to do a detailed analysis of the delta in a pull request, while the `schedule` event ensures that GitHub regularly scans the repository for the latest vulnerabilities, even if the repository becomes inactive. This action does not support the `pull_request` event.
### Configuration
You may optionally specify additional queries for CodeQL to execute by using a config file. The queries must belong to a [QL pack](https://help.semmle.com/codeql/codeql-cli/reference/qlpack-overview.html) and can be in your repository or any public repository. You can choose a single .ql file, a folder containing multiple .ql files, a .qls [query suite](https://help.semmle.com/codeql/codeql-cli/procedures/query-suites.html) file, or any combination of the above. To use queries stored in your repository or from other repositories use the same syntax as when [using an action](https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstepsuses). Note that when using local queries starting with `./`, the path is relative to the root of the repository and not to the location of the config file.
You can disable the default queries using `disable-default-queries: true`.
You can choose to ignore some files or folders from the analysis, or include additional files/folders for analysis. This *only* works for Javascript and Python analysis.
Identifying potential files for extraction:
- Scans each folder that's defined as `paths` in turn, traversing subfolders, and looking for relevant files.
- If it finds a subfolder that's defined as `paths-ignore`, stop traversing.
- If a file or folder is both in `paths` and `paths-ignore`, the `paths-ignore` is ignored.
Use the `config-file` parameter of the init action to enable the configuration file. For example:
Use the `config-file` parameter of the `init` action to enable the configuration file. The value of `config-file` is the path to the configuration file you want to use. This example loads the configuration file `./.github/codeql/codeql-config.yml`.
```yaml
- uses: github/codeql-action/init@v1
@@ -103,72 +98,41 @@ Use the `config-file` parameter of the init action to enable the configuration f
config-file: ./.github/codeql/codeql-config.yml
```
A config file looks like this:
The configuration file can be located in a different repository. This is useful if you want to share the same configuration across multiple repositories. If the configuration file is in a private repository you can also specify an `external-repository-token` option. This should be a personal access token that has read access to any repositories containing referenced config files and queries.
```yaml
name: "My CodeQL config"
- uses: github/codeql-action/init@v1
with:
config-file: owner/repo/codeql-config.yml@branch
external-repository-token: ${{ secrets.EXTERNAL_REPOSITORY_TOKEN }}
```
disable-default-queries: true
For information on how to write a configuration file, see "[Using a custom configuration file](https://help.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#using-a-custom-configuration-file)."
queries:
- name: In-repo queries (Runs the queries located in the my-queries folder of the repo)
uses: ./my-queries
- name: External Javascript QL pack (Runs a QL pack located in an external repo)
uses: /Semmle/ql/javascript/ql/src/Electron@master
- name: External query (Runs a single query located in an external QL pack)
uses: Semmle/ql/javascript/ql/src/AngularJS/DeadAngularJSEventListener.ql@master
- name: Select query suite (Runs a query suites)
uses: ./codeql-querypacks/complex-python-querypack/rootAndBar.qls
If you only want to customise the queries used, you can specify them in your workflow instead of creating a config file, using the `queries` property of the `init` action:
paths:
- src/util.ts
```yaml
- uses: github/codeql-action/init@v1
with:
queries: <local-or-remote-query>,<another-query>
```
paths-ignore:
- src
- lib
By default, this will override any queries specified in a config file. If you wish to use both sets of queries, prefix the list of queries in the workflow with `+`:
```yaml
- uses: github/codeql-action/init@v1
with:
queries: +<local-or-remote-query>,<another-query>
```
## Troubleshooting
### Trouble with Go dependencies
Read about [troubleshooting code scanning](https://help.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/troubleshooting-code-scanning).
#### If you use a vendor directory
### Note on "missing analysis" message
Try passing
The very first time code scanning is run and if it is on a pull request, you will probably get a message mentioning a "missing analysis". This is expected.
```yaml
env:
GOFLAGS: "-mod=vendor"
```
After code scanning has analyzed the code in a pull request, it needs to compare the analysis of the topic branch (the merge commit of the branch you used to create the pull request) with the analysis of the base branch (the branch into which you want to merge the pull request). This allows code scanning to compute which alerts are newly introduced by the pull request, which alerts were already present in the base branch, and whether any existing alerts are fixed by the changes in the pull request. Initially, if you use a pull request to add code scanning to a repository, the base branch has not yet been analyzed, so it's not possible to compute these details. In this case, when you click through from the results check on the pull request you will see the "Missing analysis for base commit SHA-HASH" message.
to `github/codeql-action/analyze`.
#### If you do not use a vendor directory
Dependencies on public repositories should just work. If you have dependencies on private repositories, one option is to use `git config` and a [personal access token](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line) to authenticate when downloading dependencies. Add a section like
```yaml
steps:
- name: Configure git private repo access
env:
TOKEN: ${{ secrets.GITHUB_PAT }}
run: |
git config --global url."https://${TOKEN}@github.com/foo/bar".insteadOf "https://github.com/foo/bar"
git config --global url."https://${TOKEN}@github.com/foo/baz".insteadOf "https://github.com/foo/baz"
```
before any codeql actions. A similar thing can also be done with an SSH key or deploy key.
### C# using dotnet version 2 on linux
This currently requires invoking `dotnet` with the `/p:UseSharedCompilation=false` flag. For example:
```shell
dotnet build /p:UseSharedCompilation=false
```
Version 3 does not require the additional flag.
### Analysing Go together with other languages on `macos-latest`
When running on macos it is currently not possible to analyze Go in conjunction with any of Java, C/C++, or C#. Each language can still be analyzed separately.
For more information and other causes of this message, see [Reasons for the "missing analysis" message](https://docs.github.com/en/code-security/secure-coding/automatically-scanning-your-code-for-vulnerabilities-and-errors/setting-up-code-scanning-for-a-repository#reasons-for-the-missing-analysis-message)

View File

@@ -4,6 +4,7 @@ author: 'GitHub'
inputs:
check_name:
description: The name of the check run to add text to.
required: false
output:
description: The path of the directory in which to save the SARIF results
required: false
@@ -11,14 +12,43 @@ inputs:
upload:
description: Upload the SARIF file
required: false
default: true
default: "true"
cleanup-level:
description: "Level of cleanup to perform on CodeQL databases at the end of the analyze step. This should either be 'none' to skip cleanup, or be a valid argument for the --mode flag of the CodeQL CLI command 'codeql database cleanup' as documented at https://codeql.github.com/docs/codeql-cli/manual/database-cleanup"
required: false
default: "brutal"
ram:
description: Override the amount of memory in MB to be used by CodeQL. By default, almost all the memory of the machine is used.
required: false
add-snippets:
description: Specify whether or not to add code snippets to the output sarif file.
required: false
default: "false"
skip-queries:
description: If this option is set, the CodeQL database will be built but no queries will be run on it. Thus, no results will be produced.
required: false
default: "false"
threads:
description: The number of threads to be used by CodeQL.
required: false
checkout_path:
description: "The path at which the analyzed repository was checked out. Used to relativize any absolute paths in the uploaded SARIF file."
required: false
default: ${{ github.workspace }}
category:
description: String used by Code Scanning for matching the analyses
required: false
upload-database:
description: Whether to upload the resulting CodeQL database
required: false
default: "true"
token:
default: ${{ github.token }}
matrix:
default: ${{ toJson(matrix) }}
outputs:
db-locations:
description: A map from language to absolute path for each database created by CodeQL.
runs:
using: 'node12'
main: '../lib/finalize-db.js'
main: '../lib/analyze-action.js'

View File

@@ -8,4 +8,4 @@ inputs:
default: ${{ toJson(matrix) }}
runs:
using: 'node12'
main: '../lib/autobuild.js'
main: '../lib/autobuild-action.js'

View File

@@ -1,19 +1,49 @@
name: 'CodeQL: Init'
description: 'Setup the CodeQL tracer'
description: 'Set up CodeQL'
author: 'GitHub'
inputs:
tools:
description: URL of CodeQL tools
required: false
default: https://github.com/github/codeql-action/releases/download/codeql-bundle-20200427/codeql-bundle.tar.gz
# If not specified the Action will check in several places until it finds the CodeQL tools.
languages:
description: The languages to be analysed
required: false
token:
default: ${{ github.token }}
matrix:
default: ${{ toJson(matrix) }}
config-file:
description: Path of the config file to use
required: false
db-location:
description: Path where CodeQL databases should be created. If not specified, a temporary directory will be used.
required: false
queries:
description: Comma-separated list of additional queries to run. By default, this overrides the same setting in a configuration file; prefix with "+" to use both sets of queries.
required: false
packs:
description: >-
[Experimental] Comma-separated list of packs to run. Reference a pack in the format `scope/name[@version]`. If `version` is not
specified, then the latest version of the pack is used. By default, this overrides the same setting in a
configuration file; prefix with "+" to use both sets of packs.
This input is only available in single-language analyses. To use packs in multi-language
analyses, you must specify packs in the codeql-config.yml file.
required: false
external-repository-token:
description: A token for fetching external config files and queries if they reside in a private repository.
required: false
setup-python-dependencies:
description: Try to auto-install your python dependencies
required: true
default: 'true'
source-root:
description: Path of the root source code directory, relative to $GITHUB_WORKSPACE.
required: false
outputs:
codeql-path:
description: The path of the CodeQL binary used for analysis
runs:
using: 'node12'
main: '../lib/setup-tracer.js'
main: '../lib/init-action.js'

View File

@@ -1,11 +0,0 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
testRunner: 'jest-circus/runner',
transform: {
'^.+\\.ts$': 'ts-jest'
},
verbose: true
}

563
lib/actions-util.js generated Normal file
View File

@@ -0,0 +1,563 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const core = __importStar(require("@actions/core"));
const toolrunner = __importStar(require("@actions/exec/lib/toolrunner"));
const safeWhich = __importStar(require("@chrisgavin/safe-which"));
const yaml = __importStar(require("js-yaml"));
const api = __importStar(require("./api-client"));
const sharedEnv = __importStar(require("./shared-environment"));
const util_1 = require("./util");
/**
* The utils in this module are meant to be run inside of the action only.
* Code paths from the runner should not enter this module.
*/
/**
* Wrapper around core.getInput for inputs that always have a value.
* Also see getOptionalInput.
*
* This allows us to get stronger type checking of required/optional inputs
* and make behaviour more consistent between actions and the runner.
*/
function getRequiredInput(name) {
return core.getInput(name, { required: true });
}
exports.getRequiredInput = getRequiredInput;
/**
* Wrapper around core.getInput that converts empty inputs to undefined.
* Also see getRequiredInput.
*
* This allows us to get stronger type checking of required/optional inputs
* and make behaviour more consistent between actions and the runner.
*/
function getOptionalInput(name) {
const value = core.getInput(name);
return value.length > 0 ? value : undefined;
}
exports.getOptionalInput = getOptionalInput;
function getTemporaryDirectory() {
const value = process.env["CODEQL_ACTION_TEMP"];
return value !== undefined && value !== ""
? value
: util_1.getRequiredEnvParam("RUNNER_TEMP");
}
exports.getTemporaryDirectory = getTemporaryDirectory;
function getToolCacheDirectory() {
const value = process.env["CODEQL_ACTION_TOOL_CACHE"];
return value !== undefined && value !== ""
? value
: util_1.getRequiredEnvParam("RUNNER_TOOL_CACHE");
}
exports.getToolCacheDirectory = getToolCacheDirectory;
/**
* Gets the SHA of the commit that is currently checked out.
*/
exports.getCommitOid = async function (ref = "HEAD") {
// Try to use git to get the current commit SHA. If that fails then
// log but otherwise silently fall back to using the SHA from the environment.
// The only time these two values will differ is during analysis of a PR when
// the workflow has changed the current commit to the head commit instead of
// the merge commit, which must mean that git is available.
// Even if this does go wrong, it's not a huge problem for the alerts to
// reported on the merge commit.
try {
let commitOid = "";
await new toolrunner.ToolRunner(await safeWhich.safeWhich("git"), ["rev-parse", ref], {
silent: true,
listeners: {
stdout: (data) => {
commitOid += data.toString();
},
stderr: (data) => {
process.stderr.write(data);
},
},
}).exec();
return commitOid.trim();
}
catch (e) {
core.info(`Failed to call git to get current commit. Continuing with data from environment: ${e}`);
return util_1.getRequiredEnvParam("GITHUB_SHA");
}
};
function isObject(o) {
return o !== null && typeof o === "object";
}
const GLOB_PATTERN = new RegExp("(\\*\\*?)");
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
function patternToRegExp(value) {
return new RegExp(`^${value
.toString()
.split(GLOB_PATTERN)
.reduce(function (arr, cur) {
if (cur === "**") {
arr.push(".*?");
}
else if (cur === "*") {
arr.push("[^/]*?");
}
else if (cur) {
arr.push(escapeRegExp(cur));
}
return arr;
}, [])
.join("")}$`);
}
// this function should return true if patternA is a superset of patternB
// e.g: * is a superset of main-* but main-* is not a superset of *.
function patternIsSuperset(patternA, patternB) {
return patternToRegExp(patternA).test(patternB);
}
exports.patternIsSuperset = patternIsSuperset;
function branchesToArray(branches) {
if (typeof branches === "string") {
return [branches];
}
if (Array.isArray(branches)) {
if (branches.length === 0) {
return "**";
}
return branches;
}
return "**";
}
function toCodedErrors(errors) {
return Object.entries(errors).reduce((acc, [key, value]) => {
acc[key] = { message: value, code: key };
return acc;
}, {});
}
// code to send back via status report
// message to add as a warning annotation to the run
exports.WorkflowErrors = toCodedErrors({
MismatchedBranches: `Please make sure that every branch in on.pull_request is also in on.push so that Code Scanning can compare pull requests against the state of the base branch.`,
MissingPushHook: `Please specify an on.push hook so that Code Scanning can compare pull requests against the state of the base branch.`,
PathsSpecified: `Using on.push.paths can prevent Code Scanning annotating new alerts in your pull requests.`,
PathsIgnoreSpecified: `Using on.push.paths-ignore can prevent Code Scanning annotating new alerts in your pull requests.`,
CheckoutWrongHead: `git checkout HEAD^2 is no longer necessary. Please remove this step as Code Scanning recommends analyzing the merge commit for best results.`,
});
function getWorkflowErrors(doc) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const errors = [];
const jobName = process.env.GITHUB_JOB;
if (jobName) {
const job = (_b = (_a = doc) === null || _a === void 0 ? void 0 : _a.jobs) === null || _b === void 0 ? void 0 : _b[jobName];
const steps = (_c = job) === null || _c === void 0 ? void 0 : _c.steps;
if (Array.isArray(steps)) {
for (const step of steps) {
// this was advice that we used to give in the README
// we actually want to run the analysis on the merge commit
// to produce results that are more inline with expectations
// (i.e: this is what will happen if you merge this PR)
// and avoid some race conditions
if (((_d = step) === null || _d === void 0 ? void 0 : _d.run) === "git checkout HEAD^2") {
errors.push(exports.WorkflowErrors.CheckoutWrongHead);
break;
}
}
}
}
let missingPush = false;
if (doc.on === undefined) {
// this is not a valid config
}
else if (typeof doc.on === "string") {
if (doc.on === "pull_request") {
missingPush = true;
}
}
else if (Array.isArray(doc.on)) {
const hasPush = doc.on.includes("push");
const hasPullRequest = doc.on.includes("pull_request");
if (hasPullRequest && !hasPush) {
missingPush = true;
}
}
else if (isObject(doc.on)) {
const hasPush = Object.prototype.hasOwnProperty.call(doc.on, "push");
const hasPullRequest = Object.prototype.hasOwnProperty.call(doc.on, "pull_request");
if (!hasPush && hasPullRequest) {
missingPush = true;
}
if (hasPush && hasPullRequest) {
const paths = (_e = doc.on.push) === null || _e === void 0 ? void 0 : _e.paths;
// if you specify paths or paths-ignore you can end up with commits that have no baseline
// if they didn't change any files
// currently we cannot go back through the history and find the most recent baseline
if (Array.isArray(paths) && paths.length > 0) {
errors.push(exports.WorkflowErrors.PathsSpecified);
}
const pathsIgnore = (_f = doc.on.push) === null || _f === void 0 ? void 0 : _f["paths-ignore"];
if (Array.isArray(pathsIgnore) && pathsIgnore.length > 0) {
errors.push(exports.WorkflowErrors.PathsIgnoreSpecified);
}
}
// if doc.on.pull_request is null that means 'all branches'
// if doc.on.pull_request is undefined that means 'off'
// we only want to check for mismatched branches if pull_request is on.
if (doc.on.pull_request !== undefined) {
const push = branchesToArray((_g = doc.on.push) === null || _g === void 0 ? void 0 : _g.branches);
if (push !== "**") {
const pull_request = branchesToArray((_h = doc.on.pull_request) === null || _h === void 0 ? void 0 : _h.branches);
if (pull_request !== "**") {
const difference = pull_request.filter((value) => !push.some((o) => patternIsSuperset(o, value)));
if (difference.length > 0) {
// there are branches in pull_request that may not have a baseline
// because we are not building them on push
errors.push(exports.WorkflowErrors.MismatchedBranches);
}
}
else if (push.length > 0) {
// push is set up to run on a subset of branches
// and you could open a PR against a branch with no baseline
errors.push(exports.WorkflowErrors.MismatchedBranches);
}
}
}
}
if (missingPush) {
errors.push(exports.WorkflowErrors.MissingPushHook);
}
return errors;
}
exports.getWorkflowErrors = getWorkflowErrors;
async function validateWorkflow() {
let workflow;
try {
workflow = await getWorkflow();
}
catch (e) {
return `error: getWorkflow() failed: ${e.toString()}`;
}
let workflowErrors;
try {
workflowErrors = getWorkflowErrors(workflow);
}
catch (e) {
return `error: getWorkflowErrors() failed: ${e.toString()}`;
}
if (workflowErrors.length > 0) {
let message;
try {
message = formatWorkflowErrors(workflowErrors);
}
catch (e) {
return `error: formatWorkflowErrors() failed: ${e.toString()}`;
}
core.warning(message);
}
return formatWorkflowCause(workflowErrors);
}
exports.validateWorkflow = validateWorkflow;
function formatWorkflowErrors(errors) {
const issuesWere = errors.length === 1 ? "issue was" : "issues were";
const errorsList = errors.map((e) => e.message).join(" ");
return `${errors.length} ${issuesWere} detected with this workflow: ${errorsList}`;
}
exports.formatWorkflowErrors = formatWorkflowErrors;
function formatWorkflowCause(errors) {
if (errors.length === 0) {
return undefined;
}
return errors.map((e) => e.code).join(",");
}
exports.formatWorkflowCause = formatWorkflowCause;
async function getWorkflow() {
const relativePath = await getWorkflowPath();
const absolutePath = path.join(util_1.getRequiredEnvParam("GITHUB_WORKSPACE"), relativePath);
return yaml.safeLoad(fs.readFileSync(absolutePath, "utf-8"));
}
exports.getWorkflow = getWorkflow;
/**
* Get the path of the currently executing workflow.
*/
async function getWorkflowPath() {
const repo_nwo = util_1.getRequiredEnvParam("GITHUB_REPOSITORY").split("/");
const owner = repo_nwo[0];
const repo = repo_nwo[1];
const run_id = Number(util_1.getRequiredEnvParam("GITHUB_RUN_ID"));
const apiClient = api.getActionsApiClient();
const runsResponse = await apiClient.request("GET /repos/:owner/:repo/actions/runs/:run_id", {
owner,
repo,
run_id,
});
const workflowUrl = runsResponse.data.workflow_url;
const workflowResponse = await apiClient.request(`GET ${workflowUrl}`);
return workflowResponse.data.path;
}
/**
* Get the workflow run ID.
*/
function getWorkflowRunID() {
const workflowRunID = parseInt(util_1.getRequiredEnvParam("GITHUB_RUN_ID"), 10);
if (Number.isNaN(workflowRunID)) {
throw new Error("GITHUB_RUN_ID must define a non NaN workflow run ID");
}
return workflowRunID;
}
exports.getWorkflowRunID = getWorkflowRunID;
/**
* Get the analysis key parameter for the current job.
*
* This will combine the workflow path and current job name.
* Computing this the first time requires making requests to
* the github API, but after that the result will be cached.
*/
async function getAnalysisKey() {
const analysisKeyEnvVar = "CODEQL_ACTION_ANALYSIS_KEY";
let analysisKey = process.env[analysisKeyEnvVar];
if (analysisKey !== undefined) {
return analysisKey;
}
const workflowPath = await getWorkflowPath();
const jobName = util_1.getRequiredEnvParam("GITHUB_JOB");
analysisKey = `${workflowPath}:${jobName}`;
core.exportVariable(analysisKeyEnvVar, analysisKey);
return analysisKey;
}
exports.getAnalysisKey = getAnalysisKey;
async function getAutomationID() {
const analysis_key = await getAnalysisKey();
const environment = getRequiredInput("matrix");
return computeAutomationID(analysis_key, environment);
}
exports.getAutomationID = getAutomationID;
function computeAutomationID(analysis_key, environment) {
let automationID = `${analysis_key}/`;
// the id has to be deterministic so we sort the fields
if (environment !== undefined && environment !== "null") {
const environmentObject = JSON.parse(environment);
for (const entry of Object.entries(environmentObject).sort()) {
if (typeof entry[1] === "string") {
automationID += `${entry[0]}:${entry[1]}/`;
}
else {
// In code scanning we just handle the string values,
// the rest get converted to the empty string
automationID += `${entry[0]}:/`;
}
}
}
return automationID;
}
exports.computeAutomationID = computeAutomationID;
/**
* Get the ref currently being analyzed.
*/
async function getRef() {
// Will be in the form "refs/heads/master" on a push event
// or in the form "refs/pull/N/merge" on a pull_request event
const ref = util_1.getRequiredEnvParam("GITHUB_REF");
const sha = util_1.getRequiredEnvParam("GITHUB_SHA");
// For pull request refs we want to detect whether the workflow
// has run `git checkout HEAD^2` to analyze the 'head' ref rather
// than the 'merge' ref. If so, we want to convert the ref that
// we report back.
const pull_ref_regex = /refs\/pull\/(\d+)\/merge/;
if (!pull_ref_regex.test(ref)) {
return ref;
}
const head = await exports.getCommitOid("HEAD");
// in actions/checkout@v2 we can check if git rev-parse HEAD == GITHUB_SHA
// in actions/checkout@v1 this may not be true as it checks out the repository
// using GITHUB_REF. There is a subtle race condition where
// git rev-parse GITHUB_REF != GITHUB_SHA, so we must check
// git git-parse GITHUB_REF == git rev-parse HEAD instead.
const hasChangedRef = sha !== head &&
(await exports.getCommitOid(ref.replace(/^refs\/pull\//, "refs/remotes/pull/"))) !==
head;
if (hasChangedRef) {
const newRef = ref.replace(pull_ref_regex, "refs/pull/$1/head");
core.debug(`No longer on merge commit, rewriting ref from ${ref} to ${newRef}.`);
return newRef;
}
else {
return ref;
}
}
exports.getRef = getRef;
/**
* Compose a StatusReport.
*
* @param actionName The name of the action, e.g. 'init', 'finish', 'upload-sarif'
* @param status The status. Must be 'success', 'failure', or 'starting'
* @param startedAt The time this action started executing.
* @param cause Cause of failure (only supply if status is 'failure')
* @param exception Exception (only supply if status is 'failure')
*/
async function createStatusReportBase(actionName, status, actionStartedAt, cause, exception) {
const commitOid = process.env["GITHUB_SHA"] || "";
const ref = await getRef();
const workflowRunIDStr = process.env["GITHUB_RUN_ID"];
let workflowRunID = -1;
if (workflowRunIDStr) {
workflowRunID = parseInt(workflowRunIDStr, 10);
}
const workflowName = process.env["GITHUB_WORKFLOW"] || "";
const jobName = process.env["GITHUB_JOB"] || "";
const analysis_key = await getAnalysisKey();
let workflowStartedAt = process.env[sharedEnv.CODEQL_WORKFLOW_STARTED_AT];
if (workflowStartedAt === undefined) {
workflowStartedAt = actionStartedAt.toISOString();
core.exportVariable(sharedEnv.CODEQL_WORKFLOW_STARTED_AT, workflowStartedAt);
}
// If running locally then the GITHUB_ACTION_REF cannot be trusted as it may be for the previous action
// See https://github.com/actions/runner/issues/803
const actionRef = isRunningLocalAction()
? undefined
: process.env["GITHUB_ACTION_REF"];
const statusReport = {
workflow_run_id: workflowRunID,
workflow_name: workflowName,
job_name: jobName,
analysis_key,
commit_oid: commitOid,
ref,
action_name: actionName,
action_ref: actionRef,
action_oid: "unknown",
started_at: workflowStartedAt,
action_started_at: actionStartedAt.toISOString(),
status,
};
// Add optional parameters
if (cause) {
statusReport.cause = cause;
}
if (exception) {
statusReport.exception = exception;
}
if (status === "success" || status === "failure" || status === "aborted") {
statusReport.completed_at = new Date().toISOString();
}
const matrix = getRequiredInput("matrix");
if (matrix) {
statusReport.matrix_vars = matrix;
}
return statusReport;
}
exports.createStatusReportBase = createStatusReportBase;
const GENERIC_403_MSG = "The repo on which this action is running is not opted-in to CodeQL code scanning.";
const GENERIC_404_MSG = "Not authorized to used the CodeQL code scanning feature on this repo.";
const OUT_OF_DATE_MSG = "CodeQL Action is out-of-date. Please upgrade to the latest version of codeql-action.";
const INCOMPATIBLE_MSG = "CodeQL Action version is incompatible with the code scanning endpoint. Please update to a compatible version of codeql-action.";
/**
* Send a status report to the code_scanning/analysis/status endpoint.
*
* Optionally checks the response from the API endpoint and sets the action
* as failed if the status report failed. This is only expected to be used
* when sending a 'starting' report.
*
* Returns whether sending the status report was successful of not.
*/
async function sendStatusReport(statusReport) {
const statusReportJSON = JSON.stringify(statusReport);
core.debug(`Sending status report: ${statusReportJSON}`);
const nwo = util_1.getRequiredEnvParam("GITHUB_REPOSITORY");
const [owner, repo] = nwo.split("/");
const client = api.getActionsApiClient();
try {
await client.request("PUT /repos/:owner/:repo/code-scanning/analysis/status", {
owner,
repo,
data: statusReportJSON,
});
return true;
}
catch (e) {
console.log(e);
if (util_1.isHTTPError(e)) {
switch (e.status) {
case 403:
if (workflowIsTriggeredByPushEvent() && isDependabotActor()) {
core.setFailed('Workflows triggered by Dependabot on the "push" event run with read-only access. ' +
"Uploading Code Scanning results requires write access. " +
'To use Code Scanning with Dependabot, please ensure you are using the "pull_request" event for this workflow and avoid triggering on the "push" event for Dependabot branches. ' +
"See https://docs.github.com/en/code-security/secure-coding/configuring-code-scanning#scanning-on-push for more information on how to configure these events.");
}
else {
core.setFailed(e.message || GENERIC_403_MSG);
}
return false;
case 404:
core.setFailed(GENERIC_404_MSG);
return false;
case 422:
// schema incompatibility when reporting status
// this means that this action version is no longer compatible with the API
// we still want to continue as it is likely the analysis endpoint will work
if (util_1.getRequiredEnvParam("GITHUB_SERVER_URL") !== util_1.GITHUB_DOTCOM_URL) {
core.debug(INCOMPATIBLE_MSG);
}
else {
core.debug(OUT_OF_DATE_MSG);
}
return true;
}
}
// something else has gone wrong and the request/response will be logged by octokit
// it's possible this is a transient error and we should continue scanning
core.error("An unexpected error occurred when sending code scanning status report.");
return true;
}
}
exports.sendStatusReport = sendStatusReport;
// Was the workflow run triggered by a `push` event, for example as opposed to a `pull_request` event.
function workflowIsTriggeredByPushEvent() {
return process.env["GITHUB_EVENT_NAME"] === "push";
}
// Is dependabot the actor that triggered the current workflow run.
function isDependabotActor() {
return process.env["GITHUB_ACTOR"] === "dependabot[bot]";
}
// Is the current action executing a local copy (i.e. we're running a workflow on the codeql-action repo itself)
// as opposed to running a remote action (i.e. when another repo references us)
function isRunningLocalAction() {
const relativeScriptPath = getRelativeScriptPath();
return (relativeScriptPath.startsWith("..") || path.isAbsolute(relativeScriptPath));
}
exports.isRunningLocalAction = isRunningLocalAction;
// Get the location where the action is running from.
// This can be used to get the actions name or tell if we're running a local action.
function getRelativeScriptPath() {
const runnerTemp = util_1.getRequiredEnvParam("RUNNER_TEMP");
const actionsDirectory = path.join(path.dirname(runnerTemp), "_actions");
return path.relative(actionsDirectory, __filename);
}
exports.getRelativeScriptPath = getRelativeScriptPath;
// Reads the contents of GITHUB_EVENT_PATH as a JSON object
function getWorkflowEvent() {
const eventJsonFile = util_1.getRequiredEnvParam("GITHUB_EVENT_PATH");
try {
return JSON.parse(fs.readFileSync(eventJsonFile, "utf-8"));
}
catch (e) {
throw new Error(`Unable to read workflow event JSON from ${eventJsonFile}: ${e}`);
}
}
// Is the version of the repository we are currently analyzing from the default branch,
// or alternatively from another branch or a pull request.
async function isAnalyzingDefaultBranch() {
var _a, _b;
// Get the current ref and trim and refs/heads/ prefix
let currentRef = await getRef();
currentRef = currentRef.startsWith("refs/heads/")
? currentRef.substr("refs/heads/".length)
: currentRef;
const event = getWorkflowEvent();
const defaultBranch = (_b = (_a = event) === null || _a === void 0 ? void 0 : _a.repository) === null || _b === void 0 ? void 0 : _b.default_branch;
return currentRef === defaultBranch;
}
exports.isAnalyzingDefaultBranch = isAnalyzingDefaultBranch;
//# sourceMappingURL=actions-util.js.map

1
lib/actions-util.js.map Normal file

File diff suppressed because one or more lines are too long

431
lib/actions-util.test.js generated Normal file
View File

@@ -0,0 +1,431 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ava_1 = __importDefault(require("ava"));
const yaml = __importStar(require("js-yaml"));
const sinon_1 = __importDefault(require("sinon"));
const actionsutil = __importStar(require("./actions-util"));
const testing_utils_1 = require("./testing-utils");
const util_1 = require("./util");
function errorCodes(actual, expected) {
return [actual.map(({ code }) => code), expected.map(({ code }) => code)];
}
testing_utils_1.setupTests(ava_1.default);
ava_1.default("getRef() throws on the empty string", async (t) => {
process.env["GITHUB_REF"] = "";
await t.throwsAsync(actionsutil.getRef);
});
ava_1.default("getRef() returns merge PR ref if GITHUB_SHA still checked out", async (t) => {
const expectedRef = "refs/pull/1/merge";
const currentSha = "a".repeat(40);
process.env["GITHUB_REF"] = expectedRef;
process.env["GITHUB_SHA"] = currentSha;
const callback = sinon_1.default.stub(actionsutil, "getCommitOid");
callback.withArgs("HEAD").resolves(currentSha);
const actualRef = await actionsutil.getRef();
t.deepEqual(actualRef, expectedRef);
callback.restore();
});
ava_1.default("getRef() returns merge PR ref if GITHUB_REF still checked out but sha has changed (actions checkout@v1)", async (t) => {
const expectedRef = "refs/pull/1/merge";
process.env["GITHUB_REF"] = expectedRef;
process.env["GITHUB_SHA"] = "b".repeat(40);
const sha = "a".repeat(40);
const callback = sinon_1.default.stub(actionsutil, "getCommitOid");
callback.withArgs("refs/remotes/pull/1/merge").resolves(sha);
callback.withArgs("HEAD").resolves(sha);
const actualRef = await actionsutil.getRef();
t.deepEqual(actualRef, expectedRef);
callback.restore();
});
ava_1.default("getRef() returns head PR ref if GITHUB_REF no longer checked out", async (t) => {
process.env["GITHUB_REF"] = "refs/pull/1/merge";
process.env["GITHUB_SHA"] = "a".repeat(40);
const callback = sinon_1.default.stub(actionsutil, "getCommitOid");
callback.withArgs("refs/pull/1/merge").resolves("a".repeat(40));
callback.withArgs("HEAD").resolves("b".repeat(40));
const actualRef = await actionsutil.getRef();
t.deepEqual(actualRef, "refs/pull/1/head");
callback.restore();
});
ava_1.default("computeAutomationID()", async (t) => {
let actualAutomationID = actionsutil.computeAutomationID(".github/workflows/codeql-analysis.yml:analyze", '{"language": "javascript", "os": "linux"}');
t.deepEqual(actualAutomationID, ".github/workflows/codeql-analysis.yml:analyze/language:javascript/os:linux/");
// check the environment sorting
actualAutomationID = actionsutil.computeAutomationID(".github/workflows/codeql-analysis.yml:analyze", '{"os": "linux", "language": "javascript"}');
t.deepEqual(actualAutomationID, ".github/workflows/codeql-analysis.yml:analyze/language:javascript/os:linux/");
// check that an empty environment produces the right results
actualAutomationID = actionsutil.computeAutomationID(".github/workflows/codeql-analysis.yml:analyze", "{}");
t.deepEqual(actualAutomationID, ".github/workflows/codeql-analysis.yml:analyze/");
// check non string environment values
actualAutomationID = actionsutil.computeAutomationID(".github/workflows/codeql-analysis.yml:analyze", '{"number": 1, "object": {"language": "javascript"}}');
t.deepEqual(actualAutomationID, ".github/workflows/codeql-analysis.yml:analyze/number:/object:/");
// check undefined environment
actualAutomationID = actionsutil.computeAutomationID(".github/workflows/codeql-analysis.yml:analyze", undefined);
t.deepEqual(actualAutomationID, ".github/workflows/codeql-analysis.yml:analyze/");
});
ava_1.default("getWorkflowErrors() when on is empty", (t) => {
const errors = actionsutil.getWorkflowErrors({ on: {} });
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.push is an array missing pull_request", (t) => {
const errors = actionsutil.getWorkflowErrors({ on: ["push"] });
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.push is an array missing push", (t) => {
const errors = actionsutil.getWorkflowErrors({ on: ["pull_request"] });
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.MissingPushHook]));
});
ava_1.default("getWorkflowErrors() when on.push is valid", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: ["push", "pull_request"],
});
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.push is a valid superset", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: ["push", "pull_request", "schedule"],
});
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.push should not have a path", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: {
push: { branches: ["main"], paths: ["test/*"] },
pull_request: { branches: ["main"] },
},
});
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.PathsSpecified]));
});
ava_1.default("getWorkflowErrors() when on.push is a correct object", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: { push: { branches: ["main"] }, pull_request: { branches: ["main"] } },
});
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.pull_requests is a string", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: { push: { branches: ["main"] }, pull_request: { branches: "*" } },
});
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.MismatchedBranches]));
});
ava_1.default("getWorkflowErrors() when on.pull_requests is a string and correct", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: { push: { branches: "*" }, pull_request: { branches: "*" } },
});
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.push is correct with empty objects", (t) => {
const errors = actionsutil.getWorkflowErrors(yaml.safeLoad(`
on:
push:
pull_request:
`));
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.push is mismatched", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: {
push: { branches: ["main"] },
pull_request: { branches: ["feature"] },
},
});
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.MismatchedBranches]));
});
ava_1.default("getWorkflowErrors() when on.push is not mismatched", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: {
push: { branches: ["main", "feature"] },
pull_request: { branches: ["main"] },
},
});
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.push is mismatched for pull_request", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: {
push: { branches: ["main"] },
pull_request: { branches: ["main", "feature"] },
},
});
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.MismatchedBranches]));
});
ava_1.default("getWorkflowErrors() for a range of malformed workflows", (t) => {
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: {
push: 1,
pull_request: 1,
},
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
jobs: 1,
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
jobs: [1],
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
jobs: { 1: 1 },
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
jobs: { test: 1 },
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
jobs: { test: [1] },
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
jobs: { test: { steps: 1 } },
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
jobs: { test: { steps: [{ notrun: "git checkout HEAD^2" }] } },
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: 1,
jobs: { test: [undefined] },
}), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors(1), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors({
on: {
push: {
branches: 1,
},
pull_request: {
branches: 1,
},
},
}), []));
});
ava_1.default("getWorkflowErrors() when on.pull_request for every branch but push specifies branches", (t) => {
const errors = actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on:
push:
branches: ["main"]
pull_request:
`));
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.MismatchedBranches]));
});
ava_1.default("getWorkflowErrors() when on.pull_request for wildcard branches", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: {
push: { branches: ["feature/*"] },
pull_request: { branches: "feature/moose" },
},
});
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.pull_request for mismatched wildcard branches", (t) => {
const errors = actionsutil.getWorkflowErrors({
on: {
push: { branches: ["feature/moose"] },
pull_request: { branches: "feature/*" },
},
});
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.MismatchedBranches]));
});
ava_1.default("getWorkflowErrors() when HEAD^2 is checked out", (t) => {
process.env.GITHUB_JOB = "test";
const errors = actionsutil.getWorkflowErrors({
on: ["push", "pull_request"],
jobs: { test: { steps: [{ run: "git checkout HEAD^2" }] } },
});
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.CheckoutWrongHead]));
});
ava_1.default("formatWorkflowErrors() when there is one error", (t) => {
const message = actionsutil.formatWorkflowErrors([
actionsutil.WorkflowErrors.CheckoutWrongHead,
]);
t.true(message.startsWith("1 issue was detected with this workflow:"));
});
ava_1.default("formatWorkflowErrors() when there are multiple errors", (t) => {
const message = actionsutil.formatWorkflowErrors([
actionsutil.WorkflowErrors.CheckoutWrongHead,
actionsutil.WorkflowErrors.PathsSpecified,
]);
t.true(message.startsWith("2 issues were detected with this workflow:"));
});
ava_1.default("formatWorkflowCause() with no errors", (t) => {
const message = actionsutil.formatWorkflowCause([]);
t.deepEqual(message, undefined);
});
ava_1.default("formatWorkflowCause()", (t) => {
const message = actionsutil.formatWorkflowCause([
actionsutil.WorkflowErrors.CheckoutWrongHead,
actionsutil.WorkflowErrors.PathsSpecified,
]);
t.deepEqual(message, "CheckoutWrongHead,PathsSpecified");
t.deepEqual(actionsutil.formatWorkflowCause([]), undefined);
});
ava_1.default("patternIsSuperset()", (t) => {
t.false(actionsutil.patternIsSuperset("main-*", "main"));
t.true(actionsutil.patternIsSuperset("*", "*"));
t.true(actionsutil.patternIsSuperset("*", "main-*"));
t.false(actionsutil.patternIsSuperset("main-*", "*"));
t.false(actionsutil.patternIsSuperset("main-*", "main"));
t.true(actionsutil.patternIsSuperset("main", "main"));
t.false(actionsutil.patternIsSuperset("*", "feature/*"));
t.true(actionsutil.patternIsSuperset("**", "feature/*"));
t.false(actionsutil.patternIsSuperset("feature-*", "**"));
t.false(actionsutil.patternIsSuperset("a/**/c", "a/**/d"));
t.false(actionsutil.patternIsSuperset("a/**/c", "a/**"));
t.true(actionsutil.patternIsSuperset("a/**", "a/**/c"));
t.true(actionsutil.patternIsSuperset("a/**/c", "a/main-**/c"));
t.false(actionsutil.patternIsSuperset("a/**/b/**/c", "a/**/d/**/c"));
t.true(actionsutil.patternIsSuperset("a/**/b/**/c", "a/**/b/c/**/c"));
t.true(actionsutil.patternIsSuperset("a/**/b/**/c", "a/**/b/d/**/c"));
t.false(actionsutil.patternIsSuperset("a/**/c/d/**/c", "a/**/b/**/c"));
t.false(actionsutil.patternIsSuperset("a/main-**/c", "a/**/c"));
t.true(actionsutil.patternIsSuperset("/robin/*/release/*", "/robin/moose/release/goose"));
t.false(actionsutil.patternIsSuperset("/robin/moose/release/goose", "/robin/*/release/*"));
});
ava_1.default("getWorkflowErrors() when branches contain dots", (t) => {
const errors = actionsutil.getWorkflowErrors(yaml.safeLoad(`
on:
push:
branches: [4.1, master]
pull_request:
# The branches below must be a subset of the branches above
branches: [4.1, master]
`));
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on.push has a trailing comma", (t) => {
const errors = actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on:
push:
branches: [master, ]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
`));
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() should only report the current job's CheckoutWrongHead", (t) => {
process.env.GITHUB_JOB = "test";
const errors = actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
jobs:
test:
steps:
- run: "git checkout HEAD^2"
test2:
steps:
- run: "git checkout HEAD^2"
test3:
steps: []
`));
t.deepEqual(...errorCodes(errors, [actionsutil.WorkflowErrors.CheckoutWrongHead]));
});
ava_1.default("getWorkflowErrors() should not report a different job's CheckoutWrongHead", (t) => {
process.env.GITHUB_JOB = "test3";
const errors = actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
jobs:
test:
steps:
- run: "git checkout HEAD^2"
test2:
steps:
- run: "git checkout HEAD^2"
test3:
steps: []
`));
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() when on is missing", (t) => {
const errors = actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
`));
t.deepEqual(...errorCodes(errors, []));
});
ava_1.default("getWorkflowErrors() with a different on setup", (t) => {
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on: "workflow_dispatch"
`)), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on: [workflow_dispatch]
`)), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on:
workflow_dispatch: {}
`)), []));
});
ava_1.default("getWorkflowErrors() should not report an error if PRs are totally unconfigured", (t) => {
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on:
push:
branches: [master]
`)), []));
t.deepEqual(...errorCodes(actionsutil.getWorkflowErrors(yaml.safeLoad(`
name: "CodeQL"
on: ["push"]
`)), []));
});
ava_1.default("initializeEnvironment", (t) => {
util_1.initializeEnvironment(util_1.Mode.actions, "1.2.3");
t.deepEqual(util_1.getMode(), util_1.Mode.actions);
t.deepEqual(process.env.CODEQL_ACTION_VERSION, "1.2.3");
util_1.initializeEnvironment(util_1.Mode.runner, "4.5.6");
t.deepEqual(util_1.getMode(), util_1.Mode.runner);
t.deepEqual(process.env.CODEQL_ACTION_VERSION, "4.5.6");
});
ava_1.default("isAnalyzingDefaultBranch()", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
const envFile = path.join(tmpDir, "event.json");
fs.writeFileSync(envFile, JSON.stringify({
repository: {
default_branch: "main",
},
}));
process.env["GITHUB_EVENT_PATH"] = envFile;
process.env["GITHUB_REF"] = "main";
process.env["GITHUB_SHA"] = "1234";
t.deepEqual(await actionsutil.isAnalyzingDefaultBranch(), true);
process.env["GITHUB_REF"] = "refs/heads/main";
t.deepEqual(await actionsutil.isAnalyzingDefaultBranch(), true);
process.env["GITHUB_REF"] = "feature";
t.deepEqual(await actionsutil.isAnalyzingDefaultBranch(), false);
});
});
//# sourceMappingURL=actions-util.test.js.map

File diff suppressed because one or more lines are too long

64
lib/analysis-paths.js generated
View File

@@ -7,21 +7,63 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
function includeAndExcludeAnalysisPaths(config, languages) {
const path = __importStar(require("path"));
function isInterpretedLanguage(language) {
return (language === "javascript" || language === "python" || language === "ruby");
}
// Matches a string containing only characters that are legal to include in paths on windows.
exports.legalWindowsPathCharactersRegex = /^[^<>:"|?]*$/;
// Builds an environment variable suitable for LGTM_INDEX_INCLUDE or LGTM_INDEX_EXCLUDE
function buildIncludeExcludeEnvVar(paths) {
// Ignore anything containing a *
paths = paths.filter((p) => p.indexOf("*") === -1);
// Some characters are illegal in path names in windows
if (process.platform === "win32") {
paths = paths.filter((p) => p.match(exports.legalWindowsPathCharactersRegex));
}
return paths.join("\n");
}
function printPathFiltersWarning(config, logger) {
// Index include/exclude/filters only work in javascript and python.
// If any other languages are detected/configured then show a warning.
if ((config.paths.length !== 0 || config.pathsIgnore.length !== 0) &&
!config.languages.every(isInterpretedLanguage)) {
logger.warning('The "paths"/"paths-ignore" fields of the config only have effect for JavaScript and Python');
}
}
exports.printPathFiltersWarning = printPathFiltersWarning;
function includeAndExcludeAnalysisPaths(config) {
// The 'LGTM_INDEX_INCLUDE' and 'LGTM_INDEX_EXCLUDE' environment variables
// control which files/directories are traversed when scanning.
// This allows including files that otherwise would not be scanned, or
// excluding and not traversing entire file subtrees.
// It does not understand globs or double-globs because that would require it to
// traverse the entire file tree to determine which files are matched.
// Any paths containing "*" are not included in these.
if (config.paths.length !== 0) {
core.exportVariable('LGTM_INDEX_INCLUDE', config.paths.join('\n'));
process.env["LGTM_INDEX_INCLUDE"] = buildIncludeExcludeEnvVar(config.paths);
}
if (config.pathsIgnore.length !== 0) {
core.exportVariable('LGTM_INDEX_EXCLUDE', config.pathsIgnore.join('\n'));
// If the temporary or tools directory is in the working directory ignore that too.
const tempRelativeToWorking = path.relative(process.cwd(), config.tempDir);
const toolsRelativeToWorking = path.relative(process.cwd(), config.toolCacheDir);
let pathsIgnore = config.pathsIgnore;
if (!tempRelativeToWorking.startsWith("..")) {
pathsIgnore = pathsIgnore.concat(tempRelativeToWorking);
}
function isInterpretedLanguage(language) {
return language === 'javascript' && language === 'python';
if (!toolsRelativeToWorking.startsWith("..")) {
pathsIgnore = pathsIgnore.concat(toolsRelativeToWorking);
}
// Index include/exclude only work in javascript and python
// If some other language is detected/configured show a warning
if ((config.paths.length !== 0 || config.pathsIgnore.length !== 0) && !languages.every(isInterpretedLanguage)) {
core.warning('The "paths"/"paths-ignore" fields of the config only have effect for Javascript and Python');
if (pathsIgnore.length !== 0) {
process.env["LGTM_INDEX_EXCLUDE"] = buildIncludeExcludeEnvVar(pathsIgnore);
}
// The 'LGTM_INDEX_FILTERS' environment variable controls which files are
// extracted or ignored. It does not control which directories are traversed.
// This does understand the glob and double-glob syntax.
const filters = [];
filters.push(...config.paths.map((p) => `include:${p}`));
filters.push(...config.pathsIgnore.map((p) => `exclude:${p}`));
if (filters.length !== 0) {
process.env["LGTM_INDEX_FILTERS"] = filters.join("\n");
}
}
exports.includeAndExcludeAnalysisPaths = includeAndExcludeAnalysisPaths;

View File

@@ -1 +1 @@
{"version":3,"file":"analysis-paths.js","sourceRoot":"","sources":["../src/analysis-paths.ts"],"names":[],"mappings":";;;;;;;;;AAAA,oDAAsC;AAItC,SAAgB,8BAA8B,CAAC,MAA0B,EAAE,SAAmB;IAC1F,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;QAC3B,IAAI,CAAC,cAAc,CAAC,oBAAoB,EAAE,MAAM,CAA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AC,UAAU,CAAC,IAAI,CAAC,EAAE;QAC5C,WAAW,GAAG,WAAW,CAAC,MAAM,CAAC,sBAAsB,CAAC,CAAC;KAC1D;IACD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;QAC5B,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,GAAG,yBAAyB,CAAC,WAAW,CAAC,CAAC;KAC5E;IAED,yEAAyE;IACzE,6EAA6E;IAC7E,wDAAwD;IACxD,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;IACzD,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/D,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;QACxB,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;KACxD;AACH,CAAC;AArCD,wEAqCC"}

View File

@@ -1,7 +1,4 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
@@ -9,22 +6,78 @@ var __importStar = (this && this.__importStar) || function (mod) {
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(require("path"));
const ava_1 = __importDefault(require("ava"));
const analysisPaths = __importStar(require("./analysis-paths"));
const configUtils = __importStar(require("./config-utils"));
const testing_utils_1 = require("./testing-utils");
const util = __importStar(require("./util"));
testing_utils_1.setupTests(ava_1.default);
ava_1.default("emptyPaths", async (t) => {
let config = new configUtils.Config();
analysisPaths.includeAndExcludeAnalysisPaths(config, []);
t.is(process.env['LGTM_INDEX_INCLUDE'], undefined);
t.is(process.env['LGTM_INDEX_EXCLUDE'], undefined);
return await util.withTmpDir(async (tmpDir) => {
const config = {
languages: [],
queries: {},
pathsIgnore: [],
paths: [],
originalUserInput: {},
tempDir: tmpDir,
toolCacheDir: tmpDir,
codeQLCmd: "",
gitHubVersion: { type: util.GitHubVariant.DOTCOM },
dbLocation: path.resolve(tmpDir, "codeql_databases"),
packs: {},
};
analysisPaths.includeAndExcludeAnalysisPaths(config);
t.is(process.env["LGTM_INDEX_INCLUDE"], undefined);
t.is(process.env["LGTM_INDEX_EXCLUDE"], undefined);
t.is(process.env["LGTM_INDEX_FILTERS"], undefined);
});
});
ava_1.default("nonEmptyPaths", async (t) => {
let config = new configUtils.Config();
config.paths.push('path1', 'path2');
config.pathsIgnore.push('path3', 'path4');
analysisPaths.includeAndExcludeAnalysisPaths(config, []);
t.is(process.env['LGTM_INDEX_INCLUDE'], 'path1\npath2');
t.is(process.env['LGTM_INDEX_EXCLUDE'], 'path3\npath4');
return await util.withTmpDir(async (tmpDir) => {
const config = {
languages: [],
queries: {},
paths: ["path1", "path2", "**/path3"],
pathsIgnore: ["path4", "path5", "path6/**"],
originalUserInput: {},
tempDir: tmpDir,
toolCacheDir: tmpDir,
codeQLCmd: "",
gitHubVersion: { type: util.GitHubVariant.DOTCOM },
dbLocation: path.resolve(tmpDir, "codeql_databases"),
packs: {},
};
analysisPaths.includeAndExcludeAnalysisPaths(config);
t.is(process.env["LGTM_INDEX_INCLUDE"], "path1\npath2");
t.is(process.env["LGTM_INDEX_EXCLUDE"], "path4\npath5");
t.is(process.env["LGTM_INDEX_FILTERS"], "include:path1\ninclude:path2\ninclude:**/path3\nexclude:path4\nexclude:path5\nexclude:path6/**");
});
});
ava_1.default("exclude temp dir", async (t) => {
return await util.withTmpDir(async (toolCacheDir) => {
const tempDir = path.join(process.cwd(), "codeql-runner-temp");
const config = {
languages: [],
queries: {},
pathsIgnore: [],
paths: [],
originalUserInput: {},
tempDir,
toolCacheDir,
codeQLCmd: "",
gitHubVersion: { type: util.GitHubVariant.DOTCOM },
dbLocation: path.resolve(tempDir, "codeql_databases"),
packs: {},
};
analysisPaths.includeAndExcludeAnalysisPaths(config);
t.is(process.env["LGTM_INDEX_INCLUDE"], undefined);
t.is(process.env["LGTM_INDEX_EXCLUDE"], "codeql-runner-temp");
t.is(process.env["LGTM_INDEX_FILTERS"], undefined);
});
});
//# sourceMappingURL=analysis-paths.test.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"analysis-paths.test.js","sourceRoot":"","sources":["../src/analysis-paths.test.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,8CAAuB;AAEvB,gEAAkD;AAClD,4DAA8C;AAE9C,aAAI,CAAC,YAAY,EAAE,KAAK,EAAC,CAAC,EAAC,EAAE;IACzB,IAAI,MAAM,GAAG,IAAI,WAAW,CAAC,MAAM,EAAE,CAAC;IACtC,aAAa,CAAC,8BAA8B,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IACzD,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,EAAE,SAAS,CAAC,CAAC;IACnD,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,EAAE,SAAS,CAAC,CAAC;AACvD,CAAC,CAAC,CAAC;AAEH,aAAI,CAAC,eAAe,EAAE,KAAK,EAAC,CAAC,EAAC,EAAE;IAC5B,IAAI,MAAM,GAAG,IAAI,WAAW,CAAC,MAAM,EAAE,CAAC;IACtC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACpC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC1C,aAAa,CAAC,8BAA8B,C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,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,oBAAoB,CAAC,CAAC;QAC/D,MAAM,MAAM,GAAG;YACb,SAAS,EAAE,EAAE;YACb,OAAO,EAAE,EAAE;YACX,WAAW,EAAE,EAAE;YACf,KAAK,EAAE,EAAE;YACT,iBAAiB,EAAE,EAAE;YACrB,OAAO;YACP,YAAY;YACZ,SAAS,EAAE,EAAE;YACb,aAAa,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,MAAM,EAAwB;YACxE,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,kBAAkB,CAAC;YACrD,KAAK,EAAE,EAAE;SACV,CAAC;QACF,aAAa,CAAC,8BAA8B,CAAC,MAAM,CAAC,CAAC;QACrD,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,EAAE,SAAS,CAAC,CAAC;QACnD,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,EAAE,oBAAoB,CAAC,CAAC;QAC9D,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,EAAE,SAAS,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

132
lib/analyze-action.js generated Normal file
View File

@@ -0,0 +1,132 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const core = __importStar(require("@actions/core"));
const actionsUtil = __importStar(require("./actions-util"));
const analyze_1 = require("./analyze");
const config_utils_1 = require("./config-utils");
const database_upload_1 = require("./database-upload");
const logging_1 = require("./logging");
const repository_1 = require("./repository");
const upload_lib = __importStar(require("./upload-lib"));
const util = __importStar(require("./util"));
// eslint-disable-next-line import/no-commonjs
const pkg = require("../package.json");
async function sendStatusReport(startedAt, stats, error) {
var _a, _b, _c;
const status = ((_a = stats) === null || _a === void 0 ? void 0 : _a.analyze_failure_language) !== undefined || error !== undefined
? "failure"
: "success";
const statusReportBase = await actionsUtil.createStatusReportBase("finish", status, startedAt, (_b = error) === null || _b === void 0 ? void 0 : _b.message, (_c = error) === null || _c === void 0 ? void 0 : _c.stack);
const statusReport = {
...statusReportBase,
...(stats || {}),
};
await actionsUtil.sendStatusReport(statusReport);
}
async function run() {
const startedAt = new Date();
let uploadStats = undefined;
let runStats = undefined;
let config = undefined;
util.initializeEnvironment(util.Mode.actions, pkg.version);
try {
if (!(await actionsUtil.sendStatusReport(await actionsUtil.createStatusReportBase("finish", "starting", startedAt)))) {
return;
}
const logger = logging_1.getActionsLogger();
config = await config_utils_1.getConfig(actionsUtil.getTemporaryDirectory(), logger);
if (config === undefined) {
throw new Error("Config file could not be found at expected location. Has the 'init' action been called?");
}
const apiDetails = {
auth: actionsUtil.getRequiredInput("token"),
url: util.getRequiredEnvParam("GITHUB_SERVER_URL"),
};
const outputDir = actionsUtil.getRequiredInput("output");
const threads = util.getThreadsFlag(actionsUtil.getOptionalInput("threads"), logger);
await analyze_1.runFinalize(outputDir, threads, config, logger);
if (actionsUtil.getRequiredInput("skip-queries") !== "true") {
runStats = await analyze_1.runQueries(outputDir, util.getMemoryFlag(actionsUtil.getOptionalInput("ram")), util.getAddSnippetsFlag(actionsUtil.getRequiredInput("add-snippets")), threads, actionsUtil.getOptionalInput("category"), config, logger);
}
if (actionsUtil.getOptionalInput("cleanup-level") !== "none") {
await analyze_1.runCleanup(config, actionsUtil.getOptionalInput("cleanup-level") || "brutal", logger);
}
const dbLocations = {};
for (const language of config.languages) {
dbLocations[language] = util.getCodeQLDatabasePath(config, language);
}
core.setOutput("db-locations", dbLocations);
if (runStats && actionsUtil.getRequiredInput("upload") === "true") {
uploadStats = await upload_lib.uploadFromActions(outputDir, config.gitHubVersion, apiDetails, logger);
}
else {
logger.info("Not uploading results");
}
const repositoryNwo = repository_1.parseRepositoryNwo(util.getRequiredEnvParam("GITHUB_REPOSITORY"));
await database_upload_1.uploadDatabases(repositoryNwo, config, apiDetails, logger);
}
catch (error) {
core.setFailed(error.message);
console.log(error);
if (error instanceof analyze_1.CodeQLAnalysisError) {
const stats = { ...error.queriesStatusReport };
await sendStatusReport(startedAt, stats, error);
}
else {
await sendStatusReport(startedAt, undefined, error);
}
return;
}
finally {
if (core.isDebug() && config !== undefined) {
core.info("Debug mode is on. Printing CodeQL debug logs...");
for (const language of config.languages) {
const databaseDirectory = util.getCodeQLDatabasePath(config, language);
const logsDirectory = path.join(databaseDirectory, "log");
const walkLogFiles = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile()) {
core.startGroup(`CodeQL Debug Logs - ${language} - ${entry.name}`);
process.stdout.write(fs.readFileSync(path.resolve(dir, entry.name)));
core.endGroup();
}
else if (entry.isDirectory()) {
walkLogFiles(path.resolve(dir, entry.name));
}
}
};
walkLogFiles(logsDirectory);
}
}
}
if (runStats && uploadStats) {
await sendStatusReport(startedAt, { ...runStats, ...uploadStats });
}
else if (runStats) {
await sendStatusReport(startedAt, { ...runStats });
}
else {
await sendStatusReport(startedAt, undefined);
}
}
async function runWrapper() {
try {
await run();
}
catch (error) {
core.setFailed(`analyze action failed: ${error}`);
console.log(error);
}
}
void runWrapper();
//# sourceMappingURL=analyze-action.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"analyze-action.js","sourceRoot":"","sources":["../src/analyze-action.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAE7B,oDAAsC;AAEtC,4DAA8C;AAC9C,uCAMmB;AACnB,iDAAmD;AACnD,uDAAoD;AACpD,uCAA6C;AAC7C,6CAAkD;AAClD,yDAA2C;AAE3C,6CAA+B;AAE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AC;KACpB;AACH,CAAC;AAED,KAAK,UAAU,EAAE,CAAC"}

248
lib/analyze.js generated Normal file
View File

@@ -0,0 +1,248 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const toolrunner = __importStar(require("@actions/exec/lib/toolrunner"));
const yaml = __importStar(require("js-yaml"));
const analysisPaths = __importStar(require("./analysis-paths"));
const codeql_1 = require("./codeql");
const count_loc_1 = require("./count-loc");
const languages_1 = require("./languages");
const sharedEnv = __importStar(require("./shared-environment"));
const util = __importStar(require("./util"));
class CodeQLAnalysisError extends Error {
constructor(queriesStatusReport, message) {
super(message);
this.name = "CodeQLAnalysisError";
this.queriesStatusReport = queriesStatusReport;
}
}
exports.CodeQLAnalysisError = CodeQLAnalysisError;
async function setupPythonExtractor(logger) {
const codeqlPython = process.env["CODEQL_PYTHON"];
if (codeqlPython === undefined || codeqlPython.length === 0) {
// If CODEQL_PYTHON is not set, no dependencies were installed, so we don't need to do anything
return;
}
let output = "";
const options = {
listeners: {
stdout: (data) => {
output += data.toString();
},
},
};
await new toolrunner.ToolRunner(codeqlPython, [
"-c",
"import os; import pip; print(os.path.dirname(os.path.dirname(pip.__file__)))",
], options).exec();
logger.info(`Setting LGTM_INDEX_IMPORT_PATH=${output}`);
process.env["LGTM_INDEX_IMPORT_PATH"] = output;
output = "";
await new toolrunner.ToolRunner(codeqlPython, ["-c", "import sys; print(sys.version_info[0])"], options).exec();
logger.info(`Setting LGTM_PYTHON_SETUP_VERSION=${output}`);
process.env["LGTM_PYTHON_SETUP_VERSION"] = output;
}
async function createdDBForScannedLanguages(config, logger) {
// Insert the LGTM_INDEX_X env vars at this point so they are set when
// we extract any scanned languages.
analysisPaths.includeAndExcludeAnalysisPaths(config);
const codeql = codeql_1.getCodeQL(config.codeQLCmd);
for (const language of config.languages) {
if (languages_1.isScannedLanguage(language) &&
!dbIsFinalized(config, language, logger)) {
logger.startGroup(`Extracting ${language}`);
if (language === languages_1.Language.python) {
await setupPythonExtractor(logger);
}
await codeql.extractScannedLanguage(util.getCodeQLDatabasePath(config, language), language);
logger.endGroup();
}
}
}
function dbIsFinalized(config, language, logger) {
const dbPath = util.getCodeQLDatabasePath(config, language);
try {
const dbInfo = yaml.load(fs.readFileSync(path.resolve(dbPath, "codeql-database.yml"), "utf8"));
return !("inProgress" in dbInfo);
}
catch (e) {
logger.warning(`Could not check whether database for ${language} was finalized. Assuming it is not.`);
return false;
}
}
async function finalizeDatabaseCreation(config, threadsFlag, logger) {
await createdDBForScannedLanguages(config, logger);
const codeql = codeql_1.getCodeQL(config.codeQLCmd);
for (const language of config.languages) {
if (dbIsFinalized(config, language, logger)) {
logger.info(`There is already a finalized database for ${language} at the location where the CodeQL Action places databases, so we did not create one.`);
}
else {
logger.startGroup(`Finalizing ${language}`);
await codeql.finalizeDatabase(util.getCodeQLDatabasePath(config, language), threadsFlag);
logger.endGroup();
}
}
}
// Runs queries and creates sarif files in the given folder
async function runQueries(sarifFolder, memoryFlag, addSnippetsFlag, threadsFlag, automationDetailsId, config, logger) {
var _a, _b;
const statusReport = {};
// count the number of lines in the background
const locPromise = count_loc_1.countLoc(path.resolve(),
// config.paths specifies external directories. the current
// directory is included in the analysis by default. Replicate
// that here.
config.paths, config.pathsIgnore, config.languages, logger);
for (const language of config.languages) {
const queries = config.queries[language];
const packsWithVersion = config.packs[language] || [];
const hasBuiltinQueries = ((_a = queries) === null || _a === void 0 ? void 0 : _a.builtin.length) > 0;
const hasCustomQueries = ((_b = queries) === null || _b === void 0 ? void 0 : _b.custom.length) > 0;
const hasPackWithCustomQueries = packsWithVersion.length > 0;
if (!hasBuiltinQueries && !hasCustomQueries && !hasPackWithCustomQueries) {
throw new Error(`Unable to analyse ${language} as no queries were selected for this language`);
}
try {
if (hasPackWithCustomQueries) {
logger.info("*************");
logger.info("Performing analysis with custom QL Packs. QL Packs are an experimental feature.");
logger.info("And should not be used in production yet.");
logger.info("*************");
logger.startGroup(`Downloading custom packs for ${language}`);
const codeql = codeql_1.getCodeQL(config.codeQLCmd);
const results = await codeql.packDownload(packsWithVersion);
logger.info(`Downloaded packs: ${results.packs
.map((r) => `${r.name}@${r.version || "latest"}`)
.join(", ")}`);
logger.endGroup();
}
logger.startGroup(`Running queries for ${language}`);
const querySuitePaths = [];
if (queries["builtin"].length > 0) {
const startTimeBuiltIn = new Date().getTime();
querySuitePaths.push(await runQueryGroup(language, "builtin", createQuerySuiteContents(queries["builtin"]), undefined));
statusReport[`analyze_builtin_queries_${language}_duration_ms`] =
new Date().getTime() - startTimeBuiltIn;
}
const startTimeCustom = new Date().getTime();
let ranCustom = false;
for (let i = 0; i < queries["custom"].length; ++i) {
if (queries["custom"][i].queries.length > 0) {
querySuitePaths.push(await runQueryGroup(language, `custom-${i}`, createQuerySuiteContents(queries["custom"][i].queries), queries["custom"][i].searchPath));
ranCustom = true;
}
}
if (packsWithVersion.length > 0) {
querySuitePaths.push(await runQueryGroup(language, "packs", createPackSuiteContents(packsWithVersion), undefined));
ranCustom = true;
}
if (ranCustom) {
statusReport[`analyze_custom_queries_${language}_duration_ms`] =
new Date().getTime() - startTimeCustom;
}
logger.endGroup();
logger.startGroup(`Interpreting results for ${language}`);
const startTimeInterpretResults = new Date().getTime();
const sarifFile = path.join(sarifFolder, `${language}.sarif`);
const analysisSummary = await runInterpretResults(language, querySuitePaths, sarifFile);
await injectLinesOfCode(sarifFile, language, locPromise);
statusReport[`interpret_results_${language}_duration_ms`] =
new Date().getTime() - startTimeInterpretResults;
logger.endGroup();
logger.info(analysisSummary);
printLinesOfCodeSummary(logger, language, await locPromise);
}
catch (e) {
logger.info(e);
logger.info(e.stack);
statusReport.analyze_failure_language = language;
throw new CodeQLAnalysisError(statusReport, `Error running analysis for ${language}: ${e}`);
}
}
return statusReport;
async function runInterpretResults(language, queries, sarifFile) {
const databasePath = util.getCodeQLDatabasePath(config, language);
const codeql = codeql_1.getCodeQL(config.codeQLCmd);
return await codeql.databaseInterpretResults(databasePath, queries, sarifFile, addSnippetsFlag, threadsFlag, automationDetailsId);
}
async function runQueryGroup(language, type, querySuiteContents, searchPath) {
const databasePath = util.getCodeQLDatabasePath(config, language);
// Pass the queries to codeql using a file instead of using the command
// line to avoid command line length restrictions, particularly on windows.
const querySuitePath = `${databasePath}-queries-${type}.qls`;
fs.writeFileSync(querySuitePath, querySuiteContents);
logger.debug(`Query suite file for ${language}-${type}...\n${querySuiteContents}`);
const codeql = codeql_1.getCodeQL(config.codeQLCmd);
await codeql.databaseRunQueries(databasePath, searchPath, querySuitePath, memoryFlag, threadsFlag);
logger.debug(`BQRS results produced for ${language} (queries: ${type})"`);
return querySuitePath;
}
}
exports.runQueries = runQueries;
function createQuerySuiteContents(queries) {
return queries.map((q) => `- query: ${q}`).join("\n");
}
function createPackSuiteContents(packsWithVersion) {
return packsWithVersion.map(packWithVersionToQuerySuiteEntry).join("\n");
}
function packWithVersionToQuerySuiteEntry(pack) {
let text = `- qlpack: ${pack.packName}`;
if (pack.version) {
text += `\n version: ${pack.version}`;
}
return text;
}
async function runFinalize(outputDir, threadsFlag, config, logger) {
// Delete the tracer config env var to avoid tracing ourselves
delete process.env[sharedEnv.ODASA_TRACER_CONFIGURATION];
fs.mkdirSync(outputDir, { recursive: true });
await finalizeDatabaseCreation(config, threadsFlag, logger);
}
exports.runFinalize = runFinalize;
async function runCleanup(config, cleanupLevel, logger) {
logger.startGroup("Cleaning up databases");
for (const language of config.languages) {
const codeql = codeql_1.getCodeQL(config.codeQLCmd);
const databasePath = util.getCodeQLDatabasePath(config, language);
await codeql.databaseCleanup(databasePath, cleanupLevel);
}
logger.endGroup();
}
exports.runCleanup = runCleanup;
async function injectLinesOfCode(sarifFile, language, locPromise) {
const lineCounts = await locPromise;
const idPrefix = count_loc_1.getIdPrefix(language);
if (language in lineCounts) {
const sarif = JSON.parse(fs.readFileSync(sarifFile, "utf8"));
if (Array.isArray(sarif.runs)) {
for (const run of sarif.runs) {
const ruleId = `${idPrefix}/summary/lines-of-code`;
run.properties = run.properties || {};
run.properties.metricResults = run.properties.metricResults || [];
const rule = run.properties.metricResults.find(
// the rule id can be in either of two places
(r) => { var _a; return r.ruleId === ruleId || ((_a = r.rule) === null || _a === void 0 ? void 0 : _a.id) === ruleId; });
// only add the baseline value if the rule already exists
if (rule) {
rule.baseline = lineCounts[language];
}
}
}
fs.writeFileSync(sarifFile, JSON.stringify(sarif));
}
}
function printLinesOfCodeSummary(logger, language, lineCounts) {
if (language in lineCounts) {
logger.info(`Counted a baseline of ${lineCounts[language]} lines of code for ${language}.`);
}
}
//# sourceMappingURL=analyze.js.map

1
lib/analyze.js.map Normal file

File diff suppressed because one or more lines are too long

231
lib/analyze.test.js generated Normal file
View File

@@ -0,0 +1,231 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ava_1 = __importDefault(require("ava"));
const yaml = __importStar(require("js-yaml"));
const semver_1 = require("semver");
const sinon_1 = __importDefault(require("sinon"));
const analyze_1 = require("./analyze");
const codeql_1 = require("./codeql");
const count_loc_1 = require("./count-loc");
const count = __importStar(require("./count-loc"));
const languages_1 = require("./languages");
const logging_1 = require("./logging");
const testing_utils_1 = require("./testing-utils");
const util = __importStar(require("./util"));
testing_utils_1.setupTests(ava_1.default);
// Checks that the duration fields are populated for the correct language
// and correct case of builtin or custom. Also checks the correct search
// paths are set in the database analyze invocation.
ava_1.default("status report fields and search path setting", async (t) => {
const mockLinesOfCode = Object.values(languages_1.Language).reduce((obj, lang, i) => {
// use a different line count for each language
obj[lang] = i + 1;
return obj;
}, {});
sinon_1.default.stub(count, "countLoc").resolves(mockLinesOfCode);
let searchPathsUsed = [];
return await util.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
const memoryFlag = "";
const addSnippetsFlag = "";
const threadsFlag = "";
const packs = {
[languages_1.Language.cpp]: [
{
packName: "a/b",
version: semver_1.clean("1.0.0"),
},
],
[languages_1.Language.java]: [
{
packName: "c/d",
version: semver_1.clean("2.0.0"),
},
],
};
for (const language of Object.values(languages_1.Language)) {
codeql_1.setCodeQL({
packDownload: async () => ({ packs: [] }),
databaseRunQueries: async (_db, searchPath) => {
searchPathsUsed.push(searchPath);
},
databaseInterpretResults: async (_db, _queriesRun, sarifFile) => {
fs.writeFileSync(sarifFile, JSON.stringify({
runs: [
// variant 1 uses ruleId
{
properties: {
metricResults: [
{
ruleId: `${count_loc_1.getIdPrefix(language)}/summary/lines-of-code`,
value: 123,
},
],
},
},
// variant 2 uses rule.id
{
properties: {
metricResults: [
{
rule: {
id: `${count_loc_1.getIdPrefix(language)}/summary/lines-of-code`,
},
value: 123,
},
],
},
},
{},
],
}));
return "";
},
});
searchPathsUsed = [];
const config = {
languages: [language],
queries: {},
pathsIgnore: [],
paths: [],
originalUserInput: {},
tempDir: tmpDir,
toolCacheDir: tmpDir,
codeQLCmd: "",
gitHubVersion: {
type: util.GitHubVariant.DOTCOM,
},
dbLocation: path.resolve(tmpDir, "codeql_databases"),
packs,
};
fs.mkdirSync(util.getCodeQLDatabasePath(config, language), {
recursive: true,
});
config.queries[language] = {
builtin: ["foo.ql"],
custom: [],
};
const builtinStatusReport = await analyze_1.runQueries(tmpDir, memoryFlag, addSnippetsFlag, threadsFlag, undefined, config, logging_1.getRunnerLogger(true));
const hasPacks = language in packs;
const statusReportKeys = Object.keys(builtinStatusReport).sort();
if (hasPacks) {
t.deepEqual(statusReportKeys.length, 3, statusReportKeys.toString());
t.deepEqual(statusReportKeys[0], `analyze_builtin_queries_${language}_duration_ms`);
t.deepEqual(statusReportKeys[1], `analyze_custom_queries_${language}_duration_ms`);
t.deepEqual(statusReportKeys[2], `interpret_results_${language}_duration_ms`);
}
else {
t.deepEqual(statusReportKeys[0], `analyze_builtin_queries_${language}_duration_ms`);
t.deepEqual(statusReportKeys[1], `interpret_results_${language}_duration_ms`);
}
config.queries[language] = {
builtin: [],
custom: [
{
queries: ["foo.ql"],
searchPath: "/1",
},
{
queries: ["bar.ql"],
searchPath: "/2",
},
],
};
const customStatusReport = await analyze_1.runQueries(tmpDir, memoryFlag, addSnippetsFlag, threadsFlag, undefined, config, logging_1.getRunnerLogger(true));
t.deepEqual(Object.keys(customStatusReport).length, 2);
t.true(`analyze_custom_queries_${language}_duration_ms` in customStatusReport);
const expectedSearchPathsUsed = hasPacks
? [undefined, undefined, "/1", "/2", undefined]
: [undefined, "/1", "/2"];
t.deepEqual(searchPathsUsed, expectedSearchPathsUsed);
t.true(`interpret_results_${language}_duration_ms` in customStatusReport);
}
verifyLineCounts(tmpDir);
verifyQuerySuites(tmpDir);
});
function verifyLineCounts(tmpDir) {
// eslint-disable-next-line github/array-foreach
Object.keys(languages_1.Language).forEach((lang, i) => {
verifyLineCountForFile(lang, path.join(tmpDir, `${lang}.sarif`), i + 1);
});
}
function verifyLineCountForFile(lang, filePath, lineCount) {
const idPrefix = count_loc_1.getIdPrefix(lang);
const sarif = JSON.parse(fs.readFileSync(filePath, "utf8"));
t.deepEqual(sarif.runs[0].properties.metricResults, [
{
ruleId: `${idPrefix}/summary/lines-of-code`,
value: 123,
baseline: lineCount,
},
]);
t.deepEqual(sarif.runs[1].properties.metricResults, [
{
rule: {
id: `${idPrefix}/summary/lines-of-code`,
},
value: 123,
baseline: lineCount,
},
]);
// when the rule doesn't exist, it should not be added
t.deepEqual(sarif.runs[2].properties.metricResults, []);
}
function verifyQuerySuites(tmpDir) {
const qlsContent = [
{
query: "foo.ql",
},
];
const qlsContent2 = [
{
query: "bar.ql",
},
];
const qlsPackContentCpp = [
{
qlpack: "a/b",
version: "1.0.0",
},
];
const qlsPackContentJava = [
{
qlpack: "c/d",
version: "2.0.0",
},
];
for (const lang of Object.values(languages_1.Language)) {
t.deepEqual(readContents(`${lang}-queries-builtin.qls`), qlsContent);
t.deepEqual(readContents(`${lang}-queries-custom-0.qls`), qlsContent);
t.deepEqual(readContents(`${lang}-queries-custom-1.qls`), qlsContent2);
const packSuiteName = `${lang}-queries-packs.qls`;
if (lang === languages_1.Language.cpp) {
t.deepEqual(readContents(packSuiteName), qlsPackContentCpp);
}
else if (lang === languages_1.Language.java) {
t.deepEqual(readContents(packSuiteName), qlsPackContentJava);
}
else {
t.false(fs.existsSync(path.join(tmpDir, "codeql_databases", packSuiteName)));
}
}
function readContents(name) {
const x = fs.readFileSync(path.join(tmpDir, "codeql_databases", name), "utf8");
console.log(x);
return yaml.safeLoad(fs.readFileSync(path.join(tmpDir, "codeql_databases", name), "utf8"));
}
}
});
//# sourceMappingURL=analyze.test.js.map

1
lib/analyze.test.js.map Normal file

File diff suppressed because one or more lines are too long

57
lib/api-client.js generated Normal file
View File

@@ -0,0 +1,57 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(require("path"));
const githubUtils = __importStar(require("@actions/github/lib/utils"));
const retry = __importStar(require("@octokit/plugin-retry"));
const console_log_level_1 = __importDefault(require("console-log-level"));
const actions_util_1 = require("./actions-util");
const util_1 = require("./util");
// eslint-disable-next-line import/no-commonjs
const pkg = require("../package.json");
var DisallowedAPIVersionReason;
(function (DisallowedAPIVersionReason) {
DisallowedAPIVersionReason[DisallowedAPIVersionReason["ACTION_TOO_OLD"] = 0] = "ACTION_TOO_OLD";
DisallowedAPIVersionReason[DisallowedAPIVersionReason["ACTION_TOO_NEW"] = 1] = "ACTION_TOO_NEW";
})(DisallowedAPIVersionReason = exports.DisallowedAPIVersionReason || (exports.DisallowedAPIVersionReason = {}));
exports.getApiClient = function (apiDetails, { allowExternal = false } = {}) {
const auth = (allowExternal && apiDetails.externalRepoAuth) || apiDetails.auth;
const retryingOctokit = githubUtils.GitHub.plugin(retry.retry);
return new retryingOctokit(githubUtils.getOctokitOptions(auth, {
baseUrl: getApiUrl(apiDetails.url),
userAgent: `CodeQL-${util_1.getMode()}/${pkg.version}`,
log: console_log_level_1.default({ level: "debug" }),
}));
};
function getApiUrl(githubUrl) {
const url = new URL(githubUrl);
// If we detect this is trying to connect to github.com
// then return with a fixed canonical URL.
if (url.hostname === "github.com" || url.hostname === "api.github.com") {
return "https://api.github.com";
}
// Add the /api/v3 API prefix
url.pathname = path.join(url.pathname, "api", "v3");
return url.toString();
}
// Temporary function to aid in the transition to running on and off of github actions.
// Once all code has been converted this function should be removed or made canonical
// and called only from the action entrypoints.
function getActionsApiClient() {
const apiDetails = {
auth: actions_util_1.getRequiredInput("token"),
url: util_1.getRequiredEnvParam("GITHUB_SERVER_URL"),
};
return exports.getApiClient(apiDetails);
}
exports.getActionsApiClient = getActionsApiClient;
//# sourceMappingURL=api-client.js.map

1
lib/api-client.js.map Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"api-client.js","sourceRoot":"","sources":["../src/api-client.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAA6B;AAE7B,uEAAyD;AACzD,6DAA+C;AAC/C,0EAAgD;AAEhD,iDAAkD;AAClD,iCAAsD;AAEtD,8CAA8C;AAC9C,MAAM,GAAG,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAEvC,IAAY,0BAGX;AAHD,WAAY,0BAA0B;IACpC,+FAAc,CAAA;IACd,+FAAc,CAAA;AAChB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mB,CAAC;KAC9C,CAAC;IAEF,OAAO,oBAAY,CAAC,UAAU,CAAC,CAAC;AAClC,CAAC;AAPD,kDAOC"}

79
lib/api-client.test.js generated Normal file
View File

@@ -0,0 +1,79 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const githubUtils = __importStar(require("@actions/github/lib/utils"));
const ava_1 = __importDefault(require("ava"));
const sinon_1 = __importDefault(require("sinon"));
const api_client_1 = require("./api-client");
const testing_utils_1 = require("./testing-utils");
const util_1 = require("./util");
// eslint-disable-next-line import/no-commonjs
const pkg = require("../package.json");
testing_utils_1.setupTests(ava_1.default);
let pluginStub;
let githubStub;
ava_1.default.beforeEach(() => {
pluginStub = sinon_1.default.stub(githubUtils.GitHub, "plugin");
githubStub = sinon_1.default.stub();
pluginStub.returns(githubStub);
util_1.initializeEnvironment(util_1.Mode.actions, pkg.version);
});
ava_1.default("Get the client API", async (t) => {
doTest(t, {
auth: "xyz",
externalRepoAuth: "abc",
url: "http://hucairz",
}, undefined, {
auth: "token xyz",
baseUrl: "http://hucairz/api/v3",
userAgent: `CodeQL-Action/${pkg.version}`,
});
});
ava_1.default("Get the client API external", async (t) => {
doTest(t, {
auth: "xyz",
externalRepoAuth: "abc",
url: "http://hucairz",
}, { allowExternal: true }, {
auth: "token abc",
baseUrl: "http://hucairz/api/v3",
userAgent: `CodeQL-Action/${pkg.version}`,
});
});
ava_1.default("Get the client API external not present", async (t) => {
doTest(t, {
auth: "xyz",
url: "http://hucairz",
}, { allowExternal: true }, {
auth: "token xyz",
baseUrl: "http://hucairz/api/v3",
userAgent: `CodeQL-Action/${pkg.version}`,
});
});
ava_1.default("Get the client API with github url", async (t) => {
doTest(t, {
auth: "xyz",
url: "https://github.com/some/invalid/url",
}, undefined, {
auth: "token xyz",
baseUrl: "https://api.github.com",
userAgent: `CodeQL-Action/${pkg.version}`,
});
});
function doTest(t, clientArgs, clientOptions, expected) {
api_client_1.getApiClient(clientArgs, clientOptions);
const firstCallArgs = githubStub.args[0];
// log is a function, so we don't need to test for equality of it
delete firstCallArgs[0].log;
t.deepEqual(firstCallArgs, [expected]);
}
//# sourceMappingURL=api-client.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"api-client.test.js","sourceRoot":"","sources":["../src/api-client.test.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uEAAyD;AACzD,8CAA6C;AAC7C,kDAA0B;AAE1B,6CAA4C;AAC5C,mDAA6C;AAC7C,iCAAqD;AAErD,8CAA8C;AAC9C,MAAM,GAAG,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAEvC,0BAAU,CAAC,aAAI,CAAC,CAAC;AAEjB,IAAI,UAA2B,CAAC;AAChC,IAAI,UAA2B,CAAC;AAEhC,aAAI,CAAC,UAAU,CAAC,GAAG,EAAE;IACnB,UAAU,GAAG,eAAK,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACtD,UAAU,GAAG,eAAK,CAAC,IAAI,EAAE,CAAC;IAC1B,UAAU,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAC/B,4BAAqB,CAAC,WAAI,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;AACnD,CAAC,CAAC,CAAC;AAEH,aAAI,CAAC,oBAAoB,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE;IACrC,MAAM,CACJ,CAAC,EACD;QACE,IAAI,EAAE,KAAK;QACX,gBAAgB,EAAE,KAAK;QACvB,GAAG,EAAE,gBAAgB;KACtB,EACD,SAAS,EACT;QACE,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,uBAAuB;QAChC,SAAS,EAAE,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AC,CAAC,CAAC;IACzC,iEAAiE;IACjE,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IAC5B,CAAC,CAAC,SAAS,CAAC,aAAa,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;AACzC,CAAC"}

View File

@@ -0,0 +1 @@
{ "maximumVersion": "3.2", "minimumVersion": "2.22" }

67
lib/autobuild-action.js generated Normal file
View File

@@ -0,0 +1,67 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const actions_util_1 = require("./actions-util");
const autobuild_1 = require("./autobuild");
const config_utils = __importStar(require("./config-utils"));
const logging_1 = require("./logging");
const util_1 = require("./util");
// eslint-disable-next-line import/no-commonjs
const pkg = require("../package.json");
async function sendCompletedStatusReport(startedAt, allLanguages, failingLanguage, cause) {
var _a, _b;
util_1.initializeEnvironment(util_1.Mode.actions, pkg.version);
const status = failingLanguage !== undefined || cause !== undefined
? "failure"
: "success";
const statusReportBase = await actions_util_1.createStatusReportBase("autobuild", status, startedAt, (_a = cause) === null || _a === void 0 ? void 0 : _a.message, (_b = cause) === null || _b === void 0 ? void 0 : _b.stack);
const statusReport = {
...statusReportBase,
autobuild_languages: allLanguages.join(","),
autobuild_failure: failingLanguage,
};
await actions_util_1.sendStatusReport(statusReport);
}
async function run() {
const logger = logging_1.getActionsLogger();
const startedAt = new Date();
let language = undefined;
try {
if (!(await actions_util_1.sendStatusReport(await actions_util_1.createStatusReportBase("autobuild", "starting", startedAt)))) {
return;
}
const config = await config_utils.getConfig(actions_util_1.getTemporaryDirectory(), logger);
if (config === undefined) {
throw new Error("Config file could not be found at expected location. Has the 'init' action been called?");
}
language = autobuild_1.determineAutobuildLanguage(config, logger);
if (language !== undefined) {
await autobuild_1.runAutobuild(language, config, logger);
}
}
catch (error) {
core.setFailed(`We were unable to automatically build your code. Please replace the call to the autobuild action with your custom build steps. ${error.message}`);
console.log(error);
await sendCompletedStatusReport(startedAt, language ? [language] : [], language, error);
return;
}
await sendCompletedStatusReport(startedAt, language ? [language] : []);
}
async function runWrapper() {
try {
await run();
}
catch (error) {
core.setFailed(`autobuild action failed. ${error}`);
console.log(error);
}
}
void runWrapper();
//# sourceMappingURL=autobuild-action.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autobuild-action.js","sourceRoot":"","sources":["../src/autobuild-action.ts"],"names":[],"mappings":";;;;;;;;;AAAA,oDAAsC;AAEtC,iDAKwB;AACxB,2CAAuE;AACvE,6DAA+C;AAE/C,uCAA6C;AAC7C,iCAAqD;AAErD,8CAA8C;AAC9C,MAAM,GAAG,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AASvC,KAAK,UAAU,yBAAyB,CACtC,SAAe,EACf,YAAsB,EACtB,eAAwB,EACxB,KAAa;;IAEb,4BAAqB,CAAC,WAAI,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IAEjD,MAAM,MAAM,GACV,eAAe,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS;QAClD,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,SAAS,CAAC;IAChB,MAAM,gBAAgB,GAAG,MAAM,qCAAsB,CACnD,WAAW,EACX,MAAM,EACN,SAAS,QACT,KAAK,0CAAE,OAAO,QACd,KAAK,0CAAE,KAAK,CACb,CAAC;IACF,MAAM,YAAY,GAA0B;QAC1C,GAAG,gBAAgB;QACnB,mBAAmB,EAAE,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC;QAC3C,iBAAiB,EAAE,eAAe;KACnC,CAAC;IACF,MAAM,+BAAgB,CAAC,YAAY,CAAC,CAAC;AACvC,CAAC;AAED,KAAK,UAAU,GAAG;IAChB,MAAM,MAAM,GAAG,0BAAgB,EAAE,CAAC;IAClC,MAAM,SA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;AAED,KAAK,UAAU,EAAE,CAAC"}

81
lib/autobuild.js generated
View File

@@ -1,61 +1,32 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec"));
const path = __importStar(require("path"));
const sharedEnv = __importStar(require("./shared-environment"));
const util = __importStar(require("./util"));
async function run() {
var _a;
try {
if (util.should_abort('autobuild', true) || !await util.reportActionStarting('autobuild')) {
return;
}
// Attempt to find a language to autobuild
// We want pick the dominant language in the repo from the ones we're able to build
// The languages are sorted in order specified by user or by lines of code if we got
// them from the GitHub API, so try to build the first language on the list.
const autobuildLanguages = ((_a = process.env[sharedEnv.CODEQL_ACTION_TRACED_LANGUAGES]) === null || _a === void 0 ? void 0 : _a.split(',')) || [];
const language = autobuildLanguages[0];
if (!language) {
core.info("None of the languages in this project require extra build steps");
return;
}
core.debug(`Detected dominant traced language: ${language}`);
if (autobuildLanguages.length > 1) {
core.warning(`We will only automatically build ${language} code. If you wish to scan ${autobuildLanguages.slice(1).join(' and ')}, you must replace this block with custom build steps.`);
}
core.startGroup(`Attempting to automatically build ${language} code`);
// TODO: share config accross actions better via env variables
const codeqlCmd = util.getRequiredEnvParam(sharedEnv.CODEQL_ACTION_CMD);
const cmdName = process.platform === 'win32' ? 'autobuild.cmd' : 'autobuild.sh';
const autobuildCmd = path.join(path.dirname(codeqlCmd), language, 'tools', cmdName);
// Update JAVA_TOOL_OPTIONS to contain '-Dhttp.keepAlive=false'
// This is because of an issue with Azure pipelines timing out connections after 4 minutes
// and Maven not properly handling closed connections
// Otherwise long build processes will timeout when pulling down Java packages
// https://developercommunity.visualstudio.com/content/problem/292284/maven-hosted-agent-connection-timeout.html
let javaToolOptions = process.env['JAVA_TOOL_OPTIONS'] || "";
process.env['JAVA_TOOL_OPTIONS'] = [...javaToolOptions.split(/\s+/), '-Dhttp.keepAlive=false', '-Dmaven.wagon.http.pool=false'].join(' ');
await exec.exec(autobuildCmd);
core.endGroup();
const codeql_1 = require("./codeql");
const languages_1 = require("./languages");
function determineAutobuildLanguage(config, logger) {
// Attempt to find a language to autobuild
// We want pick the dominant language in the repo from the ones we're able to build
// The languages are sorted in order specified by user or by lines of code if we got
// them from the GitHub API, so try to build the first language on the list.
const autobuildLanguages = config.languages.filter(languages_1.isTracedLanguage);
const language = autobuildLanguages[0];
if (!language) {
logger.info("None of the languages in this project require extra build steps");
return undefined;
}
catch (error) {
core.setFailed("We were unable to automatically build your code. Please replace the call to the autobuild action with your custom build steps. " + error.message);
await util.reportActionFailed('autobuild', error.message, error.stack);
return;
logger.debug(`Detected dominant traced language: ${language}`);
if (autobuildLanguages.length > 1) {
logger.warning(`We will only automatically build ${language} code. If you wish to scan ${autobuildLanguages
.slice(1)
.join(" and ")}, you must replace this call with custom build steps.`);
}
await util.reportActionSucceeded('autobuild');
return language;
}
run().catch(e => {
core.setFailed("autobuild action failed. " + e);
console.log(e);
});
exports.determineAutobuildLanguage = determineAutobuildLanguage;
async function runAutobuild(language, config, logger) {
logger.startGroup(`Attempting to automatically build ${language} code`);
const codeQL = codeql_1.getCodeQL(config.codeQLCmd);
await codeQL.runAutobuild(language);
logger.endGroup();
}
exports.runAutobuild = runAutobuild;
//# sourceMappingURL=autobuild.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"autobuild.js","sourceRoot":"","sources":["../src/autobuild.ts"],"names":[],"mappings":";;;;;;;;;AAAA,oDAAsC;AACtC,oDAAsC;AACtC,2CAA6B;AAE7B,gEAAkD;AAClD,6CAA+B;AAE/B,KAAK,UAAU,GAAG;;IAChB,IAAI;QACF,IAAI,IAAI,CAAC,YAAY,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,WAAW,CAAC,EAAE;Y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AAkB,CAAC,MAAM,GAAG,CAAC,EAAE;QACjC,MAAM,CAAC,OAAO,CACZ,oCAAoC,QAAQ,8BAA8B,kBAAkB;aACzF,KAAK,CAAC,CAAC,CAAC;aACR,IAAI,CAAC,OAAO,CAAC,uDAAuD,CACxE,CAAC;KACH;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AA7BD,gEA6BC;AAEM,KAAK,UAAU,YAAY,CAChC,QAAkB,EAClB,MAA2B,EAC3B,MAAc;IAEd,MAAM,CAAC,UAAU,CAAC,qCAAqC,QAAQ,OAAO,CAAC,CAAC;IACxE,MAAM,MAAM,GAAG,kBAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC3C,MAAM,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;IACpC,MAAM,CAAC,QAAQ,EAAE,CAAC;AACpB,CAAC;AATD,oCASC"}

624
lib/codeql.js generated Normal file
View File

@@ -0,0 +1,624 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const toolrunner = __importStar(require("@actions/exec/lib/toolrunner"));
const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
const query_string_1 = __importDefault(require("query-string"));
const semver = __importStar(require("semver"));
const actions_util_1 = require("./actions-util");
const api = __importStar(require("./api-client"));
const defaults = __importStar(require("./defaults.json")); // Referenced from codeql-action-sync-tool!
const error_matcher_1 = require("./error-matcher");
const toolcache = __importStar(require("./toolcache"));
const toolrunner_error_catcher_1 = require("./toolrunner-error-catcher");
const util = __importStar(require("./util"));
class CommandInvocationError extends Error {
constructor(cmd, args, exitCode, error) {
super(`Failure invoking ${cmd} with arguments ${args}.\n
Exit code ${exitCode} and error was:\n
${error}`);
}
}
exports.CommandInvocationError = CommandInvocationError;
/**
* Stores the CodeQL object, and is populated by `setupCodeQL` or `getCodeQL`.
* Can be overridden in tests using `setCodeQL`.
*/
let cachedCodeQL = undefined;
const CODEQL_BUNDLE_VERSION = defaults.bundleVersion;
const CODEQL_DEFAULT_ACTION_REPOSITORY = "github/codeql-action";
function getCodeQLBundleName() {
let platform;
if (process.platform === "win32") {
platform = "win64";
}
else if (process.platform === "linux") {
platform = "linux64";
}
else if (process.platform === "darwin") {
platform = "osx64";
}
else {
return "codeql-bundle.tar.gz";
}
return `codeql-bundle-${platform}.tar.gz`;
}
function getCodeQLActionRepository(logger) {
if (!util.isActions()) {
return CODEQL_DEFAULT_ACTION_REPOSITORY;
}
else {
return getActionsCodeQLActionRepository(logger);
}
}
exports.getCodeQLActionRepository = getCodeQLActionRepository;
function getActionsCodeQLActionRepository(logger) {
if (process.env["GITHUB_ACTION_REPOSITORY"] !== undefined) {
return process.env["GITHUB_ACTION_REPOSITORY"];
}
// The Actions Runner used with GitHub Enterprise Server 2.22 did not set the GITHUB_ACTION_REPOSITORY variable.
// This fallback logic can be removed after the end-of-support for 2.22 on 2021-09-23.
if (actions_util_1.isRunningLocalAction()) {
// This handles the case where the Action does not come from an Action repository,
// e.g. our integration tests which use the Action code from the current checkout.
logger.info("The CodeQL Action is checked out locally. Using the default CodeQL Action repository.");
return CODEQL_DEFAULT_ACTION_REPOSITORY;
}
logger.info("GITHUB_ACTION_REPOSITORY environment variable was not set. Falling back to legacy method of finding the GitHub Action.");
const relativeScriptPathParts = actions_util_1.getRelativeScriptPath().split(path.sep);
return `${relativeScriptPathParts[0]}/${relativeScriptPathParts[1]}`;
}
async function getCodeQLBundleDownloadURL(apiDetails, variant, logger) {
const codeQLActionRepository = getCodeQLActionRepository(logger);
const potentialDownloadSources = [
// This GitHub instance, and this Action.
[apiDetails.url, codeQLActionRepository],
// This GitHub instance, and the canonical Action.
[apiDetails.url, CODEQL_DEFAULT_ACTION_REPOSITORY],
// GitHub.com, and the canonical Action.
[util.GITHUB_DOTCOM_URL, CODEQL_DEFAULT_ACTION_REPOSITORY],
];
// We now filter out any duplicates.
// Duplicates will happen either because the GitHub instance is GitHub.com, or because the Action is not a fork.
const uniqueDownloadSources = potentialDownloadSources.filter((source, index, self) => {
return !self.slice(0, index).some((other) => fast_deep_equal_1.default(source, other));
});
const codeQLBundleName = getCodeQLBundleName();
if (variant === util.GitHubVariant.GHAE) {
try {
const release = await api
.getApiClient(apiDetails)
.request("GET /enterprise/code-scanning/codeql-bundle/find/{tag}", {
tag: CODEQL_BUNDLE_VERSION,
});
const assetID = release.data.assets[codeQLBundleName];
if (assetID !== undefined) {
const download = await api
.getApiClient(apiDetails)
.request("GET /enterprise/code-scanning/codeql-bundle/download/{asset_id}", { asset_id: assetID });
const downloadURL = download.data.url;
logger.info(`Found CodeQL bundle at GitHub AE endpoint with URL ${downloadURL}.`);
return downloadURL;
}
else {
logger.info(`Attempted to fetch bundle from GitHub AE endpoint but the bundle ${codeQLBundleName} was not found in the assets ${JSON.stringify(release.data.assets)}.`);
}
}
catch (e) {
logger.info(`Attempted to fetch bundle from GitHub AE endpoint but got error ${e}.`);
}
}
for (const downloadSource of uniqueDownloadSources) {
const [apiURL, repository] = downloadSource;
// If we've reached the final case, short-circuit the API check since we know the bundle exists and is public.
if (apiURL === util.GITHUB_DOTCOM_URL &&
repository === CODEQL_DEFAULT_ACTION_REPOSITORY) {
break;
}
const [repositoryOwner, repositoryName] = repository.split("/");
try {
const release = await api.getApiClient(apiDetails).repos.getReleaseByTag({
owner: repositoryOwner,
repo: repositoryName,
tag: CODEQL_BUNDLE_VERSION,
});
for (const asset of release.data.assets) {
if (asset.name === codeQLBundleName) {
logger.info(`Found CodeQL bundle in ${downloadSource[1]} on ${downloadSource[0]} with URL ${asset.url}.`);
return asset.url;
}
}
}
catch (e) {
logger.info(`Looked for CodeQL bundle in ${downloadSource[1]} on ${downloadSource[0]} but got error ${e}.`);
}
}
return `https://github.com/${CODEQL_DEFAULT_ACTION_REPOSITORY}/releases/download/${CODEQL_BUNDLE_VERSION}/${codeQLBundleName}`;
}
async function setupCodeQL(codeqlURL, apiDetails, tempDir, toolCacheDir, variant, logger) {
try {
// We use the special value of 'latest' to prioritize the version in the
// defaults over any pinned cached version.
const forceLatest = codeqlURL === "latest";
if (forceLatest) {
codeqlURL = undefined;
}
let codeqlFolder;
let codeqlURLVersion;
if (codeqlURL && !codeqlURL.startsWith("http")) {
codeqlFolder = await toolcache.extractTar(codeqlURL, tempDir, logger);
codeqlURLVersion = "local";
}
else {
codeqlURLVersion = getCodeQLURLVersion(codeqlURL || `/${CODEQL_BUNDLE_VERSION}/`);
const codeqlURLSemVer = convertToSemVer(codeqlURLVersion, logger);
// If we find the specified version, we always use that.
codeqlFolder = toolcache.find("CodeQL", codeqlURLSemVer, toolCacheDir, logger);
// If we don't find the requested version, in some cases we may allow a
// different version to save download time if the version hasn't been
// specified explicitly (in which case we always honor it).
if (!codeqlFolder && !codeqlURL && !forceLatest) {
const codeqlVersions = toolcache.findAllVersions("CodeQL", toolCacheDir, logger);
if (codeqlVersions.length === 1) {
const tmpCodeqlFolder = toolcache.find("CodeQL", codeqlVersions[0], toolCacheDir, logger);
if (fs.existsSync(path.join(tmpCodeqlFolder, "pinned-version"))) {
logger.debug(`CodeQL in cache overriding the default ${CODEQL_BUNDLE_VERSION}`);
codeqlFolder = tmpCodeqlFolder;
}
}
}
if (codeqlFolder) {
logger.debug(`CodeQL found in cache ${codeqlFolder}`);
}
else {
if (!codeqlURL) {
codeqlURL = await getCodeQLBundleDownloadURL(apiDetails, variant, logger);
}
const parsedCodeQLURL = new URL(codeqlURL);
const parsedQueryString = query_string_1.default.parse(parsedCodeQLURL.search);
const headers = { accept: "application/octet-stream" };
// 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.
// We also don't want to send an authorization header if there's already a token provided in the URL.
if (codeqlURL.startsWith(`${apiDetails.url}/`) &&
parsedQueryString["token"] === undefined) {
logger.debug("Downloading CodeQL bundle with token.");
headers.authorization = `token ${apiDetails.auth}`;
}
else {
logger.debug("Downloading CodeQL bundle without token.");
}
logger.info(`Downloading CodeQL tools from ${codeqlURL}. This may take a while.`);
const codeqlPath = await toolcache.downloadTool(codeqlURL, tempDir, headers);
logger.debug(`CodeQL bundle download to ${codeqlPath} complete.`);
const codeqlExtracted = await toolcache.extractTar(codeqlPath, tempDir, logger);
codeqlFolder = await toolcache.cacheDir(codeqlExtracted, "CodeQL", codeqlURLSemVer, toolCacheDir, logger);
}
}
let codeqlCmd = path.join(codeqlFolder, "codeql", "codeql");
if (process.platform === "win32") {
codeqlCmd += ".exe";
}
else if (process.platform !== "linux" && process.platform !== "darwin") {
throw new Error(`Unsupported platform: ${process.platform}`);
}
cachedCodeQL = getCodeQLForCmd(codeqlCmd);
return { codeql: cachedCodeQL, toolsVersion: codeqlURLVersion };
}
catch (e) {
logger.error(e);
throw new Error("Unable to download and extract CodeQL CLI");
}
}
exports.setupCodeQL = setupCodeQL;
function getCodeQLURLVersion(url) {
const match = url.match(/\/codeql-bundle-(.*)\//);
if (match === null || match.length < 2) {
throw new Error(`Malformed tools url: ${url}. Version could not be inferred`);
}
return match[1];
}
exports.getCodeQLURLVersion = getCodeQLURLVersion;
function convertToSemVer(version, logger) {
if (!semver.valid(version)) {
logger.debug(`Bundle version ${version} is not in SemVer format. Will treat it as pre-release 0.0.0-${version}.`);
version = `0.0.0-${version}`;
}
const s = semver.clean(version);
if (!s) {
throw new Error(`Bundle version ${version} is not in SemVer format.`);
}
return s;
}
exports.convertToSemVer = convertToSemVer;
/**
* Use the CodeQL executable located at the given path.
*/
function getCodeQL(cmd) {
if (cachedCodeQL === undefined) {
cachedCodeQL = getCodeQLForCmd(cmd);
}
return cachedCodeQL;
}
exports.getCodeQL = getCodeQL;
function resolveFunction(partialCodeql, methodName, defaultImplementation) {
if (typeof partialCodeql[methodName] !== "function") {
if (defaultImplementation !== undefined) {
return defaultImplementation;
}
const dummyMethod = () => {
throw new Error(`CodeQL ${methodName} method not correctly defined`);
};
return dummyMethod;
}
return partialCodeql[methodName];
}
/**
* Set the functionality for CodeQL methods. Only for use in tests.
*
* Accepts a partial object and any undefined methods will be implemented
* to immediately throw an exception indicating which method is missing.
*/
function setCodeQL(partialCodeql) {
cachedCodeQL = {
getPath: resolveFunction(partialCodeql, "getPath", () => "/tmp/dummy-path"),
printVersion: resolveFunction(partialCodeql, "printVersion"),
getTracerEnv: resolveFunction(partialCodeql, "getTracerEnv"),
databaseInit: resolveFunction(partialCodeql, "databaseInit"),
runAutobuild: resolveFunction(partialCodeql, "runAutobuild"),
extractScannedLanguage: resolveFunction(partialCodeql, "extractScannedLanguage"),
finalizeDatabase: resolveFunction(partialCodeql, "finalizeDatabase"),
resolveLanguages: resolveFunction(partialCodeql, "resolveLanguages"),
resolveQueries: resolveFunction(partialCodeql, "resolveQueries"),
packDownload: resolveFunction(partialCodeql, "packDownload"),
databaseCleanup: resolveFunction(partialCodeql, "databaseCleanup"),
databaseBundle: resolveFunction(partialCodeql, "databaseBundle"),
databaseRunQueries: resolveFunction(partialCodeql, "databaseRunQueries"),
databaseInterpretResults: resolveFunction(partialCodeql, "databaseInterpretResults"),
};
return cachedCodeQL;
}
exports.setCodeQL = setCodeQL;
/**
* Get the cached CodeQL object. Should only be used from tests.
*
* TODO: Work out a good way for tests to get this from the test context
* instead of having to have this method.
*/
function getCachedCodeQL() {
if (cachedCodeQL === undefined) {
// Should never happen as setCodeQL is called by testing-utils.setupTests
throw new Error("cachedCodeQL undefined");
}
return cachedCodeQL;
}
exports.getCachedCodeQL = getCachedCodeQL;
function getCodeQLForCmd(cmd) {
return {
getPath() {
return cmd;
},
async printVersion() {
await runTool(cmd, ["version", "--format=json"]);
},
async getTracerEnv(databasePath) {
// Write tracer-env.js to a temp location.
// BEWARE: The name and location of this file is recognized by `codeql database
// trace-command` in order to enable special support for concatenable tracer
// configurations. Consequently the name must not be changed.
// (This warning can be removed once a different way to recognize the
// action/runner has been implemented in `codeql database trace-command`
// _and_ is present in the latest supported CLI release.)
const tracerEnvJs = path.resolve(databasePath, "working", "tracer-env.js");
fs.mkdirSync(path.dirname(tracerEnvJs), { recursive: true });
fs.writeFileSync(tracerEnvJs, `
const fs = require('fs');
const env = {};
for (let entry of Object.entries(process.env)) {
const key = entry[0];
const value = entry[1];
if (typeof value !== 'undefined' && key !== '_' && !key.startsWith('JAVA_MAIN_CLASS_')) {
env[key] = value;
}
}
process.stdout.write(process.argv[2]);
fs.writeFileSync(process.argv[2], JSON.stringify(env), 'utf-8');`);
// BEWARE: The name and location of this file is recognized by `codeql database
// trace-command` in order to enable special support for concatenable tracer
// configurations. Consequently the name must not be changed.
// (This warning can be removed once a different way to recognize the
// action/runner has been implemented in `codeql database trace-command`
// _and_ is present in the latest supported CLI release.)
const envFile = path.resolve(databasePath, "working", "env.tmp");
await runTool(cmd, [
"database",
"trace-command",
databasePath,
...getExtraOptionsFromEnv(["database", "trace-command"]),
process.execPath,
tracerEnvJs,
envFile,
]);
return JSON.parse(fs.readFileSync(envFile, "utf-8"));
},
async databaseInit(databasePath, language, sourceRoot) {
await runTool(cmd, [
"database",
"init",
databasePath,
`--language=${language}`,
`--source-root=${sourceRoot}`,
...getExtraOptionsFromEnv(["database", "init"]),
]);
},
async runAutobuild(language) {
const cmdName = process.platform === "win32" ? "autobuild.cmd" : "autobuild.sh";
const autobuildCmd = path.join(path.dirname(cmd), language, "tools", cmdName);
// Update JAVA_TOOL_OPTIONS to contain '-Dhttp.keepAlive=false'
// This is because of an issue with Azure pipelines timing out connections after 4 minutes
// and Maven not properly handling closed connections
// Otherwise long build processes will timeout when pulling down Java packages
// https://developercommunity.visualstudio.com/content/problem/292284/maven-hosted-agent-connection-timeout.html
const javaToolOptions = process.env["JAVA_TOOL_OPTIONS"] || "";
process.env["JAVA_TOOL_OPTIONS"] = [
...javaToolOptions.split(/\s+/),
"-Dhttp.keepAlive=false",
"-Dmaven.wagon.http.pool=false",
].join(" ");
await runTool(autobuildCmd);
},
async extractScannedLanguage(databasePath, language) {
// Get extractor location
let extractorPath = "";
await new toolrunner.ToolRunner(cmd, [
"resolve",
"extractor",
"--format=json",
`--language=${language}`,
...getExtraOptionsFromEnv(["resolve", "extractor"]),
], {
silent: true,
listeners: {
stdout: (data) => {
extractorPath += data.toString();
},
stderr: (data) => {
process.stderr.write(data);
},
},
}).exec();
// Set trace command
const ext = process.platform === "win32" ? ".cmd" : ".sh";
const traceCommand = path.resolve(JSON.parse(extractorPath), "tools", `autobuild${ext}`);
// Run trace command
await toolrunner_error_catcher_1.toolrunnerErrorCatcher(cmd, [
"database",
"trace-command",
...getExtraOptionsFromEnv(["database", "trace-command"]),
databasePath,
"--",
traceCommand,
], error_matcher_1.errorMatchers);
},
async finalizeDatabase(databasePath, threadsFlag) {
await toolrunner_error_catcher_1.toolrunnerErrorCatcher(cmd, [
"database",
"finalize",
"--finalize-dataset",
threadsFlag,
...getExtraOptionsFromEnv(["database", "finalize"]),
databasePath,
], error_matcher_1.errorMatchers);
},
async resolveLanguages() {
const codeqlArgs = ["resolve", "languages", "--format=json"];
const output = await runTool(cmd, codeqlArgs);
try {
return JSON.parse(output);
}
catch (e) {
throw new Error(`Unexpected output from codeql resolve languages: ${e}`);
}
},
async resolveQueries(queries, extraSearchPath) {
const codeqlArgs = [
"resolve",
"queries",
...queries,
"--format=bylanguage",
...getExtraOptionsFromEnv(["resolve", "queries"]),
];
if (extraSearchPath !== undefined) {
codeqlArgs.push("--additional-packs", extraSearchPath);
}
const output = await runTool(cmd, codeqlArgs);
try {
return JSON.parse(output);
}
catch (e) {
throw new Error(`Unexpected output from codeql resolve queries: ${e}`);
}
},
async databaseRunQueries(databasePath, extraSearchPath, querySuitePath, memoryFlag, threadsFlag) {
const codeqlArgs = [
"database",
"run-queries",
memoryFlag,
threadsFlag,
databasePath,
"--min-disk-free=1024",
"-v",
...getExtraOptionsFromEnv(["database", "run-queries"]),
];
if (extraSearchPath !== undefined) {
codeqlArgs.push("--additional-packs", extraSearchPath);
}
codeqlArgs.push(querySuitePath);
await runTool(cmd, codeqlArgs);
},
async databaseInterpretResults(databasePath, querySuitePaths, sarifFile, addSnippetsFlag, threadsFlag, automationDetailsId) {
const codeqlArgs = [
"database",
"interpret-results",
threadsFlag,
"--format=sarif-latest",
"--print-metrics-summary",
"--sarif-group-rules-by-pack",
"-v",
`--output=${sarifFile}`,
addSnippetsFlag,
...getExtraOptionsFromEnv(["database", "interpret-results"]),
];
if (automationDetailsId !== undefined) {
codeqlArgs.push("--sarif-category", automationDetailsId);
}
codeqlArgs.push(databasePath, ...querySuitePaths);
// capture stdout, which contains analysis summaries
return await runTool(cmd, codeqlArgs);
},
/**
* Download specified packs into the package cache. If the specified
* package and version already exists (e.g., from a previous analysis run),
* then it is not downloaded again (unless the extra option `--force` is
* specified).
*
* If no version is specified, then the latest version is
* downloaded. The check to determine what the latest version is is done
* each time this package is requested.
*/
async packDownload(packs) {
const codeqlArgs = [
"pack",
"download",
"--format=json",
...getExtraOptionsFromEnv(["pack", "download"]),
...packs.map(packWithVersionToString),
];
const output = await runTool(cmd, codeqlArgs);
try {
const parsedOutput = JSON.parse(output);
if (Array.isArray(parsedOutput.packs) &&
// TODO PackDownloadOutput will not include the version if it is not specified
// in the input. The version is always the latest version available.
// It should be added to the output, but this requires a CLI change
parsedOutput.packs.every((p) => p.name /* && p.version */)) {
return parsedOutput;
}
else {
throw new Error("Unexpected output from pack download");
}
}
catch (e) {
throw new Error(`Attempted to download specified packs but got an error:\n${output}\n${e}`);
}
},
async databaseCleanup(databasePath, cleanupLevel) {
const codeqlArgs = [
"database",
"cleanup",
databasePath,
`--mode=${cleanupLevel}`,
];
await runTool(cmd, codeqlArgs);
},
async databaseBundle(databasePath, outputFilePath) {
const args = [
"database",
"bundle",
databasePath,
`--output=${outputFilePath}`,
];
await new toolrunner.ToolRunner(cmd, args).exec();
},
};
}
function packWithVersionToString(pack) {
return pack.version ? `${pack.packName}@${pack.version}` : pack.packName;
}
/**
* Gets the options for `path` of `options` as an array of extra option strings.
*/
function getExtraOptionsFromEnv(paths) {
const options = util.getExtraOptionsEnvParam();
return getExtraOptions(options, paths, []);
}
/**
* Gets `options` as an array of extra option strings.
*
* - throws an exception mentioning `pathInfo` if this conversion is impossible.
*/
function asExtraOptions(options, pathInfo) {
if (options === undefined) {
return [];
}
if (!Array.isArray(options)) {
const msg = `The extra options for '${pathInfo.join(".")}' ('${JSON.stringify(options)}') are not in an array.`;
throw new Error(msg);
}
return options.map((o) => {
const t = typeof o;
if (t !== "string" && t !== "number" && t !== "boolean") {
const msg = `The extra option for '${pathInfo.join(".")}' ('${JSON.stringify(o)}') is not a primitive value.`;
throw new Error(msg);
}
return `${o}`;
});
}
/**
* Gets the options for `path` of `options` as an array of extra option strings.
*
* - the special terminal step name '*' in `options` matches all path steps
* - throws an exception if this conversion is impossible.
*
* Exported for testing.
*/
function getExtraOptions(options, paths, pathInfo) {
var _a, _b, _c;
const all = asExtraOptions((_a = options) === null || _a === void 0 ? void 0 : _a["*"], pathInfo.concat("*"));
const specific = paths.length === 0
? asExtraOptions(options, pathInfo)
: getExtraOptions((_b = options) === null || _b === void 0 ? void 0 : _b[paths[0]], (_c = paths) === null || _c === void 0 ? void 0 : _c.slice(1), pathInfo.concat(paths[0]));
return all.concat(specific);
}
exports.getExtraOptions = getExtraOptions;
/*
* A constant defining the maximum number of characters we will keep from
* the programs stderr for logging. This serves two purposes:
* (1) It avoids an OOM if a program fails in a way that results it
* printing many log lines.
* (2) It avoids us hitting the limit of how much data we can send in our
* status reports on GitHub.com.
*/
const maxErrorSize = 20000;
async function runTool(cmd, args = []) {
let output = "";
let error = "";
const exitCode = await new toolrunner.ToolRunner(cmd, args, {
listeners: {
stdout: (data) => {
output += data.toString();
},
stderr: (data) => {
const toRead = Math.min(maxErrorSize - error.length, data.length);
error += data.toString("utf8", 0, toRead);
},
},
ignoreReturnCode: true,
}).exec();
if (exitCode !== 0)
throw new CommandInvocationError(cmd, args, exitCode, error);
return output;
}
//# sourceMappingURL=codeql.js.map

1
lib/codeql.js.map Normal file

File diff suppressed because one or more lines are too long

208
lib/codeql.test.js generated Normal file
View File

@@ -0,0 +1,208 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(require("path"));
const toolcache = __importStar(require("@actions/tool-cache"));
const ava_1 = __importDefault(require("ava"));
const nock_1 = __importDefault(require("nock"));
const codeql = __importStar(require("./codeql"));
const defaults = __importStar(require("./defaults.json"));
const logging_1 = require("./logging");
const testing_utils_1 = require("./testing-utils");
const util = __importStar(require("./util"));
const util_1 = require("./util");
testing_utils_1.setupTests(ava_1.default);
const sampleApiDetails = {
auth: "token",
url: "https://github.com",
};
const sampleGHAEApiDetails = {
auth: "token",
url: "https://example.githubenterprise.com",
};
ava_1.default.beforeEach(() => {
util_1.initializeEnvironment(util_1.Mode.actions, "1.2.3");
});
ava_1.default("download codeql bundle cache", async (t) => {
await util.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
const versions = ["20200601", "20200610"];
for (let i = 0; i < versions.length; i++) {
const version = versions[i];
nock_1.default("https://example.com")
.get(`/download/codeql-bundle-${version}/codeql-bundle.tar.gz`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle.tar.gz`));
await codeql.setupCodeQL(`https://example.com/download/codeql-bundle-${version}/codeql-bundle.tar.gz`, sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
t.assert(toolcache.find("CodeQL", `0.0.0-${version}`));
}
const cachedVersions = toolcache.findAllVersions("CodeQL");
t.is(cachedVersions.length, 2);
});
});
ava_1.default("download codeql bundle cache explicitly requested with pinned different version cached", async (t) => {
await util.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
nock_1.default("https://example.com")
.get(`/download/codeql-bundle-20200601/codeql-bundle.tar.gz`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle-pinned.tar.gz`));
await codeql.setupCodeQL("https://example.com/download/codeql-bundle-20200601/codeql-bundle.tar.gz", sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
t.assert(toolcache.find("CodeQL", "0.0.0-20200601"));
nock_1.default("https://example.com")
.get(`/download/codeql-bundle-20200610/codeql-bundle.tar.gz`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle.tar.gz`));
await codeql.setupCodeQL("https://example.com/download/codeql-bundle-20200610/codeql-bundle.tar.gz", sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
t.assert(toolcache.find("CodeQL", "0.0.0-20200610"));
});
});
ava_1.default("don't download codeql bundle cache with pinned different version cached", async (t) => {
await util.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
nock_1.default("https://example.com")
.get(`/download/codeql-bundle-20200601/codeql-bundle.tar.gz`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle-pinned.tar.gz`));
await codeql.setupCodeQL("https://example.com/download/codeql-bundle-20200601/codeql-bundle.tar.gz", sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
t.assert(toolcache.find("CodeQL", "0.0.0-20200601"));
await codeql.setupCodeQL(undefined, sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
const cachedVersions = toolcache.findAllVersions("CodeQL");
t.is(cachedVersions.length, 1);
});
});
ava_1.default("download codeql bundle cache with different version cached (not pinned)", async (t) => {
await util.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
nock_1.default("https://example.com")
.get(`/download/codeql-bundle-20200601/codeql-bundle.tar.gz`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle.tar.gz`));
await codeql.setupCodeQL("https://example.com/download/codeql-bundle-20200601/codeql-bundle.tar.gz", sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
t.assert(toolcache.find("CodeQL", "0.0.0-20200601"));
const platform = process.platform === "win32"
? "win64"
: process.platform === "linux"
? "linux64"
: "osx64";
nock_1.default("https://github.com")
.get(`/github/codeql-action/releases/download/${defaults.bundleVersion}/codeql-bundle-${platform}.tar.gz`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle.tar.gz`));
await codeql.setupCodeQL(undefined, sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
const cachedVersions = toolcache.findAllVersions("CodeQL");
t.is(cachedVersions.length, 2);
});
});
ava_1.default('download codeql bundle cache with pinned different version cached if "latest" tools specified', async (t) => {
await util.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
nock_1.default("https://example.com")
.get(`/download/codeql-bundle-20200601/codeql-bundle.tar.gz`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle-pinned.tar.gz`));
await codeql.setupCodeQL("https://example.com/download/codeql-bundle-20200601/codeql-bundle.tar.gz", sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
t.assert(toolcache.find("CodeQL", "0.0.0-20200601"));
const platform = process.platform === "win32"
? "win64"
: process.platform === "linux"
? "linux64"
: "osx64";
nock_1.default("https://github.com")
.get(`/github/codeql-action/releases/download/${defaults.bundleVersion}/codeql-bundle-${platform}.tar.gz`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle.tar.gz`));
await codeql.setupCodeQL("latest", sampleApiDetails, tmpDir, tmpDir, util.GitHubVariant.DOTCOM, logging_1.getRunnerLogger(true));
const cachedVersions = toolcache.findAllVersions("CodeQL");
t.is(cachedVersions.length, 2);
});
});
ava_1.default("download codeql bundle from github ae endpoint", async (t) => {
await util.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
const bundleAssetID = 10;
const platform = process.platform === "win32"
? "win64"
: process.platform === "linux"
? "linux64"
: "osx64";
const codeQLBundleName = `codeql-bundle-${platform}.tar.gz`;
nock_1.default("https://example.githubenterprise.com")
.get(`/api/v3/enterprise/code-scanning/codeql-bundle/find/${defaults.bundleVersion}`)
.reply(200, {
assets: { [codeQLBundleName]: bundleAssetID },
});
nock_1.default("https://example.githubenterprise.com")
.get(`/api/v3/enterprise/code-scanning/codeql-bundle/download/${bundleAssetID}`)
.reply(200, {
url: `https://example.githubenterprise.com/github/codeql-action/releases/download/${defaults.bundleVersion}/${codeQLBundleName}`,
});
nock_1.default("https://example.githubenterprise.com")
.get(`/github/codeql-action/releases/download/${defaults.bundleVersion}/${codeQLBundleName}`)
.replyWithFile(200, path.join(__dirname, `/../src/testdata/codeql-bundle-pinned.tar.gz`));
await codeql.setupCodeQL(undefined, sampleGHAEApiDetails, tmpDir, tmpDir, util.GitHubVariant.GHAE, logging_1.getRunnerLogger(true));
const cachedVersions = toolcache.findAllVersions("CodeQL");
t.is(cachedVersions.length, 1);
});
});
ava_1.default("parse codeql bundle url version", (t) => {
t.deepEqual(codeql.getCodeQLURLVersion("https://github.com/.../codeql-bundle-20200601/..."), "20200601");
});
ava_1.default("convert to semver", (t) => {
const tests = {
"20200601": "0.0.0-20200601",
"20200601.0": "0.0.0-20200601.0",
"20200601.0.0": "20200601.0.0",
"1.2.3": "1.2.3",
"1.2.3-alpha": "1.2.3-alpha",
"1.2.3-beta.1": "1.2.3-beta.1",
};
for (const [version, expectedVersion] of Object.entries(tests)) {
try {
const parsedVersion = codeql.convertToSemVer(version, logging_1.getRunnerLogger(true));
t.deepEqual(parsedVersion, expectedVersion);
}
catch (e) {
t.fail(e.message);
}
}
});
ava_1.default("getExtraOptions works for explicit paths", (t) => {
t.deepEqual(codeql.getExtraOptions({}, ["foo"], []), []);
t.deepEqual(codeql.getExtraOptions({ foo: [42] }, ["foo"], []), ["42"]);
t.deepEqual(codeql.getExtraOptions({ foo: { bar: [42] } }, ["foo", "bar"], []), ["42"]);
});
ava_1.default("getExtraOptions works for wildcards", (t) => {
t.deepEqual(codeql.getExtraOptions({ "*": [42] }, ["foo"], []), ["42"]);
});
ava_1.default("getExtraOptions works for wildcards and explicit paths", (t) => {
const o1 = { "*": [42], foo: [87] };
t.deepEqual(codeql.getExtraOptions(o1, ["foo"], []), ["42", "87"]);
const o2 = { "*": [42], foo: [87] };
t.deepEqual(codeql.getExtraOptions(o2, ["foo", "bar"], []), ["42"]);
const o3 = { "*": [42], foo: { "*": [87], bar: [99] } };
const p = ["foo", "bar"];
t.deepEqual(codeql.getExtraOptions(o3, p, []), ["42", "87", "99"]);
});
ava_1.default("getExtraOptions throws for bad content", (t) => {
t.throws(() => codeql.getExtraOptions({ "*": 42 }, ["foo"], []));
t.throws(() => codeql.getExtraOptions({ foo: 87 }, ["foo"], []));
t.throws(() => codeql.getExtraOptions({ "*": [42], foo: { "*": 87, bar: [99] } }, ["foo", "bar"], []));
});
ava_1.default("getCodeQLActionRepository", (t) => {
const logger = logging_1.getRunnerLogger(true);
util_1.initializeEnvironment(util_1.Mode.runner, "1.2.3");
const repoActions = codeql.getCodeQLActionRepository(logger);
t.deepEqual(repoActions, "github/codeql-action");
util_1.initializeEnvironment(util_1.Mode.actions, "1.2.3");
// isRunningLocalAction() === true
delete process.env["GITHUB_ACTION_REPOSITORY"];
process.env["RUNNER_TEMP"] = path.dirname(__dirname);
const repoLocalRunner = codeql.getCodeQLActionRepository(logger);
t.deepEqual(repoLocalRunner, "github/codeql-action");
process.env["GITHUB_ACTION_REPOSITORY"] = "xxx/yyy";
const repoEnv = codeql.getCodeQLActionRepository(logger);
t.deepEqual(repoEnv, "xxx/yyy");
});
//# sourceMappingURL=codeql.test.js.map

1
lib/codeql.test.js.map Normal file

File diff suppressed because one or more lines are too long

865
lib/config-utils.js generated
View File

@@ -7,95 +7,703 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const io = __importStar(require("@actions/io"));
const fs = __importStar(require("fs"));
const yaml = __importStar(require("js-yaml"));
const path = __importStar(require("path"));
const util = __importStar(require("./util"));
class ExternalQuery {
constructor(repository, ref) {
this.path = '';
this.repository = repository;
this.ref = ref;
const yaml = __importStar(require("js-yaml"));
const semver = __importStar(require("semver"));
const api = __importStar(require("./api-client"));
const externalQueries = __importStar(require("./external-queries"));
const languages_1 = require("./languages");
// Property names from the user-supplied config file.
const NAME_PROPERTY = "name";
const DISABLE_DEFAULT_QUERIES_PROPERTY = "disable-default-queries";
const QUERIES_PROPERTY = "queries";
const QUERIES_USES_PROPERTY = "uses";
const PATHS_IGNORE_PROPERTY = "paths-ignore";
const PATHS_PROPERTY = "paths";
const PACKS_PROPERTY = "packs";
/**
* A list of queries from https://github.com/github/codeql that
* we don't want to run. Disabling them here is a quicker alternative to
* disabling them in the code scanning query suites. Queries should also
* be disabled in the suites, and removed from this list here once the
* bundle is updated to make those suite changes live.
*
* Format is a map from language to an array of path suffixes of .ql files.
*/
const DISABLED_BUILTIN_QUERIES = {
csharp: [
"ql/src/Security Features/CWE-937/VulnerablePackage.ql",
"ql/src/Security Features/CWE-451/MissingXFrameOptions.ql",
],
};
function queryIsDisabled(language, query) {
return (DISABLED_BUILTIN_QUERIES[language] || []).some((disabledQuery) => query.endsWith(disabledQuery));
}
/**
* Asserts that the noDeclaredLanguage and multipleDeclaredLanguages fields are
* both empty and errors if they are not.
*/
function validateQueries(resolvedQueries) {
const noDeclaredLanguage = resolvedQueries.noDeclaredLanguage;
const noDeclaredLanguageQueries = Object.keys(noDeclaredLanguage);
if (noDeclaredLanguageQueries.length !== 0) {
throw new Error(`${"The following queries do not declare a language. " +
"Their qlpack.yml files are either missing or is invalid.\n"}${noDeclaredLanguageQueries.join("\n")}`);
}
const multipleDeclaredLanguages = resolvedQueries.multipleDeclaredLanguages;
const multipleDeclaredLanguagesQueries = Object.keys(multipleDeclaredLanguages);
if (multipleDeclaredLanguagesQueries.length !== 0) {
throw new Error(`${"The following queries declare multiple languages. " +
"Their qlpack.yml files are either missing or is invalid.\n"}${multipleDeclaredLanguagesQueries.join("\n")}`);
}
}
exports.ExternalQuery = ExternalQuery;
class Config {
constructor() {
this.name = "";
this.disableDefaultQueries = false;
this.additionalQueries = [];
this.externalQueries = [];
this.pathsIgnore = [];
this.paths = [];
/**
* Run 'codeql resolve queries' and add the results to resultMap
*
* If a checkout path is given then the queries are assumed to be custom queries
* and an error will be thrown if there is anything invalid about the queries.
* If a checkout path is not given then the queries are assumed to be builtin
* queries, and error checking will be suppressed.
*/
async function runResolveQueries(codeQL, resultMap, toResolve, extraSearchPath) {
const resolvedQueries = await codeQL.resolveQueries(toResolve, extraSearchPath);
if (extraSearchPath !== undefined) {
validateQueries(resolvedQueries);
}
addQuery(queryUses) {
// The logic for parsing the string is based on what actions does for
// parsing the 'uses' actions in the workflow file
queryUses = queryUses.trim();
if (queryUses === "") {
throw new Error(getQueryUsesBlank());
for (const [language, queryPaths] of Object.entries(resolvedQueries.byLanguage)) {
if (resultMap[language] === undefined) {
resultMap[language] = {
builtin: [],
custom: [],
};
}
// Check for the local path case before we start trying to parse the repository name
if (queryUses.startsWith("./")) {
this.additionalQueries.push(queryUses.slice(2));
return;
const queries = Object.keys(queryPaths).filter((q) => !queryIsDisabled(language, q));
if (extraSearchPath !== undefined) {
resultMap[language].custom.push({
searchPath: extraSearchPath,
queries,
});
}
let tok = queryUses.split('@');
if (tok.length !== 2) {
throw new Error(getQueryUsesIncorrect(queryUses));
else {
resultMap[language].builtin.push(...queries);
}
const ref = tok[1];
tok = tok[0].split('/');
// The first token is the owner
// The second token is the repo
// The rest is a path, if there is more than one token combine them to form the full path
if (tok.length < 2) {
throw new Error(getQueryUsesIncorrect(queryUses));
}
if (tok.length > 3) {
tok = [tok[0], tok[1], tok.slice(2).join('/')];
}
// Check none of the parts of the repository name are empty
if (tok[0].trim() === '' || tok[1].trim() === '') {
throw new Error(getQueryUsesIncorrect(queryUses));
}
let external = new ExternalQuery(tok[0] + '/' + tok[1], ref);
if (tok.length === 3) {
external.path = tok[2];
}
this.externalQueries.push(external);
}
}
exports.Config = Config;
function getQueryUsesBlank() {
return '"uses" value for queries cannot be blank';
/**
* Get the set of queries included by default.
*/
async function addDefaultQueries(codeQL, languages, resultMap) {
const suites = languages.map((l) => `${l}-code-scanning.qls`);
await runResolveQueries(codeQL, resultMap, suites, undefined);
}
exports.getQueryUsesBlank = getQueryUsesBlank;
function getQueryUsesIncorrect(queryUses) {
return '"uses" value for queries must be a path, or owner/repo@ref \n Found: ' + queryUses;
// The set of acceptable values for built-in suites from the codeql bundle
const builtinSuites = ["security-extended", "security-and-quality"];
/**
* Determine the set of queries associated with suiteName's suites and add them to resultMap.
* Throws an error if suiteName is not a valid builtin suite.
*/
async function addBuiltinSuiteQueries(languages, codeQL, resultMap, suiteName, configFile) {
const found = builtinSuites.find((suite) => suite === suiteName);
if (!found) {
throw new Error(getQueryUsesInvalid(configFile, suiteName));
}
const suites = languages.map((l) => `${l}-${suiteName}.qls`);
await runResolveQueries(codeQL, resultMap, suites, undefined);
}
exports.getQueryUsesIncorrect = getQueryUsesIncorrect;
/**
* Retrieve the set of queries at localQueryPath and add them to resultMap.
*/
async function addLocalQueries(codeQL, resultMap, localQueryPath, workspacePath, configFile) {
// Resolve the local path against the workspace so that when this is
// passed to codeql it resolves to exactly the path we expect it to resolve to.
let absoluteQueryPath = path.join(workspacePath, localQueryPath);
// Check the file exists
if (!fs.existsSync(absoluteQueryPath)) {
throw new Error(getLocalPathDoesNotExist(configFile, localQueryPath));
}
// Call this after checking file exists, because it'll fail if file doesn't exist
absoluteQueryPath = fs.realpathSync(absoluteQueryPath);
// Check the local path doesn't jump outside the repo using '..' or symlinks
if (!(absoluteQueryPath + path.sep).startsWith(fs.realpathSync(workspacePath) + path.sep)) {
throw new Error(getLocalPathOutsideOfRepository(configFile, localQueryPath));
}
const extraSearchPath = workspacePath;
await runResolveQueries(codeQL, resultMap, [absoluteQueryPath], extraSearchPath);
}
/**
* Retrieve the set of queries at the referenced remote repo and add them to resultMap.
*/
async function addRemoteQueries(codeQL, resultMap, queryUses, tempDir, apiDetails, logger, configFile) {
let tok = queryUses.split("@");
if (tok.length !== 2) {
throw new Error(getQueryUsesInvalid(configFile, queryUses));
}
const ref = tok[1];
tok = tok[0].split("/");
// The first token is the owner
// The second token is the repo
// The rest is a path, if there is more than one token combine them to form the full path
if (tok.length < 2) {
throw new Error(getQueryUsesInvalid(configFile, queryUses));
}
// Check none of the parts of the repository name are empty
if (tok[0].trim() === "" || tok[1].trim() === "") {
throw new Error(getQueryUsesInvalid(configFile, queryUses));
}
const nwo = `${tok[0]}/${tok[1]}`;
// Checkout the external repository
const checkoutPath = await externalQueries.checkoutExternalRepository(nwo, ref, apiDetails, tempDir, logger);
const queryPath = tok.length > 2
? path.join(checkoutPath, tok.slice(2).join("/"))
: checkoutPath;
await runResolveQueries(codeQL, resultMap, [queryPath], checkoutPath);
}
/**
* Parse a query 'uses' field to a discrete set of query files and update resultMap.
*
* The logic for parsing the string is based on what actions does for
* parsing the 'uses' actions in the workflow file. So it can handle
* local paths starting with './', or references to remote repos, or
* a finite set of hardcoded terms for builtin suites.
*/
async function parseQueryUses(languages, codeQL, resultMap, queryUses, tempDir, workspacePath, apiDetails, logger, configFile) {
queryUses = queryUses.trim();
if (queryUses === "") {
throw new Error(getQueryUsesInvalid(configFile));
}
// Check for the local path case before we start trying to parse the repository name
if (queryUses.startsWith("./")) {
await addLocalQueries(codeQL, resultMap, queryUses.slice(2), workspacePath, configFile);
return;
}
// Check for one of the builtin suites
if (queryUses.indexOf("/") === -1 && queryUses.indexOf("@") === -1) {
await addBuiltinSuiteQueries(languages, codeQL, resultMap, queryUses, configFile);
return;
}
// Otherwise, must be a reference to another repo
await addRemoteQueries(codeQL, resultMap, queryUses, tempDir, apiDetails, logger, configFile);
}
// Regex validating stars in paths or paths-ignore entries.
// The intention is to only allow ** to appear when immediately
// preceded and followed by a slash.
const pathStarsRegex = /.*(?:\*\*[^/].*|\*\*$|[^/]\*\*.*)/;
// Characters that are supported by filters in workflows, but not by us.
// See https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet
const filterPatternCharactersRegex = /.*[?+[\]!].*/;
// Checks that a paths of paths-ignore entry is valid, possibly modifying it
// to make it valid, or if not possible then throws an error.
function validateAndSanitisePath(originalPath, propertyName, configFile, logger) {
// Take a copy so we don't modify the original path, so we can still construct error messages
let newPath = originalPath;
// All paths are relative to the src root, so strip off leading slashes.
while (newPath.charAt(0) === "/") {
newPath = newPath.substring(1);
}
// Trailing ** are redundant, so strip them off
if (newPath.endsWith("/**")) {
newPath = newPath.substring(0, newPath.length - 2);
}
// An empty path is not allowed as it's meaningless
if (newPath === "") {
throw new Error(getConfigFilePropertyError(configFile, propertyName, `"${originalPath}" is not an invalid path. ` +
`It is not necessary to include it, and it is not allowed to exclude it.`));
}
// Check for illegal uses of **
if (newPath.match(pathStarsRegex)) {
throw new Error(getConfigFilePropertyError(configFile, propertyName, `"${originalPath}" contains an invalid "**" wildcard. ` +
`They must be immediately preceded and followed by a slash as in "/**/", or come at the start or end.`));
}
// Check for other regex characters that we don't support.
// Output a warning so the user knows, but otherwise continue normally.
if (newPath.match(filterPatternCharactersRegex)) {
logger.warning(getConfigFilePropertyError(configFile, propertyName, `"${originalPath}" contains an unsupported character. ` +
`The filter pattern characters ?, +, [, ], ! are not supported and will be matched literally.`));
}
// Ban any uses of backslash for now.
// This may not play nicely with project layouts.
// This restriction can be lifted later if we determine they are ok.
if (newPath.indexOf("\\") !== -1) {
throw new Error(getConfigFilePropertyError(configFile, propertyName, `"${originalPath}" contains an "\\" character. These are not allowed in filters. ` +
`If running on windows we recommend using "/" instead for path filters.`));
}
return newPath;
}
exports.validateAndSanitisePath = validateAndSanitisePath;
// An undefined configFile in some of these functions indicates that
// the property was in a workflow file, not a config file
function getNameInvalid(configFile) {
return getConfigFilePropertyError(configFile, NAME_PROPERTY, "must be a non-empty string");
}
exports.getNameInvalid = getNameInvalid;
function getDisableDefaultQueriesInvalid(configFile) {
return getConfigFilePropertyError(configFile, DISABLE_DEFAULT_QUERIES_PROPERTY, "must be a boolean");
}
exports.getDisableDefaultQueriesInvalid = getDisableDefaultQueriesInvalid;
function getQueriesInvalid(configFile) {
return getConfigFilePropertyError(configFile, QUERIES_PROPERTY, "must be an array");
}
exports.getQueriesInvalid = getQueriesInvalid;
function getQueryUsesInvalid(configFile, queryUses) {
return getConfigFilePropertyError(configFile, `${QUERIES_PROPERTY}.${QUERIES_USES_PROPERTY}`, `must be a built-in suite (${builtinSuites.join(" or ")}), a relative path, or be of the form "owner/repo[/path]@ref"${queryUses !== undefined ? `\n Found: ${queryUses}` : ""}`);
}
exports.getQueryUsesInvalid = getQueryUsesInvalid;
function getPathsIgnoreInvalid(configFile) {
return getConfigFilePropertyError(configFile, PATHS_IGNORE_PROPERTY, "must be an array of non-empty strings");
}
exports.getPathsIgnoreInvalid = getPathsIgnoreInvalid;
function getPathsInvalid(configFile) {
return getConfigFilePropertyError(configFile, PATHS_PROPERTY, "must be an array of non-empty strings");
}
exports.getPathsInvalid = getPathsInvalid;
function getPacksRequireLanguage(lang, configFile) {
return getConfigFilePropertyError(configFile, PACKS_PROPERTY, `has "${lang}", but it is not one of the languages to analyze`);
}
exports.getPacksRequireLanguage = getPacksRequireLanguage;
function getPacksInvalidSplit(configFile) {
return getConfigFilePropertyError(configFile, PACKS_PROPERTY, "must split packages by language");
}
exports.getPacksInvalidSplit = getPacksInvalidSplit;
function getPacksInvalid(configFile) {
return getConfigFilePropertyError(configFile, PACKS_PROPERTY, "must be an array of non-empty strings");
}
exports.getPacksInvalid = getPacksInvalid;
function getPacksStrInvalid(packStr, configFile) {
return configFile
? getConfigFilePropertyError(configFile, PACKS_PROPERTY, `"${packStr}" is not a valid pack`)
: `"${packStr}" is not a valid pack`;
}
exports.getPacksStrInvalid = getPacksStrInvalid;
function getLocalPathOutsideOfRepository(configFile, localPath) {
return getConfigFilePropertyError(configFile, `${QUERIES_PROPERTY}.${QUERIES_USES_PROPERTY}`, `is invalid as the local path "${localPath}" is outside of the repository`);
}
exports.getLocalPathOutsideOfRepository = getLocalPathOutsideOfRepository;
function getLocalPathDoesNotExist(configFile, localPath) {
return getConfigFilePropertyError(configFile, `${QUERIES_PROPERTY}.${QUERIES_USES_PROPERTY}`, `is invalid as the local path "${localPath}" does not exist in the repository`);
}
exports.getLocalPathDoesNotExist = getLocalPathDoesNotExist;
function getConfigFileOutsideWorkspaceErrorMessage(configFile) {
return 'The configuration file "' + configFile + '" is outside of the workspace';
return `The configuration file "${configFile}" is outside of the workspace`;
}
exports.getConfigFileOutsideWorkspaceErrorMessage = getConfigFileOutsideWorkspaceErrorMessage;
function getConfigFileDoesNotExistErrorMessage(configFile) {
return 'The configuration file "' + configFile + '" does not exist';
return `The configuration file "${configFile}" does not exist`;
}
exports.getConfigFileDoesNotExistErrorMessage = getConfigFileDoesNotExistErrorMessage;
function initConfig() {
let configFile = core.getInput('config-file');
const config = new Config();
// If no config file was provided create an empty one
if (configFile === '') {
core.debug('No configuration file was provided');
return config;
function getConfigFileRepoFormatInvalidMessage(configFile) {
let error = `The configuration file "${configFile}" is not a supported remote file reference.`;
error += " Expected format <owner>/<repository>/<file-path>@<ref>";
return error;
}
exports.getConfigFileRepoFormatInvalidMessage = getConfigFileRepoFormatInvalidMessage;
function getConfigFileFormatInvalidMessage(configFile) {
return `The configuration file "${configFile}" could not be read`;
}
exports.getConfigFileFormatInvalidMessage = getConfigFileFormatInvalidMessage;
function getConfigFileDirectoryGivenMessage(configFile) {
return `The configuration file "${configFile}" looks like a directory, not a file`;
}
exports.getConfigFileDirectoryGivenMessage = getConfigFileDirectoryGivenMessage;
function getConfigFilePropertyError(configFile, property, error) {
if (configFile === undefined) {
return `The workflow property "${property}" is invalid: ${error}`;
}
// Treat the config file as relative to the workspace
const workspacePath = util.getRequiredEnvParam('GITHUB_WORKSPACE');
configFile = path.resolve(workspacePath, configFile);
else {
return `The configuration file "${configFile}" is invalid: property "${property}" ${error}`;
}
}
function getNoLanguagesError() {
return ("Did not detect any languages to analyze. " +
"Please update input in workflow or check that GitHub detects the correct languages in your repository.");
}
exports.getNoLanguagesError = getNoLanguagesError;
function getUnknownLanguagesError(languages) {
return `Did not recognise the following languages: ${languages.join(", ")}`;
}
exports.getUnknownLanguagesError = getUnknownLanguagesError;
/**
* Gets the set of languages in the current repository
*/
async function getLanguagesInRepo(repository, apiDetails, logger) {
logger.debug(`GitHub repo ${repository.owner} ${repository.repo}`);
const response = await api.getApiClient(apiDetails).repos.listLanguages({
owner: repository.owner,
repo: repository.repo,
});
logger.debug(`Languages API response: ${JSON.stringify(response)}`);
// The GitHub API is going to return languages in order of popularity,
// When we pick a language to autobuild we want to pick the most popular traced language
// Since sets in javascript maintain insertion order, using a set here and then splatting it
// into an array gives us an array of languages ordered by popularity
const languages = new Set();
for (const lang of Object.keys(response.data)) {
const parsedLang = languages_1.parseLanguage(lang);
if (parsedLang !== undefined) {
languages.add(parsedLang);
}
}
return [...languages];
}
/**
* Get the languages to analyse.
*
* The result is obtained from the action input parameter 'languages' if that
* has been set, otherwise it is deduced as all languages in the repo that
* can be analysed.
*
* If no languages could be detected from either the workflow or the repository
* then throw an error.
*/
async function getLanguages(codeQL, languagesInput, repository, apiDetails, logger) {
// Obtain from action input 'languages' if set
let languages = (languagesInput || "")
.split(",")
.map((x) => x.trim())
.filter((x) => x.length > 0);
logger.info(`Languages from configuration: ${JSON.stringify(languages)}`);
if (languages.length === 0) {
// Obtain languages as all languages in the repo that can be analysed
languages = await getLanguagesInRepo(repository, apiDetails, logger);
const availableLanguages = await codeQL.resolveLanguages();
languages = languages.filter((value) => value in availableLanguages);
logger.info(`Automatically detected languages: ${JSON.stringify(languages)}`);
}
// If the languages parameter was not given and no languages were
// detected then fail here as this is a workflow configuration error.
if (languages.length === 0) {
throw new Error(getNoLanguagesError());
}
// Make sure they are supported
const parsedLanguages = [];
const unknownLanguages = [];
for (const language of languages) {
const parsedLanguage = languages_1.parseLanguage(language);
if (parsedLanguage === undefined) {
unknownLanguages.push(language);
}
else if (parsedLanguages.indexOf(parsedLanguage) === -1) {
parsedLanguages.push(parsedLanguage);
}
}
if (unknownLanguages.length > 0) {
throw new Error(getUnknownLanguagesError(unknownLanguages));
}
return parsedLanguages;
}
async function addQueriesFromWorkflow(codeQL, queriesInput, languages, resultMap, tempDir, workspacePath, apiDetails, logger) {
queriesInput = queriesInput.trim();
// "+" means "don't override config file" - see shouldAddConfigFileQueries
queriesInput = queriesInput.replace(/^\+/, "");
for (const query of queriesInput.split(",")) {
await parseQueryUses(languages, codeQL, resultMap, query, tempDir, workspacePath, apiDetails, logger);
}
}
// Returns true if either no queries were provided in the workflow.
// or if the queries in the workflow were provided in "additive" mode,
// indicating that they shouldn't override the config queries but
// should instead be added in addition
function shouldAddConfigFileQueries(queriesInput) {
if (queriesInput) {
return queriesInput.trimStart().substr(0, 1) === "+";
}
return true;
}
/**
* Get the default config for when the user has not supplied one.
*/
async function getDefaultConfig(languagesInput, queriesInput, packsInput, dbLocation, repository, tempDir, toolCacheDir, codeQL, workspacePath, gitHubVersion, apiDetails, logger) {
var _a;
const languages = await getLanguages(codeQL, languagesInput, repository, apiDetails, logger);
const queries = {};
for (const language of languages) {
queries[language] = {
builtin: [],
custom: [],
};
}
await addDefaultQueries(codeQL, languages, queries);
if (queriesInput) {
await addQueriesFromWorkflow(codeQL, queriesInput, languages, queries, tempDir, workspacePath, apiDetails, logger);
}
const packs = (_a = parsePacksFromInput(packsInput, languages), (_a !== null && _a !== void 0 ? _a : {}));
return {
languages,
queries,
pathsIgnore: [],
paths: [],
packs,
originalUserInput: {},
tempDir,
toolCacheDir,
codeQLCmd: codeQL.getPath(),
gitHubVersion,
dbLocation: dbLocationOrDefault(dbLocation, tempDir),
};
}
exports.getDefaultConfig = getDefaultConfig;
/**
* Load the config from the given file.
*/
async function loadConfig(languagesInput, queriesInput, packsInput, configFile, dbLocation, repository, tempDir, toolCacheDir, codeQL, workspacePath, gitHubVersion, apiDetails, logger) {
var _a;
let parsedYAML;
if (isLocal(configFile)) {
// Treat the config file as relative to the workspace
configFile = path.resolve(workspacePath, configFile);
parsedYAML = getLocalConfig(configFile, workspacePath);
}
else {
parsedYAML = await getRemoteConfig(configFile, apiDetails);
}
// Validate that the 'name' property is syntactically correct,
// even though we don't use the value yet.
if (NAME_PROPERTY in parsedYAML) {
if (typeof parsedYAML[NAME_PROPERTY] !== "string") {
throw new Error(getNameInvalid(configFile));
}
if (parsedYAML[NAME_PROPERTY].length === 0) {
throw new Error(getNameInvalid(configFile));
}
}
const languages = await getLanguages(codeQL, languagesInput, repository, apiDetails, logger);
const queries = {};
for (const language of languages) {
queries[language] = {
builtin: [],
custom: [],
};
}
const pathsIgnore = [];
const paths = [];
let disableDefaultQueries = false;
if (DISABLE_DEFAULT_QUERIES_PROPERTY in parsedYAML) {
if (typeof parsedYAML[DISABLE_DEFAULT_QUERIES_PROPERTY] !== "boolean") {
throw new Error(getDisableDefaultQueriesInvalid(configFile));
}
disableDefaultQueries = parsedYAML[DISABLE_DEFAULT_QUERIES_PROPERTY];
}
if (!disableDefaultQueries) {
await addDefaultQueries(codeQL, languages, queries);
}
// If queries were provided using `with` in the action configuration,
// they should take precedence over the queries in the config file
// unless they're prefixed with "+", in which case they supplement those
// in the config file.
if (queriesInput) {
await addQueriesFromWorkflow(codeQL, queriesInput, languages, queries, tempDir, workspacePath, apiDetails, logger);
}
if (shouldAddConfigFileQueries(queriesInput) &&
QUERIES_PROPERTY in parsedYAML) {
const queriesArr = parsedYAML[QUERIES_PROPERTY];
if (!Array.isArray(queriesArr)) {
throw new Error(getQueriesInvalid(configFile));
}
for (const query of queriesArr) {
if (!(QUERIES_USES_PROPERTY in query) ||
typeof query[QUERIES_USES_PROPERTY] !== "string") {
throw new Error(getQueryUsesInvalid(configFile));
}
await parseQueryUses(languages, codeQL, queries, query[QUERIES_USES_PROPERTY], tempDir, workspacePath, apiDetails, logger, configFile);
}
}
if (PATHS_IGNORE_PROPERTY in parsedYAML) {
if (!Array.isArray(parsedYAML[PATHS_IGNORE_PROPERTY])) {
throw new Error(getPathsIgnoreInvalid(configFile));
}
for (const ignorePath of parsedYAML[PATHS_IGNORE_PROPERTY]) {
if (typeof ignorePath !== "string" || ignorePath === "") {
throw new Error(getPathsIgnoreInvalid(configFile));
}
pathsIgnore.push(validateAndSanitisePath(ignorePath, PATHS_IGNORE_PROPERTY, configFile, logger));
}
}
if (PATHS_PROPERTY in parsedYAML) {
if (!Array.isArray(parsedYAML[PATHS_PROPERTY])) {
throw new Error(getPathsInvalid(configFile));
}
for (const includePath of parsedYAML[PATHS_PROPERTY]) {
if (typeof includePath !== "string" || includePath === "") {
throw new Error(getPathsInvalid(configFile));
}
paths.push(validateAndSanitisePath(includePath, PATHS_PROPERTY, configFile, logger));
}
}
const packs = parsePacks((_a = parsedYAML[PACKS_PROPERTY], (_a !== null && _a !== void 0 ? _a : {})), packsInput, languages, configFile);
return {
languages,
queries,
pathsIgnore,
paths,
packs,
originalUserInput: parsedYAML,
tempDir,
toolCacheDir,
codeQLCmd: codeQL.getPath(),
gitHubVersion,
dbLocation: dbLocationOrDefault(dbLocation, tempDir),
};
}
/**
* Pack names must be in the form of `scope/name`, with only alpha-numeric characters,
* and `-` allowed as long as not the first or last char.
**/
const PACK_IDENTIFIER_PATTERN = (function () {
const alphaNumeric = "[a-z0-9]";
const alphaNumericDash = "[a-z0-9-]";
const component = `${alphaNumeric}(${alphaNumericDash}*${alphaNumeric})?`;
return new RegExp(`^${component}/${component}$`);
})();
// Exported for testing
function parsePacksFromConfig(packsByLanguage, languages, configFile) {
const packs = {};
if (Array.isArray(packsByLanguage)) {
if (languages.length === 1) {
// single language analysis, so language is implicit
packsByLanguage = {
[languages[0]]: packsByLanguage,
};
}
else {
// this is an error since multi-language analysis requires
// packs split by language
throw new Error(getPacksInvalidSplit(configFile));
}
}
for (const [lang, packsArr] of Object.entries(packsByLanguage)) {
if (!Array.isArray(packsArr)) {
throw new Error(getPacksInvalid(configFile));
}
if (!languages.includes(lang)) {
throw new Error(getPacksRequireLanguage(lang, configFile));
}
packs[lang] = [];
for (const packStr of packsArr) {
packs[lang].push(toPackWithVersion(packStr, configFile));
}
}
return packs;
}
exports.parsePacksFromConfig = parsePacksFromConfig;
function parsePacksFromInput(packsInput, languages) {
var _a;
if (!((_a = packsInput) === null || _a === void 0 ? void 0 : _a.trim())) {
return undefined;
}
if (languages.length > 1) {
throw new Error("Cannot specify a 'packs' input in a multi-language analysis. Use a codeql-config.yml file instead and specify packs by language.");
}
else if (languages.length === 0) {
throw new Error("No languages specified. Cannot process the packs input.");
}
packsInput = packsInput.trim();
if (packsInput.startsWith("+")) {
packsInput = packsInput.substring(1).trim();
if (!packsInput) {
throw new Error("A '+' was used in the 'packs' 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 {
[languages[0]]: packsInput.split(",").reduce((packs, pack) => {
packs.push(toPackWithVersion(pack, ""));
return packs;
}, []),
};
}
function toPackWithVersion(packStr, configFile) {
if (typeof packStr !== "string") {
throw new Error(getPacksStrInvalid(packStr, configFile));
}
const nameWithVersion = packStr.trim().split("@");
let version;
if (nameWithVersion.length > 2 ||
!PACK_IDENTIFIER_PATTERN.test(nameWithVersion[0])) {
throw new Error(getPacksStrInvalid(packStr, configFile));
}
else if (nameWithVersion.length === 2) {
version = semver.clean(nameWithVersion[1]) || undefined;
if (!version) {
throw new Error(getPacksStrInvalid(packStr, configFile));
}
}
return {
packName: nameWithVersion[0].trim(),
version,
};
}
// exported for testing
function parsePacks(rawPacksFromConfig, rawPacksInput, languages, configFile) {
const packsFromInput = parsePacksFromInput(rawPacksInput, languages);
const packsFomConfig = parsePacksFromConfig(rawPacksFromConfig, languages, configFile);
if (!packsFromInput) {
return packsFomConfig;
}
if (!shouldCombinePacks(rawPacksInput)) {
return packsFromInput;
}
return combinePacks(packsFromInput, packsFomConfig);
}
exports.parsePacks = parsePacks;
function shouldCombinePacks(packsInput) {
var _a;
return !!((_a = packsInput) === null || _a === void 0 ? void 0 : _a.trim().startsWith("+"));
}
function combinePacks(packs1, packs2) {
const packs = {};
for (const lang of Object.keys(packs1)) {
packs[lang] = packs1[lang].concat(packs2[lang] || []);
}
for (const lang of Object.keys(packs2)) {
if (!packs[lang]) {
packs[lang] = packs2[lang];
}
}
return packs;
}
function dbLocationOrDefault(dbLocation, tempDir) {
return dbLocation || path.resolve(tempDir, "codeql_databases");
}
/**
* Load and return the config.
*
* This will parse the config from the user input if present, or generate
* a default config. The parsed config is then stored to a known location.
*/
async function initConfig(languagesInput, queriesInput, packsInput, configFile, dbLocation, repository, tempDir, toolCacheDir, codeQL, workspacePath, gitHubVersion, apiDetails, logger) {
var _a, _b, _c;
let config;
// If no config file was provided create an empty one
if (!configFile) {
logger.debug("No configuration file was provided");
config = await getDefaultConfig(languagesInput, queriesInput, packsInput, dbLocation, repository, tempDir, toolCacheDir, codeQL, workspacePath, gitHubVersion, apiDetails, logger);
}
else {
config = await loadConfig(languagesInput, queriesInput, packsInput, configFile, dbLocation, repository, tempDir, toolCacheDir, codeQL, workspacePath, gitHubVersion, apiDetails, logger);
}
// The list of queries should not be empty for any language. If it is then
// it is a user configuration error.
for (const language of config.languages) {
const hasBuiltinQueries = ((_a = config.queries[language]) === null || _a === void 0 ? void 0 : _a.builtin.length) > 0;
const hasCustomQueries = ((_b = config.queries[language]) === null || _b === void 0 ? void 0 : _b.custom.length) > 0;
const hasPacks = (((_c = config.packs[language]) === null || _c === void 0 ? void 0 : _c.length) || 0) > 0;
if (!hasPacks && !hasBuiltinQueries && !hasCustomQueries) {
throw new Error(`Did not detect any queries to run for ${language}. ` +
"Please make sure that the default queries are enabled, or you are specifying queries to run.");
}
}
// Save the config so we can easily access it again in the future
await saveConfig(config, logger);
return config;
}
exports.initConfig = initConfig;
function isLocal(configPath) {
// If the path starts with ./, look locally
if (configPath.indexOf("./") === 0) {
return true;
}
return configPath.indexOf("@") === -1;
}
function getLocalConfig(configFile, workspacePath) {
// Error if the config file is now outside of the workspace
if (!(configFile + path.sep).startsWith(workspacePath + path.sep)) {
throw new Error(getConfigFileOutsideWorkspaceErrorMessage(configFile));
@@ -104,68 +712,67 @@ function initConfig() {
if (!fs.existsSync(configFile)) {
throw new Error(getConfigFileDoesNotExistErrorMessage(configFile));
}
const parsedYAML = yaml.safeLoad(fs.readFileSync(configFile, 'utf8'));
if (parsedYAML.name && typeof parsedYAML.name === "string") {
config.name = parsedYAML.name;
}
if (parsedYAML['disable-default-queries'] && typeof parsedYAML['disable-default-queries'] === "boolean") {
config.disableDefaultQueries = parsedYAML['disable-default-queries'];
}
const queries = parsedYAML.queries;
if (queries && queries instanceof Array) {
queries.forEach(query => {
if (typeof query.uses === "string") {
config.addQuery(query.uses);
}
});
}
const pathsIgnore = parsedYAML['paths-ignore'];
if (pathsIgnore && pathsIgnore instanceof Array) {
pathsIgnore.forEach(path => {
if (typeof path === "string") {
config.pathsIgnore.push(path);
}
});
}
const paths = parsedYAML.paths;
if (paths && paths instanceof Array) {
paths.forEach(path => {
if (typeof path === "string") {
config.paths.push(path);
}
});
}
return config;
return yaml.safeLoad(fs.readFileSync(configFile, "utf8"));
}
function getConfigFolder() {
return util.getRequiredEnvParam('RUNNER_WORKSPACE');
}
function getConfigFile() {
return path.join(getConfigFolder(), 'config');
}
exports.getConfigFile = getConfigFile;
async function saveConfig(config) {
const configString = JSON.stringify(config);
await io.mkdirP(getConfigFolder());
fs.writeFileSync(getConfigFile(), configString, 'utf8');
core.debug('Saved config:');
core.debug(configString);
}
async function loadConfig() {
const configFile = getConfigFile();
if (fs.existsSync(configFile)) {
const configString = fs.readFileSync(configFile, 'utf8');
core.debug('Loaded config:');
core.debug(configString);
return JSON.parse(configString);
async function getRemoteConfig(configFile, apiDetails) {
// retrieve the various parts of the config location, and ensure they're present
const format = new RegExp("(?<owner>[^/]+)/(?<repo>[^/]+)/(?<path>[^@]+)@(?<ref>.*)");
const pieces = format.exec(configFile);
// 5 = 4 groups + the whole expression
if (pieces === null || pieces.groups === undefined || pieces.length < 5) {
throw new Error(getConfigFileRepoFormatInvalidMessage(configFile));
}
const response = await api
.getApiClient(apiDetails, { allowExternal: true })
.repos.getContent({
owner: pieces.groups.owner,
repo: pieces.groups.repo,
path: pieces.groups.path,
ref: pieces.groups.ref,
});
let fileContents;
if ("content" in response.data && response.data.content !== undefined) {
fileContents = response.data.content;
}
else if (Array.isArray(response.data)) {
throw new Error(getConfigFileDirectoryGivenMessage(configFile));
}
else {
const config = initConfig();
core.debug('Initialized config:');
core.debug(JSON.stringify(config));
await saveConfig(config);
return config;
throw new Error(getConfigFileFormatInvalidMessage(configFile));
}
return yaml.safeLoad(Buffer.from(fileContents, "base64").toString("binary"));
}
exports.loadConfig = loadConfig;
/**
* Get the file path where the parsed config will be stored.
*/
function getPathToParsedConfigFile(tempDir) {
return path.join(tempDir, "config");
}
exports.getPathToParsedConfigFile = getPathToParsedConfigFile;
/**
* Store the given config to the path returned from getPathToParsedConfigFile.
*/
async function saveConfig(config, logger) {
const configString = JSON.stringify(config);
const configFile = getPathToParsedConfigFile(config.tempDir);
fs.mkdirSync(path.dirname(configFile), { recursive: true });
fs.writeFileSync(configFile, 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.
*/
async function getConfig(tempDir, logger) {
const configFile = getPathToParsedConfigFile(tempDir);
if (!fs.existsSync(configFile)) {
return undefined;
}
const configString = fs.readFileSync(configFile, "utf8");
logger.debug("Loaded config:");
logger.debug(configString);
return JSON.parse(configString);
}
exports.getConfig = getConfig;
//# sourceMappingURL=config-utils.js.map

File diff suppressed because one or more lines are too long

919
lib/config-utils.test.js generated

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

91
lib/count-loc.js generated Normal file
View File

@@ -0,0 +1,91 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const github_linguist_1 = require("github-linguist");
const languages_1 = require("./languages");
const util_1 = require("./util");
// Map from linguist language names to language prefixes used in the action and codeql
const linguistToMetrics = {
c: languages_1.Language.cpp,
"c++": languages_1.Language.cpp,
"c#": languages_1.Language.csharp,
go: languages_1.Language.go,
java: languages_1.Language.java,
javascript: languages_1.Language.javascript,
python: languages_1.Language.python,
ruby: languages_1.Language.ruby,
typescript: languages_1.Language.javascript,
};
const nameToLinguist = Object.entries(linguistToMetrics).reduce((obj, [key, name]) => {
if (!obj[name]) {
obj[name] = [];
}
obj[name].push(key);
return obj;
}, {});
function getIdPrefix(language) {
switch (language) {
case languages_1.Language.cpp:
return "cpp";
case languages_1.Language.csharp:
return "cs";
case languages_1.Language.go:
return "go";
case languages_1.Language.java:
return "java";
case languages_1.Language.javascript:
return "js";
case languages_1.Language.python:
return "py";
case languages_1.Language.ruby:
return "rb";
default:
util_1.assertNever(language);
}
}
exports.getIdPrefix = getIdPrefix;
/**
* Count the lines of code of the specified language using the include
* and exclude glob paths.
*
* @param cwd the root directory to start the count from
* @param include glob patterns to include in the search for relevant files
* @param exclude glob patterns to exclude in the search for relevant files
* @param dbLanguages list of languages to include in the results
* @param logger object to log results
*/
async function countLoc(cwd, include, exclude, dbLanguages, logger) {
const result = await new github_linguist_1.LocDir({
cwd,
include: Array.isArray(include) && include.length > 0 ? include : ["**"],
exclude,
analysisLanguages: dbLanguages.flatMap((lang) => nameToLinguist[lang]),
}).loadInfo();
// The analysis counts LoC in all languages. We need to
// extract the languages we care about. Also, note that
// the analysis uses slightly different names for language.
const lineCounts = Object.entries(result.languages).reduce((obj, [language, { code }]) => {
const metricsLanguage = linguistToMetrics[language];
if (metricsLanguage && dbLanguages.includes(metricsLanguage)) {
obj[metricsLanguage] = code + (obj[metricsLanguage] || 0);
}
return obj;
}, {});
if (Object.keys(lineCounts).length) {
logger.debug("Lines of code count:");
for (const [language, count] of Object.entries(lineCounts)) {
logger.debug(` ${language}: ${count}`);
}
}
else {
logger.info("Could not determine the baseline lines of code count in this repository. " +
"Because of this, it will not be possible to compare the lines " +
"of code analyzed by code scanning with the baseline. This will not affect " +
"the results produced by code scanning. If you have any questions, you can " +
"raise an issue at https://github.com/github/codeql-action/issues. Please " +
"include a link to the repository if public, or otherwise information about " +
"the code scanning workflow you are using.");
}
return lineCounts;
}
exports.countLoc = countLoc;
//# sourceMappingURL=count-loc.js.map

1
lib/count-loc.js.map Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"count-loc.js","sourceRoot":"","sources":["../src/count-loc.ts"],"names":[],"mappings":";;AAAA,qDAAyC;AAEzC,2CAAuC;AAEvC,iCAAqC;AAKrC,sFAAsF;AACtF,MAAM,iBAAiB,GAA6B;IAClD,CAAC,EAAE,oBAAQ,CAAC,GAAG;IACf,KAAK,EAAE,oBAAQ,CAAC,GAAG;IACnB,IAAI,EAAE,oBAAQ,CAAC,MAAM;IACrB,EAAE,EAAE,oBAAQ,CAAC,EAAE;IACf,IAAI,EAAE,oBAAQ,CAAC,IAAI;IACnB,UAAU,EAAE,oBAAQ,CAAC,UAAU;IAC/B,MAAM,EAAE,oBAAQ,CAAC,MAAM;IACvB,IAAI,EAAE,oBAAQ,CAAC,IAAI;IACnB,UAAU,EAAE,oBAAQ,CAAC,UAAU;CAChC,CAAC;AAEF,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,MAAM,CAC7D,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,EAAE;IACnB,IAAI,CA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;IACvD,2DAA2D;IAC3D,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,MAAM,CACxD,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE;QAC5B,MAAM,eAAe,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAC;QACpD,IAAI,eAAe,IAAI,WAAW,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE;YAC5D,GAAG,CAAC,eAAe,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC;SAC3D;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAA8B,CAC/B,CAAC;IAEF,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,EAAE;QAClC,MAAM,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAC;QACrC,KAAK,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE;YAC1D,MAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,KAAK,KAAK,EAAE,CAAC,CAAC;SACzC;KACF;SAAM;QACL,MAAM,CAAC,IAAI,CACT,2EAA2E;YACzE,gEAAgE;YAChE,4EAA4E;YAC5E,4EAA4E;YAC5E,2EAA2E;YAC3E,6EAA6E;YAC7E,2CAA2C,CAC9C,CAAC;KACH;IAED,OAAO,UAAU,CAAC;AACpB,CAAC;AA9CD,4BA8CC"}

66
lib/count-loc.test.js generated Normal file
View File

@@ -0,0 +1,66 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(require("path"));
const ava_1 = __importDefault(require("ava"));
const count_loc_1 = require("./count-loc");
const languages_1 = require("./languages");
const logging_1 = require("./logging");
const testing_utils_1 = require("./testing-utils");
testing_utils_1.setupTests(ava_1.default);
ava_1.default("ensure lines of code works for cpp and js", async (t) => {
const results = await count_loc_1.countLoc(path.join(__dirname, "../tests/multi-language-repo"), [], [], [languages_1.Language.cpp, languages_1.Language.javascript], logging_1.getRunnerLogger(true));
t.deepEqual(results, {
cpp: 6,
javascript: 9,
});
});
ava_1.default("ensure lines of code works for csharp", async (t) => {
const results = await count_loc_1.countLoc(path.join(__dirname, "../tests/multi-language-repo"), [], [], [languages_1.Language.csharp], logging_1.getRunnerLogger(true));
t.deepEqual(results, {
csharp: 10,
});
});
ava_1.default("ensure lines of code can handle undefined language", async (t) => {
const results = await count_loc_1.countLoc(path.join(__dirname, "../tests/multi-language-repo"), [], [], [languages_1.Language.javascript, languages_1.Language.python, "hucairz"], logging_1.getRunnerLogger(true));
t.deepEqual(results, {
javascript: 9,
python: 5,
});
});
ava_1.default("ensure lines of code can handle empty languages", async (t) => {
const results = await count_loc_1.countLoc(path.join(__dirname, "../tests/multi-language-repo"), [], [], [], logging_1.getRunnerLogger(true));
t.deepEqual(results, {});
});
ava_1.default("ensure lines of code can handle includes", async (t) => {
// note that "**" is always included. The includes are for extra
// directories outside the normal structure.
const results = await count_loc_1.countLoc(path.join(__dirname, "../tests/multi-language-repo"), ["../../src/testdata"], [], [languages_1.Language.javascript], logging_1.getRunnerLogger(true));
t.deepEqual(results, {
javascript: 12,
});
});
ava_1.default("ensure lines of code can handle empty includes", async (t) => {
// note that "**" is always included. The includes are for extra
// directories outside the normal structure.
const results = await count_loc_1.countLoc(path.join(__dirname, "../tests/multi-language-repo"), ["idontexist"], [], [languages_1.Language.javascript], logging_1.getRunnerLogger(true));
t.deepEqual(results, {
// should get no results
});
});
ava_1.default("ensure lines of code can handle exclude", async (t) => {
const results = await count_loc_1.countLoc(path.join(__dirname, "../tests/multi-language-repo"), [], ["**/*.py"], [languages_1.Language.javascript, languages_1.Language.python], logging_1.getRunnerLogger(true));
t.deepEqual(results, {
javascript: 9,
});
});
//# sourceMappingURL=count-loc.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"count-loc.test.js","sourceRoot":"","sources":["../src/count-loc.test.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAA6B;AAE7B,8CAAuB;AAEvB,2CAAuC;AACvC,2CAAuC;AACvC,uCAA4C;AAC5C,mDAA6C;AAE7C,0BAAU,CAAC,aAAI,CAAC,CAAC;AAEjB,aAAI,CAAC,2CAA2C,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE;IAC5D,MAAM,OAAO,GAAG,MAAM,oBAAQ,CAC5B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,8BAA8B,CAAC,EACpD,EAAE,EACF,EAAE,EACF,CAAC,oBAAQ,CAAC,GAAG,EAAE,oBAAQ,CAAC,UAAU,CAAC,EACnC,yBAAe,CAAC,IAAI,CAAC,CACtB,CAAC;IAEF,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE;QACnB,GAAG,EAAE,CAAC;QACN,UAAU,EAAE,CAAC;KACd,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,aAAI,CAAC,uCAAuC,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE;IACxD,MAAM,OAAO,GAAG,MAAM,oBAAQ,CAC5B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,8BAA8B,CAAC,EACpD,EAAE,EACF,EAAE,EACF,CAAC,oBAAQ,CAAC,MAAM,CAAC,EACjB,yBAAe,CAAC,IAAI,CAAC,CACtB,CAAC;IAEF,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE;QACnB,MAAM,EAAE,EAAE;KACX,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,aAAI,CAAC,oDAAoD,EAAE,KAAK,EAAE,CAAC,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,MAAM,oBAAQ,CAC5B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,8BAA8B,CAAC,EACpD,CAAC,YAAY,CAAC,EACd,EAAE,EACF,CAAC,oBAAQ,CAAC,UAAU,CAAC,EACrB,yBAAe,CAAC,IAAI,CAAC,CACtB,CAAC;IAEF,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE;IACnB,wBAAwB;KACzB,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,aAAI,CAAC,yCAAyC,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE;IAC1D,MAAM,OAAO,GAAG,MAAM,oBAAQ,CAC5B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,8BAA8B,CAAC,EACpD,EAAE,EACF,CAAC,SAAS,CAAC,EACX,CAAC,oBAAQ,CAAC,UAAU,EAAE,oBAAQ,CAAC,MAAM,CAAC,EACtC,yBAAe,CAAC,IAAI,CAAC,CACtB,CAAC;IAEF,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE;QACnB,UAAU,EAAE,CAAC;KACd,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

72
lib/database-upload.js generated Normal file
View File

@@ -0,0 +1,72 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const actionsUtil = __importStar(require("./actions-util"));
const api_client_1 = require("./api-client");
const codeql_1 = require("./codeql");
const util = __importStar(require("./util"));
async function uploadDatabases(repositoryNwo, config, apiDetails, logger) {
if (actionsUtil.getRequiredInput("upload-database") !== "true") {
logger.debug("Database upload disabled in workflow. Skipping upload.");
return;
}
// Do nothing when not running against github.com
if (config.gitHubVersion.type !== util.GitHubVariant.DOTCOM) {
logger.debug("Not running against github.com. Skipping upload.");
return;
}
if (!(await actionsUtil.isAnalyzingDefaultBranch())) {
// We only want to upload a database if we are analyzing the default branch.
logger.debug("Not analyzing default branch. Skipping upload.");
return;
}
const client = api_client_1.getApiClient(apiDetails);
try {
await client.request("GET /repos/:owner/:repo/code-scanning/codeql/databases", {
owner: repositoryNwo.owner,
repo: repositoryNwo.repo,
});
}
catch (e) {
if (util.isHTTPError(e) && e.status === 404) {
logger.debug("Repository is not opted in to database uploads. Skipping upload.");
}
else {
console.log(e);
logger.info(`Skipping database upload due to unknown error: ${e}`);
}
return;
}
const codeql = codeql_1.getCodeQL(config.codeQLCmd);
for (const language of config.languages) {
// Bundle the database up into a single zip file
const databasePath = util.getCodeQLDatabasePath(config, language);
const databaseBundlePath = `${databasePath}.zip`;
await codeql.databaseBundle(databasePath, databaseBundlePath);
// Upload the database bundle
const payload = fs.readFileSync(databaseBundlePath);
try {
await client.request(`PUT /repos/:owner/:repo/code-scanning/codeql/databases/:language`, {
owner: repositoryNwo.owner,
repo: repositoryNwo.repo,
language,
data: payload,
});
logger.debug(`Successfully uploaded database for ${language}`);
}
catch (e) {
console.log(e);
// Log a warning but don't fail the workflow
logger.warning(`Failed to upload database for ${language}: ${e}`);
}
}
}
exports.uploadDatabases = uploadDatabases;
//# sourceMappingURL=database-upload.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"database-upload.js","sourceRoot":"","sources":["../src/database-upload.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAyB;AAEzB,4DAA8C;AAC9C,6CAA8D;AAC9D,qCAAqC;AAIrC,6CAA+B;AAExB,KAAK,UAAU,eAAe,CACnC,aAA4B,EAC5B,MAAc,EACd,UAA4B,EAC5B,MAAc;IAEd,IAAI,WAAW,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,KAAK,MAAM,EAAE;QAC9D,MAAM,CAAC,KAAK,CAAC,wDAAwD,CAAC,CAAC;QACvE,OAAO;KACR;IAED,iDAAiD;IACjD,IAAI,MAAM,CAAC,aAAa,CAAC,IAAI,KAAK,IAAI,C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,kEAAkE,EAClE;gBACE,KAAK,EAAE,aAAa,CAAC,KAAK;gBAC1B,IAAI,EAAE,aAAa,CAAC,IAAI;gBACxB,QAAQ;gBACR,IAAI,EAAE,OAAO;aACd,CACF,CAAC;YACF,MAAM,CAAC,KAAK,CAAC,sCAAsC,QAAQ,EAAE,CAAC,CAAC;SAChE;QAAC,OAAO,CAAC,EAAE;YACV,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YACf,4CAA4C;YAC5C,MAAM,CAAC,OAAO,CAAC,iCAAiC,QAAQ,KAAK,CAAC,EAAE,CAAC,CAAC;SACnE;KACF;AACH,CAAC;AAtED,0CAsEC"}

236
lib/database-upload.test.js generated Normal file
View File

@@ -0,0 +1,236 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const github = __importStar(require("@actions/github"));
const ava_1 = __importDefault(require("ava"));
const sinon_1 = __importDefault(require("sinon"));
const actionsUtil = __importStar(require("./actions-util"));
const apiClient = __importStar(require("./api-client"));
const codeql_1 = require("./codeql");
const database_upload_1 = require("./database-upload");
const languages_1 = require("./languages");
const testing_utils_1 = require("./testing-utils");
const util_1 = require("./util");
testing_utils_1.setupTests(ava_1.default);
ava_1.default.beforeEach(() => {
util_1.initializeEnvironment(util_1.Mode.actions, "1.2.3");
});
const testRepoName = { owner: "github", repo: "example" };
const testApiDetails = {
auth: "1234",
url: "https://github.com",
};
function getTestConfig(tmpDir) {
return {
languages: [languages_1.Language.javascript],
queries: {},
pathsIgnore: [],
paths: [],
originalUserInput: {},
tempDir: tmpDir,
toolCacheDir: tmpDir,
codeQLCmd: "foo",
gitHubVersion: { type: util_1.GitHubVariant.DOTCOM },
dbLocation: tmpDir,
packs: {},
};
}
function getRecordingLogger(messages) {
return {
debug: (message) => {
messages.push({ type: "debug", message });
console.debug(message);
},
info: (message) => {
messages.push({ type: "info", message });
console.info(message);
},
warning: (message) => {
messages.push({ type: "warning", message });
console.warn(message);
},
error: (message) => {
messages.push({ type: "error", message });
console.error(message);
},
isDebug: () => true,
startGroup: () => undefined,
endGroup: () => undefined,
};
}
function mockHttpRequests(optInStatusCode, databaseUploadStatusCode) {
// Passing an auth token is required, so we just use a dummy value
const client = github.getOctokit("123");
const requestSpy = sinon_1.default.stub(client, "request");
const optInSpy = requestSpy.withArgs("GET /repos/:owner/:repo/code-scanning/codeql/databases");
if (optInStatusCode < 300) {
optInSpy.resolves(undefined);
}
else {
optInSpy.throws(new util_1.HTTPError("some error message", optInStatusCode));
}
if (databaseUploadStatusCode !== undefined) {
const databaseUploadSpy = requestSpy.withArgs("PUT /repos/:owner/:repo/code-scanning/codeql/databases/:language");
if (databaseUploadStatusCode < 300) {
databaseUploadSpy.resolves(undefined);
}
else {
databaseUploadSpy.throws(new util_1.HTTPError("some error message", databaseUploadStatusCode));
}
}
sinon_1.default.stub(apiClient, "getApiClient").value(() => client);
}
ava_1.default("Abort database upload if 'upload-database' input set to false", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
sinon_1.default
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("false");
sinon_1.default.stub(actionsUtil, "isAnalyzingDefaultBranch").resolves(true);
const loggedMessages = [];
await database_upload_1.uploadDatabases(testRepoName, getTestConfig(tmpDir), testApiDetails, getRecordingLogger(loggedMessages));
t.assert(loggedMessages.find((v) => v.type === "debug" &&
v.message === "Database upload disabled in workflow. Skipping upload.") !== undefined);
});
});
ava_1.default("Abort database upload if running against GHES", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
sinon_1.default
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("true");
sinon_1.default.stub(actionsUtil, "isAnalyzingDefaultBranch").resolves(true);
const config = getTestConfig(tmpDir);
config.gitHubVersion = { type: util_1.GitHubVariant.GHES, version: "3.0" };
const loggedMessages = [];
await database_upload_1.uploadDatabases(testRepoName, config, testApiDetails, getRecordingLogger(loggedMessages));
t.assert(loggedMessages.find((v) => v.type === "debug" &&
v.message === "Not running against github.com. Skipping upload.") !== undefined);
});
});
ava_1.default("Abort database upload if running against GHAE", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
sinon_1.default
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("true");
sinon_1.default.stub(actionsUtil, "isAnalyzingDefaultBranch").resolves(true);
const config = getTestConfig(tmpDir);
config.gitHubVersion = { type: util_1.GitHubVariant.GHAE };
const loggedMessages = [];
await database_upload_1.uploadDatabases(testRepoName, config, testApiDetails, getRecordingLogger(loggedMessages));
t.assert(loggedMessages.find((v) => v.type === "debug" &&
v.message === "Not running against github.com. Skipping upload.") !== undefined);
});
});
ava_1.default("Abort database upload if not analyzing default branch", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
sinon_1.default
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("true");
sinon_1.default.stub(actionsUtil, "isAnalyzingDefaultBranch").resolves(false);
const loggedMessages = [];
await database_upload_1.uploadDatabases(testRepoName, getTestConfig(tmpDir), testApiDetails, getRecordingLogger(loggedMessages));
t.assert(loggedMessages.find((v) => v.type === "debug" &&
v.message === "Not analyzing default branch. Skipping upload.") !== undefined);
});
});
ava_1.default("Abort database upload if opt-in request returns 404", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
sinon_1.default
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("true");
sinon_1.default.stub(actionsUtil, "isAnalyzingDefaultBranch").resolves(true);
mockHttpRequests(404);
codeql_1.setCodeQL({
async databaseBundle() {
return;
},
});
const loggedMessages = [];
await database_upload_1.uploadDatabases(testRepoName, getTestConfig(tmpDir), testApiDetails, getRecordingLogger(loggedMessages));
t.assert(loggedMessages.find((v) => v.type === "debug" &&
v.message ===
"Repository is not opted in to database uploads. Skipping upload.") !== undefined);
});
});
ava_1.default("Abort database upload if opt-in request fails with something other than 404", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
sinon_1.default
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("true");
sinon_1.default.stub(actionsUtil, "isAnalyzingDefaultBranch").resolves(true);
mockHttpRequests(500);
codeql_1.setCodeQL({
async databaseBundle() {
return;
},
});
const loggedMessages = [];
await database_upload_1.uploadDatabases(testRepoName, getTestConfig(tmpDir), testApiDetails, getRecordingLogger(loggedMessages));
t.assert(loggedMessages.find((v) => v.type === "info" &&
v.message ===
"Skipping database upload due to unknown error: Error: some error message") !== undefined);
});
});
ava_1.default("Don't crash if uploading a database fails", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
sinon_1.default
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("true");
sinon_1.default.stub(actionsUtil, "isAnalyzingDefaultBranch").resolves(true);
mockHttpRequests(204, 500);
codeql_1.setCodeQL({
async databaseBundle(_, outputFilePath) {
fs.writeFileSync(outputFilePath, "");
},
});
const loggedMessages = [];
await database_upload_1.uploadDatabases(testRepoName, getTestConfig(tmpDir), testApiDetails, getRecordingLogger(loggedMessages));
t.assert(loggedMessages.find((v) => v.type === "warning" &&
v.message ===
"Failed to upload database for javascript: Error: some error message") !== undefined);
});
});
ava_1.default("Successfully uploading a database", async (t) => {
await util_1.withTmpDir(async (tmpDir) => {
testing_utils_1.setupActionsVars(tmpDir, tmpDir);
sinon_1.default
.stub(actionsUtil, "getRequiredInput")
.withArgs("upload-database")
.returns("true");
sinon_1.default.stub(actionsUtil, "isAnalyzingDefaultBranch").resolves(true);
mockHttpRequests(204, 201);
codeql_1.setCodeQL({
async databaseBundle(_, outputFilePath) {
fs.writeFileSync(outputFilePath, "");
},
});
const loggedMessages = [];
await database_upload_1.uploadDatabases(testRepoName, getTestConfig(tmpDir), testApiDetails, getRecordingLogger(loggedMessages));
t.assert(loggedMessages.find((v) => v.type === "debug" &&
v.message === "Successfully uploaded database for javascript") !== undefined);
});
});
//# sourceMappingURL=database-upload.test.js.map

File diff suppressed because one or more lines are too long

3
lib/defaults.json Normal file
View File

@@ -0,0 +1,3 @@
{
"bundleVersion": "codeql-bundle-20210702"
}

17
lib/error-matcher.js generated Normal file
View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// exported only for testing purposes
exports.namedMatchersForTesting = {
/*
In due course it may be possible to remove the regex, if/when javascript also exits with code 32.
*/
noSourceCodeFound: {
exitCode: 32,
outputRegex: new RegExp("No JavaScript or TypeScript code found\\."),
message: "No code found during the build. Please see:\n" +
"https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/troubleshooting-code-scanning#no-code-found-during-the-build",
},
};
// we collapse the matches into an array for use in execErrorCatcher
exports.errorMatchers = Object.values(exports.namedMatchersForTesting);
//# sourceMappingURL=error-matcher.js.map

1
lib/error-matcher.js.map Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"error-matcher.js","sourceRoot":"","sources":["../src/error-matcher.ts"],"names":[],"mappings":";;AAQA,qCAAqC;AACxB,QAAA,uBAAuB,GAAoC;IACtE;;MAEE;IACF,iBAAiB,EAAE;QACjB,QAAQ,EAAE,EAAE;QACZ,WAAW,EAAE,IAAI,MAAM,CAAC,2CAA2C,CAAC;QACpE,OAAO,EACL,+CAA+C;YAC/C,yJAAyJ;KAC5J;CACF,CAAC;AAEF,oEAAoE;AACvD,QAAA,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,+BAAuB,CAAC,CAAC"}

29
lib/error-matcher.test.js generated Normal file
View File

@@ -0,0 +1,29 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = __importDefault(require("ava"));
const error_matcher_1 = require("./error-matcher");
/*
NB We test the regexes for all the matchers against example log output snippets.
*/
ava_1.default("noSourceCodeFound matches against example javascript output", async (t) => {
t.assert(testErrorMatcher("noSourceCodeFound", `
2020-09-07T17:39:53.9050522Z [2020-09-07 17:39:53] [build] Done extracting /opt/hostedtoolcache/CodeQL/0.0.0-20200630/x64/codeql/javascript/tools/data/externs/web/ie_vml.js (3 ms)
2020-09-07T17:39:53.9051849Z [2020-09-07 17:39:53] [build-err] No JavaScript or TypeScript code found.
2020-09-07T17:39:53.9052444Z [2020-09-07 17:39:53] [build-err] No JavaScript or TypeScript code found.
2020-09-07T17:39:53.9251124Z [2020-09-07 17:39:53] [ERROR] Spawned process exited abnormally (code 255; tried to run: [/opt/hostedtoolcache/CodeQL/0.0.0-20200630/x64/codeql/javascript/tools/autobuild.sh])
`));
});
function testErrorMatcher(matcherName, logSample) {
if (!(matcherName in error_matcher_1.namedMatchersForTesting)) {
throw new Error(`Unknown matcher ${matcherName}`);
}
const regex = error_matcher_1.namedMatchersForTesting[matcherName].outputRegex;
if (regex === undefined) {
throw new Error(`Cannot test matcher ${matcherName} with null regex`);
}
return regex.test(logSample);
}
//# sourceMappingURL=error-matcher.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"error-matcher.test.js","sourceRoot":"","sources":["../src/error-matcher.test.ts"],"names":[],"mappings":";;;;;AAAA,8CAAuB;AAEvB,mDAA0D;AAE1D;;EAEE;AAEF,aAAI,CAAC,6DAA6D,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE;IAC9E,CAAC,CAAC,MAAM,CACN,gBAAgB,CACd,mBAAmB,EACnB;;;;;GAKH,CACE,CACF,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,SAAS,gBAAgB,CAAC,WAAmB,EAAE,SAAiB;IAC9D,IAAI,CAAC,CAAC,WAAW,IAAI,uCAAuB,CAAC,EAAE;QAC7C,MAAM,IAAI,KAAK,CAAC,mBAAmB,WAAW,EAAE,CAAC,CAAC;KACnD;IACD,MAAM,KAAK,GAAG,uCAAuB,CAAC,WAAW,CAAC,CAAC,WAAW,CAAC;IAC/D,IAAI,KAAK,KAAK,SAAS,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,uBAAuB,WAAW,kBAAkB,CAAC,CAAC;KACvE;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AAC/B,CAAC"}

View File

@@ -7,27 +7,48 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const util = __importStar(require("./util"));
async function checkoutExternalQueries(config) {
const folder = util.getRequiredEnvParam('RUNNER_WORKSPACE');
for (const externalQuery of config.externalQueries) {
core.info('Checking out ' + externalQuery.repository);
const checkoutLocation = path.join(folder, externalQuery.repository);
if (!fs.existsSync(checkoutLocation)) {
const repoURL = 'https://github.com/' + externalQuery.repository + '.git';
await exec.exec('git', ['clone', repoURL, checkoutLocation]);
await exec.exec('git', [
'--work-tree=' + checkoutLocation,
'--git-dir=' + checkoutLocation + '/.git',
'checkout', externalQuery.ref,
]);
}
config.additionalQueries.push(path.join(checkoutLocation, externalQuery.path));
const toolrunner = __importStar(require("@actions/exec/lib/toolrunner"));
const safeWhich = __importStar(require("@chrisgavin/safe-which"));
/**
* Check out repository at the given ref, and return the directory of the checkout.
*/
async function checkoutExternalRepository(repository, ref, apiDetails, tempDir, logger) {
logger.info(`Checking out ${repository}`);
const checkoutLocation = path.join(tempDir, repository, ref);
if (!checkoutLocation.startsWith(tempDir)) {
// this still permits locations that mess with sibling repositories in `tempDir`, but that is acceptable
throw new Error(`'${repository}@${ref}' is not a valid repository and reference.`);
}
if (!fs.existsSync(checkoutLocation)) {
const repoCloneURL = buildCheckoutURL(repository, apiDetails);
await new toolrunner.ToolRunner(await safeWhich.safeWhich("git"), [
"clone",
repoCloneURL,
checkoutLocation,
]).exec();
await new toolrunner.ToolRunner(await safeWhich.safeWhich("git"), [
`--work-tree=${checkoutLocation}`,
`--git-dir=${checkoutLocation}/.git`,
"checkout",
ref,
]).exec();
}
return checkoutLocation;
}
exports.checkoutExternalQueries = checkoutExternalQueries;
exports.checkoutExternalRepository = checkoutExternalRepository;
function buildCheckoutURL(repository, apiDetails) {
const repoCloneURL = new URL(apiDetails.url);
if (apiDetails.externalRepoAuth !== undefined) {
repoCloneURL.username = "x-access-token";
repoCloneURL.password = apiDetails.externalRepoAuth;
}
if (!repoCloneURL.pathname.endsWith("/")) {
repoCloneURL.pathname += "/";
}
repoCloneURL.pathname += `${repository}`;
return repoCloneURL.toString();
}
exports.buildCheckoutURL = buildCheckoutURL;
//# sourceMappingURL=external-queries.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"external-queries.js","sourceRoot":"","sources":["../src/external-queries.ts"],"names":[],"mappings":";;;;;;;;;AAAA,oDAAsC;AACtC,oDAAsC;AACtC,uCAAyB;AACzB,2CAA6B;AAG7B,6CAA+B;AAExB,KAAK,UAAU,uBAAuB,CAAC,MAA0B;IACtE,MAAM,MAAM,GAAG,IAAI,CAAC,mBAAmB,CAAC,kBAAkB,CAAC,CAAC;IAE5D,KAAK,MAAM,aAAa,IAAI,MAAM,CAAC,eAAe,EAAE;QAClD,IAAI,CAAC,IAAI,CAAC,eAAe,GAAG,aAAa,CAAC,UAAU,CAAC,CAAC;QAEtD,MAAM,gBAAgB,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;QACrE,IAAI,C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,CAAC;QAC9D,MAAM,IAAI,UAAU,CAAC,UAAU,CAAC,MAAM,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE;YAChE,OAAO;YACP,YAAY;YACZ,gBAAgB;SACjB,CAAC,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,UAAU,CAAC,UAAU,CAAC,MAAM,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE;YAChE,eAAe,gBAAgB,EAAE;YACjC,aAAa,gBAAgB,OAAO;YACpC,UAAU;YACV,GAAG;SACJ,CAAC,CAAC,IAAI,EAAE,CAAC;KACX;IAED,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAlCD,gEAkCC;AAED,SAAgB,gBAAgB,CAC9B,UAAkB,EAClB,UAAwC;IAExC,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC7C,IAAI,UAAU,CAAC,gBAAgB,KAAK,SAAS,EAAE;QAC7C,YAAY,CAAC,QAAQ,GAAG,gBAAgB,CAAC;QACzC,YAAY,CAAC,QAAQ,GAAG,UAAU,CAAC,gBAAgB,CAAC;KACrD;IACD,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;QACxC,YAAY,CAAC,QAAQ,IAAI,GAAG,CAAC;KAC9B;IACD,YAAY,CAAC,QAAQ,IAAI,GAAG,UAAU,EAAE,CAAC;IACzC,OAAO,YAAY,CAAC,QAAQ,EAAE,CAAC;AACjC,CAAC;AAdD,4CAcC"}

View File

@@ -1,7 +1,4 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
@@ -9,23 +6,110 @@ var __importStar = (this && this.__importStar) || function (mod) {
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = __importDefault(require("ava"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const configUtils = __importStar(require("./config-utils"));
const toolrunner = __importStar(require("@actions/exec/lib/toolrunner"));
const safeWhich = __importStar(require("@chrisgavin/safe-which"));
const ava_1 = __importDefault(require("ava"));
const externalQueries = __importStar(require("./external-queries"));
const logging_1 = require("./logging");
const testing_utils_1 = require("./testing-utils");
const util = __importStar(require("./util"));
testing_utils_1.setupTests(ava_1.default);
ava_1.default("checkoutExternalQueries", async (t) => {
let config = new configUtils.Config();
config.externalQueries = [
new configUtils.ExternalQuery("github/codeql-go", "df4c6869212341b601005567381944ed90906b6b"),
];
await util.withTmpDir(async (tmpDir) => {
process.env["RUNNER_WORKSPACE"] = tmpDir;
await externalQueries.checkoutExternalQueries(config);
// COPYRIGHT file existed in df4c6869212341b601005567381944ed90906b6b but not in master
t.true(fs.existsSync(path.join(tmpDir, "github", "codeql-go", "COPYRIGHT")));
// Create a test repo in a subdir of the temp dir.
// It should have a default branch with two commits after the initial commit, where
// - the first commit contains files 'a' and 'b'
// - the second commit contains only 'a'
// Place the repo in a subdir because we're going to checkout a copy in tmpDir
const testRepoBaseDir = path.join(tmpDir, "test-repo-dir");
const repoName = "some/repo";
const repoPath = path.join(testRepoBaseDir, repoName);
const repoGitDir = path.join(repoPath, ".git");
// Run the given git command, and return the output.
// Passes --git-dir and --work-tree.
// Any stderr output is suppressed until the command fails.
const runGit = async function (command) {
let stdout = "";
let stderr = "";
command = [
`--git-dir=${repoGitDir}`,
`--work-tree=${repoPath}`,
...command,
];
console.log(`Running: git ${command.join(" ")}`);
try {
await new toolrunner.ToolRunner(await safeWhich.safeWhich("git"), command, {
silent: true,
listeners: {
stdout: (data) => {
stdout += data.toString();
},
stderr: (data) => {
stderr += data.toString();
},
},
}).exec();
}
catch (e) {
console.log(`Command failed: git ${command.join(" ")}`);
process.stderr.write(stderr);
throw e;
}
return stdout.trim();
};
fs.mkdirSync(repoPath, { recursive: true });
await runGit(["init", repoPath]);
await runGit(["config", "user.email", "test@github.com"]);
await runGit(["config", "user.name", "Test Test"]);
await runGit(["config", "commit.gpgsign", "false"]);
fs.writeFileSync(path.join(repoPath, "a"), "a content");
await runGit(["add", "a"]);
await runGit(["commit", "-m", "commit1"]);
fs.writeFileSync(path.join(repoPath, "b"), "b content");
await runGit(["add", "b"]);
await runGit(["commit", "-m", "commit1"]);
const commit1Sha = await runGit(["rev-parse", "HEAD"]);
fs.unlinkSync(path.join(repoPath, "b"));
await runGit(["add", "b"]);
await runGit(["commit", "-m", "commit2"]);
const commit2Sha = await runGit(["rev-parse", "HEAD"]);
// Checkout the first commit, which should contain 'a' and 'b'
t.false(fs.existsSync(path.join(tmpDir, repoName)));
await externalQueries.checkoutExternalRepository(repoName, commit1Sha, { url: `file://${testRepoBaseDir}`, externalRepoAuth: "" }, tmpDir, logging_1.getRunnerLogger(true));
t.true(fs.existsSync(path.join(tmpDir, repoName)));
t.true(fs.existsSync(path.join(tmpDir, repoName, commit1Sha)));
t.true(fs.existsSync(path.join(tmpDir, repoName, commit1Sha, "a")));
t.true(fs.existsSync(path.join(tmpDir, repoName, commit1Sha, "b")));
// Checkout the second commit as well, which should only contain 'a'
t.false(fs.existsSync(path.join(tmpDir, repoName, commit2Sha)));
await externalQueries.checkoutExternalRepository(repoName, commit2Sha, { url: `file://${testRepoBaseDir}`, externalRepoAuth: "" }, tmpDir, logging_1.getRunnerLogger(true));
t.true(fs.existsSync(path.join(tmpDir, repoName, commit2Sha)));
t.true(fs.existsSync(path.join(tmpDir, repoName, commit2Sha, "a")));
t.false(fs.existsSync(path.join(tmpDir, repoName, commit2Sha, "b")));
});
});
ava_1.default("buildCheckoutURL", (t) => {
t.deepEqual(externalQueries.buildCheckoutURL("foo/bar", {
url: "https://github.com",
externalRepoAuth: undefined,
}), "https://github.com/foo/bar");
t.deepEqual(externalQueries.buildCheckoutURL("foo/bar", {
url: "https://github.example.com/",
externalRepoAuth: undefined,
}), "https://github.example.com/foo/bar");
t.deepEqual(externalQueries.buildCheckoutURL("foo/bar", {
url: "https://github.com",
externalRepoAuth: "abc",
}), "https://x-access-token:abc@github.com/foo/bar");
t.deepEqual(externalQueries.buildCheckoutURL("foo/bar", {
url: "https://github.example.com/",
externalRepoAuth: "abc",
}), "https://x-access-token:abc@github.example.com/foo/bar");
});
//# sourceMappingURL=external-queries.test.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"external-queries.test.js","sourceRoot":"","sources":["../src/external-queries.test.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,8CAAuB;AACvB,uCAAyB;AACzB,2CAA6B;AAE7B,4DAA8C;AAC9C,oEAAsD;AACtD,6CAA+B;AAE/B,aAAI,CAAC,yBAAyB,EAAE,KAAK,EAAC,CAAC,EAAC,EAAE;IACtC,IAAI,MAAM,GAAG,IAAI,WAAW,CAAC,MAAM,EAAE,CAAC;IACtC,MAAM,CAAC,eAAe,GAAG;QACrB,IAAI,WAAW,CAAC,aAAa,CAAC,kBAAkB,EAAE,0CAA0C,CAAC;KAChG,CAAC;IAEF,MAAM,IAAI,CAAC,UAAU,CAAC,KAAK,EAAC,MAAM,EAAC,EAAE;QACjC,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,GAAG,MAAM,CAAC;QACzC,MAAM,eAAe,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;QAEtD,uFAAuF;QACvF,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC;IACjF,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"}
{"version":3,"file":"external-queries.test.js","sourceRoot":"","sources":["../src/external-queries.test.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAE7B,yEAA2D;AAC3D,kEAAoD;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BAA6B;QAClC,gBAAgB,EAAE,SAAS;KAC5B,CAAC,EACF,oCAAoC,CACrC,CAAC;IAEF,CAAC,CAAC,SAAS,CACT,eAAe,CAAC,gBAAgB,CAAC,SAAS,EAAE;QAC1C,GAAG,EAAE,oBAAoB;QACzB,gBAAgB,EAAE,KAAK;KACxB,CAAC,EACF,+CAA+C,CAChD,CAAC;IACF,CAAC,CAAC,SAAS,CACT,eAAe,CAAC,gBAAgB,CAAC,SAAS,EAAE;QAC1C,GAAG,EAAE,6BAA6B;QAClC,gBAAgB,EAAE,KAAK;KACxB,CAAC,EACF,uDAAuD,CACxD,CAAC;AACJ,CAAC,CAAC,CAAC"}

164
lib/finalize-db.js generated
View File

@@ -1,164 +0,0 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec"));
const io = __importStar(require("@actions/io"));
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const configUtils = __importStar(require("./config-utils"));
const externalQueries = __importStar(require("./external-queries"));
const sharedEnv = __importStar(require("./shared-environment"));
const upload_lib = __importStar(require("./upload-lib"));
const util = __importStar(require("./util"));
function getMemoryFlag() {
let memoryToUseMegaBytes;
const memoryToUseString = core.getInput("ram");
if (memoryToUseString) {
memoryToUseMegaBytes = Number(memoryToUseString);
if (Number.isNaN(memoryToUseMegaBytes) || memoryToUseMegaBytes <= 0) {
throw new Error("Invalid RAM setting \"" + memoryToUseString + "\", specified.");
}
}
else {
const totalMemoryBytes = os.totalmem();
const totalMemoryMegaBytes = totalMemoryBytes / (1024 * 1024);
const systemReservedMemoryMegaBytes = 256;
memoryToUseMegaBytes = totalMemoryMegaBytes - systemReservedMemoryMegaBytes;
}
return "--ram=" + Math.floor(memoryToUseMegaBytes);
}
async function createdDBForScannedLanguages(codeqlCmd, databaseFolder) {
const scannedLanguages = process.env[sharedEnv.CODEQL_ACTION_SCANNED_LANGUAGES];
if (scannedLanguages) {
for (const language of scannedLanguages.split(',')) {
core.startGroup('Extracting ' + language);
// Get extractor location
let extractorPath = '';
await exec.exec(codeqlCmd, ['resolve', 'extractor', '--format=json', '--language=' + language], {
silent: true,
listeners: {
stdout: (data) => { extractorPath += data.toString(); },
stderr: (data) => { process.stderr.write(data); }
}
});
// Set trace command
const ext = process.platform === 'win32' ? '.cmd' : '.sh';
const traceCommand = path.resolve(JSON.parse(extractorPath), 'tools', 'autobuild' + ext);
// Run trace command
await exec.exec(codeqlCmd, ['database', 'trace-command', path.join(databaseFolder, language), '--', traceCommand]);
core.endGroup();
}
}
}
async function finalizeDatabaseCreation(codeqlCmd, databaseFolder) {
await createdDBForScannedLanguages(codeqlCmd, databaseFolder);
const languages = process.env[sharedEnv.CODEQL_ACTION_LANGUAGES] || '';
for (const language of languages.split(',')) {
core.startGroup('Finalizing ' + language);
await exec.exec(codeqlCmd, ['database', 'finalize', path.join(databaseFolder, language)]);
core.endGroup();
}
}
async function resolveQueryLanguages(codeqlCmd, config) {
let res = new Map();
if (config.additionalQueries.length !== 0) {
let resolveQueriesOutput = '';
const options = {
listeners: {
stdout: (data) => {
resolveQueriesOutput += data.toString();
}
}
};
await exec.exec(codeqlCmd, [
'resolve',
'queries',
...config.additionalQueries,
'--format=bylanguage'
], options);
const resolveQueriesOutputObject = JSON.parse(resolveQueriesOutput);
for (const [language, queries] of Object.entries(resolveQueriesOutputObject.byLanguage)) {
res[language] = Object.keys(queries);
}
const noDeclaredLanguage = resolveQueriesOutputObject.noDeclaredLanguage;
const noDeclaredLanguageQueries = Object.keys(noDeclaredLanguage);
if (noDeclaredLanguageQueries.length !== 0) {
throw new Error('Some queries do not declare a language, their qlpack.yml file is missing or is invalid');
}
const multipleDeclaredLanguages = resolveQueriesOutputObject.multipleDeclaredLanguages;
const multipleDeclaredLanguagesQueries = Object.keys(multipleDeclaredLanguages);
if (multipleDeclaredLanguagesQueries.length !== 0) {
throw new Error('Some queries declare multiple languages, their qlpack.yml file is missing or is invalid');
}
}
return res;
}
// Runs queries and creates sarif files in the given folder
async function runQueries(codeqlCmd, databaseFolder, sarifFolder, config) {
const queriesPerLanguage = await resolveQueryLanguages(codeqlCmd, config);
for (let database of fs.readdirSync(databaseFolder)) {
core.startGroup('Analyzing ' + database);
const queries = [];
if (!config.disableDefaultQueries) {
queries.push(database + '-code-scanning.qls');
}
queries.push(...(queriesPerLanguage[database] || []));
const sarifFile = path.join(sarifFolder, database + '.sarif');
await exec.exec(codeqlCmd, [
'database',
'analyze',
getMemoryFlag(),
path.join(databaseFolder, database),
'--format=sarif-latest',
'--output=' + sarifFile,
'--no-sarif-add-snippets',
...queries
]);
core.debug('SARIF results for database ' + database + ' created at "' + sarifFile + '"');
core.endGroup();
}
}
async function run() {
try {
if (util.should_abort('finish', true) || !await util.reportActionStarting('finish')) {
return;
}
const config = await configUtils.loadConfig();
core.exportVariable(sharedEnv.ODASA_TRACER_CONFIGURATION, '');
delete process.env[sharedEnv.ODASA_TRACER_CONFIGURATION];
const codeqlCmd = util.getRequiredEnvParam(sharedEnv.CODEQL_ACTION_CMD);
const databaseFolder = util.getRequiredEnvParam(sharedEnv.CODEQL_ACTION_DATABASE_DIR);
const sarifFolder = core.getInput('output');
await io.mkdirP(sarifFolder);
core.info('Finalizing database creation');
await finalizeDatabaseCreation(codeqlCmd, databaseFolder);
await externalQueries.checkoutExternalQueries(config);
core.info('Analyzing database');
await runQueries(codeqlCmd, databaseFolder, sarifFolder, config);
if ('true' === core.getInput('upload')) {
if (!await upload_lib.upload(sarifFolder)) {
await util.reportActionFailed('failed', 'upload');
return;
}
}
}
catch (error) {
core.setFailed(error.message);
await util.reportActionFailed('finish', error.message, error.stack);
return;
}
await util.reportActionSucceeded('finish');
}
run().catch(e => {
core.setFailed("analyze action failed: " + e);
console.log(e);
});
//# sourceMappingURL=finalize-db.js.map

File diff suppressed because one or more lines are too long

117
lib/fingerprints.js generated
View File

@@ -10,13 +10,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const fs = __importStar(require("fs"));
const long_1 = __importDefault(require("long"));
const tab = '\t'.charCodeAt(0);
const space = ' '.charCodeAt(0);
const lf = '\n'.charCodeAt(0);
const cr = '\r'.charCodeAt(0);
const tab = "\t".charCodeAt(0);
const space = " ".charCodeAt(0);
const lf = "\n".charCodeAt(0);
const cr = "\r".charCodeAt(0);
const EOF = 65535;
const BLOCK_SIZE = 100;
const MOD = long_1.default.fromInt(37); // L
// Compute the starting point for the hash mod
@@ -37,9 +37,9 @@ function computeFirstMod() {
* the hashes of the lines near the end of the file.
*
* @param callback function that is called with the line number (1-based) and hash for every line
* @param input The file's contents
* @param filepath The path to the file to hash
*/
function hash(callback, input) {
async function hash(callback, filepath) {
// A rolling view in to the input
const window = Array(BLOCK_SIZE).fill(0);
// If the character in the window is the start of a new line
@@ -47,8 +47,8 @@ function hash(callback, input) {
// Indexes match up with those from the window variable.
const lineNumbers = Array(BLOCK_SIZE).fill(-1);
// The current hash value, updated as we read each character
let hash = long_1.default.ZERO;
let firstMod = computeFirstMod();
let hashRaw = long_1.default.ZERO;
const firstMod = computeFirstMod();
// The current index in the window, will wrap around to zero when we reach BLOCK_SIZE
let index = 0;
// The line number of the character we are currently processing from the input
@@ -62,19 +62,19 @@ function hash(callback, input) {
const hashCounts = {};
// Output the current hash and line number to the callback function
const outputHash = function () {
let hashValue = hash.toUnsigned().toString(16);
const hashValue = hashRaw.toUnsigned().toString(16);
if (!hashCounts[hashValue]) {
hashCounts[hashValue] = 0;
}
hashCounts[hashValue]++;
callback(lineNumbers[index], hashValue + ":" + hashCounts[hashValue]);
callback(lineNumbers[index], `${hashValue}:${hashCounts[hashValue]}`);
lineNumbers[index] = -1;
};
// Update the current hash value and increment the index in the window
const updateHash = function (current) {
const begin = window[index];
window[index] = current;
hash = MOD.multiply(hash)
hashRaw = MOD.multiply(hashRaw)
.add(long_1.default.fromInt(current))
.subtract(firstMod.multiply(long_1.default.fromInt(begin)));
index = (index + 1) % BLOCK_SIZE;
@@ -83,12 +83,11 @@ function hash(callback, input) {
// as we go. Once we reach a point in the window again then we've processed
// BLOCK_SIZE characters and if the last character at this point in the window
// was the start of a line then we should output the hash for that line.
for (let i = 0, len = input.length; i <= len; i++) {
let current = i === len ? 65535 : input.charCodeAt(i);
const processCharacter = function (current) {
// skip tabs, spaces, and line feeds that come directly after a carriage return
if (current === space || current === tab || (prevCR && current === lf)) {
prevCR = false;
continue;
return;
}
// replace CR with LF
if (current === cr) {
@@ -110,7 +109,14 @@ function hash(callback, input) {
lineStart = true;
}
updateHash(current);
};
const readStream = fs.createReadStream(filepath, "utf8");
for await (const data of readStream) {
for (let i = 0; i < data.length; ++i) {
processCharacter(data.charCodeAt(i));
}
}
processCharacter(EOF);
// Flush the remaining lines
for (let i = 0; i < BLOCK_SIZE; i++) {
if (lineNumbers[index] !== -1) {
@@ -121,8 +127,8 @@ function hash(callback, input) {
}
exports.hash = hash;
// Generate a hash callback function that updates the given result in-place
// when it recieves a hash for the correct line number. Ignores hashes for other lines.
function locationUpdateCallback(result, location) {
// when it receives a hash for the correct line number. Ignores hashes for other lines.
function locationUpdateCallback(result, location, logger) {
var _a, _b;
let locationStartLine = (_b = (_a = location.physicalLocation) === null || _a === void 0 ? void 0 : _a.region) === null || _b === void 0 ? void 0 : _b.startLine;
if (locationStartLine === undefined) {
@@ -131,7 +137,7 @@ function locationUpdateCallback(result, location) {
// using the hash of the first line of the file.
locationStartLine = 1;
}
return function (lineNumber, hash) {
return function (lineNumber, hashValue) {
// Ignore hashes for lines that don't concern us
if (locationStartLine !== lineNumber) {
return;
@@ -143,13 +149,10 @@ function locationUpdateCallback(result, location) {
// If the hash doesn't match the existing fingerprint then
// output a warning and don't overwrite it.
if (!existingFingerprint) {
result.partialFingerprints.primaryLocationLineHash = hash;
result.partialFingerprints.primaryLocationLineHash = hashValue;
}
else if (existingFingerprint !== hash) {
core.warning("Calculated fingerprint of " + hash +
" for file " + location.physicalLocation.artifactLocation.uri +
" line " + lineNumber +
", but found existing inconsistent fingerprint value " + existingFingerprint);
else if (existingFingerprint !== hashValue) {
logger.warning(`Calculated fingerprint of ${hashValue} for file ${location.physicalLocation.artifactLocation.uri} line ${lineNumber}, but found existing inconsistent fingerprint value ${existingFingerprint}`);
}
};
}
@@ -157,48 +160,52 @@ function locationUpdateCallback(result, location) {
// the source file so we can hash it.
// If possible returns a absolute file path for the source file,
// or if not possible then returns undefined.
function resolveUriToFile(location, artifacts) {
function resolveUriToFile(location, artifacts, sourceRoot, logger) {
// This may be referencing an artifact
if (!location.uri && location.index !== undefined) {
if (typeof location.index !== 'number' ||
if (typeof location.index !== "number" ||
location.index < 0 ||
location.index >= artifacts.length ||
typeof artifacts[location.index].location !== 'object') {
core.debug('Ignoring location as index "' + location.index + '" is invalid');
typeof artifacts[location.index].location !== "object") {
logger.debug(`Ignoring location as index "${location.index}" is invalid`);
return undefined;
}
location = artifacts[location.index].location;
}
// Get the URI and decode
if (typeof location.uri !== 'string') {
core.debug('Ignoring location as uri "' + location.uri + '" is invalid');
if (typeof location.uri !== "string") {
logger.debug(`Ignoring location as URI "${location.uri}" is invalid`);
return undefined;
}
let uri = decodeURIComponent(location.uri);
// Remove a file scheme, and abort if the scheme is anything else
const fileUriPrefix = 'file://';
const fileUriPrefix = "file://";
if (uri.startsWith(fileUriPrefix)) {
uri = uri.substring(fileUriPrefix.length);
}
if (uri.indexOf('://') !== -1) {
core.debug('Ignoring location URI "' + uri + "' as the scheme is not recognised");
if (uri.indexOf("://") !== -1) {
logger.debug(`Ignoring location URI "${uri}" as the scheme is not recognised`);
return undefined;
}
// Discard any absolute paths that aren't in the src root
const srcRootPrefix = process.env['GITHUB_WORKSPACE'] + '/';
if (uri.startsWith('/') && !uri.startsWith(srcRootPrefix)) {
core.debug('Ignoring location URI "' + uri + "' as it is outside of the src root");
const srcRootPrefix = `${sourceRoot}/`;
if (uri.startsWith("/") && !uri.startsWith(srcRootPrefix)) {
logger.debug(`Ignoring location URI "${uri}" as it is outside of the src root`);
return undefined;
}
// Just assume a relative path is relative to the src root.
// This is not necessarily true but should be a good approximation
// and here we likely want to err on the side of handling more cases.
if (!uri.startsWith('/')) {
if (!uri.startsWith("/")) {
uri = srcRootPrefix + uri;
}
// Check the file exists
if (!fs.existsSync(uri)) {
core.debug("Unable to compute fingerprint for non-existent file: " + uri);
logger.debug(`Unable to compute fingerprint for non-existent file: ${uri}`);
return undefined;
}
if (fs.statSync(uri).isDirectory()) {
logger.debug(`Unable to compute fingerprint for directory: ${uri}`);
return undefined;
}
return uri;
@@ -206,42 +213,46 @@ function resolveUriToFile(location, artifacts) {
exports.resolveUriToFile = resolveUriToFile;
// Compute fingerprints for results in the given sarif file
// and return an updated sarif file contents.
function addFingerprints(sarifContents) {
let sarif = JSON.parse(sarifContents);
async function addFingerprints(sarifContents, sourceRoot, logger) {
var _a, _b, _c, _d, _e;
const sarif = JSON.parse(sarifContents);
// Gather together results for the same file and construct
// callbacks to accept hashes for that file and update the location
const callbacksByFile = {};
for (const run of sarif.runs || []) {
// We may need the list of artifacts to resolve against
let artifacts = run.artifacts || [];
const artifacts = run.artifacts || [];
for (const result of run.results || []) {
// Check the primary location is defined correctly and is in the src root
const primaryLocation = (result.locations || [])[0];
if (!primaryLocation ||
!primaryLocation.physicalLocation ||
!primaryLocation.physicalLocation.artifactLocation) {
core.debug("Unable to compute fingerprint for invalid location: " + JSON.stringify(primaryLocation));
if (!((_b = (_a = primaryLocation) === null || _a === void 0 ? void 0 : _a.physicalLocation) === null || _b === void 0 ? void 0 : _b.artifactLocation)) {
logger.debug(`Unable to compute fingerprint for invalid location: ${JSON.stringify(primaryLocation)}`);
continue;
}
const filepath = resolveUriToFile(primaryLocation.physicalLocation.artifactLocation, artifacts);
if (((_e = (_d = (_c = primaryLocation) === null || _c === void 0 ? void 0 : _c.physicalLocation) === null || _d === void 0 ? void 0 : _d.region) === null || _e === void 0 ? void 0 : _e.startLine) === undefined) {
// Locations without a line number are unlikely to be source files
continue;
}
const filepath = resolveUriToFile(primaryLocation.physicalLocation.artifactLocation, artifacts, sourceRoot, logger);
if (!filepath) {
continue;
}
if (!callbacksByFile[filepath]) {
callbacksByFile[filepath] = [];
}
callbacksByFile[filepath].push(locationUpdateCallback(result, primaryLocation));
callbacksByFile[filepath].push(locationUpdateCallback(result, primaryLocation, logger));
}
}
// Now hash each file that was found
Object.entries(callbacksByFile).forEach(([filepath, callbacks]) => {
for (const [filepath, callbacks] of Object.entries(callbacksByFile)) {
// A callback that forwards the hash to all other callbacks for that file
const teeCallback = function (lineNumber, hash) {
Object.values(callbacks).forEach(c => c(lineNumber, hash));
const teeCallback = function (lineNumber, hashValue) {
for (const c of Object.values(callbacks)) {
c(lineNumber, hashValue);
}
};
const fileContents = fs.readFileSync(filepath).toString();
hash(teeCallback, fileContents);
});
await hash(teeCallback, filepath);
}
return JSON.stringify(sarif);
}
exports.addFingerprints = addFingerprints;

File diff suppressed because one or more lines are too long

135
lib/fingerprints.test.js generated
View File

@@ -1,7 +1,4 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
@@ -9,32 +6,43 @@ var __importStar = (this && this.__importStar) || function (mod) {
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = __importDefault(require("ava"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ava_1 = __importDefault(require("ava"));
const fingerprints = __importStar(require("./fingerprints"));
function testHash(t, input, expectedHashes) {
let index = 0;
let callback = function (lineNumber, hash) {
t.is(lineNumber, index + 1);
t.is(hash, expectedHashes[index]);
index++;
};
fingerprints.hash(callback, input);
t.is(index, input.split(/\r\n|\r|\n/).length);
const logging_1 = require("./logging");
const testing_utils_1 = require("./testing-utils");
const util = __importStar(require("./util"));
testing_utils_1.setupTests(ava_1.default);
async function testHash(t, input, expectedHashes) {
await util.withTmpDir(async (tmpDir) => {
const tmpFile = path.resolve(tmpDir, "testfile");
fs.writeFileSync(tmpFile, input);
let index = 0;
const callback = function (lineNumber, hash) {
t.is(lineNumber, index + 1);
t.is(hash, expectedHashes[index]);
index++;
};
await fingerprints.hash(callback, tmpFile);
t.is(index, input.split(/\r\n|\r|\n/).length);
});
}
ava_1.default('hash', (t) => {
ava_1.default("hash", async (t) => {
// Try empty file
testHash(t, "", ["c129715d7a2bc9a3:1"]);
await testHash(t, "", ["c129715d7a2bc9a3:1"]);
// Try various combinations of newline characters
testHash(t, " a\nb\n \t\tc\n d", [
await testHash(t, " a\nb\n \t\tc\n d", [
"271789c17abda88f:1",
"54703d4cd895b18:1",
"180aee12dab6264:1",
"a23a3dc5e078b07b:1"
"a23a3dc5e078b07b:1",
]);
testHash(t, " hello; \t\nworld!!!\n\n\n \t\tGreetings\n End", [
await testHash(t, " hello; \t\nworld!!!\n\n\n \t\tGreetings\n End", [
"8b7cf3e952e7aeb2:1",
"b1ae1287ec4718d9:1",
"bff680108adb0fcc:1",
@@ -42,7 +50,7 @@ ava_1.default('hash', (t) => {
"b86d3392aea1be30:1",
"e6ceba753e1a442:1",
]);
testHash(t, " hello; \t\nworld!!!\n\n\n \t\tGreetings\n End\n", [
await testHash(t, " hello; \t\nworld!!!\n\n\n \t\tGreetings\n End\n", [
"e9496ae3ebfced30:1",
"fb7c023a8b9ccb3f:1",
"ce8ba1a563dcdaca:1",
@@ -51,7 +59,7 @@ ava_1.default('hash', (t) => {
"c8e28b0b4002a3a0:1",
"c129715d7a2bc9a3:1",
]);
testHash(t, " hello; \t\nworld!!!\r\r\r \t\tGreetings\r End\r", [
await testHash(t, " hello; \t\nworld!!!\r\r\r \t\tGreetings\r End\r", [
"e9496ae3ebfced30:1",
"fb7c023a8b9ccb3f:1",
"ce8ba1a563dcdaca:1",
@@ -60,7 +68,7 @@ ava_1.default('hash', (t) => {
"c8e28b0b4002a3a0:1",
"c129715d7a2bc9a3:1",
]);
testHash(t, " hello; \t\r\nworld!!!\r\n\r\n\r\n \t\tGreetings\r\n End\r\n", [
await testHash(t, " hello; \t\r\nworld!!!\r\n\r\n\r\n \t\tGreetings\r\n End\r\n", [
"e9496ae3ebfced30:1",
"fb7c023a8b9ccb3f:1",
"ce8ba1a563dcdaca:1",
@@ -69,7 +77,7 @@ ava_1.default('hash', (t) => {
"c8e28b0b4002a3a0:1",
"c129715d7a2bc9a3:1",
]);
testHash(t, " hello; \t\nworld!!!\r\n\n\r \t\tGreetings\r End\r\n", [
await testHash(t, " hello; \t\nworld!!!\r\n\n\r \t\tGreetings\r End\r\n", [
"e9496ae3ebfced30:1",
"fb7c023a8b9ccb3f:1",
"ce8ba1a563dcdaca:1",
@@ -79,7 +87,7 @@ ava_1.default('hash', (t) => {
"c129715d7a2bc9a3:1",
]);
// Try repeating line that will generate identical hashes
testHash(t, "Lorem ipsum dolor sit amet.\n".repeat(10), [
await testHash(t, "Lorem ipsum dolor sit amet.\n".repeat(10), [
"a7f2ff13bc495cf2:1",
"a7f2ff13bc495cf2:2",
"a7f2ff13bc495cf2:3",
@@ -90,68 +98,91 @@ ava_1.default('hash', (t) => {
"a9cf91f7bbf1862b:1",
"55ec222b86bcae53:1",
"cc97dc7b1d7d8f7b:1",
"c129715d7a2bc9a3:1"
"c129715d7a2bc9a3:1",
]);
await testHash(t, "x = 2\nx = 1\nprint(x)\nx = 3\nprint(x)\nx = 4\nprint(x)\n", [
"e54938cc54b302f1:1",
"bb609acbe9138d60:1",
"1131fd5871777f34:1",
"5c482a0f8b35ea28:1",
"54517377da7028d2:1",
"2c644846cb18d53e:1",
"f1b89f20de0d133:1",
"c129715d7a2bc9a3:1",
]);
});
function testResolveUriToFile(uri, index, artifactsURIs) {
const location = { "uri": uri, "index": index };
const artifacts = artifactsURIs.map(uri => ({ "location": { "uri": uri } }));
return fingerprints.resolveUriToFile(location, artifacts);
const location = { uri, index };
const artifacts = artifactsURIs.map((artifactURI) => ({
location: { uri: artifactURI },
}));
return fingerprints.resolveUriToFile(location, artifacts, process.cwd(), logging_1.getRunnerLogger(true));
}
ava_1.default('resolveUriToFile', t => {
ava_1.default("resolveUriToFile", (t) => {
// The resolveUriToFile method checks that the file exists and is in the right directory
// so we need to give it real files to look at. We will use this file as an example.
// For this to work we require the current working directory to be a parent, but this
// should generally always be the case so this is fine.
const cwd = process.cwd();
const filepath = __filename;
t.true(filepath.startsWith(cwd + '/'));
const relativeFilepaht = filepath.substring(cwd.length + 1);
process.env['GITHUB_WORKSPACE'] = cwd;
t.true(filepath.startsWith(`${cwd}/`));
const relativeFilepath = filepath.substring(cwd.length + 1);
// Absolute paths are unmodified
t.is(testResolveUriToFile(filepath, undefined, []), filepath);
t.is(testResolveUriToFile('file://' + filepath, undefined, []), filepath);
t.is(testResolveUriToFile(`file://${filepath}`, undefined, []), filepath);
// Relative paths are made absolute
t.is(testResolveUriToFile(relativeFilepaht, undefined, []), filepath);
t.is(testResolveUriToFile('file://' + relativeFilepaht, undefined, []), filepath);
t.is(testResolveUriToFile(relativeFilepath, undefined, []), filepath);
t.is(testResolveUriToFile(`file://${relativeFilepath}`, undefined, []), filepath);
// Absolute paths outside the src root are discarded
t.is(testResolveUriToFile('/src/foo/bar.js', undefined, []), undefined);
t.is(testResolveUriToFile('file:///src/foo/bar.js', undefined, []), undefined);
t.is(testResolveUriToFile("/src/foo/bar.js", undefined, []), undefined);
t.is(testResolveUriToFile("file:///src/foo/bar.js", undefined, []), undefined);
// Other schemes are discarded
t.is(testResolveUriToFile('https://' + filepath, undefined, []), undefined);
t.is(testResolveUriToFile('ftp://' + filepath, undefined, []), undefined);
t.is(testResolveUriToFile(`https://${filepath}`, undefined, []), undefined);
t.is(testResolveUriToFile(`ftp://${filepath}`, undefined, []), undefined);
// Invalid URIs are discarded
t.is(testResolveUriToFile(1, undefined, []), undefined);
t.is(testResolveUriToFile(undefined, undefined, []), undefined);
// Non-existant files are discarded
t.is(testResolveUriToFile(filepath + '2', undefined, []), undefined);
// Non-existent files are discarded
t.is(testResolveUriToFile(`${filepath}2`, undefined, []), undefined);
// Index is resolved
t.is(testResolveUriToFile(undefined, 0, [filepath]), filepath);
t.is(testResolveUriToFile(undefined, 1, ['foo', filepath]), filepath);
t.is(testResolveUriToFile(undefined, 1, ["foo", filepath]), filepath);
// Invalid indexes are discarded
t.is(testResolveUriToFile(undefined, 1, [filepath]), undefined);
t.is(testResolveUriToFile(undefined, '0', [filepath]), undefined);
t.is(testResolveUriToFile(undefined, "0", [filepath]), undefined);
// Directories are discarded
const dirpath = __dirname;
t.is(testResolveUriToFile(dirpath, undefined, []), undefined);
t.is(testResolveUriToFile(`file://${dirpath}`, undefined, []), undefined);
});
ava_1.default('addFingerprints', t => {
ava_1.default("addFingerprints", async (t) => {
// Run an end-to-end test on a test file
let input = fs.readFileSync(__dirname + '/../src/testdata/fingerprinting.input.sarif').toString();
let expected = fs.readFileSync(__dirname + '/../src/testdata/fingerprinting.expected.sarif').toString();
let input = fs
.readFileSync(`${__dirname}/../src/testdata/fingerprinting.input.sarif`)
.toString();
let expected = fs
.readFileSync(`${__dirname}/../src/testdata/fingerprinting.expected.sarif`)
.toString();
// The test files are stored prettified, but addFingerprints outputs condensed JSON
input = JSON.stringify(JSON.parse(input));
expected = JSON.stringify(JSON.parse(expected));
// The URIs in the SARIF files resolve to files in the testdata directory
process.env['GITHUB_WORKSPACE'] = path.normalize(__dirname + '/../src/testdata');
t.deepEqual(fingerprints.addFingerprints(input), expected);
const sourceRoot = path.normalize(`${__dirname}/../src/testdata`);
t.deepEqual(await fingerprints.addFingerprints(input, sourceRoot, logging_1.getRunnerLogger(true)), expected);
});
ava_1.default('missingRegions', t => {
ava_1.default("missingRegions", async (t) => {
// Run an end-to-end test on a test file
let input = fs.readFileSync(__dirname + '/../src/testdata/fingerprinting2.input.sarif').toString();
let expected = fs.readFileSync(__dirname + '/../src/testdata/fingerprinting2.expected.sarif').toString();
let input = fs
.readFileSync(`${__dirname}/../src/testdata/fingerprinting2.input.sarif`)
.toString();
let expected = fs
.readFileSync(`${__dirname}/../src/testdata/fingerprinting2.expected.sarif`)
.toString();
// The test files are stored prettified, but addFingerprints outputs condensed JSON
input = JSON.stringify(JSON.parse(input));
expected = JSON.stringify(JSON.parse(expected));
// The URIs in the SARIF files resolve to files in the testdata directory
process.env['GITHUB_WORKSPACE'] = path.normalize(__dirname + '/../src/testdata');
t.deepEqual(fingerprints.addFingerprints(input), expected);
const sourceRoot = path.normalize(`${__dirname}/../src/testdata`);
t.deepEqual(await fingerprints.addFingerprints(input, sourceRoot, logging_1.getRunnerLogger(true)), expected);
});
//# sourceMappingURL=fingerprints.test.js.map

File diff suppressed because one or more lines are too long

133
lib/init-action.js generated Normal file
View File

@@ -0,0 +1,133 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(require("path"));
const core = __importStar(require("@actions/core"));
const actions_util_1 = require("./actions-util");
const init_1 = require("./init");
const languages_1 = require("./languages");
const logging_1 = require("./logging");
const repository_1 = require("./repository");
const util_1 = require("./util");
// eslint-disable-next-line import/no-commonjs
const pkg = require("../package.json");
async function sendSuccessStatusReport(startedAt, config, toolsVersion) {
var _a;
const statusReportBase = await actions_util_1.createStatusReportBase("init", "success", startedAt);
const languages = config.languages.join(",");
const workflowLanguages = actions_util_1.getOptionalInput("languages");
const paths = (config.originalUserInput.paths || []).join(",");
const pathsIgnore = (config.originalUserInput["paths-ignore"] || []).join(",");
const disableDefaultQueries = config.originalUserInput["disable-default-queries"]
? languages
: "";
const queries = [];
let queriesInput = (_a = actions_util_1.getOptionalInput("queries")) === null || _a === void 0 ? void 0 : _a.trim();
if (queriesInput === undefined || queriesInput.startsWith("+")) {
queries.push(...(config.originalUserInput.queries || []).map((q) => q.uses));
}
if (queriesInput !== undefined) {
queriesInput = queriesInput.startsWith("+")
? queriesInput.substr(1)
: queriesInput;
queries.push(...queriesInput.split(","));
}
const statusReport = {
...statusReportBase,
languages,
workflow_languages: workflowLanguages || "",
paths,
paths_ignore: pathsIgnore,
disable_default_queries: disableDefaultQueries,
queries: queries.join(","),
tools_input: actions_util_1.getOptionalInput("tools") || "",
tools_resolved_version: toolsVersion,
};
await actions_util_1.sendStatusReport(statusReport);
}
async function run() {
const startedAt = new Date();
const logger = logging_1.getActionsLogger();
util_1.initializeEnvironment(util_1.Mode.actions, pkg.version);
let config;
let codeql;
let toolsVersion;
const apiDetails = {
auth: actions_util_1.getRequiredInput("token"),
externalRepoAuth: actions_util_1.getOptionalInput("external-repository-token"),
url: util_1.getRequiredEnvParam("GITHUB_SERVER_URL"),
};
const gitHubVersion = await util_1.getGitHubVersion(apiDetails);
util_1.checkGitHubVersionInRange(gitHubVersion, logger, util_1.Mode.actions);
try {
const workflowErrors = await actions_util_1.validateWorkflow();
if (!(await actions_util_1.sendStatusReport(await actions_util_1.createStatusReportBase("init", "starting", startedAt, workflowErrors)))) {
return;
}
const initCodeQLResult = await init_1.initCodeQL(actions_util_1.getOptionalInput("tools"), apiDetails, actions_util_1.getTemporaryDirectory(), actions_util_1.getToolCacheDirectory(), gitHubVersion.type, logger);
codeql = initCodeQLResult.codeql;
toolsVersion = initCodeQLResult.toolsVersion;
config = await init_1.initConfig(actions_util_1.getOptionalInput("languages"), actions_util_1.getOptionalInput("queries"), actions_util_1.getOptionalInput("packs"), actions_util_1.getOptionalInput("config-file"), actions_util_1.getOptionalInput("db-location"), repository_1.parseRepositoryNwo(util_1.getRequiredEnvParam("GITHUB_REPOSITORY")), actions_util_1.getTemporaryDirectory(), util_1.getRequiredEnvParam("RUNNER_TOOL_CACHE"), codeql, util_1.getRequiredEnvParam("GITHUB_WORKSPACE"), gitHubVersion, apiDetails, logger);
if (config.languages.includes(languages_1.Language.python) &&
actions_util_1.getRequiredInput("setup-python-dependencies") === "true") {
try {
await init_1.installPythonDeps(codeql, logger);
}
catch (err) {
logger.warning(`${err.message} You can call this action with 'setup-python-dependencies: false' to disable this process`);
}
}
}
catch (e) {
core.setFailed(e.message);
console.log(e);
await actions_util_1.sendStatusReport(await actions_util_1.createStatusReportBase("init", "aborted", startedAt, e.message));
return;
}
try {
// Forward Go flags
const goFlags = process.env["GOFLAGS"];
if (goFlags) {
core.exportVariable("GOFLAGS", goFlags);
core.warning("Passing the GOFLAGS env parameter to the init action is deprecated. Please move this to the analyze action.");
}
// Setup CODEQL_RAM flag (todo improve this https://github.com/github/dsp-code-scanning/issues/935)
const codeqlRam = process.env["CODEQL_RAM"] || "6500";
core.exportVariable("CODEQL_RAM", codeqlRam);
const sourceRoot = path.resolve(util_1.getRequiredEnvParam("GITHUB_WORKSPACE"), actions_util_1.getOptionalInput("source-root") || "");
const tracerConfig = await init_1.runInit(codeql, config, sourceRoot);
if (tracerConfig !== undefined) {
for (const [key, value] of Object.entries(tracerConfig.env)) {
core.exportVariable(key, value);
}
if (process.platform === "win32") {
await init_1.injectWindowsTracer("Runner.Worker.exe", undefined, config, codeql, tracerConfig);
}
}
core.setOutput("codeql-path", config.codeQLCmd);
}
catch (error) {
core.setFailed(error.message);
console.log(error);
await actions_util_1.sendStatusReport(await actions_util_1.createStatusReportBase("init", "failure", startedAt, error.message, error.stack));
return;
}
await sendSuccessStatusReport(startedAt, config, toolsVersion);
}
async function runWrapper() {
try {
await run();
}
catch (error) {
core.setFailed(`init action failed: ${error}`);
console.log(error);
}
}
void runWrapper();
//# sourceMappingURL=init-action.js.map

1
lib/init-action.js.map Normal file
View File

@@ -0,0 +1 @@
{"version":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AAI,CAAC,SAAS,CAAC,aAAa,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;KACjD;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC9B,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACnB,MAAM,+BAAgB,CACpB,MAAM,qCAAsB,CAC1B,MAAM,EACN,SAAS,EACT,SAAS,EACT,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,KAAK,CACZ,CACF,CAAC;QACF,OAAO;KACR;IACD,MAAM,uBAAuB,CAAC,SAAS,EAAE,MAAM,EAAE,YAAY,CAAC,CAAC;AACjE,CAAC;AAED,KAAK,UAAU,UAAU;IACvB,IAAI;QACF,MAAM,GAAG,EAAE,CAAC;KACb;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,CAAC,SAAS,CAAC,uBAAuB,KAAK,EAAE,CAAC,CAAC;QAC/C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;KACpB;AACH,CAAC;AAED,KAAK,UAAU,EAAE,CAAC"}

165
lib/init.js generated Normal file
View File

@@ -0,0 +1,165 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const toolrunner = __importStar(require("@actions/exec/lib/toolrunner"));
const safeWhich = __importStar(require("@chrisgavin/safe-which"));
const analysisPaths = __importStar(require("./analysis-paths"));
const codeql_1 = require("./codeql");
const configUtils = __importStar(require("./config-utils"));
const tracer_config_1 = require("./tracer-config");
const util = __importStar(require("./util"));
async function initCodeQL(codeqlURL, apiDetails, tempDir, toolCacheDir, variant, logger) {
logger.startGroup("Setup CodeQL tools");
const { codeql, toolsVersion } = await codeql_1.setupCodeQL(codeqlURL, apiDetails, tempDir, toolCacheDir, variant, logger);
await codeql.printVersion();
logger.endGroup();
return { codeql, toolsVersion };
}
exports.initCodeQL = initCodeQL;
async function initConfig(languagesInput, queriesInput, packsInput, configFile, dbLocation, repository, tempDir, toolCacheDir, codeQL, workspacePath, gitHubVersion, apiDetails, logger) {
logger.startGroup("Load language configuration");
const config = await configUtils.initConfig(languagesInput, queriesInput, packsInput, configFile, dbLocation, repository, tempDir, toolCacheDir, codeQL, workspacePath, gitHubVersion, apiDetails, logger);
analysisPaths.printPathFiltersWarning(config, logger);
logger.endGroup();
return config;
}
exports.initConfig = initConfig;
async function runInit(codeql, config, sourceRoot) {
fs.mkdirSync(config.dbLocation, { recursive: true });
// TODO: replace this code once CodeQL supports multi-language tracing
for (const language of config.languages) {
// Init language database
await codeql.databaseInit(util.getCodeQLDatabasePath(config, language), language, sourceRoot);
}
return await tracer_config_1.getCombinedTracerConfig(config, codeql);
}
exports.runInit = runInit;
// Runs a powershell script to inject the tracer into a parent process
// so it can tracer future processes, hopefully including the build process.
// If processName is given then injects into the nearest parent process with
// this name, otherwise uses the processLevel-th parent if defined, otherwise
// defaults to the 3rd parent as a rough guess.
async function injectWindowsTracer(processName, processLevel, config, codeql, tracerConfig) {
let script;
if (processName !== undefined) {
script = `
Param(
[Parameter(Position=0)]
[String]
$tracer
)
$id = $PID
while ($true) {
$p = Get-CimInstance -Class Win32_Process -Filter "ProcessId = $id"
Write-Host "Found process: $p"
if ($p -eq $null) {
throw "Could not determine ${processName} process"
}
if ($p[0].Name -eq "${processName}") {
Break
} else {
$id = $p[0].ParentProcessId
}
}
Write-Host "Final process: $p"
Invoke-Expression "&$tracer --inject=$id"`;
}
else {
// If the level is not defined then guess at the 3rd parent process.
// This won't be correct in every setting but it should be enough in most settings,
// and overestimating is likely better in this situation so we definitely trace
// what we want, though this does run the risk of interfering with future CI jobs.
// Note that the default of 3 doesn't work on github actions, so we include a
// special case in the script that checks for Runner.Worker.exe so we can still work
// on actions if the runner is invoked there.
processLevel = processLevel || 3;
script = `
Param(
[Parameter(Position=0)]
[String]
$tracer
)
$id = $PID
for ($i = 0; $i -le ${processLevel}; $i++) {
$p = Get-CimInstance -Class Win32_Process -Filter "ProcessId = $id"
Write-Host "Parent process \${i}: $p"
if ($p -eq $null) {
throw "Process tree ended before reaching required level"
}
# Special case just in case the runner is used on actions
if ($p[0].Name -eq "Runner.Worker.exe") {
Write-Host "Found Runner.Worker.exe process which means we are running on GitHub Actions"
Write-Host "Aborting search early and using process: $p"
Break
} elseif ($p[0].Name -eq "Agent.Worker.exe") {
Write-Host "Found Agent.Worker.exe process which means we are running on Azure Pipelines"
Write-Host "Aborting search early and using process: $p"
Break
} else {
$id = $p[0].ParentProcessId
}
}
Write-Host "Final process: $p"
Invoke-Expression "&$tracer --inject=$id"`;
}
const injectTracerPath = path.join(config.tempDir, "inject-tracer.ps1");
fs.writeFileSync(injectTracerPath, script);
await new toolrunner.ToolRunner(await safeWhich.safeWhich("powershell"), [
"-ExecutionPolicy",
"Bypass",
"-file",
injectTracerPath,
path.resolve(path.dirname(codeql.getPath()), "tools", "win64", "tracer.exe"),
], { env: { ODASA_TRACER_CONFIGURATION: tracerConfig.spec } }).exec();
}
exports.injectWindowsTracer = injectWindowsTracer;
async function installPythonDeps(codeql, logger) {
logger.startGroup("Setup Python dependencies");
const scriptsFolder = path.resolve(__dirname, "../python-setup");
try {
if (process.platform === "win32") {
await new toolrunner.ToolRunner(await safeWhich.safeWhich("powershell"), [
path.join(scriptsFolder, "install_tools.ps1"),
]).exec();
}
else {
await new toolrunner.ToolRunner(path.join(scriptsFolder, "install_tools.sh")).exec();
}
const script = "auto_install_packages.py";
if (process.platform === "win32") {
await new toolrunner.ToolRunner(await safeWhich.safeWhich("py"), [
"-3",
path.join(scriptsFolder, script),
path.dirname(codeql.getPath()),
]).exec();
}
else {
await new toolrunner.ToolRunner(path.join(scriptsFolder, script), [
path.dirname(codeql.getPath()),
]).exec();
}
}
catch (e) {
logger.endGroup();
logger.warning(`An error occurred while trying to automatically install Python dependencies: ${e}\n` +
"Please make sure any necessary dependencies are installed before calling the codeql-action/analyze " +
"step, and add a 'setup-python-dependencies: false' argument to this step to disable our automatic " +
"dependency installation and avoid this warning.");
return;
}
logger.endGroup();
}
exports.installPythonDeps = installPythonDeps;
//# sourceMappingURL=init.js.map

1
lib/init.js.map Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAyB;AACzB,2CAA6B;AAE7B,yEAA2D;AAC3D,kEAAoD;AAEpD,gEAAkD;AAElD,qCAA+C;AAC/C,4DAA8C;AAG9C,mDAAwE;AACxE,6CAA+B;AAExB,KAAK,UAAU,UAAU,CAC9B,SAA6B,EAC7B,UAA4B,EAC5B,OAAe,EACf,YAAoB,EACpB,OAA2B,EAC3B,MAAc;IAEd,MAAM,CAAC,UAAU,CAAC,oBAAoB,CAAC,CAAC;IACxC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,oBAAW,CAChD,SAAS,EACT,UAAU,EACV,OAAO,EACP,YAAY,EACZ,OAAO,EACP,MAAM,CACP,CAAC;IACF,MAAM,MAAM,CAAC,YAAY,EAAE,CAAC;IAC5B,MAAM,CAAC,QAAQ,EAAE,CAAC;IAClB,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC;AAClC,CAAC;AApBD,gCAoBC;AAEM,KAAK,UAAU,UAAU,CAC9B,cAAkC,EAClC,YAAgC,EAChC,UAA8B,EAC9B,UAA8B,EAC9B,UAA8B,EAC9B,UAAyB,EACzB,OAAe,EACf,YAAoB,EACpB,MAAc,EACd,aAAqB,EACrB,aAAiC,EACjC,UAAoC,EACpC,MAAc;IAEd,MAAM,CAAC,UAAU,CAAC,6BAA6B,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,UAAU,CACzC,cAAc,EACd,YAAY,EACZ,UAAU,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AAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;YAChC,MAAM,IAAI,UAAU,CAAC,UAAU,CAAC,MAAM,SAAS,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;gBAC/D,IAAI;gBACJ,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,MAAM,CAAC;gBAChC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;aAC/B,CAAC,CAAC,IAAI,EAAE,CAAC;SACX;aAAM;YACL,MAAM,IAAI,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,MAAM,CAAC,EAAE;gBAChE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;aAC/B,CAAC,CAAC,IAAI,EAAE,CAAC;SACX;KACF;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,CAAC,QAAQ,EAAE,CAAC;QAClB,MAAM,CAAC,OAAO,CACZ,gFAAgF,CAAC,IAAI;YACnF,qGAAqG;YACrG,oGAAoG;YACpG,iDAAiD,CACpD,CAAC;QACF,OAAO;KACR;IACD,MAAM,CAAC,QAAQ,EAAE,CAAC;AACpB,CAAC;AAtCD,8CAsCC"}

46
lib/languages.js generated Normal file
View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// All the languages supported by CodeQL
var Language;
(function (Language) {
Language["csharp"] = "csharp";
Language["cpp"] = "cpp";
Language["go"] = "go";
Language["java"] = "java";
Language["javascript"] = "javascript";
Language["python"] = "python";
Language["ruby"] = "ruby";
})(Language = exports.Language || (exports.Language = {}));
// Additional names for languages
const LANGUAGE_ALIASES = {
c: Language.cpp,
"c++": Language.cpp,
"c#": Language.csharp,
typescript: Language.javascript,
};
// Translate from user input or GitHub's API names for languages to CodeQL's names for languages
function parseLanguage(language) {
// Normalise to lower case
language = language.toLowerCase();
// See if it's an exact match
if (language in Language) {
return language;
}
// Check language aliases
if (language in LANGUAGE_ALIASES) {
return LANGUAGE_ALIASES[language];
}
return undefined;
}
exports.parseLanguage = parseLanguage;
function isTracedLanguage(language) {
return (["cpp", "java", "csharp"].includes(language) ||
(process.env["CODEQL_EXTRACTOR_GO_BUILD_TRACING"] === "on" &&
language === Language.go));
}
exports.isTracedLanguage = isTracedLanguage;
function isScannedLanguage(language) {
return !isTracedLanguage(language);
}
exports.isScannedLanguage = isScannedLanguage;
//# sourceMappingURL=languages.js.map

1
lib/languages.js.map Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"languages.js","sourceRoot":"","sources":["../src/languages.ts"],"names":[],"mappings":";;AAAA,wCAAwC;AACxC,IAAY,QAQX;AARD,WAAY,QAAQ;IAClB,6BAAiB,CAAA;IACjB,uBAAW,CAAA;IACX,qBAAS,CAAA;IACT,yBAAa,CAAA;IACb,qCAAyB,CAAA;IACzB,6BAAiB,CAAA;IACjB,yBAAa,CAAA;AACf,CAAC,EARW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAQnB;AAED,iCAAiC;AACjC,MAAM,gBAAgB,GAAiC;IACrD,CAAC,EAAE,QAAQ,CAAC,GAAG;IACf,KAAK,EAAE,QAAQ,CAAC,GAAG;IACnB,IAAI,EAAE,QAAQ,CAAC,MAAM;IACrB,UAAU,EAAE,QAAQ,CAAC,UAAU;CAChC,CAAC;AAEF,gGAAgG;AAChG,SAAgB,aAAa,CAAC,QAAgB;IAC5C,0BAA0B;IAC1B,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;IAElC,6BAA6B;IAC7B,IAAI,QAAQ,IAAI,QAAQ,EAAE;QACxB,OAAO,QAAoB,CAAC;KAC7B;IAED,yBAAyB;IACzB,IAAI,QAAQ,IAAI,gBAAgB,EAAE;QAChC,OAAO,gBAAgB,CAAC,QAAQ,CAAC,CAAC;KACnC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAfD,sCAeC;AAED,SAAgB,gBAAgB,CAAC,QAAkB;IACjD,OAAO,CACL,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAC5C,CAAC,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,KAAK,IAAI;YACxD,QAAQ,KAAK,QAAQ,CAAC,EAAE,CAAC,CAC5B,CAAC;AACJ,CAAC;AAND,4CAMC;AAED,SAAgB,iBAAiB,CAAC,QAAkB;IAClD,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;AACrC,CAAC;AAFD,8CAEC"}

44
lib/languages.test.js generated Normal file
View File

@@ -0,0 +1,44 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = __importDefault(require("ava"));
const languages_1 = require("./languages");
const testing_utils_1 = require("./testing-utils");
testing_utils_1.setupTests(ava_1.default);
ava_1.default("parseLanguage", async (t) => {
// Exact matches
t.deepEqual(languages_1.parseLanguage("csharp"), languages_1.Language.csharp);
t.deepEqual(languages_1.parseLanguage("cpp"), languages_1.Language.cpp);
t.deepEqual(languages_1.parseLanguage("go"), languages_1.Language.go);
t.deepEqual(languages_1.parseLanguage("java"), languages_1.Language.java);
t.deepEqual(languages_1.parseLanguage("javascript"), languages_1.Language.javascript);
t.deepEqual(languages_1.parseLanguage("python"), languages_1.Language.python);
// Aliases
t.deepEqual(languages_1.parseLanguage("c"), languages_1.Language.cpp);
t.deepEqual(languages_1.parseLanguage("c++"), languages_1.Language.cpp);
t.deepEqual(languages_1.parseLanguage("c#"), languages_1.Language.csharp);
t.deepEqual(languages_1.parseLanguage("typescript"), languages_1.Language.javascript);
// Not matches
t.deepEqual(languages_1.parseLanguage("foo"), undefined);
t.deepEqual(languages_1.parseLanguage(" "), undefined);
t.deepEqual(languages_1.parseLanguage(""), undefined);
});
ava_1.default("isTracedLanguage", async (t) => {
t.true(languages_1.isTracedLanguage(languages_1.Language.cpp));
t.true(languages_1.isTracedLanguage(languages_1.Language.java));
t.true(languages_1.isTracedLanguage(languages_1.Language.csharp));
t.false(languages_1.isTracedLanguage(languages_1.Language.go));
t.false(languages_1.isTracedLanguage(languages_1.Language.javascript));
t.false(languages_1.isTracedLanguage(languages_1.Language.python));
});
ava_1.default("isScannedLanguage", async (t) => {
t.false(languages_1.isScannedLanguage(languages_1.Language.cpp));
t.false(languages_1.isScannedLanguage(languages_1.Language.java));
t.false(languages_1.isScannedLanguage(languages_1.Language.csharp));
t.true(languages_1.isScannedLanguage(languages_1.Language.go));
t.true(languages_1.isScannedLanguage(languages_1.Language.javascript));
t.true(languages_1.isScannedLanguage(languages_1.Language.python));
});
//# sourceMappingURL=languages.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"languages.test.js","sourceRoot":"","sources":["../src/languages.test.ts"],"names":[],"mappings":";;;;;AAAA,8CAAuB;AAEvB,2CAKqB;AACrB,mDAA6C;AAE7C,0BAAU,CAAC,aAAI,CAAC,CAAC;AAEjB,aAAI,CAAC,eAAe,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE;IAChC,gBAAgB;IAChB,CAAC,CAAC,SAAS,CAAC,yBAAa,CAAC,QAAQ,CAAC,EAAE,oBAAQ,CAAC,MAAM,CAAC,CAAC;IACtD,CAAC,CAAC,SAAS,CAAC,yBAAa,CAAC,KAAK,CAAC,EAAE,oBAAQ,CAAC,GAAG,CAAC,CAAC;IAChD,CAAC,CAAC,SAAS,CAAC,yBAAa,CAAC,IAAI,CAAC,EAAE,oBAAQ,CAAC,EAAE,CAAC,CAAC;IAC9C,CAAC,CAAC,SAAS,CAAC,yBAAa,CAAC,MAAM,CAAC,EAAE,oBAAQ,CAAC,IAAI,CAAC,CAAC;IAClD,CAAC,CAAC,SAAS,CAAC,yBAAa,CAAC,YAAY,CAAC,EAAE,oBAAQ,CAAC,UAAU,CAAC,CAAC;IAC9D,CAAC,CAAC,SAAS,CAAC,yBAAa,CAAC,QAAQ,CAAC,EAAE,oBA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C,MAAM,CAAC,CAAC,CAAC;AAC7C,CAAC,CAAC,CAAC;AAEH,aAAI,CAAC,mBAAmB,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE;IACpC,CAAC,CAAC,KAAK,CAAC,6BAAiB,CAAC,oBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IACzC,CAAC,CAAC,KAAK,CAAC,6BAAiB,CAAC,oBAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IAC1C,CAAC,CAAC,KAAK,CAAC,6BAAiB,CAAC,oBAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAE5C,CAAC,CAAC,IAAI,CAAC,6BAAiB,CAAC,oBAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;IACvC,CAAC,CAAC,IAAI,CAAC,6BAAiB,CAAC,oBAAQ,CAAC,UAAU,CAAC,CAAC,CAAC;IAC/C,CAAC,CAAC,IAAI,CAAC,6BAAiB,CAAC,oBAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AAC7C,CAAC,CAAC,CAAC"}

27
lib/logging.js generated Normal file
View File

@@ -0,0 +1,27 @@
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
function getActionsLogger() {
return core;
}
exports.getActionsLogger = getActionsLogger;
function getRunnerLogger(debugMode) {
return {
debug: debugMode ? console.debug : () => undefined,
info: console.info,
warning: console.warn,
error: console.error,
isDebug: () => debugMode,
startGroup: () => undefined,
endGroup: () => undefined,
};
}
exports.getRunnerLogger = getRunnerLogger;
//# sourceMappingURL=logging.js.map

1
lib/logging.js.map Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"logging.js","sourceRoot":"","sources":["../src/logging.ts"],"names":[],"mappings":";;;;;;;;;AAAA,oDAAsC;AActC,SAAgB,gBAAgB;IAC9B,OAAO,IAAI,CAAC;AACd,CAAC;AAFD,4CAEC;AAED,SAAgB,eAAe,CAAC,SAAkB;IAChD,OAAO;QACL,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,SAAS;QAClD,IAAI,EAAE,OAAO,CAAC,IAAI;QAClB,OAAO,EAAE,OAAO,CAAC,IAAI;QACrB,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS;QACxB,UAAU,EAAE,GAAG,EAAE,CAAC,SAAS;QAC3B,QAAQ,EAAE,GAAG,EAAE,CAAC,SAAS;KAC1B,CAAC;AACJ,CAAC;AAVD,0CAUC"}

14
lib/repository.js generated Normal file
View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function parseRepositoryNwo(input) {
const parts = input.split("/");
if (parts.length !== 2) {
throw new Error(`"${input}" is not a valid repository name`);
}
return {
owner: parts[0],
repo: parts[1],
};
}
exports.parseRepositoryNwo = parseRepositoryNwo;
//# sourceMappingURL=repository.js.map

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