Compare commits

...

996 Commits

Author SHA1 Message Date
shati-patel
096d7719c6 v1.6.6
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2022-05-17 16:07:06 +01:00
Angela P Wen
619c485224 Show query results before structured evaluator log summary completes (#1350) 2022-05-17 10:45:52 -04:00
Shati Patel
9367d5fb45 MRVA: Export results to local markdown files (#1344) 2022-05-17 10:03:23 +01:00
Shati Patel
50ec97ad91 Update CLI version used in tests 2022-05-16 17:43:06 +01:00
shati-patel
fa5fcde987 Rename button component 2022-05-16 16:45:07 +01:00
shati-patel
5b33333404 Fix padding to match design doc 2022-05-16 16:45:07 +01:00
shati-patel
cf50624e4e Tidy up 2022-05-16 16:45:07 +01:00
shati-patel
ccc9ed8b49 MRVA: Add webview button to export results 2022-05-16 16:45:07 +01:00
shati-patel
141f5381e7 MRVA: Export results from query history 2022-05-16 10:08:46 +01:00
shati-patel
be054ca4f8 Move "exporting results" to a separate file 2022-05-12 13:26:16 +01:00
Shati Patel
0a06452450 Update extensions/ql-vscode/src/remote-queries/remote-queries-manager.ts
Co-authored-by: Charis Kyriakou <charisk@users.noreply.github.com>
2022-05-11 17:27:45 +01:00
shati-patel
b840d3f9bf Tidy up Gist creation 2022-05-11 17:27:45 +01:00
shati-patel
c829c30688 MRVA: Add command to export markdown results to gist 2022-05-11 17:27:45 +01:00
Shati Patel
7947afb1b4 Remove unnecessary commas from alert shortDescription 2022-05-10 11:39:41 +01:00
Andrew Eisenberg
c058e7a128 Merge pull request #1340 from github/aeisenberg/fix-integration-tests
Fix cli-integration tests
2022-05-09 14:48:17 -07:00
Andrew Eisenberg
1dc663339d Revert back to vscode-test 2022-05-09 14:02:22 -07:00
Andrew Eisenberg
351db4efc8 Fix cli-integration tests
The main problem this commit fixes is with vscode 1.67.0, an error is
thrown when inside of integration tests and a dialog box is opened. We
were opening the telemetry dialog box. Now, an env variable is set
during cli-integration tests that prevents the dialog from being
opened.

There are also other cleanups and improvements with cli-integration
tests that assist with running locally:

- `vscode-test` dependency has been renamed to `@vscode/test-electron`,
  so use that instead and make the small API changes to support it.
- Commit the codeql-pack.lock.yml file so it isn't recreated on each
  test run.
- Ensure all databases are removed before _and after_ each test run
  that manipulates the set of installed databases
- Similarly, for quick query files, delete them before and after each
  test.
- Change some async `forEach` blocks to for loops in order to support
  sequential operations more easily.
2022-05-09 13:50:28 -07:00
Shati Patel
12d6ea3966 Update CLI version used in tests 2022-05-05 18:17:18 +01:00
shati-patel
e1adc7b428 MRVA: Rename summary file to make it appear first alphabetically 2022-05-05 14:32:55 +01:00
shati-patel
dc34adadcd Tidy up tests to use expected directory 2022-05-05 14:01:39 +01:00
shati-patel
6e06381640 Move expected files into subdirectory 2022-05-05 14:01:39 +01:00
shati-patel
f55389cd26 MRVA: Also test names of generated markdown files 2022-05-05 14:01:39 +01:00
shati-patel
6d930f53ba Don't include file extension for summary file
(to be consistent with other markdown files)
2022-05-04 17:18:00 +01:00
shati-patel
f7616cf685 Refactor: Include filename when generating markdown 2022-05-04 17:18:00 +01:00
Andrew Eisenberg
f55d9820bd Merge pull request #1329 from github/aeisenberg/run-queries-message
Further massage the message after running remote queries
2022-05-04 08:03:04 -07:00
Andrew Eisenberg
befc2cddd2 Apply suggestions from code review
Co-authored-by: Robert <robertbrignull@github.com>
2022-05-04 07:46:53 -07:00
Andrew Eisenberg
ef268e043f Further massage the message after running remote queries 2022-05-03 16:38:44 -07:00
Charis Kyriakou
e10d2aef8e Upgrade node version minimum requirement (#1326) 2022-05-03 16:10:45 +01:00
Charis Kyriakou
a97c5fe836 MRVA: Support both local and gist links when generating markdown 2022-05-03 13:27:53 +01:00
shati-patel
9b6eddddae MRVA: Expand path results individually 2022-04-29 18:50:30 +01:00
shati-patel
ed84825e65 See if replaceAll works on actions 2022-04-29 14:58:16 +01:00
shati-patel
cb84003c31 Actually fix the test + code scanning error 🤞🏽 2022-04-29 14:58:16 +01:00
shati-patel
a1cd87aa3a Update test data + try to fix code scanning error 2022-04-29 14:58:16 +01:00
shati-patel
7d3b015e20 Generate markdown for raw result tables 2022-04-29 14:58:16 +01:00
Charis Kyriakou
7d0d11f526 MRVA: Add view on GitHub action to cancelled/failed queries (#1325) 2022-04-29 11:11:33 +01:00
Shati Patel
eb2520e7ca Fix outdated description of "watch" command 2022-04-28 15:29:38 +01:00
shati-patel
2675bf464e Correctly indent code snippets that use tabs 2022-04-28 12:03:39 +01:00
shati-patel
b638449498 Link to specific highlighted line instead of whole code snippet 2022-04-28 12:03:39 +01:00
shati-patel
e12bf63f9a Minor tidy-up 2022-04-27 16:45:01 +01:00
shati-patel
ffcc1f82f1 Generate markdown summary file for raw results 2022-04-27 16:45:01 +01:00
shati-patel
04d7b12dd8 Extract "getAnalysisResultCount" to helper file 2022-04-27 16:45:01 +01:00
shati-patel
3e33b00a75 Add test data for raw results 2022-04-27 16:45:01 +01:00
Andrew Eisenberg
12dc378fc1 Merge pull request #1305 from github/aeisenberg/mrva-result-message
Update the warning message after running variant analysis
2022-04-26 11:46:03 -07:00
Andrew Eisenberg
bbe99f4451 Fix newlines in tests 2022-04-26 11:34:00 -07:00
shati-patel
91b17f8fa6 Update CLI version used in tests 2022-04-26 14:36:48 +01:00
Shati Patel
69f1778309 Update extensions/ql-vscode/src/remote-queries/remote-queries-markdown-generation.ts
Co-authored-by: Charis Kyriakou <charisk@users.noreply.github.com>
2022-04-26 10:15:45 +01:00
shati-patel
c55e801d00 Add example with multiple paths 2022-04-26 10:15:45 +01:00
shati-patel
b363f77a83 Tidy up how we display paths 2022-04-26 10:15:45 +01:00
shati-patel
f55f46f95b Markdown rendering: Display paths 2022-04-26 10:15:45 +01:00
github-actions[bot]
5ee2f0efe1 Bump version to v1.6.6 (#1315)
Co-authored-by: angelapwen <angelapwen@users.noreply.github.com>
2022-04-25 10:34:34 -07:00
Angela P Wen
1314a36ba4 v1.6.5 (#1314)
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2022-04-25 09:42:44 -07:00
shati-patel
2b8b621298 10% nicer way of wrapping code lines 😄
+ update test data to contain a single-line example
2022-04-25 12:42:10 +01:00
shati-patel
aed4c9fc58 MRVA: Make markdown code snippets look nicer
Remove some extraneous newlines
2022-04-25 12:42:10 +01:00
Andrew Eisenberg
604001dfb1 Update extensions/ql-vscode/src/remote-queries/run-remote-query.ts
Move comment
2022-04-22 13:42:10 -07:00
shati-patel
1a03c0e4ac Attempt to fix tests 2022-04-22 14:52:15 +01:00
shati-patel
a8c54b7640 MRVA: Don't display excessive error/warning pop-ups if user doesn't select a repo list 2022-04-22 14:52:15 +01:00
shati-patel
9bb60c9474 Link to workflow + fix incorrect comment 2022-04-22 13:01:54 +01:00
shati-patel
0b2ce7a071 MRVA: Display available results, even if some jobs are cancelled 2022-04-22 13:01:54 +01:00
Andrew Eisenberg
44145baca7 Use os.EOL instead of \n 2022-04-21 08:47:48 -07:00
Angela P Wen
dac7881ca3 Bug fix for show eval log and show eval log summary commands in query history view (#1304) 2022-04-21 08:11:58 -07:00
Charis Kyriakou
31bd927959 Fix max-width for code paths (#1309) 2022-04-21 13:12:40 +00:00
shati-patel
908a862dd1 Tidy up test 2022-04-21 09:57:23 +01:00
shati-patel
6676ba99d0 Add initial test data for problem query 2022-04-21 09:57:23 +01:00
shati-patel
6d3c6e598f Change folder structure to have separate folders for path-problem and problem queries 2022-04-21 09:57:23 +01:00
shati-patel
e1a10fc827 Markdown results: Highlight snippets with "<strong>" 2022-04-21 09:17:31 +01:00
Andrew Eisenberg
2ebdbaafa3 Update the warning message after running variant analysis
Adds more information about onboarding new repos.
2022-04-20 14:46:23 -07:00
shati-patel
a74dfea08b Use HTML code blocks
This is so that we can highlight code snippets using `<strong>` tags
2022-04-20 10:32:24 +01:00
Andrew Eisenberg
44ff380c86 Merge pull request #1295 from github/aeisenberg/result-log
Add better error messages for partial failing variant analysis
2022-04-19 17:55:31 -07:00
Andrew Eisenberg
0a41713253 Add new test
And rename test file.
2022-04-19 17:45:17 -07:00
Andrew Eisenberg
f5a5675da4 Merge pull request #1298 from github/aeisenberg/no-results-mixing
Avoid loading wrong results into an open window
2022-04-19 16:02:14 -07:00
Andrew Eisenberg
7a8cf55090 Merge pull request #1294 from github/aeisenberg/db-name-github
Display nicer names for github-downloaded databases
2022-04-19 16:01:04 -07:00
Andrew Eisenberg
7932de3b7d Merge pull request #1299 from github/aeisenberg/remove-jsonc 2022-04-18 09:06:13 -07:00
Andrew Eisenberg
c8ba967a54 Remove jsonc dependency
This dependency was only used to parse package.json and
this can be just as easily parsed by regular JSON object.

jsonc can also parse JSON with comments, but there are no
comments in package.json.
2022-04-14 15:45:24 -07:00
Andrew Eisenberg
f5d2f0e0ca Merge pull request #1263 from github/dependabot/npm_and_yarn/extensions/ql-vscode/zip-a-folder-1.1.3
Bump zip-a-folder from 0.0.12 to 1.1.3 in /extensions/ql-vscode
2022-04-14 15:36:44 -07:00
Andrew Eisenberg
2c7e2f4b7f Avoid loading wrong results into an open window
This fixes a bug where an open results view will accumulate results from
other queries who have their results downloaded while this view is open.

The fix is to ensure that the results view for the query is open when
some results are downloaded.
2022-04-14 14:54:42 -07:00
dependabot[bot]
ee3ebe687b Bump zip-a-folder from 0.0.12 to 1.1.3 in /extensions/ql-vscode
Bumps [zip-a-folder](https://github.com/maugenst/zip-a-folder) from 0.0.12 to 1.1.3.
- [Release notes](https://github.com/maugenst/zip-a-folder/releases)
- [Commits](https://github.com/maugenst/zip-a-folder/commits)

---
updated-dependencies:
- dependency-name: zip-a-folder
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-04-14 21:09:55 +00:00
Andrew Eisenberg
77024f0757 Merge pull request #1297 from github/dependabot/npm_and_yarn/extensions/ql-vscode/async-2.6.4
Bump async from 2.6.3 to 2.6.4 in /extensions/ql-vscode
2022-04-14 14:08:46 -07:00
Andrew Eisenberg
c0e39886eb Add unit tests for remote queries in logs
Also, change text slightly.
2022-04-14 13:39:36 -07:00
dependabot[bot]
6339e7897d Bump async from 2.6.3 to 2.6.4 in /extensions/ql-vscode
Bumps [async](https://github.com/caolan/async) from 2.6.3 to 2.6.4.
- [Release notes](https://github.com/caolan/async/releases)
- [Changelog](https://github.com/caolan/async/blob/v2.6.4/CHANGELOG.md)
- [Commits](https://github.com/caolan/async/compare/v2.6.3...v2.6.4)

---
updated-dependencies:
- dependency-name: async
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-04-14 19:41:37 +00:00
Andrew Eisenberg
783a8a8772 Merge pull request #1290 from github/aeisenberg/remote-history-label-editing
Allow remote query items to have their labels edited
2022-04-14 12:40:50 -07:00
Andrew Eisenberg
8f2d865999 Display nicer names for github-downloaded databases
This will now name databases downloaded from github based on their nwo.

Also, this adds a new button to suggest downloading from github in an
empty databases view.
2022-04-14 12:36:43 -07:00
Andrew Eisenberg
d6d0825926 Merge branch 'main' into aeisenberg/remote-history-label-editing 2022-04-14 12:30:08 -07:00
Andrew Eisenberg
37de2e7f52 Add better error messages for partial failing variant analysis
Two scenarios handled:

1. no database for existing repo
2. repo does not exits (or no access rights for current user)

In either case, an error message is sent to the logs, with a notificaiton
in a popup.
2022-04-13 16:32:13 -07:00
Andrew Eisenberg
800c9e0c93 Remove deprecated comments
Also, change interpolation of result count. For Remote queries, this
value will be empty. For local queries, use the label `X results`, where
`X` is the number of results for this query.
2022-04-13 14:08:44 -07:00
shati-patel
a1bc7eb4d5 Capitalize! 2022-04-13 17:00:17 +01:00
shati-patel
8ff45d2aee Split handling of highlighted code lines into helper function 2022-04-13 17:00:17 +01:00
Andrew Eisenberg
8ec19777b5 Merge pull request #1291 from github/aeisenberg/handle-remote-cancel
Handle cancelling of remote queries
2022-04-13 06:59:14 -07:00
Andrew Eisenberg
3e388fedeb Merge pull request #1292 from github/aeisenberg/rename-remote-queries
Rename remote queries -> variant analysis
2022-04-13 06:41:33 -07:00
Andrew Eisenberg
83ffba2f08 Rename remote queries -> variant analysis
In some user facing text.
2022-04-12 13:16:44 -07:00
Andrew Eisenberg
f1c4fef8ba Allow remote query items to have their labels edited
The labels for remote query items are interpolated using the same
strategy as local queries with two caveats:

1. There is no easy way to get the result count without reading files,
   so, this value is kept empty.
2. There is no database name for remote queries. Instead, use the
   nwo of the controller repo.

Also, adds tests for the history item label provider.
2022-04-12 12:37:31 -07:00
Andrew Eisenberg
eec506a209 Introduce history-item-label-provider
The label provider is the instance that performs the logic for
generating labels for history items, using string interpolation when
necessary.

This commit creates the label provider and uses it with local queries.
Remote queries will be changed in the next commit.
2022-04-12 12:35:01 -07:00
Andrew Eisenberg
2ca0060c6a Remove references to 'remote query' in user-facing text
(Only in recently introduced locations. More work still needs to be
done.)

Also:

- Change error to info
- Create credentials directly, don't use a callback.
2022-04-12 12:20:39 -07:00
shati-patel
8b2d79a7f7 Formatting fixes and code tidy-up 2022-04-12 12:32:45 +01:00
shati-patel
c4db8b6d4b Create markdown summary file for sharing MRVA results 2022-04-12 12:32:45 +01:00
Andrew Eisenberg
61d4305593 Handle cancelling of remote queries
This change issues a cancel request when the user clicks on "cancel" for
a remote query.

The cancel can take quite a while to complete, so a message is popped up
to let the user know.
2022-04-11 19:05:00 -07:00
Andrew Eisenberg
542e1d24aa Allow remote query items to have their labels edited
The labels for remote query items are interpolated using the same
strategy as local queries with two caveats:

1. There is no easy way to get the result count without reading files,
   so, this value is kept empty.
2. There is no database name for remote queries. Instead, use the 
   nwo of the controller repo.
2022-04-11 14:20:57 -07:00
shati-patel
47ec074cfb Tidy-up and address review comments 2022-04-11 15:24:08 +01:00
shati-patel
e44835e795 Make line endings consistent? 2022-04-11 15:24:08 +01:00
shati-patel
2e28146a58 Create markdown files for sharing results 2022-04-11 15:24:08 +01:00
Andrew Eisenberg
85e051a76d Merge pull request #1285 from github/aeisenberg/reenable-openvsx
Reenable publishing to open-vsx
2022-04-08 09:40:40 -07:00
Andrew Eisenberg
7027a61e63 Update changelog 2022-04-07 14:01:28 -07:00
Andrew Eisenberg
e8c5b27d92 Reenable publishing to open-vsx
The extension ms-vscode.test-adapter-converter is now available on
open-vsx, but under a different name.

Fixes https://github.com/github/vscode-codeql/issues/1085

I have verified that I can publish and install the extension by
manually publishing v1.6.4.
2022-04-07 13:58:16 -07:00
Andrew Eisenberg
a3deec7875 Merge pull request #1280 from febuiles/patch-2
Update dependency-review.yml
2022-04-07 08:39:47 -07:00
Andrew Eisenberg
6282a462c8 Merge pull request #1283 from github/bump-cli 2022-04-07 07:44:29 -07:00
Shati Patel
dac5952e96 Bump CLI version used in integration tests 2022-04-07 15:30:41 +01:00
Federico Builes
ada6fcb908 Try using workflow_dispatch. 2022-04-07 13:36:57 +02:00
Andrew Eisenberg
8d2f902420 Merge pull request #1282 from github/version/bump-to-v1.6.5
Bump version to v1.6.5
2022-04-07 02:11:28 -07:00
aeisenberg
fc3fe7a81e Bump version to v1.6.5 2022-04-06 22:39:04 +00:00
Andrew Eisenberg
426cc95e9f Merge pull request #1281 from github/v1.6.4
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
v1.6.4
2022-04-06 15:36:05 -07:00
Andrew Eisenberg
9e40043fe0 v1.6.4 2022-04-06 14:54:56 -07:00
Federico Builes
14608fe5f7 Update dependency-review.yml 2022-04-06 15:17:40 +02:00
Charis Kyriakou
22ed090685 Add support for system defined repository lists (#1271) 2022-04-06 09:05:22 +01:00
Charis Kyriakou
2ca4097daf Move remote queries test files to be under remote-queries dir (#1270) 2022-04-05 08:40:10 +01:00
github-actions[bot]
f1d16015bf Bump version to v1.6.4 (#1278)
Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2022-04-04 23:44:55 +00:00
Andrew Eisenberg
9a81ad05ed Merge pull request #1277 from github/v1.6.3
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
v1.6.3
2022-04-04 12:39:27 -07:00
Andrew Eisenberg
76e983d19c v1.6.3
Also adds a step in our release process to manually test the new
extension build.
2022-04-04 12:30:41 -07:00
Andrew Eisenberg
a3015c0fa3 Merge pull request #1276 from github/aeisenberg/dev-dependencies
Move source-map-support to dependencies
2022-04-04 12:27:09 -07:00
Andrew Eisenberg
88d0bda049 Move source-map-support to dependencies 2022-04-04 12:15:57 -07:00
Andrew Eisenberg
d2ec54e89e Merge pull request #1273 from github/version/bump-to-v1.6.3
Bump version to v1.6.3
2022-04-04 09:10:52 -07:00
edoardopirovano
4559c5a38d Bump version to v1.6.3 2022-04-04 15:28:36 +00:00
Edoardo Pirovano
16bd106abc v1.6.2
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2022-04-04 08:25:23 -07:00
Charis Kyriakou
e5dcec8d8e Move repository selection code to own module (#1269) 2022-04-04 11:03:53 +01:00
Charis Kyriakou
ad3565d3ad Use the repos defined in the query result instead of the query (#1268) 2022-04-04 11:03:05 +01:00
Andrew Eisenberg
5fe12ecd74 Merge pull request #1265 from github/aeisenberg/pat-instructions-update
Move vscode marketplace pat isntructions to internal docs
2022-03-31 12:24:51 -07:00
Andrew Eisenberg
318214642f Merge pull request #1249 from github/dependabot/npm_and_yarn/extensions/ql-vscode/ts-node-10.7.0
Bump ts-node from 8.10.2 to 10.7.0 in /extensions/ql-vscode
2022-03-31 12:15:43 -07:00
Andrew Eisenberg
227fe3ee6b Fix typo
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2022-03-31 12:12:57 -07:00
dependabot[bot]
978a82dd1a Bump ts-node from 8.10.2 to 10.7.0 in /extensions/ql-vscode
Bumps [ts-node](https://github.com/TypeStrong/ts-node) from 8.10.2 to 10.7.0.
- [Release notes](https://github.com/TypeStrong/ts-node/releases)
- [Commits](https://github.com/TypeStrong/ts-node/compare/v8.10.2...v10.7.0)

---
updated-dependencies:
- dependency-name: ts-node
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-31 18:51:38 +00:00
Andrew Eisenberg
04f72a7da9 Merge pull request #1260 from github/aeisenberg/source-map-support
Add source map support and clean test dependencies
2022-03-31 11:42:22 -07:00
Andrew Eisenberg
a0954a1dc0 Move vscode marketplace pat isntructions to internal docs 2022-03-31 10:22:33 -07:00
Angela P Wen
cc1bf74370 Print end-of-query summary logs to Query Server Console (#1264)
* Log new end summary file to query server console

* Change supported CLI version to 2.9.0
2022-03-31 16:26:13 +00:00
Andrew Eisenberg
2f7908773a Merge pull request #1253 from github/aeisenberg/codeSnippet-handling 2022-03-31 07:19:44 -07:00
Andrew Eisenberg
0efd02979e Merge pull request #1242 from github/aeisenberg/analysis-results-on-restart 2022-03-31 07:19:02 -07:00
shati-patel
bd9776c4b7 Variant analysis: Remove handling of invalid repos
This is now done automatically on the API side
2022-03-31 15:15:16 +01:00
Andrew Eisenberg
35e9da83ec Add source map support and clean test dependencies
1. Source map support means that stack traces will point to the *.ts
   file instead of the generated *.js file
2. Cleaning test dependencies means moving all mocha and chai
   registration into the respective index files and removing unnecessary
   imports.
2022-03-30 12:30:18 -07:00
Andrew Eisenberg
4f5ca0bca9 Merge pull request #1261 from github/aeisenberg/dependabot-changes
Run dependabot updates weekly
2022-03-30 12:05:06 -07:00
Andrew Eisenberg
43f314b2b5 Change missing code snippet handling in UI
Also, simplify sarif tests.
2022-03-30 12:02:19 -07:00
Andrew Eisenberg
4bdf579ce2 Merge branch 'aeisenberg/analysis-results-on-restart' into aeisenberg/codeSnippet-handling 2022-03-30 11:57:24 -07:00
Andrew Eisenberg
aba3039eef Merge pull request #1257 from github/dependabot/npm_and_yarn/extensions/ql-vscode/sinon-13.0.1
Bump sinon from 9.0.2 to 13.0.1 in /extensions/ql-vscode
2022-03-30 11:48:11 -07:00
Andrew Eisenberg
bbff791c65 Merge pull request #1258 from github/dependabot/npm_and_yarn/extensions/ql-vscode/gulp-sourcemaps-3.0.0
Bump gulp-sourcemaps from 2.6.5 to 3.0.0 in /extensions/ql-vscode
2022-03-30 11:47:20 -07:00
Andrew Eisenberg
1ed50b3081 Run dependabot updates weekly
Daily is too noisy.
2022-03-30 11:45:39 -07:00
Andrew Eisenberg
67336a24e7 Simplify checking for downloaded analyses
And some renaming.
2022-03-30 11:30:10 -07:00
Andrew Eisenberg
48174c327d Merge pull request #1246 from github/aeisenberg/repo-filter
Add repositories search box
2022-03-30 11:14:27 -07:00
Andrew Eisenberg
43f2539b42 Remove unused css class 2022-03-30 10:54:14 -07:00
dependabot[bot]
462a7a722a Bump gulp-sourcemaps from 2.6.5 to 3.0.0 in /extensions/ql-vscode
Bumps [gulp-sourcemaps](https://github.com/gulp-sourcemaps/gulp-sourcemaps) from 2.6.5 to 3.0.0.
- [Release notes](https://github.com/gulp-sourcemaps/gulp-sourcemaps/releases)
- [Commits](https://github.com/gulp-sourcemaps/gulp-sourcemaps/compare/v2.6.5...v3.0.0)

---
updated-dependencies:
- dependency-name: gulp-sourcemaps
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-30 13:04:47 +00:00
dependabot[bot]
4101bb252e Bump sinon from 9.0.2 to 13.0.1 in /extensions/ql-vscode
Bumps [sinon](https://github.com/sinonjs/sinon) from 9.0.2 to 13.0.1.
- [Release notes](https://github.com/sinonjs/sinon/releases)
- [Changelog](https://github.com/sinonjs/sinon/blob/main/docs/changelog.md)
- [Commits](https://github.com/sinonjs/sinon/compare/v9.0.2...v13.0.1)

---
updated-dependencies:
- dependency-name: sinon
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-30 13:04:31 +00:00
Shati Patel
4ff4e4827e Bump CLI version in integration tests 2022-03-30 12:03:16 +01:00
Andrew Eisenberg
8daa92ad49 Merge branch 'main' into aeisenberg/analysis-results-on-restart 2022-03-29 16:04:35 -07:00
Andrew Eisenberg
371e83bff9 Merge branch 'aeisenberg/analysis-results-on-restart' into aeisenberg/codeSnippet-handling 2022-03-29 15:30:08 -07:00
Andrew Eisenberg
6fa0227a1e Merge branch 'main' into aeisenberg/codeSnippet-handling 2022-03-29 15:08:17 -07:00
Andrew Eisenberg
c38e4ce265 Merge pull request #1252 from github/aeisenberg/settings
Prevent cli path from being synced across remote instances
2022-03-29 14:23:51 -07:00
Andrew Eisenberg
de06ed148d Merge branch 'main' into aeisenberg/analysis-results-on-restart 2022-03-29 14:21:15 -07:00
Andrew Eisenberg
21bcd62ba8 Merge pull request #1239 from github/dependabot/npm_and_yarn/extensions/ql-vscode/types/gulp-replace-1.1.0
Bump @types/gulp-replace from 0.0.31 to 1.1.0 in /extensions/ql-vscode
2022-03-29 14:21:06 -07:00
Andrew Eisenberg
76c034f79a Merge branch 'main' into aeisenberg/repo-filter 2022-03-29 14:15:31 -07:00
Andrew Eisenberg
d8d394ce40 Use new version of gulp-replace 2022-03-29 14:09:01 -07:00
Andrew Eisenberg
213f4ce92f Merge branch 'main' into aeisenberg/settings 2022-03-29 13:54:41 -07:00
Andrew Eisenberg
2d1726763f Merge pull request #1254 from github/aeisenberg/fix-main
Fix duplication import
2022-03-29 13:54:00 -07:00
Andrew Eisenberg
abfd9b3cbd Fix duplication import 2022-03-29 13:21:08 -07:00
Andrew Eisenberg
6114f6a7fd Merge branch 'main' into aeisenberg/analysis-results-on-restart 2022-03-29 13:18:13 -07:00
Andrew Eisenberg
61e674e9f6 Allow for undefined codeSnippets
This reverts commit 006cc8c52a.
2022-03-29 13:10:28 -07:00
Andrew Eisenberg
006cc8c52a Undo sarif-processing change
Will move to a different PR.
2022-03-29 13:07:56 -07:00
Andrew Eisenberg
ffe7fdcb46 Rename methods and address comments 2022-03-29 13:04:00 -07:00
Andrew Eisenberg
49cceffe1b Merge pull request #1235 from github/aeisenberg/history-sort
Add query history sorting for remote queries
2022-03-29 11:13:35 -07:00
Andrew Eisenberg
011782395a Merge pull request #1250 from github/dependabot/npm_and_yarn/extensions/ql-vscode/types/webpack-5.28.0
Bump @types/webpack from 4.41.21 to 5.28.0 in /extensions/ql-vscode
2022-03-29 11:13:00 -07:00
Andrew Eisenberg
558009543f Update changelog 2022-03-29 11:11:44 -07:00
Andrew Eisenberg
aaef5bde2c Prevent cli path from being synced across remote instances
This will fix a problem where settings sync will cause the cli not
to be found on codespaces.
2022-03-29 11:08:31 -07:00
Andrew Eisenberg
f52f595d56 Add max-width for remote queries results page 2022-03-29 11:05:22 -07:00
dependabot[bot]
50196d8430 Bump @types/webpack from 4.41.21 to 5.28.0 in /extensions/ql-vscode
Bumps [@types/webpack](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/webpack) from 4.41.21 to 5.28.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/webpack)

---
updated-dependencies:
- dependency-name: "@types/webpack"
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-29 17:17:18 +00:00
Andrew Eisenberg
2ecfbfbb42 Merge pull request #1244 from github/aeisenberg/webpack-watch
Add webpack watch gulp task
2022-03-29 10:16:18 -07:00
Andrew Eisenberg
9508dffe6d Merge pull request #1236 from github/dependabot/npm_and_yarn/extensions/ql-vscode/fs-extra-10.0.1
Bump fs-extra from 9.0.1 to 10.0.1 in /extensions/ql-vscode
2022-03-29 10:15:13 -07:00
Andrew Eisenberg
b4a72bbcab Merge pull request #1238 from github/dependabot/npm_and_yarn/extensions/ql-vscode/through2-4.0.2
Bump through2 from 3.0.2 to 4.0.2 in /extensions/ql-vscode
2022-03-29 10:08:32 -07:00
Andrew Eisenberg
4ceaaf92cc Merge pull request #1237 from github/dependabot/npm_and_yarn/extensions/ql-vscode/vsce-2.7.0
Bump vsce from 1.88.0 to 2.7.0 in /extensions/ql-vscode
2022-03-29 10:07:04 -07:00
Andrew Eisenberg
ef28c9531b Update extensions/ql-vscode/gulpfile.ts/webpack.ts 2022-03-29 08:50:42 -07:00
Shati Patel
c86c602e39 Allow GitHub URL as well as NWO (#1241) 2022-03-29 12:45:46 +01:00
Angela P Wen
3bee2905e5 Gate show eval log and summary commands behind CLI v2.8.4 (#1243) 2022-03-29 05:30:31 -04:00
Edoardo Pirovano
9ac8a15cd5 Address review comments from @aeisenberg 2022-03-29 05:30:31 -04:00
Edoardo Pirovano
81b8104064 Expose per-query structured evaluator logs 2022-03-29 05:30:31 -04:00
Andrew Eisenberg
65f58b1f98 Add repositories search box
A simple, webview-only search box for filtering repositories from
the remote queries results view.
2022-03-28 17:01:11 -07:00
Andrew Eisenberg
7e872aa6d6 Add webpack watch gulp task
Now, when running `npm run watch`, both the regular tsc command
and the webpack command will be run in watch mode.

The raw gulp tasks are now:

- `gulp watchView` to watch webpack compilation.
- `gulp watchCss` to watch for css changes.
- `gulp compileView` to compile the webpack once and exit.

However, stats are no longer being printed out. Not sure why.
2022-03-28 15:43:35 -07:00
Andrew Eisenberg
0383a91a68 Display proper download state in remote results view
Before displaying any results for a remote query, ensure that all
downloaded results are in memory. This ensures the proper download icon
is displayed alongside each NWO.
2022-03-28 12:38:13 -07:00
Andrew Eisenberg
bb6ebe5750 Handle query directory not existing
Also, fix some changelog notes.
2022-03-28 10:55:02 -07:00
Andrew Eisenberg
71aa3d145f Update changelog 2022-03-25 14:30:01 -07:00
dependabot[bot]
2f1f80029b Bump @types/gulp-replace from 0.0.31 to 1.1.0 in /extensions/ql-vscode
Bumps [@types/gulp-replace](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/gulp-replace) from 0.0.31 to 1.1.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/gulp-replace)

---
updated-dependencies:
- dependency-name: "@types/gulp-replace"
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-25 21:28:00 +00:00
dependabot[bot]
ad18cfa284 Bump through2 from 3.0.2 to 4.0.2 in /extensions/ql-vscode
Bumps [through2](https://github.com/rvagg/through2) from 3.0.2 to 4.0.2.
- [Release notes](https://github.com/rvagg/through2/releases)
- [Commits](https://github.com/rvagg/through2/compare/v3.0.2...v4.0.2)

---
updated-dependencies:
- dependency-name: through2
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-25 21:27:45 +00:00
dependabot[bot]
92ed1c6ac9 Bump vsce from 1.88.0 to 2.7.0 in /extensions/ql-vscode
Bumps [vsce](https://github.com/Microsoft/vsce) from 1.88.0 to 2.7.0.
- [Release notes](https://github.com/Microsoft/vsce/releases)
- [Commits](https://github.com/Microsoft/vsce/compare/v1.88.0...v2.7.0)

---
updated-dependencies:
- dependency-name: vsce
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-25 21:27:25 +00:00
dependabot[bot]
e71e04a8f1 Bump fs-extra from 9.0.1 to 10.0.1 in /extensions/ql-vscode
Bumps [fs-extra](https://github.com/jprichardson/node-fs-extra) from 9.0.1 to 10.0.1.
- [Release notes](https://github.com/jprichardson/node-fs-extra/releases)
- [Changelog](https://github.com/jprichardson/node-fs-extra/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jprichardson/node-fs-extra/compare/9.0.1...10.0.1)

---
updated-dependencies:
- dependency-name: fs-extra
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-25 21:27:03 +00:00
Andrew Eisenberg
ef127c279c Merge pull request #1233 from github/aeisenberg/dependabot
Add dependabot configuration
2022-03-25 14:26:02 -07:00
Andrew Eisenberg
4afac5fa4d Add query history sorting for remote queries
Also, fix two smaller issues:

- Ensure the `Open Query Directory` command opens inside the specified
  directory.
- Ensure label changes are saved across restarts.
2022-03-25 14:25:07 -07:00
Andrew Eisenberg
29ae97aa82 Add actions to dependabot config 2022-03-25 13:18:46 -07:00
Andrew Eisenberg
9319d7e8ef Add dependabot configuration 2022-03-25 12:21:10 -07:00
dependabot[bot]
689db3713b Bump minimist from 1.2.5 to 1.2.6 in /extensions/ql-vscode
Bumps [minimist](https://github.com/substack/minimist) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: minimist
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-25 18:48:40 +00:00
Andrew Eisenberg
0b9fcb884b Merge pull request #1202 from github/aeisenberg/update-tsc
Update tsc to 4.5.5
2022-03-25 11:33:37 -07:00
Andrew Eisenberg
23e29a1fdc Update tsc to 4.5.5
The default version of tsc in vscode is now 4.5.4. This version
has changed the type of the variable in the catch block.
Previously, it was `any`. Now it is `unknown`.

This change updates vscode so that it can build with 4.5.4.

Previously, this had been a bit of a pain since sometimes running
a compile task in vscode will use the global default version of
tsc.
2022-03-25 09:48:51 -07:00
Shati Patel
90d636a026 Download databases from GitHub (#1229) 2022-03-25 15:24:09 +00:00
Andrew Eisenberg
3e3e12afb9 Merge pull request #1230 from github/aeisenberg/astviewer-uri
Fix invalid file comparison for changing ast viewer location
2022-03-25 08:21:05 -07:00
Andrew Eisenberg
421f5d23ec Update changelog 2022-03-24 12:39:11 -07:00
Andrew Eisenberg
0fa91f32cb Fix invalid file comparison for changing ast viewer location
This fixes a bug where the ast viewer was not updating its source
location when a user clicks on different parts of a file.

The problem was that the file name of the AST viewer was being stored as
a base name, which was getting compared with the full URI string of the
current file.

This fixes the comparison to ensure that the full URI strings are always
being compared.
2022-03-24 12:36:17 -07:00
shati-patel
3d21b203be Make "promptForLanguage" more general
(so we can use it for downloading a GH database as well)
2022-03-21 16:37:51 +00:00
shati-patel
3972b8f4c1 Rename LGTM-specific function 2022-03-21 16:37:51 +00:00
Tobias Speicher
2d1707db00 refactor: replace deprecated String.prototype.substr()
.substr() is deprecated so we replace it with .slice() which works similarily but isn't deprecated
Signed-off-by: Tobias Speicher <rootcommander@gmail.com>
2022-03-21 14:16:54 +00:00
Robert
72aa4f0561 Merge pull request #1226 from github/robertbrignull/allow-custom-action-branch
Allow a custom branch name in settings file
2022-03-21 10:52:21 +00:00
Robert
fd57cc95e9 Remove unnnecessary function 2022-03-21 10:38:00 +00:00
Robert
04c392be7e Allow a custom branch name in settings file 2022-03-18 16:26:06 +00:00
github-actions[bot]
38da598214 Bump version to v1.6.2 (#1221)
Co-authored-by: charisk <charisk@users.noreply.github.com>
2022-03-17 12:47:33 +00:00
Charis Kyriakou
3f2c9b647c v1.6.1 (#1220)
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2022-03-17 12:04:37 +00:00
Shati Patel
7d5b4369c1 Fix highlighting issues (#1219) 2022-03-17 11:45:31 +00:00
Shati Patel
aade33fa88 Minor webview fixes (#1217) 2022-03-17 11:12:50 +00:00
Shati Patel
2a8a90bdfc Change public occurrences of "remote queries" (#1215) 2022-03-17 10:14:32 +00:00
Shati Patel
f36048cc95 Use variable for highlighting code (#1216) 2022-03-17 10:08:42 +00:00
Charis Kyriakou
517feeca21 Remove SARIF viewer support (#1213) 2022-03-16 14:39:52 +00:00
Charis Kyriakou
9436a49118 Remove helper command for working on the Remote Query results view (#1214) 2022-03-16 14:19:19 +00:00
Charis Kyriakou
0e02cb08fd Enable viewing of analyses results (#1212) 2022-03-16 14:15:43 +00:00
Shati Patel
26244efc50 Create remote file links to GitHub URL (#1209)
Co-authored-by: Charis Kyriakou <charisk@github.com>
2022-03-16 14:11:17 +00:00
Charis Kyriakou
6339eeffe5 Minor styling fix for raw results (#1211) 2022-03-16 11:44:51 +00:00
Charis Kyriakou
8cc2f598eb Fix highlight region end column calculation (#1210) 2022-03-16 09:47:09 +00:00
Charis Kyriakou
46a1dd57f4 Minor style fixes around result rendering (#1208) 2022-03-15 14:43:24 +00:00
shati-patel
9d99fc521e Get database sha from result index 2022-03-15 10:30:01 +00:00
Shati Patel
bcf79354ee Bump CLI version in integration tests 2022-03-15 10:22:18 +00:00
Charis Kyriakou
27a8636bac Deal with non-printable characters when rendering raw results (#1203) 2022-03-14 11:25:33 +00:00
Charis Kyriakou
92a99938c9 Add support for remote queries raw results (#1198) 2022-03-14 08:18:43 +00:00
Charis Kyriakou
ed61eb0a95 Deal with analysis messages that have links to locations (#1195) 2022-03-14 08:14:09 +00:00
Andrew Eisenberg
50d495b522 Merge pull request #1201 from mrysav/patch-1
Install Dependency Review Action
2022-03-11 10:40:06 -08:00
Andrew Eisenberg
526d5c2c44 Apply suggestions from code review 2022-03-11 10:29:02 -08:00
Charis Kyriakou
1720f9201e Update Primer React to v35 (#1199) 2022-03-10 20:24:12 +00:00
Mitchell Rysavy
e62de1ca22 Create dependency-review.yml 2022-03-10 14:48:06 -05:00
Charis Kyriakou
d052ddb742 Rename analysis alert results (#1197) 2022-03-10 07:56:05 +00:00
Andrew Eisenberg
af53a02ea5 Merge pull request #1192 from github/aeisenberg/disable-openvsx-deploy
Disable the open-vsx-publish job
2022-03-09 09:27:17 -08:00
Charis Kyriakou
8e2d18da8c Rename ColumnValue to CellValue (#1196) 2022-03-09 16:44:15 +00:00
Charis Kyriakou
2c5004387d Add support for showing code flows (#1187) 2022-03-09 09:15:45 +00:00
Charis Kyriakou
3fc3b259ba Add pre-push hook check to block leftover .only()s (#1189) 2022-03-08 09:32:18 +00:00
Andrew Eisenberg
cd95f68692 Merge pull request #1191 from github/version/bump-to-v1.6.1
Bump version to v1.6.1
2022-03-07 10:25:23 -08:00
Andrew Eisenberg
59c3b1ba2f Disable the open-vsx-publish job
It is failing, blocked on #1085
2022-03-07 10:19:42 -08:00
aeisenberg
fa85865fe5 Bump version to v1.6.1 2022-03-07 18:04:29 +00:00
Andrew Eisenberg
5575d4142c Merge pull request #1190 from github/v1.6.0
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
v1.6.0
2022-03-07 10:00:52 -08:00
Andrew Eisenberg
ae6263a07f v1.6.0
Note that the change to `run-remote-query.ts` is being coordinated
with the rest of the remote-queries team.
2022-03-07 09:46:56 -08:00
Charis Kyriakou
9af75634fa Remove .only from mocha test (#1188) 2022-03-07 10:04:29 +00:00
Andrew Eisenberg
04b8681272 Merge pull request #1184 from github/aeisenberg/open-remote
Add command to open remote query on github
2022-03-04 10:46:55 -08:00
Andrew Eisenberg
d5549f2894 Add command to open remote query on github
Command is available for remote queries that are in progress or
completed.
2022-03-04 10:36:41 -08:00
Charis Kyriakou
b510b85ca0 Extract code snippet into stand alone component (#1181) 2022-03-04 08:06:19 +00:00
Andrew Eisenberg
5ad754a3a2 Merge pull request #1178 from github/aeisenberg/log-history
Save log files to the query history directory
2022-03-03 08:14:25 -08:00
Andrew Eisenberg
4f04f9db6e Merge pull request #1179 from github/aeisenberg/open-query-folder
Add new command to open the query history directory
2022-03-03 08:00:55 -08:00
Andrew Eisenberg
025a1a1383 Add new command to open the query history directory
Allows users to explore the contents and all artifacts of the query
that was just run.
2022-03-03 07:57:56 -08:00
Andrew Eisenberg
f28c1f91d9 Ensure structured logging file exists before running a query 2022-03-03 07:57:23 -08:00
Charis Kyriakou
c609377a9c Add SARIF processing and basic alert rendering (#1171) 2022-03-03 09:03:27 +00:00
Andrew Eisenberg
2579d12f24 Save log files to the query history directory
This commit deprecates the the cutsom log directory option by saving
all log files with query history.

There is a simplification of the `OutputChannelLogger` since it no
longer needs to manage deleting log files on exit.

Also, the `codeQL.runningQueries.customLogDirectory` is marked as
deprecated. If this value is being used, a warning message is popped
up after the query completes.
2022-03-02 12:21:15 -08:00
Andrew Eisenberg
c18f7953e7 Merge pull request #1111 from github/aeisenberg/graph-viewer
More work on the graph viewer
2022-03-02 07:52:49 -08:00
Andrew Eisenberg
3a292b02b6 Simplify walkDirectory
The check for `seenFiles` is not necessary since we do not need to
handle symbolic links.
2022-03-01 14:02:21 -08:00
Andrew Eisenberg
7baf2d0a2a Small formatting changes for graphes 2022-03-01 11:50:55 -08:00
Andrew Eisenberg
328289eb1c Ensure graph view loads when result is clicked
Without these changes, a race condition was sometimes hit when viewing
a graph. There are two, related issues that are fixed. These problems
did not appear in the past since rendering a normal results view is
much faster and the message handler is always already set up by the
time the interface first sends a message over to the web view.

1. `vscode.postMessage({ t: 'resultViewLoaded' });` was being called
   before the component is completely mounted. Ie- `componentDidMount`
   is not called. So, the interface is notified that the web view is
   ready to receive messages _before_ it is actually ready to receive
   messages.

   The change ensures the interface only sends messages when the web
   view is ready.

2. `this._panelLoaded` is never set to false if the panel is unloaded.
   This means that if a panel is re-opened, the interface assumes that
   the view is nearly _immediately_ ready to receive messages.

   The change ensures that the interface waits for the webview to really
   be loaded before sending messages.

In both of these cases, if the interface sends the `setState` message
too early, then the message is ignored since no handlers have been added
to the web view.
2022-03-01 11:46:26 -08:00
Andrew Eisenberg
95d93eeb61 Merge pull request #1176 from github/bump-cli
Bump CLI version in integration tests
2022-03-01 08:15:05 -08:00
Charis Kyriakou
b54cc27cab Update ECMAScript version to be the same across the codebase (#1177) 2022-03-01 16:01:29 +00:00
shati-patel
c9ca1ee7b3 Bump CLI version in integration tests 2022-03-01 12:14:30 +01:00
Charis Kyriakou
649d6d94a3 Expose Remote Query language (#1173) 2022-02-28 13:12:01 +00:00
Charis Kyriakou
bf68d21830 Some UI fixes for collapsible items (#1172) 2022-02-28 10:53:02 +00:00
Andrew Eisenberg
64b33b76cb Update node version in CI 2022-02-26 19:48:55 -08:00
Andrew Eisenberg
c189df3fd6 Ensure Graph results can only be seen if in canary mode 2022-02-25 18:04:21 -08:00
Andrew Eisenberg
277869ebca Ensure graph queries with ids that have slashes work
Do this by actually walking the interpretation directory.

Move the directory walker from tests to prod and make it async. Also
add tests for it.

And add a warning on graph views to let users know that it is not
production quality.

Finally, change the interpreted directory to be `graphResults` instead
of `interpretedResults.sarif`.
2022-02-25 18:03:14 -08:00
shati-patel
303513a566 Make icon part of clickable link
Plus fix the associated styling/CSS
2022-02-25 21:08:16 +00:00
shati-patel
8712106b3d Add link to workflow run logs from results view 2022-02-25 21:08:16 +00:00
Andrew Eisenberg
cdb9506583 Merge branch 'main' into aeisenberg/graph-viewer 2022-02-25 10:38:19 -08:00
Andrew Eisenberg
94a311a550 Merge pull request #1166 from github/aeisenberg/remote-queries-unit-tests
Add unit tests for query history and remote queries
2022-02-25 10:07:56 -08:00
Andrew Eisenberg
791e7e9c4d Small cleanups around remote-queries tests
- More explicit test helper module names
- Fix unit test names
- Better sanitization of repo names in tests
2022-02-25 09:57:15 -08:00
Angela P Wen
6cfa7e2cd3 Integrate evaluator structured logging per query server instance (#1151)
Adds structured evaluator logging on a per-query instance to CLI v 2.8.2+. The newline-delimited JSON logs are emitted to `structured-evaluator-log.json` in the directory with other query artifacts, but not consumed by the extension.

Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2022-02-25 09:22:56 -08:00
Andrew Eisenberg
7196c26181 Merge pull request #1168 from github/aeisenberg/query-history-version
Preemptively add a version number to the query history json file
2022-02-25 08:11:14 -08:00
Charis Kyriakou
735f177283 Use webview CSP source for style-src (#1170) 2022-02-25 16:03:58 +00:00
Andrew Eisenberg
f857e5ec6c Ensure all tests are run
Co-authored-by: Charis Kyriakou <charisk@users.noreply.github.com>
2022-02-25 08:00:03 -08:00
Charis Kyriakou
a5e02950c2 Fixed unique key warning (#1169) 2022-02-25 10:58:24 +00:00
Andrew Eisenberg
4a928f1298 Add unit tests for query history and remote queries
Adds some tests for reading in the history and manipulating.
There are some more tests to come later. Maybe in another PR, maybe in
this one.

Note that this PR uses a new node 16 API String.prototype.replaceAll.
I think this is ok since vscode ships with node 16. If this causes
problems, I can separate to a different PR and we can discuss there.
2022-02-24 23:09:55 -08:00
Andrew Eisenberg
f59012862e Preemptively add a version number to the query history json file
Since we are now storing query history on disk, we will need to handle
situations where versions change. For now, there is only version 1. In
the future, we may need to make breaking changes to this format and we
need the flexibility to detect and possibly handle different versions.

In this case, users don't often downgrade their vscode versions, so
most likely, we only need to be forward compatible. Ie- we need to
handle moving from v1 to v2, but not the other way around.
2022-02-24 11:42:46 -08:00
Andrew Eisenberg
5f5418a297 Merge pull request #1164 from github/aeisenberg/avoid-download
Avoid downloading a result if it already exists
2022-02-24 08:11:02 -08:00
Andrew Eisenberg
548a216b56 Avoid downloading a result if it already exists
This commit adds a check if a results artifact already exists before
trying to download it again.

This is not a complete solution since the page icon will still have a
download button even if the artifact already exists. In this case,
clicking on it will avoid downloading it a second time.

The next step is to read in the downloaded artifacts and display them
appropriately.
2022-02-23 11:16:39 -08:00
Andrew Eisenberg
c943c89fc6 Merge pull request #1163 from github/aeisenberg/remote-multi-analyses
Allow multiple analyses for same repo to be downloaded
2022-02-23 11:13:37 -08:00
Andrew Eisenberg
06de6077ba Merge pull request #1162 from github/aeisenberg/remote-query-restart
Remember remote queries across restarts
2022-02-23 11:13:17 -08:00
Andrew Eisenberg
cef1fcc95d Merge pull request #1155 from github/aeisenberg/remote-query-save
Add remote query items to history view
2022-02-23 11:13:00 -08:00
Andrew Eisenberg
1ed8b225db Small cleanup and comment 2022-02-23 09:52:46 -08:00
Andrew Eisenberg
f0354c87f4 Allow multiple analyses for same repo to be downloaded
Removes the limitation specified in #1089 where analyses for the same
repo and different queries will overwrite each other.
2022-02-22 14:16:54 -08:00
Andrew Eisenberg
5e06a615cd Remember remote queries across restarts
Remote query items will be stored in query history and will remain
available across restarts.

When the extension is restarted, any `InProgress` remote queries will
be monitored until they complete.

When clicked on, a remote query is opened and its results can be
downloaded. The query text and the query file can be opened from the
history menu. A remote query can be deleted as well, which will purge
all results from global storage.

Limitations:

1. Labels are not editable
2. Running multiple queries that each run on the same repository
   will have conflicting results and there will be errors when trying
   to view the results of the second query. This limitation is not new,
   but it is easier to hit now. See #1089.

Both of these limitations will be addressed in future PRs.
2022-02-22 11:42:52 -08:00
Andrew Eisenberg
e11aa7af18 Merge branch 'main' into aeisenberg/remote-query-save 2022-02-22 10:13:16 -08:00
Andrew Eisenberg
f4ddc17851 Merge pull request #1158 from github/aeisenberg/open-query-logger
Open query server logger for query errors
2022-02-22 09:55:19 -08:00
Andrew Eisenberg
ebce2826cb Merge pull request #1143 from github/aeisenberg/refactor-query-history-info
Refactor query history to handle remote and local
2022-02-22 09:51:13 -08:00
Andrew Eisenberg
4c411acef4 Merge branch 'main' into aeisenberg/open-query-logger 2022-02-22 09:44:41 -08:00
Andrew Eisenberg
ddc941f464 Merge pull request #1157 from github/aeisenerg/empty-additional-packs
Ensure `--addtional-packs` arg not used for empty workspace
2022-02-22 09:44:10 -08:00
shati-patel
c5ff2c6f76 Fix styling for light mode 2022-02-22 17:14:15 +00:00
shati-patel
85ac16bb22 Change shape of result index 2022-02-22 17:14:15 +00:00
shati-patel
e7ee4a33c7 Add new component for displaying analysis failures 2022-02-22 17:14:15 +00:00
shati-patel
ac0da04542 Read analysis failures from index file 2022-02-22 17:14:15 +00:00
shati-patel
3337117970 Use more accurate primer icon 2022-02-22 12:04:21 +00:00
Charis Kyriakou
9b61ff5714 Use Primer octicons where possible (#1156) 2022-02-21 11:28:13 +00:00
Andrew Eisenberg
d25db48452 Open query server logger for query errors
Because errors when running queries tend to have better explanations
in the query server log instead of the extension log, by default open
the query server log for query errors.
2022-02-18 12:55:32 -08:00
Andrew Eisenberg
251f354076 Ensure --addtional-packs arg not used for empty workspace 2022-02-18 10:16:42 -08:00
Andrew Eisenberg
9c6ae226fb Merge branch 'aeisenberg/refactor-query-history-info' into aeisenberg/remote-query-save 2022-02-17 14:11:44 -08:00
Andrew Eisenberg
a502ee85d1 Fix unit test and add comments/todos 2022-02-17 13:07:10 -08:00
Andrew Eisenberg
eec72e0cbd Merge pull request #1142 from github/aeisenberg/remote-queries-history
Store remote query artifacts in global storage
2022-02-17 12:35:09 -08:00
Andrew Eisenberg
7a1acce133 Merge pull request #1150 from github/aeisenberg/clear-cache
Fix race condition where packs with no name errored during remote query
2022-02-17 10:04:53 -08:00
Andrew Eisenberg
84b4bfe663 Merge pull request #1149 from github/aeisenberg/avoid-redownload
Avoid re-downloading analyses
2022-02-17 08:14:58 -08:00
Andrew Eisenberg
16df990183 Add remote query items to history view
This is another incremental step on the way to saving history.

This commit adds remote items to the history view. It adds in progress
and completed icons. Users can explicitly remove items.

Here is what is _not_ working:

1. Any other query history commands like open results or open query.
2. Seeing items after a restart.
2022-02-16 18:43:00 -08:00
Andrew Eisenberg
969dd26041 Use QueryHistoryInfo instead of LocalQueryInfo
Also, rename RemoteQueryInfo -> RemoteQueryHistoryItem
2022-02-16 13:52:17 -08:00
Andrew Eisenberg
9df1f91318 Fix race condition where packs with no name errored during remote query
Uses the internal `clear-cache` CLI server command.
2022-02-16 12:46:38 -08:00
Andrew Eisenberg
48ddc66d47 Merge branch 'aeisenberg/remote-queries-history' into aeisenberg/refactor-query-history-info 2022-02-16 12:34:43 -08:00
Andrew Eisenberg
85e3869607 Avoid re-downloading analyses
Avoids re-downloading analyses when downloading all analyses.
2022-02-16 12:01:21 -08:00
Andrew Eisenberg
5bb2a763e3 Avoid artifactStorageDir and use queryId to build storage paths
This is still an intermediate step as we start to bring in more
abstractions. I plan to implement a storage handler that will
keep track of all the different bits for a remote query.
2022-02-16 11:46:10 -08:00
Andrew Eisenberg
2110709d72 Merge pull request #1140 from github/aeisenberg/contextual-storage
Store query results for contextual queries elsewhere
2022-02-16 08:11:49 -08:00
shati-patel
493033edc0 Remove unused code about validating DB uploads 2022-02-16 14:25:43 +00:00
Andrew Eisenberg
bf8e77b9b9 Ensure proper paths are used for retrieving artifacts
This change builds on the previous change to ensure that sarif results
can be displayed properly. Here is what it does:

- Move prepareDownloadDirectory to the RemoteQueryManager
- Store the queryResult to disk
- Use the `artifactStorageDir` as the location where artifacts are kept
- Add `artifactStorageDir` to DownloadLink
- Ensure the webview passes around the right links.
2022-02-15 20:24:17 -08:00
Andrew Eisenberg
c7e5581027 Store query results for contextual queries elsewhere
We want them to be deleted when the application exits. We don't want
them to be stored with user queries.
2022-02-15 13:18:45 -08:00
Andrew Eisenberg
c78802a1ed Refactor query history to handle remote and local
This is a step on the way towards storing remote query history across
restarts.

This PR adds a `QueryHistoryInfo` type that is a union of two types:
`LocalQueryInfo` and `RemoteQueryInfo`.

`LocalQueryInfo` used to be called `FullQueryInfo` and `RemoteQueryInfo`
is only a skeleton right now. The body will be added later. This PR
only introduces it and changes types to make future PRs simpler.

Also, `slurp` and `splat` have been moved to the `query-serialization.ts`
module.
2022-02-15 13:07:47 -08:00
Andrew Eisenberg
39f9c082b9 Store remote query artifacts in global storage
This moves all artifacts downloaded for a remote query into the global
storage directory. Each remote query gets its own directory. The
parent directory is the shared query storage directory.

Each remote query directory also gets a timestamp file.

With these changes, remote queries will be persisted across restarts
and deleted automatically on the same schedule as local queries.

Note: This does _not_ add remote queries to the query history view yet.
This part of the feature is coming next.
2022-02-15 13:05:51 -08:00
shati-patel
ca1ef5192d Update wording in results view 2022-02-15 17:36:39 +00:00
Shati Patel
1d6fef9169 Update CLI version in integration tests 2022-02-15 15:50:51 +00:00
shati-patel
81f80ddbe5 Clear SARIF viewer before showing new results 2022-02-15 14:33:15 +00:00
Andrew Eisenberg
b53657344c General refactoring and adding comments
There is no new behaviour added in this commit. Just some cleanup:

- Move some shared constants to the `helpers` module
- Add comments to some of the query related modules
- Some general formatting and tidying
2022-02-14 11:39:19 -08:00
Andrew Eisenberg
95e818898e Merge pull request #1130 from github/aeisenberg/save-query-history
Save query history across restarts
2022-02-14 11:25:35 -08:00
Andrew Eisenberg
a7e014a87e Merge branch 'main' into aeisenberg/save-query-history 2022-02-14 11:15:22 -08:00
Andrew Eisenberg
cca65e5a48 Rename and add comment 2022-02-14 10:54:17 -08:00
Robin Neatherway
a75249f3e4 Merge pull request #1132 from github/rneatherway/remove-repositories
Remove .repositories configuration approach
2022-02-14 17:43:24 +00:00
Henry Mercer
053a4b0392 Remove feature flag for loading ML models from packs
This functionality should now be enabled for all users.
2022-02-14 10:36:00 +00:00
Andrew Eisenberg
d1362bf44f More work on the graph viewer
The viewer is largely implemented now with the following features and
limitations:

1. Any query with `@kind graph` will be opened as a graph
2. Queries that are `@kind graph` and
   `@tags ide-contextual-queries/print-cfg` will be used in the
   `CodeQL: View CFG` context command. This will be visible
   similar to how the AST viewer works. If there is not exactly
   1 such query for a given language, then the extension will throw
   an error.
3. Unfortunately, the cg viewer assumes that the entire file will
   be added to the graph, so often this will be too big, That leads to
   the following limitation:
4. There is no size checking on the graph. Graphs that are too big will
   crash vscode.
5. Lastly, there is a small bug in how the `@id` is interpreted. Any
   `@id` with a `/` in it will place the `.dot` in a location that
   can't be found by vscode. So, just don't name your queries with any
   `/`.

This feature is only available in canary mode.
2022-02-11 15:55:01 -08:00
Tom Hvitved
580832ea7b Graph viewer support 2022-02-11 14:47:13 -08:00
Tom Hvitved
ddca0bb851 Address review comments 2022-02-11 14:45:15 -08:00
Tom Hvitved
d9a04ea895 Refactor interpreted-data interface in preparation for other interpretations than SARIF 2022-02-11 14:45:15 -08:00
Andrew Eisenberg
48ccb27e49 Update changelog 2022-02-11 13:54:09 -08:00
Andrew Eisenberg
a2b5ad07ff Fix upgrades path
Ensure that upgrades can be resolved even when the upgrades pack is not
in the workspace. This is the situation when the core libraries are
resolved from the package cache.

This change works because `qlProgram.libraryPath` is the resolved
search path for compiling the query. We are guaranteed that the
appropriate core libraries are included in this query.

Note that this change avoids using extra source folders from the
workspace. Previously without using packages, we assume that all
relevant query paths are already inside the workspace. With
packaging, this is no longer the case.

It is theoretically possible that there will be extra upgrade scripts
that are not on the resolved search path, but are included in the
workspace. This situation would have worked in the past.This is not a
situation that we expect to happen in practice. And if this does happen,
I believe this is an error and all upgrades should be added explicitly
to the search path.

An open question is if this will work with downgrade scripts. If it does
not, then I don't think this change makes things any worse than before.
2022-02-11 12:58:34 -08:00
dependabot[bot]
cc9cbf7f06 Bump pathval from 1.1.0 to 1.1.1 in /extensions/ql-vscode
Bumps [pathval](https://github.com/chaijs/pathval) from 1.1.0 to 1.1.1.
- [Release notes](https://github.com/chaijs/pathval/releases)
- [Changelog](https://github.com/chaijs/pathval/blob/master/CHANGELOG.md)
- [Commits](https://github.com/chaijs/pathval/compare/v1.1.0...v1.1.1)

---
updated-dependencies:
- dependency-name: pathval
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-11 11:40:21 +00:00
Andrew Eisenberg
ad5c43c9ba Fix failing tests 2022-02-10 20:00:46 -08:00
Andrew Eisenberg
9c27d01d47 Merge branch 'main' into aeisenberg/save-query-history 2022-02-10 16:03:56 -08:00
Andrew Eisenberg
64ac33e3bb Address comments from PR
- Rename queryStorageLocation -> queryStorageDir
- Extract scrubber to its own module
- Add more comments
- Rename source -> cancellationSource
- Ensure cancellatinSource is disposed
2022-02-10 16:03:46 -08:00
aeisenberg
329fb87e12 Bump version to v1.5.12 2022-02-10 12:50:03 -08:00
Andrew Eisenberg
bd5da2b0f0 Release preparation for v1.5.11
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2022-02-10 12:26:24 -08:00
Henry Mercer
55c21888af Update Code Scanning workflow now that we no longer need tools: latest
The Actions VM image containing v2.7.6 of the CodeQL CLI has now fully
rolled out, so we no longer need to download the latest CodeQL bundle to
use this CLI and include this repo in the ML-powered queries beta.
2022-02-10 18:15:52 +00:00
Robin Neatherway
d49e6e19a6 Remove .repositories configuration approach
This was our first temporary attempt at configuration of a remote
query run. I don't think that we're using it anymore, so it simplifies
the code to remove it.
2022-02-10 12:47:48 +00:00
Charis Kyriakou
edb1af09c4 Hide analyses results until view is complete (#1126) 2022-02-10 08:13:59 +00:00
Charis Kyriakou
ab3822d1cc Use SARIF viewer extension for analysis results (#1125) 2022-02-10 08:13:31 +00:00
Andrew Eisenberg
69120e0799 Add extra delay in telemetry test
Some of our internal integration tests are failing occasionally. I
think extending the wait time here will fix.
2022-02-09 15:10:59 -08:00
Andrew Eisenberg
7785dfead2 Update changelog 2022-02-09 15:09:08 -08:00
Andrew Eisenberg
29c29f9e3a Save query history across restarts
Successfully completed queries will be stored on disk and available
across restarts.

- The query results are contained in global storage.
- Metadata and a summary about a query are stored in workspace storage.
- There is a job that runs every 2 hours to determine if any queries are
  old enough to be deleted.
2022-02-09 15:01:44 -08:00
Andrew Eisenberg
b7dafc31bb Better comments around splat and slurp functions
Also, address other small PR comments.
2022-02-08 12:43:38 -08:00
Andrew Eisenberg
2f5a306c2d Simplify the query history objects to make them serializable
The goal with this change is to simplify the query history to make it
possible to serialize and de serialize.

This change adds serialization support. Since query history objects are
complex, the de-serialization requires manipulation of the 
de serialized object prototypes.
2022-02-08 12:43:38 -08:00
Charis Kyriakou
0ef6b45b19 Remove use of all-results artifact (#1120) 2022-02-08 08:28:54 +00:00
dependabot[bot]
d9f33d34e3 Bump copy-props from 2.0.4 to 2.0.5 in /extensions/ql-vscode
Bumps [copy-props](https://github.com/gulpjs/copy-props) from 2.0.4 to 2.0.5.
- [Release notes](https://github.com/gulpjs/copy-props/releases)
- [Changelog](https://github.com/gulpjs/copy-props/blob/master/CHANGELOG.md)
- [Commits](https://github.com/gulpjs/copy-props/compare/2.0.4...2.0.5)

---
updated-dependencies:
- dependency-name: copy-props
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-07 15:39:23 -08:00
dependabot[bot]
5758e03a17 Bump nth-check from 2.0.0 to 2.0.1 in /extensions/ql-vscode
Bumps [nth-check](https://github.com/fb55/nth-check) from 2.0.0 to 2.0.1.
- [Release notes](https://github.com/fb55/nth-check/releases)
- [Commits](https://github.com/fb55/nth-check/compare/v2.0.0...v2.0.1)

---
updated-dependencies:
- dependency-name: nth-check
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-07 15:38:18 -08:00
Andrew Eisenberg
5d9f80cce8 Update ensureCli.ts 2022-02-07 13:30:15 -08:00
Andrew Eisenberg
867ee530b1 Update CLI test version 2022-02-07 13:30:15 -08:00
Charis Kyriakou
27e6a55756 Add full screen modal component (#1117) 2022-02-07 08:24:29 +00:00
Andrew Eisenberg
b237bafa2f Avoid AST Viewer for invalid selections
When a directory is selected or there are multiple selections, do not
show the command.
2022-02-04 11:54:11 -08:00
Andrew Eisenberg
d0bde800f7 Update changelog 2022-02-04 11:54:11 -08:00
Andrew Eisenberg
da0090aa99 Fix ast view and command registration
Two small bugs:

1. The AST view command was viewing the wrong ast when the command was
   selected from the context menu. It was always selecting the active
   editor instead of the item selected in the file menu.
2. The `codeql.showLogs` command was not being registered properly.
   With this change, there is uniform error handling, telemetry,
   and disposal.
2022-02-04 11:54:11 -08:00
Charis Kyriakou
66c9879ce3 Fix package versions for react typings (#1118) 2022-02-04 13:39:29 +00:00
Charis Kyriakou
9c2585116a Show collapsible analyses results (#1116) 2022-02-04 08:02:21 +00:00
Andrew Eisenberg
e46c0e25e8 Update CODEOWNERS
code-scanning security experiences team should be helping to review the remote queries part of the extension.
2022-02-03 08:14:25 -08:00
Charis Kyriakou
658b0ce243 Convert re-usable components to styled-components (#1112) 2022-02-03 08:34:24 +00:00
Andrew Eisenberg
c084e31416 Simplify command expressions
Use only `||` and clearly specify when each item should be visible.
2022-02-02 13:39:12 -08:00
Andrew Eisenberg
9046844f0c Add cancellation from query history view
And tweak the commands visible from the view.
2022-02-02 13:39:12 -08:00
Charis Kyriakou
5a9b49b9bb Show remote analyses results status (#1108) 2022-02-01 17:55:10 +00:00
Andrew Eisenberg
0672133bca Ensure query text shows for empty selections
Fixes a bug where quick eval was showing empty query text.

Previously, `getQueryText` was looking up the query text when it was
called if the specified text was empty. This was removed with the
recent changes to query history. It was also a bug since the query file
could have changed after the query was run.

This change ensures that if the quick eval position is empty, the
entire line is returned as the quick eval location.
2022-02-01 06:34:48 -08:00
Andrew Eisenberg
c0de99bc42 Add tests for sort order and selection 2022-02-01 06:34:48 -08:00
Andrew Eisenberg
6dbb1a27b9 Fix sort order and selection
This commit fixes two related issues with the
history view.

1. Sort order was changing after a query item completed. The fix is a
   change in how we fire off the `onDidChangeTreeData` event. When the
   event is fired with a single item, that item is pushed to the top of
   the list. I'm not exactly sure why this wasn't happening before, but
   I suspect it was because we were refreshing the list at the same time
   as we were inserting the new item.

   The solution here is to always refresh the entire list, instead of
   single items. This is fine since re building the list is a trivial
   operation. See the `refreshTreeView()` method.

   With this change, the sort order is now stable.

2. Originally reported here: #1093
   The problem is that the internal treeView selection was not being
   updated when a new item was being added. Due to some oddities with
   the way selection works in the tree view (ie- the visible selection
   does not always match the internal selection).

   The solution is to use the current item from the `treeDataProvider`
   in `determineSelection`.

Also, this change makes the sorting more precise and fixes some typos.
2022-02-01 06:34:48 -08:00
Andrew Eisenberg
dc1bace4c6 Ensure Open Query Text works for in progress queries
Same with "Open query that produced these results".

In order to do this, needed to move the query id generation into the
InitialQueryInfo.
2022-02-01 06:34:48 -08:00
Andrew Eisenberg
afe3c56ca8 Update changelog 2022-02-01 06:34:48 -08:00
Andrew Eisenberg
a6f42e3eb3 Add query items immediately
This is a large commit and includes all the changes to add query
history items immediately. This also includes some smaller related 
changes that were hit while cleaning this area up.

The major part of this change is a refactoring of what we store in
the query history list. Previously, the `CompletedQuery` was stored.
Previously, objects of this type include all information about a query that was run
including:

- Its source file and text range (if a quick eval)
- Its database
- Its label
- The query results itself
- Metrics about the query run
- Metadata about the query itself

Now, the item stored is called a `FullQueryInfo`, which has two
properties:

- InitialQueryInfo: all the data about the query that we know _before_
  the query completes, eg- its source file and text range, database, and
  label
- CompletedQueryInfo: all the data about the query that we can only
  learn _after_ the query completes. This is an optional property.

There is also a `failureReason` property, which is an optional string
describing why the query failed.


There is also a `FullCompletedQueryInfo` type, which only exists to 
help with stronger typing. It is a `FullQueryInfo` with a non-optional
`CompletedQueryInfo`.

Most of the changes are around changing how the query history accesses
its history list.

There are some other smaller changes included here:

- New icon for completed query (previously, completed queries had no
  icons).
- New spinning icon for in progress queries.
- Better error handling in the logger to handle log messages when the
  extension is shutting down. This mostly helps clean up the output
  during tests.
- Add more disposables to subscriptions to be disposed of when the
  extension shuts down.
2022-02-01 06:34:48 -08:00
Charis Kyriakou
9c2bd2a57b Use streaming SARIF parser (#1109) 2022-01-31 16:39:20 +00:00
Charis Kyriakou
f42f474113 Use 'engines' to define required node and npm versions (#1106) 2022-01-28 15:37:04 +00:00
Henry Mercer
17c31e1539 Run CodeQL analysis with latest CLI to opt into ML-powered queries beta 2022-01-28 14:14:00 +00:00
Charis Kyriakou
b0fb4d6bc9 Upgrade React version (#1103) 2022-01-28 10:37:59 +00:00
Charis Kyriakou
f8690bcebc Auto-download analyses results (#1098) 2022-01-27 10:16:13 +00:00
shati-patel
b0410ec5de Update to VS Code 1.59.0 2022-01-26 12:31:09 +00:00
shati-patel
19e0058e61 Bump version to v1.5.11 2022-01-25 16:41:03 +00:00
shati-patel
6d64c8f031 v1.5.10
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2022-01-25 16:19:57 +00:00
Charis Kyriakou
1216fce853 Download and process analyses results (#1089) 2022-01-25 08:28:53 +00:00
dependabot[bot]
c598306f49 Bump node-fetch from 2.6.1 to 2.6.7 in /extensions/ql-vscode
Bumps [node-fetch](https://github.com/node-fetch/node-fetch) from 2.6.1 to 2.6.7.
- [Release notes](https://github.com/node-fetch/node-fetch/releases)
- [Changelog](https://github.com/node-fetch/node-fetch/blob/main/docs/CHANGELOG.md)
- [Commits](https://github.com/node-fetch/node-fetch/compare/v2.6.1...v2.6.7)

---
updated-dependencies:
- dependency-name: node-fetch
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-24 13:56:26 -08:00
Shati Patel
4f8d6e310c Bump CLI version for integration tests 2022-01-24 11:56:10 +00:00
Shati Patel
894eb7046e Make step for maintainers only 2022-01-20 09:32:07 +00:00
shati-patel
3d6515e807 Update documentation step in PR template 2022-01-20 09:32:07 +00:00
shati-patel
068d461c14 Update progress bar for "install pack dependencies" 2022-01-20 09:15:35 +00:00
shati-patel
8e20d01b4e Sleep earlier 2022-01-19 20:46:33 +00:00
shati-patel
8aaa2492f2 Wait a few seconds before monitoring remote query run 2022-01-19 20:46:33 +00:00
Shati Patel
c9a649f974 Update extensions/ql-vscode/CHANGELOG.md
Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>
2022-01-19 20:43:25 +00:00
shati-patel
f07d9cff9b Update wording to be more clear 2022-01-19 20:43:25 +00:00
shati-patel
b7bfd9ea85 Add CLI version constraint for packaging 2022-01-19 20:43:25 +00:00
shati-patel
25f0e3ccab Add separate tests for valid/invalid pack install 2022-01-19 20:43:25 +00:00
shati-patel
e19addec60 Catch error in tests 2022-01-19 20:43:25 +00:00
shati-patel
a5bc25e211 Fix import + throw error 2022-01-19 20:43:25 +00:00
shati-patel
c90659fd92 First attempt at tests 2022-01-19 20:43:25 +00:00
shati-patel
30b7fe7472 Update changelog 2022-01-19 20:43:25 +00:00
shati-patel
d54fbdf4e6 Address review comments
1. Hard-code more common query packs
2. Correctly resolve workspace packs
3. Only install workspace packs
2022-01-19 20:43:25 +00:00
shati-patel
6d7b02583d Add "pack install" and "pack download" commands 2022-01-19 20:43:25 +00:00
shati-patel
51906cbbda Update dependencies in integration test runner 2022-01-19 16:16:53 +00:00
Shati Patel
d3da9d30f4 Make sure extension dependencies are installed 2022-01-19 16:16:53 +00:00
Charis Kyriakou
9b9a0cb64a Split download actions in remote queries view (#1083) 2022-01-19 09:41:04 +00:00
Andrew Eisenberg
1dde5af591 Bump CLI version to run integration tests against 2022-01-18 08:41:00 -08:00
Charis Kyriakou
4312d35743 Added paging to the listWorkflowRunArtifacts call (#1082) 2022-01-18 16:24:25 +00:00
Charis Kyriakou
2dcdbcbd32 Break remote queries view into more components (#1079) 2022-01-18 15:46:45 +00:00
Charis Kyriakou
e8e50c4381 Extract base react components (#1078) 2022-01-17 19:41:33 +00:00
Charis Kyriakou
0e6d85374f Rename analysis result to analysis summary (#1074) 2022-01-10 11:57:02 +00:00
Angela P Wen
54789613dc Merge pull request #1071 from angelapwen/standardize-integration-args
Standardize integration test args in VSCode debugger
2022-01-07 12:00:20 -08:00
Angela P Wen
43b3f72a41 Clarify instructions in comment 2022-01-07 11:51:44 -08:00
Angela P Wen
13742a4e9e Match integration test args with run-integration-tests.ts 2022-01-07 11:25:48 -08:00
Charis Kyriakou
6bd7f0ae12 Add helper command for working on the Remote Queries Results view (#1069) 2022-01-07 13:39:07 +00:00
shati-patel
fc51b336fa Update changelog 2022-01-06 19:34:29 +00:00
shati-patel
df16d1ab1d Results view: Don't reopen webview if it's already visible 2022-01-06 19:34:29 +00:00
Dominik Bamberger
b661b2be97 Update Docs ping in issue template (#1061)
* Update Docs ping in issue template

* Update .github/pull_request_template.md

Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>

Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>
2021-12-22 08:59:25 -08:00
Andrew Eisenberg
2d39bee416 Ensure all tests are run 2021-12-17 13:22:20 -08:00
Andrew Eisenberg
56eeb1badb Delete output folder before building 2021-12-17 13:09:02 -08:00
shati-patel
d547f81a55 Bump version to v1.5.10 2021-12-17 15:36:16 +00:00
Charis Kyriakou
e1b35cdbbc Fix CSS file paths
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-12-17 15:14:08 +00:00
shati-patel
c01704b8aa v1.5.9 2021-12-17 12:04:27 +00:00
shati-patel
5a19042fc8 Update changelog 2021-12-16 17:58:55 +00:00
shati-patel
bdf8c0b9c2 Add setting to enable/disable Quick Eval codelens 2021-12-16 17:58:55 +00:00
Shati Patel
bc08cbe74f Tidy up and add test for getting query metadata (#1050)
* Move/rename query metadata function

* Add test for `tryGetQueryMetadata`

* Split into two tests
2021-12-15 20:11:59 +00:00
Andrew Eisenberg
6e2e72a500 Be nicer about where to open the results webview (#1037)
* Be nicer about where to open the results webview

Currently, the webview _always_ opens next to the currently active
editor. This is a pain if you already have 2 columns open since this
means that the webview will open in a third column, which is rarely
what you want.

This change uses a more sophisticated approach to opening the webview:

1. If there is only one column, open webview to the right of it
2. If there are multiple columns and the active editor is _not_ the
   last column, open to the right of the active editor
3. Otherwise open in the first column.

This will avoid opening a new column unless there is only one column
open right now.

There is no native API that vscode exposed to compare column locations,
so this uses the `ViewColumn` api is a slightly non-standard way.

A limitation is that if the last column is empty and the active editor
is to the left of it, then the webview will not be opened there (which
would be nice). Instead, it will be opened in column 1.

Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2021-12-15 19:33:53 +00:00
shati-patel
d0953fb63c Remote queries: Get query name from metadata (if possible) 2021-12-15 11:00:41 +00:00
Charis Kyriakou
4dbd15c66d Remote queries: No results view (#1048) 2021-12-15 08:55:00 +00:00
Charis Kyriakou
e9e41e07d1 Implement download behaviour in remote queries view (#1046) 2021-12-15 08:34:34 +00:00
Andrew Eisenberg
b435df4682 Fix type in comment
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2021-12-14 09:39:43 -08:00
Andrew Eisenberg
a3bf9f1c71 Handle different dependencies in remote queries tests
Starting in CLI 2.7.5, there will no longer be any
`codeql/javascript-upgrades` pack. Change the test so that it passes
using both old and new packs.
2021-12-14 09:39:43 -08:00
shati-patel
72ff828b57 Style link text + tidy up functions 2021-12-14 12:13:20 +00:00
shati-patel
b7f86ae7a9 Display query text in "virtual" (readonly) file 2021-12-14 12:13:20 +00:00
shati-patel
3c73390a44 Save query text in a temporary file 2021-12-14 12:13:20 +00:00
shati-patel
7117faa92b Rename properties and handle missing files 2021-12-14 12:13:20 +00:00
shati-patel
4257555c88 Remote queries: Open query file/text from webview 2021-12-14 12:13:20 +00:00
Angela P Wen
33b1465ccc Docs: add clarification on directory for running tests via CLI 2021-12-10 12:29:15 -08:00
Andrew Eisenberg
c8ed8b2591 Add code lens for quick evaluation (#1035)
* Add code lens for quick eval command

* Ensure commented out predicates do not have code lens

* Improve conditional check for commented out predicate  detection

* Refactor regex

* Move comment check to eliminate evaluating regex more than once

Co-authored-by: marcnjaramillo <mnj.webdeveloper@gmail.com>
2021-12-10 19:17:21 +00:00
Andrew Eisenberg
58f4a82616 Update changelog 2021-12-10 07:50:08 -08:00
Andrew Eisenberg
d5f0a659af Avoid showing the alert option in the drop down
Only show it when there really is an alert table to see.
2021-12-10 07:50:08 -08:00
Charis Kyriakou
60c977bff9 Move GitHub actions code to separate module (#1044) 2021-12-10 13:59:20 +00:00
Andrew Eisenberg
73f1beac6a Bump cli version for integration tests 2021-12-09 13:50:41 -08:00
Charis Kyriakou
6195c6552f Made the repo list in the remote query view expandable (#1039) 2021-12-09 10:38:18 +00:00
Charis Kyriakou
e365744dbc Monitor remote query run and render results (#1033) 2021-12-09 10:05:51 +00:00
Andrew Eisenberg
68f566dd1a Pass --old-eval-stats to query server
This is in preparation of supporting structured query logs.
When passing this option, use the old format of query logs.
Later, when we want to add support for structured query
logs, we can add remove this option.
2021-12-07 07:53:58 -08:00
Charis Kyriakou
bf350779c9 Merge pull request #1032 from github/remote-query-submission-result
Expose remote query submission result
2021-12-06 09:28:14 +00:00
Charis Kyriakou
07329c9ea5 Expose remote query submission result 2021-12-03 16:16:48 +00:00
Shati Patel
7e6483490a Merge remote queries webview outline into main (#1027) 2021-12-03 10:48:54 +00:00
shati-patel
749565828d Bump version to v1.5.9 2021-12-02 14:27:37 +00:00
shati-patel
ff751cc877 v1.5.8
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-12-02 11:26:36 +00:00
Robin Neatherway
d7ba941803 Merge pull request #1009 from github/aeisenberg/remote-nested-queries
Remote queries: Handle nested queries
2021-12-01 19:24:10 +00:00
Andrew Eisenberg
e58201e24b Ensure server uses a well-known query pack name 2021-12-01 10:53:51 -08:00
Henry Mercer
81e60286f2 Require canary for loading models from packs 2021-12-01 09:40:06 +00:00
Henry Mercer
8e156d69d7 Apply suggestions from code review
Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2021-12-01 09:40:06 +00:00
Henry Mercer
dfcaa27235 Update lockfile 2021-12-01 09:40:06 +00:00
Henry Mercer
ed0553c6b6 Gate loading ML models behind a hidden setting 2021-12-01 09:40:06 +00:00
Henry Mercer
84ecbfc7a1 Resolve ML models and pass them to the queryserver 2021-12-01 09:40:06 +00:00
Andrew Eisenberg
e13349ceb0 Update changelog 2021-11-29 11:16:49 -08:00
Andrew Eisenberg
a1bcb7519f Ensure src.zip is prioritized over src folder
Fixes a bug where legacy databases with both unzipped and zipped sources
were incorrectly being loaded with the src folder.
2021-11-29 11:16:49 -08:00
Andrew Eisenberg
b481441052 Emit more relevant error message when failing to add source folder (#1021)
* Emit more relevant error message when failing to add source folder

Fixes #1020

* Update changelog

* Clarify changelog and error message

Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>

Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2021-11-29 16:28:07 +00:00
github-actions[bot]
6a1d1a492e Bump version to v1.5.8 (#1017)
Co-authored-by: aeisenberg <aeisenberg@users.noreply.github.com>
2021-11-23 21:13:41 +00:00
Andrew Eisenberg
1dcd9c495c Prepare for the 1.5.7 release (#1016)
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-11-23 12:52:40 -08:00
Andrew Eisenberg
a9b9502dbd Fix failing tests on windows
1. Acknowledge that the CLI has a bug for path serialization on <=2.7.2.
   Avoid testing the query path on that version.
2. Fix calculation of root path on windows.
2021-11-22 12:53:52 -08:00
Andrew Eisenberg
16c0bea799 Merge pull request #1004 from marcnjaramillo/fix-large-sarif-handling
Fix large sarif handling
2021-11-22 12:24:17 -08:00
marcnjaramillo
ad81127267 Move test files into data directory 2021-11-22 11:49:40 -08:00
Andrew Eisenberg
30d01cb0e0 Merge pull request #1007 from github/aeisenberg/sorted-result-sets
Ensure all result set names are loaded
2021-11-22 09:08:55 -08:00
Shati Patel
2584971a07 Update CLI version in tests 2021-11-22 14:02:09 +00:00
marcnjaramillo
9d9f48bcf8 Fix tests for sarif parser 2021-11-19 20:43:22 -08:00
marcnjaramillo
0bb1501e72 Move sarif parser and tests, build completing 2021-11-19 17:21:42 -08:00
marcnjaramillo
d53abd815d Make suggested changes, build currently failing 2021-11-19 16:01:18 -08:00
Andrew Eisenberg
d9c5ecf462 Fix failing test and remove changelog note 2021-11-19 14:32:38 -08:00
Shati Patel
51ed2cd480 Delete outdated issue template
I don't think we need this issue template any more... The release process is in https://github.com/github/vscode-codeql/blob/main/CONTRIBUTING.md#releasing-write-access-required.
2021-11-19 17:47:23 +00:00
Andrew Eisenberg
4c83805030 Update changelog 2021-11-18 18:13:29 -08:00
marcnjaramillo
c3eca5b1b7 Update test for valid SARIF file 2021-11-18 16:05:31 -08:00
Andrew Eisenberg
742bca1cf5 Remote queries: Handle nested queries
This change allows remote queries to run a query from a directory that
is not in the root of the qlpack.

The change is the following:

1. walk up the directory hierarchy to check for a non-local qlpack.yml
2. Copy over the files as before, but keep track of the relative
   location of the query compared to the location of the qlpack.yml.
3. Change the defaultSuite of the qlpack.yml so that _only_ this query
   is run as part of the default query.

Also, this adds a new integration test to ensure the nested query is
packaged appropriately.
2021-11-18 15:27:29 -08:00
Andrew Eisenberg
5ab55bb5a5 Merge branch 'main' into aeisenberg/sorted-result-sets 2021-11-18 10:49:44 -08:00
Musab Guma'a
3743895b66 Add "Preview Query Help" command 2021-11-18 16:10:26 +00:00
marcnjaramillo
ca5e5e23e6 Finish tests 2021-11-17 16:37:56 -08:00
marcnjaramillo
a666619289 Remove error handling for now 2021-11-17 16:37:56 -08:00
marcnjaramillo
63129236d0 Work on tests for new behavior 2021-11-17 16:37:56 -08:00
marcnjaramillo
4374f409a8 Add changelog entry and add missing dependencies 2021-11-17 16:37:37 -08:00
marcnjaramillo
c49aa8e05e Fix issue with large SARIF files crashing view
Authored by: Marc Jaramillo marcnjaramillo@github.com
Authored by: Musab Guma'a mgsium@github.com
2021-11-17 16:33:49 -08:00
Andrew Eisenberg
c590e2f36c Update package lock (#1003)
* Add leniency in how positions are handled

Previously, positions with end column of 0 were rejected by the
extension. CodeQL positions are supposed to be 1-based, but the CLI
does handle 0-based and negative positions by using character offsets
from the current line start.

Instead of rejecting these kinds of positions, the extension should
handle them as gracefully as possible.

Fixes #999

* Update package lock
2021-11-17 16:24:59 -08:00
Andrew Eisenberg
03d4aca639 Add leniency in how positions are handled (#1002)
* Add leniency in how positions are handled

Previously, positions with end column of 0 were rejected by the
extension. CodeQL positions are supposed to be 1-based, but the CLI
does handle 0-based and negative positions by using character offsets
from the current line start.

Instead of rejecting these kinds of positions, the extension should
handle them as gracefully as possible.

Fixes #999

* Add changelog entry
2021-11-17 16:24:48 -08:00
Andrew Eisenberg
01f24523ac Update changelog 2021-11-17 09:39:49 -08:00
Andrew Eisenberg
98312a72a7 Ensure all result set names are loaded
When the extension loads a sorted result set, it takes a shortcut and
avoids loads a file with only the bqrs results for that sorted table.

However, it does not load the results for any other table. This causes
result set names to go away. This change ensures that if we are loading
a sorted table, we also load the result set names for all other tables
in that query.

Fixes #1005.
2021-11-17 09:37:42 -08:00
Shati Patel
d579cd6541 Update CLI version
Version 2.7.1 was released this week
2021-11-17 13:30:34 +00:00
shati-patel
38e5d8babc Attempt to fix tests 2021-11-12 16:03:17 +00:00
shati-patel
c1fceab8d9 Re-use dbSchemeToLanguage 2021-11-12 16:03:17 +00:00
shati-patel
ae555969b5 Tidy up language dropdown 2021-11-12 16:03:17 +00:00
Andrew Eisenberg
3e0ea1ba77 Merge pull request #997 from github/aeisenberg/cli-version-test
Avoid testing for the correct CLI_VERSION if CLI_PATH is set
2021-11-08 09:37:18 -08:00
Andrew Eisenberg
ce1ebd2218 Avoid testing for the correct CLI_VERSION if CLI_PATH is set 2021-11-08 09:26:25 -08:00
Andrew Eisenberg
6215c2763e Merge pull request #996 from rneatherway/rneatherway/use-workflow-run-id
Start linking to the exact workflow run
2021-11-08 08:20:58 -08:00
Robin Neatherway
07437000ce Start linking to the exact workflow run
Now that the queries endpoint returns the id we can link straight
there. We'll make more changes to the progress tracking, but I think
it's worth making this minimal change now.
2021-11-08 15:19:29 +00:00
Andrew Eisenberg
0ef635bc68 Use the correct environment variable in integration tests (#994)
Also, fix documentation and launch configs to specify the correct and
complete set of environment variables we should be using.
2021-11-03 23:04:14 +00:00
Andrew Eisenberg
e9574d33a9 Merge pull request #985 from github/qc-packs
Remote Queries: Create packs for remote queries
2021-11-03 08:49:08 -07:00
Musab Guma'a
848869e3f4 Make "Open Referenced File" command functional on open .qlref 2021-11-02 11:19:39 +00:00
Andrew Eisenberg
4a65b6a8b2 Ensure anonymous and scope-less packs can be used as remote queries
When we generate the synthetic pack, just ensure that there is a valid name.
2021-11-01 15:18:23 -07:00
Andrew Eisenberg
28c76bece0 Change to 0.0.0 as synthetic version 2021-11-01 14:45:55 -07:00
shati-patel
56faf36edf Fix Windows path issue 2021-10-29 17:56:23 +01:00
Andrew Eisenberg
440044d2aa Add more debugging logic
Help understand why tests are failing.
2021-10-29 09:18:34 -07:00
Andrew Eisenberg
48468ff354 Allow custom setting of codeql cli for integration tessts 2021-10-29 08:29:45 -07:00
shati-patel
31dc11ed73 Fix recommended extensions 2021-10-29 14:53:45 +01:00
Andrew Eisenberg
903f5db707 Avoid running remote queries on v2.6.3 cli or earlier
Also:

- Fix the count of copied files
- A few typos
- Ensure the correct settings are applied for remote queries before
  running tests.
2021-10-28 16:08:43 -07:00
shati-patel
8317f39459 Update CLI version in ensureCli.ts 2021-10-28 15:25:22 +01:00
Andrew Eisenberg
42051f1620 Remote Queries: Create packs for remote queries
This is still a bit rough, but handles two cases:

1. There is a qlpack.yml or codeql-pack.yml file in the same directory
   as the query to run remotely. In this case, run `codeql pack
   packlist` to determine what files to include (and also always include
   the lock file and the query itself. Copy to a temp folder and run
   `pack install`, then `pack bundle`. Finally upload.
2. There is no qlpack in the current directory. Just copy the single
   file to the temp folder and generate a synthetic qlpack before
   installing, bundling and uploading.

Two cases that are not handled:

1. The query file is part of a workspace. Peer dependencies will not be
   found.
2. The query file and its qlpack file are not in the same directory.

These should be possible to handle later.  Also, need to create some
unit and integration tests for this.
2021-10-27 21:09:34 -07:00
Andrew Eisenberg
9b90579160 Merge pull request #984 from github/aeisenberg/add270
Add v2.7.0 CLI run tests against
2021-10-27 15:30:23 -07:00
Andrew Eisenberg
541367122e Add v2.7.0 CLI run tests against 2021-10-27 15:23:06 -07:00
Andrew Eisenberg
0a0500a60d Merge pull request #979 from mgsium/windows-paths
Fix the "CodeQL: Open Referenced File" command for windows paths
2021-10-27 09:00:23 -07:00
Musab Guma'a
746086b761 Fix "Open Referenced File" command for windows paths 2021-10-27 16:54:21 +01:00
Andrew Eisenberg
412d96409e Merge pull request #982 from github/aeisenberg/debug-cli-server
Add support for debugging the CLI server
2021-10-26 09:59:35 -07:00
Andrew Eisenberg
93e15b43a3 Remove hunks
Accidentally included from a different PR.
2021-10-26 09:42:32 -07:00
Andrew Eisenberg
dbc8198daa Add support for debugging the CLI server 2021-10-24 16:39:08 -07:00
Andrew Eisenberg
b3a51d7afd Merge pull request #978 from mgsium/case-insensitive-slugs
Case insensitive fallback check for GitHub repositories
2021-10-20 13:50:48 -07:00
Musab Guma'a
3d24328402 Update CHANGELOG.md 2021-10-20 20:46:22 +01:00
Musab Guma'a
1014c4bdda Added case-insensitive fallback check for GitHub repos when downloading an LGTM project. 2021-10-20 19:35:41 +01:00
shati-patel
b2a6263431 Send a query pack 2021-10-20 15:06:33 +01:00
Andrew Eisenberg
20cdca77a3 Merge pull request #977 from marcnjaramillo/fix-changelog-entries
Update CHANGELOG.md entries for most recent changes
2021-10-19 11:25:46 -07:00
marcnjaramillo
98d48a3709 Update CHANGELOG.md entries for most recent changes 2021-10-19 11:14:19 -07:00
Andrew Eisenberg
6b57993b2a Merge pull request #976 from marcnjaramillo/selected-database-view
Fix issue where 'Set current database' shows on selected database in …
2021-10-19 11:04:22 -07:00
marcnjaramillo
34ac30e403 Fix issue where 'Set current database' shows on selected database in the database view 2021-10-19 10:52:06 -07:00
Andrew Eisenberg
b8618aa87e Merge pull request #971 from marcnjaramillo/integrate-codeql-database-unbundle
Integrate codeql database unbundle
2021-10-19 10:01:40 -07:00
marcnjaramillo
7d8e63c1d1 Make changes requested by @aeisenberg
Co-authored by: Marc Jaramillo mnj.webdeveloper@gmail.com
Co-authored by: Musab Guma'a mgsium@github.com
2021-10-18 18:38:25 -07:00
marcnjaramillo
b22a8692c8 Integrated CLI database unbundle command for archive download
Co-authored by: Marc Jaramillo mnj.webdeveloper@gmail.comm
Co-authored by: Musab Guma'a mgsium@github.com
2021-10-18 14:55:17 -07:00
Marc Jaramillo
b5cdd833e2 Merge branch 'github:main' into main 2021-10-14 10:41:05 -07:00
Andrew Eisenberg
81a2f9c428 Merge pull request #963 from marcnjaramillo/handle-nonprint-chars
Handle nonprint chars
2021-10-08 14:35:24 -07:00
Marc Jaramillo
b43b824da6 Simplify changelog entry
Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2021-10-08 13:52:07 -07:00
marcnjaramillo
22616c5582 Add changes to changelog 2021-10-08 13:05:48 -07:00
Marc Jaramillo
2570d179bc Merge branch 'github:main' into handle-nonprint-chars 2021-10-08 13:00:10 -07:00
Marc Jaramillo
1980f862c6 Merge branch 'github:main' into main 2021-10-08 12:57:36 -07:00
marcnjaramillo
d1eb31e231 Finish creating check for non-printing characters 2021-10-08 12:56:56 -07:00
shati-patel
68863e3b90 Bump version to v1.5.7 2021-10-07 18:47:29 +01:00
shati-patel
b38b884715 Add 1.5.6 header
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-10-07 18:31:36 +01:00
shati-patel
cc6f2d8886 Prepare release 2021-10-07 18:31:36 +01:00
marcnjaramillo
245db7ca28 Add a check for strings with only new line chars 2021-10-07 09:09:48 -07:00
Andrew Eisenberg
197ab99db8 Merge pull request #959 from alexet/fix-db-remove
Delete database after removing it from query server control.
2021-10-07 08:50:22 -07:00
Andrew Eisenberg
6292adf491 Merge branch 'main' into fix-db-remove 2021-10-07 08:17:24 -07:00
Andrew Eisenberg
112d40ff1c Update CHANGELOG.md 2021-10-07 08:15:35 -07:00
Andrew Eisenberg
b92d6bab7c Merge pull request #965 from github/aeisenberg/logo-update
Update CodeQL logo
2021-10-07 08:08:51 -07:00
Andrew Eisenberg
0a4879c9a8 Merge branch 'main' into aeisenberg/logo-update 2021-10-07 08:01:05 -07:00
shati-patel
7d4d57104a Update integration test version 2021-10-07 10:13:53 +01:00
Andrew Eisenberg
f06c9abb35 Update integration test versions 2021-10-07 10:13:53 +01:00
marcnjaramillo
2f7d175a76 Make edits per feedback 2021-10-06 14:01:39 -07:00
Andrew Eisenberg
85eaa8b275 Update CodeQL logo
Both the marketplace icon and the sideview svg
2021-10-06 11:12:53 -07:00
marcnjaramillo
4783ad6bff Create rough solution for handling non-printing characters in results 2021-10-05 19:37:14 -07:00
Marc Jaramillo
9f0a975a0c Merge pull request #1 from github/main
Add progress messages to LGTM download option. (#960)
2021-10-05 19:22:49 -07:00
Marc Jaramillo
21dda65871 Add progress messages to LGTM download option. (#960)
* Add progress messages to LGTM download option.

* Add additional argument to get test passing again.

* Make edits requested by @aeisenerg

* Fix assertion in test case

* Update extensions/ql-vscode/CHANGELOG.md
2021-10-04 17:22:11 +01:00
Andrew Eisenberg
39fdd0cad5 Merge pull request #957 from marcnjaramillo/fix-lgtm-download-message
Remove line about selecting a language from the dropdown.
2021-10-01 12:07:46 -07:00
Marc Jaramillo
3fb2c71390 Merge branch 'main' into fix-lgtm-download-message 2021-10-01 11:19:57 -07:00
marcnjaramillo
b40f648a87 Remove line about selecting a language from the dropdown. 2021-10-01 11:07:37 -07:00
alexet
57216249c2 Delete database after removing it from query server control. 2021-10-01 18:40:07 +01:00
shati-patel
fbadc15ae9 Also prompt user if the repo in the config is invalid 2021-10-01 18:11:53 +01:00
shati-patel
89b00eaef8 Show input box if there's no controller repo defined in settings 2021-10-01 18:11:53 +01:00
shati-patel
4bc5086cfb Update test 2021-10-01 18:11:53 +01:00
shati-patel
7a79d39e23 Add new setting to specify controller repo 2021-10-01 18:11:53 +01:00
shati-patel
41ae5a4b5f Create new "remoteQueries" setting 2021-10-01 18:11:53 +01:00
Musab Guma'a
0493e316c0 Update extensions/ql-vscode/CHANGELOG.md
Co-authored-by: Edoardo Pirovano <6748066+edoardopirovano@users.noreply.github.com>
2021-10-01 17:37:54 +01:00
Musab Guma'a
137e17c2e1 Add fix entry to CHANGELOG.md 2021-10-01 17:37:54 +01:00
Musab Guma'a
31db2ffb82 Fix version copy for missing cli 2021-10-01 17:37:54 +01:00
Aditya Sharad
df18ff3052 Update CLI tests to use 2.6.2 (#955)
* Actions: Update tests to use CLI 2.6.2

* Integration tests: Update to CLI 2.6.2
2021-09-21 22:44:01 +00:00
Benjamin Muskalla
74555510b4 Fix formatting for history format preference
There was a space missing for one of the items, making it not rendered as part of the list
2021-09-16 07:53:23 -07:00
shati-patel
a2b8e7d193 Rename function 2021-09-15 10:52:47 +01:00
shati-patel
b59638bd2e Test the regex for "getRepositories" 2021-09-15 10:52:47 +01:00
shati-patel
b0e19926da Tests for "validateRepositories" 2021-09-15 10:52:47 +01:00
shati-patel
2e1b83588c Put error handling into separate "validateRepositories" function 2021-09-15 10:52:47 +01:00
shati-patel
ab441ef75c Tests for "getRepositories" 2021-09-15 10:52:47 +01:00
shati-patel
b4478e9b54 Remove token for running a remote query 2021-09-09 14:06:29 +01:00
aeisenberg
a715ce13c9 Bump version to v1.5.6 2021-09-08 16:15:15 -07:00
Andrew Eisenberg
005372abba v1.5.5
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-09-08 15:49:18 -07:00
Andrew Eisenberg
3f22587a7c Update changelog 2021-09-08 17:02:49 -04:00
Andrew Eisenberg
b95533e8c0 Remove support for 2.2.6 CLI
This is old enough that we don't need to support it.
2021-09-08 17:02:49 -04:00
Andrew Eisenberg
210d8a3c64 Expand qlpack resolution integration test to all languages
Go is not yet supported since we do not include the go submodule in the
integration tests.
2021-09-08 17:02:49 -04:00
Andrew Eisenberg
c2d3829a72 Fix AST Viewer
The previous synthetic query suite was not finding the ast query because
the `qlpack` directive in a query suite only matches queries from the
default suite, which `printAST.ql` is not part of.

This changes to using `from` and `queries` directives.

Also, adds an integration test to ensure we find the queries using
different CLIs. However, this only tests using the latest `main` from
the codeql repository. I wonder if we should start testing using
different versions of the repo.
2021-09-08 17:02:49 -04:00
Robert
cd427ee119 fix strings again 2021-09-08 18:21:41 +01:00
Robert
ad4c30ecf8 Include clickable link to show logs in message 2021-09-08 18:21:41 +01:00
Robert
db7f5f5114 Add spaces to printed array 2021-09-08 18:21:41 +01:00
Robert
7c9fa03da8 update messages 2021-09-08 18:21:41 +01:00
Robert
615dd691bf offer option to rerun on subset of valid repositories 2021-09-08 18:21:41 +01:00
shati-patel
64ba2cabad Attempt to fix quick query test 2021-09-08 13:02:57 +01:00
shati-patel
a9dcb2d705 Attempt to fix qlpack test 2021-09-08 13:02:57 +01:00
Shati Patel
4c81cdec98 Update CLI version for integration tests 2021-09-08 13:02:57 +01:00
Harry Maclean
db529d5247 Update changelog 2021-09-07 15:58:33 +01:00
Harry Maclean
4f568ea331 Wait for document to be saved before running query
This prevents a race condition where the query runs before the editor has saved the file.
2021-09-07 15:58:33 +01:00
Shati Patel
6d41362251 Configure correct TypeScript version to use in VS Code 2021-09-07 09:38:16 +01:00
Andrew Eisenberg
7f65a54060 Fix dependabot warning 2021-09-03 09:53:59 +01:00
aeisenberg
0c6ca81437 Bump version to v1.5.5 2021-09-02 12:40:04 -07:00
Andrew Eisenberg
b2422216b5 Update changelog for v2.5.4 release
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-09-02 11:51:35 -07:00
Andrew Eisenberg
71f374d797 Fix unit test and add new test
Test that old CLIs properly ignore the library packs.
2021-09-02 11:14:32 -07:00
Dave Bartolomeo
7e78a6bc5c Fix PR feedback 2021-09-02 11:14:32 -07:00
Dave Bartolomeo
a4532fdc61 Add changenote for AST viewer failure fix 2021-09-02 11:14:32 -07:00
Dave Bartolomeo
7c5135d7d0 Fix AST viewer for refactored language packs
Most of the languages have recently been refactored into separate library and query packs, with the contextual queries defined in the query pack. In the near future, these contextual queries will move to the library pack.

Current CLI releases throw an error in `codeql resolve queries` when the extension tries to search the library pack for contextual queries. This change makes two related fixes:

1. If the queries are not found in the library pack, it then scans the corresponding standard query pack as a fallback.
2. It detects the problematic combination of CLI and packs, and avoids scanning the library pack at all in those cases. If no queries are found in the problematic scenario, the error message instructs the user to upgrade to the latest CLI version, instead of claiming that the language simply doesn't support the contextual queries yet.

This change depends on CLI 2.6.1, which is being released soon, adding the `--allow-library-packs` option to `codeql resolve queries`. That PR is already open against the CLI.
2021-09-02 11:14:32 -07:00
shati-patel
cdd6738748 Try using a separate test query 2021-09-02 16:44:22 +01:00
shati-patel
6f16192865 Add test for resolveQueryByLanguage 2021-09-02 16:44:22 +01:00
shati-patel
8151739f87 Update syntax 2021-09-01 11:02:21 +01:00
shati-patel
72fc53ba9c Add "resolveLanguages" test 2021-09-01 11:02:21 +01:00
shati-patel
3e6ee01c4e Move findLanguage function into helpers.ts 2021-09-01 11:02:21 +01:00
Benjamin Muskalla
f6485dac95 Add changelog for sticky pagination controls 2021-08-26 08:14:25 -07:00
Benjamin Muskalla
48f15b5fc7 Stick result pagination to top 2021-08-26 08:14:25 -07:00
shati-patel
f856e3ac2c Address review comments 2021-08-25 09:27:37 +01:00
shati-patel
38a64017f2 New setting to specify number of paths per alert 2021-08-25 09:27:37 +01:00
Andrew Eisenberg
20b15b6e1d Add v2.6.0 to list of versions we use for integration testing 2021-08-24 21:03:27 -07:00
Edoardo Pirovano
e119218828 Update extensions/ql-vscode/CHANGELOG.md
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2021-08-23 21:30:30 +01:00
Edoardo Pirovano
f494988ba6 Address PR comments from @aeisenberg and @shati-patel 2021-08-23 21:30:30 +01:00
Edoardo Pirovano
2561db1721 Allow exporting of results for non-alert queries 2021-08-23 21:30:30 +01:00
Benjamin Muskalla
089b23f0aa Remove old changelog entry 2021-08-19 13:04:16 +01:00
Benjamin Muskalla
fbed7dd1ca Mention filename pattern in changelog 2021-08-19 13:04:16 +01:00
Benjamin Muskalla
06ef67f22d Add support for filename pattern in history view 2021-08-19 13:04:16 +01:00
shati-patel
3d647f68e1 Bump version to v1.5.4 2021-08-18 16:43:37 +01:00
shati-patel
6a36dc34cc v1.5.3
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-08-18 16:29:41 +01:00
Shati Patel
b48aaeac7b Fix type for "remote repo list" setting 2021-08-18 15:33:26 +01:00
Edoardo Pirovano
2da1065027 PR Checks: Use version of codeql repo suitable for CLI version 2021-08-18 15:25:21 +01:00
shati-patel
3536124fbc Tweak the regex 2021-08-17 16:54:48 +01:00
shati-patel
10b4e08bf8 Validate user input for "owner/repo" 2021-08-17 16:54:48 +01:00
shati-patel
b1f426672c Add option to enter a single repo 2021-08-17 16:54:48 +01:00
shati-patel
087cae287f Add a new "remote repository lists" setting 2021-08-17 16:54:48 +01:00
Eric Kim
3d8032c9b7 Update Changelog 2021-08-17 08:28:25 -07:00
Eric Kim
6470238311 Adjust test-adapter to display diffs only for failing tests 2021-08-17 08:28:25 -07:00
Andrew Eisenberg
0093af8994 Update the CLI versions to run integration tests against 2021-08-09 15:00:01 -07:00
shati-patel
2bfcd119db Don't show empty list of DBs 2021-08-04 20:00:49 +01:00
shati-patel
5932bdba96 Address review comments
- Tweak return types + logging
- Update changelog
2021-08-04 20:00:49 +01:00
shati-patel
1afe6b56fa Autodetect language using "resolve queries"
Also use autodection in relevant places
- When running on multiple databases
- When running a remote query
2021-08-04 20:00:49 +01:00
Andrew Eisenberg
72776e8254 Update the CLI versions to run integration tests against 2021-07-26 19:24:10 +01:00
shati-patel
d2d1a09723 Update changelog 2021-07-16 09:34:45 +01:00
shati-patel
793b82333f Rename variable and tweak error display 2021-07-16 09:34:45 +01:00
shati-patel
b3abff3e88 Add some error handling 2021-07-16 09:34:45 +01:00
shati-patel
890549f9e7 Fix database selection 2021-07-16 09:34:45 +01:00
shati-patel
66825d6a37 Add command for running queries on multiple databases 2021-07-16 09:34:45 +01:00
Andrew Eisenberg
d42982ee4c Fix dependabot errors
Updates the package dependencies to avoid dependabot errors.

I updated the `@types/gulp` to avoid some typings errors that were
introduced by incompatible versions of `@types/undertaker`.

Also, I forced resolution on `"glob-parent": "~6.0.0"` that avoids
a vulnerability on earlier versions.

I did a smoke test of features that use glob, as well as running a few
queries. All looks good.
2021-07-15 20:03:48 -07:00
shati-patel
7df634f050 Bump version to v1.5.3 2021-07-13 18:50:52 +01:00
shati-patel
46606aa7b5 v1.5.2
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-07-13 18:27:28 +01:00
shati-patel
de5704974d Use new endpoint for running remote queries 2021-07-13 18:09:21 +01:00
shati-patel
977b061048 Fix error from "Open Query Results" button 2021-07-13 09:04:00 +01:00
Chuan-kai Lin
560f694f73 Calculate databasesUnderTest with a loop
Currently QLTestAdapter.run() calculates the databases affected by a set of
tests (those databases will be deleted and then reopened after test completion)
using a nested filter-find expression. Which does not work because the
predicate is an async function, so the expression is testing the truthiness of
a Promise instead of the async result.

This commit fixes the problem by implementing the same check with a loop so
that we can invoke the async predicate using await.
2021-07-12 16:00:46 -07:00
shati-patel
7a58d360fd Update changelog 2021-07-12 09:36:10 +01:00
shati-patel
9601d6c140 Render command description as markdown 2021-07-12 09:36:10 +01:00
Edoardo Pirovano
db66184c35 Run tests with nightly CLI 2021-07-02 17:21:03 +01:00
Shati Patel
93e7daea49 Update CLI integration tests with latest version of CLI
CodeQL CLI v2.5.7 is now released 🎉
2021-07-02 15:34:54 +01:00
shati-patel
1a18c6d056 Update changelog 2021-06-25 16:14:12 -07:00
shati-patel
7eb12e0004 Loop through DBs individually, instead of adding multiple DBs in parallel 2021-06-25 16:14:12 -07:00
shati-patel
d3192b7e3b New command to add database source folder to workspace 2021-06-25 16:14:12 -07:00
Shati Patel
e7ab2969d7 Update CLI integration tests with latest version of CLI (#889)
CodeQL CLI v2.5.6 was released yesterday 🎉
2021-06-23 12:06:31 -07:00
Shati Patel
49a35343f6 Run PR checks on "ready_for_review" 2021-06-23 19:53:21 +01:00
shati-patel
c361671e36 Bump version to v1.5.2 2021-06-23 19:28:31 +01:00
shati-patel
b71452b87c v1.5.1
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-06-23 16:11:05 +01:00
Shati Patel
06170f9713 Changes from dev branch (#882)
Two new "canary" commands:
* GitHub authentication (from #874)
* Workflow dispatch (run remote query)
2021-06-23 09:14:42 +01:00
Andrew Eisenberg
920515c071 Add CODEOWNERS 2021-06-17 10:01:31 -07:00
Shati Patel
6a124685bd Don't run on pull requests
I don't think we ever need to run on PRs 🤔
2021-06-15 18:19:32 +01:00
shati-patel
75f76ecd23 Create version bump PRs in draft mode
Currently, the token we use to create these PRs doesn't have sufficient permissions to set off PR checks. Maybe if we create the PR as a draft and have a real person mark the PR as "ready-for-review", this will be enough to start PR checks.
2021-06-15 18:19:32 +01:00
shati-patel
5a0b1b290f Bump version to v1.5.1 2021-06-14 20:23:08 +01:00
shati-patel
472008888c v1.5.0
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-06-14 20:00:34 +01:00
shati-patel
aa0d844dc1 Add more context in changelog 2021-06-14 18:42:42 +01:00
shati-patel
2523f81640 Update changelog 2021-06-14 18:42:42 +01:00
shati-patel
9e8b1ffd50 Update to VS Code 1.57.0
This version of VS Code has workspace trust enabled by default
2021-06-14 18:42:42 +01:00
shati-patel
06b22511a7 Update to VS Code 1.48.0
partial cherry-pick from `qc-development` branch
2021-06-14 18:42:42 +01:00
shati-patel
61373209ff Use the workspace trust feature 2021-06-14 18:42:42 +01:00
Andrew Eisenberg
b1e28f6b7d Fix running integration tests
The main fix is in `telemetry.ts:213`.
2021-06-11 14:08:25 -07:00
Andrew Eisenberg
1d414bac55 Update linting rules
Add the `@typescript-eslint/no-floating-promises` rule with an allowance
for floating promises if `void` is used.

This increases safety and ensures that we are explicit when we avoid
awaiting a promise. I already caught a few bugish locations.

In general, we don't need to await the results of logging calls.

databases-ui, we were using a deprecated method for removing a
directory. `fs.rmdir` instead of `fs.remove`.
2021-06-11 14:08:25 -07:00
shati-patel
2f3be92a71 Make functions async + other review comments 2021-05-21 21:41:40 +01:00
shati-patel
a8fd6cc0ee Add changelog note 2021-05-21 21:41:40 +01:00
shati-patel
e591236c4e Update tests 2021-05-21 21:41:40 +01:00
shati-patel
41f4e04379 Create custom log directory, if possible
(I haven't got the error handling to work asynchronously, so I stuck with `mkdirSync` for now)
2021-05-21 21:41:40 +01:00
shati-patel
7e27f20e0e Specify custom directory for storing query server logs 2021-05-21 21:41:40 +01:00
Eric Kim
f550cbe98f Increase font size and add margins to empty query message 2021-05-21 12:35:29 -07:00
Eric Kim
5315c16338 Adjust empty query message 2021-05-21 12:35:29 -07:00
Chuan-kai Lin
540cb99de4 Reregister testproj databases around test runs
To deal with the problem of CodeQL tests modifying open testproj databases,
this commit removes open databases from the extension prior to running tests,
and tries to open those databases again after tests finish running.
2021-05-20 16:00:45 -07:00
Eric Kim
3abc8df8fc Update ChangeLog 2021-05-17 19:01:03 -07:00
Eric Kim
ca93f0e84b Add link to language guides for empty query results 2021-05-17 19:01:03 -07:00
Andrew Eisenberg
d9ff5bdca4 Update cli integration tests with new cli version 2021-05-17 12:39:25 -07:00
Andrew Eisenberg
c4b12250ba Update ChangeLog 2021-05-14 08:00:25 -07:00
Andrew Eisenberg
d73f00196b Add version info while downloading 2021-05-14 08:00:25 -07:00
Andrew Eisenberg
6bf616ff4d Fix code scanning errors and dependabot issues
* Log injection errors
* Also, ran `npm audit fix`
2021-05-10 09:39:55 -07:00
Andrew Eisenberg
ff02d1da05 Add extra emphasis in contributing docs 2021-05-06 14:54:48 -07:00
shati-patel
72d57eec6e Bump version to v1.4.9 2021-05-05 10:04:39 -07:00
shati-patel
692e1235e8 v1.4.8
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-05-05 17:41:02 +01:00
Andrew Eisenberg
b69bbf5c5d Update integration test cli versions 2021-04-30 10:11:03 -07:00
Shati Patel
b64284c43e Apply suggestions from code review
Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2021-04-29 10:31:51 -07:00
Shati Patel
67eaaadfce Update changelog 2021-04-29 10:31:51 -07:00
Shati Patel
a9545458b9 minor unrelated typo fixes 2021-04-29 10:31:51 -07:00
Shati Patel
3e1b121471 Prompt users to choose a DB language 2021-04-29 10:31:51 -07:00
Shati Patel
28d7a26b5f Fix syntax in CodeQL code scanning workflow 2021-04-28 16:19:24 +01:00
Andrew Eisenberg
1d49ae5b99 Actions: Add permissions block to code scanning workflow (#850) 2021-04-26 17:57:13 +00:00
Andrew Eisenberg
b00826d76a Use the main branch of the codeql action
This commit switches to the bleeding edge, main branch of the
codeql action. This helps us test the action before merging all
of the new changes into main, which occurs roughly once a week.

If there are commits that introduce bugs in codeql-action, then
we will be more likely to catch it before releasing to the world
if we are using it in this extension.
2021-04-26 08:50:42 -07:00
Shati Patel
eab5865a5c Fix conflict in changelog 2021-04-26 07:53:03 -07:00
Shati Patel
0e8cd0d2b1 Update changelog 2021-04-26 07:53:03 -07:00
Shati Patel
8281f408dc Add command to copy version information 2021-04-26 07:53:03 -07:00
Andrew Eisenberg
fce9bbce20 Update changelog 2021-04-23 14:57:28 -07:00
Andrew Eisenberg
dc5efcedba Watch for changes in directory structure
This ensures that directories renamed, added or deleted are
properly checked to see if they contain tests. The test tree
will be correctly updated when any directory changes.s
2021-04-23 14:57:28 -07:00
aeisenberg
f6c67bf696 Bump version to v1.4.8 2021-04-23 17:29:40 +01:00
Andrew Eisenberg
3fce04a24b v1.4.7
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-04-23 08:11:50 -07:00
Henry Mercer
fba8f51d1b Add polyfill for path to fix a bug that prevented the results view from being loaded (#842)
* Add a polyfill for the Node.js path module

Webpack >v5 doesn't include polyfills for core modules from Node.js by
default. Since we use `path` in the results table UI, we need to include
our own polyfill. This commit adds `path-browserify` to the
distributed extension.

As future work, we could move SARIF location rendering into the core
extension so we don't need to use `path.basename` in the UI. This would
allow us to remove the polyfill.

* Add changelog note
2021-04-23 12:53:48 +01:00
aeisenberg
31ee3cb978 Bump version to v1.4.7 2021-04-23 03:57:48 -07:00
Andrew Eisenberg
4d99126994 v1.4.6
Some checks failed
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-04-21 11:33:47 -07:00
Henry Mercer
ced34ad704 Add changelog note 2021-04-21 15:43:57 +01:00
Henry Mercer
f5e0011aa1 Forward all query metadata to the queryserver 2021-04-21 15:43:57 +01:00
Andrew Eisenberg
a0b759ecd8 Avoid printing a stack trace when there is no resultsPath
I don't know exactly when this can happen, but a customer has just
shown me a stack trace like this:

```
TypeError: Cannot destructure property 'resultsPath' of 'resultsPaths' as it is undefined.
    at Object.interpretResults (/xxx/.vscode/extensions/github.vscode-codeql-1.4.5/out/query-results.js:120:13)
    at InterfaceManager._getInterpretedResults (/xxx/.vscode/extensions/github.vscode-codeql-1.4.5/out/interface.js:377:45)
    at InterfaceManager.showResultsAsDiagnostics (/xxx/.vscode/extensions/github.vscode-codeql-1.4.5/out/interface.js:447:43)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async InterfaceManager.handleMsgFromView (/xxx/.vscode/extensions/github.vscode-codeql-1.4.5/out/interface.js:151:29)
```

This commit will avoid printing this stack trace and instead print
a more descriptive message to the logs.
2021-04-20 12:55:13 -07:00
Andrew Eisenberg
58cf4db9ee Add v2.5.1 to cli versions in integration test 2021-04-19 13:53:21 -07:00
Henry Mercer
e0c5ae815c Remove commented out code 2021-04-19 08:44:57 -07:00
Andrew Eisenberg
bf5ed193be Avoid opening the results panel on db deletion
Fixes https://github.com/github/vscode-codeql/issues/823
2021-04-19 08:05:27 -07:00
Aditya Sharad
aa60fbc213 Actions: Simplify code scanning workflow
Run only on pushes and PRs against `main`.
2021-04-14 11:58:46 -07:00
Andrew Eisenberg
bdb2feb559 Refactor version constraints
A simple refactoring that simplifies and unifies how we check if a
feature is supported by a specific cli version.
2021-04-13 10:36:54 -07:00
Andrew Eisenberg
5b08fd0df1 Fix CHANGELOG 2021-04-10 11:19:32 -07:00
Andrew Eisenberg
c83dbde20f Add cli version for message 2021-04-09 15:19:47 -07:00
Edoardo Pirovano
e033578cd2 Add feature to jump to the .ql file referenced by a .qlref 2021-04-09 15:19:47 -07:00
Andrew Eisenberg
c082a38b6b Add a canary setting to avoid caching AST viewer queries (#818)
When codeql library developers are working on PrintAST queries, it is
not easy to use the AST Viewer. The AST Viewer caches results so that
multiple calls to view the AST of the same file are nearly
instantaneous.

However, this breaks down if you are changing the actual queries that
perform AST viewing. In this case, you do not want the cache to be
active.

This commit adds an undocumented setting that prevents caching. To
enable, set:

```
"codeQL.isCanary": true,
"codeQL.astViewer.disableCache": true
```

Note that *both* settings must be true for this to work.

This behaviour and all canary behaviour should be documented somewhere.
I will add that later.
2021-04-01 14:12:13 -07:00
Andrew Eisenberg
bdda27703a Ensure snippets.json is copied when packaging the extension 2021-03-31 10:47:48 -07:00
Andrew Eisenberg
36bfb3987e Fix dependabot warnings (#816)
This commit updates to webpack 5 in order to fix some dependabot errors.
Because webpack 5 introduces some breaking changes, this commit also
makes some minor changes to the build code.
2021-03-29 19:46:20 +00:00
Andrew Eisenberg
6d26491243 Avoid displaying error message for @kind table queries
Also, add a unit test for this area.
2021-03-29 08:16:51 -07:00
Edoardo Pirovano
98a2bbbb47 Limit error messages shown in popups to 2 lines 2021-03-28 16:14:55 -07:00
Aditya Sharad
fb6bed6042 Actions: Test against CodeQL CLI 2.5.0 (#812) 2021-03-26 11:31:31 -07:00
github-actions[bot]
df0cc921fd Bump version to v1.4.6 (#805)
* Bump version to v1.4.6

* Update CHANGELOG.md

Co-authored-by: adityasharad <adityasharad@users.noreply.github.com>
Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>
2021-03-23 00:40:39 +00:00
Aditya Sharad
cd7354446b v1.4.5 (#804)
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-03-22 17:18:32 -07:00
Alexander Eyers-Taylor
d909f98fcb Fix running tests when ms-python is installed. (#803)
Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>
2021-03-22 16:54:02 -07:00
Andrew Eisenberg
8c2db75886 Avoid showing an error when query has not @kind metadata (#801)
Fixes #800
2021-03-22 08:03:13 -07:00
Aditya Sharad
73e560e6da Actions: Test against CodeQL 2.4.6
Deliberately keeping 2.4.5 as well, to keep testing enterprise compatibility.
2021-03-19 17:01:58 -07:00
aeisenberg
ada1180468 Bump version to v1.4.5 2021-03-19 15:39:32 -07:00
Shati Patel
d1e70816aa Update pull_request_template.md (#791) 2021-03-19 17:38:56 +00:00
Andrew Eisenberg
df936167d5 v1.4.4
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-03-19 10:24:35 -07:00
Andrew Eisenberg
0327ec358c Update Changelog 2021-03-19 08:58:10 -07:00
Edoardo Pirovano
7a78fca252 Report description for test failure when possible 2021-03-19 08:58:10 -07:00
Edoardo Pirovano
10e86f1835 Add some commonly used QL snippets 2021-03-17 08:43:00 -07:00
Edoardo Pirovano
dbaed3acd5 Implement viewing of query results as a CSV 2021-03-17 08:04:46 -07:00
Edoardo Pirovano
6830bdd28d Add option to pass additional arguments when running tests 2021-03-16 13:45:00 -07:00
Edoardo Pirovano
e316decae1 Implement sorting of query history by name, date, and result count 2021-03-15 11:18:47 -07:00
Marcono1234
a86c1ce69b Use HTTPS for links 2021-03-14 22:58:50 -07:00
Marcono1234
01418cba26 Update Semmle links in extension README 2021-03-14 22:58:50 -07:00
Edoardo Pirovano
35d98f62e8 Limit scope of save cache option. 2021-03-12 08:46:45 -08:00
Edoardo Pirovano
b30121b84c Apply suggestions from code review
Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2021-03-12 08:46:45 -08:00
Edoardo Pirovano
fd15217a20 Expand disk cache evaluator options 2021-03-12 08:46:45 -08:00
Shati Patel
1d03702334 Docs: Update Telemetry links 2021-03-09 08:41:52 -08:00
Andrew Eisenberg
c47029e9eb Update cli version used in integration tests 2021-03-08 13:25:24 -08:00
Alexander Eyers-Taylor
5fdfb44c2e Use downgrades when fixing dbscheme mismatches where possible. (#765) 2021-03-04 10:48:12 +00:00
Andrew Eisenberg
6e40478440 Add error message when interpretation fails
One way it can fail is if the SARIF is too large. We explicitly call
out that error because the raw message received from the node runtime
is not very understandable.
2021-03-02 14:03:19 -08:00
Andrew Eisenberg
9e68b4f061 Use codeQL.runningQueries.numberOfThreads to run interpretation
When running `codeql bqrs interpret`, ensure the
`codeQL.runningQueries.numberOfThreads` setting is respected.
2021-03-02 13:47:12 -08:00
Andrew Eisenberg
0f82875b9d Allow raw project slugs for fetching lgtm dbs
The following is now acceptable for fetching the codeql lgtm database:

```
g/github/codeql
```
2021-03-02 11:40:51 -08:00
aeisenberg
fd52f66f6d Bump version to v1.4.4 2021-03-02 10:23:52 -08:00
Henry Mercer
42cfa45d7e Update page size setting description 2021-02-26 15:22:00 +00:00
Andrew Eisenberg
5023f91475 Bump test timeouts
Necessary because we just added some extra waiting
in order to ensure that config listeners have all
fired.
2021-02-22 12:50:39 -08:00
Andrew Eisenberg
48df77f673 v1.4.3 (#761)
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-02-22 12:30:14 -08:00
Andrew Eisenberg
839665588f Avoid clobbering quick-query file when re-opened
Only recreate the qlpack.yml file.

Also, add an integration test for quick-query creation.
2021-02-22 12:05:25 -08:00
Andrew Eisenberg
ab31d86a8d Update cli version in integration test
Simplify description of executablePath setting

"This overrides all other CodeQL CLI settings" is a potential source of
confusion, since it suggests the RAM and threads settings may not be
passed to custom CLIs, when this is in fact the case.
2021-02-18 09:05:19 -08:00
Henry Mercer
f2d07729b9 Simplify description of executablePath setting
"This overrides all other CodeQL CLI settings" is a potential source of
confusion, since it suggests the RAM and threads settings may not be
passed to custom CLIs, when this is in fact the case.
2021-02-15 18:39:00 +00:00
Andrew Eisenberg
707cba4ac9 Fix issues with dynamic updating of the version status bar item
1. Wait a few seconds before updating the status bar after a version
   change.
2. Ensure we are watching the correct configuration items for changes.
3. Ensure the cli version is refreshed correctly.
2021-02-12 08:22:59 -08:00
Andrew Eisenberg
6304fe0e30 Update typings for mocha (#752)
* Update typings for mocha

This is includes an update of the lock file to the v2 format. It's a big
change, but not much is happening here. I thought it best to keep it
separate.

* Fix globalSetup/teardown for mocha

Updating the typings for mocha uncovered an error in how we were
registering global setups and teardowns.

When calling `mocha.globalSetup` or `mocha.globalTeardown`, any
previously registered globals are overwritten. The workaround
is to attach globals directly to the internal options object.

This is a requirement because we are now registering globals in
multiple files.

Unfortunately, the typings for mocha do not permit this and I may need
to fix them again.
2021-02-11 16:48:52 -08:00
Andrew Eisenberg
be9084e83e Fix error messages for ast viewers and update caching
This commit does two things:

1. Add more appropriate error messages when asts can't be viewed.
2. Make better use of cached operations for asts. In the past, we were
not actually using cached operations. Each time an ast view request
occurred, we created a new TemplatePrintAstProvider instance. With this
change, we reuse the TemplatePrintAstProvider between calls and ensure
that an AST that is called once is reused on subsequent calls.
2021-02-11 15:34:49 -08:00
Andrew Eisenberg
57d856ff5c Avoid displaying irrelevant error
Problem was misplaced parens. We were not waiting for
the call to `pathExists` to complete before making the call
to `stat` the directory. When the directory does not
exist, then `stat` throws an error.
2021-02-11 13:07:52 -08:00
Andrew Eisenberg
343e9e5466 Convert env.openExternal to a noop for testing
We should not be opening any external links during tests. This is
causing some builds to hang when running on CI.

See https://github.com/github/vscode-codeql/pull/750 for an example.
2021-02-11 12:32:42 -08:00
Andrew Eisenberg
f2620c65af Add disposeHandlers
These functions assist with object disposal. They add custom behaviour
during disposal. The primary usage of disposalHandlers is during testing
where some objects should not be disposed in order to avoid testing
errors.

Additionally, move DisposableObject to the pure folder and create unit
tests for it.

Also, add `--disable-gpu` to command line options when running tests.
It helps to avoid error messages like this:

```- [19141:19141:0425/011526.129520:ERROR:sandbox_linux.cc(374)] InitializeSandbox() called with multiple threads in process gpu-process.```

See also https://askubuntu.com/a/1288969
2021-02-11 12:32:42 -08:00
Andrew Eisenberg
c5fe58db37 Add workflow dispatch 2021-02-11 12:32:42 -08:00
aeisenberg
47b57c01f3 Bump version to v1.4.3 2021-02-02 14:34:19 -08:00
Andrew Eisenberg
27529bfc33 v1.4.2
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-02-02 14:23:49 -08:00
Andrew Eisenberg
0e4ae83e74 ` 2021-02-02 12:38:53 -08:00
Andrew Eisenberg
3b1ff0f4a3 Add a codeql status bar item
Includes the current cli version as well as the
canary status (codeQL.canary) in the settings.
2021-02-02 09:40:59 -08:00
Andrew Eisenberg
5079abd06f Fix version constraint
Non-destructive upgrades only exist in versions >= 2.4.2
2021-02-02 09:17:33 -08:00
aeisenberg
4e94f70e6f Bump version to v1.4.2 2021-01-29 21:45:42 -08:00
Andrew Eisenberg
79e2666586 v1.4.1
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-01-29 21:37:29 -08:00
Andrew Eisenberg
02080cd797 Change text and fix link of modal dialog
Modal dialogs do not allow for markdown text. The link was invalid.
Also, make CodeQL more prominent in the dialog.
2021-01-29 17:46:42 -08:00
aeisenberg
7347ff5512 Bump version to v1.4.1 2021-01-29 16:07:07 -08:00
Andrew Eisenberg
c26217df88 v1.4.0
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-01-29 15:32:50 -08:00
Andrew Eisenberg
31b445c8d2 Remove logic to only create release artifacts on PRs
Create them for appropriately named tags and workflow dispatch as well.
2021-01-29 15:21:12 -08:00
Andrew Eisenberg
7387ef6d2c Fix telemetry recording bug
When someone disables and then re-enables the global telemetry setting,
the telemetry recorder needs to be recreated in order to allow it to
respond to events again.

Also, write the telemetry log item in the same telemetry processor as
is used to remove unused fields. This ensures there is no race condition
on the order of telemetry processors being run. We always log after
fields are removed.
2021-01-29 15:21:12 -08:00
Andrew Eisenberg
091d36b1a0 Tweak telemetry page and changelog 2021-01-29 15:21:12 -08:00
Andrew Eisenberg
292e695646 Add telemetry for commands
This commit adds telemetry capturing for command execution. The data
captured explicitly captured and sent to application insights is only
the command id, execution time, and command completion status. We also
capture errors thrown by any command execution, but these are not sent
to application insights.

Telemetry capturing is opt-in. No data will be sent to application
insights unless the user explicitly allows it.

There are two new config settings added. The first controls whether or
not telemetry should be sent. This setting AND the global telemetry setting
must be enabled in order for telemetry to be sent.

The second setting controls whether or not telemetry event data should
be logged to the extension console. The hope here is that users can
inspect exactly what data is sent to the server and can have confidence
that nothing concerning is being leaked.

Note that the global setting for disabling telemetry collection is
handled inside the  `vscode-extension-telemetry` package implicitly, so
this extension doesn't touch that setting explicitly.

The `codeql.canary` setting is being used to add an additional flag to
telemetry events. This flag will help us determine if a user in internal
or not.

The application insights key is injected at build time through a
repository secret.

This commit also includes a new `TELEMETRY.md` file that explains what
is being captured, and why.
2021-01-29 15:21:12 -08:00
Andrew Eisenberg
f154206b47 Fix invalid property name on message 2021-01-29 11:24:07 -08:00
Andrew Eisenberg
07eb334e6c Ensure databases are re-registered when query server restarts
This commit fixes #733. It does it by ensuring that the query server
emits an event when it restarts the query server. The database manager
listens for this even and properly re-registers its databases.

A few caveats though:

1. Convert query restarts to using a command that includes progress.
   This will ensure that errors on restart are logged properly.
2. Because we want to log errors, we cannot use the vscode standard
   EventEmitters. They run in the next tick and therefore any errors
   will not be associated with this command execution.
3. Update the default cli version to run integration tests against to
   2.4.2.
4. Add a new integration test that fails if databases are not
   re-registered.
2021-01-29 11:24:07 -08:00
alexet
89b86055d7 Use asycy tmp 2021-01-28 16:13:33 -08:00
alexet
4dfec7014c Adress comments 2021-01-28 16:13:33 -08:00
alexet
fbff2df899 Remove unused variable 2021-01-28 16:13:33 -08:00
alexet
9cbe5ba2e8 Simplify query server interface. 2021-01-28 16:13:33 -08:00
alexet
70ddbd05be Adress comments on non-destructive upgrades. 2021-01-28 16:13:33 -08:00
alexet
ace92a4674 Remove uneeded argument 2021-01-28 16:13:33 -08:00
alexet
24b3e158b7 Set codeql version to required version. 2021-01-28 16:13:33 -08:00
alexet
a399041cba Fix rebase conflict 2021-01-28 16:13:33 -08:00
alexet
676546d32b Adress review comments 2021-01-28 16:13:33 -08:00
alexet
a25db9616f QueryServer: Use non-destructive upgrades where possible. 2021-01-28 16:13:33 -08:00
alexet
cb4d6f228b QueryServer: Add new commands to client. 2021-01-28 16:13:33 -08:00
alexet
424884b6b1 Add support for new cli feature 2021-01-28 16:13:33 -08:00
Henry Mercer
f741deb48b Forward scored query metadata property for canary users 2021-01-21 19:36:34 +00:00
Henry Mercer
ae6be79c51 Add config setting to enable canary features 2021-01-21 19:36:34 +00:00
Henry Mercer
154b4a2fe2 Fix missing call to showAndLogErrorMessage 2021-01-21 11:34:30 -08:00
aeisenberg
650f4ca047 Bump version to v1.3.11 2021-01-21 19:06:58 +00:00
Andrew Eisenberg
a7c73cc421 v1.3.10
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
Release / Publish to VS Code Marketplace (push) Has been cancelled
Release / Publish to Open VSX Registry (push) Has been cancelled
2021-01-20 14:15:45 -08:00
Andrew Eisenberg
044bc30d96 Clarify how to run CLI tests locally
Also, remove an errant `only`, which was preventing some tests from
running.
2021-01-20 13:05:53 -08:00
Andrew Eisenberg
9c72e81264 Update changelog 2021-01-20 13:05:53 -08:00
Andrew Eisenberg
3a718ee6e0 Include the full stack in error log messages
Ensure we only show the truncated error message in the popup.

This will help with debugging.
2021-01-20 13:05:53 -08:00
Andrew Eisenberg
540124478b Refactor: Move commandRunner to its own module
Also, extract related functions and types. There are no behavioral
changes in this commit. Only refactorings.
2021-01-19 12:51:12 -08:00
Henry Mercer
6074a1a7c8 Fix minor typo in welcome content
Replace "Code QL database" with "CodeQL database" for consistency with [documentation](https://codeql.github.com/docs/codeql-cli/creating-codeql-databases/).
2021-01-19 06:51:18 -08:00
Andrew Eisenberg
093a51cee3 Fix Code Scanning warnings 2021-01-11 15:27:43 -08:00
Andrew Eisenberg
cace4acb1e Update internal docs for publishing
And remove unused file.
2021-01-11 13:38:21 -08:00
Andrew Eisenberg
696c16b5b4 Add workflow jobs to deploy extension
This adds two new jobs to the `Release` workflow. These
jobs are blocked behind an environment. When approved
by a committer, the extension will be deployed to
Open VSX and VS Code marketplace.

Also, update contributing docs for open-vsx publishing.
2021-01-11 13:38:21 -08:00
Andrew Eisenberg
7b439e4511 Make typing more explicit 2021-01-04 08:55:47 -08:00
alexet
402700f56f SingleFileUpgrades: Address comments 2021-01-04 08:55:47 -08:00
alexet
8eaeefb9ea Use single file upgrades where possible. 2021-01-04 08:55:47 -08:00
aeisenberg
49ac9796a1 Bump version to v1.3.9 2020-12-17 11:55:58 -08:00
Andrew Eisenberg
89b6b5a945 v1.3.8
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
2020-12-17 11:52:33 -08:00
Andrew Eisenberg
53ac1ed70d Update changelog
Clarify a few entries.
2020-12-17 11:07:37 -08:00
Andrew Eisenberg
5824e3607a Add View AST Command to text editor where appropriate
Also, hide the `CodeQL: Run Queries` command inside of zip folders
since we do not allow queries to be in archives. I wish we could be more
specific about when to show that command, eg- only *.ql files and
directories, but I couldn't find a way to restrict a command to only
appear on directories.
2020-12-17 11:07:37 -08:00
Andrew Eisenberg
e6eb914783 Add unit tests for query-history 2020-12-16 13:26:09 -08:00
Andrew Eisenberg
b0e032be2c Fix set label command on history items
This removes the cached treeItem that is a property of the
completedQuery. We should not be caching them since they are cached by
the vscode api itself. Instead, we should recreate whenever requested.

Also, this change fixes #598 in a new way. Instead of adding the
context to the cached treeItem, we simply refresh only the item that has
changed. This is a fast operation.
2020-12-16 13:26:09 -08:00
Andrew Eisenberg
3ea3eda8aa Add descriptive text and a link at top of query results
The descriptive text is the same as the label in the query history view.
The link opens the file that ran the query.
2020-12-16 13:18:49 -08:00
Andrew Eisenberg
ca9510c08d Add unit test for test discovery
When directory is not present.
2020-12-14 17:47:49 -08:00
Andrew Eisenberg
303cb3284c Avoid uninteresting user facing errors
This change avoids popping up error messages in two cases:

1. When doing test discovery, do not run discovery on non-existant
   directories. Also, if there is an error, print to the log, and do not
   pop up an error window. The reason is that test discovery is a
   background operation and these should not normally cause pop-ups.
2. When looking for orphaned databases, don't pop up an error if the
   storagePath can't be found. This is normal when working in a new,
   single root workspace.
2020-12-14 17:47:49 -08:00
Andrew Eisenberg
5ad433775b Move query.test.ts to the cli integration tests
* Now query.test.ts runs on multiple cli versions
* Removed most `dispose` calls in cli tests because each test shares the
  same instance of the extension and all of its properties. So, we
  shouldn't be disposing until the last test completes. It's likely that
  we will need to be more careful about cleaning up state between test
  runs, but we haven't hit that yet and this can happen in a later
  commit.
2020-12-14 12:36:46 -08:00
Andrew Eisenberg
69ca0f55ba Re-enable the queries cli test
* Requires that QL_PATH environment variable is set and points to a
  checkout of github/codeql
* Adds the `quiet` flag to the cli. When set, this flag will prevent
  some modal dialogs from disrupting the flow. Currently, we only ensure
  that the upgrades dialog is avoided.
* Update the main.yml workflow to checkout the codeql repo
2020-12-14 12:36:46 -08:00
Andrew Eisenberg
b5e708796d Fix failing test
Also, small change to ensure `qlpackOfDatabase` never returns undefined.
It will either return a value or throw.
2020-12-14 10:20:28 -08:00
Tom Hvitved
2516a62469 Add missing call to getPrimaryDbscheme in qlpackOfDatabase 2020-12-14 10:20:28 -08:00
Andrew Eisenberg
9ffb3a14c7 Save downloaded DB archives to disk before unzipping (#700)
This fixes two classes of DBs that can't be installed directly from
downloading:

1. DBs whose central directories do not align with their file headers.
   We need to download and save the entire archive  before we can read
   the central directory and use that to guide the unzipping.
2. Large DBs require too much memory so can't be downloaded and unzipped
   in a single stream.

We also add proper progress notifications to the download progress
monitor so users are aware of how many more MBs are left to download.

It's not yet possible to do the same for unzipping using the current
unzipper library, since unzipping using the central directory does not
expose a stream.

Co-authored-by: Alexander Eyers-Taylor <alexet@github.com>
2020-12-14 16:26:29 +00:00
dependabot[bot]
51835a2466 Bump ini from 1.3.5 to 1.3.8 in /extensions/ql-vscode
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 15:52:35 -08:00
Andrew Eisenberg
b470e41431 Make error messages clearer for some common problems
1. Clicking on query history menu items when nothing is selected. Error
   message is clearer. It would be better to disable when nothing is
   selected, but waiting on
   https://github.com/microsoft/vscode/issues/99767 to be released.
2. Trying to run query with a missing or invalid qlpack has better
   message.
3. Better hover text for "Open query".

Co-authored-by: Aditya Sharad <6874315+adityasharad@users.noreply.github.com>
2020-12-09 15:35:59 -08:00
Andrew Eisenberg
370dbcbfae Update integration test version numbers
Also, fix a typo and remove comment.
2020-12-04 10:08:15 -08:00
Andrew Eisenberg
6046cf1472 Add integration test for running a query
In order to do this, needed to add a few extra pieces:

* extracted the simple database download so that it only happens
  once and is shared across all tests.
* needed to update mocha to latest version since that has the new API
* But typings isn't updated yet, so submitted a PR into DefinitelyTyped
  for that.
* Added a concept of helper files for test runs. These helper files
  will contain all the shared global setup.

Unfortunately, at this point, we can't run using a language pack since
we would also need to download the the ql repository from somewhere.
2020-12-04 10:08:15 -08:00
Andrew Eisenberg
864041efcb Add integration tests for database fetching 2020-12-04 10:08:15 -08:00
Andrew Eisenberg
16eac45822 Add integration tests with the CLI
This commit adds integration tests that run commands using the CLI. This
change introduces a number of enhancements in order to get there.

1. Augments the index-template.ts file so that it downloads an
appropriate cli version if requested.
2. Adds the ensureCli.ts that performs the download if a a suitable
version is not already installed. See the comments in the file for how
this is done.
3. Changes how run-integration-tests is done so that the directories
run are specified through a cli argument.
4. Updates the main.yml workflow so that it also runs the
cli-integration tests.
5. Takes advantage of the return value of the call to `activate` on the
extension. This allows the integration tests to have access to internal
variables of the extension like the context, cli, and query server.
6. And of course, adds a handful of simple tests that ensure we have a
cli installed of the correct version.
2020-12-04 10:08:15 -08:00
Andrew Eisenberg
06a1fd91e4 Fix typos and augment comments around language labels 2020-12-04 09:36:54 -08:00
Andrew Eisenberg
67e8c86ccc Use codeql resolve database to get language
This commit moves to using codeql resolve database instead of inspecting
the `codeql-database.yml` file.

When the extension starts and if the cli supports it, the extension will
attempt to get the name for any databases that don't yet have a name.
Once a name is searched for once by the cli, it will be cached so we
don't need to rediscover the name again.
2020-12-04 09:36:54 -08:00
Andrew Eisenberg
43ef44ff12 Add a language label next to databases in the UI
This change will only work on databases created by cli >= 2.4.1. In that
version, a new `primaryLanguage` field in the `codeql-database.yml`
file. We use this property as the language.

This change also includes a refactoring of the logic around extracting
database information heuristically based on file location. As much
as possible, it is extracted to the `helpers` module. Also, the
initial quick query text is generated based on the language (if known)
otherwise it falls back to the old style of generation.
2020-12-04 09:36:54 -08:00
Andrew Eisenberg
0d04c5d463 Ensure all tests run (#696)
Accidentally committed `.only`.
2020-12-02 15:57:40 -08:00
Andrew Eisenberg
b6c7837fd7 Pluralize registration message names
And do a version check before adding `--require-db-registration` flag.
2020-12-02 11:49:56 -08:00
Andrew Eisenberg
d76f912903 Add version check for db registration
Database registration is available in versions >= 2.4.1
2020-12-02 11:49:56 -08:00
Andrew Eisenberg
1b4a992182 Update changelog 2020-12-02 11:49:56 -08:00
Andrew Eisenberg
2795184e70 Add support for database registration 2020-12-02 11:49:56 -08:00
Andrew Eisenberg
3c08baf062 Add query running test for computeDefaultStrings flag 2020-12-01 14:31:39 -08:00
Andrew Eisenberg
6afb946200 Update changelog 2020-12-01 14:31:39 -08:00
Andrew Eisenberg
bfe4aa386c Pass computeDefaultStrings to query server when compiling queries 2020-12-01 14:31:39 -08:00
Max Schaefer
f4624f3dbf Fix dubious index check (#692)
* Fix dubious index check

* Add unit tests for add/remove database

In order to do this, needed to move `databases.test.ts` to the
`minimal-workspace` test folder because these tests require that there
be some kind of workspace open in order to check on workspace folders.

Unfortunately, during tests vscode does not allow you to convert from a
single root workspace to multi-root and so several of the workspace
functions needed to be stubbed out.

* Update changelog

Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2020-11-30 11:34:47 -08:00
aeisenberg
1b4d8e303d Bump version to v1.3.8 2020-11-24 14:11:16 -08:00
Andrew Eisenberg
b7b5a6ec30 v1.3.7
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
2020-11-24 14:02:25 -08:00
Andrew Eisenberg
da9576fee0 Add workflow_dispatch to release workflow 2020-11-23 17:56:36 -08:00
Andrew Eisenberg
579df25be4 Use the ast edge label when building the ast node label
The C PrintAST library now includes the edge name in the AST Viewer
tree.
2020-11-23 15:27:24 -08:00
Andrew Eisenberg
1886c0c9ec Add a setting to control page size
Also, set a max and min value on the input control of the page. This
prevents going to a negative page, or a page after the last one.
2020-11-21 09:45:52 -08:00
Andrew Eisenberg
f48176bebf Re-sort databases list after db rename 2020-11-20 15:12:47 -08:00
Andrew Eisenberg
83f64fbdcd Avoid dependabot error 2020-11-19 14:02:21 -08:00
Andrew Eisenberg
a7bf5e60f3 Add debug flag for query server
And separate flag for IDE server. Setting these flags to `true` will
start the respective Java processes in debug mode so that they can
be attached to a debugger.
2020-11-18 15:55:24 -08:00
Andrew Eisenberg
e0cd041d98 Clean databases folder on startup (#675)
Cleans orphan databases on startup. This commit also bumps the fs-extra
dependency to get readdir with dirent objects.

Adds the `asyncFilter` to filter arrays asynchronously.
2020-11-16 16:32:05 +00:00
Andrew Eisenberg
4f76e9da60 Use the value not the label for the print ast node
Fixes #659
2020-11-13 09:45:30 -08:00
Andrew Eisenberg
966cc5af92 Add more structured output for tests
The diff and the errors were always available, but they were not being
sent to the output.

Additionally, make sure to send output to both the test explorer log and
the codeql test log.
2020-11-09 14:31:02 -08:00
Andrew Eisenberg
f4998d90e7 Creates an empty .expected file when running test output compare
If the expected file does not already exists. This helps with test
creation and allows users to create tests more quickly.
2020-11-09 14:27:20 -08:00
Andrew Eisenberg
245496c854 Remove QLPackDiscovery
We no longer rely on qlpacks for our ql test structure. For this reason,
we no longer need to do qlpack discovery.
2020-11-09 11:53:42 -08:00
Andrew Eisenberg
d553f6c069 Restructure the tree in the Test Explorer View
With this change we display the tree based on the file system not based
on ql-packs. We also merge test folders whose only child is another
test folder.

Resolves #595
2020-11-09 11:53:42 -08:00
Andrew Eisenberg
afd0694111 Update changelog 2020-11-09 11:53:42 -08:00
Andrew Eisenberg
32db9cdec6 Open editor containing query location in non-preview mode 2020-11-05 10:32:58 -08:00
github-actions[bot]
ad3cd7e7ac Bump version to v1.3.7 (#672)
Co-authored-by: aeisenberg <aeisenberg@users.noreply.github.com>
2020-11-04 14:09:37 -08:00
Andrew Eisenberg
e719c68321 Update the contributing docs
Just adds some more details.
2020-11-04 12:47:38 -08:00
Andrew Eisenberg
ce3b4ed43d v1.3.6 (#671)
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
2020-11-04 12:06:05 -08:00
Andrew Eisenberg
2953c15e5e Avoid recursive selection changes in ast viewer
This will prevent selections jumping around when an ast entry is
selected and its child has the same source location as the current
selection.
2020-11-04 07:14:39 -08:00
Andrew Eisenberg
b2b1021207 Disable codeql test commands from the command palette
These commands are not applicable from the global context. They require
an argument to be passed in. So, they should be hidden in the command
palette.
2020-11-03 15:52:00 -08:00
Andrew Eisenberg
9ddfd58a2b Adds interface-types and result-keys to pure
Will ensure that these files never have vscode dependencies.
2020-11-03 12:56:52 -08:00
Andrew Eisenberg
fe1476f875 Ensure uris are using encoded strings (#653)
This fixes a bug where if there are special characters in a database
path, it is not possible to navigate to that file from the results view.

Note that the results from our BQRS returned properly encoded URIs, but
our paths coming from sarif were unencoded. Our path parsing handled
the latter correctly (even though these are not correct URIs) and the
former incorrectly.

The fix here is to first ensure all uris are properly encoded. We do
this by running `encodeURI` in sarif-utils (can't run encodeURIComponent
or else the path separators `/` will also be encoded).

Then, we ensure that when we resolve locations, we decode all file
paths.

This works in all cases I have tried. I still have an issue with running
View AST on some of these databases, but that I believe is a separate
issue.
2020-11-03 18:06:44 +00:00
alexet
067a87a07c Results View: Fix display of booleans 2020-11-03 08:09:53 -05:00
Andrew Eisenberg
5133ee713f Add the assert-pure query
This query ensures that all of our files marked as "pure" remain that
way. In this case "pure" means that it does not depend on vscode and
can therefore be run in tests outside of a runtime environment.

This commit also explicitly moves all of our "pure" files to the
`src/pure` directory.
2020-11-02 18:40:45 -08:00
aeisenberg
2ac7881cf2 Bump version to v1.3.6 2020-10-27 12:56:22 -07:00
Andrew Eisenberg
5e8773b2b0 Prepare for release v1.3.5
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
2020-10-27 12:37:06 -07:00
Andrew Eisenberg
2ac44b188c Ensure decoded archive fs paths are never empty (#648)
Empty paths should be replaced as '/'. This is a fix for a bug
introduced in 899f988df8.
2020-10-27 18:38:31 +00:00
Andrew Eisenberg
ef5d7bf684 Add version info to cli
And also only add the `--kind=DIL` to `generateDil` if version is
>= 2.3.0.
2020-10-26 09:03:43 -07:00
Andrew Eisenberg
ec98a577a2 Bump version of create-pull-request action
New version will avoid deprecation warnings for add-path
and set-var.
2020-10-22 14:17:53 -07:00
github-actions[bot]
ea9f8d494c Bump version to v1.3.5 2020-10-22 10:55:20 -07:00
Andrew Eisenberg
7cfaeddbc0 Prepare for release v1.3.4
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Release / Release (push) Has been cancelled
2020-10-22 10:45:18 -07:00
Andrew Eisenberg
093646c8a3 Remove the --kind dil options from decompile command
This option is not recognized.
2020-10-22 10:28:43 -07:00
Andrew Eisenberg
d8ab85748f Add some config listener tests
This also renames the config listeners for more consistency.
2020-10-21 15:48:35 -07:00
Andrew Eisenberg
1a5deab711 Remove unnecessary preLaunchTask 2020-10-21 15:48:35 -07:00
Andrew Eisenberg
68fe3bfbef Use the codeQL.runningTests.numberOfThreads
This setting has existed for a while, but it was not used for some
reason.
2020-10-21 15:48:35 -07:00
Andrew Eisenberg
899f988df8 Fix other locations where we create an invalid codeql-zip-archive uri
Also, create a convenience function for generating a codeql-zip-archive
at the root of the archive.
2020-10-21 14:23:51 -07:00
Andrew Eisenberg
9547aa3851 Remove feature flag for the AST Viewer 2020-10-21 14:07:05 -07:00
Andrew Eisenberg
e7e8ebab98 Fix flaky tests
These tests make API calls and may need extra time to complete.
2020-10-21 10:40:30 -07:00
Andrew Eisenberg
5b6371fb94 Fix archive encoding when there is an empty uri authority
This commit fixes a bug uncovered by
c66fe07b06.

The findSourceArchive function in databases.ts creates a
codeql-zip-archive uri with an empty authority component. This will
fail to decode. Until recently, this situation never happened. But in
the commit linked above, we start decoding some of these incorrectly
encoded uris.

This commit fixes that issue.
2020-10-21 08:07:48 -07:00
Andrew Eisenberg
542bb85490 Avoid running workflows on all push events
Only run on push events to main. This ensures that our main branch
is always passing.
2020-10-20 12:48:46 -07:00
Andrew Eisenberg
c66fe07b06 Return undefined for finding file ranges on empty URI
Also, refactor resolveSourceFile to make it easier to read.
And add unit tests for resolveSourceFile.

This commit fixes a bug in resolveSourceFile where the 
`pathWithinSourceArchive` was being removed and appended to the
`sourceArchiveZipPath`. In normal situations, we don't hit this bug
because most database source archive uris have an empty path for the
`pathWithinSourceArchive`.
2020-10-19 07:10:12 -07:00
Andrew Eisenberg
fe219e05d8 Refactor extension context subscriptions
Use DiposableObject more consistently and ensure all commands are
added as a disposable to the ExtensionContext.
2020-10-13 13:54:04 -07:00
Andrew Eisenberg
2dcf3b3feb Fix whitespace in CONTRIBUTING.md
Co-authored-by: jcreedcmu <jcreed@gmail.com>
2020-10-13 11:35:40 -07:00
Andrew Eisenberg
50efdea9d6 Remove build before launch in launch.json
And update contributing with new instructions.
2020-10-13 11:35:40 -07:00
Andrew Eisenberg
9300c07d42 Add command to view the DIL of a query 2020-10-13 11:07:43 -07:00
Andrew Eisenberg
8e817ee01a Refactor the commandRunner
Split commandRunner into two functions: commandRunner and
commandRunnerWithProgress.

Also, take advantage of default arguments for ProgressOptions.

And updates changelog.
2020-10-09 10:48:44 -07:00
Andrew Eisenberg
e5d439ae89 Update changelog
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2020-10-09 10:48:44 -07:00
Andrew Eisenberg
2c75a5c8cb Ensure database upgrade request happens only once
When a user runs multiple queries on a non-upgraded database, ensure
that only one dialog appears for upgrade.

This commit also migrates the upgrades.ts file to using the passed-in
cancellation token and progress monitor. This ensures that cancelling
a database upgrade command will also cancel out of any wrapper
operations.

Fixes #534
2020-10-09 10:48:44 -07:00
Andrew Eisenberg
7f472ac100 Add the commandRunner
The commandRunner wraps all vscode command registrations. It provides
uniform error handling and an optional progress monitor.

In general, progress monitors should only be created by the
commandRunner and passed through to the locations that use it.
2020-10-09 10:48:44 -07:00
Andrew Eisenberg
43d5ee78ea Add comments to interfaces.ts and databases-ui.ts
Also, small refactoring of the vscodeMessageHandler.
2020-10-08 12:32:27 -07:00
Andrew Eisenberg
54fee0bed8 Add unit tests for event emitting in database manager 2020-10-08 12:32:27 -07:00
Andrew Eisenberg
6bc720468c Update changelog 2020-10-08 12:32:27 -07:00
Andrew Eisenberg
7961816906 Only clear problems view when a database is removed
This commit adds DatabaseChangedEvent and ensures that all events
fired by the DatabaseManager includes one of these kinds.

Currently, the only kind that we care about is `Remove`. We ensure that
the problems view is only cleared on Remove events.
2020-10-08 12:32:27 -07:00
Andrew Eisenberg
672b20d4aa Clear problems view when a database is removed
This commit fixes the problem whereby a database is removed and the
problems associated with queries run from that database stick around
in the problems view.

Also, once problems are cleared, we need to make sure that we uncheck
the checkbox in the results view.

This commit has several limitations:

1. There is duplicated code for message handling in both results.tsx and
result-tables.tsx.
2. Problems are cleared whenever there is *any* change to any database.
Ideally we should only clear problems when a database is removed and
only problems associated with that database. I'll fix part of this in
a future commit.

Resolves #525
2020-10-08 12:32:27 -07:00
Andrew Eisenberg
c83d1b305e Rename AstItem -> ChildAstItem and RootAstItem -> AstItem
This simplifies some of our type conversions since all ChildAstItem
are AstItem.
2020-10-07 17:48:40 -07:00
Andrew Eisenberg
732eb83d07 Select the appropriate node in the AST viewer when the editor text selection changes
When a user clicks in an editor that whose source tree is currently being displayed in
the ast viewer, the viewer selection will stay in sync with the editor selection.
2020-10-07 17:48:40 -07:00
Andrew Eisenberg
7e5d5922db Update changelog 2020-10-06 08:42:29 -07:00
Andrew Eisenberg
15f38c6f18 Add icons for various query history view commands
And show these commands in the title bar.
2020-10-06 08:42:29 -07:00
Andrew Eisenberg
4adbfa4e81 Update changelog 2020-10-06 08:42:29 -07:00
Andrew Eisenberg
7c10d72117 Adds a message that appears in an empty databases view
Also, fixes a regex.
2020-10-06 08:42:29 -07:00
Andrew Eisenberg
7800c68065 Allow setting number of threads to 0
Fixes #603
2020-10-05 07:54:42 -07:00
Andrew Eisenberg
c4d9eed734 Update error message when there is a missing contextual query
References #476
2020-10-01 14:15:07 -07:00
Andrew Eisenberg
c34c9fae6a Avoid using path.join for sarif uris
These are uris, not paths and always use '/', even on windows.
2020-10-01 07:44:47 -07:00
Andrew Eisenberg
03f1e4ef08 Update changelog 2020-10-01 07:44:47 -07:00
Andrew Eisenberg
06b6a4705a Ensure backslashes are properly escaped in sarif messages
Problem was that we were not globally replaceing `\\` with `\`.

Also, this PR adds some new tests to sarif-utils.ts. In doing so, we
have fixed a small bug in getPathRelativeToSourceLocationPrefix.

Previously, we were uri decoding the sarifRelativeUri. However, this is
no longer correct because the result is another URI and it should
remain encoded if it originally was.

Resolves #585
2020-10-01 07:44:47 -07:00
Andrew Eisenberg
7ca456d6a0 Ensure all fields have labels
Never show an empty string in the results view. This fixes #535 (again).
2020-09-30 11:05:20 -07:00
Jason Reed
5244a1c3b0 Actually refresh the treeview when updating SARIF context value 2020-09-29 15:04:00 -07:00
Jason Reed
f4775954b6 Fix #597. 2020-09-29 15:04:00 -07:00
Andrew Eisenberg
7c48c5f887 Update changelog 2020-09-29 15:03:15 -07:00
Andrew Eisenberg
3e3a31d5e2 Add unit tests for query-results.ts 2020-09-29 15:03:15 -07:00
Andrew Eisenberg
72160a24bd Fix incorrect call to bqrs info when retrieving paginated results
When retrieving paginated results, need to make sure we are getting
page offsets from the correct results file.

Previously, we were incorrectly extracting page offsets from the default
(unsorted) file. With this change, we ensure that we get offsets from
the proper results file when there is a request for a page of results.
2020-09-29 15:03:15 -07:00
Andrew Eisenberg
456c25f617 Fix invalid sort after reloading query results
With this change, we use the stored sort order if it exists
after reloading a query results page.
2020-09-29 15:03:15 -07:00
Andrew Eisenberg
0c571b1942 Fix mocha test running (#600)
PR #591 broke the build.
2020-09-29 16:34:51 -04:00
Andrew Eisenberg
7e4491ac45 Update mocha version (#591)
This fixes a dependabot error on yargs-parser
2020-09-29 09:04:46 -04:00
Andrew Eisenberg
75b5c1d316 Allow max queries to be configurable
Max number of simultaneous queries launchable by runQueries command is
now configurable by codeQL.runningQueries.maxQueries.
2020-09-25 07:54:41 -07:00
Andrew Eisenberg
db6fc5d7f0 Refactor: Change renderLocation in webview
* It is now more general and the logic is simplified
* Also, add more comments
* Rename `adaptBqrs` to `transformBqrsResultSet`
* Remove a react error for missing a key attribute in a list
2020-09-24 07:54:50 -07:00
Andrew Eisenberg
84028434e0 Refactor: Remove duplicated BQRS types
This refactoring combines the types in `bqrs-types.ts` and
`bqrs-cli-types.ts`. Historically, the former was used for BQRS files
parsed by the extension and the latter for BQRS files parsed by the cli.
They describe the same file types, but using different property and type
names.

We have moved to parsing all BQRS files by the cli. This refactoring
removes the `bqrs-types.ts` file and replaces all BQRS references to
use types in `bqrs-cli-types.ts`.

Additionally, the `adapt.ts` file has been deleted since its purpose
was to convert between extension and cli BQRS types. Some one type and
one function from `adapt.ts` has been moved from `adapt.ts` to
`bqrs-types.ts`. It's possible that we want to do a further refactoring
to simply remove them both.
2020-09-24 07:54:50 -07:00
github-actions[bot]
b917a204ba Bump version to v1.3.4 (#580)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2020-09-16 16:35:21 -04:00
jcreedcmu
8a5514c696 Date CHANGELOG for release (#579)
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Build Extension / Build (ubuntu-latest) (push) Has been cancelled
Build Extension / Build (windows-latest) (push) Has been cancelled
Build Extension / Test (ubuntu-latest) (push) Has been cancelled
Build Extension / Test (windows-latest) (push) Has been cancelled
Release / Release (push) Has been cancelled
2020-09-16 16:22:01 -04:00
Andrew Eisenberg
29f92575ee Update npm dependencies fix security vulns
* node-fetch
* bl
2020-09-16 07:57:31 -07:00
Aditya Sharad
5d63431b8c Actions: Pin version of upload-artifact action (#549) 2020-09-08 16:25:18 -07:00
Andrew Eisenberg
17eee86765 Update changelog 2020-09-02 08:16:27 -07:00
Andrew Eisenberg
95d5274fd4 Avoid showing a link when the underlying path is empty
A common situation when a file is not relevant for a particular result
is to return an empty file path location.

Currently, we are displaying this situation as a hyperlink in the
results, but when clicking on the link, there is an error.

To mirror the behaviour of Eclipse, we should avoid showing a link here.
This commit changes that behaviour.
2020-09-02 08:16:27 -07:00
Dave Bartolomeo
959552544a Fix highlighting after disembodied IPA branch
Fixes #543
```ql
newtype TA = TB()

private predicate foo() { any() }
```
Our TextMate grammar didn't realize that the newtype declaration ended after the closing paren of the branch's parameter list, so the `private` modifier was highlighted incorrectly.

It's surprisingly tricky to get TextMate to handle this correctly, so I wound up just treating the IPA declaration head (`newtype TA`), the branch head (`= TB`), the branch parameter list, and the branch body as directly children of the module body. This is kind of hacky, but it does fix the bug without introducing any new cases where we have incorrect highlighting of valid code.
2020-09-01 22:31:16 -07:00
Andrew Eisenberg
16fab7f45d Fix typo 2020-08-26 08:27:11 -07:00
Andrew Eisenberg
cb03da3716 Avoid running query when a user cancels when there are unsaved changes
Fixes #538

Adds a new menu item to cancel a query run when the query is unsaved.

Also, ensures that no warning message is sent to the console.
2020-08-25 07:43:52 -07:00
Andrew Eisenberg
f968f8e2f5 Add a top-level tsconfig.json
The reason to add this is that I am getting misleadings errors in
vscode that this file is missing. By adding this file, I no longer
see these errors.
2020-08-24 10:58:17 -07:00
jcreedcmu
c247292181 Merge pull request #537 from jcreedcmu/jcreed/fix-paginated-sorting
Fix changing page forgetting about sorting
2020-08-14 09:47:46 -04:00
Jason Reed
518e6c14cc Add changelog entry 2020-08-14 08:09:28 -04:00
Jason Reed
37cf525c8e Fix changing page forgetting about sorting 2020-08-14 08:06:31 -04:00
jcreedcmu
1f4e69940d Merge pull request #536 from jcreedcmu/jcreed/fix-none
Fix #535
2020-08-13 11:04:09 -04:00
Jason Reed
72878fb6fd Pass up empty string at this stage 2020-08-13 09:43:04 -04:00
Jason Reed
6b343b4581 Add changelog entry 2020-08-13 08:23:02 -04:00
Jason Reed
b191f68599 Fix #535. 2020-08-13 08:19:55 -04:00
Andrew Eisenberg
ef84d8d362 Update changelog after release
Add a simple perl script that will augment the CHANGELOG with
an [UNRELEASED] section when creating the PR after a release.
2020-08-12 11:33:18 -07:00
github-actions[bot]
ef55d9d4e0 Bump version to v1.3.3 2020-08-12 10:43:21 -07:00
Andrew Eisenberg
ff841950ae Update Chnagelog for v1.3.2
Some checks failed
Code Scanning - CodeQL / codeql (push) Has been cancelled
Build Extension / Build (ubuntu-latest) (push) Has been cancelled
Build Extension / Build (windows-latest) (push) Has been cancelled
Build Extension / Test (ubuntu-latest) (push) Has been cancelled
Build Extension / Test (windows-latest) (push) Has been cancelled
Release / Release (push) Has been cancelled
2020-08-12 10:35:35 -07:00
Andrew Eisenberg
aaf9e1fb9c Update changelog 2020-08-12 10:35:35 -07:00
jcreedcmu
7f885755c2 Merge pull request #529 from jcreedcmu/jcreed/fix-527
Fix sorting of raw results
2020-08-12 12:31:39 -04:00
Jason Reed
8c55e3ef2d Simplify argument passing 2020-08-12 12:25:20 -04:00
Jason Reed
039343efa2 Fix #527. 2020-08-12 12:10:02 -04:00
Jason Reed
d0982f34a4 Defunctionalize updating sort state
This leads to less sharing of codepaths which is a little bad (slightly more
repetition and rendundancy) but a lot good (can independently fix the way
raw results are redisplayed so as to be actually correct).
2020-08-12 12:10:02 -04:00
jcreedcmu
890821b273 Merge pull request #528 from aeisenberg/aeisenberg/ast-changelog
Update changelog to include line about experimental AST Viewer
2020-08-12 11:22:33 -04:00
Andrew Eisenberg
84e2cf7986 Update changelog to include line about experimental AST Viewer 2020-08-12 07:37:08 -07:00
Andrew Eisenberg
648bf4b629 Add a debug flag to allow remote debugging (#524)
With this flag on, it is possible to remote-debug the language server in a java debugger.
2020-08-06 11:08:26 -07:00
Henning Makholm
8ccb7c4fa4 Merge pull request #522 from github/shati-patel-patch-1
Update pull_request_template.md
2020-07-31 21:31:31 +02:00
Shati Patel
73fc37d370 Update pull_request_template.md
The team has been renamed 🙂
2020-07-31 20:27:28 +01:00
Aditya Sharad
0a3d4095b7 Merge pull request #521 from adityasharad/actions/label-issue
Actions: Autolabel issues when opened
2020-07-31 09:40:41 -07:00
Aditya Sharad
32d4deb575 Update label-issue.yml 2020-07-31 08:57:33 -07:00
Aditya Sharad
d2409054e2 Actions: Autolabel issues when opened 2020-07-30 16:59:07 -07:00
jcreedcmu
6ae5cd3ac3 Merge pull request #519 from aeisenberg/aeisenberg/remove-from-changelog
Remove unreleased feature from changelog
2020-07-27 13:05:09 -04:00
Andrew Eisenberg
0dfc64c7e8 Remove unreleased feature from changelog 2020-07-27 09:53:31 -07:00
Andrew Eisenberg
6a9c9a1eb4 Add catch handler for discovery failures
Display a reasonable message to users if there is a failure.
2020-07-27 08:34:03 -07:00
Andrew Eisenberg
f62cce32da Change how we check for relevant ql packs 2020-07-27 08:34:03 -07:00
Andrew Eisenberg
a36ff8ca1e Update changelog 2020-07-27 08:34:03 -07:00
Andrew Eisenberg
0d1199bb64 Filters qltest-discovery
qlpack tests that are not contained within the current workspace folder
will be filtered from the test runner view.

This also fixes a test that should have been failing but wasn't.
2020-07-27 08:34:03 -07:00
jcreedcmu
3edd8ec1d1 Merge pull request #516 from aeisenberg/aeisenberg/refactor-contextual
Refactor contextual queries
2020-07-24 08:49:37 -04:00
jcreedcmu
4a030dc2f4 Merge pull request #514 from aeisenberg/aeisenberg/fix-ast-viewer-0-id
Fix AST viewer bug where nodes with id=0 did not have children
2020-07-24 08:47:55 -04:00
jcreedcmu
a4f19c9b5d Merge pull request #515 from aeisenberg/aeisenberg/launch-no-npx
Remove reference to npx in luanch config
2020-07-24 08:45:14 -04:00
Andrew Eisenberg
353a87de12 Refactor contextual queries
Break the  file into logically contained
smaller files. And add unit tests for .
2020-07-23 15:00:04 -07:00
Andrew Eisenberg
a2cda79ceb Remove reference to npx in luanch config
Users should not need to install npx in order to launch
the extension.
2020-07-23 12:45:08 -07:00
Andrew Eisenberg
bc73712987 Fix AST viewer bug where nodes with id=0 did not have children 2020-07-23 12:43:11 -07:00
Jason Reed
09c4e7e99b Fix broken launch config
We need to provide the `--extensionDevelopmentPath` flag in these
launch configurations.

It appears to be unnecessary to include
`${workspaceRoot}/extensions/ql-vscode/out/vscode-tests/**/*.js`
in addition to the strictly more general pattern
${workspaceRoot}/extensions/ql-vscode/out/**/*.js

An unfortunate UI fact appears to be that the log of the gulp build is
focused whenever these tasks are run, even though the log you actually
care about seeing is in the `Debug Console` section. Not sure how to
fix that.
2020-07-23 12:40:29 -07:00
jcreedcmu
d0e0ad619b Merge pull request #511 from ceh-forks/ceh-skip-log
Suppress database downloaded message when action canceled
2020-07-23 14:02:24 -04:00
Emil Hessman
e4ff8d1fa8 Only focus database panel on successful download 2020-07-23 19:44:36 +02:00
Andrew Eisenberg
9052851f9a Run CodeQL Action on PRs 2020-07-23 10:25:16 -07:00
jcreedcmu
a946965331 Merge pull request #508 from jcreedcmu/jcreed/untangle3
Fix documentation for current build process
2020-07-23 09:43:40 -04:00
Andrew Eisenberg
10177412f6 Merge pull request #492 from aeisenberg/aeisenberg/ast-viewer
Add the AST Viewer
2020-07-23 06:36:11 -07:00
jcreedcmu
4519e0f951 Update CONTRIBUTING.md
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2020-07-23 09:14:37 -04:00
Emil Hessman
0d2b44cdba Suppress database downloaded message when action canceled 2020-07-23 06:40:43 +02:00
Andrew Eisenberg
0045891f9d Clean up ast builder code 2020-07-22 13:34:01 -07:00
Jason Reed
2b712827df Clean up build instructions 2020-07-22 13:05:13 -04:00
Andrew Eisenberg
65b5b68df6 Remove duplicate changelog line 2020-07-21 12:28:50 -07:00
Andrew Eisenberg
f21296e4f6 Merge branch 'aeisenberg/ast-viewer' of github.com:aeisenberg/vscode-codeql into aeisenberg/ast-viewer 2020-07-21 10:10:23 -07:00
Jason Reed
762edd137c Fix CONTRIBUTING.md to reflect changes to build process. 2020-07-21 13:09:44 -04:00
jcreedcmu
b3dc7d75a8 Merge pull request #503 from jcreedcmu/jcreed/untangle2
Try moving build to just gulp
2020-07-21 12:56:34 -04:00
Jason Reed
9ad0bf6f43 Call into package.json scripts from actions workflow 2020-07-21 12:20:17 -04:00
Jason Reed
f8804f946c Use explicit path for vsce 2020-07-21 12:19:03 -04:00
Jason Reed
3c07be5f74 Move type dependency to devDependencies 2020-07-21 12:13:01 -04:00
Jason Reed
cd329eeaeb Fix source maps 2020-07-21 10:09:42 -04:00
Jason Reed
2671414f32 Extract rush from vscode tasks 2020-07-21 09:21:11 -04:00
Andrew Eisenberg
b6bd534857 Fixes pagination when there are no results
When there are no results, always ensure that max pages is 1.

This commit also changes the way pagination buttons are displayed,
removing their border.
2020-07-20 07:11:56 -07:00
Andrew Eisenberg
8093d9a529 Check window event origins
Fixes codescanning warnings:

- https://github.com/github/vscode-codeql/security/code-scanning/1
- https://github.com/github/vscode-codeql/security/code-scanning/2
2020-07-17 10:25:25 -07:00
jcreedcmu
aebab082c2 Merge branch 'main' into aeisenberg/ast-viewer 2020-07-17 10:53:15 -04:00
Andrew Eisenberg
36d612e5b0 Add feature flag for ast viewer
Set `codeQL.experimentalAstViewer` to true in settings
in order for component to be enabled.
2020-07-16 15:42:26 -07:00
Andrew Eisenberg
8459edb57c Fix tests and reformatting
* Fix command-linting tests.
* Fix failing windows test and Use Uri.parse(_, true)
* Use  Uri.parse(_, true). That is the preferred API.
* Reformat comments.
2020-07-16 14:42:48 -07:00
Andrew Eisenberg
af965c941a Update changelog 2020-07-16 14:42:48 -07:00
Andrew Eisenberg
eaa26e5ef7 Add the AST Viewer
This commit adds the AST Viewer for viewing the QL AST of a file in a
database.

The different components are as follows:

1. There is a new view `codeQLAstViewer`, which displays the AST
2. This view is backed by the `AstViewerDataProvider` and `AstViewer` classes in astView.ts
3. To generate an AST, we use contextual queries, similar to how Find references/declarations are implemented. In particular, in `definitions.ts` there is `TemplatePrintAstProvider` which provides an AST for a given source buffer.
  - Similar to the other queries, we first determine which database the buffer belongs to.
  - Based on that, we generate a synthetic qlpack and run the templatized `printAst.ql` query
  - We plug in the archive-relative path name of the source file.
  - After the query is run, we wrap the results in an `AstBuilder` instance.
  - When requested, the `AstBuilder` will generate the full AST of the file from the BQRS results.
  - The AST roots (all top-level elements, functions, variable declarations, etc, are roots) are passed to the `AstViewer` instance, which handles the display lifecycle and other VS Code-specific functions.

There are a few unrelated pieces here, which can be pulled out to another PR if required:

- The `codeQLQueryHistory` view now has a _welcome_ message to make it more obvious to users how to start.
- `definitions.ts` is moved to the `contextual` subfolder.
- `fileRangeFromURI` is extracted from `definitions.ts` to its own file so it can be reused.

Also, note that this relies on https://github.com/github/codeql/pull/3931 for the C/C++ query to be available in the QL sources. Other languages will need similar queries.
2020-07-16 14:42:47 -07:00
Andrew Eisenberg
546ec2eb1c Update changelog 2020-07-16 09:10:05 -07:00
Andrew Eisenberg
565ea0d8a0 Use proper check for existence of search path
Fixes #499
2020-07-16 09:10:05 -07:00
Jason Reed
258f43132c Relax version constraints in package.json 2020-07-16 09:19:07 -04:00
Jason Reed
b7a72b9d21 Remove now unused rush configuration 2020-07-16 09:10:53 -04:00
Jason Reed
d2138907b9 Fix test section of workflow file 2020-07-16 08:51:35 -04:00
Jason Reed
bce3413158 Run npm-installed copy of vsce 2020-07-16 08:49:47 -04:00
Jason Reed
2b53396146 Fix warning 2020-07-16 08:49:07 -04:00
Jason Reed
19a76dcbee Update action to not depend on rush 2020-07-16 08:43:07 -04:00
Jason Reed
56b62ff758 Fix package deploy to not depend on rush 2020-07-16 08:39:17 -04:00
Jason Reed
9083c5d649 Reconcile vscode-engine and api versions 2020-07-16 08:00:37 -04:00
Jason Reed
49c0d39a50 Replace javascript gulpfile with typescript 2020-07-14 13:51:49 -04:00
jcreedcmu
57ea215639 Merge pull request #496 from jcreedcmu/jcreed/untangle
Reduce dependencies on internal modules
2020-07-14 13:03:03 -04:00
Jason Reed
528cbc8d49 Move more config into local typescript gulpfile 2020-07-14 12:52:06 -04:00
Jason Reed
2c5b672c81 Make stub typescript gulpfile 2020-07-14 12:11:54 -04:00
Jason Reed
f0055910c1 Remove typescript-config package 2020-07-14 12:02:51 -04:00
Jason Reed
657df5e07d inline tsconfig inheritance 2020-07-14 11:54:34 -04:00
Jason Reed
53d5c2438a Remove now unused library. 2020-07-14 08:19:45 -04:00
Jason Reed
ac941eb9dd Copy semmle-vscode-utils into extension. 2020-07-14 08:17:30 -04:00
Jason Reed
e5e854822d Remove now-unused libraries. 2020-07-14 08:00:11 -04:00
Jason Reed
868b356588 Sharpen comment slightly. 2020-07-14 07:46:43 -04:00
Jason Reed
2dd841e667 Pacify lint.
Apparently the linter wants a tsconfig file to be able to lint the
compare view typescript. I made the configFile specification in the
webpack.config.ts more specific so that we use the same config
every time during webview build.
2020-07-13 13:04:22 -04:00
Jason Reed
609fea404d Remove extension dependency on semmle-io-node 2020-07-13 12:59:13 -04:00
Jason Reed
24da63fbfa Remove extension dependency on semmle-bqrs 2020-07-13 12:48:55 -04:00
Jason Reed
10156b1f49 Remove semmle-bqrs dependency from test. 2020-07-13 12:46:17 -04:00
Jason Reed
3694fdaecb Make tsconfig.json selection during webpack deterministic.
Without this `configFile` option, ts-loader apparently does not
guarantee a deterministic choice of which of the three `tsconfig.json`
files below `extensions/ql-vscode` actually gets used during webpack.
This leads to very strange behavior as even removing dead code can
change which `tsconfig.json` 'wins the race'. I observed that removing
a dependence on `semmle-bqrs` from `src/view` *tended* to make
`ts-loader` choose `src/compare/view/tsconfig.json` instead.
2020-07-13 12:39:37 -04:00
Jason Reed
4c30374dc3 Extract tryGetResolvableLocation from semmle-bqrs 2020-07-13 11:01:11 -04:00
Jason Reed
26d83b5cef Reduce dependencies on semmle-bqrs.
Eliminate references to types in library semmle-bqrs in favor of a
local copy of those same types in bqrs-types.ts.
2020-07-13 10:56:11 -04:00
Andrew Eisenberg
3639dcb806 Fix tests and reformatting
* Fix command-linting tests.
* Fix failing windows test and Use Uri.parse(_, true)
* Use  Uri.parse(_, true). That is the preferred API.
* Reformat comments.
2020-07-10 08:17:11 -07:00
Andrew Eisenberg
4aa752135d Update changelog 2020-07-10 08:16:40 -07:00
Andrew Eisenberg
80c6ea6eac Add the AST Viewer
This commit adds the AST Viewer for viewing the QL AST of a file in a
database.

The different components are as follows:

1. There is a new view `codeQLAstViewer`, which displays the AST
2. This view is backed by the `AstViewerDataProvider` and `AstViewer` classes in astView.ts
3. To generate an AST, we use contextual queries, similar to how Find references/declarations are implemented. In particular, in `definitions.ts` there is `TemplatePrintAstProvider` which provides an AST for a given source buffer.
  - Similar to the other queries, we first determine which database the buffer belongs to.
  - Based on that, we generate a synthetic qlpack and run the templatized `printAst.ql` query
  - We plug in the archive-relative path name of the source file.
  - After the query is run, we wrap the results in an `AstBuilder` instance.
  - When requested, the `AstBuilder` will generate the full AST of the file from the BQRS results.
  - The AST roots (all top-level elements, functions, variable declarations, etc, are roots) are passed to the `AstViewer` instance, which handles the display lifecycle and other VS Code-specific functions.

There are a few unrelated pieces here, which can be pulled out to another PR if required:

- The `codeQLQueryHistory` view now has a _welcome_ message to make it more obvious to users how to start.
- `definitions.ts` is moved to the `contextual` subfolder.
- `fileRangeFromURI` is extracted from `definitions.ts` to its own file so it can be reused.

Also, note that this relies on https://github.com/github/codeql/pull/3931 for the C/C++ query to be available in the QL sources. Other languages will need similar queries.
2020-07-10 08:16:40 -07:00
jcreedcmu
2243c21afc Merge pull request #494 from jcreedcmu/jcreed/fix-integration-tests
Remove failing integration test
2020-07-10 11:06:41 -04:00
Jason Reed
46bddcd8fa Remove dead code and associated test. 2020-07-10 09:11:08 -04:00
Jason Reed
df5dccc3f6 'Pin' to stable instead 2020-07-10 08:59:23 -04:00
Jason Reed
3207c594e7 Pin to vscode version for integration testing 2020-07-09 18:39:19 -04:00
jcreedcmu
70de59eabd Merge pull request #491 from jcreedcmu/jcreed/cleanup
Remove pagination feature flag
2020-07-08 11:31:23 -04:00
Jason Reed
27dd804731 Fix display of offsets in raw results table 2020-07-08 08:56:42 -04:00
Jason Reed
240e0fbd4e Remove feature flag 2020-07-08 08:56:42 -04:00
Jason Reed
f65caa0d85 Remove ExtensionParsedResultSets type 2020-07-08 08:56:42 -04:00
Jason Reed
e7192eb423 Remove WebviewParsed branch from ParsedResultSets
Also remove dead code downstream from it.
2020-07-08 08:56:42 -04:00
jcreedcmu
06b51326a3 Merge pull request #490 from github/version/bump-to-v1.3.2
Bump version to v1.3.2
2020-07-07 14:44:42 -04:00
github-actions[bot]
82a6ef4844 Bump version to v1.3.2 2020-07-07 18:36:48 +00:00
354 changed files with 70429 additions and 15703 deletions

View File

@@ -10,7 +10,12 @@ assignees: ''
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
**Version**
The CodeQL and VS Code version in which the bug occurs.
<!-- To copy version information for the CodeQL extension, click "CodeQL CLI vX.X.X" in the status bar at the bottom of the screen.
To copy detailed version information for VS Code itself, see https://code.visualstudio.com/docs/supporting/FAQ#_how-do-i-find-the-version. -->
**To reproduce**
Steps to reproduce the behavior.
**Expected behavior**

View File

@@ -1,18 +0,0 @@
---
name: New extension release
about: Create an issue with a checklist for the release steps (write access required
for the steps)
title: Release Checklist for version xx.xx.xx
labels: ''
assignees: ''
---
- [ ] Update this issue title to refer to the version of the release
- [ ] Trigger a release build on Actions by adding a new tag on branch `main` of the format `vxx.xx.xx`
- [ ] Monitor the status of the release build in the `Release` workflow in the Actions tab.
- [ ] Download the VSIX from the draft GitHub release that is created when the release build finishes.
- [ ] Log into the [Visual Studio Marketplace](https://marketplace.visualstudio.com/manage/publishers/github).
- [ ] Click the `...` menu in the CodeQL row and click **Update**.
- [ ] Drag the `.vsix` file you downloaded from the GitHub release into the Marketplace and click **Upload**.
- [ ] Publish the draft GitHub release and confirm the new release is marked as the latest release at https://github.com/github/vscode-codeql/releases.

12
.github/codeql/codeql-config.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
name: "CodeQL config"
queries:
- name: Run standard queries
uses: security-and-quality
- name: Run custom javascript queries
uses: ./.github/codeql/queries
paths:
- ./extensions/ql-vscode
paths-ignore:
- '**/node_modules'
- '**/build'
- '**/out'

21
.github/codeql/queries/assert-pure.ql vendored Normal file
View File

@@ -0,0 +1,21 @@
/**
* @name Unwanted dependency on vscode API
* @kind problem
* @problem.severity error
* @id vscode-codeql/assert-pure
* @description The modules stored under `pure` and tested in the `pure-tests`
* are intended to be "pure".
*/
import javascript
class VSCodeImport extends ASTNode {
VSCodeImport() {
this.(Import).getImportedPath().getValue() = "vscode"
}
}
from Module m, VSCodeImport v
where
m.getFile().getRelativePath().regexpMatch(".*src/pure/.*") and
m.getAnImportedModule*().getAnImport() = v
select m, "This module is not pure: it has a transitive dependency on the vscode API imported $@", v, "here"

3
.github/codeql/queries/qlpack.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
name: vscode-codeql-custom-queries-javascript
version: 0.0.0
libraryPathDependencies: codeql-javascript

22
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "extensions/ql-vscode"
schedule:
interval: "weekly"
day: "thursday" # Thursday is arbitrary
labels:
- "Update dependencies"
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-minor", "version-update:semver-patch"]
- package-ecosystem: "github-actions"
directory: ".github"
schedule:
interval: "weekly"
day: "thursday" # Thursday is arbitrary
labels:
- "Update dependencies"
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-minor", "version-update:semver-patch"]

View File

@@ -9,4 +9,4 @@ Replace this with a description of the changes your pull request makes.
- [ ] [CHANGELOG.md](https://github.com/github/vscode-codeql/blob/main/extensions/ql-vscode/CHANGELOG.md) has been updated to incorporate all user visible changes made by this pull request.
- [ ] Issues have been created for any UI or other user-facing changes made by this pull request.
- [ ] `@github/product-docs-dsp` has been cc'd in all issues for UI or other user-facing changes made by this pull request.
- [ ] _[Maintainers only]_ If this pull request makes user-facing changes that require documentation changes, open a corresponding docs pull request in the [github/codeql](https://github.com/github/codeql/tree/main/docs/codeql/codeql-for-visual-studio-code) repo and add the `ready-for-doc-review` label there.

View File

@@ -2,20 +2,31 @@ name: "Code Scanning - CodeQL"
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 0 * * 0'
- cron: '21 17 * * 0'
jobs:
codeql:
strategy:
fail-fast: false
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
pull-requests: read
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
uses: github/codeql-action/init@main
with:
languages: javascript
config-file: ./.github/codeql/codeql-config.yml
tools: latest
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
uses: github/codeql-action/analyze@main

16
.github/workflows/dependency-review.yml vendored Normal file
View File

@@ -0,0 +1,16 @@
name: 'Dependency Review'
on:
- pull_request
- workflow_dispatch
permissions:
contents: read
jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- name: 'Checkout Repository'
uses: actions/checkout@v3
- name: 'Dependency Review'
uses: actions/dependency-review-action@v1

15
.github/workflows/label-issue.yml vendored Normal file
View File

@@ -0,0 +1,15 @@
name: Label issue
on:
issues:
types: [opened]
jobs:
label:
name: Label issue
runs-on: ubuntu-latest
steps:
- name: Label issue
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
echo '{"labels": ["VSCode"]}' | gh api repos/${{ github.repository }}/issues/${{ github.event.issue.number }}/labels --input -

View File

@@ -1,5 +1,11 @@
name: Build Extension
on: [push, pull_request]
on:
workflow_dispatch:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
push:
branches:
- main
jobs:
build:
@@ -16,14 +22,20 @@ jobs:
- uses: actions/setup-node@v1
with:
node-version: '10.18.1'
node-version: '16.13.0'
- name: Install dependencies
run: node common/scripts/install-run-rush.js install
working-directory: extensions/ql-vscode
run: |
npm install
shell: bash
- name: Build
run: node common/scripts/install-run-rush.js build
working-directory: extensions/ql-vscode
env:
APP_INSIGHTS_KEY: '${{ secrets.APP_INSIGHTS_KEY }}'
run: |
npm run build
shell: bash
- name: Prepare artifacts
@@ -33,15 +45,32 @@ jobs:
cp dist/*.vsix artifacts
- name: Upload artifacts
uses: actions/upload-artifact@master
uses: actions/upload-artifact@v2
if: matrix.os == 'ubuntu-latest'
with:
name: vscode-codeql-extension
path: artifacts
find-nightly:
name: Find Nightly Release
runs-on: ubuntu-latest
outputs:
url: ${{ steps.get-url.outputs.nightly-url }}
steps:
- 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: |
LATEST=`gh api repos/dsp-testing/codeql-cli-nightlies/releases --jq '.[].tag_name' --method GET --raw-field 'per_page=1'`
echo "::set-output name=nightly-url::https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/$LATEST"
test:
name: Test
runs-on: ${{ matrix.os }}
needs: [find-nightly]
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
@@ -53,53 +82,115 @@ jobs:
- uses: actions/setup-node@v1
with:
node-version: '10.18.1'
node-version: '16.13.0'
# We have to build the dependencies in `lib` before running any tests.
- name: Install dependencies
run: node common/scripts/install-run-rush.js install
working-directory: extensions/ql-vscode
run: |
npm install
shell: bash
- name: Build
run: node common/scripts/install-run-rush.js build
working-directory: extensions/ql-vscode
env:
APP_INSIGHTS_KEY: '${{ secrets.APP_INSIGHTS_KEY }}'
run: |
npm run build
shell: bash
- name: Lint
working-directory: extensions/ql-vscode
run: |
cd extensions/ql-vscode
npm run lint
- name: Install CodeQL
run: |
mkdir codeql-home
curl -L --silent https://github.com/github/codeql-cli-binaries/releases/latest/download/codeql.zip -o codeql-home/codeql.zip
unzip -q -o codeql-home/codeql.zip -d codeql-home
unzip -q -o codeql-home/codeql.zip codeql/codeql.exe -d codeql-home
rm codeql-home/codeql.zip
shell: bash
- name: Run unit tests (Linux)
working-directory: extensions/ql-vscode
if: matrix.os == 'ubuntu-latest'
run: |
cd extensions/ql-vscode
CODEQL_PATH=$GITHUB_WORKSPACE/codeql-home/codeql/codeql npm run test
npm run test
- name: Run unit tests (Windows)
if: matrix.os == 'windows-latest'
working-directory: extensions/ql-vscode
run: |
cd extensions/ql-vscode
$env:CODEQL_PATH=$(Join-Path $env:GITHUB_WORKSPACE -ChildPath 'codeql-home/codeql/codeql.exe')
npm run test
- name: Run integration tests (Linux)
if: matrix.os == 'ubuntu-latest'
working-directory: extensions/ql-vscode
run: |
cd extensions/ql-vscode
sudo apt-get install xvfb
/usr/bin/xvfb-run npm run integration
- name: Run integration tests (Windows)
if: matrix.os == 'windows-latest'
working-directory: extensions/ql-vscode
run: |
cd extensions/ql-vscode
npm run integration
cli-test:
name: CLI Test
runs-on: ${{ matrix.os }}
needs: [find-nightly]
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
version: ['v2.3.3', 'v2.4.6', 'v2.5.9', 'v2.6.3', 'v2.7.6', 'v2.8.5', 'v2.9.2', 'nightly']
env:
CLI_VERSION: ${{ matrix.version }}
NIGHTLY_URL: ${{ needs.find-nightly.outputs.url }}
TEST_CODEQL_PATH: '${{ github.workspace }}/codeql'
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: '16.13.0'
- name: Install dependencies
working-directory: extensions/ql-vscode
run: |
npm install
shell: bash
- name: Build
working-directory: extensions/ql-vscode
run: |
npm run build
shell: bash
- name: Decide on ref of CodeQL repo
id: choose-ref
shell: bash
run: |
if [[ "${{ matrix.version }}" == "nightly" ]]
then
REF="codeql-cli/latest"
elif [[ "${{ matrix.version }}" == "v2.2.6" || "${{ matrix.version }}" == "v2.3.3" ]]
then
REF="codeql-cli/v2.4.5"
else
REF="codeql-cli/${{ matrix.version }}"
fi
echo "::set-output name=ref::$REF"
- name: Checkout QL
uses: actions/checkout@v2
with:
repository: github/codeql
ref: ${{ steps.choose-ref.outputs.ref }}
path: codeql
- name: Run CLI tests (Linux)
working-directory: extensions/ql-vscode
if: matrix.os == 'ubuntu-latest'
run: |
/usr/bin/xvfb-run npm run cli-integration
- name: Run CLI tests (Windows)
working-directory: extensions/ql-vscode
if: matrix.os == 'windows-latest'
run: |
npm run cli-integration

View File

@@ -6,39 +6,37 @@
name: Release
on:
workflow_dispatch:
push:
# Path filters are not evaluated for pushes to tags.
# (source: https://help.github.com/en/github/automating-your-workflow-with-github-actions/workflow-syntax-for-github-actions#onpushpull_requestpaths)
# So this workflow is triggered in the following events:
# - Release event: a SemVer tag, e.g. v1.0.0 or v1.0.0-alpha, is pushed
tags:
- 'v[0-9]+.[0-9]+.[0-9]+*'
# OR
# - Test event: this file is modified on a branch in the main repo containing `/actions/` in the name.
branches:
- '**/actions/**'
paths:
- '**/workflows/release.yml'
jobs:
build:
name: Release
runs-on: ubuntu-latest
# TODO Share steps with the main workflow.
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: '10.18.1'
node-version: '16.13.0'
- name: Install dependencies
run: node common/scripts/install-run-rush.js install
run: |
cd extensions/ql-vscode
npm ci
shell: bash
- name: Build
run: node common/scripts/install-run-rush.js build --release
env:
APP_INSIGHTS_KEY: '${{ secrets.APP_INSIGHTS_KEY }}'
run: |
echo "APP INSIGHTS KEY LENGTH: ${#APP_INSIGHTS_KEY}"
cd extensions/ql-vscode
npm run build -- --release
shell: bash
- name: Prepare artifacts
@@ -55,11 +53,8 @@ jobs:
REF_NAME="$(echo ${{ github.ref }} | sed -e 's:^refs/tags/::' | sed -e 's:/:-:g')"
echo "::set-output name=ref_name::$REF_NAME"
# Uploading artifacts is not necessary to create a release.
# This is just in case the release itself fails and we want to access the built artifacts from Actions.
# TODO Remove if not useful.
- name: Upload artifacts
uses: actions/upload-artifact@master
uses: actions/upload-artifact@v2
with:
name: vscode-codeql-extension
path: artifacts
@@ -93,6 +88,10 @@ jobs:
asset_name: ${{ format('vscode-codeql-{0}.vsix', steps.prepare-artifacts.outputs.ref_name) }}
asset_content_type: application/zip
###
# Do Post release work: version bump and changelog PR
# Only do this if we are running from a PR (ie- this is part of the release process)
# The checkout action does not fetch the main branch.
# Fetch the main branch so that we can base the version bump PR against main.
- name: Fetch main branch
@@ -110,8 +109,14 @@ jobs:
NEXT_VERSION="$(npm version patch)"
echo "::set-output name=next_version::$NEXT_VERSION"
- name: Add changelog for next release
if: success()
run: |
cd extensions/ql-vscode
perl -i -pe 's/^/## \[UNRELEASED\]\n\n/ if($.==3)' CHANGELOG.md
- name: Create version bump PR
uses: peter-evans/create-pull-request@c7b64af0a489eae91f7890f2c1b63d13cc2d8ab7 # v2.4.2
uses: peter-evans/create-pull-request@c7f493a8000b8aeb17a1332e326ba76b57cb83eb # v3.4.1
if: success()
with:
token: ${{ secrets.GITHUB_TOKEN }}
@@ -120,3 +125,41 @@ jobs:
body: This PR was automatically generated by the GitHub Actions release workflow in this repository.
branch: ${{ format('version/bump-to-{0}', steps.bump-patch-version.outputs.next_version) }}
base: main
draft: true
vscode-publish:
name: Publish to VS Code Marketplace
needs: build
environment: publish-vscode-marketplace
runs-on: ubuntu-latest
env:
VSCE_TOKEN: ${{ secrets.VSCE_TOKEN }}
steps:
- name: Download artifact
uses: actions/download-artifact@v2
with:
name: vscode-codeql-extension
- name: Publish to Registry
run: |
npx vsce publish -p $VSCE_TOKEN --packagePath *.vsix || \
echo "Failed to publish to VS Code Marketplace. \
If this was an authentication problem, please make sure the \
auth token hasn't expired."
open-vsx-publish:
name: Publish to Open VSX Registry
needs: build
environment: publish-open-vsx
runs-on: ubuntu-latest
env:
OPEN_VSX_TOKEN: ${{ secrets.OPEN_VSX_TOKEN }}
steps:
- name: Download artifact
uses: actions/download-artifact@v2
with:
name: vscode-codeql-extension
- name: Publish to Registry
run: |
npx ovsx publish -p $OPEN_VSX_TOKEN *.vsix

1
.gitignore vendored
View File

@@ -4,6 +4,7 @@
# Generated files
/dist/
out/
build/
server/
node_modules/
gen/

View File

@@ -1,9 +1,9 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"eamodio.tsl-problem-matcher",
"amodio.tsl-problem-matcher",
"dbaeumer.vscode-eslint",
"eternalphane.tsfmt-vscode"
],

84
.vscode/launch.json vendored
View File

@@ -8,18 +8,22 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}/dist/vscode-codeql"
"--extensionDevelopmentPath=${workspaceRoot}/extensions/ql-vscode",
// Add a reference to a workspace to open. Eg-
// "${workspaceRoot}/../vscode-codeql-starter/vscode-codeql-starter.code-workspace"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/dist/vscode-codeql/out/**/*.js",
"${workspaceRoot}/dist/vscode-codeql/node_modules/semmle-bqrs/out/**/*.js",
"${workspaceRoot}/dist/vscode-codeql/node_modules/semmle-io/out/**/*.js",
"${workspaceRoot}/dist/vscode-codeql/node_modules/semmle-io-node/out/**/*.js",
"${workspaceRoot}/dist/vscode-codeql/node_modules/@github/codeql-vscode-utils/out/**/*.js"
"${workspaceRoot}/extensions/ql-vscode/out/**/*.js",
],
"preLaunchTask": "Build"
"env": {
// change to 'true' debug the IDE or Query servers
"IDE_SERVER_JAVA_DEBUG": "false",
"QUERY_SERVER_JAVA_DEBUG": "false",
"CLI_SERVER_JAVA_DEBUG": "false",
// Uncomment to set the JAVA_HOME for the codeql instance to use
// "CODEQL_JAVA_HOME": "/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home"
}
},
{
"name": "Launch Unit Tests (vscode-codeql)",
@@ -41,10 +45,8 @@
"ts-node/register",
"test/pure-tests/**/*.ts"
],
"port": 9229,
"stopOnEntry": false,
"sourceMaps": true,
"preLaunchTask": "Build",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
@@ -54,16 +56,16 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}/dist/vscode-codeql",
"--extensionTestsPath=${workspaceRoot}/extensions/ql-vscode/out/vscode-tests/no-workspace/index"
"--extensionDevelopmentPath=${workspaceRoot}/extensions/ql-vscode",
"--extensionTestsPath=${workspaceRoot}/extensions/ql-vscode/out/vscode-tests/no-workspace/index",
"--disable-workspace-trust",
"--disable-extensions",
"--disable-gpu"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/dist/vscode-codeql/out/**/*.js",
"${workspaceRoot}/extensions/ql-vscode/out/vscode-tests/**/*.js"
"${workspaceRoot}/extensions/ql-vscode/out/**/*.js",
],
"preLaunchTask": "Build"
},
{
"name": "Launch Integration Tests - Minimal Workspace (vscode-codeql)",
@@ -71,17 +73,57 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}/dist/vscode-codeql",
"--extensionDevelopmentPath=${workspaceRoot}/extensions/ql-vscode",
"--extensionTestsPath=${workspaceRoot}/extensions/ql-vscode/out/vscode-tests/minimal-workspace/index",
"--disable-workspace-trust",
"--disable-extensions",
"--disable-gpu",
"${workspaceRoot}/extensions/ql-vscode/test/data"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/dist/vscode-codeql/out/**/*.js",
"${workspaceRoot}/extensions/ql-vscode/out/vscode-tests/**/*.js"
"${workspaceRoot}/extensions/ql-vscode/out/**/*.js",
],
},
{
"name": "Launch Integration Tests - With CLI",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}/extensions/ql-vscode",
"--extensionTestsPath=${workspaceRoot}/extensions/ql-vscode/out/vscode-tests/cli-integration/index",
"--disable-workspace-trust",
"--disable-gpu",
"--disable-extension",
"eamodio.gitlens",
"--disable-extension",
"github.codespaces",
"--disable-extension",
"github.copilot",
"${workspaceRoot}/extensions/ql-vscode/src/vscode-tests/cli-integration/data",
// Uncomment the last line and modify the path to a checked out
// instance of the codeql repository so the libraries are
// available in the workspace for the tests.
// "${workspaceRoot}/../codeql"
],
"env": {
// Optionally, set the version to use for the integration tests.
// Use "nightly" to use the latest nightly build.
// "CLI_VERSION": "2.7.0",
// If CLI_VERSION is set to nightly, set this to the url of the nightly build.
// "NIGHTLY_URL": "some url to grab the nightly build",
// Optionally, add a path to the codeql executable to be used during these tests.
// If not specified, one will be downloaded automatically.
// This option overrides the CLI_VERSION option.
// "CLI_PATH": "${workspaceRoot}/../semmle-code/target/intree/codeql/codeql",
},
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/extensions/ql-vscode/out/**/*.js",
],
"preLaunchTask": "Build"
}
]
}

View File

@@ -22,7 +22,8 @@
"common/temp": true,
"**/.vscode-test": true
},
"typescript.tsdk": "./common/temp/node_modules/typescript/lib", // we want to use the TS server from our node_modules folder to control its version
"typescript.tsdk": "./extensions/ql-vscode/node_modules/typescript/lib", // we want to use the TS server from our node_modules folder to control its version
"typescript.enablePromptUseWorkspaceTsdk": true,
"eslint.validate": [
"javascript",
"javascriptreact",

66
.vscode/tasks.json vendored
View File

@@ -10,7 +10,10 @@
"kind": "build",
"isDefault": true
},
"command": "node common/scripts/install-run-rush.js build --verbose",
"command": "npm run build",
"options": {
"cwd": "extensions/ql-vscode/"
},
"presentation": {
"echo": true,
"reveal": "always",
@@ -33,64 +36,13 @@
"$ts-webpack"
]
},
{
"label": "Rebuild",
"type": "shell",
"group": "build",
"command": "node common/scripts/install-run-rush.js rebuild --verbose",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": true
},
"problemMatcher": [
{
"owner": "typescript",
"fileLocation": "absolute",
"pattern": {
"regexp": "^\\[gulp-typescript\\] ([^(]+)\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\): error TS\\d+: (.*)$",
"file": 1,
"location": 2,
"message": 3
}
}
]
},
{
"label": "Update",
"type": "shell",
"command": "node common/scripts/install-run-rush.js update",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": true
},
"problemMatcher": []
},
{
"label": "Update (full)",
"type": "shell",
"command": "node common/scripts/install-run-rush.js update --full",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": true
},
"problemMatcher": []
},
{
"label": "Format",
"type": "shell",
"command": "node common/scripts/install-run-rush.js format",
"command": "npm run format",
"options": {
"cwd": "extensions/ql-vscode/"
},
"presentation": {
"echo": true,
"reveal": "always",
@@ -111,4 +63,4 @@
"group": "build"
}
]
}
}

2
CODEOWNERS Normal file
View File

@@ -0,0 +1,2 @@
**/* @github/codeql-vscode-reviewers
/extensions/ql-vscode/src/remote-queries/ @github/code-scanning-secexp-reviewers

View File

@@ -25,94 +25,39 @@ Here are a few things you can do that will increase the likelihood of your pull
* Follow the [style guide][style].
* Write tests. Tests that don't require the VS Code API are located [here](extensions/ql-vscode/test). Integration tests that do require the VS Code API are located [here](extensions/ql-vscode/src/vscode-tests).
* Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
* Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
* Write a [good commit message](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
## Setting up a local build
Make sure you have a fairly recent version of vscode (>1.32) and are using nodejs
version >=v10.13.0. (Tested on v10.15.1 and v10.16.0).
Make sure you have installed recent versions of vscode (>= v1.52), node (>=12.16), and npm (>= 7.5.2). Earlier versions will probably work, but we no longer test against them.
This repo uses [Rush](https://rushjs.io) to handle package management, building, and other
operations across multiple projects. See the Rush "[Getting started as a developer](https://rushjs.io/pages/developer/new_developer/)" docs
for more details.
### Installing all packages
If you plan on building from the command line, it's easiest if Rush is installed globally:
From the command line, go to the directory `extensions/ql-vscode` and run
```shell
npm install -g @microsoft/rush
npm install
```
To get started, run:
### Building the extension
From the command line, go to the directory `extensions/ql-vscode` and run
```shell
rush update && rush build
npm run build
npm run watch
```
Note that when you run the `rush` command from the globally installed version, it will examine the
`rushVersion` property in the repo's `rush.json`, and if it differs from the globally installed
version, it will download, cache, and run the version of Rush specified in the `rushVersion`
property.
Alternatively, you can build the extension within VS Code via `Terminal > Run Build Task...` (or `Ctrl+Shift+B` with the default key bindings). And you can run the watch command via `Terminal > Run Task` and then select `npm watch` from the menu.
A few more things to know about using rush:
Before running any of the launch commands, be sure to have run the `build` command to ensure that the JavaScript is compiled and the resources are copied to the proper location.
* Avoid running `npm` for any commands that install/link dependencies
* Instead use the *rush* equivalent: `rush add <package>`, `rush update`, etc.
* If you plan on only building via VS Code tasks, you don't need Rush installed at all, since those
tasks run `common/scripts/install-run-rush.js` to bootstrap a locally installed and cached copy of
Rush.
We recommend that you keep `npm run watch` running in the backgound and you only need to re-run `npm run build` in the following situations:
### Building
1. on first checkout
2. whenever any of the non-TypeScript resources have changed
#### Installing all packages (instead of `npm install`)
After updating any `package.json` file, or after checking or pulling a new branch, you need to
make sure all the right npm packages are installed, which you would normally do via `npm install` in
a single-project repo. With Rush, you need to do an "update" instead:
##### From VS Code
`Terminal > Run Task... > Update`
##### From the command line
```shell
rush update
```
#### Building all projects (instead of `gulp`)
Rush builds all projects in the repo, in dependency order, building multiple projects in parallel
where possible. By default, the build also packages the extension itself into a .vsix file in the
`dist` directory. To build:
##### From VS Code
`Terminal > Run Build Task...` (or just `Ctrl+Shift+B` with the default key bindings)
##### From the command line
```shell
rush build --verbose
```
#### Forcing a clean build
Rush does a reasonable job of detecting on its own which projects need to be rebuilt, but if you need to
force a full rebuild of all projects:
##### From VS Code
`Terminal > Run Task... > Rebuild`
##### From the command line
```shell
rush rebuild --verbose
```
Note that `rush rebuild` performs a complete rebuild, whereas `rush build` performs an incremental build and in many cases will not need to do anything at all.
### Installing
### Installing the extension
You can install the `.vsix` file from within VS Code itself, from the Extensions container in the sidebar:
@@ -130,11 +75,11 @@ $ vscode/scripts/code-cli.sh --install-extension dist/vscode-codeql-*.vsix # if
You can use VS Code to debug the extension without explicitly installing it. Just open this directory as a workspace in VS Code, and hit `F5` to start a debugging session.
### Running the unit/integration tests
### Running the unit tests and integration tests that do not require a CLI instance
Ensure the `CODEQL_PATH` environment variable is set to point to the `codeql` cli executable.
Unit tests and many integration tests do not require a copy of the CodeQL CLI.
Outside of vscode, run:
Outside of vscode, in the `extensions/ql-vscode` directory, run:
```shell
npm run test && npm run integration
@@ -142,26 +87,63 @@ npm run test && npm run integration
Alternatively, you can run the tests inside of vscode. There are several vscode launch configurations defined that run the unit and integration tests. They can all be found in the debug view.
Only the _With CLI_ tests require a CLI instance to run. See below on how to do that.
Running from a terminal, you _must_ set the `TEST_CODEQL_PATH` variable to point to a checkout of the `github/codeql` repository. The appropriate CLI version will be downloaded as part of the test.
### Running the integration tests
The _Launch Integration Tests - With CLI_ tests require a CLI instance in order to run. There are several environment variables you can use to configure this.
From inside of VSCode, open the `launch.json` file and in the _Launch Integration Tests - With CLI_ uncomment and change the environment variables appropriate for your purpose.
## Releasing (write access required)
1. Double-check the `CHANGELOG.md` contains all desired change comments
and has the version to be released with date at the top.
1. Double-check that the extension `package.json` has the version you intend to release.
If you are doing a patch release (as opposed to minor or major version) this should already
be correct.
1. Trigger a release build on Actions by adding a new tag on branch `main` of the format `vxx.xx.xx`
1. Double-check the `CHANGELOG.md` contains all desired change comments and has the version to be released with date at the top.
* Go through all recent PRs and make sure they are properly accounted for.
* Make sure all changelog entries have links back to their PR(s) if appropriate.
1. Double-check that the extension `package.json` and `package-lock.json` have the version you intend to release. If you are doing a patch release (as opposed to minor or major version) this should already be correct.
1. Create a PR for this release:
* This PR will contain any missing bits from steps 1 and 2. Most of the time, this will just be updating `CHANGELOG.md` with today's date.
* Create a new branch for the release named after the new version. For example: `v1.3.6`
* Create a new commit with a message the same as the branch name.
* Create a PR for this branch.
* Wait for the PR to be merged into `main`
1. Trigger a release build on Actions by adding a new tag on branch `main` named after the release, as above. Note that when you push to upstream, you will need to fully qualify the ref. A command like this will work:
```bash
git push upstream refs/tags/v1.3.6
```
* **IMPORTANT** Make sure you are on the `main` branch and your local checkout is fully updated when you add the tag.
* If you accidentally add the tag to the wrong ref, you can just force push it to the right one later.
1. Monitor the status of the release build in the `Release` workflow in the Actions tab.
1. Download the VSIX from the draft GitHub release at the top of [the releases page](https://github.com/github/vscode-codeql/releases) that is created when the release build finishes.
1. Optionally unzip the `.vsix` and inspect its `package.json` to make sure the version is what you expect,
1. Unzip the `.vsix` and inspect its `package.json` to make sure the version is what you expect,
or look at the source if there's any doubt the right code is being shipped.
1. Log into the [Visual Studio Marketplace](https://marketplace.visualstudio.com/manage/publishers/github).
1. Click the `...` menu in the CodeQL row and click **Update**.
1. Drag the `.vsix` file you downloaded from the GitHub release into the Marketplace and click **Upload**.
1. Go to the draft GitHub release, click 'Edit', add some summary description, and publish it.
1. Install the `.vsix` file into your vscode IDE and ensure the extension can load properly. Run a single command (like run query, or add database).
1. Go to the actions tab of the vscode-codeql repository and select the [Release workflow](https://github.com/github/vscode-codeql/actions?query=workflow%3ARelease).
- If there is an authentication failure when publishing, be sure to check that the authentication keys haven't expired. See below.
1. Approve the deployments of the correct Release workflow. This will automatically publish to Open VSX and VS Code Marketplace.
1. Go to the draft GitHub release in [the releases tab of the repository](https://github.com/github/vscode-codeql/releases), click 'Edit', add some summary description, and publish it.
1. Confirm the new release is marked as the latest release at <https://github.com/github/vscode-codeql/releases>.
1. If documentation changes need to be published, notify documentation team that release has been made.
1. Review and merge the version bump PR that is automatically created by Actions.
## Secrets and authentication for publishing
Repository administrators, will need to manage the authentication keys for publishing to the VS Code marketplace and Open VSX. Each requires an authentication token. The VS Code marketplace token expires yearly.
To regenerate the Open VSX token:
1. Log in to the [user settings page on Open VSX](https://open-vsx.org/user-settings/namespaces).
1. Make sure you are a member of the GitHub namespace.
1. Go to the [Access Tokens](https://open-vsx.org/user-settings/tokens) page and generate a new token.
1. Update the secret in the `publish-open-vsx` environment in the project settings.
To regenerate the VSCode Marketplace token, please see our internal documentation. Note that Azure DevOps PATs expire every 90 days and must be regenerated.
## Resources
* [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)

View File

@@ -16,7 +16,6 @@ To see what has changed in the last few versions of the extension, see the [Chan
* Provides an easy way to run queries from the large, open source repository of [CodeQL security queries](https://github.com/github/codeql).
* Adds IntelliSense to support you writing and editing your own CodeQL query and library files.
## Project goals and scope
This project will track new feature development in CodeQL and, whenever appropriate, bring that functionality to the Visual Studio Code experience.

View File

@@ -1,28 +0,0 @@
This directory contains content from https://github.com/microsoft/rushstack,
used under the MIT license as follows.
See https://github.com/microsoft/rushstack/blob/master/stack/rush-stack/LICENSE.
@microsoft/rush-stack
Copyright (c) Microsoft Corporation. All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,12 +0,0 @@
# Rush uses this file to configure the package registry, regardless of whether the
# package manager is PNPM, NPM, or Yarn. Prior to invoking the package manager,
# Rush will always copy this file to the folder where installation is performed.
# When NPM is the package manager, Rush works around NPM's processing of
# undefined environment variables by deleting any lines that reference undefined
# environment variables.
#
# DO NOT SPECIFY AUTHENTICATION CREDENTIALS IN THIS FILE. It should only be used
# to configure registry sources.
registry=https://registry.npmjs.org/
always-auth=false

View File

@@ -1,32 +0,0 @@
/**
* This configuration file defines custom commands for the "rush" command-line.
* For full documentation, please see https://rushjs.io/pages/configs/command_line_json/
*/
{
"$schema": "https://developer.microsoft.com/json-schemas/rush/v5/command-line.schema.json",
"commands": [
{
"commandKind": "bulk",
"name": "format",
"summary": "Reformat source code in all projects",
"description": "Runs the `format` npm task in each project, if present.",
"safeForSimultaneousRushProcesses": false,
"enableParallelism": true,
"ignoreDependencyOrder": true,
"ignoreMissingScript": true,
"allowWarningsInSuccessfulBuild": false
}
],
"parameters": [
{
"parameterKind": "flag",
"longName": "--release",
"shortName": "-r",
"description": "Perform a release build",
"associatedCommands": [
"build",
"rebuild"
],
}
]
}

View File

@@ -1,43 +0,0 @@
/**
* This configuration file specifies NPM dependency version selections that affect all projects
* in a Rush repo. For full documentation, please see https://rushjs.io
*/
{
"$schema": "https://developer.microsoft.com/json-schemas/rush/v5/common-versions.schema.json",
/**
* A table that specifies a "preferred version" for a dependency package. The "preferred version"
* is typically used to hold an indirect dependency back to a specific version, however generally
* it can be any SemVer range specifier (e.g. "~1.2.3"), and it will narrow any (compatible)
* SemVer range specifier. See the Rush documentation for details about this feature.
*/
"preferredVersions": {
/**
* When someone asks for "^1.0.0" make sure they get "1.2.3" when working in this repo,
* instead of the latest version.
*/
// "some-library": "1.2.3"
},
/**
* The "rush check" command can be used to enforce that every project in the repo must specify
* the same SemVer range for a given dependency. However, sometimes exceptions are needed.
* The allowedAlternativeVersions table allows you to list other SemVer ranges that will be
* accepted by "rush check" for a given dependency.
*
* IMPORTANT: THIS TABLE IS FOR *ADDITIONAL* VERSION RANGES THAT ARE ALTERNATIVES TO THE
* USUAL VERSION (WHICH IS INFERRED BY LOOKING AT ALL PROJECTS IN THE REPO).
* This design avoids unnecessary churn in this file.
*/
"allowedAlternativeVersions": {
/**
* For example, allow some projects to use an older TypeScript compiler
* (in addition to whatever "usual" version is being used by other projects in the repo):
*/
// "typescript": [
// "~2.4.0"
// ]
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,32 +0,0 @@
"use strict";
/**
* When using the PNPM package manager, you can use pnpmfile.js to workaround
* dependencies that have mistakes in their package.json file. (This feature is
* functionally similar to Yarn's "resolutions".)
*
* For details, see the PNPM documentation:
* https://pnpm.js.org/docs/en/hooks.html
*
* IMPORTANT: SINCE THIS FILE CONTAINS EXECUTABLE CODE, MODIFYING IT IS LIKELY
* TO INVALIDATE ANY CACHED DEPENDENCY ANALYSIS. We recommend to run "rush update --full"
* after any modification to pnpmfile.js.
*
*/
module.exports = {
hooks: {
readPackage
}
};
/**
* This hook is invoked during installation before a package's dependencies
* are selected.
* The `packageJson` parameter is the deserialized package.json
* contents for the package that is about to be installed.
* The `context` parameter provides a log() function.
* The return value is the updated object.
*/
function readPackage(packageJson, context) {
return packageJson;
}

View File

@@ -1,10 +0,0 @@
/**
* This is configuration file is used for advanced publishing configurations with Rush.
* For full documentation, please see https://rushjs.io/pages/configs/version_policies_json/
*/
[
{
"definitionName": "individualVersion",
"policyName": "utilities"
}
]

View File

@@ -1,67 +0,0 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See the @microsoft/rush package's LICENSE file for license information.
Object.defineProperty(exports, "__esModule", { value: true });
// THIS FILE WAS GENERATED BY A TOOL. ANY MANUAL MODIFICATIONS WILL GET OVERWRITTEN WHENEVER RUSH IS UPGRADED.
//
// This script is intended for usage in an automated build environment where the Rush command may not have
// been preinstalled, or may have an unpredictable version. This script will automatically install the version of Rush
// specified in the rush.json configuration file (if not already installed), and then pass a command-line to it.
// An example usage would be:
//
// node common/scripts/install-run-rush.js install
//
// For more information, see: https://rushjs.io/pages/maintainer/setup_new_repo/
const path = require("path");
const fs = require("fs");
const install_run_1 = require("./install-run");
const PACKAGE_NAME = '@microsoft/rush';
const RUSH_PREVIEW_VERSION = 'RUSH_PREVIEW_VERSION';
function _getRushVersion() {
const rushPreviewVersion = process.env[RUSH_PREVIEW_VERSION];
if (rushPreviewVersion !== undefined) {
console.log(`Using Rush version from environment variable ${RUSH_PREVIEW_VERSION}=${rushPreviewVersion}`);
return rushPreviewVersion;
}
const rushJsonFolder = install_run_1.findRushJsonFolder();
const rushJsonPath = path.join(rushJsonFolder, install_run_1.RUSH_JSON_FILENAME);
try {
const rushJsonContents = fs.readFileSync(rushJsonPath, 'utf-8');
// Use a regular expression to parse out the rushVersion value because rush.json supports comments,
// but JSON.parse does not and we don't want to pull in more dependencies than we need to in this script.
const rushJsonMatches = rushJsonContents.match(/\"rushVersion\"\s*\:\s*\"([0-9a-zA-Z.+\-]+)\"/);
return rushJsonMatches[1];
}
catch (e) {
throw new Error(`Unable to determine the required version of Rush from rush.json (${rushJsonFolder}). ` +
'The \'rushVersion\' field is either not assigned in rush.json or was specified ' +
'using an unexpected syntax.');
}
}
function _run() {
const [nodePath, /* Ex: /bin/node */ scriptPath, /* /repo/common/scripts/install-run-rush.js */ ...packageBinArgs /* [build, --to, myproject] */] = process.argv;
// Detect if this script was directly invoked, or if the install-run-rushx script was invokved to select the
// appropriate binary inside the rush package to run
const scriptName = path.basename(scriptPath);
const bin = scriptName.toLowerCase() === 'install-run-rushx.js' ? 'rushx' : 'rush';
if (!nodePath || !scriptPath) {
throw new Error('Unexpected exception: could not detect node path or script path');
}
if (process.argv.length < 3) {
console.log(`Usage: ${scriptName} <command> [args...]`);
if (scriptName === 'install-run-rush.js') {
console.log(`Example: ${scriptName} build --to myproject`);
}
else {
console.log(`Example: ${scriptName} custom-command`);
}
process.exit(1);
}
install_run_1.runWithErrorAndStatusCode(() => {
const version = _getRushVersion();
console.log(`The rush.json configuration requests Rush version ${version}`);
return install_run_1.installAndRun(PACKAGE_NAME, version, bin, packageBinArgs);
});
}
_run();
//# sourceMappingURL=install-run-rush.js.map

View File

@@ -1,18 +0,0 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See the @microsoft/rush package's LICENSE file for license information.
Object.defineProperty(exports, "__esModule", { value: true });
// THIS FILE WAS GENERATED BY A TOOL. ANY MANUAL MODIFICATIONS WILL GET OVERWRITTEN WHENEVER RUSH IS UPGRADED.
//
// This script is intended for usage in an automated build environment where the Rush command may not have
// been preinstalled, or may have an unpredictable version. This script will automatically install the version of Rush
// specified in the rush.json configuration file (if not already installed), and then pass a command-line to the
// rushx command.
//
// An example usage would be:
//
// node common/scripts/install-run-rushx.js custom-command
//
// For more information, see: https://rushjs.io/pages/maintainer/setup_new_repo/
require("./install-run-rush");
//# sourceMappingURL=install-run-rushx.js.map

View File

@@ -1,433 +0,0 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See the @microsoft/rush package's LICENSE file for license information.
Object.defineProperty(exports, "__esModule", { value: true });
// THIS FILE WAS GENERATED BY A TOOL. ANY MANUAL MODIFICATIONS WILL GET OVERWRITTEN WHENEVER RUSH IS UPGRADED.
//
// This script is intended for usage in an automated build environment where a Node tool may not have
// been preinstalled, or may have an unpredictable version. This script will automatically install the specified
// version of the specified tool (if not already installed), and then pass a command-line to it.
// An example usage would be:
//
// node common/scripts/install-run.js qrcode@1.2.2 qrcode https://rushjs.io
//
// For more information, see: https://rushjs.io/pages/maintainer/setup_new_repo/
const childProcess = require("child_process");
const fs = require("fs");
const os = require("os");
const path = require("path");
exports.RUSH_JSON_FILENAME = 'rush.json';
const RUSH_TEMP_FOLDER_ENV_VARIABLE_NAME = 'RUSH_TEMP_FOLDER';
const INSTALLED_FLAG_FILENAME = 'installed.flag';
const NODE_MODULES_FOLDER_NAME = 'node_modules';
const PACKAGE_JSON_FILENAME = 'package.json';
/**
* Parse a package specifier (in the form of name\@version) into name and version parts.
*/
function _parsePackageSpecifier(rawPackageSpecifier) {
rawPackageSpecifier = (rawPackageSpecifier || '').trim();
const separatorIndex = rawPackageSpecifier.lastIndexOf('@');
let name;
let version = undefined;
if (separatorIndex === 0) {
// The specifier starts with a scope and doesn't have a version specified
name = rawPackageSpecifier;
}
else if (separatorIndex === -1) {
// The specifier doesn't have a version
name = rawPackageSpecifier;
}
else {
name = rawPackageSpecifier.substring(0, separatorIndex);
version = rawPackageSpecifier.substring(separatorIndex + 1);
}
if (!name) {
throw new Error(`Invalid package specifier: ${rawPackageSpecifier}`);
}
return { name, version };
}
/**
* As a workaround, copyAndTrimNpmrcFile() copies the .npmrc file to the target folder, and also trims
* unusable lines from the .npmrc file.
*
* Why are we trimming the .npmrc lines? NPM allows environment variables to be specified in
* the .npmrc file to provide different authentication tokens for different registry.
* However, if the environment variable is undefined, it expands to an empty string, which
* produces a valid-looking mapping with an invalid URL that causes an error. Instead,
* we'd prefer to skip that line and continue looking in other places such as the user's
* home directory.
*
* IMPORTANT: THIS CODE SHOULD BE KEPT UP TO DATE WITH Utilities._copyNpmrcFile()
*/
function _copyAndTrimNpmrcFile(sourceNpmrcPath, targetNpmrcPath) {
console.log(`Copying ${sourceNpmrcPath} --> ${targetNpmrcPath}`); // Verbose
let npmrcFileLines = fs.readFileSync(sourceNpmrcPath).toString().split('\n');
npmrcFileLines = npmrcFileLines.map((line) => (line || '').trim());
const resultLines = [];
// Trim out lines that reference environment variables that aren't defined
for (const line of npmrcFileLines) {
// This finds environment variable tokens that look like "${VAR_NAME}"
const regex = /\$\{([^\}]+)\}/g;
const environmentVariables = line.match(regex);
let lineShouldBeTrimmed = false;
if (environmentVariables) {
for (const token of environmentVariables) {
// Remove the leading "${" and the trailing "}" from the token
const environmentVariableName = token.substring(2, token.length - 1);
if (!process.env[environmentVariableName]) {
lineShouldBeTrimmed = true;
break;
}
}
}
if (lineShouldBeTrimmed) {
// Example output:
// "; MISSING ENVIRONMENT VARIABLE: //my-registry.com/npm/:_authToken=${MY_AUTH_TOKEN}"
resultLines.push('; MISSING ENVIRONMENT VARIABLE: ' + line);
}
else {
resultLines.push(line);
}
}
fs.writeFileSync(targetNpmrcPath, resultLines.join(os.EOL));
}
/**
* syncNpmrc() copies the .npmrc file to the target folder, and also trims unusable lines from the .npmrc file.
* If the source .npmrc file not exist, then syncNpmrc() will delete an .npmrc that is found in the target folder.
*
* IMPORTANT: THIS CODE SHOULD BE KEPT UP TO DATE WITH Utilities._syncNpmrc()
*/
function _syncNpmrc(sourceNpmrcFolder, targetNpmrcFolder, useNpmrcPublish) {
const sourceNpmrcPath = path.join(sourceNpmrcFolder, !useNpmrcPublish ? '.npmrc' : '.npmrc-publish');
const targetNpmrcPath = path.join(targetNpmrcFolder, '.npmrc');
try {
if (fs.existsSync(sourceNpmrcPath)) {
_copyAndTrimNpmrcFile(sourceNpmrcPath, targetNpmrcPath);
}
else if (fs.existsSync(targetNpmrcPath)) {
// If the source .npmrc doesn't exist and there is one in the target, delete the one in the target
console.log(`Deleting ${targetNpmrcPath}`); // Verbose
fs.unlinkSync(targetNpmrcPath);
}
}
catch (e) {
throw new Error(`Error syncing .npmrc file: ${e}`);
}
}
let _npmPath = undefined;
/**
* Get the absolute path to the npm executable
*/
function getNpmPath() {
if (!_npmPath) {
try {
if (os.platform() === 'win32') {
// We're on Windows
const whereOutput = childProcess.execSync('where npm', { stdio: [] }).toString();
const lines = whereOutput.split(os.EOL).filter((line) => !!line);
// take the last result, we are looking for a .cmd command
// see https://github.com/microsoft/rushstack/issues/759
_npmPath = lines[lines.length - 1];
}
else {
// We aren't on Windows - assume we're on *NIX or Darwin
_npmPath = childProcess.execSync('which npm', { stdio: [] }).toString();
}
}
catch (e) {
throw new Error(`Unable to determine the path to the NPM tool: ${e}`);
}
_npmPath = _npmPath.trim();
if (!fs.existsSync(_npmPath)) {
throw new Error('The NPM executable does not exist');
}
}
return _npmPath;
}
exports.getNpmPath = getNpmPath;
function _ensureFolder(folderPath) {
if (!fs.existsSync(folderPath)) {
const parentDir = path.dirname(folderPath);
_ensureFolder(parentDir);
fs.mkdirSync(folderPath);
}
}
/**
* Create missing directories under the specified base directory, and return the resolved directory.
*
* Does not support "." or ".." path segments.
* Assumes the baseFolder exists.
*/
function _ensureAndJoinPath(baseFolder, ...pathSegments) {
let joinedPath = baseFolder;
try {
for (let pathSegment of pathSegments) {
pathSegment = pathSegment.replace(/[\\\/]/g, '+');
joinedPath = path.join(joinedPath, pathSegment);
if (!fs.existsSync(joinedPath)) {
fs.mkdirSync(joinedPath);
}
}
}
catch (e) {
throw new Error(`Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}`);
}
return joinedPath;
}
function _getRushTempFolder(rushCommonFolder) {
const rushTempFolder = process.env[RUSH_TEMP_FOLDER_ENV_VARIABLE_NAME];
if (rushTempFolder !== undefined) {
_ensureFolder(rushTempFolder);
return rushTempFolder;
}
else {
return _ensureAndJoinPath(rushCommonFolder, 'temp');
}
}
/**
* Resolve a package specifier to a static version
*/
function _resolvePackageVersion(rushCommonFolder, { name, version }) {
if (!version) {
version = '*'; // If no version is specified, use the latest version
}
if (version.match(/^[a-zA-Z0-9\-\+\.]+$/)) {
// If the version contains only characters that we recognize to be used in static version specifiers,
// pass the version through
return version;
}
else {
// version resolves to
try {
const rushTempFolder = _getRushTempFolder(rushCommonFolder);
const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush');
_syncNpmrc(sourceNpmrcFolder, rushTempFolder);
const npmPath = getNpmPath();
// This returns something that looks like:
// @microsoft/rush@3.0.0 '3.0.0'
// @microsoft/rush@3.0.1 '3.0.1'
// ...
// @microsoft/rush@3.0.20 '3.0.20'
// <blank line>
const npmVersionSpawnResult = childProcess.spawnSync(npmPath, ['view', `${name}@${version}`, 'version', '--no-update-notifier'], {
cwd: rushTempFolder,
stdio: []
});
if (npmVersionSpawnResult.status !== 0) {
throw new Error(`"npm view" returned error code ${npmVersionSpawnResult.status}`);
}
const npmViewVersionOutput = npmVersionSpawnResult.stdout.toString();
const versionLines = npmViewVersionOutput.split('\n').filter((line) => !!line);
const latestVersion = versionLines[versionLines.length - 1];
if (!latestVersion) {
throw new Error('No versions found for the specified version range.');
}
const versionMatches = latestVersion.match(/^.+\s\'(.+)\'$/);
if (!versionMatches) {
throw new Error(`Invalid npm output ${latestVersion}`);
}
return versionMatches[1];
}
catch (e) {
throw new Error(`Unable to resolve version ${version} of package ${name}: ${e}`);
}
}
}
let _rushJsonFolder;
/**
* Find the absolute path to the folder containing rush.json
*/
function findRushJsonFolder() {
if (!_rushJsonFolder) {
let basePath = __dirname;
let tempPath = __dirname;
do {
const testRushJsonPath = path.join(basePath, exports.RUSH_JSON_FILENAME);
if (fs.existsSync(testRushJsonPath)) {
_rushJsonFolder = basePath;
break;
}
else {
basePath = tempPath;
}
} while (basePath !== (tempPath = path.dirname(basePath))); // Exit the loop when we hit the disk root
if (!_rushJsonFolder) {
throw new Error('Unable to find rush.json.');
}
}
return _rushJsonFolder;
}
exports.findRushJsonFolder = findRushJsonFolder;
/**
* Detects if the package in the specified directory is installed
*/
function _isPackageAlreadyInstalled(packageInstallFolder) {
try {
const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME);
if (!fs.existsSync(flagFilePath)) {
return false;
}
const fileContents = fs.readFileSync(flagFilePath).toString();
return fileContents.trim() === process.version;
}
catch (e) {
return false;
}
}
/**
* Removes the following files and directories under the specified folder path:
* - installed.flag
* -
* - node_modules
*/
function _cleanInstallFolder(rushTempFolder, packageInstallFolder) {
try {
const flagFile = path.resolve(packageInstallFolder, INSTALLED_FLAG_FILENAME);
if (fs.existsSync(flagFile)) {
fs.unlinkSync(flagFile);
}
const packageLockFile = path.resolve(packageInstallFolder, 'package-lock.json');
if (fs.existsSync(packageLockFile)) {
fs.unlinkSync(packageLockFile);
}
const nodeModulesFolder = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME);
if (fs.existsSync(nodeModulesFolder)) {
const rushRecyclerFolder = _ensureAndJoinPath(rushTempFolder, 'rush-recycler', `install-run-${Date.now().toString()}`);
fs.renameSync(nodeModulesFolder, rushRecyclerFolder);
}
}
catch (e) {
throw new Error(`Error cleaning the package install folder (${packageInstallFolder}): ${e}`);
}
}
function _createPackageJson(packageInstallFolder, name, version) {
try {
const packageJsonContents = {
'name': 'ci-rush',
'version': '0.0.0',
'dependencies': {
[name]: version
},
'description': 'DON\'T WARN',
'repository': 'DON\'T WARN',
'license': 'MIT'
};
const packageJsonPath = path.join(packageInstallFolder, PACKAGE_JSON_FILENAME);
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonContents, undefined, 2));
}
catch (e) {
throw new Error(`Unable to create package.json: ${e}`);
}
}
/**
* Run "npm install" in the package install folder.
*/
function _installPackage(packageInstallFolder, name, version) {
try {
console.log(`Installing ${name}...`);
const npmPath = getNpmPath();
const result = childProcess.spawnSync(npmPath, ['install'], {
stdio: 'inherit',
cwd: packageInstallFolder,
env: process.env
});
if (result.status !== 0) {
throw new Error('"npm install" encountered an error');
}
console.log(`Successfully installed ${name}@${version}`);
}
catch (e) {
throw new Error(`Unable to install package: ${e}`);
}
}
/**
* Get the ".bin" path for the package.
*/
function _getBinPath(packageInstallFolder, binName) {
const binFolderPath = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin');
const resolvedBinName = (os.platform() === 'win32') ? `${binName}.cmd` : binName;
return path.resolve(binFolderPath, resolvedBinName);
}
/**
* Write a flag file to the package's install directory, signifying that the install was successful.
*/
function _writeFlagFile(packageInstallFolder) {
try {
const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME);
fs.writeFileSync(flagFilePath, process.version);
}
catch (e) {
throw new Error(`Unable to create installed.flag file in ${packageInstallFolder}`);
}
}
function installAndRun(packageName, packageVersion, packageBinName, packageBinArgs) {
const rushJsonFolder = findRushJsonFolder();
const rushCommonFolder = path.join(rushJsonFolder, 'common');
const rushTempFolder = _getRushTempFolder(rushCommonFolder);
const packageInstallFolder = _ensureAndJoinPath(rushTempFolder, 'install-run', `${packageName}@${packageVersion}`);
if (!_isPackageAlreadyInstalled(packageInstallFolder)) {
// The package isn't already installed
_cleanInstallFolder(rushTempFolder, packageInstallFolder);
const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush');
_syncNpmrc(sourceNpmrcFolder, packageInstallFolder);
_createPackageJson(packageInstallFolder, packageName, packageVersion);
_installPackage(packageInstallFolder, packageName, packageVersion);
_writeFlagFile(packageInstallFolder);
}
const statusMessage = `Invoking "${packageBinName} ${packageBinArgs.join(' ')}"`;
const statusMessageLine = new Array(statusMessage.length + 1).join('-');
console.log(os.EOL + statusMessage + os.EOL + statusMessageLine + os.EOL);
const binPath = _getBinPath(packageInstallFolder, packageBinName);
const result = childProcess.spawnSync(binPath, packageBinArgs, {
stdio: 'inherit',
cwd: process.cwd(),
env: process.env
});
if (result.status !== null) {
return result.status;
}
else {
throw result.error || new Error('An unknown error occurred.');
}
}
exports.installAndRun = installAndRun;
function runWithErrorAndStatusCode(fn) {
process.exitCode = 1;
try {
const exitCode = fn();
process.exitCode = exitCode;
}
catch (e) {
console.error(os.EOL + os.EOL + e.toString() + os.EOL + os.EOL);
}
}
exports.runWithErrorAndStatusCode = runWithErrorAndStatusCode;
function _run() {
const [nodePath, /* Ex: /bin/node */ scriptPath, /* /repo/common/scripts/install-run-rush.js */ rawPackageSpecifier, /* qrcode@^1.2.0 */ packageBinName, /* qrcode */ ...packageBinArgs /* [-f, myproject/lib] */] = process.argv;
if (!nodePath) {
throw new Error('Unexpected exception: could not detect node path');
}
if (path.basename(scriptPath).toLowerCase() !== 'install-run.js') {
// If install-run.js wasn't directly invoked, don't execute the rest of this function. Return control
// to the script that (presumably) imported this file
return;
}
if (process.argv.length < 4) {
console.log('Usage: install-run.js <package>@<version> <command> [args...]');
console.log('Example: install-run.js qrcode@1.2.2 qrcode https://rushjs.io');
process.exit(1);
}
runWithErrorAndStatusCode(() => {
const rushJsonFolder = findRushJsonFolder();
const rushCommonFolder = _ensureAndJoinPath(rushJsonFolder, 'common');
const packageSpecifier = _parsePackageSpecifier(rawPackageSpecifier);
const name = packageSpecifier.name;
const version = _resolvePackageVersion(rushCommonFolder, packageSpecifier);
if (packageSpecifier.version !== version) {
console.log(`Resolved to ${name}@${version}`);
}
return installAndRun(name, version, packageBinName, packageBinArgs);
});
}
_run();
//# sourceMappingURL=install-run.js.map

View File

@@ -1,8 +0,0 @@
{
"$schema": "http://json.schemastore.org/tsconfig",
"extends": "./common.tsconfig.json",
"compilerOptions": {
"declaration": false,
"strict": true
}
}

View File

@@ -1,4 +0,0 @@
{
"$schema": "http://json.schemastore.org/tsconfig",
"extends": "./common.tsconfig.json"
}

View File

@@ -1,18 +0,0 @@
{
"name": "typescript-config",
"description": "TypeScript configurations",
"author": "GitHub",
"private": true,
"version": "0.0.1",
"publisher": "GitHub",
"repository": {
"type": "git",
"url": "https://github.com/github/vscode-codeql"
},
"scripts": {
"build": "",
"format": ""
},
"devDependencies": {},
"dependencies": {}
}

View File

@@ -3,7 +3,7 @@ module.exports = {
parserOptions: {
ecmaVersion: 2018,
sourceType: "module",
project: ["tsconfig.json", "./src/**/tsconfig.json"],
project: ["tsconfig.json", "./src/**/tsconfig.json", "./gulpfile.ts/tsconfig.json"],
},
plugins: ["@typescript-eslint"],
env: {
@@ -22,8 +22,10 @@ module.exports = {
},
],
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-floating-promises": [ "error", { ignoreVoid: true } ],
"prefer-const": ["warn", { destructuring: "all" }],
indent: "off",
"@typescript-eslint/indent": "off",

View File

@@ -1,5 +1,257 @@
# CodeQL for Visual Studio Code: Changelog
## 1.6.6 - 17 May 2022
No user facing changes.
## 1.6.5 - 25 April 2022
- Re-enable publishing to open-vsx. [#1285](https://github.com/github/vscode-codeql/pull/1285)
## 1.6.4 - 6 April 2022
No user facing changes.
## 1.6.3 - 4 April 2022
- Fix a bug where the AST viewer was not synchronizing its selected node when the editor selection changes. [#1230](https://github.com/github/vscode-codeql/pull/1230)
- Avoid synchronizing the `codeQL.cli.executablePath` setting. [#1252](https://github.com/github/vscode-codeql/pull/1252)
- Open the directory in the finder/explorer (instead of just highlighting it) when running the "Open query directory" command from the query history view. [#1235](https://github.com/github/vscode-codeql/pull/1235)
- Ensure query label in the query history view changes are persisted across restarts. [#1235](https://github.com/github/vscode-codeql/pull/1235)
- Prints end-of-query evaluator log summaries to the Query Server Console. [#1264](https://github.com/github/vscode-codeql/pull/1264)
## 1.6.1 - 17 March 2022
No user facing changes.
## 1.6.0 - 7 March 2022
- Fix a bug where database upgrades could not be resolved if some of the target pack's dependencies are outside of the workspace. [#1138](https://github.com/github/vscode-codeql/pull/1138)
- Open the query server logs for query errors (instead of the extension log). This will make it easier to track down query errors. [#1158](https://github.com/github/vscode-codeql/pull/1158)
- Fix a bug where queries took a long time to run if there are no folders in the workspace. [#1157](https://github.com/github/vscode-codeql/pull/1157)
- [BREAKING CHANGE] The `codeQL.runningQueries.customLogDirectory` setting is deprecated and no longer has any function. Instead, all query log files will be stored in the query history directory, next to the query results. [#1178](https://github.com/github/vscode-codeql/pull/1178)
- Add a _Open query directory_ command for query items. This command opens the directory containing all artifacts for a query. [#1179](https://github.com/github/vscode-codeql/pull/1179)
- Add options to display evaluator logs for a given query run. Some information that was previously found in the query server output may now be found here. [#1186](https://github.com/github/vscode-codeql/pull/1186)
## 1.5.11 - 10 February 2022
- Fix a bug where invoking _View AST_ from the file explorer would not view the selected file. Instead it would view the active editor. Also, prevent the _View AST_ from appearing if the current selection includes a directory or multiple files. [#1113](https://github.com/github/vscode-codeql/pull/1113)
- Add query history items as soon as a query is run, including new icons for each history item. [#1094](https://github.com/github/vscode-codeql/pull/1094)
- Save query history items across restarts. Items will be saved for 30 days and can be overwritten by setting the `codeQL.queryHistory.ttl` configuration setting. [#1130](https://github.com/github/vscode-codeql/pull/1130)
- Allow in-progress query items to be cancelled from the query history view. [#1105](https://github.com/github/vscode-codeql/pull/1105)
## 1.5.10 - 25 January 2022
- Fix a bug where the results view moved column even when it was already visible. [#1070](https://github.com/github/vscode-codeql/pull/1070)
- Add packaging-related commands. _CodeQL: Download Packs_ downloads query packs from the package registry that can be run locally, and _CodeQL: Install Pack Dependencies_ installs dependencies for packs in your workspace. [#1076](https://github.com/github/vscode-codeql/pull/1076)
## 1.5.9 - 17 December 2021
- Avoid creating a third column when opening the results view. The results view will always open to the right of the active editor, unless the active editor is in the rightmost editor column. In that case open in the leftmost column. [#1037](https://github.com/github/vscode-codeql/pull/1037)
- Add a CodeLens to make the Quick Evaluation command more accessible. Click the `Quick Evaluation` prompt above a predicate definition in the editor to evaluate that predicate on its own. You can enable/disable this feature in the `codeQL.runningQueries.quickEvalCodelens` setting. [#1035](https://github.com/github/vscode-codeql/pull/1035) & [#1052](https://github.com/github/vscode-codeql/pull/1052)
- Fix a bug where the _Alerts_ option would show in the results view even if there is no alerts table available. [#1038](https://github.com/github/vscode-codeql/pull/1038)
## 1.5.8 - 2 December 2021
- Emit a more explicit error message when a user tries to add a database with an unzipped source folder to the workspace. [#1021](https://github.com/github/vscode-codeql/pull/1021)
- Ensure `src.zip` archives are used as the canonical source instead of `src` folders when importing databases. [#1025](https://github.com/github/vscode-codeql/pull/1025)
## 1.5.7 - 23 November 2021
- Fix the _CodeQL: Open Referenced File_ command for Windows systems. [#979](https://github.com/github/vscode-codeql/pull/979)
- Support large SARIF results files (>4GB) without crashing VS Code. [#1004](https://github.com/github/vscode-codeql/pull/1004)
- Fix a bug that shows 'Set current database' when hovering over the currently selected database in the databases view. [#976](https://github.com/github/vscode-codeql/pull/976)
- Fix a bug with importing large databases. Databases over 4GB can now be imported directly from LGTM or from a zip file. This functionality is only available when using CodeQL CLI version 2.6.0 or later. [#971](https://github.com/github/vscode-codeql/pull/971)
- Replace certain control codes (`U+0000` - `U+001F`) with their corresponding control labels (`U+2400` - `U+241F`) in the results view. [#963](https://github.com/github/vscode-codeql/pull/963)
- Allow case-insensitive project slugs for GitHub repositories when adding a CodeQL database from LGTM. [#978](https://github.com/github/vscode-codeql/pull/961)
- Add a _CodeQL: Preview Query Help_ command to generate Markdown previews of `.qhelp` query help files. This command should only be run in trusted workspaces. See [the CodeQL CLI docs](https://codeql.github.com/docs/codeql-cli/testing-query-help-files) for more information about query help. [#988](https://github.com/github/vscode-codeql/pull/988)
- Make "Open Referenced File" command accessible from the active editor menu. [#989](https://github.com/github/vscode-codeql/pull/989)
- Fix a bug where result set names in the result set drop-down were disappearing when viewing a sorted table. [#1007](https://github.com/github/vscode-codeql/pull/1007)
- Allow query result locations with 0 as the end column value. These are treated as the first column in the line. [#1002](https://github.com/github/vscode-codeql/pull/1002)
## 1.5.6 - 07 October 2021
- Add progress messages to LGTM download option. This makes the two-step process (selecting a project, then selecting a language) more clear. [#960](https://github.com/github/vscode-codeql/pull/960)
- Remove line about selecting a language from the dropdown when downloading database from LGTM. This makes the download progress visible when the popup is not expanded. [#957](https://github.com/github/vscode-codeql/pull/957)
- Fix a bug where copying the version information fails when a CodeQL CLI cannot be found. [#958](https://github.com/github/vscode-codeql/pull/958)
- Avoid a race condition when deleting databases that can cause occasional errors. [#959](https://github.com/github/vscode-codeql/pull/959)
- Update CodeQL logos. [#965](https://github.com/github/vscode-codeql/pull/965)
## 1.5.5 - 08 September 2021
- Fix bug where a query is sometimes run before the file is saved. [#947](https://github.com/github/vscode-codeql/pull/947)
- Fix broken contextual queries, including _View AST_. [#949](https://github.com/github/vscode-codeql/pull/949)
## 1.5.4 - 02 September 2021
- Add support for filename pattern in history view. [#930](https://github.com/github/vscode-codeql/pull/930)
- Add an option _View Results (CSV)_ to view the results of a non-alert query. The existing options for alert queries have been renamed to _View Alerts_ to avoid confusion. [#929](https://github.com/github/vscode-codeql/pull/929)
- Allow users to specify the number of paths to display for each alert. [#931](https://github.com/github/vscode-codeql/pull/931)
- Adjust pagination controls in _CodeQL Query Results_ to always be visible [#936](https://github.com/github/vscode-codeql/pull/936)
- Fix bug where _View AST_ fails due to recent refactoring in the standard library and query packs. [#939](https://github.com/github/vscode-codeql/pull/939)
## 1.5.3 - 18 August 2021
- Add a command _CodeQL: Run Query on Multiple Databases_, which lets users select multiple databases to run a query on. [#898](https://github.com/github/vscode-codeql/pull/898)
- Autodetect what language a query targets. This refines the _CodeQL: Run Query on Multiple Databases_ command to only show relevant databases. [#915](https://github.com/github/vscode-codeql/pull/915)
- Adjust test log output to display diffs only when comparing failed test results with expected test results. [#920](https://github.com/github/vscode-codeql/pull/920)
## 1.5.2 - 13 July 2021
- Add the _Add Database Source to Workspace_ command to the right-click context menu in the databases view. This lets users re-add a database's source folder to the workspace and browse the source code. [#891](https://github.com/github/vscode-codeql/pull/891)
- Fix markdown rendering in the description of the `codeQL.cli.executablePath` setting. [#908](https://github.com/github/vscode-codeql/pull/908)
- Fix the _Open Query Results_ command in the query history view. [#909](https://github.com/github/vscode-codeql/pull/909)
## 1.5.1 - 23 June 2021
No user facing changes.
## 1.5.0 - 14 June 2021
- Display CodeQL CLI version being downloaded during an upgrade. [#862](https://github.com/github/vscode-codeql/pull/862)
- Display a helpful message and link to documentation when a query produces no results. [#866](https://github.com/github/vscode-codeql/pull/866)
- Refresh test databases automatically after a test run. [#868](https://github.com/github/vscode-codeql/pull/868)
- Allow users to specify a custom directory for storing query server logs (`codeQL.runningQueries.customLogDirectory`). The extension will not delete these logs automatically. [#863](https://github.com/github/vscode-codeql/pull/863)
- Support the VS Code [Workspace Trust feature](https://code.visualstudio.com/docs/editor/workspace-trust). This extension is now enabled in untrusted workspaces, but it restricts commands that contain arbitrary paths. [#861](https://github.com/github/vscode-codeql/pull/861)
- Allow the `codeQL.cli.executablePath` configuration setting to be set in workspace-scoped configuration files. This means that each workspace can now specify its own CodeQL CLI compiler, a feature that is unblocked due to implementing Workspace Trust. [#861](https://github.com/github/vscode-codeql/pull/861)
## 1.4.8 - 05 May 2021
- Copy version information to the clipboard when a user clicks the CodeQL section of the status bar. [#845](https://github.com/github/vscode-codeql/pull/845)
- Ensure changes in directories that contain tests will be properly updated in the test explorer. [#846](https://github.com/github/vscode-codeql/pull/846)
- Remind users to choose a language when downloading a database from LGTM. [#852](https://github.com/github/vscode-codeql/pull/852)
## 1.4.7 - 23 April 2021
- Fix a bug that prevented the results view from being loaded. [#842](https://github.com/github/vscode-codeql/pull/842)
## 1.4.6 - 21 April 2021
- Avoid showing an error popup when running a query with `@kind table` metadata. [#814](https://github.com/github/vscode-codeql/pull/814)
- Add an option to jump from a .qlref file to the .ql file it references. [#815](https://github.com/github/vscode-codeql/pull/815)
- Avoid opening the results panel when a database is deleted. [#831](https://github.com/github/vscode-codeql/pull/831)
- Forward all query metadata to the CLI when interpreting results. [#838](https://github.com/github/vscode-codeql/pull/838)
## 1.4.5 - 22 March 2021
- Avoid showing an error popup when user runs a query without `@kind` metadata. [#801](https://github.com/github/vscode-codeql/pull/801)
- Fix running of tests when the `ms-python` extension is installed. [#803](https://github.com/github/vscode-codeql/pull/803)
## 1.4.4 - 19 March 2021
- Introduce evaluator options for saving intermediate results to the disk cache (`codeQL.runningQueries.saveCache`) and for limiting the size of this cache (`codeQL.runningQueries.cacheSize`). [#778](https://github.com/github/vscode-codeql/pull/778)
- Respect the `codeQL.runningQueries.numberOfThreads` setting when creating SARIF files during result interpretation. [#771](https://github.com/github/vscode-codeql/pull/771)
- Allow using raw LGTM project slugs for fetching LGTM databases. [#769](https://github.com/github/vscode-codeql/pull/769)
- Better error messages when BQRS interpretation fails to produce SARIF. [#770](https://github.com/github/vscode-codeql/pull/770)
- Implement sorting of the query history view by name, date, and results count. [#777](https://github.com/github/vscode-codeql/pull/777)
- Add a configuration option to pass additional arguments to the CLI when running tests. [#785](https://github.com/github/vscode-codeql/pull/785)
- Introduce option to view query results as CSV. [#784](https://github.com/github/vscode-codeql/pull/784)
- Add some snippets for commonly used QL statements. [#782](https://github.com/github/vscode-codeql/pull/782)
- More descriptive error messages on QL test failures. [#788](https://github.com/github/vscode-codeql/pull/788)
## 1.4.3 - 22 February 2021
- Avoid displaying an error when removing orphaned databases and the storage folder does not exist. [#748](https://github.com/github/vscode-codeql/pull/748)
- Add better error messages when AST Viewer is unable to create an AST. [#753](https://github.com/github/vscode-codeql/pull/753)
- Cache AST viewing operations so that subsequent calls to view the AST of a single file will be extremely fast. [#753](https://github.com/github/vscode-codeql/pull/753)
- Ensure CodeQL version in status bar updates correctly when version changes. [#754](https://github.com/github/vscode-codeql/pull/754)
- Avoid deleting the quick query file when it is re-opened. [#747](https://github.com/github/vscode-codeql/pull/747)
## 1.4.2 - 2 February 2021
- Add a status bar item for the CodeQL CLI to show the current version. [#741](https://github.com/github/vscode-codeql/pull/741)
- Fix version constraint for flagging CLI support of non-destructive updates. [#744](https://github.com/github/vscode-codeql/pull/744)
- Add a _More Information_ button in the telemetry popup that opens the [telemetry documentation](https://codeql.github.com/docs/codeql-for-visual-studio-code/about-telemetry-in-codeql-for-visual-studio-code) in a browser tab. [#742](https://github.com/github/vscode-codeql/pull/742)
## 1.4.1 - 29 January 2021
- Reword the telemetry modal dialog box. [#738](https://github.com/github/vscode-codeql/pull/738)
## 1.4.0 - 29 January 2021
- Fix bug where databases are not reregistered when the query server restarts. [#734](https://github.com/github/vscode-codeql/pull/734)
- Fix bug where upgrade requests were erroneously being marked as failed. [#734](https://github.com/github/vscode-codeql/pull/734)
- On a strictly opt-in basis, collect anonymized usage data from the VS Code extension, helping improve CodeQL's usability and performance. See the [telemetry documentation](https://codeql.github.com/docs/codeql-for-visual-studio-code/about-telemetry-in-codeql-for-visual-studio-code) for more information on exactly what data is collected and what it is used for. [#611](https://github.com/github/vscode-codeql/pull/611)
## 1.3.10 - 20 January 2021
- Include the full stack in error log messages to help with debugging. [#726](https://github.com/github/vscode-codeql/pull/726)
## 1.3.9 - 12 January 2021
- No changes visible to end users.
## 1.3.8 - 17 December 2020
- Ensure databases are unlocked when removing them from the workspace. This will ensure that after a database is removed from VS Code, queries can be run on it from the command line without restarting the IDE. Requires CodeQL CLI 2.4.1 or later. [#681](https://github.com/github/vscode-codeql/pull/681)
- Fix bug when removing databases where sometimes the source folder would not also be removed from the workspace or the database files would not be deleted from the workspace storage location. [#692](https://github.com/github/vscode-codeql/pull/692)
- Query results with no string representation will now be displayed with placeholder text in query results. Previously, they were omitted. [#694](https://github.com/github/vscode-codeql/pull/694)
- Add a label for the language of a database in the databases view. This will only take effect for new databases created with the CodeQL CLI v2.4.1 or later. [#697](https://github.com/github/vscode-codeql/pull/697)
- Add clearer error message when running a query using a missing or invalid qlpack. [#702](https://github.com/github/vscode-codeql/pull/702)
- Add clearer error message when trying to run a command from the query history view if no item in the history is selected. [#702](https://github.com/github/vscode-codeql/pull/702)
- Fix a bug where it is not possible to download some database archives. This fix specifically addresses large archives and archives whose central directories do not align with file headers. [#700](https://github.com/github/vscode-codeql/pull/700)
- Avoid error dialogs when QL test discovery or database cleanup encounters a missing directory. [#706](https://github.com/github/vscode-codeql/pull/706)
- Add descriptive text and a link in the results view. [#711](https://github.com/github/vscode-codeql/pull/711)
- Fix the _Set Label_ command in the query history view. [#710](https://github.com/github/vscode-codeql/pull/710)
- Add the _CodeQL: View AST_ command to the right-click context menu when a source file in a database source archive is open in the editor. [#712](https://github.com/github/vscode-codeql/pull/712)
## 1.3.7 - 24 November 2020
- Editors opened by navigating from the results view are no longer opened in _preview mode_. Now they are opened as a persistent editor. [#630](https://github.com/github/vscode-codeql/pull/630)
- When comparing the results of a failed QL test run and the `.expected` file does not exist, an empty `.expected` file is created and compared against the `.actual` file. [#669](https://github.com/github/vscode-codeql/pull/669)
- Alter structure of the _Test Explorer_ tree. It now follows the structure of the filesystem instead of the QL Packs. [#624](https://github.com/github/vscode-codeql/pull/624)
- Alter structure of the _Test Explorer_ tree. It now follows the structure of the filesystem instead of the QL Packs. [#624](https://github.com/github/vscode-codeql/pull/624)
- Add more structured output for tests. [#626](https://github.com/github/vscode-codeql/pull/626)
- Whenever the extension restarts, orphaned databases will be cleaned up. These are databases whose files are located inside of the extension's storage area, but are not imported into the workspace.
- After renaming a database, the database list is re-sorted. [#685](https://github.com/github/vscode-codeql/pull/685)
- Add a `codeQl.resultsDisplay.pageSize` setting to configure the number of results displayed in a single results view page. Increase the default page size from 100 to 200. [#686](https://github.com/github/vscode-codeql/pull/686)
- Update the AST Viewer to include edge labels (if available) in addition to the target node labels. So far, only C/C++ databases take advantage of this change. [#688](https://github.com/github/vscode-codeql/pull/688)
## 1.3.6 - 4 November 2020
- Fix URI encoding for databases that were created with special characters in their paths. [#648](https://github.com/github/vscode-codeql/pull/648)
- Disable CodeQL Test commands from the command palette [#667](https://github.com/github/vscode-codeql/pull/667)
- Fix display of booleans in results view. [#657](https://github.com/github/vscode-codeql/pull/657)
- Avoid recursive selection changes in AST Viewer. [#668](https://github.com/github/vscode-codeql/pull/668)
## 1.3.5 - 27 October 2020
- Fix a bug where archived source folders for databases were not showing any contents.
- Fix URI encoding for databases that were created with special characters in their paths.
## 1.3.4 - 22 October 2020
- Add friendly welcome message when the databases view is empty.
- Add open query, open results, and remove query commands in the query history view title bar.
- The maximum number of simultaneous queries launchable by the `CodeQL: Run Queries in Selected Files` command is now configurable by changing the `codeQL.runningQueries.maxQueries` setting.
- Allow simultaneously run queries to be canceled in a single-click.
- Prevent multiple upgrade dialogs from appearing when running simultaneous queries on upgradeable databases.
- Fix sorting of results. Some pages of results would have the wrong sort order and columns.
- Remember previous sort order when reloading query results.
- Fix proper escaping of backslashes in SARIF message strings.
- Allow setting `codeQL.runningQueries.numberOfThreads` and `codeQL.runningTests.numberOfThreads` to 0, (which is interpreted as 'use one thread per core on the machine').
- Clear the problems view of all CodeQL query results when a database is removed.
- Add a `View DIL` command on query history items. This opens a text editor containing the Datalog Intermediary Language representation of the compiled query.
- Remove feature flag for the AST Viewer. For more information on how to use the AST Viewer, [see the documentation](https://help.semmle.com/codeql/codeql-for-vscode/procedures/exploring-the-structure-of-your-source-code.html).
- The `codeQL.runningTests.numberOfThreads` setting is now used correctly when running tests.
- Alter structure of the _Test Explorer_ tree. It now follows the structure of the filesystem instead of the qlpacks.
- Ensure output of CodeQL test runs includes compilation error messages and test failure messages.
## 1.3.3 - 16 September 2020
- Fix display of raw results entities with label but no url.
- Fix bug where sort order is forgotten when changing raw results page.
- Avoid showing a location link in results view when a result item has an empty location.
## 1.3.2 - 12 August 2020
- Fix error with choosing qlpack search path.
- Fix pagination when there are no results.
- Suppress database downloaded from URL message when action canceled.
- Fix QL test discovery to avoid showing duplicate tests in the test explorer.
- Enable pagination of query results
- Add experimental AST Viewer for Go and C++. To enable, add `"codeQL.experimentalAstViewer": true` to the user settings file.
## 1.3.1 - 7 July 2020
- Fix unzipping of large files.

View File

@@ -1,6 +1,6 @@
# CodeQL extension for Visual Studio Code
This project is an extension for Visual Studio Code that adds rich language support for [CodeQL](https://help.semmle.com/codeql) and allows you to easily find problems in codebases. In particular, the extension:
This project is an extension for Visual Studio Code that adds rich language support for [CodeQL](https://codeql.github.com/docs/) and allows you to easily find problems in codebases. In particular, the extension:
- Enables you to use CodeQL to query databases generated from source code.
- Shows the flow of data through the results of path queries, which is essential for triaging security results.
@@ -12,7 +12,7 @@ To see what has changed in the last few versions of the extension, see the [Chan
## Quick start overview
The information in this `README` file describes the quickest way to start using CodeQL.
For information about other configurations, see the separate [CodeQL help](https://help.semmle.com/codeql/codeql-for-vscode.html).
For information about other configurations, see the separate [CodeQL help](https://codeql.github.com/docs/codeql-for-visual-studio-code/).
### Quick start: Installing and configuring the extension
@@ -40,9 +40,9 @@ The CodeQL extension requires a minimum of Visual Studio Code 1.39. Older versio
### Checking access to the CodeQL CLI
The extension uses the [CodeQL CLI](https://help.semmle.com/codeql/codeql-cli.html) to compile and run queries. The extension automatically manages access to the CLI for you by default (recommended). To check for updates to the CodeQL CLI, you can use the **CodeQL: Check for CLI Updates** command.
The extension uses the [CodeQL CLI](https://codeql.github.com/docs/codeql-cli/) to compile and run queries. The extension automatically manages access to the CLI for you by default (recommended). To check for updates to the CodeQL CLI, you can use the **CodeQL: Check for CLI Updates** command.
If you want to override the default behavior and use a CodeQL CLI that's already on your machine, see [Configuring access to the CodeQL CLI](https://help.semmle.com/codeql/codeql-for-vscode/procedures/setting-up.html#configuring-access-to-the-codeql-cli).
If you want to override the default behavior and use a CodeQL CLI that's already on your machine, see [Configuring access to the CodeQL CLI](https://codeql.github.com/docs/codeql-for-visual-studio-code/setting-up-codeql-in-visual-studio-code/#configuring-access-to-the-codeql-cli).
If you have any difficulty with CodeQL CLI access, see the **CodeQL Extension Log** in the **Output** view for any error messages.
@@ -52,7 +52,7 @@ When you're working with CodeQL, you need access to the standard CodeQL librarie
Initially, we recommend that you clone and use the ready-to-use [starter workspace](https://github.com/github/vscode-codeql-starter/).
This includes libraries and queries for the main supported languages, with folders set up ready for your custom queries. After cloning the workspace (use `git clone --recursive`), you can use it in the same way as any other VS Code workspace—with the added advantage that you can easily update the CodeQL libraries.
For information about configuring an existing workspace for CodeQL, [see the documentation](https://help.semmle.com/codeql/codeql-for-vscode/procedures/setting-up.html#updating-an-existing-workspace-for-codeql).
For information about configuring an existing workspace for CodeQL, [see the documentation](https://codeql.github.com/docs/codeql-for-visual-studio-code/setting-up-codeql-in-visual-studio-code/#updating-an-existing-workspace-for-codeql).
## Upgrading CodeQL standard libraries
@@ -75,7 +75,7 @@ You can find all the commands contributed by the extension in the Command Palett
### Importing a database from LGTM
While you can use the [CodeQL CLI to create your own databases](https://help.semmle.com/codeql/codeql-cli/procedures/create-codeql-database.html), the simplest way to start is by downloading a database from LGTM.com.
While you can use the [CodeQL CLI to create your own databases](https://codeql.github.com/docs/codeql-cli/creating-codeql-databases/), the simplest way to start is by downloading a database from LGTM.com.
1. Open [LGTM.com](https://lgtm.com/#explore) in your browser.
1. Search for a project you're interested in, for example [Apache Kafka](https://lgtm.com/projects/g/apache/kafka).
@@ -100,13 +100,17 @@ If there are any problems running a query, a notification is displayed in the bo
## What next?
For more information about the CodeQL extension, [see the documentation](https://help.semmle.com/codeql/codeql-for-vscode.html). Otherwise, you could:
For more information about the CodeQL extension, [see the documentation](https://codeql.github.com/docs/codeql-for-visual-studio-code/). Otherwise, you could:
- [Create a database for a different codebase](https://help.semmle.com/codeql/codeql-cli/procedures/create-codeql-database.html).
- [Create a database for a different codebase](https://codeql.github.com/docs/codeql-cli/creating-codeql-databases/).
- [Try out variant analysis](https://help.semmle.com/QL/learn-ql/ql-training.html).
- [Learn more about CodeQL](https://help.semmle.com/QL/learn-ql/).
- [Learn more about CodeQL](https://codeql.github.com/docs/).
- [Read how security researchers use CodeQL to find CVEs](https://securitylab.github.com/research).
## License
The CodeQL extension for Visual Studio Code is [licensed](LICENSE.md) under the MIT License. The version of CodeQL used by the CodeQL extension is subject to the [GitHub CodeQL Terms & Conditions](https://securitylab.github.com/tools/codeql/license).
## Data and Telemetry
If you specifically opt-in to permit GitHub to do so, GitHub will collect usage data and metrics for the purposes of helping the core developers to improve the CodeQL extension for VS Code. This data will not be shared with any parties outside of GitHub. IP addresses and installation IDs will be retained for a maximum of 30 days. Anonymous data will be retained for a maximum of 180 days. For more information about telemetry, [see the documentation](https://codeql.github.com/docs/codeql-for-visual-studio-code/about-telemetry-in-codeql-for-visual-studio-code).

View File

@@ -1,19 +0,0 @@
'use strict';
require('ts-node').register({});
const gulp = require('gulp');
const {
compileTypeScript,
watchTypeScript,
packageExtension,
compileTextMateGrammar,
copyTestData,
copyViewCss
} = require('@github/codeql-gulp-tasks');
const { compileView } = require('./webpack');
exports.buildWithoutPackage = gulp.parallel(compileTypeScript, compileTextMateGrammar, compileView, copyTestData, copyViewCss);
exports.compileTextMateGrammar = compileTextMateGrammar;
exports.default = gulp.series(exports.buildWithoutPackage, packageExtension);
exports.watchTypeScript = watchTypeScript;
exports.compileTypeScript = compileTypeScript;

View File

@@ -1,28 +0,0 @@
import * as webpack from 'webpack';
import { config } from './webpack.config';
export function compileView(cb: (err?: Error) => void) {
webpack(config).run((error, stats) => {
if (error) {
cb(error);
}
console.log(stats.toString({
errorDetails: true,
colors: true,
assets: false,
builtAt: false,
version: false,
hash: false,
entrypoints: false,
timings: false,
modules: false,
errors: true
}));
if (stats.hasErrors()) {
cb(new Error('Compilation errors detected.'));
return;
}
cb();
});
}

View File

@@ -0,0 +1,17 @@
import * as gulp from 'gulp';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const replace = require('gulp-replace');
/** Inject the application insights key into the telemetry file */
export function injectAppInsightsKey() {
if (!process.env.APP_INSIGHTS_KEY) {
// noop
console.log('APP_INSIGHTS_KEY environment variable is not set. So, cannot inject it into the application.');
return Promise.resolve();
}
// replace the key
return gulp.src(['out/telemetry.js'])
.pipe(replace(/REPLACE-APP-INSIGHTS-KEY/, process.env.APP_INSIGHTS_KEY))
.pipe(gulp.dest('out/'));
}

View File

@@ -0,0 +1,72 @@
import * as fs from 'fs-extra';
import * as path from 'path';
export interface DeployedPackage {
distPath: string;
name: string;
version: string;
}
const packageFiles = [
'.vscodeignore',
'CHANGELOG.md',
'README.md',
'language-configuration.json',
'snippets.json',
'media',
'node_modules',
'out'
];
async function copyPackage(sourcePath: string, destPath: string): Promise<void> {
for (const file of packageFiles) {
console.log(`copying ${path.resolve(sourcePath, file)} to ${path.resolve(destPath, file)}`);
await fs.copy(path.resolve(sourcePath, file), path.resolve(destPath, file));
}
}
export async function deployPackage(packageJsonPath: string): Promise<DeployedPackage> {
try {
const packageJson: any = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
// Default to development build; use flag --release to indicate release build.
const isDevBuild = !process.argv.includes('--release');
const distDir = path.join(__dirname, '../../../dist');
await fs.mkdirs(distDir);
if (isDevBuild) {
// NOTE: rootPackage.name had better not have any regex metacharacters
const oldDevBuildPattern = new RegExp('^' + packageJson.name + '[^/]+-dev[0-9.]+\\.vsix$');
// Dev package filenames are of the form
// vscode-codeql-0.0.1-dev.2019.9.27.19.55.20.vsix
(await fs.readdir(distDir)).filter(name => name.match(oldDevBuildPattern)).map(build => {
console.log(`Deleting old dev build ${build}...`);
fs.unlinkSync(path.join(distDir, build));
});
const now = new Date();
packageJson.version = packageJson.version +
`-dev.${now.getUTCFullYear()}.${now.getUTCMonth() + 1}.${now.getUTCDate()}` +
`.${now.getUTCHours()}.${now.getUTCMinutes()}.${now.getUTCSeconds()}`;
}
const distPath = path.join(distDir, packageJson.name);
await fs.remove(distPath);
await fs.mkdirs(distPath);
await fs.writeFile(path.join(distPath, 'package.json'), JSON.stringify(packageJson, null, 2));
const sourcePath = path.join(__dirname, '..');
console.log(`Copying package '${packageJson.name}' and its dependencies to '${distPath}'...`);
await copyPackage(sourcePath, distPath);
return {
distPath: distPath,
name: packageJson.name,
version: packageJson.version
};
}
catch (e) {
console.error(e);
throw e;
}
}

View File

@@ -0,0 +1,28 @@
import * as gulp from 'gulp';
import { compileTypeScript, watchTypeScript, copyViewCss, cleanOutput, watchCss } from './typescript';
import { compileTextMateGrammar } from './textmate';
import { copyTestData } from './tests';
import { compileView, watchView } from './webpack';
import { packageExtension } from './package';
import { injectAppInsightsKey } from './appInsights';
export const buildWithoutPackage =
gulp.series(
cleanOutput,
gulp.parallel(
compileTypeScript, compileTextMateGrammar, compileView, copyTestData, copyViewCss
)
);
export {
cleanOutput,
compileTextMateGrammar,
watchTypeScript,
watchView,
compileTypeScript,
copyTestData,
injectAppInsightsKey,
compileView,
watchCss
};
export default gulp.series(buildWithoutPackage, injectAppInsightsKey, packageExtension);

View File

@@ -1,6 +1,6 @@
import * as path from 'path';
import { deployPackage } from './deploy';
import * as child_process from 'child-process-promise';
import * as childProcess from 'child-process-promise';
export async function packageExtension(): Promise<void> {
const deployedPackage = await deployPackage(path.resolve('package.json'));
@@ -9,7 +9,7 @@ export async function packageExtension(): Promise<void> {
'package',
'--out', path.resolve(deployedPackage.distPath, '..', `${deployedPackage.name}-${deployedPackage.version}.vsix`)
];
const proc = child_process.spawn('vsce', args, {
const proc = childProcess.spawn('./node_modules/.bin/vsce', args, {
cwd: deployedPackage.distPath
});
proc.childProcess.stdout!.on('data', (data) => {

View File

@@ -0,0 +1,17 @@
import * as gulp from 'gulp';
export function copyTestData() {
copyNoWorkspaceData();
copyCliIntegrationData();
return Promise.resolve();
}
function copyNoWorkspaceData() {
return gulp.src('src/vscode-tests/no-workspace/data/**/*')
.pipe(gulp.dest('out/vscode-tests/no-workspace/data'));
}
function copyCliIntegrationData() {
return gulp.src('src/vscode-tests/cli-integration/data/**/*')
.pipe(gulp.dest('out/vscode-tests/cli-integration/data'));
}

View File

@@ -1,5 +1,5 @@
import * as gulp from 'gulp';
import * as js_yaml from 'js-yaml';
import * as jsYaml from 'js-yaml';
import * as through from 'through2';
import * as PluginError from 'plugin-error';
import * as Vinyl from 'vinyl';
@@ -13,9 +13,10 @@ import * as Vinyl from 'vinyl';
*/
function replaceReferencesWithStrings(value: string, replacements: Map<string, string>): string {
let result = value;
// eslint-disable-next-line no-constant-condition
while (true) {
const original = result;
for (const key of replacements.keys()) {
for (const key of Array.from(replacements.keys())) {
result = result.replace(`(?#${key})`, `(?:${replacements.get(key)})`);
}
if (result === original) {
@@ -32,7 +33,7 @@ function replaceReferencesWithStrings(value: string, replacements: Map<string, s
*/
function gatherMacros(yaml: any): Map<string, string> {
const macros = new Map<string, string>();
for (var key in yaml.macros) {
for (const key in yaml.macros) {
macros.set(key, yaml.macros[key]);
}
@@ -55,7 +56,7 @@ function getNodeMatchText(rule: any): string {
else if (rule.patterns !== undefined) {
const patterns: string[] = [];
// For a list of patterns, use the disjunction of those patterns.
for (var patternIndex in rule.patterns) {
for (const patternIndex in rule.patterns) {
const pattern = rule.patterns[patternIndex];
if (pattern.include !== null) {
patterns.push('(?' + pattern.include + ')');
@@ -65,7 +66,7 @@ function getNodeMatchText(rule: any): string {
return '(?:' + patterns.join('|') + ')';
}
else {
return ''
return '';
}
}
@@ -78,7 +79,7 @@ function getNodeMatchText(rule: any): string {
*/
function gatherMatchTextForRules(yaml: any): Map<string, string> {
const replacements = new Map<string, string>();
for (var key in yaml.repository) {
for (const key in yaml.repository) {
const node = yaml.repository[key];
replacements.set(key, getNodeMatchText(node));
}
@@ -106,7 +107,7 @@ function visitAllRulesInFile(yaml: any, action: (rule: any) => void) {
* @param action Callback to invoke on each rule.
*/
function visitAllRulesInRuleMap(ruleMap: any, action: (rule: any) => void) {
for (var key in ruleMap) {
for (const key in ruleMap) {
const rule = ruleMap[key];
if ((typeof rule) === 'object') {
action(rule);
@@ -124,7 +125,7 @@ function visitAllRulesInRuleMap(ruleMap: any, action: (rule: any) => void) {
* @param action The transformation to make on each match pattern.
*/
function visitAllMatchesInRule(rule: any, action: (match: any) => any) {
for (var key in rule) {
for (const key in rule) {
switch (key) {
case 'begin':
case 'end':
@@ -184,10 +185,10 @@ function transformFile(yaml: any) {
visitAllRulesInFile(yaml, (rule) => {
visitAllMatchesInRule(rule, (match) => {
if ((typeof match) === 'object') {
for (var key in match) {
for (const key in match) {
return macros.get(key)!.replace('(?#)', `(?:${match[key]})`);
}
throw new Error("No key in macro map.")
throw new Error('No key in macro map.');
}
else {
return match;
@@ -225,7 +226,7 @@ export function transpileTextMateGrammar() {
else if (file.isBuffer()) {
const buf: Buffer = file.contents;
const yamlText: string = buf.toString('utf8');
const jsonData: any = js_yaml.safeLoad(yamlText);
const jsonData: any = jsYaml.safeLoad(yamlText);
transformFile(jsonData);
file.contents = Buffer.from(JSON.stringify(jsonData, null, 2), 'utf8');

View File

@@ -1,15 +1,14 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"declaration": true,
"strict": true,
"module": "commonjs",
"target": "es2017",
"outDir": "out",
"lib": [
"es6"
],
"lib": ["ES2021"],
"moduleResolution": "node",
"sourceMap": true,
"rootDir": "../../src",
"rootDir": ".",
"strictNullChecks": true,
"noFallthroughCasesInSwitch": true,
"preserveWatchOutput": true,
@@ -17,14 +16,8 @@
"noImplicitReturns": true,
"experimentalDecorators": true,
"noUnusedLocals": true,
"noUnusedParameters": true
"noUnusedParameters": true,
"esModuleInterop": true
},
"include": [
"../../src/**/*.ts"
],
"exclude": [
"../../node_modules",
"../../test",
"../../**/view"
]
"include": ["*.ts"]
}

View File

@@ -0,0 +1,51 @@
import * as colors from 'ansi-colors';
import * as gulp from 'gulp';
import * as sourcemaps from 'gulp-sourcemaps';
import * as ts from 'gulp-typescript';
import * as del from 'del';
function goodReporter(): ts.reporter.Reporter {
return {
error: (error, typescript) => {
if (error.tsFile) {
console.log('[' + colors.gray('gulp-typescript') + '] ' + colors.red(error.fullFilename
+ '(' + (error.startPosition!.line + 1) + ',' + error.startPosition!.character + '): ')
+ 'error TS' + error.diagnostic.code + ': ' + typescript.flattenDiagnosticMessageText(error.diagnostic.messageText, '\n'));
}
else {
console.log(error.message);
}
},
};
}
const tsProject = ts.createProject('tsconfig.json');
export function cleanOutput() {
return tsProject.projectDirectory ? del(tsProject.projectDirectory + '/out/*') : Promise.resolve();
}
export function compileTypeScript() {
return tsProject.src()
.pipe(sourcemaps.init())
.pipe(tsProject(goodReporter()))
.pipe(sourcemaps.write('.', {
includeContent: false,
sourceRoot: '.',
}))
.pipe(gulp.dest('out'));
}
export function watchTypeScript() {
gulp.watch('src/**/*.ts', compileTypeScript);
}
export function watchCss() {
gulp.watch('src/**/*.css', copyViewCss);
}
/** Copy CSS files for the results view into the output directory. */
export function copyViewCss() {
return gulp.src('src/**/view/*.css')
.pipe(gulp.dest('out'));
}

View File

@@ -6,20 +6,27 @@ export const config: webpack.Configuration = {
entry: {
resultsView: './src/view/results.tsx',
compareView: './src/compare/view/Compare.tsx',
remoteQueriesView: './src/remote-queries/view/RemoteQueries.tsx',
},
output: {
path: path.resolve(__dirname, '..', 'out'),
filename: "[name].js"
filename: '[name].js'
},
devtool: "inline-source-map",
devtool: 'inline-source-map',
resolve: {
extensions: ['.js', '.ts', '.tsx', '.json']
extensions: ['.js', '.ts', '.tsx', '.json'],
fallback: {
path: require.resolve('path-browserify')
}
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: 'ts-loader',
options: {
configFile: 'src/view/tsconfig.json',
}
},
{
test: /\.less$/,

View File

@@ -0,0 +1,51 @@
import * as webpack from 'webpack';
import { config } from './webpack.config';
export function compileView(cb: (err?: Error) => void) {
doWebpack(config, true, cb);
}
export function watchView(cb: (err?: Error) => void) {
const watchConfig = {
...config,
watch: true,
watchOptions: {
aggregateTimeout: 200,
poll: 1000,
}
};
doWebpack(watchConfig, false, cb);
}
function doWebpack(internalConfig: webpack.Configuration, failOnError: boolean, cb: (err?: Error) => void) {
const resultCb = (error: Error | undefined, stats?: webpack.Stats) => {
if (error) {
cb(error);
}
if (stats) {
console.log(stats.toString({
errorDetails: true,
colors: true,
assets: false,
builtAt: false,
version: false,
hash: false,
entrypoints: false,
timings: false,
modules: false,
errors: true
}));
if (stats.hasErrors()) {
if (failOnError) {
cb(new Error('Compilation errors detected.'));
return;
} else {
console.error('Compilation errors detected.');
}
}
cb();
}
};
webpack(internalConfig, resultCb);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 499 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View File

@@ -0,0 +1,7 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 12.6L10.7 13.3L12.3 11.7L13.9 13.3L14.7 12.6L13 11L14.7 9.40005L13.9 8.60005L12.3 10.3L10.7 8.60005L10 9.40005L11.6 11L10 12.6Z" fill="#C5C5C5"/>
<path d="M1 4L15 4L15 3L1 3L1 4Z" fill="#C5C5C5"/>
<path d="M1 7L15 7L15 6L1 6L1 7Z" fill="#C5C5C5"/>
<path d="M9 9.5L9 9L1 9L1 10L9 10L9 9.5Z" fill="#C5C5C5"/>
<path d="M9 13L9 12.5L9 12L1 12L1 13L9 13Z" fill="#C5C5C5"/>
</svg>

After

Width:  |  Height:  |  Size: 483 B

View File

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.23 1H11.77L3.52002 9.25L3.35999 9.46997L1 13.59L2.41003 15L6.53003 12.64L6.75 12.48L15 4.22998V2.77002L13.23 1ZM2.41003 13.59L3.92004 10.59L5.37 12.04L2.41003 13.59ZM6.23999 11.53L4.46997 9.76001L12.47 1.76001L14.24 3.53003L6.23999 11.53Z" fill="#C5C5C5"/>
</svg>

After

Width:  |  Height:  |  Size: 372 B

View File

@@ -0,0 +1,4 @@
<!-- From https://github.com/microsoft/vscode-icons -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.97553 0C3.57186 0 0 3.57186 0 7.97553C0 11.4985 2.29969 14.4832 5.43119 15.5596C5.82263 15.6086 5.96942 15.3639 5.96942 15.1682C5.96942 14.9725 5.96942 14.4832 5.96942 13.7982C3.76758 14.2875 3.27829 12.7217 3.27829 12.7217C2.93578 11.792 2.39755 11.5474 2.39755 11.5474C1.66361 11.0581 2.44648 11.0581 2.44648 11.0581C3.22936 11.107 3.66972 11.8899 3.66972 11.8899C4.40367 13.1131 5.52905 12.7706 5.96942 12.5749C6.01835 12.0367 6.263 11.6942 6.45872 11.4985C4.69725 11.3028 2.83792 10.6177 2.83792 7.53517C2.83792 6.65443 3.1315 5.96942 3.66972 5.38226C3.62079 5.23547 3.32722 4.40367 3.76758 3.32722C3.76758 3.32722 4.4526 3.1315 5.96942 4.15902C6.6055 3.9633 7.29052 3.91437 7.97553 3.91437C8.66055 3.91437 9.34557 4.01223 9.98165 4.15902C11.4985 3.1315 12.1835 3.32722 12.1835 3.32722C12.6239 4.40367 12.3303 5.23547 12.2813 5.43119C12.7706 5.96942 13.1131 6.70336 13.1131 7.5841C13.1131 10.6667 11.2538 11.3028 9.49235 11.4985C9.78593 11.7431 10.0306 12.2324 10.0306 12.9664C10.0306 14.0428 10.0306 14.8746 10.0306 15.1682C10.0306 15.3639 10.1774 15.6086 10.5688 15.5596C13.7492 14.4832 16 11.4985 16 7.97553C15.9511 3.57186 12.3792 0 7.97553 0Z" fill="#C5C5C5"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M2 2H14L15 3V13L14 14H2L1 13V3L2 2ZM2 13H14V3H2V13ZM13 4H3V7H13V4ZM12 6H4V5H12V6ZM9 12H13V8H9V12ZM10 9H12V11H10V9ZM7 8H3V9H7V8ZM3 11H7V12H3V11Z" fill="#C5C5C5"/>
</svg>

After

Width:  |  Height:  |  Size: 313 B

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" fill="none"
viewBox="0 0 432 432" style="enable-background:new 0 0 432 432;" xml:space="preserve">
<g>
<g>
<g>
<polygon points="234.24,9.067 183.893,59.413 284.587,59.413" fill="#C5C5C5"/>
<path d="m 259.24622,341.40906 v -32.34375 q 13.35937,6.32812 27.07031,9.66797 13.71094,3.33984 26.89453,3.33984 35.15625,0 53.61328,-23.55469 18.63282,-23.73047 21.26953,-71.89453 -10.19531,15.11719 -25.83984,23.20313 -15.64453,8.08593 -34.62891,8.08593 -39.375,0 -62.40234,-23.73046 -22.85156,-23.90625 -22.85156,-65.21485 0,-40.42969 23.90625,-64.86328 23.90625,-24.433594 63.63281,-24.433594 45.52734,0 69.43359,34.980474 24.08204,34.80468 24.08204,101.25 0,62.05078 -29.53125,99.14062 -29.35547,36.91406 -79.10157,36.91406 -13.35937,0 -27.07031,-2.63672 -13.71094,-2.63671 -28.47656,-7.91015 z m 70.66406,-111.26953 q 23.90625,0 37.79297,-16.34766 14.0625,-16.34766 14.0625,-44.82422 0,-28.30078 -14.0625,-44.64844 -13.88672,-16.52343 -37.79297,-16.52343 -23.90625,0 -37.96875,16.52343 -13.88672,16.34766 -13.88672,44.64844 0,28.47656 13.88672,44.82422 14.0625,16.34766 37.96875,16.34766 z" fill="#C5C5C5" />
<polygon points="234.24,422.933 283.947,373.227 184.533,373.227" fill="#C5C5C5"/>
<path d="M 35.300905,316.97546 H 93.308718 V 116.76062 L 30.203249,129.41687 V 97.07312 L 92.957155,84.41687 h 35.507815 v 232.55859 h 58.00781 v 29.88282 H 35.300905 Z" fill="#C5C5C5"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M10 3H12H13V4H12V13L11 14H4L3 13V4H2V3H5V2C5 1.73478 5.10531 1.48038 5.29285 1.29285C5.48038 1.10531 5.73478 1 6 1H9C9.26522 1 9.51962 1.10531 9.70715 1.29285C9.89469 1.48038 10 1.73478 10 2V3ZM9 2H6V3H9V2ZM4 13H11V4H4V13ZM6 5H5V12H6V5ZM7 5H8V12H7V5ZM9 5H10V12H9V5Z" fill="#C5C5C5"/>
</svg>

After

Width:  |  Height:  |  Size: 435 B

View File

@@ -0,0 +1,7 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M15.5 12.1952C15.5 12.9126 14.9137 13.4996 14.1957 13.4996H1.80435C1.08696 13.4996 0.5 12.9126 0.5 12.1952L0.5 9.80435C0.5 9.08696 1.08696 8.5 1.80435 8.5H14.1956C14.9137 8.5 15.5 9.08696 15.5 9.80435L15.5 12.1952Z" stroke="#959DA5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M2.45654 11.5H13.5435" stroke="#959DA5" stroke-linecap="round" stroke-linejoin="round"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.5 9.5C13.224 9.5 13 9.725 13 10C13 10.275 13.224 10.5 13.5 10.5C13.776 10.5 14 10.275 14 10C14 9.725 13.776 9.5 13.5 9.5" fill="#959DA5"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M11.5 9.5C11.224 9.5 11 9.725 11 10C11 10.275 11.224 10.5 11.5 10.5C11.776 10.5 12 10.275 12 10C12 9.725 11.776 9.5 11.5 9.5" fill="#959DA5"/>
<path d="M15.5 9.81464L13.8728 2.76261C13.6922 2.06804 12.9572 1.5 12.2391 1.5H3.76087C3.04348 1.5 2.30848 2.06804 2.12783 2.76261L0.5 9.8" stroke="#959DA5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,16 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="7.5" cy="7.5" r="7" stroke="#959DA5"/>
<mask id="mask0_394_2982" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="15" height="15">
<circle cx="7.5" cy="7.5" r="7.5" fill="#C4C4C4"/>
</mask>
<g mask="url(#mask0_394_2982)">
<path d="M14.5 7.5C14.5 9.42971 13.6822 11.1907 12.5493 12.4721C11.4035 13.7683 10.0054 14.5 8.90625 14.5C7.84644 14.5 6.81131 13.8113 6.01569 12.5383C5.22447 11.2724 4.71875 9.49235 4.71875 7.5C4.71875 5.50765 5.22447 3.72765 6.01569 2.4617C6.81131 1.1887 7.84644 0.5 8.90625 0.5C10.0054 0.5 11.4035 1.23172 12.5493 2.52786C13.6822 3.80934 14.5 5.57029 14.5 7.5Z" stroke="#959DA5"/>
</g>
<mask id="mask1_394_2982" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="1" y="0" width="16" height="15">
<circle cx="9.375" cy="7.5" r="7.5" fill="#C4C4C4"/>
</mask>
<g mask="url(#mask1_394_2982)">
<path d="M10.2812 7.5C10.2812 9.49235 9.77553 11.2724 8.98431 12.5383C8.18869 13.8113 7.15356 14.5 6.09375 14.5C4.99456 14.5 3.5965 13.7683 2.45067 12.4721C1.31781 11.1907 0.5 9.42971 0.5 7.5C0.5 5.57029 1.31781 3.80934 2.45067 2.52786C3.5965 1.23172 4.99456 0.5 6.09375 0.5C7.15356 0.5 8.18869 1.1887 8.98431 2.4617C9.77553 3.72765 10.2812 5.50765 10.2812 7.5Z" stroke="#959DA5"/>
</g>
<line y1="7.5" x2="15" y2="7.5" stroke="#959DA5"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1,7 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.0001 12.6L10.7001 13.3L12.3001 11.7L13.9001 13.3L14.7001 12.6L13.0001 11L14.7001 9.40005L13.9001 8.60005L12.3001 10.3L10.7001 8.60005L10.0001 9.40005L11.6001 11L10.0001 12.6Z" fill="#424242"/>
<path d="M1.00006 4L15.0001 4L15.0001 3L1.00006 3L1.00006 4Z" fill="#424242"/>
<path d="M1.00006 7L15.0001 7L15.0001 6L1.00006 6L1.00006 7Z" fill="#424242"/>
<path d="M9.00006 9.5L9.00006 9L1.00006 9L1.00006 10L9.00006 10L9.00006 9.5Z" fill="#424242"/>
<path d="M9.00006 13L9.00006 12.5L9.00006 12L1.00006 12L1.00006 13L9.00006 13Z" fill="#424242"/>
</svg>

After

Width:  |  Height:  |  Size: 658 B

View File

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.2302 1H11.7703L3.52026 9.25L3.36023 9.46997L1.00024 13.59L2.41028 15L6.53027 12.64L6.75024 12.48L15.0002 4.22998V2.77002L13.2302 1ZM2.41028 13.59L3.92029 10.59L5.37024 12.04L2.41028 13.59ZM6.24023 11.53L4.47021 9.76001L12.4702 1.76001L14.2402 3.53003L6.24023 11.53Z" fill="#424242"/>
</svg>

After

Width:  |  Height:  |  Size: 399 B

View File

@@ -0,0 +1,11 @@
<!-- From https://github.com/microsoft/vscode-icons -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.97578 0C3.57211 0 0.000244141 3.57186 0.000244141 7.97553C0.000244141 11.4985 2.29994 14.4832 5.43144 15.5596C5.82287 15.6086 5.96966 15.3639 5.96966 15.1682C5.96966 14.9725 5.96966 14.4832 5.96966 13.7982C3.76783 14.2875 3.27853 12.7217 3.27853 12.7217C2.93602 11.792 2.3978 11.5474 2.3978 11.5474C1.66385 11.0581 2.44673 11.0581 2.44673 11.0581C3.2296 11.107 3.66997 11.8899 3.66997 11.8899C4.40391 13.1131 5.5293 12.7706 5.96966 12.5749C6.01859 12.0367 6.26324 11.6942 6.45896 11.4985C4.69749 11.3028 2.83816 10.6177 2.83816 7.53517C2.83816 6.65443 3.13174 5.96942 3.66997 5.38226C3.62104 5.23547 3.32746 4.40367 3.76783 3.32722C3.76783 3.32722 4.45284 3.1315 5.96966 4.15902C6.60575 3.9633 7.29076 3.91437 7.97578 3.91437C8.66079 3.91437 9.34581 4.01223 9.98189 4.15902C11.4987 3.1315 12.1837 3.32722 12.1837 3.32722C12.6241 4.40367 12.3305 5.23547 12.2816 5.43119C12.7709 5.96942 13.1134 6.70336 13.1134 7.5841C13.1134 10.6667 11.2541 11.3028 9.4926 11.4985C9.78618 11.7431 10.0308 12.2324 10.0308 12.9664C10.0308 14.0428 10.0308 14.8746 10.0308 15.1682C10.0308 15.3639 10.1776 15.6086 10.5691 15.5596C13.7495 14.4832 16.0002 11.4985 16.0002 7.97553C15.9513 3.57186 12.3794 0 7.97578 0Z" fill="#424242"/>
</g>
<defs>
<clipPath id="clip0">
<rect width="16" height="16" fill="white" transform="translate(0.000244141)"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M2.00024 2H14.0002L15.0002 3V13L14.0002 14H2.00024L1.00024 13V3L2.00024 2ZM2.00024 13H14.0002V3H2.00024V13ZM13.0002 4H3.00024V7H13.0002V4ZM12.0002 6H4.00024V5H12.0002V6ZM9.00024 12H13.0002V8H9.00024V12ZM10.0002 9H12.0002V11H10.0002V9ZM7.00024 8H3.00024V9H7.00024V8ZM3.00024 11H7.00024V12H3.00024V11Z" fill="#424242"/>
</svg>

After

Width:  |  Height:  |  Size: 469 B

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 432 432" style="enable-background:new 0 0 432 432;" xml:space="preserve">
<g>
<g>
<g>
<polygon points="234.24,9.067 183.893,59.413 284.587,59.413" />
<path d="m 259.24622,341.40906 v -32.34375 q 13.35937,6.32812 27.07031,9.66797 13.71094,3.33984 26.89453,3.33984 35.15625,0 53.61328,-23.55469 18.63282,-23.73047 21.26953,-71.89453 -10.19531,15.11719 -25.83984,23.20313 -15.64453,8.08593 -34.62891,8.08593 -39.375,0 -62.40234,-23.73046 -22.85156,-23.90625 -22.85156,-65.21485 0,-40.42969 23.90625,-64.86328 23.90625,-24.433594 63.63281,-24.433594 45.52734,0 69.43359,34.980474 24.08204,34.80468 24.08204,101.25 0,62.05078 -29.53125,99.14062 -29.35547,36.91406 -79.10157,36.91406 -13.35937,0 -27.07031,-2.63672 -13.71094,-2.63671 -28.47656,-7.91015 z m 70.66406,-111.26953 q 23.90625,0 37.79297,-16.34766 14.0625,-16.34766 14.0625,-44.82422 0,-28.30078 -14.0625,-44.64844 -13.88672,-16.52343 -37.79297,-16.52343 -23.90625,0 -37.96875,16.52343 -13.88672,16.34766 -13.88672,44.64844 0,28.47656 13.88672,44.82422 14.0625,16.34766 37.96875,16.34766 z" />
<polygon points="234.24,422.933 283.947,373.227 184.533,373.227" />
<path d="M 35.300905,316.97546 H 93.308718 V 116.76062 L 30.203249,129.41687 V 97.07312 L 92.957155,84.41687 h 35.507815 v 232.55859 h 58.00781 v 29.88282 H 35.300905 Z" />
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.0002 3H12.0002H13.0002V4H12.0002V13L11.0002 14H4.00024L3.00024 13V4H2.00024V3H5.00024V2C5.00024 1.73478 5.10555 1.48038 5.29309 1.29285C5.48063 1.10531 5.73503 1 6.00024 1H9.00024C9.26546 1 9.51986 1.10531 9.7074 1.29285C9.89493 1.48038 10.0002 1.73478 10.0002 2V3ZM9.00024 2H6.00024V3H9.00024V2ZM4.00024 13H11.0002V4H4.00024V13ZM6.00024 5H5.00024V12H6.00024V5ZM7.00024 5H8.00024V12H7.00024V5ZM9.00024 5H10.0002V12H9.00024V5Z" fill="#424242"/>
</svg>

After

Width:  |  Height:  |  Size: 599 B

View File

@@ -1,14 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="27px" height="16px" viewBox="0 0 27 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 59 (86127) - https://sketch.com -->
<title>Slice</title>
<desc>Created with Sketch.</desc>
<g id="light" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="QL" transform="translate(1.000000, 1.000000)">
<rect id="Rectangle-41" stroke="#2088FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" x="0" y="0" width="25" height="14" rx="2"></rect>
<line x1="17" y1="5" x2="19" y2="5" id="Stroke-15" stroke="#2088FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></line>
<line x1="17" y1="9" x2="21" y2="9" id="Stroke-15" stroke="#2088FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></line>
<path d="M8.85227273,7 C8.85227273,7.51894199 8.76988719,7.97537682 8.60511364,8.36931818 C8.44034009,8.76325955 8.21591051,9.08711994 7.93181818,9.34090909 L8.76420455,10.3863636 L7.61647727,10.3863636 L7.14772727,9.80965909 C6.83143781,9.92897787 6.49147909,9.98863636 6.12784091,9.98863636 C5.61079287,9.98863636 5.14678236,9.8712133 4.73579545,9.63636364 C4.32480855,9.40151398 4.00000119,9.06108178 3.76136364,8.61505682 C3.52272608,8.16903186 3.40340909,7.63068497 3.40340909,7 C3.40340909,6.36552713 3.52272608,5.8257598 3.76136364,5.38068182 C4.00000119,4.93560384 4.32480855,4.59611859 4.73579545,4.36221591 C5.14678236,4.12831322 5.61079287,4.01136364 6.12784091,4.01136364 C6.642995,4.01136364 7.10605855,4.12831322 7.51704545,4.36221591 C7.92803236,4.59611859 8.2533132,4.93560384 8.49289773,5.38068182 C8.73248226,5.8257598 8.85227273,6.36552713 8.85227273,7 Z M5.70170455,7.88636364 L6.74715909,7.88636364 L7.17897727,8.44034091 C7.31344764,8.27935526 7.41808675,8.07859969 7.49289773,7.83806818 C7.56770871,7.59753668 7.60511364,7.31818341 7.60511364,7 C7.60511364,6.38257267 7.47064528,5.91145996 7.20170455,5.58664773 C6.93276381,5.2618355 6.57481284,5.09943182 6.12784091,5.09943182 C5.68086898,5.09943182 5.32291801,5.2618355 5.05397727,5.58664773 C4.78503653,5.91145996 4.65056818,6.38257267 4.65056818,7 C4.65056818,7.61553338 4.78503653,8.08617261 5.05397727,8.41193182 C5.32291801,8.73769102 5.68086898,8.90056818 6.12784091,8.90056818 C6.23958389,8.90056818 6.34564344,8.89015162 6.44602273,8.86931818 L5.70170455,7.88636364 Z M10.1813315,10 L10.1813315,4 L11.4114451,4 L11.4114451,8.98579545 L13.9057633,8.98579545 L13.9057633,10 L10.1813315,10 Z" fill="#2088FF" fill-rule="nonzero"></path>
</g>
</g>
</svg>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.19789 8C8.19789 8.51894 8.1155 8.97538 7.95073 9.36932C7.78595 9.76326 7.56152 10.0871 7.27743 10.3409L8.10982 11.3864H6.96209L6.49334 10.8097C6.17705 10.929 5.83709 10.9886 5.47346 10.9886C4.95641 10.9886 4.4924 10.8712 4.08141 10.6364C3.67042 10.4015 3.34562 10.0611 3.10698 9.61506C2.86834 9.16903 2.74902 8.63068 2.74902 8C2.74902 7.36553 2.86834 6.82576 3.10698 6.38068C3.34562 5.9356 3.67042 5.59612 4.08141 5.36222C4.4924 5.12831 4.95641 5.01136 5.47346 5.01136C5.98861 5.01136 6.45167 5.12831 6.86266 5.36222C7.27365 5.59612 7.59893 5.9356 7.83851 6.38068C8.0781 6.82576 8.19789 7.36553 8.19789 8ZM5.04732 8.88636H6.09277L6.52459 9.44034C6.65906 9.27936 6.7637 9.0786 6.83851 8.83807C6.91332 8.59754 6.95073 8.31818 6.95073 8C6.95073 7.38257 6.81626 6.91146 6.54732 6.58665C6.27838 6.26184 5.92043 6.09943 5.47346 6.09943C5.02648 6.09943 4.66853 6.26184 4.39959 6.58665C4.13065 6.91146 3.99618 7.38257 3.99618 8C3.99618 8.61553 4.13065 9.08617 4.39959 9.41193C4.66853 9.73769 5.02648 9.90057 5.47346 9.90057C5.5852 9.90057 5.69126 9.89015 5.79164 9.86932L5.04732 8.88636ZM9.52695 11V5H10.7571V9.9858H13.2514V11H9.52695Z" fill="#24292F"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M13 1.5H3C2.17157 1.5 1.5 2.17157 1.5 3V13C1.5 13.8284 2.17157 14.5 3 14.5H13C13.8284 14.5 14.5 13.8284 14.5 13V3C14.5 2.17157 13.8284 1.5 13 1.5ZM3 0C1.34315 0 0 1.34315 0 3V13C0 14.6569 1.34315 16 3 16H13C14.6569 16 16 14.6569 16 13V3C16 1.34315 14.6569 0 13 0H3Z" fill="#24292F"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

25618
extensions/ql-vscode/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
if grep -rq --include '*.test.ts' 'it.only\|describe.only' './test' './src'; then
echo 'There is a .only() in the tests. Please remove it.'
exit 1;
else
exit 0;
fi

View File

@@ -0,0 +1,134 @@
{
"Query Metadata": {
"prefix": "querymetadata",
"body": [
"/**",
" * @name $1",
" * @description $2",
" * @kind $3",
" * @id $4",
" * @tags $5",
" */"
],
"description": "Metadata for a query"
},
"Class": {
"prefix": "class",
"body": ["class $1 extends $2 {", "\t$0", "}"],
"description": "A class"
},
"From/Where/Select": {
"prefix": "from",
"body": ["from $1", "where $2", "select $3"],
"description": "A from/where/select statement"
},
"Predicate": {
"prefix": "predicate",
"body": ["predicate $1($2) {", "\t$0", "}"],
"description": "A predicate"
},
"Dataflow Tracking Class": {
"prefix": "dataflowtracking",
"body": [
"class $1 extends DataFlow::Configuration {",
"\t$1() { this = \"$1\" }",
"\t",
"\toverride predicate isSource(DataFlow::Node node) {",
"\t\t${2:none()}",
"\t}",
"\t",
"\toverride predicate isSink(DataFlow::Node node) {",
"\t\t${3:none()}",
"\t}",
"}"
],
"description": "Boilerplate for a dataflow tracking class"
},
"Taint Tracking Class": {
"prefix": "tainttracking",
"body": [
"class $1 extends TaintTracking::Configuration {",
"\t$1() { this = \"$1\" }",
"\t",
"\toverride predicate isSource(DataFlow::Node node) {",
"\t\t${2:none()}",
"\t}",
"\t",
"\toverride predicate isSink(DataFlow::Node node) {",
"\t\t${3:none()}",
"\t}",
"}"
],
"description": "Boilerplate for a taint tracking class"
},
"Count": {
"prefix": "count",
"body": ["count($1 | $2 | $3)"],
"description": "A count aggregate"
},
"Max": {
"prefix": "max",
"body": ["max($1 | $2 | $3)"],
"description": "A max aggregate"
},
"Min": {
"prefix": "min",
"body": ["min($1 | $2 | $3)"],
"description": "A min aggregate"
},
"Average": {
"prefix": "avg",
"body": ["avg($1 | $2 | $3)"],
"description": "An average aggregate"
},
"Sum": {
"prefix": "sum",
"body": ["sum($1 | $2 | $3)"],
"description": "A sum aggregate"
},
"Concatenation": {
"prefix": "concat",
"body": ["concat($1 | $2 | $3)"],
"description": "A concatenation aggregate"
},
"Rank": {
"prefix": "rank",
"body": ["rank[$1]($2 | $3 | $4)"],
"description": "A rank aggregate"
},
"Strict Sum": {
"prefix": "strictsum",
"body": ["strictsum($1 | $2 | $3)"],
"description": "A strict sum aggregate"
},
"Strict Concatenation": {
"prefix": "strictconcat",
"body": ["strictconcat($1 | $2 | $3)"],
"description": "A strict concatenation aggregate"
},
"Strict Count": {
"prefix": "strictcount",
"body": ["strictcount($1 | $2 | $3)"],
"description": "A strict count aggregate"
},
"Unique": {
"prefix": "unique",
"body": ["unique($1 | $2 | $3)"],
"description": "A unique aggregate"
},
"Exists": {
"prefix": "exists",
"body": ["exists($1 | $2 | $3)"],
"description": "An exists quantifier"
},
"For All": {
"prefix": "forall",
"body": ["forall($1 | $2 | $3)"],
"description": "A for all quantifier"
},
"For All and Exists": {
"prefix": "forex",
"body": ["forex($1 | $2 | $3)"],
"description": "A for all and exists quantifier"
}
}

View File

@@ -1,136 +0,0 @@
import { DecodedBqrsChunk, ResultSetSchema, ColumnKind, Column, ColumnValue } from './bqrs-cli-types';
import { LocationValue, ResultSetSchema as AdaptedSchema, ColumnSchema, ColumnType, LocationStyle } from 'semmle-bqrs';
import { ResultSet } from './interface-types';
// FIXME: This is a temporary bit of impedance matching to convert
// from the types provided by ./bqrs-cli-types, to the types used by
// the view layer.
//
// The reason that it is benign for now is that it is only used by
// feature-flag-guarded codepaths that won't be encountered by normal
// users. It is not yet guaranteed to produce correct output for raw
// results.
//
// Eventually, the view layer should be refactored to directly accept data
// of types coming from bqrs-cli-types, and this file can be deleted.
export type ResultRow = ResultValue[];
export interface ResultElement {
label: string;
location?: LocationValue;
}
export interface ResultUri {
uri: string;
}
export type ResultValue = ResultElement | ResultUri | string;
export interface RawResultSet {
readonly schema: AdaptedSchema;
readonly rows: readonly ResultRow[];
}
function adaptKind(kind: ColumnKind): ColumnType {
// XXX what about 'u'?
if (kind === 'e') {
return { type: 'e', primitiveType: 's', locationStyle: LocationStyle.FivePart, hasLabel: true };
}
else {
return { type: kind };
}
}
function adaptColumn(col: Column): ColumnSchema {
return { name: col.name!, type: adaptKind(col.kind) };
}
export function adaptSchema(schema: ResultSetSchema): AdaptedSchema {
return {
columns: schema.columns.map(adaptColumn),
name: schema.name,
tupleCount: schema.rows,
version: 0,
};
}
export function adaptValue(val: ColumnValue): ResultValue {
// XXX taking a lot of incorrect shortcuts here
if (typeof val === 'string') {
return val;
}
if (typeof val === 'number' || typeof val === 'boolean') {
return val + '';
}
const url = val.url;
if (typeof url === 'string') {
return url;
}
if (url === undefined) {
return 'none';
}
return {
label: val.label || '',
location: {
t: LocationStyle.FivePart,
lineStart: url.startLine,
lineEnd: url.endLine,
colStart: url.startColumn,
colEnd: url.endColumn,
// FIXME: This seems definitely wrong. Should we be using
// something like the code in sarif-utils.ts?
file: url.uri.replace(/file:/, ''),
}
};
}
export function adaptRow(row: ColumnValue[]): ResultRow {
return row.map(adaptValue);
}
export function adaptBqrs(schema: AdaptedSchema, page: DecodedBqrsChunk): RawResultSet {
return {
schema,
rows: page.tuples.map(adaptRow),
};
}
/**
* This type has two branches; we are in the process of changing from
* one to the other. The old way is to parse them inside the webview,
* the new way is to parse them in the extension. The main motivation
* for this transition is to make pagination possible in such a way
* that only one page needs to be sent from the extension to the webview.
*/
export type ParsedResultSets = ExtensionParsedResultSets | WebviewParsedResultSets;
/**
* The old method doesn't require any nontrivial information to be included here,
* just a tag to indicate that it is being used.
*/
export interface WebviewParsedResultSets {
t: 'WebviewParsed';
selectedTable?: string; // when undefined, means 'show default table'
}
/**
* The new method includes which bqrs page is being sent, and the
* actual results parsed on the extension side.
*/
export interface ExtensionParsedResultSets {
t: 'ExtensionParsed';
pageNumber: number;
numPages: number;
numInterpretedPages: number;
selectedTable?: string; // when undefined, means 'show default table'
resultSetNames: string[];
resultSet: ResultSet;
}

View File

@@ -0,0 +1,15 @@
/**
* The d3 library is designed to work in both the browser and
* node. Consequently their typings files refer to both node
* types like `Buffer` (which don't exist in the browser), and browser
* types like `Blob` (which don't exist in node). Instead of sticking
* all of `dom` in `compilerOptions.lib`, it suffices just to put in a
* stub definition of the affected types so that compilation
* succeeds.
*/
declare type RequestInit = Record<string, unknown>;
declare type ElementTagNameMap = any;
declare type NodeListOf<T> = Record<string, T>;
declare type Node = Record<string, unknown>;
declare type XMLDocument = Record<string, unknown>;

View File

@@ -84,12 +84,25 @@ export function encodeSourceArchiveUri(ref: ZipFileReference): vscode.Uri {
// This lets us separate the paths, ignoring the leading slash if we added one.
const sourceArchiveZipPathEndIndex = sourceArchiveZipPathStartIndex + sourceArchiveZipPath.length;
const authority = `${sourceArchiveZipPathStartIndex}-${sourceArchiveZipPathEndIndex}`;
return vscode.Uri.parse(zipArchiveScheme + ':/').with({
return vscode.Uri.parse(zipArchiveScheme + ':/', true).with({
path: encodedPath,
authority,
});
}
/**
* Convenience method to create a codeql-zip-archive with a path to the root
* archive
*
* @param pathToArchive the filesystem path to the root of the archive
*/
export function encodeArchiveBasePath(sourceArchiveZipPath: string) {
return encodeSourceArchiveUri({
sourceArchiveZipPath,
pathWithinSourceArchive: ''
});
}
const sourceArchiveUriAuthorityPattern = /^(\d+)-(\d+)$/;
class InvalidSourceArchiveUriError extends Error {
@@ -100,6 +113,14 @@ class InvalidSourceArchiveUriError extends Error {
/** Decodes an encoded source archive URI into its corresponding paths. Inverse of `encodeSourceArchiveUri`. */
export function decodeSourceArchiveUri(uri: vscode.Uri): ZipFileReference {
if (!uri.authority) {
// Uri is malformed, but this is recoverable
void logger.log(`Warning: ${new InvalidSourceArchiveUriError(uri).message}`);
return {
pathWithinSourceArchive: '/',
sourceArchiveZipPath: uri.path
};
}
const match = sourceArchiveUriAuthorityPattern.exec(uri.authority);
if (match === null)
throw new InvalidSourceArchiveUriError(uri);
@@ -108,7 +129,7 @@ export function decodeSourceArchiveUri(uri: vscode.Uri): ZipFileReference {
if (isNaN(zipPathStartIndex) || isNaN(zipPathEndIndex))
throw new InvalidSourceArchiveUriError(uri);
return {
pathWithinSourceArchive: uri.path.substring(zipPathEndIndex),
pathWithinSourceArchive: uri.path.substring(zipPathEndIndex) || '/',
sourceArchiveZipPath: uri.path.substring(zipPathStartIndex, zipPathEndIndex),
};
}
@@ -120,7 +141,7 @@ function ensureFile(map: DirectoryHierarchyMap, file: string) {
const dirname = path.dirname(file);
if (dirname === '.') {
const error = `Ill-formed path ${file} in zip archive (expected absolute path)`;
logger.log(error);
void logger.log(error);
throw new Error(error);
}
ensureDir(map, dirname);

View File

@@ -0,0 +1,205 @@
import {
window,
TreeDataProvider,
EventEmitter,
Event,
ProviderResult,
TreeItemCollapsibleState,
TreeItem,
TreeView,
TextEditorSelectionChangeEvent,
TextEditorSelectionChangeKind,
Location,
Range,
Uri
} from 'vscode';
import * as path from 'path';
import { DatabaseItem } from './databases';
import { UrlValue, BqrsId } from './pure/bqrs-cli-types';
import { showLocation } from './interface-utils';
import { isStringLoc, isWholeFileLoc, isLineColumnLoc } from './pure/bqrs-utils';
import { commandRunner } from './commandRunner';
import { DisposableObject } from './pure/disposable-object';
import { showAndLogErrorMessage } from './helpers';
export interface AstItem {
id: BqrsId;
label?: string;
location?: UrlValue;
fileLocation?: Location;
children: ChildAstItem[];
order: number;
}
export interface ChildAstItem extends AstItem {
parent: ChildAstItem | AstItem;
}
class AstViewerDataProvider extends DisposableObject implements TreeDataProvider<AstItem> {
public roots: AstItem[] = [];
public db: DatabaseItem | undefined;
private _onDidChangeTreeData =
this.push(new EventEmitter<AstItem | undefined>());
readonly onDidChangeTreeData: Event<AstItem | undefined> =
this._onDidChangeTreeData.event;
constructor() {
super();
this.push(
commandRunner('codeQLAstViewer.gotoCode',
async (item: AstItem) => {
await showLocation(item.fileLocation);
})
);
}
refresh(): void {
this._onDidChangeTreeData.fire(undefined);
}
getChildren(item?: AstItem): ProviderResult<AstItem[]> {
const children = item ? item.children : this.roots;
return children.sort((c1, c2) => (c1.order - c2.order));
}
getParent(item: ChildAstItem): ProviderResult<AstItem> {
return item.parent;
}
getTreeItem(item: AstItem): TreeItem {
const line = this.extractLineInfo(item?.location);
const state = item.children.length
? TreeItemCollapsibleState.Collapsed
: TreeItemCollapsibleState.None;
const treeItem = new TreeItem(item.label || '', state);
treeItem.description = line ? `Line ${line}` : '';
treeItem.id = String(item.id);
treeItem.tooltip = `${treeItem.description} ${treeItem.label}`;
treeItem.command = {
command: 'codeQLAstViewer.gotoCode',
title: 'Go To Code',
tooltip: `Go To ${item.location}`,
arguments: [item]
};
return treeItem;
}
private extractLineInfo(loc?: UrlValue) {
if (!loc) {
return '';
} else if (isStringLoc(loc)) {
return loc;
} else if (isWholeFileLoc(loc)) {
return loc.uri;
} else if (isLineColumnLoc(loc)) {
return loc.startLine;
} else {
return '';
}
}
}
export class AstViewer extends DisposableObject {
private treeView: TreeView<AstItem>;
private treeDataProvider: AstViewerDataProvider;
private currentFileUri: Uri | undefined;
constructor() {
super();
this.treeDataProvider = new AstViewerDataProvider();
this.treeView = window.createTreeView('codeQLAstViewer', {
treeDataProvider: this.treeDataProvider,
showCollapseAll: true
});
this.push(this.treeView);
this.push(this.treeDataProvider);
this.push(
commandRunner('codeQLAstViewer.clear', async () => {
this.clear();
})
);
this.push(window.onDidChangeTextEditorSelection(this.updateTreeSelection, this));
}
updateRoots(roots: AstItem[], db: DatabaseItem, fileUri: Uri) {
this.treeDataProvider.roots = roots;
this.treeDataProvider.db = db;
this.treeDataProvider.refresh();
this.treeView.message = `AST for ${path.basename(fileUri.fsPath)}`;
this.currentFileUri = fileUri;
// Handle error on reveal. This could happen if
// the tree view is disposed during the reveal.
this.treeView.reveal(roots[0], { focus: false })?.then(
() => { /**/ },
err => showAndLogErrorMessage(err)
);
}
private updateTreeSelection(e: TextEditorSelectionChangeEvent) {
function isInside(selectedRange: Range, astRange?: Range): boolean {
return !!astRange?.contains(selectedRange);
}
// Recursively iterate all children until we find the node with the smallest
// range that contains the selection.
// Some nodes do not have a location, but their children might, so must
// recurse though location-less AST nodes to see if children are correct.
function findBest(selectedRange: Range, items?: AstItem[]): AstItem | undefined {
if (!items || !items.length) {
return;
}
for (const item of items) {
let candidate: AstItem | undefined = undefined;
if (isInside(selectedRange, item.fileLocation?.range)) {
candidate = item;
}
// always iterate through children since the location of an AST node in code QL does not
// always cover the complete text of the node.
candidate = findBest(selectedRange, item.children) || candidate;
if (candidate) {
return candidate;
}
}
return;
}
// Avoid recursive tree-source code updates.
if (e.kind === TextEditorSelectionChangeKind.Command) {
return;
}
if (
this.treeView.visible &&
e.textEditor.document.uri.fsPath === this.currentFileUri?.fsPath &&
e.selections.length === 1
) {
const selection = e.selections[0];
const range = selection.anchor.isBefore(selection.active)
? new Range(selection.anchor, selection.active)
: new Range(selection.active, selection.anchor);
const targetItem = findBest(range, this.treeDataProvider.roots);
if (targetItem) {
// Handle error on reveal. This could happen if
// the tree view is disposed during the reveal.
this.treeView.reveal(targetItem)?.then(
() => { /**/ },
err => showAndLogErrorMessage(err)
);
}
}
}
private clear() {
this.treeDataProvider.roots = [];
this.treeDataProvider.db = undefined;
this.treeDataProvider.refresh();
this.treeView.message = undefined;
this.currentFileUri = undefined;
}
}

View File

@@ -0,0 +1,72 @@
import * as vscode from 'vscode';
import * as Octokit from '@octokit/rest';
const GITHUB_AUTH_PROVIDER_ID = 'github';
// We need 'repo' scope for triggering workflows and 'gist' scope for exporting results to Gist.
// For a comprehensive list of scopes, see:
// https://docs.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps
const SCOPES = ['repo', 'gist'];
/**
* Handles authentication to GitHub, using the VS Code [authentication API](https://code.visualstudio.com/api/references/vscode-api#authentication).
*/
export class Credentials {
private octokit: Octokit.Octokit | undefined;
// Explicitly make the constructor private, so that we can't accidentally call the constructor from outside the class
// without also initializing the class.
// eslint-disable-next-line @typescript-eslint/no-empty-function
private constructor() { }
/**
* Initializes an instance of credentials with an octokit instance.
*
* Do not call this method until you know you actually need an instance of credentials.
* since calling this method will require the user to log in.
*
* @param context The extension context.
* @returns An instance of credentials.
*/
static async initialize(context: vscode.ExtensionContext): Promise<Credentials> {
const c = new Credentials();
c.registerListeners(context);
c.octokit = await c.createOctokit(false);
return c;
}
private async createOctokit(createIfNone: boolean): Promise<Octokit.Octokit | undefined> {
const session = await vscode.authentication.getSession(GITHUB_AUTH_PROVIDER_ID, SCOPES, { createIfNone });
if (session) {
return new Octokit.Octokit({
auth: session.accessToken
});
} else {
return undefined;
}
}
registerListeners(context: vscode.ExtensionContext): void {
// Sessions are changed when a user logs in or logs out.
context.subscriptions.push(vscode.authentication.onDidChangeSessions(async e => {
if (e.provider.id === GITHUB_AUTH_PROVIDER_ID) {
this.octokit = await this.createOctokit(false);
}
}));
}
async getOctokit(): Promise<Octokit.Octokit> {
if (this.octokit) {
return this.octokit;
}
this.octokit = await this.createOctokit(true);
// octokit shouldn't be undefined, since we've set "createIfNone: true".
// The following block is mainly here to prevent a compiler error.
if (!this.octokit) {
throw new Error('Did not initialize Octokit.');
}
return this.octokit;
}
}

View File

@@ -1,11 +0,0 @@
/**
* The npm library jszip is designed to work in both the browser and
* node. Consequently its typings @types/jszip refers to both node
* types like `Buffer` (which don't exist in the browser), and browser
* types like `Blob` (which don't exist in node). Instead of sticking
* all of `dom` in `compilerOptions.lib`, it suffices just to put in a
* stub definition of the type `Blob` here so that compilation
* succeeds.
*/
declare type Blob = string;

View File

@@ -1,6 +1,7 @@
import * as semver from 'semver';
import { runCodeQlCliCommand } from './cli';
import { Logger } from './logging';
import { getErrorMessage } from './pure/helpers-pure';
/**
* Get the version of a CodeQL CLI.
@@ -18,7 +19,7 @@ export async function getCodeQlCliVersion(codeQlPath: string, logger: Logger): P
} catch (e) {
// Failed to run the version command. This might happen if the cli version is _really_ old, or it is corrupted.
// Either way, we can't determine compatibility.
logger.log(`Failed to run 'codeql version'. Reason: ${e.message}`);
void logger.log(`Failed to run 'codeql version'. Reason: ${getErrorMessage(e)}`);
return undefined;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,246 @@
import {
CancellationToken,
ProgressOptions,
window as Window,
commands,
Disposable,
ProgressLocation
} from 'vscode';
import { showAndLogErrorMessage, showAndLogWarningMessage } from './helpers';
import { logger } from './logging';
import { getErrorMessage, getErrorStack } from './pure/helpers-pure';
import { telemetryListener } from './telemetry';
export class UserCancellationException extends Error {
/**
* @param message The error message
* @param silent If silent is true, then this exception will avoid showing a warning message to the user.
*/
constructor(message?: string, public readonly silent = false) {
super(message);
}
}
export interface ProgressUpdate {
/**
* The current step
*/
step: number;
/**
* The maximum step. This *should* be constant for a single job.
*/
maxStep: number;
/**
* The current progress message
*/
message: string;
}
export type ProgressCallback = (p: ProgressUpdate) => void;
/**
* A task that handles command invocations from `commandRunner`
* and includes a progress monitor.
*
*
* Arguments passed to the command handler are passed along,
* untouched to this `ProgressTask` instance.
*
* @param progress a progress handler function. Call this
* function with a `ProgressUpdate` instance in order to
* denote some progress being achieved on this task.
* @param token a cencellation token
* @param args arguments passed to this task passed on from
* `commands.registerCommand`.
*/
export type ProgressTask<R> = (
progress: ProgressCallback,
token: CancellationToken,
...args: any[]
) => Thenable<R>;
/**
* A task that handles command invocations from `commandRunner`.
* Arguments passed to the command handler are passed along,
* untouched to this `NoProgressTask` instance.
*
* @param args arguments passed to this task passed on from
* `commands.registerCommand`.
*/
type NoProgressTask = ((...args: any[]) => Promise<any>);
/**
* This mediates between the kind of progress callbacks we want to
* write (where we *set* current progress position and give
* `maxSteps`) and the kind vscode progress api expects us to write
* (which increment progress by a certain amount out of 100%).
*
* Where possible, the `commandRunner` function below should be used
* instead of this function. The commandRunner is meant for wrapping
* top-level commands and provides error handling and other support
* automatically.
*
* Only use this function if you need a progress monitor and the
* control flow does not always come from a command (eg- during
* extension activation, or from an internal language server
* request).
*/
export function withProgress<R>(
options: ProgressOptions,
task: ProgressTask<R>,
...args: any[]
): Thenable<R> {
let progressAchieved = 0;
return Window.withProgress(options,
(progress, token) => {
return task(p => {
const { message, step, maxStep } = p;
const increment = 100 * (step - progressAchieved) / maxStep;
progressAchieved = step;
progress.report({ message, increment });
}, token, ...args);
});
}
/**
* A generic wrapper for command registration. This wrapper adds uniform error handling for commands.
*
* In this variant of the command runner, no progress monitor is used.
*
* @param commandId The ID of the command to register.
* @param task The task to run. It is passed directly to `commands.registerCommand`. Any
* arguments to the command handler are passed on to the task.
*/
export function commandRunner(
commandId: string,
task: NoProgressTask,
): Disposable {
return commands.registerCommand(commandId, async (...args: any[]) => {
const startTime = Date.now();
let error: Error | undefined;
try {
return await task(...args);
} catch (e) {
const errorMessage = `${getErrorMessage(e) || e} (${commandId})`;
error = e instanceof Error ? e : new Error(errorMessage);
const errorStack = getErrorStack(e);
if (e instanceof UserCancellationException) {
// User has cancelled this action manually
if (e.silent) {
void logger.log(errorMessage);
} else {
void showAndLogWarningMessage(errorMessage);
}
} else {
// Include the full stack in the error log only.
const fullMessage = errorStack
? `${errorMessage}\n${errorStack}`
: errorMessage;
void showAndLogErrorMessage(errorMessage, {
fullMessage
});
}
return undefined;
} finally {
const executionTime = Date.now() - startTime;
telemetryListener.sendCommandUsage(commandId, executionTime, error);
}
});
}
/**
* A generic wrapper for command registration. This wrapper adds uniform error handling,
* progress monitoring, and cancellation for commands.
*
* @param commandId The ID of the command to register.
* @param task The task to run. It is passed directly to `commands.registerCommand`. Any
* arguments to the command handler are passed on to the task after the progress callback
* and cancellation token.
* @param progressOptions Progress options to be sent to the progress monitor.
*/
export function commandRunnerWithProgress<R>(
commandId: string,
task: ProgressTask<R>,
progressOptions: Partial<ProgressOptions>,
outputLogger = logger
): Disposable {
return commands.registerCommand(commandId, async (...args: any[]) => {
const startTime = Date.now();
let error: Error | undefined;
const progressOptionsWithDefaults = {
location: ProgressLocation.Notification,
...progressOptions
};
try {
return await withProgress(progressOptionsWithDefaults, task, ...args);
} catch (e) {
const errorMessage = `${getErrorMessage(e) || e} (${commandId})`;
error = e instanceof Error ? e : new Error(errorMessage);
const errorStack = getErrorStack(e);
if (e instanceof UserCancellationException) {
// User has cancelled this action manually
if (e.silent) {
void outputLogger.log(errorMessage);
} else {
void showAndLogWarningMessage(errorMessage, { outputLogger });
}
} else {
// Include the full stack in the error log only.
const fullMessage = errorStack
? `${errorMessage}\n${errorStack}`
: errorMessage;
void showAndLogErrorMessage(errorMessage, {
outputLogger,
fullMessage
});
}
return undefined;
} finally {
const executionTime = Date.now() - startTime;
telemetryListener.sendCommandUsage(commandId, executionTime, error);
}
});
}
/**
* Displays a progress monitor that indicates how much progess has been made
* reading from a stream.
*
* @param readable The stream to read progress from
* @param messagePrefix A prefix for displaying the message
* @param totalNumBytes Total number of bytes in this stream
* @param progress The progress callback used to set messages
*/
export function reportStreamProgress(
readable: NodeJS.ReadableStream,
messagePrefix: string,
totalNumBytes?: number,
progress?: ProgressCallback
) {
if (progress && totalNumBytes) {
let numBytesDownloaded = 0;
const bytesToDisplayMB = (numBytes: number): string => `${(numBytes / (1024 * 1024)).toFixed(1)} MB`;
const updateProgress = () => {
progress({
step: numBytesDownloaded,
maxStep: totalNumBytes,
message: `${messagePrefix} [${bytesToDisplayMB(numBytesDownloaded)} of ${bytesToDisplayMB(totalNumBytes)}]`,
});
};
// Display the progress straight away rather than waiting for the first chunk.
updateProgress();
readable.on('data', data => {
numBytesDownloaded += data.length;
updateProgress();
});
} else if (progress) {
progress({
step: 1,
maxStep: 2,
message: `${messagePrefix} (Size unknown)`,
});
}
}

View File

@@ -1,4 +1,4 @@
import { DisposableObject } from '@github/codeql-vscode-utils';
import { DisposableObject } from '../pure/disposable-object';
import {
WebviewPanel,
ExtensionContext,
@@ -8,24 +8,25 @@ import {
} from 'vscode';
import * as path from 'path';
import { tmpDir } from '../run-queries';
import { CompletedQuery } from '../query-results';
import { tmpDir } from '../helpers';
import {
FromCompareViewMessage,
ToCompareViewMessage,
QueryCompareResult,
} from '../interface-types';
} from '../pure/interface-types';
import { Logger } from '../logging';
import { CodeQLCliServer } from '../cli';
import { DatabaseManager } from '../databases';
import { getHtmlForWebview, jumpToLocation } from '../interface-utils';
import { adaptSchema, adaptBqrs, RawResultSet } from '../adapt';
import { BQRSInfo } from '../bqrs-cli-types';
import { transformBqrsResultSet, RawResultSet, BQRSInfo } from '../pure/bqrs-cli-types';
import resultsDiff from './resultsDiff';
import { CompletedLocalQueryInfo } from '../query-results';
import { getErrorMessage } from '../pure/helpers-pure';
import { HistoryItemLabelProvider } from '../history-item-label-provider';
interface ComparePair {
from: CompletedQuery;
to: CompletedQuery;
from: CompletedLocalQueryInfo;
to: CompletedLocalQueryInfo;
}
export class CompareInterfaceManager extends DisposableObject {
@@ -39,16 +40,17 @@ export class CompareInterfaceManager extends DisposableObject {
private databaseManager: DatabaseManager,
private cliServer: CodeQLCliServer,
private logger: Logger,
private labelProvider: HistoryItemLabelProvider,
private showQueryResultsCallback: (
item: CompletedQuery
item: CompletedLocalQueryInfo
) => Promise<void>
) {
super();
}
async showResults(
from: CompletedQuery,
to: CompletedQuery,
from: CompletedLocalQueryInfo,
to: CompletedLocalQueryInfo,
selectedResultSetName?: string
) {
this.comparePair = { from, to };
@@ -71,7 +73,7 @@ export class CompareInterfaceManager extends DisposableObject {
try {
rows = this.compareResults(fromResultSet, toResultSet);
} catch (e) {
message = e.message;
message = getErrorMessage(e);
}
await this.postMessage({
@@ -81,18 +83,14 @@ export class CompareInterfaceManager extends DisposableObject {
// since we split the description into several rows
// only run interpolation if the label is user-defined
// otherwise we will wind up with duplicated rows
name: from.options.label
? from.interpolate(from.getLabel())
: from.queryName,
status: from.statusString,
time: from.time,
name: this.labelProvider.getShortLabel(from),
status: from.completedQuery.statusString,
time: from.startTime,
},
toQuery: {
name: to.options.label
? to.interpolate(to.getLabel())
: to.queryName,
status: to.statusString,
time: to.time,
name: this.labelProvider.getShortLabel(to),
status: to.completedQuery.statusString,
time: to.startTime,
},
},
columns: fromResultSet.schema.columns,
@@ -100,7 +98,7 @@ export class CompareInterfaceManager extends DisposableObject {
currentResultSetName: currentResultSetName,
rows,
message,
datebaseUri: to.database.databaseUri,
databaseUri: to.initialInfo.databaseInfo.databaseUri,
});
}
}
@@ -122,33 +120,34 @@ export class CompareInterfaceManager extends DisposableObject {
],
}
));
this.panel.onDidDispose(
this.push(this.panel.onDidDispose(
() => {
this.panel = undefined;
this.comparePair = undefined;
},
null,
ctx.subscriptions
);
));
const scriptPathOnDisk = Uri.file(
ctx.asAbsolutePath('out/compareView.js')
);
const stylesheetPathOnDisk = Uri.file(
ctx.asAbsolutePath('out/resultsView.css')
ctx.asAbsolutePath('out/view/resultsView.css')
);
panel.webview.html = getHtmlForWebview(
panel.webview,
scriptPathOnDisk,
stylesheetPathOnDisk
[stylesheetPathOnDisk],
false
);
panel.webview.onDidReceiveMessage(
this.push(panel.webview.onDidReceiveMessage(
async (e) => this.handleMsgFromView(e),
undefined,
ctx.subscriptions
);
));
}
return this.panel;
}
@@ -174,7 +173,7 @@ export class CompareInterfaceManager extends DisposableObject {
break;
case 'changeCompare':
this.changeTable(msg.newResultSetName);
await this.changeTable(msg.newResultSetName);
break;
case 'viewSourceFile':
@@ -192,15 +191,15 @@ export class CompareInterfaceManager extends DisposableObject {
}
private async findCommonResultSetNames(
from: CompletedQuery,
to: CompletedQuery,
from: CompletedLocalQueryInfo,
to: CompletedLocalQueryInfo,
selectedResultSetName: string | undefined
): Promise<[string[], string, RawResultSet, RawResultSet]> {
const fromSchemas = await this.cliServer.bqrsInfo(
from.query.resultsPaths.resultsPath
from.completedQuery.query.resultsPaths.resultsPath
);
const toSchemas = await this.cliServer.bqrsInfo(
to.query.resultsPaths.resultsPath
to.completedQuery.query.resultsPaths.resultsPath
);
const fromSchemaNames = fromSchemas['result-sets'].map(
(schema) => schema.name
@@ -216,12 +215,12 @@ export class CompareInterfaceManager extends DisposableObject {
const fromResultSet = await this.getResultSet(
fromSchemas,
currentResultSetName,
from.query.resultsPaths.resultsPath
from.completedQuery.query.resultsPaths.resultsPath
);
const toResultSet = await this.getResultSet(
toSchemas,
currentResultSetName,
to.query.resultsPaths.resultsPath
to.completedQuery.query.resultsPaths.resultsPath
);
return [
commonResultSetNames,
@@ -257,8 +256,7 @@ export class CompareInterfaceManager extends DisposableObject {
resultsPath,
resultSetName
);
const adaptedSchema = adaptSchema(schema);
return adaptBqrs(adaptedSchema, chunk);
return transformBqrsResultSet(schema, chunk);
}
private compareResults(
@@ -269,11 +267,11 @@ export class CompareInterfaceManager extends DisposableObject {
return resultsDiff(fromResults, toResults);
}
private openQuery(kind: 'from' | 'to') {
private async openQuery(kind: 'from' | 'to') {
const toOpen =
kind === 'from' ? this.comparePair?.from : this.comparePair?.to;
if (toOpen) {
this.showQueryResultsCallback(toOpen);
await this.showQueryResultsCallback(toOpen);
}
}
}

View File

@@ -1,5 +1,5 @@
import { RawResultSet } from '../adapt';
import { QueryCompareResult } from '../interface-types';
import { RawResultSet } from '../pure/bqrs-cli-types';
import { QueryCompareResult } from '../pure/interface-types';
/**
* Compare the rows of two queries. Use deep equality to determine if

View File

@@ -5,7 +5,7 @@ import * as Rdom from 'react-dom';
import {
ToCompareViewMessage,
SetComparisonsMessage,
} from '../../interface-types';
} from '../../pure/interface-types';
import CompareSelector from './CompareSelector';
import { vscode } from '../../view/vscode-api';
import CompareTable from './CompareTable';
@@ -17,11 +17,11 @@ const emptyComparison: SetComparisonsMessage = {
columns: [],
commonResultSetNames: [],
currentResultSetName: '',
datebaseUri: '',
databaseUri: '',
message: 'Empty comparison'
};
export function Compare(_: {}): JSX.Element {
export function Compare(_: Record<string, never>): JSX.Element {
const [comparison, setComparison] = useState<SetComparisonsMessage>(
emptyComparison
);
@@ -31,10 +31,16 @@ export function Compare(_: {}): JSX.Element {
useEffect(() => {
window.addEventListener('message', (evt: MessageEvent) => {
const msg: ToCompareViewMessage = evt.data;
switch (msg.t) {
case 'setComparisons':
setComparison(msg);
if (evt.origin === window.origin) {
const msg: ToCompareViewMessage = evt.data;
switch (msg.t) {
case 'setComparisons':
setComparison(msg);
}
} else {
// sanitize origin
const origin = evt.origin.replace(/\n|\r/g, '');
console.error(`Invalid event origin ${origin}`);
}
});
});

View File

@@ -1,9 +1,9 @@
import * as React from 'react';
import { SetComparisonsMessage } from '../../interface-types';
import { SetComparisonsMessage } from '../../pure/interface-types';
import RawTableHeader from '../../view/RawTableHeader';
import { className } from '../../view/result-table-utils';
import { ResultRow } from '../../adapt';
import { ResultRow } from '../../pure/bqrs-cli-types';
import RawTableRow from '../../view/RawTableRow';
import { vscode } from '../../view/vscode-api';
@@ -76,7 +76,7 @@ export default function CompareTable(props: Props) {
schemaName={comparison.currentResultSetName}
preventSort={true}
/>
{createRows(rows.from, comparison.datebaseUri)}
{createRows(rows.from, comparison.databaseUri)}
</table>
</td>
<td>
@@ -86,7 +86,7 @@ export default function CompareTable(props: Props) {
schemaName={comparison.currentResultSetName}
preventSort={true}
/>
{createRows(rows.to, comparison.datebaseUri)}
{createRows(rows.to, comparison.databaseUri)}
</table>
</td>
</tr>

View File

@@ -4,21 +4,15 @@
"moduleResolution": "node",
"target": "es6",
"outDir": "out",
"lib": [
"es6",
"dom"
],
"lib": ["ES2021", "dom"],
"jsx": "react",
"sourceMap": true,
"rootDir": "../..",
"rootDir": "..",
"strict": true,
"noUnusedLocals": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"experimentalDecorators": true,
"typeRoots" : ["./typings"]
"experimentalDecorators": true
},
"exclude": [
"node_modules"
]
"exclude": ["node_modules"]
}

View File

@@ -1,10 +1,11 @@
import { DisposableObject } from '@github/codeql-vscode-utils';
import { DisposableObject } from './pure/disposable-object';
import { workspace, Event, EventEmitter, ConfigurationChangeEvent, ConfigurationTarget } from 'vscode';
import { DistributionManager } from './distribution';
import { logger } from './logging';
import { ONE_DAY_IN_MS } from './pure/helpers-pure';
/** Helper class to look up a labelled (and possibly nested) setting. */
class Setting {
export class Setting {
name: string;
parent?: Setting;
@@ -39,69 +40,98 @@ class Setting {
const ROOT_SETTING = new Setting('codeQL');
// Enable experimental features
// Global configuration
const TELEMETRY_SETTING = new Setting('telemetry', ROOT_SETTING);
const AST_VIEWER_SETTING = new Setting('astViewer', ROOT_SETTING);
const GLOBAL_TELEMETRY_SETTING = new Setting('telemetry');
/**
* Any settings below are deliberately not in package.json so that
* they do not appear in the settings ui in vscode itself. If users
* want to enable experimental features, they can add them directly in
* their vscode settings json file.
*/
export const LOG_TELEMETRY = new Setting('logTelemetry', TELEMETRY_SETTING);
export const ENABLE_TELEMETRY = new Setting('enableTelemetry', TELEMETRY_SETTING);
/* Advanced setting: used to enable bqrs parsing in the cli instead of in the webview. */
export const EXPERIMENTAL_BQRS_SETTING = new Setting('experimentalBqrsParsing', ROOT_SETTING);
export const GLOBAL_ENABLE_TELEMETRY = new Setting('enableTelemetry', GLOBAL_TELEMETRY_SETTING);
// Distribution configuration
const DISTRIBUTION_SETTING = new Setting('cli', ROOT_SETTING);
const CUSTOM_CODEQL_PATH_SETTING = new Setting('executablePath', DISTRIBUTION_SETTING);
export const CUSTOM_CODEQL_PATH_SETTING = new Setting('executablePath', DISTRIBUTION_SETTING);
const INCLUDE_PRERELEASE_SETTING = new Setting('includePrerelease', DISTRIBUTION_SETTING);
const PERSONAL_ACCESS_TOKEN_SETTING = new Setting('personalAccessToken', DISTRIBUTION_SETTING);
// Query History configuration
const QUERY_HISTORY_SETTING = new Setting('queryHistory', ROOT_SETTING);
const QUERY_HISTORY_FORMAT_SETTING = new Setting('format', QUERY_HISTORY_SETTING);
const QUERY_HISTORY_TTL = new Setting('format', QUERY_HISTORY_SETTING);
/** When these settings change, the distribution should be updated. */
const DISTRIBUTION_CHANGE_SETTINGS = [CUSTOM_CODEQL_PATH_SETTING, INCLUDE_PRERELEASE_SETTING, PERSONAL_ACCESS_TOKEN_SETTING];
export interface DistributionConfig {
customCodeQlPath?: string;
readonly customCodeQlPath?: string;
updateCustomCodeQlPath: (newPath: string | undefined) => Promise<void>;
includePrerelease: boolean;
personalAccessToken?: string;
ownerName?: string;
repositoryName?: string;
onDidChangeDistributionConfiguration?: Event<void>;
onDidChangeConfiguration?: Event<void>;
}
// Query server configuration
const RUNNING_QUERIES_SETTING = new Setting('runningQueries', ROOT_SETTING);
const NUMBER_OF_THREADS_SETTING = new Setting('numberOfThreads', RUNNING_QUERIES_SETTING);
const SAVE_CACHE_SETTING = new Setting('saveCache', RUNNING_QUERIES_SETTING);
const CACHE_SIZE_SETTING = new Setting('cacheSize', RUNNING_QUERIES_SETTING);
const TIMEOUT_SETTING = new Setting('timeout', RUNNING_QUERIES_SETTING);
const MEMORY_SETTING = new Setting('memory', RUNNING_QUERIES_SETTING);
const DEBUG_SETTING = new Setting('debug', RUNNING_QUERIES_SETTING);
const MAX_PATHS = new Setting('maxPaths', RUNNING_QUERIES_SETTING);
const RUNNING_TESTS_SETTING = new Setting('runningTests', ROOT_SETTING);
const RESULTS_DISPLAY_SETTING = new Setting('resultsDisplay', ROOT_SETTING);
export const ADDITIONAL_TEST_ARGUMENTS_SETTING = new Setting('additionalTestArguments', RUNNING_TESTS_SETTING);
export const NUMBER_OF_TEST_THREADS_SETTING = new Setting('numberOfThreads', RUNNING_TESTS_SETTING);
export const MAX_QUERIES = new Setting('maxQueries', RUNNING_QUERIES_SETTING);
export const AUTOSAVE_SETTING = new Setting('autoSave', RUNNING_QUERIES_SETTING);
export const PAGE_SIZE = new Setting('pageSize', RESULTS_DISPLAY_SETTING);
const CUSTOM_LOG_DIRECTORY_SETTING = new Setting('customLogDirectory', RUNNING_QUERIES_SETTING);
/** When these settings change, the running query server should be restarted. */
const QUERY_SERVER_RESTARTING_SETTINGS = [NUMBER_OF_THREADS_SETTING, MEMORY_SETTING, DEBUG_SETTING];
const QUERY_SERVER_RESTARTING_SETTINGS = [
NUMBER_OF_THREADS_SETTING, SAVE_CACHE_SETTING, CACHE_SIZE_SETTING, MEMORY_SETTING,
DEBUG_SETTING, CUSTOM_LOG_DIRECTORY_SETTING,
];
export interface QueryServerConfig {
codeQlPath: string;
debug: boolean;
numThreads: number;
saveCache: boolean;
cacheSize: number;
queryMemoryMb?: number;
timeoutSecs: number;
onDidChangeQueryServerConfiguration?: Event<void>;
customLogDirectory?: string;
onDidChangeConfiguration?: Event<void>;
}
/** When these settings change, the query history should be refreshed. */
const QUERY_HISTORY_SETTINGS = [QUERY_HISTORY_FORMAT_SETTING];
const QUERY_HISTORY_SETTINGS = [QUERY_HISTORY_FORMAT_SETTING, QUERY_HISTORY_TTL];
export interface QueryHistoryConfig {
format: string;
onDidChangeQueryHistoryConfiguration: Event<void>;
ttlInMillis: number;
onDidChangeConfiguration: Event<void>;
}
abstract class ConfigListener extends DisposableObject {
const CLI_SETTINGS = [ADDITIONAL_TEST_ARGUMENTS_SETTING, NUMBER_OF_TEST_THREADS_SETTING, NUMBER_OF_THREADS_SETTING, MAX_PATHS];
export interface CliConfig {
additionalTestArguments: string[];
numberTestThreads: number;
numberThreads: number;
maxPaths: number;
onDidChangeConfiguration?: Event<void>;
}
export abstract class ConfigListener extends DisposableObject {
protected readonly _onDidChangeConfiguration = this.push(new EventEmitter<void>());
constructor() {
@@ -126,7 +156,11 @@ abstract class ConfigListener extends DisposableObject {
protected abstract handleDidChangeConfiguration(e: ConfigurationChangeEvent): void;
private updateConfiguration(): void {
this._onDidChangeConfiguration.fire();
this._onDidChangeConfiguration.fire(undefined);
}
public get onDidChangeConfiguration(): Event<void> {
return this._onDidChangeConfiguration.event;
}
}
@@ -143,8 +177,8 @@ export class DistributionConfigListener extends ConfigListener implements Distri
return PERSONAL_ACCESS_TOKEN_SETTING.getValue() || undefined;
}
public get onDidChangeDistributionConfiguration(): Event<void> {
return this._onDidChangeConfiguration.event;
public async updateCustomCodeQlPath(newPath: string | undefined) {
await CUSTOM_CODEQL_PATH_SETTING.updateValue(newPath, ConfigurationTarget.Global);
}
protected handleDidChangeConfiguration(e: ConfigurationChangeEvent): void {
@@ -153,7 +187,7 @@ export class DistributionConfigListener extends ConfigListener implements Distri
}
export class QueryServerConfigListener extends ConfigListener implements QueryServerConfig {
private constructor(private _codeQlPath: string) {
public constructor(private _codeQlPath = '') {
super();
}
@@ -164,7 +198,7 @@ export class QueryServerConfigListener extends ConfigListener implements QuerySe
config.push(distributionManager.onDidChangeDistribution(async () => {
const codeQlPath = await distributionManager.getCodeQlPathWithoutVersionCheck();
config._codeQlPath = codeQlPath!;
config._onDidChangeConfiguration.fire();
config._onDidChangeConfiguration.fire(undefined);
}));
}
return config;
@@ -174,10 +208,22 @@ export class QueryServerConfigListener extends ConfigListener implements QuerySe
return this._codeQlPath;
}
public get customLogDirectory(): string | undefined {
return CUSTOM_LOG_DIRECTORY_SETTING.getValue<string>() || undefined;
}
public get numThreads(): number {
return NUMBER_OF_THREADS_SETTING.getValue<number>();
}
public get saveCache(): boolean {
return SAVE_CACHE_SETTING.getValue<boolean>();
}
public get cacheSize(): number {
return CACHE_SIZE_SETTING.getValue<number | null>() || 0;
}
/** Gets the configured query timeout, in seconds. This looks up the setting at the time of access. */
public get timeoutSecs(): number {
return TIMEOUT_SETTING.getValue<number | null>() || 0;
@@ -189,7 +235,7 @@ export class QueryServerConfigListener extends ConfigListener implements QuerySe
return undefined;
}
if (memory == 0 || typeof (memory) !== 'number') {
logger.log(`Ignoring value '${memory}' for setting ${MEMORY_SETTING.qualifiedName}`);
void logger.log(`Ignoring value '${memory}' for setting ${MEMORY_SETTING.qualifiedName}`);
return undefined;
}
return memory;
@@ -199,10 +245,6 @@ export class QueryServerConfigListener extends ConfigListener implements QuerySe
return DEBUG_SETTING.getValue<boolean>();
}
public get onDidChangeQueryServerConfiguration(): Event<void> {
return this._onDidChangeConfiguration.event;
}
protected handleDidChangeConfiguration(e: ConfigurationChangeEvent): void {
this.handleDidChangeConfigurationForRelevantSettings(QUERY_SERVER_RESTARTING_SETTINGS, e);
}
@@ -213,11 +255,120 @@ export class QueryHistoryConfigListener extends ConfigListener implements QueryH
this.handleDidChangeConfigurationForRelevantSettings(QUERY_HISTORY_SETTINGS, e);
}
public get onDidChangeQueryHistoryConfiguration(): Event<void> {
return this._onDidChangeConfiguration.event;
}
public get format(): string {
return QUERY_HISTORY_FORMAT_SETTING.getValue<string>();
}
/**
* The configuration value is in days, but return the value in milliseconds to make it easier to use.
*/
public get ttlInMillis(): number {
return (QUERY_HISTORY_TTL.getValue<number>() || 30) * ONE_DAY_IN_MS;
}
}
export class CliConfigListener extends ConfigListener implements CliConfig {
public get additionalTestArguments(): string[] {
return ADDITIONAL_TEST_ARGUMENTS_SETTING.getValue();
}
public get numberTestThreads(): number {
return NUMBER_OF_TEST_THREADS_SETTING.getValue();
}
public get numberThreads(): number {
return NUMBER_OF_THREADS_SETTING.getValue<number>();
}
public get maxPaths(): number {
return MAX_PATHS.getValue<number>();
}
protected handleDidChangeConfiguration(e: ConfigurationChangeEvent): void {
this.handleDidChangeConfigurationForRelevantSettings(CLI_SETTINGS, e);
}
}
/**
* Whether to enable CodeLens for the 'Quick Evaluation' command.
*/
const QUICK_EVAL_CODELENS_SETTING = new Setting('quickEvalCodelens', RUNNING_QUERIES_SETTING);
export function isQuickEvalCodelensEnabled() {
return QUICK_EVAL_CODELENS_SETTING.getValue<boolean>();
}
// Enable experimental features
/**
* Any settings below are deliberately not in package.json so that
* they do not appear in the settings ui in vscode itself. If users
* want to enable experimental features, they can add them directly in
* their vscode settings json file.
*/
/**
* Enables canary features of this extension. Recommended for all internal users.
*/
export const CANARY_FEATURES = new Setting('canary', ROOT_SETTING);
export function isCanary() {
return !!CANARY_FEATURES.getValue<boolean>();
}
/**
* Avoids caching in the AST viewer if the user is also a canary user.
*/
export const NO_CACHE_AST_VIEWER = new Setting('disableCache', AST_VIEWER_SETTING);
// Settings for variant analysis
const REMOTE_QUERIES_SETTING = new Setting('variantAnalysis', ROOT_SETTING);
/**
* Lists of GitHub repositories that you want to query remotely via the "Run Variant Analysis" command.
* Note: This command is only available for internal users.
*
* This setting should be a JSON object where each key is a user-specified name (string),
* and the value is an array of GitHub repositories (of the form `<owner>/<repo>`).
*/
const REMOTE_REPO_LISTS = new Setting('repositoryLists', REMOTE_QUERIES_SETTING);
export function getRemoteRepositoryLists(): Record<string, string[]> | undefined {
return REMOTE_REPO_LISTS.getValue<Record<string, string[]>>() || undefined;
}
export async function setRemoteRepositoryLists(lists: Record<string, string[]> | undefined) {
await REMOTE_REPO_LISTS.updateValue(lists, ConfigurationTarget.Global);
}
/**
* The name of the "controller" repository that you want to use with the "Run Variant Analysis" command.
* Note: This command is only available for internal users.
*
* This setting should be a GitHub repository of the form `<owner>/<repo>`.
*/
const REMOTE_CONTROLLER_REPO = new Setting('controllerRepo', REMOTE_QUERIES_SETTING);
export function getRemoteControllerRepo(): string | undefined {
return REMOTE_CONTROLLER_REPO.getValue<string>() || undefined;
}
export async function setRemoteControllerRepo(repo: string | undefined) {
await REMOTE_CONTROLLER_REPO.updateValue(repo, ConfigurationTarget.Global);
}
/**
* The branch of "github/codeql-variant-analysis-action" to use with the "Run Variant Analysis" command.
* Default value is "main".
* Note: This command is only available for internal users.
*/
const ACTION_BRANCH = new Setting('actionBranch', REMOTE_QUERIES_SETTING);
export function getActionBranch(): string {
return ACTION_BRANCH.getValue<string>() || 'main';
}
export function isIntegrationTestMode() {
return process.env.INTEGRATION_TEST_MODE === 'true';
}

View File

@@ -0,0 +1,148 @@
import { QueryWithResults } from '../run-queries';
import { CodeQLCliServer } from '../cli';
import { DecodedBqrsChunk, BqrsId, EntityValue } from '../pure/bqrs-cli-types';
import { DatabaseItem } from '../databases';
import { ChildAstItem, AstItem } from '../astViewer';
import fileRangeFromURI from './fileRangeFromURI';
import { Uri } from 'vscode';
/**
* A class that wraps a tree of QL results from a query that
* has an @kind of graph
*/
export default class AstBuilder {
private roots: AstItem[] | undefined;
private bqrsPath: string;
constructor(
queryResults: QueryWithResults,
private cli: CodeQLCliServer,
public db: DatabaseItem,
public fileName: Uri
) {
this.bqrsPath = queryResults.query.resultsPaths.resultsPath;
}
async getRoots(): Promise<AstItem[]> {
if (!this.roots) {
this.roots = await this.parseRoots();
}
return this.roots;
}
private async parseRoots(): Promise<AstItem[]> {
const options = { entities: ['id', 'url', 'string'] };
const [nodeTuples, edgeTuples, graphProperties] = await Promise.all([
await this.cli.bqrsDecode(this.bqrsPath, 'nodes', options),
await this.cli.bqrsDecode(this.bqrsPath, 'edges', options),
await this.cli.bqrsDecode(this.bqrsPath, 'graphProperties', options),
]);
if (!this.isValidGraph(graphProperties)) {
throw new Error('AST is invalid');
}
const idToItem = new Map<BqrsId, AstItem>();
const parentToChildren = new Map<BqrsId, BqrsId[]>();
const childToParent = new Map<BqrsId, BqrsId>();
const astOrder = new Map<BqrsId, number>();
const edgeLabels = new Map<BqrsId, string>();
const roots = [];
// Build up the parent-child relationships
edgeTuples.tuples.forEach(tuple => {
const [source, target, tupleType, value] = tuple as [EntityValue, EntityValue, string, string];
const sourceId = source.id!;
const targetId = target.id!;
switch (tupleType) {
case 'semmle.order':
astOrder.set(targetId, Number(value));
break;
case 'semmle.label': {
childToParent.set(targetId, sourceId);
let children = parentToChildren.get(sourceId);
if (!children) {
parentToChildren.set(sourceId, children = []);
}
children.push(targetId);
// ignore values that indicate a numeric order.
if (!Number.isFinite(Number(value))) {
edgeLabels.set(targetId, value);
}
break;
}
default:
// ignore other tupleTypes since they are not needed by the ast viewer
}
});
// populate parents and children
nodeTuples.tuples.forEach(tuple => {
const [entity, tupleType, value] = tuple as [EntityValue, string, string];
const id = entity.id!;
switch (tupleType) {
case 'semmle.order':
astOrder.set(id, Number(value));
break;
case 'semmle.label': {
// If an edge label exists, include it and separate from the node label using ':'
const nodeLabel = value ?? entity.label;
const edgeLabel = edgeLabels.get(id);
const label = [edgeLabel, nodeLabel].filter(e => e).join(': ');
const item = {
id,
label,
location: entity.url,
fileLocation: fileRangeFromURI(entity.url, this.db),
children: [] as ChildAstItem[],
order: Number.MAX_SAFE_INTEGER
};
idToItem.set(id, item);
const parent = idToItem.get(childToParent.has(id) ? childToParent.get(id)! : -1);
if (parent) {
const astItem = item as ChildAstItem;
astItem.parent = parent;
parent.children.push(astItem);
}
const children = parentToChildren.has(id) ? parentToChildren.get(id)! : [];
children.forEach(childId => {
const child = idToItem.get(childId) as ChildAstItem | undefined;
if (child) {
child.parent = item;
item.children.push(child);
}
});
break;
}
default:
// ignore other tupleTypes since they are not needed by the ast viewer
}
});
// find the roots and add the order
for (const [, item] of idToItem) {
item.order = astOrder.has(item.id)
? astOrder.get(item.id)!
: Number.MAX_SAFE_INTEGER;
if (!('parent' in item)) {
roots.push(item);
}
}
return roots;
}
private isValidGraph(graphProperties: DecodedBqrsChunk) {
const tuple = graphProperties?.tuples?.find(t => t[0] === 'semmle.graphKind');
return tuple?.[1] === 'tree';
}
}

View File

@@ -0,0 +1,31 @@
import * as vscode from 'vscode';
import { UrlValue, LineColumnLocation } from '../pure/bqrs-cli-types';
import { isEmptyPath } from '../pure/bqrs-utils';
import { DatabaseItem } from '../databases';
export default function fileRangeFromURI(uri: UrlValue | undefined, db: DatabaseItem): vscode.Location | undefined {
if (!uri || typeof uri === 'string') {
return undefined;
} else if ('startOffset' in uri) {
return undefined;
} else {
const loc = uri as LineColumnLocation;
if (isEmptyPath(loc.uri)) {
return undefined;
}
const range = new vscode.Range(Math.max(0, (loc.startLine || 0) - 1),
Math.max(0, (loc.startColumn || 0) - 1),
Math.max(0, (loc.endLine || 0) - 1),
Math.max(0, (loc.endColumn || 0)));
try {
if (uri.uri.startsWith('file:')) {
return new vscode.Location(db.resolveSourceFile(uri.uri), range);
}
return undefined;
} catch (e) {
return undefined;
}
}
}

View File

@@ -0,0 +1,43 @@
export enum KeyType {
DefinitionQuery = 'DefinitionQuery',
ReferenceQuery = 'ReferenceQuery',
PrintAstQuery = 'PrintAstQuery',
PrintCfgQuery = 'PrintCfgQuery',
}
export function tagOfKeyType(keyType: KeyType): string {
switch (keyType) {
case KeyType.DefinitionQuery:
return 'ide-contextual-queries/local-definitions';
case KeyType.ReferenceQuery:
return 'ide-contextual-queries/local-references';
case KeyType.PrintAstQuery:
return 'ide-contextual-queries/print-ast';
case KeyType.PrintCfgQuery:
return 'ide-contextual-queries/print-cfg';
}
}
export function nameOfKeyType(keyType: KeyType): string {
switch (keyType) {
case KeyType.DefinitionQuery:
return 'definitions';
case KeyType.ReferenceQuery:
return 'references';
case KeyType.PrintAstQuery:
return 'print AST';
case KeyType.PrintCfgQuery:
return 'print CFG';
}
}
export function kindOfKeyType(keyType: KeyType): string {
switch (keyType) {
case KeyType.DefinitionQuery:
case KeyType.ReferenceQuery:
return 'definitions';
case KeyType.PrintAstQuery:
case KeyType.PrintCfgQuery:
return 'graph';
}
}

View File

@@ -0,0 +1,134 @@
import { decodeSourceArchiveUri, encodeArchiveBasePath } from '../archive-filesystem-provider';
import { ColumnKindCode, EntityValue, getResultSetSchema, ResultSetSchema } from '../pure/bqrs-cli-types';
import { CodeQLCliServer } from '../cli';
import { DatabaseManager, DatabaseItem } from '../databases';
import fileRangeFromURI from './fileRangeFromURI';
import * as messages from '../pure/messages';
import { QueryServerClient } from '../queryserver-client';
import { QueryWithResults, compileAndRunQueryAgainstDatabase, createInitialQueryInfo } from '../run-queries';
import { ProgressCallback } from '../commandRunner';
import { KeyType } from './keyType';
import { qlpackOfDatabase, resolveQueries } from './queryResolver';
import { CancellationToken, LocationLink, Uri } from 'vscode';
export const SELECT_QUERY_NAME = '#select';
export const TEMPLATE_NAME = 'selectedSourceFile';
export interface FullLocationLink extends LocationLink {
originUri: Uri;
}
/**
* This function executes a contextual query inside a given database, filters, and converts
* the results into source locations. This function is the workhorse for all search-based
* contextual queries like find references and find definitions.
*
* @param cli The cli server
* @param qs The query server client
* @param dbm The database manager
* @param uriString The selected source file and location
* @param keyType The contextual query type to run
* @param queryStorageDir The directory to store the query results
* @param progress A progress callback
* @param token A CancellationToken
* @param filter A function that will filter extraneous results
*/
export async function getLocationsForUriString(
cli: CodeQLCliServer,
qs: QueryServerClient,
dbm: DatabaseManager,
uriString: string,
keyType: KeyType,
queryStorageDir: string,
progress: ProgressCallback,
token: CancellationToken,
filter: (src: string, dest: string) => boolean
): Promise<FullLocationLink[]> {
const uri = decodeSourceArchiveUri(Uri.parse(uriString, true));
const sourceArchiveUri = encodeArchiveBasePath(uri.sourceArchiveZipPath);
const db = dbm.findDatabaseItemBySourceArchive(sourceArchiveUri);
if (!db) {
return [];
}
const qlpack = await qlpackOfDatabase(cli, db);
const templates = createTemplates(uri.pathWithinSourceArchive);
const links: FullLocationLink[] = [];
for (const query of await resolveQueries(cli, qlpack, keyType)) {
const initialInfo = await createInitialQueryInfo(
Uri.file(query),
{
name: db.name,
databaseUri: db.databaseUri.toString(),
},
false
);
const results = await compileAndRunQueryAgainstDatabase(
cli,
qs,
db,
initialInfo,
queryStorageDir,
progress,
token,
templates
);
if (results.result.resultType == messages.QueryResultType.SUCCESS) {
links.push(...await getLinksFromResults(results, cli, db, filter));
}
}
return links;
}
async function getLinksFromResults(
results: QueryWithResults,
cli: CodeQLCliServer,
db: DatabaseItem,
filter: (srcFile: string, destFile: string) => boolean
): Promise<FullLocationLink[]> {
const localLinks: FullLocationLink[] = [];
const bqrsPath = results.query.resultsPaths.resultsPath;
const info = await cli.bqrsInfo(bqrsPath);
const selectInfo = getResultSetSchema(SELECT_QUERY_NAME, info);
if (isValidSelect(selectInfo)) {
// TODO: Page this
const allTuples = await cli.bqrsDecode(bqrsPath, SELECT_QUERY_NAME);
for (const tuple of allTuples.tuples) {
const [src, dest] = tuple as [EntityValue, EntityValue];
const srcFile = src.url && fileRangeFromURI(src.url, db);
const destFile = dest.url && fileRangeFromURI(dest.url, db);
if (srcFile && destFile && filter(srcFile.uri.toString(), destFile.uri.toString())) {
localLinks.push({
targetRange: destFile.range,
targetUri: destFile.uri,
originSelectionRange: srcFile.range,
originUri: srcFile.uri
});
}
}
}
return localLinks;
}
function createTemplates(path: string): messages.TemplateDefinitions {
return {
[TEMPLATE_NAME]: {
values: {
tuples: [[{
stringValue: path
}]]
}
}
};
}
function isValidSelect(selectInfo: ResultSetSchema | undefined) {
return selectInfo && selectInfo.columns.length == 3
&& selectInfo.columns[0].kind == ColumnKindCode.ENTITY
&& selectInfo.columns[1].kind == ColumnKindCode.ENTITY
&& selectInfo.columns[2].kind == ColumnKindCode.STRING;
}

View File

@@ -0,0 +1,106 @@
import * as fs from 'fs-extra';
import * as yaml from 'js-yaml';
import * as tmp from 'tmp-promise';
import * as helpers from '../helpers';
import {
KeyType,
kindOfKeyType,
nameOfKeyType,
tagOfKeyType
} from './keyType';
import { CodeQLCliServer } from '../cli';
import { DatabaseItem } from '../databases';
import { QlPacksForLanguage } from '../helpers';
export async function qlpackOfDatabase(cli: CodeQLCliServer, db: DatabaseItem): Promise<QlPacksForLanguage> {
if (db.contents === undefined) {
throw new Error('Database is invalid and cannot infer QLPack.');
}
const datasetPath = db.contents.datasetUri.fsPath;
const dbscheme = await helpers.getPrimaryDbscheme(datasetPath);
return await helpers.getQlPackForDbscheme(cli, dbscheme);
}
/**
* Finds the contextual queries with the specified key in a list of CodeQL packs.
*
* @param cli The CLI instance to use.
* @param qlpacks The list of packs to search.
* @param keyType The contextual query key of the query to search for.
* @returns The found queries from the first pack in which any matching queries were found.
*/
async function resolveQueriesFromPacks(cli: CodeQLCliServer, qlpacks: string[], keyType: KeyType): Promise<string[]> {
const suiteFile = (await tmp.file({
postfix: '.qls'
})).path;
const suiteYaml = [];
for (const qlpack of qlpacks) {
suiteYaml.push({
from: qlpack,
queries: '.',
include: {
kind: kindOfKeyType(keyType),
'tags contain': tagOfKeyType(keyType)
}
});
}
await fs.writeFile(suiteFile, yaml.safeDump(suiteYaml), 'utf8');
const queries = await cli.resolveQueriesInSuite(suiteFile, helpers.getOnDiskWorkspaceFolders());
return queries;
}
export async function resolveQueries(cli: CodeQLCliServer, qlpacks: QlPacksForLanguage, keyType: KeyType): Promise<string[]> {
const cliCanHandleLibraryPack = await cli.cliConstraints.supportsAllowLibraryPacksInResolveQueries();
const packsToSearch: string[] = [];
let blameCli: boolean;
if (cliCanHandleLibraryPack) {
// The CLI can handle both library packs and query packs, so search both packs in order.
packsToSearch.push(qlpacks.dbschemePack);
if (qlpacks.queryPack !== undefined) {
packsToSearch.push(qlpacks.queryPack);
}
// If we don't find the query, it's because it's not there, not because the CLI was unable to
// search the pack.
blameCli = false;
} else {
// Older CLIs can't handle `codeql resolve queries` with a suite that references a library pack.
if (qlpacks.dbschemePackIsLibraryPack) {
if (qlpacks.queryPack !== undefined) {
// Just search the query pack, because some older library/query releases still had the
// contextual queries in the query pack.
packsToSearch.push(qlpacks.queryPack);
}
// If we don't find it, it's because the CLI was unable to search the library pack that
// actually contains the query. Blame any failure on the CLI, not the packs.
blameCli = true;
} else {
// We have an old CLI, but the dbscheme pack is old enough that it's still a unified pack with
// both libraries and queries. Just search that pack.
packsToSearch.push(qlpacks.dbschemePack);
// Any CLI should be able to search the single query pack, so if we don't find it, it's
// because the language doesn't support it.
blameCli = false;
}
}
const queries = await resolveQueriesFromPacks(cli, packsToSearch, keyType);
if (queries.length > 0) {
return queries;
}
// No queries found. Determine the correct error message for the various scenarios.
const errorMessage = blameCli ?
`Your current version of the CodeQL CLI, '${(await cli.getVersion()).version}', \
is unable to use contextual queries from recent versions of the standard CodeQL libraries. \
Please upgrade to the latest version of the CodeQL CLI.`
:
`No ${nameOfKeyType(keyType)} queries (tagged "${tagOfKeyType(keyType)}") could be found in the current library path. \
Try upgrading the CodeQL libraries. If that doesn't work, then ${nameOfKeyType(keyType)} queries are not yet available \
for this language.`;
void helpers.showAndLogErrorMessage(errorMessage);
throw new Error(`Couldn't find any queries tagged ${tagOfKeyType(keyType)} in any of the following packs: ${packsToSearch.join(', ')}.`);
}

View File

@@ -0,0 +1,290 @@
import {
CancellationToken,
DefinitionProvider,
Location,
LocationLink,
Position,
ProgressLocation,
ReferenceContext,
ReferenceProvider,
TextDocument,
Uri
} from 'vscode';
import { decodeSourceArchiveUri, encodeArchiveBasePath, zipArchiveScheme } from '../archive-filesystem-provider';
import { CodeQLCliServer } from '../cli';
import { DatabaseManager } from '../databases';
import { CachedOperation } from '../helpers';
import { ProgressCallback, withProgress } from '../commandRunner';
import * as messages from '../pure/messages';
import { QueryServerClient } from '../queryserver-client';
import { compileAndRunQueryAgainstDatabase, createInitialQueryInfo, QueryWithResults } from '../run-queries';
import AstBuilder from './astBuilder';
import {
KeyType,
} from './keyType';
import { FullLocationLink, getLocationsForUriString, TEMPLATE_NAME } from './locationFinder';
import { qlpackOfDatabase, resolveQueries } from './queryResolver';
import { isCanary, NO_CACHE_AST_VIEWER } from '../config';
/**
* Run templated CodeQL queries to find definitions and references in
* source-language files. We may eventually want to find a way to
* generalize this to other custom queries, e.g. showing dataflow to
* or from a selected identifier.
*/
export class TemplateQueryDefinitionProvider implements DefinitionProvider {
private cache: CachedOperation<LocationLink[]>;
constructor(
private cli: CodeQLCliServer,
private qs: QueryServerClient,
private dbm: DatabaseManager,
private queryStorageDir: string,
) {
this.cache = new CachedOperation<LocationLink[]>(this.getDefinitions.bind(this));
}
async provideDefinition(document: TextDocument, position: Position, _token: CancellationToken): Promise<LocationLink[]> {
const fileLinks = await this.cache.get(document.uri.toString());
const locLinks: LocationLink[] = [];
for (const link of fileLinks) {
if (link.originSelectionRange!.contains(position)) {
locLinks.push(link);
}
}
return locLinks;
}
private async getDefinitions(uriString: string): Promise<LocationLink[]> {
return withProgress({
location: ProgressLocation.Notification,
cancellable: true,
title: 'Finding definitions'
}, async (progress, token) => {
return getLocationsForUriString(
this.cli,
this.qs,
this.dbm,
uriString,
KeyType.DefinitionQuery,
this.queryStorageDir,
progress,
token,
(src, _dest) => src === uriString
);
});
}
}
export class TemplateQueryReferenceProvider implements ReferenceProvider {
private cache: CachedOperation<FullLocationLink[]>;
constructor(
private cli: CodeQLCliServer,
private qs: QueryServerClient,
private dbm: DatabaseManager,
private queryStorageDir: string,
) {
this.cache = new CachedOperation<FullLocationLink[]>(this.getReferences.bind(this));
}
async provideReferences(
document: TextDocument,
position: Position,
_context: ReferenceContext,
_token: CancellationToken
): Promise<Location[]> {
const fileLinks = await this.cache.get(document.uri.toString());
const locLinks: Location[] = [];
for (const link of fileLinks) {
if (link.targetRange!.contains(position)) {
locLinks.push({ range: link.originSelectionRange!, uri: link.originUri });
}
}
return locLinks;
}
private async getReferences(uriString: string): Promise<FullLocationLink[]> {
return withProgress({
location: ProgressLocation.Notification,
cancellable: true,
title: 'Finding references'
}, async (progress, token) => {
return getLocationsForUriString(
this.cli,
this.qs,
this.dbm,
uriString,
KeyType.DefinitionQuery,
this.queryStorageDir,
progress,
token,
(src, _dest) => src === uriString
);
});
}
}
type QueryWithDb = {
query: QueryWithResults,
dbUri: Uri
};
export class TemplatePrintAstProvider {
private cache: CachedOperation<QueryWithDb>;
constructor(
private cli: CodeQLCliServer,
private qs: QueryServerClient,
private dbm: DatabaseManager,
private queryStorageDir: string,
) {
this.cache = new CachedOperation<QueryWithDb>(this.getAst.bind(this));
}
async provideAst(
progress: ProgressCallback,
token: CancellationToken,
fileUri?: Uri
): Promise<AstBuilder | undefined> {
if (!fileUri) {
throw new Error('Cannot view the AST. Please select a valid source file inside a CodeQL database.');
}
const { query, dbUri } = this.shouldCache()
? await this.cache.get(fileUri.toString(), progress, token)
: await this.getAst(fileUri.toString(), progress, token);
return new AstBuilder(
query, this.cli,
this.dbm.findDatabaseItem(dbUri)!,
fileUri,
);
}
private shouldCache() {
return !(isCanary() && NO_CACHE_AST_VIEWER.getValue<boolean>());
}
private async getAst(
uriString: string,
progress: ProgressCallback,
token: CancellationToken
): Promise<QueryWithDb> {
const uri = Uri.parse(uriString, true);
if (uri.scheme !== zipArchiveScheme) {
throw new Error('Cannot view the AST. Please select a valid source file inside a CodeQL database.');
}
const zippedArchive = decodeSourceArchiveUri(uri);
const sourceArchiveUri = encodeArchiveBasePath(zippedArchive.sourceArchiveZipPath);
const db = this.dbm.findDatabaseItemBySourceArchive(sourceArchiveUri);
if (!db) {
throw new Error('Can\'t infer database from the provided source.');
}
const qlpacks = await qlpackOfDatabase(this.cli, db);
const queries = await resolveQueries(this.cli, qlpacks, KeyType.PrintAstQuery);
if (queries.length > 1) {
throw new Error('Found multiple Print AST queries. Can\'t continue');
}
if (queries.length === 0) {
throw new Error('Did not find any Print AST queries. Can\'t continue');
}
const query = queries[0];
const templates: messages.TemplateDefinitions = {
[TEMPLATE_NAME]: {
values: {
tuples: [[{
stringValue: zippedArchive.pathWithinSourceArchive
}]]
}
}
};
const initialInfo = await createInitialQueryInfo(
Uri.file(query),
{
name: db.name,
databaseUri: db.databaseUri.toString(),
},
false
);
return {
query: await compileAndRunQueryAgainstDatabase(
this.cli,
this.qs,
db,
initialInfo,
this.queryStorageDir,
progress,
token,
templates
),
dbUri: db.databaseUri
};
}
}
export class TemplatePrintCfgProvider {
private cache: CachedOperation<[Uri, messages.TemplateDefinitions] | undefined>;
constructor(
private cli: CodeQLCliServer,
private dbm: DatabaseManager,
) {
this.cache = new CachedOperation<[Uri, messages.TemplateDefinitions] | undefined>(this.getCfgUri.bind(this));
}
async provideCfgUri(document?: TextDocument): Promise<[Uri, messages.TemplateDefinitions] | undefined> {
if (!document) {
return;
}
return await this.cache.get(document.uri.toString());
}
private async getCfgUri(uriString: string): Promise<[Uri, messages.TemplateDefinitions]> {
const uri = Uri.parse(uriString, true);
if (uri.scheme !== zipArchiveScheme) {
throw new Error('CFG Viewing is only available for databases with zipped source archives.');
}
const zippedArchive = decodeSourceArchiveUri(uri);
const sourceArchiveUri = encodeArchiveBasePath(zippedArchive.sourceArchiveZipPath);
const db = this.dbm.findDatabaseItemBySourceArchive(sourceArchiveUri);
if (!db) {
throw new Error('Can\'t infer database from the provided source.');
}
const qlpack = await qlpackOfDatabase(this.cli, db);
if (!qlpack) {
throw new Error('Can\'t infer qlpack from database source archive.');
}
const queries = await resolveQueries(this.cli, qlpack, KeyType.PrintCfgQuery);
if (queries.length > 1) {
throw new Error(`Found multiple Print CFG queries. Can't continue. Make sure there is exacly one query with the tag ${KeyType.PrintCfgQuery}`);
}
if (queries.length === 0) {
throw new Error(`Did not find any Print CFG queries. Can't continue. Make sure there is exacly one query with the tag ${KeyType.PrintCfgQuery}`);
}
const queryUri = Uri.file(queries[0]);
const templates: messages.TemplateDefinitions = {
[TEMPLATE_NAME]: {
values: {
tuples: [[{
stringValue: zippedArchive.pathWithinSourceArchive
}]]
}
}
};
return [queryUri, templates];
}
}

View File

@@ -1,69 +1,144 @@
import fetch, { Response } from 'node-fetch';
import * as unzipper from 'unzipper';
import { zip } from 'zip-a-folder';
import * as unzipper from 'unzipper';
import {
Uri,
ProgressOptions,
ProgressLocation,
CancellationToken,
commands,
window,
} from 'vscode';
import { CodeQLCliServer } from './cli';
import * as fs from 'fs-extra';
import * as path from 'path';
import { DatabaseManager, DatabaseItem } from './databases';
import {
ProgressCallback,
showAndLogErrorMessage,
withProgress,
showAndLogInformationMessage,
} from './helpers';
import {
reportStreamProgress,
ProgressCallback,
} from './commandRunner';
import { logger } from './logging';
import { tmpDir } from './helpers';
import { Credentials } from './authentication';
import { REPO_REGEX, getErrorMessage } from './pure/helpers-pure';
/**
* Prompts a user to fetch a database from a remote location. Database is assumed to be an archive file.
*
* @param databasesManager the DatabaseManager
* @param databaseManager the DatabaseManager
* @param storagePath where to store the unzipped database.
*/
export async function promptImportInternetDatabase(
databasesManager: DatabaseManager,
storagePath: string
databaseManager: DatabaseManager,
storagePath: string,
progress: ProgressCallback,
token: CancellationToken,
cli?: CodeQLCliServer
): Promise<DatabaseItem | undefined> {
let item: DatabaseItem | undefined = undefined;
try {
const databaseUrl = await window.showInputBox({
prompt: 'Enter URL of zipfile of database to download',
});
if (databaseUrl) {
validateHttpsUrl(databaseUrl);
const progressOptions: ProgressOptions = {
location: ProgressLocation.Notification,
title: 'Adding database from URL',
cancellable: false,
};
await withProgress(
progressOptions,
async (progress) =>
(item = await databaseArchiveFetcher(
databaseUrl,
databasesManager,
storagePath,
progress
))
);
commands.executeCommand('codeQLDatabases.focus');
}
showAndLogInformationMessage(
'Database downloaded and imported successfully.'
);
} catch (e) {
showAndLogErrorMessage(e.message);
const databaseUrl = await window.showInputBox({
prompt: 'Enter URL of zipfile of database to download',
});
if (!databaseUrl) {
return;
}
validateHttpsUrl(databaseUrl);
const item = await databaseArchiveFetcher(
databaseUrl,
{},
databaseManager,
storagePath,
undefined,
progress,
token,
cli
);
if (item) {
await commands.executeCommand('codeQLDatabases.focus');
void showAndLogInformationMessage('Database downloaded and imported successfully.');
}
return item;
}
/**
* Prompts a user to fetch a database from GitHub.
* User enters a GitHub repository and then the user is asked which language
* to download (if there is more than one)
*
* @param databaseManager the DatabaseManager
* @param storagePath where to store the unzipped database.
*/
export async function promptImportGithubDatabase(
databaseManager: DatabaseManager,
storagePath: string,
credentials: Credentials,
progress: ProgressCallback,
token: CancellationToken,
cli?: CodeQLCliServer
): Promise<DatabaseItem | undefined> {
progress({
message: 'Choose repository',
step: 1,
maxStep: 2
});
const githubRepo = await window.showInputBox({
title: 'Enter a GitHub repository URL or "name with owner" (e.g. https://github.com/github/codeql or github/codeql)',
placeHolder: 'https://github.com/<owner>/<repo> or <owner>/<repo>',
ignoreFocusOut: true,
});
if (!githubRepo) {
return;
}
if (!looksLikeGithubRepo(githubRepo)) {
throw new Error(`Invalid GitHub repository: ${githubRepo}`);
}
const result = await convertGithubNwoToDatabaseUrl(githubRepo, credentials, progress);
if (!result) {
return;
}
const { databaseUrl, name, owner } = result;
const octokit = await credentials.getOctokit();
/**
* The 'token' property of the token object returned by `octokit.auth()`.
* The object is undocumented, but looks something like this:
* {
* token: 'xxxx',
* tokenType: 'oauth',
* type: 'token',
* }
* We only need the actual token string.
*/
const octokitToken = (await octokit.auth() as { token: string })?.token;
if (!octokitToken) {
// Just print a generic error message for now. Ideally we could show more debugging info, like the
// octokit object, but that would expose a user token.
throw new Error('Unable to get GitHub token.');
}
const item = await databaseArchiveFetcher(
databaseUrl,
{ 'Accept': 'application/zip', 'Authorization': `Bearer ${octokitToken}` },
databaseManager,
storagePath,
`${owner}/${name}`,
progress,
token,
cli
);
if (item) {
await commands.executeCommand('codeQLDatabases.focus');
void showAndLogInformationMessage('Database downloaded and imported successfully.');
return item;
}
return;
}
/**
@@ -71,102 +146,103 @@ export async function promptImportInternetDatabase(
* User enters a project url and then the user is asked which language
* to download (if there is more than one)
*
* @param databasesManager the DatabaseManager
* @param databaseManager the DatabaseManager
* @param storagePath where to store the unzipped database.
*/
export async function promptImportLgtmDatabase(
databasesManager: DatabaseManager,
storagePath: string
databaseManager: DatabaseManager,
storagePath: string,
progress: ProgressCallback,
token: CancellationToken,
cli?: CodeQLCliServer
): Promise<DatabaseItem | undefined> {
let item: DatabaseItem | undefined = undefined;
try {
const lgtmUrl = await window.showInputBox({
prompt:
'Enter the project URL on LGTM (e.g., https://lgtm.com/projects/g/github/codeql)',
});
if (!lgtmUrl) {
return;
}
if (looksLikeLgtmUrl(lgtmUrl)) {
const databaseUrl = await convertToDatabaseUrl(lgtmUrl);
if (databaseUrl) {
const progressOptions: ProgressOptions = {
location: ProgressLocation.Notification,
title: 'Adding database from LGTM',
cancellable: false,
};
await withProgress(
progressOptions,
async (progress) =>
(item = await databaseArchiveFetcher(
databaseUrl,
databasesManager,
storagePath,
progress
))
);
commands.executeCommand('codeQLDatabases.focus');
}
} else {
throw new Error(`Invalid LGTM URL: ${lgtmUrl}`);
}
if (item) {
showAndLogInformationMessage(
'Database downloaded and imported successfully.'
);
}
} catch (e) {
showAndLogErrorMessage(e.message);
progress({
message: 'Choose project',
step: 1,
maxStep: 2
});
const lgtmUrl = await window.showInputBox({
prompt:
'Enter the project slug or URL on LGTM (e.g., g/github/codeql or https://lgtm.com/projects/g/github/codeql)',
});
if (!lgtmUrl) {
return;
}
return item;
if (looksLikeLgtmUrl(lgtmUrl)) {
const databaseUrl = await convertLgtmUrlToDatabaseUrl(lgtmUrl, progress);
if (databaseUrl) {
const item = await databaseArchiveFetcher(
databaseUrl,
{},
databaseManager,
storagePath,
undefined,
progress,
token,
cli
);
if (item) {
await commands.executeCommand('codeQLDatabases.focus');
void showAndLogInformationMessage('Database downloaded and imported successfully.');
}
return item;
}
} else {
throw new Error(`Invalid LGTM URL: ${lgtmUrl}`);
}
return;
}
export async function retrieveCanonicalRepoName(lgtmUrl: string) {
const givenRepoName = extractProjectSlug(lgtmUrl);
const response = await checkForFailingResponse(await fetch(`https://api.github.com/repos/${givenRepoName}`), 'Failed to locate the repository on github');
const repo = await response.json();
if (!repo || !repo.full_name) {
return;
}
return repo.full_name;
}
/**
* Imports a database from a local archive.
*
* @param databaseUrl the file url of the archive to import
* @param databasesManager the DatabaseManager
* @param databaseManager the DatabaseManager
* @param storagePath where to store the unzipped database.
*/
export async function importArchiveDatabase(
databaseUrl: string,
databasesManager: DatabaseManager,
storagePath: string
databaseManager: DatabaseManager,
storagePath: string,
progress: ProgressCallback,
token: CancellationToken,
cli?: CodeQLCliServer,
): Promise<DatabaseItem | undefined> {
let item: DatabaseItem | undefined = undefined;
try {
const progressOptions: ProgressOptions = {
location: ProgressLocation.Notification,
title: 'Importing database from archive',
cancellable: false,
};
await withProgress(
progressOptions,
async (progress) =>
(item = await databaseArchiveFetcher(
databaseUrl,
databasesManager,
storagePath,
progress
))
const item = await databaseArchiveFetcher(
databaseUrl,
{},
databaseManager,
storagePath,
undefined,
progress,
token,
cli
);
commands.executeCommand('codeQLDatabases.focus');
if (item) {
showAndLogInformationMessage(
'Database unzipped and imported successfully.'
);
await commands.executeCommand('codeQLDatabases.focus');
void showAndLogInformationMessage('Database unzipped and imported successfully.');
}
return item;
} catch (e) {
if (e.message.includes('unexpected end of file')) {
showAndLogErrorMessage('Database is corrupt or too large. Try unzipping outside of VS Code and importing the unzipped folder instead.');
if (getErrorMessage(e).includes('unexpected end of file')) {
throw new Error('Database is corrupt or too large. Try unzipping outside of VS Code and importing the unzipped folder instead.');
} else {
showAndLogErrorMessage(e.message);
// delegate
throw e;
}
}
return item;
}
/**
@@ -174,17 +250,24 @@ export async function importArchiveDatabase(
* or in the local filesystem.
*
* @param databaseUrl URL from which to grab the database
* @param databasesManager the DatabaseManager
* @param requestHeaders Headers to send with the request
* @param databaseManager the DatabaseManager
* @param storagePath where to store the unzipped database.
* @param progressCallback optional callback to send progress messages to
* @param nameOverride a name for the database that overrides the default
* @param progress callback to send progress messages to
* @param token cancellation token
*/
async function databaseArchiveFetcher(
databaseUrl: string,
databasesManager: DatabaseManager,
requestHeaders: { [key: string]: string },
databaseManager: DatabaseManager,
storagePath: string,
progressCallback?: ProgressCallback
nameOverride: string | undefined,
progress: ProgressCallback,
token: CancellationToken,
cli?: CodeQLCliServer,
): Promise<DatabaseItem> {
progressCallback?.({
progress({
message: 'Getting database',
step: 1,
maxStep: 4,
@@ -196,12 +279,12 @@ async function databaseArchiveFetcher(
const unzipPath = await getStorageFolder(storagePath, databaseUrl);
if (isFile(databaseUrl)) {
await readAndUnzip(databaseUrl, unzipPath);
await readAndUnzip(databaseUrl, unzipPath, cli, progress);
} else {
await fetchAndUnzip(databaseUrl, unzipPath, progressCallback);
await fetchAndUnzip(databaseUrl, requestHeaders, unzipPath, cli, progress);
}
progressCallback?.({
progress({
message: 'Opening database',
step: 3,
maxStep: 4,
@@ -214,15 +297,15 @@ async function databaseArchiveFetcher(
'codeql-database.yml'
);
if (dbPath) {
progressCallback?.({
progress({
message: 'Validating and fixing source location',
step: 4,
maxStep: 4,
});
await ensureZippedSourceLocation(dbPath);
const item = await databasesManager.openDatabase(Uri.file(dbPath));
databasesManager.setCurrentDatabaseItem(item);
const item = await databaseManager.openDatabase(progress, token, Uri.file(dbPath), nameOverride);
await databaseManager.setCurrentDatabaseItem(item);
return item;
} else {
throw new Error('Database not found in archive.');
@@ -269,48 +352,78 @@ function validateHttpsUrl(databaseUrl: string) {
}
}
async function readAndUnzip(databaseUrl: string, unzipPath: string) {
const databaseFile = Uri.parse(databaseUrl).fsPath;
const directory = await unzipper.Open.file(databaseFile);
await directory.extract({ path: unzipPath });
async function readAndUnzip(
zipUrl: string,
unzipPath: string,
cli?: CodeQLCliServer,
progress?: ProgressCallback
) {
// TODO: Providing progress as the file is unzipped is currently blocked
// on https://github.com/ZJONSSON/node-unzipper/issues/222
const zipFile = Uri.parse(zipUrl).fsPath;
progress?.({
maxStep: 10,
step: 9,
message: `Unzipping into ${path.basename(unzipPath)}`
});
if (cli && await cli.cliConstraints.supportsDatabaseUnbundle()) {
// Use the `database unbundle` command if the installed cli version supports it
await cli.databaseUnbundle(zipFile, unzipPath);
} else {
// Must get the zip central directory since streaming the
// zip contents may not have correct local file headers.
// Instead, we can only rely on the central directory.
const directory = await unzipper.Open.file(zipFile);
await directory.extract({ path: unzipPath });
}
}
async function fetchAndUnzip(
databaseUrl: string,
requestHeaders: { [key: string]: string },
unzipPath: string,
progressCallback?: ProgressCallback
cli?: CodeQLCliServer,
progress?: ProgressCallback
) {
const response = await fetch(databaseUrl);
// Although it is possible to download and stream directly to an unzipped directory,
// we need to avoid this for two reasons. The central directory is located at the
// end of the zip file. It is the source of truth of the content locations. Individual
// file headers may be incorrect. Additionally, saving to file first will reduce memory
// pressure compared with unzipping while downloading the archive.
await checkForFailingResponse(response);
const archivePath = path.join(tmpDir.name, `archive-${Date.now()}.zip`);
const unzipStream = unzipper.Extract({
path: unzipPath,
});
progressCallback?.({
progress?.({
maxStep: 3,
message: 'Unzipping database',
step: 2,
});
await new Promise((resolve, reject) => {
const handler = (err: Error) => {
if (err.message.startsWith('invalid signature')) {
reject(new Error('Not a valid archive.'));
} else {
reject(err);
}
};
response.body.on('error', handler);
unzipStream.on('error', handler);
unzipStream.on('close', resolve);
response.body.pipe(unzipStream);
message: 'Downloading database',
step: 1,
});
const response = await checkForFailingResponse(
await fetch(databaseUrl, { headers: requestHeaders }),
'Error downloading database'
);
const archiveFileStream = fs.createWriteStream(archivePath);
const contentLength = response.headers.get('content-length');
const totalNumBytes = contentLength ? parseInt(contentLength, 10) : undefined;
reportStreamProgress(response.body, 'Downloading database', totalNumBytes, progress);
await new Promise((resolve, reject) =>
response.body.pipe(archiveFileStream)
.on('finish', resolve)
.on('error', reject)
);
await readAndUnzip(Uri.file(archivePath).toString(true), unzipPath, cli, progress);
// remove archivePath eagerly since these archives can be large.
await fs.remove(archivePath);
}
async function checkForFailingResponse(response: Response): Promise<void | never> {
async function checkForFailingResponse(response: Response, errorMessage: string): Promise<Response | never> {
if (response.ok) {
return;
return response;
}
// An error downloading the database. Attempt to extract the resaon behind it.
@@ -322,7 +435,7 @@ async function checkForFailingResponse(response: Response): Promise<void | never
} catch (e) {
msg = text;
}
throw new Error(`Error downloading database.\n\nReason: ${msg}`);
throw new Error(`${errorMessage}.\n\nReason: ${msg}`);
}
function isFile(databaseUrl: string) {
@@ -359,15 +472,99 @@ export async function findDirWithFile(
return;
}
/**
* The URL pattern is https://github.com/{owner}/{name}/{subpages}.
*
* This function accepts any URL that matches the pattern above. It also accepts just the
* name with owner (NWO): `<owner>/<repo>`.
*
* @param githubRepo The GitHub repository URL or NWO
*
* @return true if this looks like a valid GitHub repository URL or NWO
*/
export function looksLikeGithubRepo(
githubRepo: string | undefined
): githubRepo is string {
if (!githubRepo) {
return false;
}
if (REPO_REGEX.test(githubRepo) || convertGitHubUrlToNwo(githubRepo)) {
return true;
}
return false;
}
/**
* Converts a GitHub repository URL to the corresponding NWO.
* @param githubUrl The GitHub repository URL
* @return The corresponding NWO, or undefined if the URL is not valid
*/
function convertGitHubUrlToNwo(githubUrl: string): string | undefined {
try {
const uri = Uri.parse(githubUrl, true);
if (uri.scheme !== 'https') {
return;
}
if (uri.authority !== 'github.com' && uri.authority !== 'www.github.com') {
return;
}
const paths = uri.path.split('/').filter((segment: string) => segment);
const nwo = `${paths[0]}/${paths[1]}`;
if (REPO_REGEX.test(nwo)) {
return nwo;
}
return;
} catch (e) {
// Ignore the error here, since we catch failures at a higher level.
// In particular: returning undefined leads to an error in 'promptImportGithubDatabase'.
return;
}
}
export async function convertGithubNwoToDatabaseUrl(
githubRepo: string,
credentials: Credentials,
progress: ProgressCallback): Promise<{
databaseUrl: string,
owner: string,
name: string
} | undefined> {
try {
const nwo = convertGitHubUrlToNwo(githubRepo) || githubRepo;
const [owner, repo] = nwo.split('/');
const octokit = await credentials.getOctokit();
const response = await octokit.request('GET /repos/:owner/:repo/code-scanning/codeql/databases', { owner, repo });
const languages = response.data.map((db: any) => db.language);
const language = await promptForLanguage(languages, progress);
if (!language) {
return;
}
return {
databaseUrl: `https://api.github.com/repos/${owner}/${repo}/code-scanning/codeql/databases/${language}`,
owner,
name: repo
};
} catch (e) {
void logger.log(`Error: ${getErrorMessage(e)}`);
throw new Error(`Unable to get database for '${githubRepo}'`);
}
}
/**
* The URL pattern is https://lgtm.com/projects/{provider}/{org}/{name}/{irrelevant-subpages}.
* There are several possibilities for the provider: in addition to GitHub.com(g),
* There are several possibilities for the provider: in addition to GitHub.com (g),
* LGTM currently hosts projects from Bitbucket (b), GitLab (gl) and plain git (git).
*
* After the {provider}/{org}/{name} path components, there may be the components
* related to sub pages.
* This function accepts any url that matches the pattern above. It also accepts the
* raw project slug, e.g., `g/myorg/myproject`
*
* This function accepts any url that matches the patter above
* After the `{provider}/{org}/{name}` path components, there may be the components
* related to sub pages.
*
* @param lgtmUrl The URL to the lgtm project
*
@@ -379,6 +576,10 @@ export function looksLikeLgtmUrl(lgtmUrl: string | undefined): lgtmUrl is string
return false;
}
if (convertRawLgtmSlug(lgtmUrl)) {
return true;
}
try {
const uri = Uri.parse(lgtmUrl, true);
if (uri.scheme !== 'https') {
@@ -389,29 +590,60 @@ export function looksLikeLgtmUrl(lgtmUrl: string | undefined): lgtmUrl is string
return false;
}
const paths = uri.path.split('/').filter((segment) => segment);
const paths = uri.path.split('/').filter((segment: string) => segment);
return paths.length >= 4 && paths[0] === 'projects';
} catch (e) {
return false;
}
}
function convertRawLgtmSlug(maybeSlug: string): string | undefined {
if (!maybeSlug) {
return;
}
const segments = maybeSlug.split('/');
const providers = ['g', 'gl', 'b', 'git'];
if (segments.length === 3 && providers.includes(segments[0])) {
return `https://lgtm.com/projects/${maybeSlug}`;
}
return;
}
function extractProjectSlug(lgtmUrl: string): string | undefined {
// Only matches the '/g/' provider (github)
const re = new RegExp('https://lgtm.com/projects/g/(.*[^/])');
const match = lgtmUrl.match(re);
if (!match) {
return;
}
return match[1];
}
// exported for testing
export async function convertToDatabaseUrl(lgtmUrl: string) {
export async function convertLgtmUrlToDatabaseUrl(
lgtmUrl: string,
progress: ProgressCallback) {
try {
const uri = Uri.parse(lgtmUrl, true);
const paths = ['api', 'v1.0'].concat(
uri.path.split('/').filter((segment) => segment)
).slice(0, 6);
const projectUrl = `https://lgtm.com/${paths.join('/')}`;
const projectResponse = await fetch(projectUrl);
const projectJson = await projectResponse.json();
lgtmUrl = convertRawLgtmSlug(lgtmUrl) || lgtmUrl;
let projectJson = await downloadLgtmProjectMetadata(lgtmUrl);
if (projectJson.code === 404) {
throw new Error();
// fallback check for github repositories with same name but different case
// will fail for other providers
let canonicalName = await retrieveCanonicalRepoName(lgtmUrl);
if (!canonicalName) {
throw new Error(`Project was not found at ${lgtmUrl}.`);
}
canonicalName = convertRawLgtmSlug(`g/${canonicalName}`);
projectJson = await downloadLgtmProjectMetadata(canonicalName);
if (projectJson.code === 404) {
throw new Error('Failed to download project from LGTM.');
}
}
const language = await promptForLanguage(projectJson);
const languages = projectJson?.languages?.map((lang: { language: string }) => lang.language) || [];
const language = await promptForLanguage(languages, progress);
if (!language) {
return;
}
@@ -423,25 +655,43 @@ export async function convertToDatabaseUrl(lgtmUrl: string) {
language,
].join('/')}`;
} catch (e) {
logger.log(`Error: ${e.message}`);
void logger.log(`Error: ${getErrorMessage(e)}`);
throw new Error(`Invalid LGTM URL: ${lgtmUrl}`);
}
}
async function downloadLgtmProjectMetadata(lgtmUrl: string): Promise<any> {
const uri = Uri.parse(lgtmUrl, true);
const paths = ['api', 'v1.0'].concat(
uri.path.split('/').filter((segment: string) => segment)
).slice(0, 6);
const projectUrl = `https://lgtm.com/${paths.join('/')}`;
const projectResponse = await fetch(projectUrl);
return projectResponse.json();
}
async function promptForLanguage(
projectJson: any
languages: string[],
progress: ProgressCallback
): Promise<string | undefined> {
if (!projectJson?.languages?.length) {
return;
progress({
message: 'Choose language',
step: 2,
maxStep: 2
});
if (!languages.length) {
throw new Error('No databases found');
}
if (projectJson.languages.length === 1) {
return projectJson.languages[0].language;
if (languages.length === 1) {
return languages[0];
}
return await window.showQuickPick(
projectJson.languages.map((lang: { language: string }) => lang.language), {
placeHolder: 'Select the database language to download:'
}
languages,
{
placeHolder: 'Select the database language to download:',
ignoreFocusOut: true,
}
);
}

View File

@@ -1,10 +1,8 @@
import * as path from 'path';
import { DisposableObject } from '@github/codeql-vscode-utils';
import { DisposableObject } from './pure/disposable-object';
import {
commands,
Event,
EventEmitter,
ExtensionContext,
ProviderResult,
TreeDataProvider,
TreeItem,
@@ -14,22 +12,34 @@ import {
} from 'vscode';
import * as fs from 'fs-extra';
import * as cli from './cli';
import {
DatabaseChangedEvent,
DatabaseItem,
DatabaseManager,
getUpgradesDirectories,
} from './databases';
import { getOnDiskWorkspaceFolders, showAndLogErrorMessage } from './helpers';
import {
commandRunner,
commandRunnerWithProgress,
ProgressCallback,
} from './commandRunner';
import {
isLikelyDatabaseRoot,
isLikelyDbLanguageFolder,
showAndLogErrorMessage
} from './helpers';
import { logger } from './logging';
import { clearCacheInDatabase, UserCancellationException } from './run-queries';
import { clearCacheInDatabase } from './run-queries';
import * as qsClient from './queryserver-client';
import { upgradeDatabase } from './upgrades';
import { upgradeDatabaseExplicit } from './upgrades';
import {
importArchiveDatabase,
promptImportGithubDatabase,
promptImportInternetDatabase,
promptImportLgtmDatabase,
} from './databaseFetcher';
import { CancellationToken } from 'vscode';
import { asyncFilter, getErrorMessage } from './pure/helpers-pure';
import { Credentials } from './authentication';
type ThemableIconPath = { light: string; dark: string } | string;
@@ -72,14 +82,12 @@ class DatabaseTreeDataProvider extends DisposableObject
implements TreeDataProvider<DatabaseItem> {
private _sortOrder = SortOrder.NameAsc;
private readonly _onDidChangeTreeData = new EventEmitter<
DatabaseItem | undefined
>();
private readonly _onDidChangeTreeData = this.push(new EventEmitter<DatabaseItem | undefined>());
private currentDatabaseItem: DatabaseItem | undefined;
constructor(
private ctx: ExtensionContext,
private databaseManager: DatabaseManager
private databaseManager: DatabaseManager,
private readonly extensionPath: string
) {
super();
@@ -101,19 +109,22 @@ class DatabaseTreeDataProvider extends DisposableObject
return this._onDidChangeTreeData.event;
}
private handleDidChangeDatabaseItem = (
databaseItem: DatabaseItem | undefined
): void => {
this._onDidChangeTreeData.fire(databaseItem);
private handleDidChangeDatabaseItem = (event: DatabaseChangedEvent): void => {
// Note that events from the database manager are instances of DatabaseChangedEvent
// and events fired by the UI are instances of DatabaseItem
// When event.item is undefined, then the entire tree is refreshed.
// When event.item is a db item, then only that item is refreshed.
this._onDidChangeTreeData.fire(event.item);
};
private handleDidChangeCurrentDatabaseItem = (
databaseItem: DatabaseItem | undefined
event: DatabaseChangedEvent
): void => {
if (this.currentDatabaseItem) {
this._onDidChangeTreeData.fire(this.currentDatabaseItem);
}
this.currentDatabaseItem = databaseItem;
this.currentDatabaseItem = event.item;
if (this.currentDatabaseItem) {
this._onDidChangeTreeData.fire(this.currentDatabaseItem);
}
@@ -123,16 +134,18 @@ class DatabaseTreeDataProvider extends DisposableObject
const item = new TreeItem(element.name);
if (element === this.currentDatabaseItem) {
item.iconPath = joinThemableIconPath(
this.ctx.extensionPath,
this.extensionPath,
SELECTED_DATABASE_ICON
);
item.contextValue = 'currentDatabase';
} else if (element.error !== undefined) {
item.iconPath = joinThemableIconPath(
this.ctx.extensionPath,
this.extensionPath,
INVALID_DATABASE_ICON
);
}
item.tooltip = element.databaseUri.fsPath;
item.description = element.language;
return item;
}
@@ -169,7 +182,7 @@ class DatabaseTreeDataProvider extends DisposableObject
public set sortOrder(newSortOrder: SortOrder) {
this._sortOrder = newSortOrder;
this._onDidChangeTreeData.fire();
this._onDidChangeTreeData.fire(undefined);
}
}
@@ -205,16 +218,16 @@ export class DatabaseUI extends DisposableObject {
private treeDataProvider: DatabaseTreeDataProvider;
public constructor(
ctx: ExtensionContext,
private cliserver: cli.CodeQLCliServer,
private databaseManager: DatabaseManager,
private readonly queryServer: qsClient.QueryServerClient | undefined,
private readonly storagePath: string
private readonly storagePath: string,
readonly extensionPath: string,
private readonly getCredentials: () => Promise<Credentials>
) {
super();
this.treeDataProvider = this.push(
new DatabaseTreeDataProvider(ctx, databaseManager)
new DatabaseTreeDataProvider(databaseManager, extensionPath)
);
this.push(
window.createTreeView('codeQLDatabases', {
@@ -222,90 +235,149 @@ export class DatabaseUI extends DisposableObject {
canSelectMany: true,
})
);
}
logger.log('Registering database panel commands.');
ctx.subscriptions.push(
commands.registerCommand(
init() {
void logger.log('Registering database panel commands.');
this.push(
commandRunnerWithProgress(
'codeQL.setCurrentDatabase',
this.handleSetCurrentDatabase
this.handleSetCurrentDatabase,
{
title: 'Importing database from archive',
}
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunnerWithProgress(
'codeQL.upgradeCurrentDatabase',
this.handleUpgradeCurrentDatabase
this.handleUpgradeCurrentDatabase,
{
title: 'Upgrading current database',
cancellable: true,
}
)
);
ctx.subscriptions.push(
commands.registerCommand('codeQL.clearCache', this.handleClearCache)
this.push(
commandRunnerWithProgress(
'codeQL.clearCache',
this.handleClearCache,
{
title: 'Clearing Cache',
})
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseFolder',
this.handleChooseDatabaseFolder
this.handleChooseDatabaseFolder,
{
title: 'Adding database from folder',
}
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseArchive',
this.handleChooseDatabaseArchive
this.handleChooseDatabaseArchive,
{
title: 'Adding database from archive',
}
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseInternet',
this.handleChooseDatabaseInternet
this.handleChooseDatabaseInternet,
{
title: 'Adding database from URL',
}
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseGithub',
async (
progress: ProgressCallback,
token: CancellationToken
) => {
const credentials = await this.getCredentials();
await this.handleChooseDatabaseGithub(credentials, progress, token);
},
{
title: 'Adding database from GitHub',
})
);
this.push(
commandRunnerWithProgress(
'codeQLDatabases.chooseDatabaseLgtm',
this.handleChooseDatabaseLgtm
)
this.handleChooseDatabaseLgtm,
{
title: 'Adding database from LGTM',
})
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunner(
'codeQLDatabases.setCurrentDatabase',
this.handleMakeCurrentDatabase
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunner(
'codeQLDatabases.sortByName',
this.handleSortByName
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunner(
'codeQLDatabases.sortByDateAdded',
this.handleSortByDateAdded
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunnerWithProgress(
'codeQLDatabases.removeDatabase',
this.handleRemoveDatabase
this.handleRemoveDatabase,
{
title: 'Removing database',
cancellable: false
}
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunnerWithProgress(
'codeQLDatabases.upgradeDatabase',
this.handleUpgradeDatabase
this.handleUpgradeDatabase,
{
title: 'Upgrading database',
cancellable: true,
}
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunner(
'codeQLDatabases.renameDatabase',
this.handleRenameDatabase
)
);
ctx.subscriptions.push(
commands.registerCommand(
this.push(
commandRunner(
'codeQLDatabases.openDatabaseFolder',
this.handleOpenFolder
)
);
this.push(
commandRunner(
'codeQLDatabases.addDatabaseSource',
this.handleAddSource
)
);
this.push(
commandRunner(
'codeQLDatabases.removeOrphanedDatabases',
this.handleRemoveOrphanedDatabases
)
);
}
private handleMakeCurrentDatabase = async (
@@ -314,40 +386,134 @@ export class DatabaseUI extends DisposableObject {
await this.databaseManager.setCurrentDatabaseItem(databaseItem);
};
handleChooseDatabaseFolder = async (): Promise<DatabaseItem | undefined> => {
handleChooseDatabaseFolder = async (
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
try {
return await this.chooseAndSetDatabase(true);
return await this.chooseAndSetDatabase(true, progress, token);
} catch (e) {
showAndLogErrorMessage(e.message);
void showAndLogErrorMessage(getErrorMessage(e));
return undefined;
}
};
handleChooseDatabaseArchive = async (): Promise<DatabaseItem | undefined> => {
handleRemoveOrphanedDatabases = async (): Promise<void> => {
void logger.log('Removing orphaned databases from workspace storage.');
let dbDirs = undefined;
if (
!(await fs.pathExists(this.storagePath)) ||
!(await fs.stat(this.storagePath)).isDirectory()
) {
void logger.log('Missing or invalid storage directory. Not trying to remove orphaned databases.');
return;
}
dbDirs =
// read directory
(await fs.readdir(this.storagePath, { withFileTypes: true }))
// remove non-directories
.filter(dirent => dirent.isDirectory())
// get the full path
.map(dirent => path.join(this.storagePath, dirent.name))
// remove databases still in workspace
.filter(dbDir => {
const dbUri = Uri.file(dbDir);
return this.databaseManager.databaseItems.every(item => item.databaseUri.fsPath !== dbUri.fsPath);
});
// remove non-databases
dbDirs = await asyncFilter(dbDirs, isLikelyDatabaseRoot);
if (!dbDirs.length) {
void logger.log('No orphaned databases found.');
return;
}
// delete
const failures = [] as string[];
await Promise.all(
dbDirs.map(async dbDir => {
try {
void logger.log(`Deleting orphaned database '${dbDir}'.`);
await fs.remove(dbDir);
} catch (e) {
failures.push(`${path.basename(dbDir)}`);
}
})
);
if (failures.length) {
const dirname = path.dirname(failures[0]);
void showAndLogErrorMessage(
`Failed to delete unused databases (${failures.join(', ')
}).\nTo delete unused databases, please remove them manually from the storage folder ${dirname}.`
);
}
};
handleChooseDatabaseArchive = async (
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
try {
return await this.chooseAndSetDatabase(false);
return await this.chooseAndSetDatabase(false, progress, token);
} catch (e) {
showAndLogErrorMessage(e.message);
void showAndLogErrorMessage(getErrorMessage(e));
return undefined;
}
};
handleChooseDatabaseInternet = async (): Promise<
DatabaseItem | undefined
> => {
handleChooseDatabaseInternet = async (
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
return await promptImportInternetDatabase(
this.databaseManager,
this.storagePath
this.storagePath,
progress,
token,
this.queryServer?.cliServer
);
};
handleChooseDatabaseLgtm = async (): Promise<DatabaseItem | undefined> => {
return await promptImportLgtmDatabase(
handleChooseDatabaseGithub = async (
credentials: Credentials,
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
return await promptImportGithubDatabase(
this.databaseManager,
this.storagePath
this.storagePath,
credentials,
progress,
token,
this.queryServer?.cliServer
);
};
handleChooseDatabaseLgtm = async (
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> => {
return await promptImportLgtmDatabase(
this.databaseManager,
this.storagePath,
progress,
token,
this.queryServer?.cliServer
);
};
async tryUpgradeCurrentDatabase(
progress: ProgressCallback,
token: CancellationToken
) {
await this.handleUpgradeCurrentDatabase(progress, token);
}
private handleSortByName = async () => {
if (this.treeDataProvider.sortOrder === SortOrder.NameAsc) {
this.treeDataProvider.sortOrder = SortOrder.NameDesc;
@@ -364,127 +530,115 @@ export class DatabaseUI extends DisposableObject {
}
};
private handleUpgradeCurrentDatabase = async (): Promise<void> => {
private handleUpgradeCurrentDatabase = async (
progress: ProgressCallback,
token: CancellationToken,
): Promise<void> => {
await this.handleUpgradeDatabase(
progress, token,
this.databaseManager.currentDatabaseItem,
[]
);
};
private handleUpgradeDatabase = async (
progress: ProgressCallback,
token: CancellationToken,
databaseItem: DatabaseItem | undefined,
multiSelect: DatabaseItem[] | undefined
multiSelect: DatabaseItem[] | undefined,
): Promise<void> => {
try {
if (multiSelect?.length) {
await Promise.all(
multiSelect.map((dbItem) => this.handleUpgradeDatabase(dbItem, []))
);
}
if (this.queryServer === undefined) {
logger.log(
'Received request to upgrade database, but there is no running query server.'
);
return;
}
if (databaseItem === undefined) {
logger.log(
'Received request to upgrade database, but no database was provided.'
);
return;
}
if (databaseItem.contents === undefined) {
logger.log(
'Received request to upgrade database, but database contents could not be found.'
);
return;
}
if (databaseItem.contents.dbSchemeUri === undefined) {
logger.log(
'Received request to upgrade database, but database has no schema.'
);
return;
}
// Search for upgrade scripts in any workspace folders available
const searchPath: string[] = getOnDiskWorkspaceFolders();
const upgradeInfo = await this.cliserver.resolveUpgrades(
databaseItem.contents.dbSchemeUri.fsPath,
searchPath
if (multiSelect?.length) {
await Promise.all(
multiSelect.map((dbItem) => this.handleUpgradeDatabase(progress, token, dbItem, []))
);
const { scripts, finalDbscheme } = upgradeInfo;
if (finalDbscheme === undefined) {
logger.log('Could not determine target dbscheme to upgrade to.');
return;
}
const targetDbSchemeUri = Uri.file(finalDbscheme);
await upgradeDatabase(
this.queryServer,
databaseItem,
targetDbSchemeUri,
getUpgradesDirectories(scripts)
);
} catch (e) {
if (e instanceof UserCancellationException) {
logger.log(e.message);
} else throw e;
}
if (this.queryServer === undefined) {
throw new Error(
'Received request to upgrade database, but there is no running query server.'
);
}
if (databaseItem === undefined) {
throw new Error(
'Received request to upgrade database, but no database was provided.'
);
}
if (databaseItem.contents === undefined) {
throw new Error(
'Received request to upgrade database, but database contents could not be found.'
);
}
if (databaseItem.contents.dbSchemeUri === undefined) {
throw new Error(
'Received request to upgrade database, but database has no schema.'
);
}
// Search for upgrade scripts in any workspace folders available
await upgradeDatabaseExplicit(
this.queryServer,
databaseItem,
progress,
token
);
};
private handleClearCache = async (): Promise<void> => {
private handleClearCache = async (
progress: ProgressCallback,
token: CancellationToken,
): Promise<void> => {
if (
this.queryServer !== undefined &&
this.databaseManager.currentDatabaseItem !== undefined
) {
await clearCacheInDatabase(
this.queryServer,
this.databaseManager.currentDatabaseItem
this.databaseManager.currentDatabaseItem,
progress,
token
);
}
};
private handleSetCurrentDatabase = async (
uri: Uri
): Promise<DatabaseItem | undefined> => {
progress: ProgressCallback,
token: CancellationToken,
uri: Uri,
): Promise<void> => {
try {
// Assume user has selected an archive if the file has a .zip extension
if (uri.path.endsWith('.zip')) {
return await importArchiveDatabase(
await importArchiveDatabase(
uri.toString(true),
this.databaseManager,
this.storagePath
this.storagePath,
progress,
token,
this.queryServer?.cliServer
);
} else {
await this.setCurrentDatabase(progress, token, uri);
}
return await this.setCurrentDatabase(uri);
} catch (e) {
showAndLogErrorMessage(
`Could not set database to ${path.basename(uri.fsPath)}. Reason: ${
e.message
}`
// rethrow and let this be handled by default error handling.
throw new Error(
`Could not set database to ${path.basename(uri.fsPath)}. Reason: ${getErrorMessage(e)}`
);
return undefined;
}
};
private handleRemoveDatabase = (
private handleRemoveDatabase = async (
progress: ProgressCallback,
token: CancellationToken,
databaseItem: DatabaseItem,
multiSelect: DatabaseItem[] | undefined
): void => {
try {
if (multiSelect?.length) {
multiSelect.forEach((dbItem) =>
this.databaseManager.removeDatabaseItem(dbItem)
);
} else {
this.databaseManager.removeDatabaseItem(databaseItem);
}
} catch (e) {
showAndLogErrorMessage(e.message);
): Promise<void> => {
if (multiSelect?.length) {
await Promise.all(multiSelect.map((dbItem) =>
this.databaseManager.removeDatabaseItem(progress, token, dbItem)
));
} else {
await this.databaseManager.removeDatabaseItem(progress, token, databaseItem);
}
};
@@ -492,19 +646,15 @@ export class DatabaseUI extends DisposableObject {
databaseItem: DatabaseItem,
multiSelect: DatabaseItem[] | undefined
): Promise<void> => {
try {
this.assertSingleDatabase(multiSelect);
this.assertSingleDatabase(multiSelect);
const newName = await window.showInputBox({
prompt: 'Choose new database name',
value: databaseItem.name,
});
const newName = await window.showInputBox({
prompt: 'Choose new database name',
value: databaseItem.name,
});
if (newName) {
this.databaseManager.renameDatabaseItem(databaseItem, newName);
}
} catch (e) {
showAndLogErrorMessage(e.message);
if (newName) {
await this.databaseManager.renameDatabaseItem(databaseItem, newName);
}
};
@@ -512,16 +662,30 @@ export class DatabaseUI extends DisposableObject {
databaseItem: DatabaseItem,
multiSelect: DatabaseItem[] | undefined
): Promise<void> => {
try {
if (multiSelect?.length) {
await Promise.all(
multiSelect.map((dbItem) => env.openExternal(dbItem.databaseUri))
);
} else {
await env.openExternal(databaseItem.databaseUri);
if (multiSelect?.length) {
await Promise.all(
multiSelect.map((dbItem) => env.openExternal(dbItem.databaseUri))
);
} else {
await env.openExternal(databaseItem.databaseUri);
}
};
/**
* Adds the source folder of a CodeQL database to the workspace.
* When a database is first added in the "Databases" view, its source folder is added to the workspace.
* If the source folder is removed from the workspace for some reason, we want to be able to re-add it if need be.
*/
private handleAddSource = async (
databaseItem: DatabaseItem,
multiSelect: DatabaseItem[] | undefined
): Promise<void> => {
if (multiSelect?.length) {
for (const dbItem of multiSelect) {
await this.databaseManager.addDatabaseSourceArchiveFolder(dbItem);
}
} catch (e) {
showAndLogErrorMessage(e.message);
} else {
await this.databaseManager.addDatabaseSourceArchiveFolder(databaseItem);
}
};
@@ -530,20 +694,25 @@ export class DatabaseUI extends DisposableObject {
* current database, ask the user for one, and return that, or
* undefined if they cancel.
*/
public async getDatabaseItem(): Promise<DatabaseItem | undefined> {
public async getDatabaseItem(
progress: ProgressCallback,
token: CancellationToken
): Promise<DatabaseItem | undefined> {
if (this.databaseManager.currentDatabaseItem === undefined) {
await this.chooseAndSetDatabase(false);
await this.chooseAndSetDatabase(false, progress, token);
}
return this.databaseManager.currentDatabaseItem;
}
private async setCurrentDatabase(
progress: ProgressCallback,
token: CancellationToken,
uri: Uri
): Promise<DatabaseItem | undefined> {
let databaseItem = this.databaseManager.findDatabaseItem(uri);
if (databaseItem === undefined) {
databaseItem = await this.databaseManager.openDatabase(uri);
databaseItem = await this.databaseManager.openDatabase(progress, token, uri);
}
await this.databaseManager.setCurrentDatabaseItem(databaseItem);
@@ -555,10 +724,11 @@ export class DatabaseUI extends DisposableObject {
* operation was canceled.
*/
private async chooseAndSetDatabase(
byFolder: boolean
byFolder: boolean,
progress: ProgressCallback,
token: CancellationToken,
): Promise<DatabaseItem | undefined> {
const uri = await chooseDatabaseDir(byFolder);
if (!uri) {
return undefined;
}
@@ -566,14 +736,17 @@ export class DatabaseUI extends DisposableObject {
if (byFolder) {
const fixedUri = await this.fixDbUri(uri);
// we are selecting a database folder
return await this.setCurrentDatabase(fixedUri);
return await this.setCurrentDatabase(progress, token, fixedUri);
} else {
// we are selecting a database archive. Must unzip into a workspace-controlled area
// before importing.
return await importArchiveDatabase(
uri.toString(true),
this.databaseManager,
this.storagePath
this.storagePath,
progress,
token,
this.queryServer?.cliServer
);
}
}
@@ -585,7 +758,7 @@ export class DatabaseUI extends DisposableObject {
* 2. If the selected URI is a directory matching db-*, choose the containing directory
* 3. choose the current directory
*
* @param uri a URI that is a datbase folder or inside it
* @param uri a URI that is a database folder or inside it
*
* @return the actual database folder found by using the heuristics above.
*/
@@ -595,7 +768,7 @@ export class DatabaseUI extends DisposableObject {
dbPath = path.dirname(dbPath);
}
if (isLikelyDbFolder(dbPath)) {
if (isLikelyDbLanguageFolder(dbPath)) {
dbPath = path.dirname(dbPath);
}
return Uri.file(dbPath);
@@ -610,8 +783,3 @@ export class DatabaseUI extends DisposableObject {
}
}
}
const dbRegeEx = /^db-(javascript|go|cpp|java|python)$/;
function isLikelyDbFolder(dbPath: string) {
return path.basename(dbPath).match(dbRegeEx);
}

View File

@@ -4,11 +4,22 @@ import * as path from 'path';
import * as vscode from 'vscode';
import * as cli from './cli';
import { ExtensionContext } from 'vscode';
import { showAndLogErrorMessage, showAndLogWarningMessage, showAndLogInformationMessage } from './helpers';
import { zipArchiveScheme, encodeSourceArchiveUri, decodeSourceArchiveUri } from './archive-filesystem-provider';
import { DisposableObject } from '@github/codeql-vscode-utils';
import { QueryServerConfig } from './config';
import {
showAndLogErrorMessage,
showAndLogWarningMessage,
showAndLogInformationMessage,
isLikelyDatabaseRoot
} from './helpers';
import {
ProgressCallback,
withProgress
} from './commandRunner';
import { zipArchiveScheme, encodeArchiveBasePath, decodeSourceArchiveUri, encodeSourceArchiveUri } from './archive-filesystem-provider';
import { DisposableObject } from './pure/disposable-object';
import { Logger, logger } from './logging';
import { registerDatabases, Dataset, deregisterDatabases } from './pure/messages';
import { QueryServerClient } from './queryserver-client';
import { getErrorMessage } from './pure/helpers-pure';
/**
* databases.ts
@@ -36,11 +47,13 @@ export interface DatabaseOptions {
displayName?: string;
ignoreSourceArchive?: boolean;
dateAdded?: number | undefined;
language?: string;
}
interface FullDatabaseOptions extends DatabaseOptions {
export interface FullDatabaseOptions extends DatabaseOptions {
ignoreSourceArchive: boolean;
dateAdded: number | undefined;
language: string | undefined;
}
interface PersistedDatabaseItem {
@@ -103,36 +116,39 @@ async function findDataset(parentDirectory: string): Promise<vscode.Uri> {
const dbAbsolutePath = path.join(parentDirectory, dbRelativePaths[0]);
if (dbRelativePaths.length > 1) {
showAndLogWarningMessage(`Found multiple dataset directories in database, using '${dbAbsolutePath}'.`);
void showAndLogWarningMessage(`Found multiple dataset directories in database, using '${dbAbsolutePath}'.`);
}
return vscode.Uri.file(dbAbsolutePath);
}
async function findSourceArchive(
// exported for testing
export async function findSourceArchive(
databasePath: string, silent = false
): Promise<vscode.Uri | undefined> {
const relativePaths = ['src', 'output/src_archive'];
for (const relativePath of relativePaths) {
const basePath = path.join(databasePath, relativePath);
const zipPath = basePath + '.zip';
if (await fs.pathExists(basePath)) {
// Prefer using a zip archive over a directory.
if (await fs.pathExists(zipPath)) {
return encodeArchiveBasePath(zipPath);
} else if (await fs.pathExists(basePath)) {
return vscode.Uri.file(basePath);
}
else if (await fs.pathExists(zipPath)) {
return vscode.Uri.file(zipPath).with({ scheme: zipArchiveScheme });
}
}
if (!silent)
showAndLogInformationMessage(`Could not find source archive for database '${databasePath}'. Assuming paths are absolute.`);
if (!silent) {
void showAndLogInformationMessage(
`Could not find source archive for database '${databasePath}'. Assuming paths are absolute.`
);
}
return undefined;
}
async function resolveDatabase(
databasePath: string
databasePath: string,
): Promise<DatabaseContents> {
const name = path.basename(databasePath);
@@ -147,7 +163,6 @@ async function resolveDatabase(
datasetUri,
sourceArchiveUri
};
}
/** Gets the relative paths of all `.dbscheme` files in the given directory. */
@@ -155,7 +170,9 @@ async function getDbSchemeFiles(dbDirectory: string): Promise<string[]> {
return await glob('*.dbscheme', { cwd: dbDirectory });
}
async function resolveDatabaseContents(uri: vscode.Uri): Promise<DatabaseContents> {
async function resolveDatabaseContents(
uri: vscode.Uri,
): Promise<DatabaseContents> {
if (uri.scheme !== 'file') {
throw new Error(`Database URI scheme '${uri.scheme}' not supported; only 'file' URIs are supported.`);
}
@@ -191,6 +208,9 @@ export interface DatabaseItem {
readonly databaseUri: vscode.Uri;
/** The name of the database to be displayed in the UI */
name: string;
/** The primary language of the database or empty string if unknown */
readonly language: string;
/** The URI of the database's source archive, or `undefined` if no source archive is to be used. */
readonly sourceArchive: vscode.Uri | undefined;
/**
@@ -241,24 +261,60 @@ export interface DatabaseItem {
* Returns the root uri of the virtual filesystem for this database's source archive,
* as displayed in the filesystem explorer.
*/
getSourceArchiveExplorerUri(): vscode.Uri | undefined;
getSourceArchiveExplorerUri(): vscode.Uri;
/**
* Holds if `uri` belongs to this database's source archive.
*/
belongsToSourceArchiveExplorerUri(uri: vscode.Uri): boolean;
/**
* Whether the database may be affected by test execution for the given path.
*/
isAffectedByTest(testPath: string): Promise<boolean>;
/**
* Gets the state of this database, to be persisted in the workspace state.
*/
getPersistedState(): PersistedDatabaseItem;
/**
* Verifies that this database item has a zipped source folder. Returns an error message if it does not.
*/
verifyZippedSources(): string | undefined;
}
class DatabaseItemImpl implements DatabaseItem {
export enum DatabaseEventKind {
Add = 'Add',
Remove = 'Remove',
// Fired when databases are refreshed from persisted state
Refresh = 'Refresh',
// Fired when the current database changes
Change = 'Change',
Rename = 'Rename'
}
export interface DatabaseChangedEvent {
kind: DatabaseEventKind;
item: DatabaseItem | undefined;
}
// Exported for testing
export class DatabaseItemImpl implements DatabaseItem {
private _error: Error | undefined = undefined;
private _contents: DatabaseContents | undefined;
/** A cache of database info */
private _dbinfo: cli.DbInfo | undefined;
public constructor(public readonly databaseUri: vscode.Uri,
contents: DatabaseContents | undefined, private options: FullDatabaseOptions,
private readonly onChanged: (item: DatabaseItemImpl) => void) {
public constructor(
public readonly databaseUri: vscode.Uri,
contents: DatabaseContents | undefined,
private options: FullDatabaseOptions,
private readonly onChanged: (event: DatabaseChangedEvent) => void
) {
this._contents = contents;
}
@@ -281,8 +337,7 @@ class DatabaseItemImpl implements DatabaseItem {
public get sourceArchive(): vscode.Uri | undefined {
if (this.options.ignoreSourceArchive || (this._contents === undefined)) {
return undefined;
}
else {
} else {
return this._contents.sourceArchiveUri;
}
}
@@ -307,51 +362,57 @@ class DatabaseItemImpl implements DatabaseItem {
}
catch (e) {
this._contents = undefined;
this._error = e;
this._error = e instanceof Error ? e : new Error(String(e));
throw e;
}
}
finally {
this.onChanged(this);
this.onChanged({
kind: DatabaseEventKind.Refresh,
item: this
});
}
}
public resolveSourceFile(file: string | undefined): vscode.Uri {
public resolveSourceFile(uriStr: string | undefined): vscode.Uri {
const sourceArchive = this.sourceArchive;
if (sourceArchive === undefined) {
if (file !== undefined) {
// Treat it as an absolute path.
return vscode.Uri.file(file);
}
else {
const uri = uriStr ? vscode.Uri.parse(uriStr, true) : undefined;
if (uri && uri.scheme !== 'file') {
throw new Error(`Invalid uri scheme in ${uriStr}. Only 'file' is allowed.`);
}
if (!sourceArchive) {
if (uri) {
return uri;
} else {
return this.databaseUri;
}
}
else {
if (file !== undefined) {
const absoluteFilePath = file.replace(':', '_');
// Strip any leading slashes from the file path, and replace `:` with `_`.
const relativeFilePath = absoluteFilePath.replace(/^\/*/, '').replace(':', '_');
if (sourceArchive.scheme == zipArchiveScheme) {
return encodeSourceArchiveUri({
pathWithinSourceArchive: absoluteFilePath,
sourceArchiveZipPath: sourceArchive.fsPath,
});
}
else {
let newPath = sourceArchive.path;
if (!newPath.endsWith('/')) {
// Ensure a trailing slash.
newPath += '/';
}
newPath += relativeFilePath;
return sourceArchive.with({ path: newPath });
if (uri) {
const relativeFilePath = decodeURI(uri.path).replace(':', '_').replace(/^\/*/, '');
if (sourceArchive.scheme === zipArchiveScheme) {
const zipRef = decodeSourceArchiveUri(sourceArchive);
const pathWithinSourceArchive = zipRef.pathWithinSourceArchive === '/'
? relativeFilePath
: zipRef.pathWithinSourceArchive + '/' + relativeFilePath;
return encodeSourceArchiveUri({
pathWithinSourceArchive,
sourceArchiveZipPath: zipRef.sourceArchiveZipPath,
});
} else {
let newPath = sourceArchive.path;
if (!newPath.endsWith('/')) {
// Ensure a trailing slash.
newPath += '/';
}
newPath += relativeFilePath;
return sourceArchive.with({ path: newPath });
}
else {
return sourceArchive;
}
} else {
return sourceArchive;
}
}
@@ -369,10 +430,7 @@ class DatabaseItemImpl implements DatabaseItem {
* Holds if the database item refers to an exported snapshot
*/
public async hasMetadataFile(): Promise<boolean> {
return (await Promise.all([
fs.pathExists(path.join(this.databaseUri.fsPath, '.dbinfo')),
fs.pathExists(path.join(this.databaseUri.fsPath, 'codeql-database.yml'))
])).some(x => x);
return await isLikelyDatabaseRoot(this.databaseUri.fsPath);
}
/**
@@ -402,17 +460,31 @@ class DatabaseItemImpl implements DatabaseItem {
return dbInfo.datasetFolder;
}
public get language() {
return this.options.language || '';
}
/**
* Returns the root uri of the virtual filesystem for this database's source archive.
*/
public getSourceArchiveExplorerUri(): vscode.Uri | undefined {
public getSourceArchiveExplorerUri(): vscode.Uri {
const sourceArchive = this.sourceArchive;
if (sourceArchive === undefined || !sourceArchive.fsPath.endsWith('.zip'))
return undefined;
return encodeSourceArchiveUri({
pathWithinSourceArchive: '/',
sourceArchiveZipPath: sourceArchive.fsPath,
});
if (sourceArchive === undefined || !sourceArchive.fsPath.endsWith('.zip')) {
throw new Error(this.verifyZippedSources());
}
return encodeArchiveBasePath(sourceArchive.fsPath);
}
public verifyZippedSources(): string | undefined {
const sourceArchive = this.sourceArchive;
if (sourceArchive === undefined) {
return `${this.name} has no source archive.`;
}
if (!sourceArchive.fsPath.endsWith('.zip')) {
return `${this.name} has a source folder that is unzipped.`;
}
return;
}
/**
@@ -424,6 +496,27 @@ class DatabaseItemImpl implements DatabaseItem {
return uri.scheme === zipArchiveScheme &&
decodeSourceArchiveUri(uri).sourceArchiveZipPath === this.sourceArchive.fsPath;
}
public async isAffectedByTest(testPath: string): Promise<boolean> {
const databasePath = this.databaseUri.fsPath;
if (!databasePath.endsWith('.testproj')) {
return false;
}
try {
const stats = await fs.stat(testPath);
if (stats.isDirectory()) {
return !path.relative(testPath, databasePath).startsWith('..');
} else {
// database for /one/two/three/test.ql is at /one/two/three/three.testproj
const testdir = path.dirname(testPath);
const testdirbase = path.basename(testdir);
return databasePath == path.join(testdir, testdirbase + '.testproj');
}
} catch {
// No information available for test path - assume database is unaffected.
return false;
}
}
}
/**
@@ -434,7 +527,7 @@ class DatabaseItemImpl implements DatabaseItem {
function eventFired<T>(event: vscode.Event<T>, timeoutMs = 1000): Promise<T | undefined> {
return new Promise((res, _rej) => {
const timeout = setTimeout(() => {
logger.log(`Waiting for event ${event} timed out after ${timeoutMs}ms`);
void logger.log(`Waiting for event ${event} timed out after ${timeoutMs}ms`);
res(undefined);
dispose();
}, timeoutMs);
@@ -450,48 +543,73 @@ function eventFired<T>(event: vscode.Event<T>, timeoutMs = 1000): Promise<T | un
}
export class DatabaseManager extends DisposableObject {
private readonly _onDidChangeDatabaseItem = this.push(new vscode.EventEmitter<DatabaseItem | undefined>());
private readonly _onDidChangeDatabaseItem = this.push(new vscode.EventEmitter<DatabaseChangedEvent>());
readonly onDidChangeDatabaseItem = this._onDidChangeDatabaseItem.event;
private readonly _onDidChangeCurrentDatabaseItem = this.push(new vscode.EventEmitter<DatabaseItem | undefined>());
private readonly _onDidChangeCurrentDatabaseItem = this.push(new vscode.EventEmitter<DatabaseChangedEvent>());
readonly onDidChangeCurrentDatabaseItem = this._onDidChangeCurrentDatabaseItem.event;
private readonly _databaseItems: DatabaseItemImpl[] = [];
private readonly _databaseItems: DatabaseItem[] = [];
private _currentDatabaseItem: DatabaseItem | undefined = undefined;
constructor(private ctx: ExtensionContext,
public config: QueryServerConfig,
public logger: Logger) {
constructor(
private readonly ctx: ExtensionContext,
private readonly qs: QueryServerClient,
private readonly cli: cli.CodeQLCliServer,
public logger: Logger
) {
super();
this.loadPersistedState(); // Let this run async.
qs.onDidStartQueryServer(this.reregisterDatabases.bind(this));
// Let this run async.
void this.loadPersistedState();
}
public async openDatabase(
uri: vscode.Uri, options?: DatabaseOptions
progress: ProgressCallback,
token: vscode.CancellationToken,
uri: vscode.Uri,
displayName?: string
): Promise<DatabaseItem> {
const contents = await resolveDatabaseContents(uri);
const realOptions = options || {};
// Ignore the source archive for QLTest databases by default.
const isQLTestDatabase = path.extname(uri.fsPath) === '.testproj';
const fullOptions: FullDatabaseOptions = {
ignoreSourceArchive: (realOptions.ignoreSourceArchive !== undefined) ?
realOptions.ignoreSourceArchive : isQLTestDatabase,
displayName: realOptions.displayName,
dateAdded: realOptions.dateAdded || Date.now()
ignoreSourceArchive: isQLTestDatabase,
// If a displayName is not passed in, the basename of folder containing the database is used.
displayName,
dateAdded: Date.now(),
language: await this.getPrimaryLanguage(uri.fsPath)
};
const databaseItem = new DatabaseItemImpl(uri, contents, fullOptions, (item) => {
this._onDidChangeDatabaseItem.fire(item);
const databaseItem = new DatabaseItemImpl(uri, contents, fullOptions, (event) => {
this._onDidChangeDatabaseItem.fire(event);
});
await this.addDatabaseItem(databaseItem);
await this.addDatabaseItem(progress, token, databaseItem);
await this.addDatabaseSourceArchiveFolder(databaseItem);
return databaseItem;
}
private async addDatabaseSourceArchiveFolder(item: DatabaseItem) {
private async reregisterDatabases(
progress: ProgressCallback,
token: vscode.CancellationToken
) {
let completed = 0;
await Promise.all(this._databaseItems.map(async (databaseItem) => {
await this.registerDatabase(progress, token, databaseItem);
completed++;
progress({
maxStep: this._databaseItems.length,
step: completed,
message: 'Re-registering databases'
});
}));
}
public async addDatabaseSourceArchiveFolder(item: DatabaseItem) {
// The folder may already be in workspace state from a previous
// session. If not, add it.
const index = this.getDatabaseWorkspaceFolderIndex(item);
@@ -507,36 +625,41 @@ export class DatabaseManager extends DisposableObject {
// This is undesirable, as we might be adding and removing many
// workspace folders as the user adds and removes databases.
const end = (vscode.workspace.workspaceFolders || []).length;
const msg = item.verifyZippedSources();
if (msg) {
void logger.log(`Could not add source folder because ${msg}`);
return;
}
const uri = item.getSourceArchiveExplorerUri();
if (uri === undefined) {
logger.log(`Couldn't obtain file explorer uri for ${item.name}`);
}
else {
logger.log(`Adding workspace folder for ${item.name} source archive at index ${end}`);
if ((vscode.workspace.workspaceFolders || []).length < 2) {
// Adding this workspace folder makes the workspace
// multi-root, which may surprise the user. Let them know
// we're doing this.
vscode.window.showInformationMessage(`Adding workspace folder for source archive of database ${item.name}.`);
}
vscode.workspace.updateWorkspaceFolders(end, 0, {
name: `[${item.name} source archive]`,
uri,
});
// vscode api documentation says we must to wait for this event
// between multiple `updateWorkspaceFolders` calls.
await eventFired(vscode.workspace.onDidChangeWorkspaceFolders);
void logger.log(`Adding workspace folder for ${item.name} source archive at index ${end}`);
if ((vscode.workspace.workspaceFolders || []).length < 2) {
// Adding this workspace folder makes the workspace
// multi-root, which may surprise the user. Let them know
// we're doing this.
void vscode.window.showInformationMessage(`Adding workspace folder for source archive of database ${item.name}.`);
}
vscode.workspace.updateWorkspaceFolders(end, 0, {
name: `[${item.name} source archive]`,
uri,
});
// vscode api documentation says we must to wait for this event
// between multiple `updateWorkspaceFolders` calls.
await eventFired(vscode.workspace.onDidChangeWorkspaceFolders);
}
}
private async createDatabaseItemFromPersistedState(
progress: ProgressCallback,
token: vscode.CancellationToken,
state: PersistedDatabaseItem
): Promise<DatabaseItem> {
let displayName: string | undefined = undefined;
let ignoreSourceArchive = false;
let dateAdded = undefined;
let language = undefined;
if (state.options) {
if (typeof state.options.displayName === 'string') {
displayName = state.options.displayName;
@@ -547,43 +670,69 @@ export class DatabaseManager extends DisposableObject {
if (typeof state.options.dateAdded === 'number') {
dateAdded = state.options.dateAdded;
}
language = state.options.language;
}
const dbBaseUri = vscode.Uri.parse(state.uri, true);
if (language === undefined) {
// we haven't been successful yet at getting the language. try again
language = await this.getPrimaryLanguage(dbBaseUri.fsPath);
}
const fullOptions: FullDatabaseOptions = {
ignoreSourceArchive,
displayName,
dateAdded
dateAdded,
language
};
const item = new DatabaseItemImpl(vscode.Uri.parse(state.uri), undefined, fullOptions,
(item) => {
this._onDidChangeDatabaseItem.fire(item);
const item = new DatabaseItemImpl(dbBaseUri, undefined, fullOptions,
(event) => {
this._onDidChangeDatabaseItem.fire(event);
});
await this.addDatabaseItem(item);
await this.addDatabaseItem(progress, token, item);
return item;
}
private async loadPersistedState(): Promise<void> {
const currentDatabaseUri = this.ctx.workspaceState.get<string>(CURRENT_DB);
const databases = this.ctx.workspaceState.get<PersistedDatabaseItem[]>(DB_LIST, []);
try {
for (const database of databases) {
const databaseItem = await this.createDatabaseItemFromPersistedState(database);
return withProgress({
location: vscode.ProgressLocation.Notification
},
async (progress, token) => {
const currentDatabaseUri = this.ctx.workspaceState.get<string>(CURRENT_DB);
const databases = this.ctx.workspaceState.get<PersistedDatabaseItem[]>(DB_LIST, []);
let step = 0;
progress({
maxStep: databases.length,
message: 'Loading persisted databases',
step
});
try {
await databaseItem.refresh();
if (currentDatabaseUri === database.uri) {
this.setCurrentDatabaseItem(databaseItem, true);
for (const database of databases) {
progress({
maxStep: databases.length,
message: `Loading ${database.options?.displayName || 'databases'}`,
step: ++step
});
const databaseItem = await this.createDatabaseItemFromPersistedState(progress, token, database);
try {
await databaseItem.refresh();
await this.registerDatabase(progress, token, databaseItem);
if (currentDatabaseUri === database.uri) {
await this.setCurrentDatabaseItem(databaseItem, true);
}
}
catch (e) {
// When loading from persisted state, leave invalid databases in the list. They will be
// marked as invalid, and cannot be set as the current database.
}
}
} catch (e) {
// database list had an unexpected type - nothing to be done?
void showAndLogErrorMessage(`Database list loading failed: ${getErrorMessage(e)}`);
}
catch (e) {
// When loading from persisted state, leave invalid databases in the list. They will be
// marked as invalid, and cannot be set as the current database.
}
}
} catch (e) {
// database list had an unexpected type - nothing to be done?
showAndLogErrorMessage(`Database list loading failed: ${e.message}`);
}
});
}
public get databaseItems(): readonly DatabaseItem[] {
@@ -594,8 +743,10 @@ export class DatabaseManager extends DisposableObject {
return this._currentDatabaseItem;
}
public async setCurrentDatabaseItem(item: DatabaseItem | undefined,
skipRefresh = false): Promise<void> {
public async setCurrentDatabaseItem(
item: DatabaseItem | undefined,
skipRefresh = false
): Promise<void> {
if (!skipRefresh && (item !== undefined)) {
await item.refresh(); // Will throw on invalid database.
@@ -603,7 +754,13 @@ export class DatabaseManager extends DisposableObject {
if (this._currentDatabaseItem !== item) {
this._currentDatabaseItem = item;
this.updatePersistedCurrentDatabaseItem();
this._onDidChangeCurrentDatabaseItem.fire(item);
await vscode.commands.executeCommand('setContext', 'codeQL.currentDatabaseItem', item?.name);
this._onDidChangeCurrentDatabaseItem.fire({
item,
kind: DatabaseEventKind.Change
});
}
}
@@ -626,57 +783,135 @@ export class DatabaseManager extends DisposableObject {
return this._databaseItems.find(item => item.sourceArchive && item.sourceArchive.toString(true) === uriString);
}
private async addDatabaseItem(item: DatabaseItemImpl) {
private async addDatabaseItem(
progress: ProgressCallback,
token: vscode.CancellationToken,
item: DatabaseItem
) {
this._databaseItems.push(item);
this.updatePersistedDatabaseList();
this._onDidChangeDatabaseItem.fire(undefined);
await this.updatePersistedDatabaseList();
// Add this database item to the allow-list
// Database items reconstituted from persisted state
// will not have their contents yet.
if (item.contents?.datasetUri) {
await this.registerDatabase(progress, token, item);
}
// note that we use undefined as the item in order to reset the entire tree
this._onDidChangeDatabaseItem.fire({
item: undefined,
kind: DatabaseEventKind.Add
});
}
public async renameDatabaseItem(item: DatabaseItem, newName: string) {
item.name = newName;
this.updatePersistedDatabaseList();
this._onDidChangeDatabaseItem.fire(item);
await this.updatePersistedDatabaseList();
this._onDidChangeDatabaseItem.fire({
// pass undefined so that the entire tree is rebuilt in order to re-sort
item: undefined,
kind: DatabaseEventKind.Rename
});
}
public removeDatabaseItem(item: DatabaseItem) {
if (this._currentDatabaseItem == item)
public async removeDatabaseItem(
progress: ProgressCallback,
token: vscode.CancellationToken,
item: DatabaseItem
) {
if (this._currentDatabaseItem == item) {
this._currentDatabaseItem = undefined;
}
const index = this.databaseItems.findIndex(searchItem => searchItem === item);
if (index >= 0) {
this._databaseItems.splice(index, 1);
}
this.updatePersistedDatabaseList();
await this.updatePersistedDatabaseList();
// Delete folder from workspace, if it is still there
const folderIndex = (vscode.workspace.workspaceFolders || []).findIndex(folder => item.belongsToSourceArchiveExplorerUri(folder.uri));
if (index >= 0) {
logger.log(`Removing workspace folder at index ${folderIndex}`);
const folderIndex = (vscode.workspace.workspaceFolders || []).findIndex(
folder => item.belongsToSourceArchiveExplorerUri(folder.uri)
);
if (folderIndex >= 0) {
void logger.log(`Removing workspace folder at index ${folderIndex}`);
vscode.workspace.updateWorkspaceFolders(folderIndex, 1);
}
// Remove this database item from the allow-list
await this.deregisterDatabase(progress, token, item);
// Delete folder from file system only if it is controlled by the extension
if (this.isExtensionControlledLocation(item.databaseUri)) {
logger.log('Deleting database from filesystem.');
fs.remove(item.databaseUri.path).then(
() => logger.log(`Deleted '${item.databaseUri.path}'`),
e => logger.log(`Failed to delete '${item.databaseUri.path}'. Reason: ${e.message}`));
void logger.log('Deleting database from filesystem.');
fs.remove(item.databaseUri.fsPath).then(
() => void logger.log(`Deleted '${item.databaseUri.fsPath}'`),
e => void logger.log(`Failed to delete '${item.databaseUri.fsPath}'. Reason: ${getErrorMessage(e)}`));
}
this._onDidChangeDatabaseItem.fire(undefined);
// note that we use undefined as the item in order to reset the entire tree
this._onDidChangeDatabaseItem.fire({
item: undefined,
kind: DatabaseEventKind.Remove
});
}
private async deregisterDatabase(
progress: ProgressCallback,
token: vscode.CancellationToken,
dbItem: DatabaseItem,
) {
if (dbItem.contents && (await this.cli.cliConstraints.supportsDatabaseRegistration())) {
const databases: Dataset[] = [{
dbDir: dbItem.contents.datasetUri.fsPath,
workingSet: 'default'
}];
await this.qs.sendRequest(deregisterDatabases, { databases }, token, progress);
}
}
private async registerDatabase(
progress: ProgressCallback,
token: vscode.CancellationToken,
dbItem: DatabaseItem,
) {
if (dbItem.contents && (await this.cli.cliConstraints.supportsDatabaseRegistration())) {
const databases: Dataset[] = [{
dbDir: dbItem.contents.datasetUri.fsPath,
workingSet: 'default'
}];
await this.qs.sendRequest(registerDatabases, { databases }, token, progress);
}
}
private updatePersistedCurrentDatabaseItem(): void {
this.ctx.workspaceState.update(CURRENT_DB, this._currentDatabaseItem ?
void this.ctx.workspaceState.update(CURRENT_DB, this._currentDatabaseItem ?
this._currentDatabaseItem.databaseUri.toString(true) : undefined);
}
private updatePersistedDatabaseList(): void {
this.ctx.workspaceState.update(DB_LIST, this._databaseItems.map(item => item.getPersistedState()));
private async updatePersistedDatabaseList(): Promise<void> {
await this.ctx.workspaceState.update(DB_LIST, this._databaseItems.map(item => item.getPersistedState()));
}
private isExtensionControlledLocation(uri: vscode.Uri) {
const storagePath = this.ctx.storagePath || this.ctx.globalStoragePath;
return uri.path.startsWith(storagePath);
// the uri.fsPath function on windows returns a lowercase drive letter,
// but storagePath will have an uppercase drive letter. Be sure to compare
// URIs to URIs only
if (storagePath) {
return uri.fsPath.startsWith(vscode.Uri.file(storagePath).fsPath);
}
return false;
}
private async getPrimaryLanguage(dbPath: string) {
if (!(await this.cli.cliConstraints.supportsLanguageName())) {
// return undefined so that we recalculate on restart until the cli is at a version that
// supports this feature. This recalculation is cheap since we avoid calling into the cli
// unless we know it can return the langauges property.
return undefined;
}
const dbInfo = await this.cli.resolveDatabase(dbPath);
return dbInfo.languages?.[0] || '';
}
}

View File

@@ -1,216 +0,0 @@
import * as fs from 'fs-extra';
import * as yaml from 'js-yaml';
import * as tmp from 'tmp-promise';
import * as vscode from 'vscode';
import { decodeSourceArchiveUri, zipArchiveScheme } from './archive-filesystem-provider';
import { ColumnKindCode, EntityValue, getResultSetSchema, LineColumnLocation, UrlValue } from './bqrs-cli-types';
import { CodeQLCliServer } from './cli';
import { DatabaseItem, DatabaseManager } from './databases';
import * as helpers from './helpers';
import { CachedOperation } from './helpers';
import * as messages from './messages';
import { QueryServerClient } from './queryserver-client';
import { compileAndRunQueryAgainstDatabase, QueryWithResults } from './run-queries';
/**
* Run templated CodeQL queries to find definitions and references in
* source-language files. We may eventually want to find a way to
* generalize this to other custom queries, e.g. showing dataflow to
* or from a selected identifier.
*/
const TEMPLATE_NAME = 'selectedSourceFile';
const SELECT_QUERY_NAME = '#select';
enum KeyType {
DefinitionQuery = 'DefinitionQuery',
ReferenceQuery = 'ReferenceQuery',
}
function tagOfKeyType(keyType: KeyType): string {
switch (keyType) {
case KeyType.DefinitionQuery: return 'ide-contextual-queries/local-definitions';
case KeyType.ReferenceQuery: return 'ide-contextual-queries/local-references';
}
}
function nameOfKeyType(keyType: KeyType): string {
switch (keyType) {
case KeyType.DefinitionQuery: return 'definitions';
case KeyType.ReferenceQuery: return 'references';
}
}
async function resolveQueries(cli: CodeQLCliServer, qlpack: string, keyType: KeyType): Promise<string[]> {
const suiteFile = (await tmp.file({
postfix: '.qls'
})).path;
const suiteYaml = { qlpack, include: { kind: 'definitions', 'tags contain': tagOfKeyType(keyType) } };
await fs.writeFile(suiteFile, yaml.safeDump(suiteYaml), 'utf8');
const queries = await cli.resolveQueriesInSuite(suiteFile, helpers.getOnDiskWorkspaceFolders());
if (queries.length === 0) {
vscode.window.showErrorMessage(
`No ${nameOfKeyType(keyType)} queries (tagged "${tagOfKeyType(keyType)}") could be found in the current library path. It might be necessary to upgrade the CodeQL libraries.`
);
throw new Error(`Couldn't find any queries tagged ${tagOfKeyType(keyType)} for qlpack ${qlpack}`);
}
return queries;
}
async function qlpackOfDatabase(cli: CodeQLCliServer, db: DatabaseItem): Promise<string | undefined> {
if (db.contents === undefined)
return undefined;
const datasetPath = db.contents.datasetUri.fsPath;
const { qlpack } = await helpers.resolveDatasetFolder(cli, datasetPath);
return qlpack;
}
interface FullLocationLink extends vscode.LocationLink {
originUri: vscode.Uri;
}
export class TemplateQueryDefinitionProvider implements vscode.DefinitionProvider {
private cache: CachedOperation<vscode.LocationLink[]>;
constructor(
private cli: CodeQLCliServer,
private qs: QueryServerClient,
private dbm: DatabaseManager,
) {
this.cache = new CachedOperation<vscode.LocationLink[]>(this.getDefinitions.bind(this));
}
async getDefinitions(uriString: string): Promise<vscode.LocationLink[]> {
return getLinksForUriString(this.cli, this.qs, this.dbm, uriString, KeyType.DefinitionQuery, (src, _dest) => src === uriString);
}
async provideDefinition(document: vscode.TextDocument, position: vscode.Position, _token: vscode.CancellationToken): Promise<vscode.LocationLink[]> {
const fileLinks = await this.cache.get(document.uri.toString());
const locLinks: vscode.LocationLink[] = [];
for (const link of fileLinks) {
if (link.originSelectionRange!.contains(position)) {
locLinks.push(link);
}
}
return locLinks;
}
}
export class TemplateQueryReferenceProvider implements vscode.ReferenceProvider {
private cache: CachedOperation<FullLocationLink[]>;
constructor(
private cli: CodeQLCliServer,
private qs: QueryServerClient,
private dbm: DatabaseManager,
) {
this.cache = new CachedOperation<FullLocationLink[]>(this.getReferences.bind(this));
}
async getReferences(uriString: string): Promise<FullLocationLink[]> {
return getLinksForUriString(this.cli, this.qs, this.dbm, uriString, KeyType.ReferenceQuery, (_src, dest) => dest === uriString);
}
async provideReferences(document: vscode.TextDocument, position: vscode.Position, _context: vscode.ReferenceContext, _token: vscode.CancellationToken): Promise<vscode.Location[]> {
const fileLinks = await this.cache.get(document.uri.toString());
const locLinks: vscode.Location[] = [];
for (const link of fileLinks) {
if (link.targetRange!.contains(position)) {
locLinks.push({ range: link.originSelectionRange!, uri: link.originUri });
}
}
return locLinks;
}
}
interface FileRange {
file: vscode.Uri;
range: vscode.Range;
}
async function getLinksFromResults(results: QueryWithResults, cli: CodeQLCliServer, db: DatabaseItem, filter: (srcFile: string, destFile: string) => boolean): Promise<FullLocationLink[]> {
const localLinks: FullLocationLink[] = [];
const bqrsPath = results.query.resultsPaths.resultsPath;
const info = await cli.bqrsInfo(bqrsPath);
const selectInfo = getResultSetSchema(SELECT_QUERY_NAME, info);
if (selectInfo && selectInfo.columns.length == 3
&& selectInfo.columns[0].kind == ColumnKindCode.ENTITY
&& selectInfo.columns[1].kind == ColumnKindCode.ENTITY
&& selectInfo.columns[2].kind == ColumnKindCode.STRING) {
// TODO: Page this
const allTuples = await cli.bqrsDecode(bqrsPath, SELECT_QUERY_NAME);
for (const tuple of allTuples.tuples) {
const src = tuple[0] as EntityValue;
const dest = tuple[1] as EntityValue;
const srcFile = src.url && fileRangeFromURI(src.url, db);
const destFile = dest.url && fileRangeFromURI(dest.url, db);
if (srcFile && destFile && filter(srcFile.file.toString(), destFile.file.toString())) {
localLinks.push({ targetRange: destFile.range, targetUri: destFile.file, originSelectionRange: srcFile.range, originUri: srcFile.file });
}
}
}
return localLinks;
}
async function getLinksForUriString(
cli: CodeQLCliServer,
qs: QueryServerClient,
dbm: DatabaseManager,
uriString: string,
keyType: KeyType,
filter: (src: string, dest: string) => boolean
) {
const uri = decodeSourceArchiveUri(vscode.Uri.parse(uriString));
const sourceArchiveUri = vscode.Uri.file(uri.sourceArchiveZipPath).with({ scheme: zipArchiveScheme });
const db = dbm.findDatabaseItemBySourceArchive(sourceArchiveUri);
if (db) {
const qlpack = await qlpackOfDatabase(cli, db);
if (qlpack === undefined) {
throw new Error('Can\'t infer qlpack from database source archive');
}
const links: FullLocationLink[] = [];
for (const query of await resolveQueries(cli, qlpack, keyType)) {
const templates: messages.TemplateDefinitions = {
[TEMPLATE_NAME]: {
values: {
tuples: [[{
stringValue: uri.pathWithinSourceArchive
}]]
}
}
};
const results = await compileAndRunQueryAgainstDatabase(cli, qs, db, false, vscode.Uri.file(query), templates);
if (results.result.resultType == messages.QueryResultType.SUCCESS) {
links.push(...await getLinksFromResults(results, cli, db, filter));
}
}
return links;
} else {
return [];
}
}
function fileRangeFromURI(uri: UrlValue, db: DatabaseItem): FileRange | undefined {
if (typeof uri === 'string') {
return undefined;
} else if ('startOffset' in uri) {
return undefined;
} else {
const loc = uri as LineColumnLocation;
const range = new vscode.Range(Math.max(0, loc.startLine - 1),
Math.max(0, loc.startColumn - 1),
Math.max(0, loc.endLine - 1),
Math.max(0, loc.endColumn));
try {
const parsed = vscode.Uri.parse(uri.uri, true);
if (parsed.scheme === 'file') {
return { file: db.resolveSourceFile(parsed.fsPath), range };
}
return undefined;
} catch (e) {
return undefined;
}
}
}

View File

@@ -1,4 +1,5 @@
import { DisposableObject } from '@github/codeql-vscode-utils';
import { DisposableObject } from './pure/disposable-object';
import { logger } from './logging';
/**
* Base class for "discovery" operations, which scan the file system to find specific kinds of
@@ -9,7 +10,7 @@ export abstract class Discovery<T> extends DisposableObject {
private retry = false;
private discoveryInProgress = false;
constructor() {
constructor(private readonly name: string) {
super();
}
@@ -58,18 +59,23 @@ export abstract class Discovery<T> extends DisposableObject {
this.discoveryInProgress = false;
this.update(results);
}
});
discoveryPromise.finally(() => {
if (this.retry) {
// Another refresh request came in while we were still running a previous discovery
// operation. Since the discovery results we just computed are now stale, we'll launch
// another discovery operation instead of updating.
// Note that by doing this inside of `finally`, we will relaunch discovery even if the
// initial discovery operation failed.
this.retry = false;
this.launchDiscovery();
}
});
})
.catch(err => {
void logger.log(`${this.name} failed. Reason: ${err.message}`);
})
.finally(() => {
if (this.retry) {
// Another refresh request came in while we were still running a previous discovery
// operation. Since the discovery results we just computed are now stale, we'll launch
// another discovery operation instead of updating.
// Note that by doing this inside of `finally`, we will relaunch discovery even if the
// initial discovery operation failed.
this.retry = false;
this.launchDiscovery();
}
});
}
/**

View File

@@ -7,10 +7,15 @@ import * as unzipper from 'unzipper';
import * as url from 'url';
import { ExtensionContext, Event } from 'vscode';
import { DistributionConfig } from './config';
import { InvocationRateLimiter, InvocationRateLimiterResultKind, showAndLogErrorMessage } from './helpers';
import {
InvocationRateLimiter,
InvocationRateLimiterResultKind,
showAndLogErrorMessage,
showAndLogWarningMessage
} from './helpers';
import { logger } from './logging';
import * as helpers from './helpers';
import { getCodeQlCliVersion } from './cli-version';
import { ProgressCallback, reportStreamProgress } from './commandRunner';
/**
* distribution.ts
@@ -45,19 +50,40 @@ export const DEFAULT_DISTRIBUTION_VERSION_RANGE: semver.Range = new semver.Range
export interface DistributionProvider {
getCodeQlPathWithoutVersionCheck(): Promise<string | undefined>;
onDidChangeDistribution?: Event<void>;
getDistribution(): Promise<FindDistributionResult>;
}
export class DistributionManager implements DistributionProvider {
constructor(extensionContext: ExtensionContext, config: DistributionConfig, versionRange: semver.Range) {
this._config = config;
this._extensionSpecificDistributionManager = new ExtensionSpecificDistributionManager(extensionContext, config, versionRange);
this._onDidChangeDistribution = config.onDidChangeDistributionConfiguration;
this._updateCheckRateLimiter = new InvocationRateLimiter(
/**
* Get the name of the codeql cli installation we prefer to install, based on our current platform.
*/
public static getRequiredAssetName(): string {
switch (os.platform()) {
case 'linux':
return 'codeql-linux64.zip';
case 'darwin':
return 'codeql-osx64.zip';
case 'win32':
return 'codeql-win64.zip';
default:
return 'codeql.zip';
}
}
constructor(
public readonly config: DistributionConfig,
private readonly versionRange: semver.Range,
extensionContext: ExtensionContext
) {
this._onDidChangeDistribution = config.onDidChangeConfiguration;
this.extensionSpecificDistributionManager =
new ExtensionSpecificDistributionManager(config, versionRange, extensionContext);
this.updateCheckRateLimiter = new InvocationRateLimiter(
extensionContext,
'extensionSpecificDistributionUpdateCheck',
() => this._extensionSpecificDistributionManager.checkForUpdatesToDistribution()
() => this.extensionSpecificDistributionManager.checkForUpdatesToDistribution()
);
this._versionRange = versionRange;
}
/**
@@ -94,9 +120,9 @@ export class DistributionManager implements DistributionProvider {
* - If the user is using an extension-managed CLI, then prereleases are only accepted when the
* includePrerelease config option is set.
*/
const includePrerelease = distribution.kind !== DistributionKind.ExtensionManaged || this._config.includePrerelease;
const includePrerelease = distribution.kind !== DistributionKind.ExtensionManaged || this.config.includePrerelease;
if (!semver.satisfies(version, this._versionRange, { includePrerelease })) {
if (!semver.satisfies(version, this.versionRange, { includePrerelease })) {
return {
distribution,
kind: FindDistributionResultKind.IncompatibleDistribution,
@@ -125,9 +151,9 @@ export class DistributionManager implements DistributionProvider {
*/
async getDistributionWithoutVersionCheck(): Promise<Distribution | undefined> {
// Check config setting, then extension specific distribution, then PATH.
if (this._config.customCodeQlPath) {
if (!await fs.pathExists(this._config.customCodeQlPath)) {
showAndLogErrorMessage(`The CodeQL executable path is specified as "${this._config.customCodeQlPath}" ` +
if (this.config.customCodeQlPath) {
if (!await fs.pathExists(this.config.customCodeQlPath)) {
void showAndLogErrorMessage(`The CodeQL executable path is specified as "${this.config.customCodeQlPath}" ` +
'by a configuration setting, but a CodeQL executable could not be found at that path. Please check ' +
'that a CodeQL executable exists at the specified path or remove the setting.');
return undefined;
@@ -136,18 +162,18 @@ export class DistributionManager implements DistributionProvider {
// emit a warning if using a deprecated launcher and a non-deprecated launcher exists
if (
deprecatedCodeQlLauncherName() &&
this._config.customCodeQlPath.endsWith(deprecatedCodeQlLauncherName()!) &&
this.config.customCodeQlPath.endsWith(deprecatedCodeQlLauncherName()!) &&
await this.hasNewLauncherName()
) {
warnDeprecatedLauncher();
}
return {
codeQlPath: this._config.customCodeQlPath,
codeQlPath: this.config.customCodeQlPath,
kind: DistributionKind.CustomPathConfig
};
}
const extensionSpecificCodeQlPath = await this._extensionSpecificDistributionManager.getCodeQlPathWithoutVersionCheck();
const extensionSpecificCodeQlPath = await this.extensionSpecificDistributionManager.getCodeQlPathWithoutVersionCheck();
if (extensionSpecificCodeQlPath !== undefined) {
return {
codeQlPath: extensionSpecificCodeQlPath,
@@ -165,7 +191,7 @@ export class DistributionManager implements DistributionProvider {
};
}
}
logger.log('INFO: Could not find CodeQL on path.');
void logger.log('INFO: Could not find CodeQL on path.');
}
return undefined;
@@ -180,12 +206,12 @@ export class DistributionManager implements DistributionProvider {
public async checkForUpdatesToExtensionManagedDistribution(
minSecondsSinceLastUpdateCheck: number): Promise<DistributionUpdateCheckResult> {
const distribution = await this.getDistributionWithoutVersionCheck();
const extensionManagedCodeQlPath = await this._extensionSpecificDistributionManager.getCodeQlPathWithoutVersionCheck();
const extensionManagedCodeQlPath = await this.extensionSpecificDistributionManager.getCodeQlPathWithoutVersionCheck();
if (distribution?.codeQlPath !== extensionManagedCodeQlPath) {
// A distribution is present but it isn't managed by the extension.
return createInvalidLocationResult();
}
const updateCheckResult = await this._updateCheckRateLimiter.invokeFunctionIfIntervalElapsed(minSecondsSinceLastUpdateCheck);
const updateCheckResult = await this.updateCheckRateLimiter.invokeFunctionIfIntervalElapsed(minSecondsSinceLastUpdateCheck);
switch (updateCheckResult.kind) {
case InvocationRateLimiterResultKind.Invoked:
return updateCheckResult.result;
@@ -199,9 +225,11 @@ export class DistributionManager implements DistributionProvider {
*
* Returns a failed promise if an unexpected error occurs during installation.
*/
public installExtensionManagedDistributionRelease(release: Release,
progressCallback?: helpers.ProgressCallback): Promise<void> {
return this._extensionSpecificDistributionManager.installDistributionRelease(release, progressCallback);
public installExtensionManagedDistributionRelease(
release: Release,
progressCallback?: ProgressCallback
): Promise<void> {
return this.extensionSpecificDistributionManager.installDistributionRelease(release, progressCallback);
}
public get onDidChangeDistribution(): Event<void> | undefined {
@@ -214,27 +242,27 @@ export class DistributionManager implements DistributionProvider {
* installation. False otherwise.
*/
private async hasNewLauncherName(): Promise<boolean> {
if (!this._config.customCodeQlPath) {
if (!this.config.customCodeQlPath) {
// not managed externally
return false;
}
const dir = path.dirname(this._config.customCodeQlPath);
const dir = path.dirname(this.config.customCodeQlPath);
const newLaunderPath = path.join(dir, codeQlLauncherName());
return await fs.pathExists(newLaunderPath);
}
private readonly _config: DistributionConfig;
private readonly _extensionSpecificDistributionManager: ExtensionSpecificDistributionManager;
private readonly _updateCheckRateLimiter: InvocationRateLimiter<DistributionUpdateCheckResult>;
private readonly extensionSpecificDistributionManager: ExtensionSpecificDistributionManager;
private readonly updateCheckRateLimiter: InvocationRateLimiter<DistributionUpdateCheckResult>;
private readonly _onDidChangeDistribution: Event<void> | undefined;
private readonly _versionRange: semver.Range;
}
class ExtensionSpecificDistributionManager {
constructor(extensionContext: ExtensionContext, config: DistributionConfig, versionRange: semver.Range) {
this._extensionContext = extensionContext;
this._config = config;
this._versionRange = versionRange;
constructor(
private readonly config: DistributionConfig,
private readonly versionRange: semver.Range,
private readonly extensionContext: ExtensionContext
) {
/**/
}
public async getCodeQlPathWithoutVersionCheck(): Promise<string | undefined> {
@@ -248,7 +276,7 @@ class ExtensionSpecificDistributionManager {
try {
await this.removeDistribution();
} catch (e) {
logger.log('WARNING: Tried to remove corrupted CodeQL CLI at ' +
void logger.log('WARNING: Tried to remove corrupted CodeQL CLI at ' +
`${this.getDistributionStoragePath()} but encountered an error: ${e}.`);
}
}
@@ -282,29 +310,29 @@ class ExtensionSpecificDistributionManager {
* Returns a failed promise if an unexpected error occurs during installation.
*/
public async installDistributionRelease(release: Release,
progressCallback?: helpers.ProgressCallback): Promise<void> {
progressCallback?: ProgressCallback): Promise<void> {
await this.downloadDistribution(release, progressCallback);
// Store the installed release within the global extension state.
this.storeInstalledRelease(release);
await this.storeInstalledRelease(release);
}
private async downloadDistribution(release: Release,
progressCallback?: helpers.ProgressCallback): Promise<void> {
progressCallback?: ProgressCallback): Promise<void> {
try {
await this.removeDistribution();
} catch (e) {
logger.log(`Tried to clean up old version of CLI at ${this.getDistributionStoragePath()} ` +
void logger.log(`Tried to clean up old version of CLI at ${this.getDistributionStoragePath()} ` +
`but encountered an error: ${e}.`);
}
// Filter assets to the unique one that we require.
const requiredAssetName = this.getRequiredAssetName();
const requiredAssetName = DistributionManager.getRequiredAssetName();
const assets = release.assets.filter(asset => asset.name === requiredAssetName);
if (assets.length === 0) {
throw new Error(`Invariant violation: chose a release to install that didn't have ${requiredAssetName}`);
}
if (assets.length > 1) {
logger.log('WARNING: chose a release with more than one asset to install, found ' +
void logger.log('WARNING: chose a release with more than one asset to install, found ' +
assets.map(asset => asset.name).join(', '));
}
@@ -316,27 +344,8 @@ class ExtensionSpecificDistributionManager {
const archiveFile = fs.createWriteStream(archivePath);
const contentLength = assetStream.headers.get('content-length');
let numBytesDownloaded = 0;
if (progressCallback && contentLength !== null) {
const totalNumBytes = parseInt(contentLength, 10);
const bytesToDisplayMB = (numBytes: number): string => `${(numBytes / (1024 * 1024)).toFixed(1)} MB`;
const updateProgress = (): void => {
progressCallback({
step: numBytesDownloaded,
maxStep: totalNumBytes,
message: `Downloading CodeQL CLI… [${bytesToDisplayMB(numBytesDownloaded)} of ${bytesToDisplayMB(totalNumBytes)}]`,
});
};
// Display the progress straight away rather than waiting for the first chunk.
updateProgress();
assetStream.body.on('data', data => {
numBytesDownloaded += data.length;
updateProgress();
});
}
const totalNumBytes = contentLength ? parseInt(contentLength, 10) : undefined;
reportStreamProgress(assetStream.body, `Downloading CodeQL CLI ${release.name}`, totalNumBytes, progressCallback);
await new Promise((resolve, reject) =>
assetStream.body.pipe(archiveFile)
@@ -346,7 +355,7 @@ class ExtensionSpecificDistributionManager {
await this.bumpDistributionFolderIndex();
logger.log(`Extracting CodeQL CLI to ${this.getDistributionStoragePath()}`);
void logger.log(`Extracting CodeQL CLI to ${this.getDistributionStoragePath()}`);
await extractZipArchive(archivePath, this.getDistributionStoragePath());
} finally {
await fs.remove(tmpDirectory);
@@ -359,37 +368,27 @@ class ExtensionSpecificDistributionManager {
* This should not be called for a distribution that is currently in use, as remove may fail.
*/
private async removeDistribution(): Promise<void> {
this.storeInstalledRelease(undefined);
await this.storeInstalledRelease(undefined);
if (await fs.pathExists(this.getDistributionStoragePath())) {
await fs.remove(this.getDistributionStoragePath());
}
}
/**
* Get the name of the codeql cli installation we prefer to install, based on our current platform.
*/
private getRequiredAssetName(): string {
if (os.platform() === 'linux') return 'codeql-linux64.zip';
if (os.platform() === 'darwin') return 'codeql-osx64.zip';
if (os.platform() === 'win32') return 'codeql-win64.zip';
return 'codeql.zip';
}
private async getLatestRelease(): Promise<Release> {
const requiredAssetName = this.getRequiredAssetName();
logger.log(`Searching for latest release including ${requiredAssetName}.`);
const requiredAssetName = DistributionManager.getRequiredAssetName();
void logger.log(`Searching for latest release including ${requiredAssetName}.`);
return this.createReleasesApiConsumer().getLatestRelease(
this._versionRange,
this._config.includePrerelease,
this.versionRange,
this.config.includePrerelease,
release => {
const matchingAssets = release.assets.filter(asset => asset.name === requiredAssetName);
if (matchingAssets.length === 0) {
// For example, this could be a release with no platform-specific assets.
logger.log(`INFO: Ignoring a release with no assets named ${requiredAssetName}`);
void logger.log(`INFO: Ignoring a release with no assets named ${requiredAssetName}`);
return false;
}
if (matchingAssets.length > 1) {
logger.log(`WARNING: Ignoring a release with more than one asset named ${requiredAssetName}`);
void logger.log(`WARNING: Ignoring a release with more than one asset named ${requiredAssetName}`);
return false;
}
return true;
@@ -398,23 +397,23 @@ class ExtensionSpecificDistributionManager {
}
private createReleasesApiConsumer(): ReleasesApiConsumer {
const ownerName = this._config.ownerName ? this._config.ownerName : DEFAULT_DISTRIBUTION_OWNER_NAME;
const repositoryName = this._config.repositoryName ? this._config.repositoryName : DEFAULT_DISTRIBUTION_REPOSITORY_NAME;
return new ReleasesApiConsumer(ownerName, repositoryName, this._config.personalAccessToken);
const ownerName = this.config.ownerName ? this.config.ownerName : DEFAULT_DISTRIBUTION_OWNER_NAME;
const repositoryName = this.config.repositoryName ? this.config.repositoryName : DEFAULT_DISTRIBUTION_REPOSITORY_NAME;
return new ReleasesApiConsumer(ownerName, repositoryName, this.config.personalAccessToken);
}
private async bumpDistributionFolderIndex(): Promise<void> {
const index = this._extensionContext.globalState.get(
const index = this.extensionContext.globalState.get(
ExtensionSpecificDistributionManager._currentDistributionFolderIndexStateKey, 0);
await this._extensionContext.globalState.update(
await this.extensionContext.globalState.update(
ExtensionSpecificDistributionManager._currentDistributionFolderIndexStateKey, index + 1);
}
private getDistributionStoragePath(): string {
// Use an empty string for the initial distribution for backwards compatibility.
const distributionFolderIndex = this._extensionContext.globalState.get(
const distributionFolderIndex = this.extensionContext.globalState.get(
ExtensionSpecificDistributionManager._currentDistributionFolderIndexStateKey, 0) || '';
return path.join(this._extensionContext.globalStoragePath,
return path.join(this.extensionContext.globalStoragePath,
ExtensionSpecificDistributionManager._currentDistributionFolderBaseName + distributionFolderIndex);
}
@@ -424,17 +423,13 @@ class ExtensionSpecificDistributionManager {
}
private getInstalledRelease(): Release | undefined {
return this._extensionContext.globalState.get(ExtensionSpecificDistributionManager._installedReleaseStateKey);
return this.extensionContext.globalState.get(ExtensionSpecificDistributionManager._installedReleaseStateKey);
}
private async storeInstalledRelease(release: Release | undefined): Promise<void> {
await this._extensionContext.globalState.update(ExtensionSpecificDistributionManager._installedReleaseStateKey, release);
await this.extensionContext.globalState.update(ExtensionSpecificDistributionManager._installedReleaseStateKey, release);
}
private readonly _config: DistributionConfig;
private readonly _extensionContext: ExtensionContext;
private readonly _versionRange: semver.Range;
private static readonly _currentDistributionFolderBaseName = 'distribution';
private static readonly _currentDistributionFolderIndexStateKey = 'distributionFolderIndex';
private static readonly _installedReleaseStateKey = 'distributionRelease';
@@ -575,7 +570,7 @@ export async function extractZipArchive(archivePath: string, outPath: string): P
}));
}
function codeQlLauncherName(): string {
export function codeQlLauncherName(): string {
return (os.platform() === 'win32') ? 'codeql.exe' : 'codeql';
}
@@ -712,14 +707,14 @@ export async function getExecutableFromDirectory(directory: string, warnWhenNotF
return alternateExpectedLauncherPath;
}
if (warnWhenNotFound) {
logger.log(`WARNING: Expected to find a CodeQL CLI executable at ${expectedLauncherPath} but one was not found. ` +
void logger.log(`WARNING: Expected to find a CodeQL CLI executable at ${expectedLauncherPath} but one was not found. ` +
'Will try PATH.');
}
return undefined;
}
function warnDeprecatedLauncher() {
helpers.showAndLogWarningMessage(
void showAndLogWarningMessage(
`The "${deprecatedCodeQlLauncherName()!}" launcher has been deprecated and will be removed in a future version. ` +
`Please use "${codeQlLauncherName()}" instead. It is recommended to update to the latest CodeQL binaries.`
);

File diff suppressed because it is too large Load Diff

View File

@@ -1,23 +0,0 @@
/**
* helpers-pure.ts
* ------------
*
* Helper functions that don't depend on vscode and therefore can be used by the front-end and pure unit tests.
*/
/**
* This error is used to indicate a runtime failure of an exhaustivity check enforced at compile time.
*/
class ExhaustivityCheckingError extends Error {
constructor(public expectedExhaustiveValue: never) {
super('Internal error: exhaustivity checking failure');
}
}
/**
* Used to perform compile-time exhaustivity checking on a value. This function will not be executed at runtime unless
* the type system has been subverted.
*/
export function assertNever(value: never): never {
throw new ExhaustivityCheckingError(value);
}

View File

@@ -2,52 +2,29 @@ import * as fs from 'fs-extra';
import * as glob from 'glob-promise';
import * as yaml from 'js-yaml';
import * as path from 'path';
import { CancellationToken, ExtensionContext, ProgressOptions, window as Window, workspace } from 'vscode';
import { CodeQLCliServer } from './cli';
import * as tmp from 'tmp-promise';
import {
ExtensionContext,
Uri,
window as Window,
workspace,
env
} from 'vscode';
import { CodeQLCliServer, QlpacksInfo } from './cli';
import { UserCancellationException } from './commandRunner';
import { logger } from './logging';
import { QueryInfo } from './run-queries';
import { QueryMetadata } from './pure/interface-types';
export interface ProgressUpdate {
/**
* The current step
*/
step: number;
/**
* The maximum step. This *should* be constant for a single job.
*/
maxStep: number;
/**
* The current progress message
*/
message: string;
}
// Shared temporary folder for the extension.
export const tmpDir = tmp.dirSync({ prefix: 'queries_', keep: false, unsafeCleanup: true });
export const upgradesTmpDir = path.join(tmpDir.name, 'upgrades');
fs.ensureDirSync(upgradesTmpDir);
export type ProgressCallback = (p: ProgressUpdate) => void;
/**
* This mediates between the kind of progress callbacks we want to
* write (where we *set* current progress position and give
* `maxSteps`) and the kind vscode progress api expects us to write
* (which increment progress by a certain amount out of 100%)
*/
export function withProgress<R>(
options: ProgressOptions,
task: (
progress: (p: ProgressUpdate) => void,
token: CancellationToken
) => Thenable<R>
): Thenable<R> {
let progressAchieved = 0;
return Window.withProgress(options,
(progress, token) => {
return task(p => {
const { message, step, maxStep } = p;
const increment = 100 * (step - progressAchieved) / maxStep;
progressAchieved = step;
progress.report({ message, increment });
}, token);
});
}
export const tmpDirDisposal = {
dispose: () => {
tmpDir.removeCallback();
}
};
/**
* Show an error message and log it to the console
@@ -55,15 +32,24 @@ export function withProgress<R>(
* @param message The message to show.
* @param options.outputLogger The output logger that will receive the message
* @param options.items A set of items that will be rendered as actions in the message.
* @param options.fullMessage An alternate message that is added to the log, but not displayed
* in the popup. This is useful for adding extra detail to the logs
* that would be too noisy for the popup.
*
* @return A promise that resolves to the selected item or undefined when being dismissed.
*/
export async function showAndLogErrorMessage(message: string, {
outputLogger = logger,
items = [] as string[]
items = [] as string[],
fullMessage = undefined as (string | undefined)
} = {}): Promise<string | undefined> {
return internalShowAndLog(message, items, outputLogger, Window.showErrorMessage);
return internalShowAndLog(dropLinesExceptInitial(message), items, outputLogger, Window.showErrorMessage, fullMessage);
}
function dropLinesExceptInitial(message: string, n = 2) {
return message.toString().split(/\r?\n/).slice(0, n).join('\n');
}
/**
* Show a warning message and log it to the console
*
@@ -90,17 +76,23 @@ export async function showAndLogWarningMessage(message: string, {
*/
export async function showAndLogInformationMessage(message: string, {
outputLogger = logger,
items = [] as string[]
items = [] as string[],
fullMessage = ''
} = {}): Promise<string | undefined> {
return internalShowAndLog(message, items, outputLogger, Window.showInformationMessage);
return internalShowAndLog(message, items, outputLogger, Window.showInformationMessage, fullMessage);
}
type ShowMessageFn = (message: string, ...items: string[]) => Thenable<string | undefined>;
async function internalShowAndLog(message: string, items: string[], outputLogger = logger,
fn: ShowMessageFn): Promise<string | undefined> {
async function internalShowAndLog(
message: string,
items: string[],
outputLogger = logger,
fn: ShowMessageFn,
fullMessage?: string
): Promise<string | undefined> {
const label = 'Show Log';
outputLogger.log(message);
void outputLogger.log(fullMessage || message);
const result = await fn(message, label, ...items);
if (result === label) {
outputLogger.show();
@@ -110,17 +102,61 @@ async function internalShowAndLog(message: string, items: string[], outputLogger
/**
* Opens a modal dialog for the user to make a yes/no choice.
* @param message The message to show.
*
* @return `true` if the user clicks 'Yes', `false` if the user clicks 'No' or cancels the dialog.
* @param message The message to show.
* @param modal If true (the default), show a modal dialog box, otherwise dialog is non-modal and can
* be closed even if the user does not make a choice.
*
* @return
* `true` if the user clicks 'Yes',
* `false` if the user clicks 'No' or cancels the dialog,
* `undefined` if the dialog is closed without the user making a choice.
*/
export async function showBinaryChoiceDialog(message: string): Promise<boolean> {
export async function showBinaryChoiceDialog(message: string, modal = true): Promise<boolean | undefined> {
const yesItem = { title: 'Yes', isCloseAffordance: false };
const noItem = { title: 'No', isCloseAffordance: true };
const chosenItem = await Window.showInformationMessage(message, { modal: true }, yesItem, noItem);
const chosenItem = await Window.showInformationMessage(message, { modal }, yesItem, noItem);
if (!chosenItem) {
return undefined;
}
return chosenItem?.title === yesItem.title;
}
/**
* Opens a modal dialog for the user to make a yes/no choice.
*
* @param message The message to show.
* @param modal If true (the default), show a modal dialog box, otherwise dialog is non-modal and can
* be closed even if the user does not make a choice.
*
* @return
* `true` if the user clicks 'Yes',
* `false` if the user clicks 'No' or cancels the dialog,
* `undefined` if the dialog is closed without the user making a choice.
*/
export async function showBinaryChoiceWithUrlDialog(message: string, url: string): Promise<boolean | undefined> {
const urlItem = { title: 'More Information', isCloseAffordance: false };
const yesItem = { title: 'Yes', isCloseAffordance: false };
const noItem = { title: 'No', isCloseAffordance: true };
let chosenItem;
// Keep the dialog open as long as the user is clicking the 'more information' option.
// To prevent an infinite loop, if the user clicks 'more information' 5 times, close the dialog and return cancelled
let count = 0;
do {
chosenItem = await Window.showInformationMessage(message, { modal: true }, urlItem, yesItem, noItem);
if (chosenItem === urlItem) {
await env.openExternal(Uri.parse(url, true));
}
count++;
} while (chosenItem === urlItem && count < 5);
if (!chosenItem || chosenItem.title === urlItem.title) {
return undefined;
}
return chosenItem.title === yesItem.title;
}
/**
* Show an information message with a customisable action.
* @param message The message to show.
@@ -145,24 +181,6 @@ export function getOnDiskWorkspaceFolders() {
return diskWorkspaceFolders;
}
/**
* Gets a human-readable name for an evaluated query.
* Uses metadata if it exists, and defaults to the query file name.
*/
export function getQueryName(query: QueryInfo) {
// Queries run through quick evaluation are not usually the entire query file.
// Label them differently and include the line numbers.
if (query.quickEvalPosition !== undefined) {
const { line, endLine, fileName } = query.quickEvalPosition;
const lineInfo = line === endLine ? `${line}` : `${line}-${endLine}`;
return `Quick evaluation of ${path.basename(fileName)}:${lineInfo}`;
} else if (query.metadata && query.metadata.name) {
return query.metadata.name;
} else {
return path.basename(query.program.queryPath);
}
}
/**
* Provides a utility method to invoke a function only if a minimum time interval has elapsed since
* the last invocation of that function.
@@ -251,40 +269,78 @@ function createRateLimitedResult(): RateLimitedResult {
};
}
export type DatasetFolderInfo = {
dbscheme: string;
qlpack: string;
export interface QlPacksForLanguage {
/** The name of the pack containing the dbscheme. */
dbschemePack: string;
/** `true` if `dbschemePack` is a library pack. */
dbschemePackIsLibraryPack: boolean;
/**
* The name of the corresponding standard query pack.
* Only defined if `dbschemePack` is a library pack.
*/
queryPack?: string;
}
export async function getQlPackForDbscheme(cliServer: CodeQLCliServer, dbschemePath: string): Promise<string> {
const qlpacks = await cliServer.resolveQlpacks(getOnDiskWorkspaceFolders());
const packs: { packDir: string | undefined; packName: string }[] =
Object.entries(qlpacks).map(([packName, dirs]) => {
if (dirs.length < 1) {
logger.log(`In getQlPackFor ${dbschemePath}, qlpack ${packName} has no directories`);
return { packName, packDir: undefined };
}
if (dirs.length > 1) {
logger.log(`In getQlPackFor ${dbschemePath}, qlpack ${packName} has more than one directory; arbitrarily choosing the first`);
}
return {
packName,
packDir: dirs[0]
};
});
interface QlPackWithPath {
packName: string;
packDir: string | undefined;
}
async function findDbschemePack(packs: QlPackWithPath[], dbschemePath: string): Promise<{ name: string; isLibraryPack: boolean; }> {
for (const { packDir, packName } of packs) {
if (packDir !== undefined) {
const qlpack = yaml.safeLoad(await fs.readFile(path.join(packDir, 'qlpack.yml'), 'utf8'));
const qlpack = yaml.safeLoad(await fs.readFile(path.join(packDir, 'qlpack.yml'), 'utf8')) as { dbscheme?: string; library?: boolean; };
if (qlpack.dbscheme !== undefined && path.basename(qlpack.dbscheme) === path.basename(dbschemePath)) {
return packName;
return {
name: packName,
isLibraryPack: qlpack.library === true
};
}
}
}
throw new Error(`Could not find qlpack file for dbscheme ${dbschemePath}`);
}
export async function resolveDatasetFolder(cliServer: CodeQLCliServer, datasetFolder: string): Promise<DatasetFolderInfo> {
function findStandardQueryPack(qlpacks: QlpacksInfo, dbschemePackName: string): string | undefined {
const matches = dbschemePackName.match(/^codeql\/(?<language>[a-z]+)-all$/);
if (matches) {
const queryPackName = `codeql/${matches.groups!.language}-queries`;
if (qlpacks[queryPackName] !== undefined) {
return queryPackName;
}
}
// Either the dbscheme pack didn't look like one where the queries might be in the query pack, or
// no query pack was found in the search path. Either is OK.
return undefined;
}
export async function getQlPackForDbscheme(cliServer: CodeQLCliServer, dbschemePath: string): Promise<QlPacksForLanguage> {
const qlpacks = await cliServer.resolveQlpacks(getOnDiskWorkspaceFolders());
const packs: QlPackWithPath[] =
Object.entries(qlpacks).map(([packName, dirs]) => {
if (dirs.length < 1) {
void logger.log(`In getQlPackFor ${dbschemePath}, qlpack ${packName} has no directories`);
return { packName, packDir: undefined };
}
if (dirs.length > 1) {
void logger.log(`In getQlPackFor ${dbschemePath}, qlpack ${packName} has more than one directory; arbitrarily choosing the first`);
}
return {
packName,
packDir: dirs[0]
};
});
const dbschemePack = await findDbschemePack(packs, dbschemePath);
const queryPack = dbschemePack.isLibraryPack ? findStandardQueryPack(qlpacks, dbschemePack.name) : undefined;
return {
dbschemePack: dbschemePack.name,
dbschemePackIsLibraryPack: dbschemePack.isLibraryPack,
queryPack
};
}
export async function getPrimaryDbscheme(datasetFolder: string): Promise<string> {
const dbschemes = await glob(path.join(datasetFolder, '*.dbscheme'));
if (dbschemes.length < 1) {
@@ -293,31 +349,30 @@ export async function resolveDatasetFolder(cliServer: CodeQLCliServer, datasetFo
dbschemes.sort();
const dbscheme = dbschemes[0];
if (dbschemes.length > 1) {
Window.showErrorMessage(`Found multiple dbschemes in ${datasetFolder} during quick query; arbitrarily choosing the first, ${dbscheme}, to decide what library to use.`);
}
const qlpack = await getQlPackForDbscheme(cliServer, dbscheme);
return { dbscheme, qlpack };
if (dbschemes.length > 1) {
void Window.showErrorMessage(`Found multiple dbschemes in ${datasetFolder} during quick query; arbitrarily choosing the first, ${dbscheme}, to decide what library to use.`);
}
return dbscheme;
}
/**
* A cached mapping from strings to value of type U.
*/
export class CachedOperation<U> {
private readonly operation: (t: string) => Promise<U>;
private readonly operation: (t: string, ...args: any[]) => Promise<U>;
private readonly cached: Map<string, U>;
private readonly lru: string[];
private readonly inProgressCallbacks: Map<string, [(u: U) => void, (reason?: any) => void][]>;
constructor(operation: (t: string) => Promise<U>, private cacheSize = 100) {
constructor(operation: (t: string, ...args: any[]) => Promise<U>, private cacheSize = 100) {
this.operation = operation;
this.lru = [];
this.inProgressCallbacks = new Map<string, [(u: U) => void, (reason?: any) => void][]>();
this.cached = new Map<string, U>();
}
async get(t: string): Promise<U> {
async get(t: string, ...args: any[]): Promise<U> {
// Try and retrieve from the cache
const fromCache = this.cached.get(t);
if (fromCache !== undefined) {
@@ -338,7 +393,7 @@ export class CachedOperation<U> {
const callbacks: [(u: U) => void, (reason?: any) => void][] = [];
this.inProgressCallbacks.set(t, callbacks);
try {
const result = await this.operation(t);
const result = await this.operation(t, ...args);
callbacks.forEach(f => f[0](result));
this.inProgressCallbacks.delete(t);
if (this.lru.length > this.cacheSize) {
@@ -357,3 +412,172 @@ export class CachedOperation<U> {
}
}
}
/**
* The following functions al heuristically determine metadata about databases.
*/
/**
* Note that this heuristic is only being used for backwards compatibility with
* CLI versions before the langauge name was introduced to dbInfo. Features
* that do not require backwards compatibility should call
* `cli.CodeQLCliServer.resolveDatabase` and use the first entry in the
* `languages` property.
*
* @see cli.CliVersionConstraint.supportsLanguageName
* @see cli.CodeQLCliServer.resolveDatabase
*/
export const dbSchemeToLanguage = {
'semmlecode.javascript.dbscheme': 'javascript',
'semmlecode.cpp.dbscheme': 'cpp',
'semmlecode.dbscheme': 'java',
'semmlecode.python.dbscheme': 'python',
'semmlecode.csharp.dbscheme': 'csharp',
'go.dbscheme': 'go',
'ruby.dbscheme': 'ruby'
};
export const languageToDbScheme = Object.entries(dbSchemeToLanguage).reduce((acc, [k, v]) => {
acc[v] = k;
return acc;
}, {} as { [k: string]: string });
/**
* Returns the initial contents for an empty query, based on the language of the selected
* databse.
*
* First try to use the given language name. If that doesn't exist, try to infer it based on
* dbscheme. Otherwise return no import statement.
*
* @param language the database language or empty string if unknown
* @param dbscheme path to the dbscheme file
*
* @returns an import and empty select statement appropriate for the selected language
*/
export function getInitialQueryContents(language: string, dbscheme: string) {
if (!language) {
const dbschemeBase = path.basename(dbscheme) as keyof typeof dbSchemeToLanguage;
language = dbSchemeToLanguage[dbschemeBase];
}
return language
? `import ${language}\n\nselect ""`
: 'select ""';
}
/**
* Heuristically determines if the directory passed in corresponds
* to a database root.
*
* @param maybeRoot
*/
export async function isLikelyDatabaseRoot(maybeRoot: string) {
const [a, b, c] = (await Promise.all([
// databases can have either .dbinfo or codeql-database.yml.
fs.pathExists(path.join(maybeRoot, '.dbinfo')),
fs.pathExists(path.join(maybeRoot, 'codeql-database.yml')),
// they *must* have a db-{language} folder
glob('db-*/', { cwd: maybeRoot })
]));
return !!((a || b) && c);
}
export function isLikelyDbLanguageFolder(dbPath: string) {
return !!path.basename(dbPath).startsWith('db-');
}
/**
* Finds the language that a query targets.
* If it can't be autodetected, prompt the user to specify the language manually.
*/
export async function findLanguage(
cliServer: CodeQLCliServer,
queryUri: Uri | undefined
): Promise<string | undefined> {
const uri = queryUri || Window.activeTextEditor?.document.uri;
if (uri !== undefined) {
try {
const queryInfo = await cliServer.resolveQueryByLanguage(getOnDiskWorkspaceFolders(), uri);
const language = (Object.keys(queryInfo.byLanguage))[0];
void logger.log(`Detected query language: ${language}`);
return language;
} catch (e) {
void logger.log('Could not autodetect query language. Select language manually.');
}
}
// will be undefined if user cancels the quick pick.
return await askForLanguage(cliServer, false);
}
export async function askForLanguage(cliServer: CodeQLCliServer, throwOnEmpty = true): Promise<string | undefined> {
const language = await Window.showQuickPick(
await cliServer.getSupportedLanguages(),
{ placeHolder: 'Select target language for your query', ignoreFocusOut: true }
);
if (!language) {
// This only happens if the user cancels the quick pick.
if (throwOnEmpty) {
throw new UserCancellationException('Cancelled.');
} else {
void showAndLogErrorMessage('Language not found. Language must be specified manually.');
}
}
return language;
}
/**
* Gets metadata for a query, if it exists.
* @param cliServer The CLI server.
* @param queryPath The path to the query.
* @returns A promise that resolves to the query metadata, if available.
*/
export async function tryGetQueryMetadata(cliServer: CodeQLCliServer, queryPath: string): Promise<QueryMetadata | undefined> {
try {
return await cliServer.resolveMetadata(queryPath);
} catch (e) {
// Ignore errors and provide no metadata.
void logger.log(`Couldn't resolve metadata for ${queryPath}: ${e}`);
return;
}
}
/**
* Creates a file in the query directory that indicates when this query was created.
* This is important for keeping track of when queries should be removed.
*
* @param queryPath The directory that will containt all files relevant to a query result.
* It does not need to exist.
*/
export async function createTimestampFile(storagePath: string) {
const timestampPath = path.join(storagePath, 'timestamp');
await fs.ensureDir(storagePath);
await fs.writeFile(timestampPath, Date.now().toString(), 'utf8');
}
/**
* Recursively walk a directory and return the full path to all files found.
* Symbolic links are ignored.
*
* @param dir the directory to walk
*
* @return An iterator of the full path to all files recursively found in the directory.
*/
export async function* walkDirectory(dir: string): AsyncIterableIterator<string> {
const seenFiles = new Set<string>();
for await (const d of await fs.opendir(dir)) {
const entry = path.join(dir, d.name);
seenFiles.add(entry);
if (d.isDirectory()) {
yield* walkDirectory(entry);
} else if (d.isFile()) {
yield entry;
}
}
}

View File

@@ -0,0 +1,82 @@
import { env } from 'vscode';
import * as path from 'path';
import { QueryHistoryConfig } from './config';
import { LocalQueryInfo, QueryHistoryInfo } from './query-results';
import { RemoteQueryHistoryItem } from './remote-queries/remote-query-history-item';
interface InterpolateReplacements {
t: string; // Start time
q: string; // Query name
d: string; // Database/Controller repo name
r: string; // Result count/Empty
s: string; // Status
f: string; // Query file name
'%': '%'; // Percent sign
}
export class HistoryItemLabelProvider {
constructor(private config: QueryHistoryConfig) {
/**/
}
getLabel(item: QueryHistoryInfo) {
const replacements = item.t === 'local'
? this.getLocalInterpolateReplacements(item)
: this.getRemoteInterpolateReplacements(item);
const rawLabel = item.userSpecifiedLabel ?? (this.config.format || '%q');
return this.interpolate(rawLabel, replacements);
}
/**
* If there is a user-specified label for this query, interpolate and use that.
* Otherwise, use the raw name of this query.
*
* @returns the name of the query, unless there is a custom label for this query.
*/
getShortLabel(item: QueryHistoryInfo): string {
return item.userSpecifiedLabel
? this.getLabel(item)
: item.t === 'local'
? item.getQueryName()
: item.remoteQuery.queryName;
}
private interpolate(rawLabel: string, replacements: InterpolateReplacements): string {
return rawLabel.replace(/%(.)/g, (match, key: keyof InterpolateReplacements) => {
const replacement = replacements[key];
return replacement !== undefined ? replacement : match;
});
}
private getLocalInterpolateReplacements(item: LocalQueryInfo): InterpolateReplacements {
const { resultCount = 0, statusString = 'in progress' } = item.completedQuery || {};
return {
t: item.startTime,
q: item.getQueryName(),
d: item.initialInfo.databaseInfo.name,
r: `${resultCount} results`,
s: statusString,
f: item.getQueryFileName(),
'%': '%',
};
}
private getRemoteInterpolateReplacements(item: RemoteQueryHistoryItem): InterpolateReplacements {
return {
t: new Date(item.remoteQuery.executionStartTime).toLocaleString(env.language),
q: item.remoteQuery.queryName,
// There is no database name for remote queries. Instead use the controller repository name.
d: `${item.remoteQuery.controllerRepository.owner}/${item.remoteQuery.controllerRepository.name}`,
// There is no synchronous way to get the results count.
r: '',
s: item.status,
f: path.basename(item.remoteQuery.queryFilePath),
'%': '%'
};
}
}

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