Compare commits

..

1006 Commits

Author SHA1 Message Date
Nora
9ed6b011a5 Merge pull request #2662 from github/v1.8.9
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
Release prep for v1.8.9
2023-08-03 10:52:15 +02:00
Nora
912254fd3c Update extensions/ql-vscode/CHANGELOG.md
Co-authored-by: Charis Kyriakou <charisk@users.noreply.github.com>
2023-08-03 10:31:41 +02:00
Nora
7eab911cc5 v1.8.9 2023-08-03 08:17:20 +00:00
Nora
80ae9a4b36 Merge pull request #2658 from github/nora-koen/data-extensions-editor-without-ql-submodule
Remove submodules dependency from data extension editor
2023-08-02 17:30:46 +02:00
Nora
868fae093d Reorder db language check 2023-08-02 14:25:39 +00:00
Andrew Eisenberg
1289ab509c Merge pull request #2659 from github/aeisenberg/download-pack-in-tests2
Install `java-all` and transitive dependencies
2023-08-01 07:43:40 -07:00
Nora
5f489212d4 Add test for setup 2023-08-01 12:39:30 +00:00
Nora
fea45ea04d wrap all describe blocks in external api usage test 2023-08-01 12:39:30 +00:00
Nora
a39e55590a Move query setup to query file 2023-08-01 12:39:30 +00:00
Nora
6e4641f2c1 Clean up runQyery test 2023-08-01 12:39:30 +00:00
Nora
553e5cb4a1 Remove automodel qll file 2023-08-01 12:39:29 +00:00
Nora
4c0f68f193 Adjust picker test 2023-08-01 12:39:29 +00:00
Nora
1ee9cdaadd Add test for error log 2023-08-01 12:39:29 +00:00
Nora
098437b463 Cleanup 2023-08-01 12:39:29 +00:00
Nora
558a70e3c8 Adjust external api query test 2023-08-01 12:39:29 +00:00
Nora
7c10447bb5 Add .github folder manually 2023-08-01 12:39:29 +00:00
Nora
9fd6cb8c1f Cleanup and install pack dependencies 2023-08-01 12:39:29 +00:00
Koen Vlaswinkel
f4da522953 wip: data extensions editor without ql submodule 2023-08-01 12:39:29 +00:00
Robert
6dfe1736f8 Merge pull request #2657 from github/robertbrignull/clean-test-dir
Add `npm run clean-test-dir`
2023-08-01 09:19:42 +01:00
Andrew Eisenberg
b46e0ab175 Install java-all and transitive dependencies
need to install all transitive dependencies of `java-all` as well. This
will do it.
2023-07-31 11:14:59 -07:00
Andrew Eisenberg
34fa629054 Merge pull request #2655 from github/aeisenberg/download-pack-in-tests
Download `codeql/java-all` in tests
2023-07-31 10:02:14 -07:00
Robert
5107086a93 Switch to using find 2023-07-31 11:09:31 +01:00
Robert
58c5c0e5f5 Add npm run clean-test-dir 2023-07-31 11:09:31 +01:00
Charis Kyriakou
5427b5718f Only show automodel button for Java (#2656) 2023-07-31 09:43:07 +00:00
Andrew Eisenberg
0cc399507f Download codeql/java-all in tests
An upcoming change in the CLI will require that the extensible
predicates that are targeted by a data extension needs to be available
in order for the `resolve extensions` command to succeed.

There are a handful of tests that are failing with this new CLI. This
change will update the tests so that the `codeql/java-all` pack is
available in the tests and ensures they pass.
2023-07-28 14:49:55 -07:00
Robert
bb9299e0e2 Merge pull request #2646 from github/robertbrignull/fix_alert_461
Split codeQL.copyVariantAnalysisRepoList into two commands
2023-07-28 10:56:35 +01:00
Robert
e8afa54584 Fix test by mocking the correct function 2023-07-28 10:26:52 +01:00
Robert
d94443e025 Merge pull request #2652 from github/robertbrignull/data_narrow
Make the data extensions editor look a little bit better at small screen sizes
2023-07-28 10:15:28 +01:00
Robert
0e5cb1a3e8 Merge pull request #2653 from github/robertbrignull/dependencies_versions
Change all dependencies to use ^ instead of ~
2023-07-28 10:09:57 +01:00
Robert
59958a5b32 Log a ui-interaction telemetry event when copying repository lists 2023-07-28 10:09:12 +01:00
Robert
3d9b2da514 Remove codeQL.copyVariantAnalysisRepoListView command and instead call copyRepoListToClipboard directly 2023-07-28 10:09:11 +01:00
Robert
3b8cea8df4 Remove codeQL.copyVariantAnalysisRepoListQueryHistory command and instead call copyRepoListToClipboard directly 2023-07-28 10:00:38 +01:00
Robert
6adf683c87 Merge branch 'main' into robertbrignull/dependencies_versions 2023-07-28 09:51:43 +01:00
Robert
37f1c62ee6 Merge branch 'main' into robertbrignull/data_narrow 2023-07-28 09:51:27 +01:00
Chuan-kai Lin
c1107d7423 Merge pull request #2649 from github/cklin/remove-legacy-query-server-test
legacy-query.test.ts: skip if CLI supports new query server
2023-07-27 09:48:36 -07:00
Chuan-kai Lin
72fa1c5583 legacy-query.test.ts: skip if CLI supports new query server 2023-07-27 09:10:04 -07:00
github-actions[bot]
5f65498e0a Bump CLI version from v2.14.0 to v2.14.1 for integration tests (#2650)
Co-authored-by: github-actions[bot] <github-actions@github.com>
2023-07-27 16:04:05 +00:00
Shati Patel
6e21706c15 Implement "Hide modeled APIs" checkbox and make it the default (#2651) 2023-07-27 15:49:41 +00:00
Robert
4dcca4e97c Change all dependencies to use ^ instead of ~ 2023-07-27 16:15:39 +01:00
Robert
84492d2fb9 Make sure the classifications don't wrap 2023-07-27 16:00:38 +01:00
Robert
a2c9ac792b Move the method classification to the start of the row 2023-07-27 15:57:45 +01:00
Robert
18704558d3 Make the method name column 50% 2023-07-27 15:57:34 +01:00
Robert
ca16dca7ed Merge pull request #2645 from github/robertbrignull/fix_alert_546
Don't alert for multiple usages of built-in VS Code commands
2023-07-27 15:20:39 +01:00
Robert
f05d5d9766 Split codeQL.copyVariantAnalysisRepoList into two commands 2023-07-27 12:22:19 +01:00
Robert
aacc243bae Don't report multiply usages of builtin VS Code commands 2023-07-27 11:24:18 +01:00
Robert
396dc3e915 Merge pull request #2644 from github/robertbrignull/fix_alert_384
Fix alert by rewriting query history scrubbed to do fewer file operations
2023-07-27 11:22:10 +01:00
Robert
d3b2d0fce8 Fix indentation in query 2023-07-27 11:14:14 +01:00
Robert
4d4cd4c2d6 Use getErrorMessage 2023-07-27 10:32:19 +01:00
Shati Patel
72512da3b5 Data extensions editor: Allow users to pick an existing database from their workspace (#2643) 2023-07-27 10:09:12 +01:00
Koen Vlaswinkel
c2ed98eb85 Merge pull request #2633 from github/koesie10/automodel-v2
Add LLM functionality using auto-model V2
2023-07-27 10:02:55 +02:00
Koen Vlaswinkel
bebe130fb0 Do not use mocked URI in locations test 2023-07-27 09:40:37 +02:00
Koen Vlaswinkel
db065584fa Merge remote-tracking branch 'origin/main' into koesie10/automodel-v2 2023-07-27 09:18:59 +02:00
Robert
844f25ed98 Rewrite query history scrubbed to do fewer file operations 2023-07-26 16:56:02 +01:00
Koen Vlaswinkel
546f668301 Move createMockUri to mocking helpers 2023-07-26 14:35:15 +02:00
Koen Vlaswinkel
a79753d0a5 Move all runAutoModelQuery arguments into the options object 2023-07-26 14:32:43 +02:00
Koen Vlaswinkel
32c44cdfe3 Rename Options to AutoModelQueriesOptions 2023-07-26 14:31:28 +02:00
Koen Vlaswinkel
de5dbea69f Use promisify for gzip 2023-07-26 14:28:45 +02:00
Robert
3f896751f3 Merge pull request #2640 from github/robertbrignull/fix_alert_547
Fix alert by replacing regex with path.basename
2023-07-26 11:18:40 +01:00
Robert
41f5beb619 Merge pull request #2638 from github/robertbrignull/data_new_header
Add new data extensions header UI elements
2023-07-26 11:12:25 +01:00
Koen Vlaswinkel
5e5535653b Merge pull request #2642 from github/koesie10/remove-path-browserify
Remove path-browserify
2023-07-26 12:09:47 +02:00
Robert
af50d90bcb Merge branch 'main' into robertbrignull/data_new_header 2023-07-26 10:29:22 +01:00
Robert
c5a4c53a1a Merge branch 'main' into robertbrignull/fix_alert_547 2023-07-26 10:26:24 +01:00
Koen Vlaswinkel
016940f2ce Remove path-browserify 2023-07-26 11:23:39 +02:00
Robert
e877695a14 Merge pull request #2641 from github/robertbrignull/LockFileForStandardQueryResult
Unexport LockFileForStandardQueryResult
2023-07-26 10:22:53 +01:00
Robert
e2256e28ba Unexport LockFileForStandardQueryResult 2023-07-26 10:06:55 +01:00
Robert
5c08083336 Merge pull request #2639 from github/robertbrignull/data_progress
Remove custom progress bar and use normal VS Code notification for progress
2023-07-26 10:05:05 +01:00
Robert
07b8732a31 Use custom implementation of basename instead of path-browserify version 2023-07-26 09:59:02 +01:00
Robert
3e49d05ef9 Text is uppercased automatically by styling 2023-07-26 09:51:51 +01:00
Koen Vlaswinkel
83cc9835e8 Merge pull request #2634 from github/koesie10/cleanup-query-resolver
Make query resolver more generic
2023-07-26 09:36:32 +02:00
Robert
c5af8bdcd7 Replace regex with path.basename 2023-07-25 17:29:34 +01:00
Robert
55b21c2add Remove custom progress bar and use normal VS Code notification for progress 2023-07-25 15:33:39 +01:00
Charis Kyriakou
b87fe94a92 Remove most recent commit information and sorting (#2637) 2023-07-25 14:15:08 +00:00
Robert
493de4c190 Add new header UI elements 2023-07-25 15:01:27 +01:00
Shati Patel
8f99ed2478 Data extensions editor: Change "already modeled" message (#2636) 2023-07-25 13:40:54 +00:00
Shati Patel
cdcbdc60fb Data extensions editor: Remove buttons that are no longer needed (#2635) 2023-07-25 14:12:16 +01:00
Robert
e1bbbd6e9c Merge pull request #2631 from github/robertbrignull/deadcode_ci
Add check for deadcode for CI
2023-07-25 13:09:44 +01:00
Koen Vlaswinkel
84de8ad252 Add creation of auto-model request V2 2023-07-25 10:35:19 +02:00
Koen Vlaswinkel
57bcfbbe29 Extract creation of lock file to more generic function 2023-07-25 10:03:01 +02:00
Koen Vlaswinkel
32656c1cb8 Extract query resolving to more generic functions 2023-07-25 10:03:01 +02:00
Robert
5572cece83 Convert find-deadcode to a script 2023-07-24 18:00:30 +01:00
Robert
08675e6713 Rename to tsconfig.deadcode.json 2023-07-24 17:27:39 +01:00
Robert
abee109dbd Merge branch 'main' into robertbrignull/deadcode_ci 2023-07-24 17:26:18 +01:00
Robert
ef27730e5e Merge pull request #2632 from github/robertbrignull/deadcode_changes
Remove or fix dead code / unused exports
2023-07-24 16:32:13 +01:00
Robert
10c6708db5 Fix reference to tsconfig.json 2023-07-24 14:29:01 +01:00
Robert
a618aed415 Mark fileMock and styleMock as allowable exports 2023-07-24 14:28:41 +01:00
Robert
8e8e0faa9e Unexport types that are unused outside of their source file 2023-07-24 14:22:23 +01:00
Robert
41ce5086e7 Mark the extension activation function as allowed to be exported but unused 2023-07-24 14:22:23 +01:00
Robert
a79b71cff6 Switch ALLOW_HTTP_SETTING for allowHttp() 2023-07-24 14:22:23 +01:00
Robert
f0318b0c84 Delete vsCodeGetConfiguration 2023-07-24 14:22:23 +01:00
Robert
814acfa74a Add find-deadcode to CI linting workflow 2023-07-24 11:23:04 +01:00
Robert
d73276c136 Add find-deadcode npm script 2023-07-24 11:23:01 +01:00
Robert
44b58280e8 Merge pull request #2628 from github/robertbrignull/disposable
Merge definitions of Disposable where possible
2023-07-24 11:20:39 +01:00
Robert
49a05c412c Delete pathRowClassName 2023-07-24 11:11:55 +01:00
Robert
f57bbc2b52 Delete decimalFormatter 2023-07-24 11:11:55 +01:00
Robert
e620120144 Delete getTestDirectory 2023-07-24 11:11:55 +01:00
Robert
6fbe95a334 Delete isRemoteSystemDefinedListDbItem 2023-07-24 11:11:55 +01:00
Robert
cb4dcc81ea Delete remoteDbKinds and localDbKinds 2023-07-24 11:11:55 +01:00
Robert
3126c8d1a8 Delete PAGE_SIZE 2023-07-24 11:11:55 +01:00
Robert
0d7814c778 Delete InspectionResult 2023-07-24 11:11:55 +01:00
Robert
f70ea71885 Delete isVariantAnalysisLiveResultsEnabled 2023-07-24 11:11:55 +01:00
Robert
04df20a732 Install ts-unused-exports 2023-07-24 11:10:19 +01:00
Robert
c7b556e748 Merge pull request #2624 from github/robertbrignull/autoClosingPairs
Delete autoClosingPairs from LanguageConfiguration to appease proposed API
2023-07-24 11:04:52 +01:00
Charis Kyriakou
8314a5486d Merge pull request #2627 from github/charisk/remove-deprecated-version-support
Remove conditionals and version constraints for unsupported CLI versions
2023-07-24 10:07:34 +01:00
Charis Kyriakou
e80ef7c1dc Remove CLI_VERSION_WITH_PER_QUERY_EVAL_LOG constraint 2023-07-24 08:24:07 +00:00
Robert
f1a928994a Merge all our DisposableObject definitions 2023-07-21 17:06:53 +01:00
Charis Kyriakou
0f594704d5 Remove CLI_VERSION_WITH_STRUCTURED_EVAL_LOG constraint 2023-07-21 15:37:56 +00:00
Charis Kyriakou
3064415068 Remove setting of evaluator log verbosity level 2023-07-21 15:33:07 +00:00
Charis Kyriakou
f03ef66596 Update handling of return value from packlist command 2023-07-21 15:31:57 +00:00
Robert
0617e3ec7f Merge pull request #2626 from github/robertbrignull/data-make-selected
Instead of resetting the database after importing, pass through makeSelected = false
2023-07-21 16:20:37 +01:00
Shati Patel
dacaf4e394 Update title in Data extensions editor tab (#2625) 2023-07-21 14:44:41 +01:00
Robert
e6566b910a Instead of resetting the database after importing, pass through makeSelected = false 2023-07-21 12:49:36 +01:00
Robert
778f839e8e Merge pull request #2623 from github/robertbrignull/data-model-dependency
Implement "model dependency" button in application mode
2023-07-21 12:10:15 +01:00
Robert
52711c5cc1 Delete autoClosingPairs from LanguageConfiguration to appease proposed API 2023-07-21 11:31:55 +01:00
Robert
d8687b5985 Merge pull request #2621 from github/robertbrignull/data-saving
Load existing modeled methods before saving, to avoid overwriting data
2023-07-20 08:54:29 +01:00
Robert
19ad237427 Pull out common code for importing and resetting the current database 2023-07-19 16:29:13 +01:00
Robert
bb246144c2 Add comments to createDataExtensionYamlsForFrameworkMode too 2023-07-19 16:22:00 +01:00
Robert
fa01b33dfa Implement modelDependency message 2023-07-19 16:14:44 +01:00
Robert
00780442dd Send modelDependency message 2023-07-19 16:14:44 +01:00
Robert
5b170d02eb Avoiding overwriting any existing modeled methods from the files 2023-07-19 11:44:12 +01:00
Robert
db4dc89e42 Split loadModeledMethods into loading all files individually and then merging them 2023-07-19 11:44:12 +01:00
Robert
b5b606d486 Make loadModeledMethodFiles return relative paths from the extension pack 2023-07-19 11:43:57 +01:00
Robert
f2c7c41117 Merge pull request #2406 from Marcono1234/location-url-column
Include column numbers in location URLs
2023-07-19 11:01:20 +01:00
Robert
152e194655 Merge branch 'main' into location-url-column 2023-07-19 09:58:46 +01:00
Robert
f12ba96389 Update CHANGELOG.md 2023-07-19 09:57:58 +01:00
Koen Vlaswinkel
add3296071 Merge pull request #2618 from github/dependabot/npm_and_yarn/extensions/ql-vscode/word-wrap-1.2.4
Bump word-wrap from 1.2.3 to 1.2.4 in /extensions/ql-vscode
2023-07-19 10:04:56 +02:00
Koen Vlaswinkel
a90b85c2a6 Merge pull request #2259 from github/koesie10/upgrade-storybook-7
Upgrade to Storybook 7
2023-07-19 09:51:13 +02:00
dependabot[bot]
3568d4a780 Bump word-wrap from 1.2.3 to 1.2.4 in /extensions/ql-vscode
Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
- [Commits](https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4)

---
updated-dependencies:
- dependency-name: word-wrap
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-18 23:40:55 +00:00
Robert
d3a5a5e669 Merge pull request #2611 from github/robertbrignull/data-unsaved-checkbox
Show whether changes to a method are saved or not
2023-07-18 16:31:46 +01:00
Robert
fc77a52c46 Merge pull request #2614 from github/robertbrignull/Locations
Move components for rendering locations to a separate file
2023-07-18 15:31:15 +01:00
Robert
5617331598 Pass in methodIsUnsaved instead of modifiedSignatures 2023-07-18 15:26:34 +01:00
Robert
76a7a266ff Rename jumpToLocationHandler => handleClick 2023-07-18 15:11:54 +01:00
Robert
b6c60b26cd Rename handleClick => onClick 2023-07-18 15:11:22 +01:00
Robert
30d8303320 Pull out getModelingStatus method and avoid useMemo 2023-07-18 15:07:26 +01:00
Robert
5c12a4b205 Merge pull request #2605 from github/robertbrignull/data-modeled-methods-tests
Refactor the code for loading/saving modeled methods to disk, and add tests
2023-07-18 14:34:21 +01:00
Koen Vlaswinkel
b830781e48 Replace deprecated uses of ComponentMeta and ComponentStory 2023-07-18 15:29:11 +02:00
Koen Vlaswinkel
8329dedd7f Upgrade to Storybook 7 2023-07-18 15:07:15 +02:00
Robert
70e04a1c99 Rename to MdelingStatusIndicator and move to a separate file 2023-07-18 10:59:08 +01:00
Marcono1234
768b95d3a9 Fix typo in CHANGELOG.md (#2617) 2023-07-17 19:39:38 +00:00
Shati Patel
8e4ee5df3d Update release test plan (#2616) 2023-07-17 19:05:25 +01:00
Alexander Eyers-Taylor
baa2a7fed3 Add comma as a word boundary charecter. (#2615)
* Add comma as a word boundary charecter.

* Add changelog for missing trailing commas.
2023-07-17 16:12:36 +00:00
Robert
1f16294d7e Avoid else blocks when we're returning early 2023-07-17 17:04:41 +01:00
Robert
679266c0b7 Remove unnecessarily forcing non-undefined 2023-07-17 17:02:59 +01:00
Robert
f1e96f7812 Use more standard name for callback 2023-07-17 17:02:16 +01:00
Robert
f8e6ccea23 Do event propogation cancelation before other work 2023-07-17 16:59:26 +01:00
Robert
8f46052459 Use optional call instead of explicit if-then 2023-07-17 16:58:52 +01:00
Robert
b210d83210 Use named Props interfaces instead of defining types inline 2023-07-17 16:58:08 +01:00
Robert
eaf8d68dd1 Remove all usages of NonClickableLocation outside of Location 2023-07-17 16:56:16 +01:00
Robert
c4ebee8e8d Have each component in a separate file 2023-07-17 16:56:15 +01:00
Robert
2962306094 Specify that tmp dir is under homedir on windows 2023-07-17 15:48:20 +01:00
Robert
a4c0365a95 Move components for rendering locations to a separate file 2023-07-17 14:36:08 +01:00
Shati Patel
2abc4d542b Merge pull request #2613 from github/version/bump-to-v1.8.9
Bump version to v1.8.9
2023-07-17 12:01:59 +01:00
github-actions[bot]
700b9bf348 Bump version to v1.8.9 2023-07-17 10:35:30 +00:00
Shati Patel
6be797d9d2 Merge pull request #2612 from github/v1.8.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
Release prep for v1.8.8
2023-07-17 11:10:54 +01:00
Robert
9924f87473 Add a test that calls loadModeledMethods 2023-07-17 11:07:24 +01:00
Robert
f19b600287 Fix semantic merge conflict in imports 2023-07-17 11:07:10 +01:00
Robert
14200a5011 Merge branch 'main' into robertbrignull/data-modeled-methods-tests 2023-07-17 11:06:40 +01:00
shati-patel
3fa7590187 v1.8.8 2023-07-17 10:17:54 +01:00
Marcono1234
fffb692ca8 Include column numbers in location URLs 2023-07-15 22:00:21 +02:00
Shati Patel
6cfc7d5ced Remove support for CodeQL CLI versions older than 2.9.4 (#2610) 2023-07-14 16:13:46 +00:00
Philip Ginsbach
7ea6cd871b Merge pull request #2609 from github/ginsbach/AdditionalAndDefaultKeywords
add `additional` and `default` keywords to the TextMate grammar
2023-07-14 16:23:50 +01:00
Shati Patel
5631d33b20 Change the data extension's webview icon (#2608) 2023-07-14 15:17:56 +00:00
Robert
de7d65fc8b Replace checkbox with an icon that shows saved status 2023-07-14 16:16:30 +01:00
Robert
e73421dabb Track changed signatures instead of unsaved models 2023-07-14 16:16:27 +01:00
Philip Ginsbach
e1e55d1d01 link to the PR from the changelog entry 2023-07-14 15:23:55 +01:00
Robert
421fe11664 Normalize paths before doing string comparisons 2023-07-14 15:12:12 +01:00
Philip Ginsbach
0b18492946 add changelog entry for 'additional' and 'default' keywords 2023-07-14 14:57:46 +01:00
Philip Ginsbach
f3ad6ec105 recompile the TextMate grammar 2023-07-14 14:57:46 +01:00
Philip Ginsbach
d97e4d1ba1 add 'additional' and 'default' annotation keywords to grammar 2023-07-14 14:47:07 +01:00
Koen Vlaswinkel
ccda490ab4 Merge pull request #2566 from github/koesie10/library-version
Add library versions to data extensions editor
2023-07-14 15:43:42 +02:00
Robert
1dcd048268 Move version check next to existing check 2023-07-14 14:20:58 +01:00
Robert
12511922ad Remove version check in resolveExtensions method 2023-07-14 14:15:07 +01:00
Robert
2392d7c7b6 Merge pull request #2606 from github/robertbrignull/data-modeled-method-signature
Add signature and related fields to ModeledMethod
2023-07-14 14:11:40 +01:00
Koen Vlaswinkel
4158df197c Improve library version matching regex 2023-07-14 14:13:23 +02:00
Robert
1782239c7c Add in CodeQL CLI version check for the "resolve extensions" command 2023-07-14 11:38:07 +01:00
Robert
e2b211ad53 Merge branch 'main' into robertbrignull/data-modeled-method-signature
pick 2db42e3e Pull out createDataExtensionYamls into yaml.ts
pick 52f7cac0 Move saveModeledMethods to a separate file
pick ba27230e Move loadModeledMethods to a separate file
pick c512a11e Split out listModelFiles from loadModeledMethods
pick 752cf8ab Add some tests of listModelFiles
2023-07-14 11:05:14 +01:00
Koen Vlaswinkel
f91da95081 Add library versions to data extensions editor 2023-07-14 12:02:05 +02:00
Koen Vlaswinkel
10d9213dbe Merge pull request #2563 from github/koesie10/classification
Add call classification and supported kind to data extensions editor
2023-07-14 12:01:58 +02:00
Robert
bb110152f2 Fix expected values in tests 2023-07-14 10:55:43 +01:00
Koen Vlaswinkel
bd6c302360 Add tooltip to classifications container 2023-07-14 11:38:45 +02:00
Koen Vlaswinkel
1272ddd696 Decrease text size of test and generated tags 2023-07-14 11:36:00 +02:00
Koen Vlaswinkel
ca7ba89a68 Move method classifications to separate component 2023-07-14 11:32:34 +02:00
Andrew Eisenberg
39465d9ad9 Merge pull request #2607 from github/github-action/bump-cli 2023-07-13 14:45:20 -07:00
github-actions[bot]
b419b8d308 Bump CLI version from v2.13.5 to v2.14.0 for integration tests 2023-07-13 18:34:27 +00:00
Robert
169221305f Remove the ModeledMethodWithSignature type in favour of just ModeledMethod 2023-07-13 16:55:04 +01:00
Robert
97a331cf6a Remove the ModeledExternalApiUsage type in favour of just ModeledMethod 2023-07-13 16:55:04 +01:00
Robert
16f98491e7 Remove the ExternalApiUsageByType in favour of just ModeledMethod 2023-07-13 16:55:04 +01:00
Robert
111dfff7fb Add signature to ModeledMethod 2023-07-13 16:55:04 +01:00
Robert
f927ac9f1c Split out MethodSignature from ExternalApiUsage 2023-07-13 16:55:04 +01:00
Koen Vlaswinkel
6a0cae58e0 Remove call type for unmodelable methods
This removes the call type as shown for an unmodelable method. We still
need to decide how to show this information, so this may be added back
in later.
2023-07-13 16:44:43 +02:00
Koen Vlaswinkel
1efc276c24 Show labels for methods only classified in test and generated 2023-07-13 16:36:37 +02:00
Koen Vlaswinkel
94015a0ac2 Show type for supported methods 2023-07-13 16:33:34 +02:00
Koen Vlaswinkel
048552093b Add classification and type to types 2023-07-13 16:19:05 +02:00
Koen Vlaswinkel
0560f4fe76 Add classification and type to queries 2023-07-13 16:15:58 +02:00
Robert
752cf8ab16 Add some tests of listModelFiles 2023-07-13 10:29:52 +01:00
Robert
c512a11e7e Split out listModelFiles from loadModeledMethods 2023-07-13 09:50:54 +01:00
Robert
ba27230e3c Move loadModeledMethods to a separate file 2023-07-13 09:29:42 +01:00
Robert
52f7cac0a9 Move saveModeledMethods to a separate file 2023-07-13 09:20:00 +01:00
Robert
2db42e3eb0 Pull out createDataExtensionYamls into yaml.ts 2023-07-13 08:54:11 +01:00
Robert
31fdc794e5 Merge pull request #2600 from github/robertbrignull/data-supported
Show more clearly when a method is already modeled
2023-07-12 17:26:10 +01:00
Robert
e55800ae2d Tweak message 2023-07-12 16:37:44 +01:00
Robert
0f39d41e50 fix typo 2023-07-12 16:37:18 +01:00
Robert
31118a514f Merge pull request #2599 from github/nora/make-result-table-functional-component
Convert ResultTable to a functional component
2023-07-12 16:34:57 +01:00
Robert
fa5c24d837 Display an explanatory message on unmodelable methods 2023-07-12 14:56:15 +01:00
Robert
8ec08ef43f Remove ugly jumpToUsage prop 2023-07-12 14:36:40 +01:00
Robert
7d59224407 Pull out ModelableMethodRow as a separate component 2023-07-12 14:36:40 +01:00
Robert
aba574e423 Pull out UmmodelableMethodRow to a separate component 2023-07-12 14:36:39 +01:00
Robert
799b96e7f6 Convert modelTypeOptions to be a const 2023-07-12 14:35:42 +01:00
Nora
60f33e573e Convert ResultTable 2023-07-12 13:12:14 +00:00
Robert
5fa338e460 Return early if method cannot be modeled 2023-07-12 14:04:58 +01:00
Robert
8529c05396 Move boolean showXCell variables to be later and together 2023-07-12 14:02:39 +01:00
Robert
70b2e68ce7 Rename showModelTypeCell => methodCanBeModeled 2023-07-12 14:01:01 +01:00
Robert
8432f6cdfe Move predicate variable closer to where it's used 2023-07-12 13:50:31 +01:00
Robert
39d53f469f Merge pull request #2598 from github/robertbrignull/data-framework-model
Don't show model from source button in framework mode
2023-07-12 10:22:24 +01:00
Robert
c8ba8d6e1b Merge branch 'main' into robertbrignull/data-framework-model 2023-07-12 10:05:06 +01:00
Robert
28c6ab36ce Merge pull request #2597 from github/robertbrignull/data-view-state
Clear up how we pass around view state
2023-07-12 10:04:39 +01:00
Dave Bartolomeo
3e5985955d Merge pull request #2538 from github/dbartol/save-before-start
Save dirty documents before evaluating queries
2023-07-11 15:55:03 -04:00
Dave Bartolomeo
a4cff531be Remove more debugging code 2023-07-11 15:32:09 -04:00
Dave Bartolomeo
c18bb39f40 Remove more debugging code 2023-07-11 14:49:32 -04:00
Dave Bartolomeo
d93f2b67c8 Remove some debugging code 2023-07-11 14:42:57 -04:00
Robert
5b65e08fdf Don't show model from source button in framework mode 2023-07-11 17:32:12 +01:00
Robert
79a567b478 Avoid passing in both viewState and mode at the same time 2023-07-11 16:53:12 +01:00
Robert
5e84b5f055 Enforce that viewState is defined and show a loading screen otherwise 2023-07-11 16:47:44 +01:00
Robert
aa4df082bf Merge pull request #2594 from github/robertbrignull/data-unsaved-changes
Include in addModeledMethods whether the methods are unsaved or not
2023-07-11 16:26:44 +01:00
Robert
370872d005 Split addModeledMethods into that and loadModeledMethods 2023-07-11 15:23:30 +01:00
Robert
930103b3a8 Merge branch 'main' into robertbrignull/data-unsaved-changes 2023-07-11 15:11:24 +01:00
dependabot[bot]
6cf2f32705 Bump @octokit/plugin-retry from 3.0.9 to 4.1.6 in /extensions/ql-vscode (#2518)
Bumps [@octokit/plugin-retry](https://github.com/octokit/plugin-retry.js) from 3.0.9 to 4.1.6.
- [Release notes](https://github.com/octokit/plugin-retry.js/releases)
- [Commits](https://github.com/octokit/plugin-retry.js/compare/v3.0.9...v4.1.6)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Charis Kyriakou <charisk@users.noreply.github.com>
2023-07-11 13:02:04 +01:00
Robert
83a25006ec Merge pull request #2586 from github/dependabot/npm_and_yarn/extensions/ql-vscode/prettier-3.0.0
Bump prettier from 2.7.1 to 3.0.0 in /extensions/ql-vscode
2023-07-11 11:11:21 +01:00
Robert
38d0d0ee7d Merge pull request #2593 from github/dependabot/npm_and_yarn/extensions/ql-vscode/tough-cookie-4.1.3
Bump tough-cookie from 4.1.2 to 4.1.3 in /extensions/ql-vscode
2023-07-11 10:51:42 +01:00
Robert
296922c193 Merge pull request #2595 from github/robertbrignull/data-generate-from-source
Hook up generating from source in the new collapsible section
2023-07-11 09:54:07 +01:00
Robert
e5ae41328b Run: npm run format 2023-07-11 09:51:28 +01:00
Robert
0fc3adf29a Upgrade eslint-plugin-prettier to 5.0.0 2023-07-11 09:43:58 +01:00
dependabot[bot]
49954b5af0 Bump prettier from 2.7.1 to 3.0.0 in /extensions/ql-vscode
Bumps [prettier](https://github.com/prettier/prettier) from 2.7.1 to 3.0.0.
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/2.7.1...3.0.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-10 15:19:00 +00:00
Nora
f493ba102b Merge pull request #2596 from github/nora/update-eslint
Update eslint
2023-07-10 17:17:01 +02:00
Nora
43aa06a248 Update eslint 2023-07-10 13:49:55 +00:00
Robert
c8fd00b983 Hook up generating from source 2023-07-10 13:03:28 +01:00
Robert
c25619332c Merge pull request #2569 from github/robertbrignull/convert-ResultsApp
Convert ResultsApp to a function component
2023-07-10 11:36:32 +01:00
Robert
f4b37c96e4 Merge branch 'main' into robertbrignull/convert-ResultsApp 2023-07-10 11:16:57 +01:00
Robert
f7239b073a Include in addModeledMethods whether the methods are unsaved or not 2023-07-10 10:48:33 +01:00
Robert
bf0032d8de Merge pull request #2592 from github/robertbrignull/data-supported-doc
Add documentation to ExternalApiUsage fields
2023-07-10 10:04:52 +01:00
dependabot[bot]
7eeec834ed Bump tough-cookie from 4.1.2 to 4.1.3 in /extensions/ql-vscode
Bumps [tough-cookie](https://github.com/salesforce/tough-cookie) from 4.1.2 to 4.1.3.
- [Release notes](https://github.com/salesforce/tough-cookie/releases)
- [Changelog](https://github.com/salesforce/tough-cookie/blob/master/CHANGELOG.md)
- [Commits](https://github.com/salesforce/tough-cookie/compare/v4.1.2...v4.1.3)

---
updated-dependencies:
- dependency-name: tough-cookie
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-09 22:27:45 +00:00
Robert
5eab1f8882 Add documentation to ExternalApiUsage fields 2023-07-07 17:10:06 +01:00
Robert
2525ae80b9 Merge pull request #2591 from github/robertbrignull/data-llm-section
Use AI to model just a single section
2023-07-07 16:16:42 +01:00
Robert
8423c73bdd Merge pull request #2590 from github/robertbrignull/data-button-features
Only show LLM / framework mode when the view state says to show the button
2023-07-07 16:09:10 +01:00
Robert
37980612ac Define separate no-op handler 2023-07-07 15:31:08 +01:00
Robert
c4912b1a65 Show framework mode button when available 2023-07-07 14:28:18 +01:00
Robert
ae3b6eccc3 Only show AI button when available 2023-07-07 14:28:01 +01:00
Robert
48ffca3103 Use AI to model just a single section 2023-07-07 12:37:10 +01:00
Robert
dae74e8772 Merge pull request #2588 from github/robertbrignull/data-save-single-model
Implement saving only one model at a time
2023-07-07 09:50:19 +01:00
Robert
e2dc0d6db5 Merge pull request #2589 from github/robertbrignull/data-title-buttons-background
Use better colours for title buttons
2023-07-07 09:26:03 +01:00
Robert
bf087d2114 Merge branch 'main' into robertbrignull/data-title-buttons-background 2023-07-07 08:41:58 +01:00
Shati Patel
8fab24f424 Merge pull request #2587 from github/shati-patel/unsaved-tag
Data extensions editor: Update styling of "unsaved" tag
2023-07-07 08:39:33 +01:00
Robert
7bda76347c Changes buttons to avoid custom styling 2023-07-06 17:02:01 +01:00
dependabot[bot]
5db2b90212 Bump zip-a-folder from 1.1.3 to 2.0.0 in /extensions/ql-vscode (#2517)
Bumps [zip-a-folder](https://github.com/maugenst/zip-a-folder) from 1.1.3 to 2.0.0.
- [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>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Charis Kyriakou <charisk@users.noreply.github.com>
2023-07-06 17:01:50 +01:00
shati-patel
2b13645b6f Move "Save" button slightly to the left 2023-07-06 16:32:34 +01:00
shati-patel
4acc6f9e41 Use native "VS Code Tag" instead of custom span 2023-07-06 16:31:29 +01:00
Robert
e67f93c7bc Implement saving only one model at a time 2023-07-06 16:28:29 +01:00
Robert
261f11e30e Merge pull request #2582 from github/robertbrignull/data-table
Update data extensions modelling table to new designs
2023-07-06 16:27:06 +01:00
Robert
a07e829bf1 Make view link not wrap 2023-07-06 15:25:39 +01:00
Robert
afc9635d43 Use --vscode styles 2023-07-06 15:25:27 +01:00
Robert
7a54b00d29 Merge pull request #2583 from github/robertbrignull/data-unsaved-changes
Show when there are unsaved changes to a model
2023-07-06 12:08:01 +01:00
Robert
903e8c6688 Convert dropdown to a full component 2023-07-06 11:46:57 +01:00
Robert
d5c4f33d6e Use a native select instead of VSCodeDropdown 2023-07-06 11:22:17 +01:00
Robert
7688542aa2 Merge branch 'main' into robertbrignull/data-unsaved-changes 2023-07-06 10:14:15 +01:00
Dave Bartolomeo
614a8d123c Merge pull request #2584 from github/github-action/bump-cli
Bump CLI Version to v2.13.5 for integration tests
2023-07-05 14:33:43 -04:00
github-actions[bot]
e3ff6ace08 Bump CLI version from v2.13.4 to v2.13.5 for integration tests 2023-07-05 15:31:44 +00:00
Robert
fc866acae3 Show when there are unsaved changes to a model 2023-07-05 12:16:40 +01:00
Robert
f75b358e6c Disable buttons instead of hiding them 2023-07-04 17:21:55 +01:00
Robert
e82bfb4153 Pull out booleans controlling visibility of each cell 2023-07-04 17:10:10 +01:00
Charis Kyriakou
7541b64ec8 Move some top level files (#2580)
* Move code-tour.ts to /code-tour

* Move qlpack-generator.ts to /local-queries

* Move query-status.ts to /query-history

* Move skeleton-query-wizard.ts to /local-queries
2023-07-04 16:08:26 +00:00
Robert
12e9de85c7 Merge pull request #2575 from github/robertbrignull/data-editor-story
Use more varied data for the number of usages
2023-07-04 17:01:20 +01:00
Shati Patel
5afdef1ec8 Merge pull request #2581 from github/shati-patel/data-ui-background
Data extensions UI: Change background colour of library container
2023-07-04 17:00:27 +01:00
Robert
870827085d Remove colouring of the methods 2023-07-04 16:57:13 +01:00
Robert
e384f2447c Convert data table to new column layout 2023-07-04 16:57:13 +01:00
Shati Patel
2c5b1da7b2 Merge pull request #2579 from github/shati-patel/bottom-bar
Data extensions UI: Add save button
2023-07-04 16:38:03 +01:00
shati-patel
c7295e66bc Change background colour of library container 2023-07-04 16:35:15 +01:00
Shati Patel
5e49bd5491 Merge pull request #2578 from github/data-ext-divider
Data extensions UI: Add divider between title and status containers
2023-07-04 16:32:28 +01:00
shati-patel
33cb206fed Add save button 2023-07-04 16:07:39 +01:00
shati-patel
882352fcbf Add divider between title and status containers 2023-07-04 16:06:47 +01:00
Robert
f8ad72233a Merge pull request #2574 from github/robertbrignull/data-title
Update data extensions modelling table title bar
2023-07-04 15:57:45 +01:00
Charis Kyriakou
31e94a877d Add code search functionality to test plan (#2577) 2023-07-04 14:47:49 +01:00
Charis Kyriakou
545286b8d9 Add ability to record and replay mock code search requests (#2576) 2023-07-04 14:47:30 +01:00
Robert
c178d251a1 Use more varied data for the number of usages 2023-07-04 11:20:06 +01:00
Robert
97219b9f63 Remove old status info 2023-07-03 16:01:35 +01:00
Robert
15be27c4c3 Add new buttons to title bar 2023-07-03 16:01:34 +01:00
Nora
a3921b7afa Merge pull request #2562 from github/nora/refactor-graph
Convert Graph to a functional component
2023-07-03 15:08:53 +02:00
Nora
9ba5701874 implement merge comments 2023-07-03 11:31:02 +00:00
Robert
4d8694e78b Merge pull request #2571 from github/robertbrignull/AlertTableHeader
Pull out AlertTableHeader to a separate component/file
2023-07-03 12:22:05 +01:00
Robert
e5d4545150 Remove unnecessary function 2023-07-03 10:55:27 +01:00
Robert
0a0b9e590b Merge pull request #2523 from github/robertbrignull/queries-loading
Display different message when queries are loading vs no queries found
2023-07-03 10:52:33 +01:00
Robert
f0af593b67 Simplify comparisons with undefined 2023-07-03 10:51:52 +01:00
Robert
08a8d6396c Remove column arg where it is always "alert-message" 2023-07-03 10:47:02 +01:00
Robert
c876867753 Rename to folder/file items 2023-07-03 09:52:09 +01:00
Robert
eec2f33cba Check for underfined before filtering 2023-07-03 09:44:07 +01:00
Robert
78e794ccdf Convert back to type import 2023-07-03 09:40:05 +01:00
Robert
6acfb8d151 Merge pull request #2570 from github/robertbrignull/AlertTable-rename
Rename PathTable => AlertTable
2023-07-03 09:35:10 +01:00
Dave Bartolomeo
e80a06c5c1 Try grabbing screenshot 2023-06-30 13:36:58 -04:00
Dave Bartolomeo
c70ec7159a Try different default for saveBeforeStart 2023-06-30 10:50:26 -04:00
Dave Bartolomeo
c25410ed5d Log config settings 2023-06-30 10:16:49 -04:00
Dave Bartolomeo
81b2407a47 Log content of untitled docs 2023-06-30 09:57:47 -04:00
Dave Bartolomeo
1f5b3919b0 Dump dirty documents 2023-06-30 09:37:28 -04:00
Dave Bartolomeo
b859bca25f Even more logging 2023-06-30 08:50:06 -04:00
Robert
bfae001b3c Pull out AlertTableHeader to a separate component/file 2023-06-30 10:07:11 +01:00
Robert
2c2b0ecd79 Rename PathTable => AlertTable 2023-06-30 10:01:34 +01:00
Dave Bartolomeo
53a51ab1c9 More logging 2023-06-29 15:33:34 -04:00
Dave Bartolomeo
9f077b0810 Run Jest in verbose mode 2023-06-29 15:14:48 -04:00
Dave Bartolomeo
bf36051054 Increase timeout 2023-06-29 14:52:19 -04:00
Dave Bartolomeo
dbd257e2c0 More logging 2023-06-29 14:39:30 -04:00
Dave Bartolomeo
9fd0697868 Fix format 2023-06-29 12:15:36 -04:00
Dave Bartolomeo
adf0ccb48b Disable workspace trust for CLI integration tests 2023-06-29 12:10:39 -04:00
Robert
3ff649a49a Convert ResultsApp to a function component 2023-06-29 14:49:15 +01:00
Robert
dc5826a848 Rearrange functions so they are defined earlier in the file from where they are called 2023-06-29 14:47:45 +01:00
Anders Starcke Henriksen
4e92688900 Merge pull request #2567 from github/version/bump-to-v1.8.8
Bump version to v1.8.8
2023-06-29 15:30:29 +02:00
github-actions[bot]
08544a4248 Bump version to v1.8.8 2023-06-29 12:22:33 +00:00
Anders Starcke Henriksen
c00adc01f1 Merge pull request #2565 from github/v1.8.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
v1.8.7
2023-06-29 13:04:42 +02:00
Anders Starcke Henriksen
65a3ba96c0 v1.8.7 2023-06-29 10:43:05 +02:00
Dave Bartolomeo
d27efb3a17 Merge remote-tracking branch 'origin/main' into dbartol/save-before-start 2023-06-28 20:07:12 -04:00
Dave Bartolomeo
8ff1db13f7 Fix bad diff 2023-06-28 19:55:43 -04:00
Alexander Eyers-Taylor
67d342f2ed Give visibility information to the ide-server. (#2482)
* Add version constraint for Check errors

* Refactor parts of the ideserver out of extension.ts

* Give visibility information to the ide-server.

This allows it to report errors on visible files
eagerly.
2023-06-28 18:21:55 +00:00
Robert
d1838ba0f7 Convert to match style from DB panel 2023-06-28 17:00:44 +01:00
Nora
98d1a24a43 Convert Graph to a functional component 2023-06-28 12:11:55 +00:00
Robert
66d233d669 Merge pull request #2561 from github/enable-a11y-linting-rules
Enable accessibility linting rules and comment out existing violations
2023-06-28 11:54:50 +01:00
Koen Vlaswinkel
a64f44bc41 Merge pull request #2559 from github/koesie10/framework-mode-refresh-button
Add a refresh button to the data extensions editor
2023-06-28 12:38:04 +02:00
Sam Partington
b8b15a53dc Enable accessibility linting rules and comment out existing violations
cf https://github.com/github/code-stats-collector/pull/390 /
https://github.com/github/code-scanning/issues/9347
2023-06-28 10:59:18 +01:00
Robert
6be9e5359c fix typo 2023-06-28 10:37:19 +01:00
Koen Vlaswinkel
266b1e5818 Add a refresh button to the data extensions editor
This adds a refresh button to the data extensions editor when the
framework mode feature flag is enabled. If you are using framework mode,
you can have multiple tabs of the data extensions editor open in which
you are modeling the library separately from the application. When you
save the library in framework mode, the application mode will not
refresh and show that these calls have been modeled. Rather than using
apply, which might also save all modeled methods, you can now use the
refresh button to refresh the external API usages and whether they are
supported.
2023-06-28 11:33:21 +02:00
Koen Vlaswinkel
001179056e Merge pull request #2558 from github/koesie10/exclude-test-methods-in-framework-mode
Exclude methods in tests in framework mode
2023-06-28 11:14:55 +02:00
Koen Vlaswinkel
bcbbb42b41 Exclude methods in tests in framework mode
This excludes methods defined in tests in framework mode, significantly
cutting down on the number of methods shown that would need to be
modeled.

For C#, this just checks that the file is not a test file, as defined
by the QL library.

For Java, this makes a copy of the internal
[`ModelExclusions.qll`](249f9f863d/java/ql/lib/semmle/code/java/dataflow/internal/ModelExclusions.qll)
file to avoid the use of internal modules. This module will tell us
whether a method is "interesting" to model or not. Not all of the checks
in this module need to happen for framework mode, but these checks might
be useful for telling a user whether a method is interesting to model
in application mode.
2023-06-28 10:21:26 +02:00
Koen Vlaswinkel
6465786411 Merge pull request #2557 from github/koesie10/jump-to-def-framework-mode
Add jump to definition in framework mode
2023-06-28 09:49:45 +02:00
Robert
d290b56649 Display custom text message when there are no queries found 2023-06-27 17:04:26 +01:00
Robert
cf49d5dcde Change welcome message to say we're searching for queries 2023-06-27 17:04:26 +01:00
Robert
94fe3e0020 Always trigger pathsChanged listener after initial refresh 2023-06-27 17:04:26 +01:00
Shati Patel
9314b3ba56 Merge pull request #2554 from github/shati-patel/run-all-context-menu
Queries panel: Run all queries in folder (context menu)
2023-06-27 16:51:40 +01:00
Nora
af366afcff Merge pull request #2556 from github/nora/release-run-from-tab
Release run query from file tab icon
2023-06-27 17:46:35 +02:00
Robert
6fe7b82397 Only return something from getPathData once discover has run at least once 2023-06-27 16:20:30 +01:00
Koen Vlaswinkel
1579859c9d Merge pull request #2555 from github/koesie10/nested-name-csharp
Add `nestedName` function for C#
2023-06-27 17:00:23 +02:00
Koen Vlaswinkel
5349a75bd0 Add jump to definition in framework mode
This makes the method name and parameters in framework mode a link to
the definition of the method. In framework mode, the `usages` contains
1 element, which is the location of the definition of the method.
Therefore, we can simply use `jumpToUsage` to jump to the definition.
2023-06-27 16:57:46 +02:00
Nora
46a32081d9 Release run query from file tab 2023-06-27 14:40:48 +00:00
Nora
82977519ce Merge pull request #2552 from github/nora/run-all-queries-panel
Queries Panel: run-all queries of a folders
2023-06-27 16:37:43 +02:00
Nora
32555cc4f2 Merge pull request #2548 from github/dependabot/npm_and_yarn/extensions/ql-vscode/semver-7.5.2
Bump semver from 7.3.7 to 7.5.2 in /extensions/ql-vscode
2023-06-27 16:33:16 +02:00
Koen Vlaswinkel
4b8cdf872a Merge pull request #2553 from github/koesie10/nested-name
Use `nestedName` for getting the name of an API
2023-06-27 16:17:43 +02:00
Koen Vlaswinkel
8af0ba7411 Add nestedName function for C#
Similar to https://github.com/github/vscode-codeql/pull/2553, this
changes the C# query to correctly report the name of nested types. I
couldn't find a `nestedName` method for C#, so this adds one in the
`AutomodelVsCode` library.

C# seems to use `+` as a separator for nested types, as reported by
`getQualifiedName()`:

```
GitHub.Nested.MyFirstClass+NestedClass
```

The `getApiName()` will now report:

```
GitHub.Nested#MyFirstClass+NestedClass.Test()
```
2023-06-27 16:14:42 +02:00
shati-patel
02b356cf86 Queries panel: Run all queries in folder (context menu)
Adds a command to run all queries in a certain folder.
This uses the existing `runQueries` command, which lets you run multiple queries against the selected local database.
We don't have a corresponding command for running multiple variant analysis queries, so I haven't implemented that.
2023-06-27 15:03:23 +01:00
Koen Vlaswinkel
3ad3644219 Merge pull request #2542 from github/koesie10/override-extension-directory
Allow overriding the data extensions editor extensions directory
2023-06-27 15:13:59 +02:00
Koen Vlaswinkel
77495df97d Merge pull request #2550 from github/koesie10/refactor-duplication-queries
Refactor data extensions editor queries to reduce duplication
2023-06-27 15:13:50 +02:00
Nora
a591c82b3c Add run all on folders 2023-06-27 15:08:30 +02:00
Shati Patel
ee68156574 Merge pull request #2547 from github/shati-patel/run-query-context-menu-remote
Run variant analysis from Queries Panel context menu
2023-06-27 13:38:25 +01:00
Koen Vlaswinkel
a053792d6e Use nestedName for getting the name of an API
This changes the Java `CallableMethod.getApiName()` to use `nestedName`
instead of `getSourceDeclaration`. `getSourceDeclaration` would return a
`RefType`, on which the `toString()` method returns its `getName`().
However, for nested types this wouldn't work and wouldn't include the
enclosing type. This fixes it by using `nestedName` which matches the
method that is also used for determining whether a type matches an
extensible predicate.
2023-06-27 14:38:19 +02:00
Alexander Eyers-Taylor
b0699ee524 Add quick eval count to the command palette (#2475)
* Add version constraint for quick-eval-count

* Add quick eval count context.

* Add support for running quick-eval-count from the command pallete

* Adjust name for quick-eval-count-queries

* Add changenote for quick-eval-count.

* QuickEval:Address review comments

* Fix rebase conflict in changelog
2023-06-27 11:28:28 +01:00
Koen Vlaswinkel
bd0e5604a8 Fix incorrect JAR name being displayed in application mode 2023-06-27 11:22:03 +02:00
Nora
2a332f90c4 Merge pull request #2551 from github/nora/fix-merge-conflict-mistake
Fix merge conflict error: Re-add icon
2023-06-27 10:46:00 +02:00
Shati Patel
7b73ff4231 Merge pull request #2546 from github/shati-patel/run-query-context-menu-local
Run local query from Queries Panel context menu
2023-06-26 17:08:42 +01:00
Shati Patel
0d0ae6449f Merge branch 'main' into shati-patel/run-query-context-menu-local 2023-06-26 16:46:24 +01:00
Nora
3c156b858c Re-add icon 2023-06-26 14:54:17 +00:00
Koen Vlaswinkel
7e8578a22c Refactor data extensions editor queries to reduce duplication
This refactors the data extensions editor queries to use a new
`AutomodelVsCode` module. This module is based on the `ExternalApi`
module, but is more general and can be used for retrieving public
methods from the source as well. The actual conditions are now in the
queries themselves.

This reduces the duplicated module in the framework mode query and will
mean that when we update the `ExternalApi` module, we will just have to
port it to the `AutomodelVsCode` module, and not to the `ExternalApi`
and a separate framework mode query.
2023-06-26 16:33:05 +02:00
Koen Vlaswinkel
aa4d3f4399 Merge pull request #2549 from github/koesie10/consistent-sorting
Sort methods sent to LLM the same way as the UI
2023-06-26 16:11:38 +02:00
Nora
75d2f76658 Merge pull request #2544 from github/nora/queries-panel-file-tab
Queries Panel: run local query from file tab
2023-06-26 16:09:03 +02:00
Robert
75cffd50b1 Merge pull request #2539 from github/robertbrignull/raw-results-react
Convert RawTable to a function component
2023-06-26 14:23:19 +01:00
Nora
10d8bbfe63 Add run icon to file tab 2023-06-26 14:48:48 +02:00
Koen Vlaswinkel
90c8391fea Sort methods sent to LLM the same way as the UI
This changes the sorting of the methods sent to LLM to match the order
shown in the data extensions editor. This will ensure that the methods
which are shown first in the data extensions editor are also modeled
first.
2023-06-26 14:26:31 +02:00
Koen Vlaswinkel
a8aee6a8e1 Extract sorting to separate functions 2023-06-26 14:08:46 +02:00
dependabot[bot]
d41e9ef163 Bump semver from 7.3.7 to 7.5.2 in /extensions/ql-vscode
Bumps [semver](https://github.com/npm/node-semver) from 7.3.7 to 7.5.2.
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/main/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v7.3.7...v7.5.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-26 11:57:15 +00:00
Nora
13a5b7854f Merge pull request #2534 from github/nora/run-local-query-panel
Queries Panel: run local query from panel
2023-06-26 13:56:08 +02:00
shati-patel
3a3264302a Run variant analysis from Queries Panel context menu 2023-06-26 11:53:01 +01:00
shati-patel
9704b498fe Run local query from Queries Panel context menu 2023-06-26 10:51:18 +01:00
Nora
2b48991494 Rename command 2023-06-26 09:04:06 +00:00
Nora
ff41e50954 Show run button only when db is selected 2023-06-26 09:04:06 +00:00
Nora
24683f34de Adjust command lint tests 2023-06-26 09:04:06 +00:00
Nora
7db84b0276 Always show run button 2023-06-26 09:04:06 +00:00
Nora
655294db06 Use only one command 2023-06-26 09:04:06 +00:00
Nora
5845e9e59e Merge comments and mock command 2023-06-26 09:04:06 +00:00
Nora
c0c42d36b9 Use corret Uri method and extract feature flag guard 2023-06-26 09:04:06 +00:00
Nora
2898acd67f Hide new command behind feature flag 2023-06-26 09:04:06 +00:00
Robert
7409fe8a56 rename commands to match linter 2023-06-26 09:04:06 +00:00
Robert
f25d7baa56 Expose QueryServerCommandManager from app 2023-06-26 09:04:06 +00:00
Nora
3f1b619904 Create new runQuery command for the queries panel 2023-06-26 09:04:06 +00:00
Nora
12c0c57c25 hook up new command and make runQuery executable 2023-06-26 09:04:06 +00:00
Nora
c78db22599 Hide run button when no local database is selected 2023-06-26 09:04:06 +00:00
Nora
fea0c3ce46 Add icon 2023-06-26 09:04:06 +00:00
Robert
0e033b48d4 Avoid creating and throwing away Scroller each render 2023-06-26 10:03:15 +01:00
Koen Vlaswinkel
971d1461c8 Merge pull request #2543 from github/koesie10/exclude-anonymous-classes
Exclude methods from anonymous classes in framework mode
2023-06-26 10:00:04 +02:00
Koen Vlaswinkel
a76bd4627c Merge pull request #2535 from github/koesie10/framework-mode
Add initial implementation of framework mode
2023-06-23 13:57:09 +02:00
Koen Vlaswinkel
6e16f826fb Exclude methods from anonymous classes in framework mode 2023-06-23 13:45:06 +02:00
Koen Vlaswinkel
4f367119cb Fix data extensions editor story 2023-06-23 11:59:26 +02:00
Koen Vlaswinkel
01da0f1d34 Fix incorrect comment on method 2023-06-23 11:58:43 +02:00
Koen Vlaswinkel
aec5ff3902 Allow overriding the extensions directory
This will allow users to override the default directory in which
extension packs are created by using the
`codeQL.dataExtensions.extensionsDirectory` setting. This setting can be
overriden per language, so the user could create the following
configuration to set the extension pack setting for Java only:

```json
"[java]": {
  "codeQL.dataExtensions.extensionsDirectory": "/Users/user/github/vscode-codeql-starter/codeql-custom-queries-java",
}
```
2023-06-23 11:37:58 +02:00
Koen Vlaswinkel
f90d538743 Add feature flag for framework mode 2023-06-23 11:12:28 +02:00
Koen Vlaswinkel
72a91efde9 Add tests for framework mode YAML generation 2023-06-23 10:45:12 +02:00
Koen Vlaswinkel
8c36e572cb Create model filenames for framework mode 2023-06-23 10:04:37 +02:00
Koen Vlaswinkel
2351346440 Change data flow generator for framework mode 2023-06-23 09:53:53 +02:00
Koen Vlaswinkel
d26d886d09 Add grouping by package and remove usages for framework mode 2023-06-23 09:53:53 +02:00
Koen Vlaswinkel
48b78c1ac1 Change tests to include framework mode queries 2023-06-23 09:53:53 +02:00
Koen Vlaswinkel
526e7474a5 Add switching of mode 2023-06-23 09:53:52 +02:00
Koen Vlaswinkel
31e1bef548 Add framework mode queries 2023-06-23 09:53:01 +02:00
Koen Vlaswinkel
82cdf03d8c Merge pull request #2521 from github/koesie10/auto-create-model-files
Automatically create different model files per library
2023-06-23 09:52:39 +02:00
Dave Bartolomeo
d9a1aa8a23 Just kidding, _this_ time it's fixed for reals 2023-06-22 14:40:26 -04:00
Dave Bartolomeo
3705464766 Seriously, I think they'll pass for reals this time. 2023-06-22 14:32:25 -04:00
Dave Bartolomeo
ff2d67d930 Merge remote-tracking branch 'origin/main' into dbartol/save-before-start 2023-06-22 17:32:05 +00:00
Dave Bartolomeo
ec71f53e38 Fix more test failures 2023-06-22 13:31:12 -04:00
Robert
fa23441efb Merge pull request #2541 from github/robertbrignull/move-pure-4
Move tests out of pure directory
2023-06-22 17:08:58 +01:00
Dave Bartolomeo
6bdc095d27 Fix test failure 2023-06-22 11:45:54 -04:00
Robert
ecfa0ff5b9 Convert dataRows to a useMemo 2023-06-22 16:45:23 +01:00
Robert
3957d356f0 Import react hooks explicitly 2023-06-22 16:45:23 +01:00
Robert
f08ef1b742 Use useRef instead of useMemo for scroller 2023-06-22 16:45:21 +01:00
Robert
e29bfc83c8 Use useEffect instead of calling directly every time 2023-06-22 16:20:32 +01:00
Robert
8b95320ba8 Move tests out of pure directory 2023-06-22 15:19:47 +01:00
Robert
480bd48a8d Merge pull request #2533 from github/robertbrignull/assert-pure
Update assert-pure.ql now that the /pure directory has been removed
2023-06-22 15:19:25 +01:00
Robert
1499d909c8 Merge pull request #2537 from github/robertbrignull/move-pure-3
Move files from /pure to the /common (and other) directories (part 3 of 3)
2023-06-22 15:15:31 +01:00
Dave Bartolomeo
2397ead586 Fix test failure 2023-06-22 10:02:10 -04:00
Koen Vlaswinkel
b42457c50b Merge pull request #2540 from github/koesie10/update-external-api-qll
Update ExternalApi.qll dependencies
2023-06-22 15:21:10 +02:00
Robert
f5fef92f0f Move variant-analysis-filter-sort to shared directory 2023-06-22 13:42:12 +01:00
Robert
fc36eaab4b Move variant-analysis-filter-sort.ts to /variant-analysis 2023-06-22 13:37:13 +01:00
Robert
08fdddeefc Move result-keys.ts to /view/results 2023-06-22 13:37:13 +01:00
Robert
8e58854302 Move log-summary-parser.ts to /log-insights 2023-06-22 13:37:13 +01:00
Robert
1750594d11 Move new-messages.ts to /query-server 2023-06-22 13:37:10 +01:00
Koen Vlaswinkel
2e7c86d107 Update ExternalApi.qll dependencies 2023-06-22 14:33:28 +02:00
Robert
6143bd30d8 Convert RawTable to a functional component 2023-06-22 12:41:23 +01:00
Dave Bartolomeo
0bd0bf1944 _Correctly_ emulate VS Code's saveBeforeStart 2023-06-22 07:30:53 -04:00
Robert
cd69e5934b Merge pull request #2536 from github/robertbrignull/throw-instead-of-fail
Throw error instead of using fail method
2023-06-22 11:48:49 +01:00
Koen Vlaswinkel
669f4a6430 Add .model suffix to model filenames 2023-06-22 11:44:20 +02:00
Koen Vlaswinkel
b7b4302c1e Automatically create different model files per library
This will remove the user input for a model file and will instead create
1 model file per library (JAR/DLL). The model filename will be based on
the JAR/DLL name, but will remove the version number and the file
extension. It will also normalize the name.

These files will be created automatically, and the editor now also reads
in all files contained in an extension pack to read the modeled methods.
This could result in duplicates if the user has created a different file
to contain the same modeled methods, but this is an edge-case that we're
explicitly not handling.
2023-06-22 11:44:18 +02:00
Koen Vlaswinkel
100b557823 Merge pull request #2520 from github/koesie10/auto-name-extension-pack
Automatically name extension packs
2023-06-22 11:34:37 +02:00
Koen Vlaswinkel
7249f4c343 Add comment to explain heuristic 2023-06-22 10:08:11 +02:00
Koen Vlaswinkel
e4e849d14c Merge remote-tracking branch 'origin/main' into koesie10/auto-name-extension-pack 2023-06-22 10:01:51 +02:00
Dave Bartolomeo
b182d7afef Fix PR feedback 2023-06-21 17:20:32 -04:00
Dave Bartolomeo
1da96c5a55 Allow languageId: scopes in tests 2023-06-21 17:01:13 -04:00
Dave Bartolomeo
de38b1fd20 Stop overriding saveBeforeStart for ql language 2023-06-21 14:27:57 -04:00
Dave Bartolomeo
7a46bac078 Save dirty documents before evaluating queries 2023-06-21 18:12:42 +00:00
Robert
f8b0583c5f Move messages-shared.ts to /query-server 2023-06-21 16:31:57 +01:00
Robert
b0e6478bfe Move legacy-messages.ts to /query-server 2023-06-21 16:31:57 +01:00
Robert
0031c1acc0 Throw error instead of using fail method 2023-06-21 16:02:57 +01:00
Robert
0451dd8d1b Merge pull request #2532 from github/robertbrignull/move-pure-2
Move files from /pure to the /common directory (part 2 of 3)
2023-06-21 13:15:38 +01:00
Robert
8559d3baa0 Update assert-pure.ql now that the /pure directory has been removed 2023-06-21 12:33:32 +01:00
Robert
f12b62fa9d Move zip.ts to /common 2023-06-21 12:19:35 +01:00
Robert
90e94e04fc Move word.ts to /common 2023-06-21 12:19:35 +01:00
Robert
236a317fa0 Move time.ts to /common 2023-06-21 12:19:35 +01:00
Robert
1bf14e393f Move text-utils.ts to /common 2023-06-21 12:19:35 +01:00
Robert
655adfcd51 Move sarif-utils.ts to /common 2023-06-21 12:19:35 +01:00
Robert
b11a675004 Move ql.ts to /common 2023-06-21 12:19:35 +01:00
Robert
855cac628b Move number.ts to /common 2023-06-21 12:19:35 +01:00
Robert
5b168dfb7e Move location-link-utils.ts to /common 2023-06-21 12:19:35 +01:00
Robert
704ebf1ff6 Move interface-types.ts to /common 2023-06-21 12:19:35 +01:00
Robert
9903982bb1 Merge pull request #2530 from github/robertbrignull/move-pure-1
Move files from /pure to the /common directory (part 1 of 3)
2023-06-21 11:54:11 +01:00
Robert
d0df2966c5 Merge branch 'main' into robertbrignull/move-pure-1 2023-06-21 11:23:42 +01:00
Koen Vlaswinkel
7f9208f1e1 Merge pull request #2531 from github/koesie10/remove-common-index
Remove `common/index.ts` and vscode from `common/logging`
2023-06-21 12:11:19 +02:00
Robert
e92b676820 Merge branch 'main' into robertbrignull/move-pure-1 2023-06-21 10:37:39 +01:00
Robert
a054290c50 Merge pull request #2529 from github/robertbrignull/queries-panel-errors
Ensure errors for one path don't stop discovery of other paths
2023-06-21 10:09:45 +01:00
Koen Vlaswinkel
eeb867624e Remove common/index.ts and vscode from common/logging
The `logging` part of `common` was exported in `common/index.ts` and
could be imported by importing `common`. I don't think this makes a lot
of sense, so I removed it.

The `common/logging/index.ts` also contained exports of the
`common/logging/vscode` directory, which means that importing
`common/logging` automatically brings in the `vscode` module. This
removes that export, so now there are two separate imports needed for
importing the common part and the `vscode` specific part. This should
make it easier to keep them separate and be more explicit about what
you're importing.
2023-06-21 10:20:19 +02:00
Robert
2813576f07 Move helpers-pure.ts to /common 2023-06-21 09:10:26 +01:00
Robert
1ced7a90fd Move files.ts to /common 2023-06-21 09:06:38 +01:00
Robert
4cbd0b7fb8 Move errors.ts to /common 2023-06-21 09:03:16 +01:00
Robert
af97077095 Move distribution.ts to /common 2023-06-21 08:59:51 +01:00
Robert
a5aa0c4cf3 Move disposable-object.ts to /common 2023-06-21 08:56:59 +01:00
Koen Vlaswinkel
d092e69abf Add detection of root workspace directory using .git folder 2023-06-21 09:55:29 +02:00
Robert
7cab02de60 Move date.ts to /common 2023-06-21 08:53:51 +01:00
Robert
dc91028cee Move bqrs-utils.ts to /common 2023-06-21 08:50:39 +01:00
Robert
f228ec9645 Move bqrs-cli-types.ts to /common 2023-06-21 08:50:35 +01:00
Koen Vlaswinkel
f32a240e24 Exclude workspace folders in the system temp dir 2023-06-21 09:44:39 +02:00
Robert
7135d39aad Log error message 2023-06-21 08:24:22 +01:00
Shati Patel
c628454e25 Allow queries panel to be visible in non-dev mode too (#2528) 2023-06-20 16:46:31 +01:00
Robert
fa773a0029 Ensure errors for one path don't stop discovery of other paths 2023-06-20 16:21:20 +01:00
Koen Vlaswinkel
2c97ca95aa Merge pull request #2527 from github/koesie10/replace-faker-uuid
Replace deprecated faker.datatype.uuid by faker.string.uuid
2023-06-20 16:50:30 +02:00
Koen Vlaswinkel
d3a179744e Merge branch 'main' into koesie10/replace-faker-uuid 2023-06-20 16:22:51 +02:00
Koen Vlaswinkel
8fb1229c49 Merge pull request #2524 from github/koesie10/grouping-improvements
Improve grouping of libraries
2023-06-20 15:22:33 +02:00
Robert
23173bf441 Merge pull request #2525 from github/robertbrignull/sendRequest_progress
Remove ProgressCallback / CancellationToken arguments where they aren't used
2023-06-20 14:16:36 +01:00
Koen Vlaswinkel
1cc6aa5303 Merge branch 'main' into koesie10/auto-name-extension-pack 2023-06-20 15:12:15 +02:00
Koen Vlaswinkel
2800ccb74c Add extra sorting parameters for libraries 2023-06-20 14:24:56 +02:00
Robert
3685575c11 Merge branch 'main' into robertbrignull/sendRequest_progress 2023-06-20 13:24:30 +01:00
github-actions[bot]
c40be89636 Bump CLI version from v2.13.3 to v2.13.4 for integration tests (#2526)
Co-authored-by: github-actions[bot] <github-actions@github.com>
2023-06-20 11:28:25 +01:00
Robert
f99957435d Fix expected args in tests 2023-06-20 11:09:13 +01:00
Koen Vlaswinkel
ff491bb706 Replace deprecated faker.datatype.uuid by faker.string.uuid 2023-06-20 11:48:31 +02:00
Koen Vlaswinkel
cfc66a4e17 Store extension packs in .github/codeql/extensions 2023-06-20 11:16:23 +02:00
Robert
4d8506b3f5 Add back in manual progress update 2023-06-20 09:42:59 +01:00
Koen Vlaswinkel
ab6db71727 Move workspace folder functions to separate file 2023-06-20 10:06:52 +02:00
Koen Vlaswinkel
ddd97f08a3 Add chevron to show whether row is expanded 2023-06-20 09:32:57 +02:00
Koen Vlaswinkel
32d8968c56 Use pluralize function for pluralization 2023-06-20 09:32:57 +02:00
Koen Vlaswinkel
768c10734e Make libraries collapsible 2023-06-20 09:32:57 +02:00
Koen Vlaswinkel
a833f78151 Sort libraries by supported and usages 2023-06-20 09:32:57 +02:00
Robert
c93449ab9f Remove ProgressCallback / CancellationToken arguments where they aren't used 2023-06-19 17:13:40 +01:00
Robert
d8c3410641 Merge pull request #2490 from github/robertbrignull/resolve-queries-manual
Add manual discovery of queries and query packs
2023-06-19 14:40:50 +01:00
Robert
d2b69b1316 Normalize tmp path to ensure correct comparrison on windows 2023-06-19 14:13:09 +01:00
Koen Vlaswinkel
e83ad364f5 Merge pull request #2522 from github/koesie10/group-by-library
Group modeled methods by library in the data extensions editor
2023-06-19 15:01:19 +02:00
Koen Vlaswinkel
fe29a1a32a Add more comments 2023-06-19 13:54:17 +02:00
Koen Vlaswinkel
3323fd4e3b Add more tests for auto pack naming 2023-06-19 13:51:24 +02:00
Koen Vlaswinkel
3c60708b55 Separate pack naming and create interface 2023-06-19 13:47:27 +02:00
Koen Vlaswinkel
8980aabbfc Split flows for checking existing extension pack 2023-06-19 13:34:35 +02:00
Robert
a30ec907d0 Add tiny sleep to fix tests 2023-06-19 11:32:55 +01:00
Robert
96bb7058a2 Make note about NodeJS.ErrnoException 2023-06-19 11:09:08 +01:00
Koen Vlaswinkel
5dcadd2f1f Merge pull request #2519 from github/koesie10/add-library-to-data-extensions-editor
Add library to data extensions editor
2023-06-19 12:07:34 +02:00
Robert
1f18cc3f2c Use Readonly and ReadonlyArray 2023-06-19 10:58:26 +01:00
Robert
989ef8b681 Fix typo 2023-06-19 10:57:20 +01:00
Robert
70681253eb Only expose event to subclasses, instead of event emitter 2023-06-19 10:57:10 +01:00
Koen Vlaswinkel
bbc39b060f Remove library column 2023-06-19 11:52:09 +02:00
Koen Vlaswinkel
590e908886 Group modeled methods by library 2023-06-19 11:39:47 +02:00
Koen Vlaswinkel
487c0a66f4 Create ModeledMethodDataGrid component 2023-06-19 11:33:45 +02:00
Koen Vlaswinkel
23745ba93f Change jar to library for Java query 2023-06-19 11:25:40 +02:00
Robert
af62a92c5b Make pathData private to FilePathDiscovery 2023-06-16 16:40:11 +01:00
Robert
da92a67834 Introduce recomputeAllData to avoid mutating pathData from outside of FilePathDiscovery 2023-06-16 16:35:58 +01:00
Robert
c6a7e1fb3c Rename from path to pathData where appropriate 2023-06-16 16:23:39 +01:00
Robert
d626cea837 Use getOnDiskWorkspaceFolders instead of getOnDiskWorkspaceFoldersObjects when all we need is the path 2023-06-16 16:14:08 +01:00
Robert
bdea0c2c20 Use one lstat call instead of calling exists first 2023-06-16 16:12:29 +01:00
Robert
44327cac23 Use sets instead of custom expectArraysEqual 2023-06-16 15:23:32 +01:00
Koen Vlaswinkel
5d83ac84e3 Fix tests on Windows 2023-06-16 16:01:30 +02:00
Robert
3a0aaa0ae9 Use jest.SpiedFunction instead of jest.SpyInstance 2023-06-16 12:35:59 +01:00
Robert
18e7431a44 Make conditional easier to read 2023-06-16 12:33:21 +01:00
Koen Vlaswinkel
549884d507 Automatically name extension packs
This will change how extension packs are named in the data extensions
editor. Before, the user had to pick a workspace folder and a name for
the extension pack. Now, the workspace folder will be picked
automatically if we can detect it (i.e. it follows the naming structure
we expect), or the user will still need to select it. The extension pack
name is always auto-generated based on the database name and the
database language.

This adds a new `codeQL.dataExtensions.disableAutoNameExtensionPack`
setting to disable this behavior while we are still working on changing
how the data extensions editor works.
2023-06-16 13:31:31 +02:00
Robert
6504e46011 Invert condition to reduce nesting 2023-06-16 12:31:12 +01:00
Robert
ce6a21c65a Use pathExists instead of exists 2023-06-16 12:21:36 +01:00
Robert
fce27d02dc Use a plain Set intead of custom FilePathSet 2023-06-16 11:29:38 +01:00
Robert
f7a72c6d45 Use QueryLanguage where possible 2023-06-16 11:29:28 +01:00
Koen Vlaswinkel
55d1f14ac4 Add library to data extensions editor
This adds a new library column to the data extensions editor containing
the JAR or DLL file the method is defined in. This will be used to group
methods by library in the future. For now, it just shows in a column.
2023-06-16 12:01:30 +02:00
Robert
959c3fbcb8 Fix typos 2023-06-16 10:47:07 +01:00
Koen Vlaswinkel
0f9d127b4c Merge pull request #2513 from github/koesie10/show-telemetry-without-vscode
Make the `showAndLogExceptionWithTelemetry` function work without the `vscode` module
2023-06-16 09:39:12 +02:00
Andrew Eisenberg
f9a415c377 Merge pull request #2516 from github/aeisenberg/modernize
Modernize query packs
2023-06-15 08:01:22 -07:00
Koen Vlaswinkel
539284b902 Merge pull request #2511 from github/koesie10/show-and-log-without-vscode
Make the showAndLog family of functions usable without the `vscode` module
2023-06-15 09:29:18 +02:00
Andrew Eisenberg
244bc3bdab Modernize query packs
Remove legacy `libraryPathDependencies`. We are making some
changes internally that will cause legacy packs with lock
files to throw an error.
2023-06-14 20:56:45 +00:00
Robert
5cbb7b49d7 Update QueryDiscovery to use FilePathDiscovery and QueryPackDiscovery 2023-06-14 17:30:40 +01:00
Robert
a9d59aecb8 Add QueryPackDiscovery 2023-06-14 17:30:37 +01:00
Robert
17b5e000f8 Add FilePathDiscovery 2023-06-14 17:30:33 +01:00
Robert
790c33c661 Add silent arg to resolveLibraryPath 2023-06-14 16:09:42 +01:00
Robert
51b94e3fed Add FilePathSet 2023-06-14 16:09:42 +01:00
Robert
b0441956df Remove the update method from the Discovery class
See https://github.com/github/vscode-codeql/pull/2490#discussion_r1226437598
for more explanation. This will make the class more useful for future usecases
where we don't want the behaviour of only calling update when there isn't
another refresh scheduled. I also think it doesn't negatively affect other
users such as the query test discovery. The effect should be that we'll see
more updates to the UI. These updates will get overwritten quickly, but they
are all genuine snapshots of the filesystem at the point the discovery process
ran, so they aren't incorrect, or aren't more incorrect than continuing to show
the old state before any discovery ran.
2023-06-14 16:09:42 +01:00
Koen Vlaswinkel
8803433fa4 Merge pull request #2515 from github/version/bump-to-v1.8.7
Bump version to v1.8.7
2023-06-14 14:53:24 +02:00
github-actions[bot]
ab448e51d5 Bump version to v1.8.7 2023-06-14 12:20:00 +00:00
Koen Vlaswinkel
2905f5340a Merge pull request #2514 from github/v1.8.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
v1.8.6
2023-06-14 13:51:21 +02:00
Koen Vlaswinkel
170fce8815 v1.8.6 2023-06-14 13:17:03 +02:00
Koen Vlaswinkel
7a76e20841 Move showAndLogExceptionWithTelemetry out of vscode directory 2023-06-14 11:59:14 +02:00
Koen Vlaswinkel
d03d355513 Add telemetry as argument to showAndLogExceptionWithTelemetry 2023-06-14 11:19:50 +02:00
Koen Vlaswinkel
959728d1ca Add telemetry to App 2023-06-14 11:19:46 +02:00
Koen Vlaswinkel
fefb2f6694 Add AppTelemetry interface 2023-06-14 11:19:16 +02:00
Koen Vlaswinkel
08786055e3 Move telemetry to common/vscode 2023-06-14 11:19:10 +02:00
Koen Vlaswinkel
108d5268b0 Fix tests mocking showAndLog functions 2023-06-14 11:17:49 +02:00
Koen Vlaswinkel
fcbe3bea1e Use app logger instead of extLogger where possible
To increase the use of the `app` logger, this replaces the direct use of
`extLogger` by the `app.logger` where possible. This should not change
the behavior since the `extLogger` is the logger used by the `app`.
2023-06-14 11:17:37 +02:00
Koen Vlaswinkel
2b85690c68 Change logger on app to NotificationLogger 2023-06-14 11:17:18 +02:00
Koen Vlaswinkel
67c081921b Move show and log functions to common
This moves the `showAndLog` family of functions to the `common/logging`
directory. It explicitly moves the `showAndLogExceptionWithTelemetry`
function to the `common/vscode/logging.ts` file because it still has a
dependency on the `telemetryListener`, which depends on the `vscode`
module.
2023-06-14 11:17:17 +02:00
Koen Vlaswinkel
9ff2d568c8 Change showAndLog functions to take NotificationLogger 2023-06-14 11:16:52 +02:00
Koen Vlaswinkel
d54ee0c0e5 Merge pull request #2508 from github/koesie10/split-helpers-4
Split helpers.ts [Part 4]
2023-06-14 11:15:04 +02:00
Nora
fa7d85ea58 Merge pull request #2512 from github/nora/remove-code-search-flag
Remove code search feature flag
2023-06-14 10:41:19 +02:00
Koen Vlaswinkel
179942680e Merge pull request #2506 from github/koesie10/split-helpers-3
Move show and log functions out of helpers
2023-06-14 10:28:43 +02:00
Koen Vlaswinkel
f67f53dd68 Merge remote-tracking branch 'origin/main' into koesie10/split-helpers-3 2023-06-14 09:30:41 +02:00
Koen Vlaswinkel
c6c56284ff Merge pull request #2505 from github/koesie10/split-helpers-2
Split `helpers.ts` [Part 2]
2023-06-14 09:29:58 +02:00
Nora
afa2f426b8 Update Changelog 2023-06-13 14:55:14 +00:00
Nora
fd381640a0 Remove feature flag 2023-06-13 14:55:02 +00:00
Robert
019e3772ef Merge pull request #2510 from github/robertbrignull/use_contains_path
Use containsPath where possible
2023-06-13 10:19:01 +01:00
Nora
a03b3dca86 Merge pull request #2507 from github/nora/remove-1000-list-limit
Remove limit of 1000 repos per list
2023-06-13 09:57:16 +02:00
Robert
cad651d6bd Use containsPath where possible 2023-06-12 16:33:35 +01:00
Robert
400bde6e03 Merge pull request #2509 from github/robertbrignull/contains_path
Fix containsPath for paths that share a prefix
2023-06-12 16:17:39 +01:00
Robert
3a9fa42790 Merge branch 'main' into robertbrignull/contait push origin robertbrignull/contains_pathns_path 2023-06-12 15:39:47 +01:00
Robert
c920b7e49e Remove explicit check for windows 2023-06-12 15:16:43 +01:00
Koen Vlaswinkel
ccf38a98fb Move incorrectly named helpers.test.ts 2023-06-12 15:55:10 +02:00
Koen Vlaswinkel
00240e56f4 Rename helpers.ts to tmp-dir.ts 2023-06-12 15:55:10 +02:00
Koen Vlaswinkel
1096ed8bf5 Move upgradesTmpDir out of helpers 2023-06-12 15:55:10 +02:00
Koen Vlaswinkel
61ac19f715 Move createTimestampFile out of helpers 2023-06-12 15:55:09 +02:00
Koen Vlaswinkel
9a32556b4d Move query language functions out of helpers 2023-06-12 15:55:09 +02:00
Koen Vlaswinkel
2cd88cecde Move tryGetQueryMetadata out of helpers 2023-06-12 15:55:09 +02:00
Robert
6dbbd22c0a Merge pull request #2497 from github/robertbrignull/cleanup_workspace_folders
Remove workspaceFolders from app because it turned out not to be useful
2023-06-12 14:50:00 +01:00
Robert
aa4c459cdd Use relative instead of startsWith to handle paths with the same prefix 2023-06-12 14:41:31 +01:00
Robert
f7c1f06354 Add another test case for case insensitivity on windows 2023-06-12 14:41:31 +01:00
Robert
6e3d0147c9 Add test cases for paths with the same prefix 2023-06-12 14:41:31 +01:00
Robert
300503e1c9 Remove platform arg as it's never not the process.platform 2023-06-12 14:41:31 +01:00
Robert
bdd2319297 Update docs to mention about paths being equal 2023-06-12 14:41:21 +01:00
Nora
4c16888624 Remove limit of 1000 to repo lists 2023-06-12 12:46:40 +00:00
Koen Vlaswinkel
d71f210647 Merge pull request #2504 from github/koesie10/split-helpers
Split helpers.ts file
2023-06-12 14:42:32 +02:00
Koen Vlaswinkel
c16d363b08 Move show and log functions out of helpers 2023-06-12 14:24:04 +02:00
Robert
8b1e49c6c0 Use more descriptive names 2023-06-12 12:50:01 +01:00
Koen Vlaswinkel
50f958067c Move prepareCodeTour to separate file 2023-06-12 12:12:18 +02:00
Koen Vlaswinkel
7f3e9607aa Move dialog functions to separate file 2023-06-12 12:09:36 +02:00
Koen Vlaswinkel
0cfbf0cb2a Move workspace folder functions to separate file 2023-06-12 12:02:45 +02:00
Koen Vlaswinkel
bfead07592 Move walkDirectory to pure files file 2023-06-12 11:13:57 +02:00
Koen Vlaswinkel
8c98401efe Move isQueryLanguage to query language file 2023-06-12 11:11:47 +02:00
Koen Vlaswinkel
a4e4c67bf2 Move getInitialQueryContents to separate file 2023-06-12 11:10:23 +02:00
Koen Vlaswinkel
754fa675f9 Move db contents heuristics to separate file 2023-06-12 11:07:25 +02:00
Koen Vlaswinkel
b0c18b3300 Move unused languageToDbScheme 2023-06-12 11:01:42 +02:00
Koen Vlaswinkel
706c6b8a7a Move qlpacks helpers to separate file 2023-06-12 10:59:42 +02:00
Nora
fe21a21ca2 Merge pull request #2501 from github/nora/polish-code-search-copy
Code search: Use correct link and text
2023-06-12 07:44:25 +02:00
Koen Vlaswinkel
bca8e8fdb9 Merge pull request #2503 from github/koesie10/move-interface
Move interface.ts to local-queries/results-view.ts
2023-06-09 17:11:51 +02:00
Koen Vlaswinkel
5259456fe8 Merge pull request #2502 from github/koesie10/move-interface-utils
Move interface-utils to local-queries/webview
2023-06-09 17:11:39 +02:00
Robert
adc64c37c5 Merge pull request #2498 from github/robertbrignull/queries-panel-codeowners
Mark the queries panel as owned by secexp
2023-06-09 15:27:29 +01:00
Koen Vlaswinkel
2f1a3e95bf Move interface.ts to local-queries/results-view.ts 2023-06-09 16:24:32 +02:00
Koen Vlaswinkel
00b32376d5 Move interface-utils to local-queries/webview 2023-06-09 16:20:30 +02:00
Koen Vlaswinkel
dfef8104c8 Merge pull request #2485 from github/koesie10/move-location-utils
Move functions for resolving locations
2023-06-09 15:59:48 +02:00
Nora
f0a8f79c2e Use correct link and test 2023-06-09 13:25:39 +00:00
Charis Kyriakou
d485ff0015 Deal with no predictions gracefully (#2499) 2023-06-09 13:17:26 +01:00
Robert
7b5fb5b3aa Mark the queries panel as owned by secexp 2023-06-09 10:49:32 +01:00
Robert
eb938034fb Pass in just the environment instead of full app 2023-06-09 10:26:50 +01:00
Robert
a19c40bd66 Avoid using app.createEventEmitter 2023-06-09 10:24:07 +01:00
Koen Vlaswinkel
6b8169c479 Merge pull request #2494 from github/dependabot/npm_and_yarn/extensions/ql-vscode/eslint-plugin-jest-dom-5.0.1
Bump eslint-plugin-jest-dom from 4.0.2 to 5.0.1 in /extensions/ql-vscode
2023-06-09 11:19:26 +02:00
Koen Vlaswinkel
71ac6c73cd Merge pull request #2496 from github/dependabot/npm_and_yarn/extensions/ql-vscode/xml2js-and-vscode/vsce-and-azure/core-http-0.5.0
Bump xml2js, @vscode/vsce and @azure/core-http in /extensions/ql-vscode
2023-06-09 11:19:15 +02:00
Koen Vlaswinkel
8b3ca1035c Merge pull request #2495 from github/koesie10/remove-xml2js-types
Remove `@types/xml2js` dependency
2023-06-09 11:18:51 +02:00
Robert
f0cf4a0105 Remove onDidChangeWorkspaceFolders from app 2023-06-09 10:18:22 +01:00
Robert
1bd78649e7 Remove workspaceFolders from app 2023-06-09 09:57:23 +01:00
dependabot[bot]
f2ab949417 Bump xml2js, @vscode/vsce and @azure/core-http in /extensions/ql-vscode
Bumps [xml2js](https://github.com/Leonidas-from-XIV/node-xml2js) to 0.5.0 and updates ancestor dependencies [xml2js](https://github.com/Leonidas-from-XIV/node-xml2js), [@vscode/vsce](https://github.com/Microsoft/vsce) and [@azure/core-http](https://github.com/Azure/azure-sdk-for-js). These dependencies need to be updated together.


Updates `xml2js` from 0.4.23 to 0.5.0
- [Commits](https://github.com/Leonidas-from-XIV/node-xml2js/commits/0.5.0)

Updates `@vscode/vsce` from 2.15.0 to 2.19.0
- [Release notes](https://github.com/Microsoft/vsce/releases)
- [Commits](https://github.com/Microsoft/vsce/compare/v2.15.0...v2.19.0)

Updates `@azure/core-http` from 2.2.7 to 2.3.2
- [Release notes](https://github.com/Azure/azure-sdk-for-js/releases)
- [Changelog](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/Changelog-for-next-generation.md)
- [Commits](https://github.com/Azure/azure-sdk-for-js/compare/@azure/core-http_2.2.7...@azure/core-http_2.3.2)

---
updated-dependencies:
- dependency-name: xml2js
  dependency-type: indirect
- dependency-name: "@vscode/vsce"
  dependency-type: direct:development
- dependency-name: "@azure/core-http"
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-09 08:44:18 +00:00
Koen Vlaswinkel
7869225cf1 Remove @types/xml2js
We don't seem to be using this dependency anymore, so we can remove it.
2023-06-09 10:38:19 +02:00
Koen Vlaswinkel
95828cdc61 Add @testing-library/dom as devDependency 2023-06-09 10:35:05 +02:00
Andrew Eisenberg
afb490b64b Merge pull request #2441 from github/RasmusWL/codeql-executable-wording
Expand description for `codeQL.cli.executablePath`
2023-06-09 01:19:09 -07:00
dependabot[bot]
c3299f92c4 Bump eslint-plugin-jest-dom from 4.0.2 to 5.0.1 in /extensions/ql-vscode
Bumps [eslint-plugin-jest-dom](https://github.com/testing-library/eslint-plugin-jest-dom) from 4.0.2 to 5.0.1.
- [Release notes](https://github.com/testing-library/eslint-plugin-jest-dom/releases)
- [Commits](https://github.com/testing-library/eslint-plugin-jest-dom/compare/v4.0.2...v5.0.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-08 13:58:25 +00:00
Koen Vlaswinkel
dc9f648452 Merge pull request #2470 from github/dependabot/npm_and_yarn/extensions/ql-vscode/faker-js/faker-8.0.2
Bump @faker-js/faker from 7.5.0 to 8.0.2 in /extensions/ql-vscode
2023-06-08 14:52:15 +02:00
Shati Patel
ee11805060 Update changelog (MRVA -> variant analysis) (#2492) 2023-06-08 12:47:59 +00:00
Koen Vlaswinkel
a24f640dc0 Replace faker.datatype.hexadecimal by faker.string.hexadecimal 2023-06-08 13:47:03 +02:00
Koen Vlaswinkel
4d2a935e80 Merge pull request #2469 from github/dependabot/npm_and_yarn/extensions/ql-vscode/css-loader-6.8.1
Bump css-loader from 3.1.0 to 6.8.1 in /extensions/ql-vscode
2023-06-08 12:57:59 +02:00
Koen Vlaswinkel
bbffc16b64 Replace faker.random.word by faker.word.sample 2023-06-08 12:50:42 +02:00
Koen Vlaswinkel
a4f90b7197 Replace faker.datatype.number by faker.number.int 2023-06-08 12:48:48 +02:00
Charis Kyriakou
286018ccea Colour draft modeled methods with orange (#2491) 2023-06-08 11:33:51 +01:00
Koen Vlaswinkel
d2df162afd Switch to Webpack asset modules
css-loader 6 deprecates the use of `file-loader`. As a replacement,
we can use asset modules which generates very similar results. This is a
fairly simple change, and this makes fonts work again.

See: https://github.com/webpack-contrib/css-loader/releases/tag/v6.0.0
See: https://webpack.js.org/guides/asset-modules/
2023-06-08 11:38:20 +02:00
dependabot[bot]
a73c39a29a Bump css-loader from 3.1.0 to 6.8.1 in /extensions/ql-vscode
Bumps [css-loader](https://github.com/webpack-contrib/css-loader) from 3.1.0 to 6.8.1.
- [Release notes](https://github.com/webpack-contrib/css-loader/releases)
- [Changelog](https://github.com/webpack-contrib/css-loader/blob/master/CHANGELOG.md)
- [Commits](https://github.com/webpack-contrib/css-loader/compare/v3.1.0...v6.8.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-08 09:31:26 +00:00
dependabot[bot]
5113b04b36 Bump @faker-js/faker from 7.5.0 to 8.0.2 in /extensions/ql-vscode
Bumps [@faker-js/faker](https://github.com/faker-js/faker) from 7.5.0 to 8.0.2.
- [Release notes](https://github.com/faker-js/faker/releases)
- [Changelog](https://github.com/faker-js/faker/blob/next/CHANGELOG.md)
- [Commits](https://github.com/faker-js/faker/compare/v7.5.0...v8.0.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-08 09:30:06 +00:00
Koen Vlaswinkel
8db5c6de65 Merge pull request #2488 from github/koesie10/fix-locale-lower-case
Add locale to `toLocaleLowerCase` calls
2023-06-08 11:14:07 +02:00
Koen Vlaswinkel
a46a8d06ec Merge pull request #2489 from github/koesie10/add-cli-tests-timeout
Add timeout to CLI tests
2023-06-08 09:45:30 +02:00
Koen Vlaswinkel
3569c77626 Add timeout to CLI tests
It seems like some CLI tests are hanging and only completing after 6
hours when they run into the default timeout. This updates the timeout
to 30 minutes. All CLI tests should complete in 30 minutes, so this
should ensure that they are cancelled when they are stuck.
2023-06-07 15:41:42 +02:00
Koen Vlaswinkel
0b22a6f34d Add locale to toLocaleLowerCase calls 2023-06-07 14:51:03 +02:00
Anders Starcke Henriksen
7c47a99805 Merge pull request #2486 from github/starcke/candidate-selection
Tweak candidate selection
2023-06-07 14:16:50 +02:00
Anders Starcke Henriksen
15c2a86725 Use Argument[this] instead of Argument[-1] 2023-06-07 13:14:31 +02:00
Anders Starcke Henriksen
e14b4c3040 Update extensions/ql-vscode/src/data-extensions-editor/auto-model.ts
Co-authored-by: Koen Vlaswinkel <koesie10@users.noreply.github.com>
2023-06-07 11:56:46 +02:00
Anders Starcke Henriksen
e3f192b76d Add new test. 2023-06-07 11:24:06 +02:00
Anders Starcke Henriksen
222c0d72bd Update tests. 2023-06-07 11:24:06 +02:00
Anders Starcke Henriksen
895c22ea85 Fix supported. 2023-06-07 11:24:02 +02:00
Nora
805d71286f Merge pull request #2487 from github/version/bump-to-v1.8.6
Bump version to v1.8.6
2023-06-07 10:18:17 +02:00
github-actions[bot]
2e01836f55 Bump version to v1.8.6 2023-06-06 15:16:08 +00:00
Koen Vlaswinkel
bca8885513 Merge pull request #2484 from github/koesie10/move-webview-html
Move Webview HTML generation out of `interface-utils.ts`
2023-06-06 17:14:09 +02:00
Anders Starcke Henriksen
76fb55f918 Tweak candidate selection:
- At most 6 usages.
- Send -1 for `this` argument.
- Do not send only some arguments for candidate or sample.
2023-06-06 16:49:50 +02:00
Nora
999b24a40d Merge pull request #2466 from github/v1.8.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
v1.8.5
2023-06-06 15:15:28 +02:00
Nora
e612c8efcc Update Changelog 2023-06-06 12:23:36 +00:00
Koen Vlaswinkel
ba9f5e35cb Remove dependency on interface types from jumpToLocation 2023-06-06 11:27:57 +02:00
Koen Vlaswinkel
aa87fa8cda Move functions for resolving locations 2023-06-06 11:25:43 +02:00
Koen Vlaswinkel
a98e31fffb Merge pull request #2483 from github/koesie10/fix-locale-compare
Fix remaining `localeCompare` without locale set
2023-06-06 11:14:28 +02:00
Koen Vlaswinkel
461ff9bd21 Move Webview HTML generation out of interface-utils.ts
This moves the Webview HTML generation used by `AbstractWebview` out of
`interface-utils.ts` and into a new file `webview-html.ts` in the
`common/vscode` directory.
2023-06-06 11:12:05 +02:00
Koen Vlaswinkel
a678f8b3bc Fix remaining localeCompare without locale set 2023-06-06 10:55:15 +02:00
Nora
cc9fb826b3 v1.8.5 2023-06-06 08:48:01 +00:00
Nora
a7a24fc0e9 Merge pull request #2476 from github/nora/use-code-search-api
Code search: use code search api
2023-06-06 10:29:43 +02:00
Koen Vlaswinkel
10bd774bcb Merge pull request #2479 from github/koesie10/validate-scoped-pack-name
Only allow scoped extension pack names
2023-06-06 10:09:11 +02:00
Robert
ead138ee13 Merge pull request #2480 from github/robertbrignull/app-environment
Add EnvironmentContext so common code can do localisation
2023-06-06 08:44:12 +01:00
Nora
945594d47a Adjust error response wording 2023-06-05 15:55:18 +00:00
Nora
876b92aa98 Move code search api call to its own file 2023-06-05 15:42:10 +00:00
Nora
b47006129d Move octokit initialization to db panel to send log messages to the user 2023-06-05 15:42:10 +00:00
Nora
fef28806b1 Use showAndLogWarning to surface rateLimit 2023-06-05 15:42:10 +00:00
Nora
5467c50395 Implement throttling 2023-06-05 15:42:10 +00:00
Nora
6da1f936dd Add no-language option 2023-06-05 15:42:10 +00:00
Robert
b722fb4d70 Convert to using a getter for AppEnvironmentContext.language 2023-06-05 14:04:27 +01:00
Nora
9672a0b1f1 Merge pull request #2478 from github/nora/code-search-feature-flag
Protect codeSearch feature for now
2023-06-05 14:33:09 +02:00
Robert
0e65c79c92 Pass in app.environment instead of vscode.env 2023-06-05 13:27:17 +01:00
Nora
897ad5bb57 Add 'codeSearch' feature flag 2023-06-05 11:55:50 +00:00
Robert
1d80cbb496 Add EnvironmentContext to App 2023-06-05 11:50:50 +01:00
Koen Vlaswinkel
b0d45cefe9 Only allow scoped extension pack names
When packaging an extension pack, unscoped extension pack names are not
allowed and calling `codeql pack bundle` will fail with an error. This
command will be called when running a variant analysis, so these packs
will not work for a variant analysis.

To improve the user experience, we now only allow scoped extension pack
names. This means that the user will now have to enter a scope when
creating a new extension pack.
2023-06-05 12:30:20 +02:00
Shati Patel
af9af99f09 Queries panel: display the query language in the UI (#2472) 2023-06-05 11:07:59 +01:00
Koen Vlaswinkel
0d390aa984 Merge pull request #2468 from github/koesie10/remove-ignore-source-archive-option
Remove `ignoreSourceArchive` option from databases
2023-06-05 09:41:14 +02:00
Andrew Eisenberg
610a349f26 Merge pull request #2405 from Marcono1234/simpler-location-url
Simplify location URLs if start and end line are the same
2023-06-02 11:07:07 -07:00
Andrew Eisenberg
afbf762d22 Merge branch 'main' into simpler-location-url 2023-06-02 10:47:23 -07:00
Charis Kyriakou
c96fd817b3 Allow unclassified methods to be marked as neutral (#2477) 2023-06-02 15:08:29 +00:00
Charis Kyriakou
134c4405f9 Handle 429 from auto-model service (#2474) 2023-06-02 12:51:40 +00:00
Koen Vlaswinkel
7250e82055 Merge pull request #2421 from github/koesie10/data-extension-editor-provenance
Add provenance support to data extensions editor
2023-06-02 14:13:40 +02:00
Koen Vlaswinkel
4ef520dc10 Merge pull request #2407 from github/koesie10/query-language
Use `QueryLanguage` type for representing query languages
2023-06-02 14:13:04 +02:00
Koen Vlaswinkel
cae72396d3 Merge pull request #2416 from github/koesie10/resolve-data-extensions-editor-queries
Resolve queries instead of hardcoding the path
2023-06-02 13:45:55 +02:00
Koen Vlaswinkel
e7ef449874 Add support for auto-model provenance 2023-06-02 12:21:04 +02:00
Koen Vlaswinkel
1cc77c0a26 Merge remote-tracking branch 'origin/main' into koesie10/data-extension-editor-provenance 2023-06-02 12:09:23 +02:00
Koen Vlaswinkel
c1edd08662 Remove unnecessary export on resolveQueries 2023-06-02 12:07:41 +02:00
Koen Vlaswinkel
96a28100b7 Merge remote-tracking branch 'origin/main' into koesie10/resolve-data-extensions-editor-queries 2023-06-02 12:06:18 +02:00
Koen Vlaswinkel
98844769a9 Merge remote-tracking branch 'origin/main' into koesie10/query-language 2023-06-02 12:03:16 +02:00
Nora
12615f19f8 Merge pull request #2473 from github/nora/move-cached-operation-to-common
Move CachedOperation to language-support contextual
2023-06-02 11:34:22 +02:00
Nora
b2adbf63eb Move file to language-support/contextual 2023-06-02 08:33:09 +00:00
Koen Vlaswinkel
f115412cec Merge branch 'main' into koesie10/remove-ignore-source-archive-option 2023-06-02 10:16:34 +02:00
Koen Vlaswinkel
26d27f832e Merge pull request #2467 from github/koesie10/fix-neutral-definition
Fix neutral definition for CodeQL 2.13.3
2023-06-02 09:46:39 +02:00
Andrew Eisenberg
f5c96025cb Merge pull request #2461 from aibaars/selected-line-column
View CFG: export selected line and column position
2023-06-01 10:15:54 -07:00
Andrew Eisenberg
51be504f6d Merge branch 'main' into selected-line-column 2023-06-01 08:07:18 -07:00
Koen Vlaswinkel
831b2499a2 Merge branch 'main' into koesie10/fix-neutral-definition 2023-06-01 16:59:31 +02:00
github-actions[bot]
cf343785a7 Bump CLI version from v2.13.1 to v2.13.3 for integration tests (#2465)
Co-authored-by: github-actions[bot] <github-actions@github.com>
2023-06-01 15:57:18 +01:00
Koen Vlaswinkel
0e47709d10 Remove ignoreSourceArchive option from databases
This option was used to ignore source archives for `.testproj`
databases. It is only set to `true` or `false` when creating the
database and could not be changed, so I don't think we need this option.
It can simply be derived from the database URI. This simplifies handling
of databases a bit.
2023-06-01 15:32:30 +02:00
Koen Vlaswinkel
2b915b82e4 Fix neutral definition for CodeQL 2.13.3
In CodeQL 2.13.3, the definition of the neutralModel predicate has
changed to include the `kind`. This updates the definition of the
data extensions editor to match the new definition.

One caveat is that when selecting a `kind` other than `summary`, the
method will not be shown as supported. This is because a
`NeutralCallable` only calls into `neutralSummaryElement`. This matches
the previous behavior because setting the `kind` to `source` or `sink`
only says that the method is either not a source or not a sink, but not
both. Only `summary` fully models the method.

See: https://github.com/github/codeql/pull/12931
See: ff78ac98d2/java/ql/lib/semmle/code/java/dataflow/internal/FlowSummaryImpl.qll (L338)
See: ff78ac98d2/java/ql/lib/semmle/code/java/dataflow/internal/FlowSummaryImplSpecific.qll (L160)
2023-06-01 14:59:47 +02:00
Koen Vlaswinkel
2f61cfe693 Merge pull request #2457 from github/koesie10/auto-model-usages-sarif
Retrieve external API usage snippets using SARIF
2023-06-01 11:28:42 +02:00
Shati Patel
5387546e93 Don't log the resolve queries CLI command (#2454) 2023-06-01 09:49:35 +01:00
Koen Vlaswinkel
dd268af9e9 Use type in auto model usages query file
Co-authored-by: Charis Kyriakou <charisk@users.noreply.github.com>
2023-06-01 10:47:16 +02:00
Robert
bc342022cb Merge pull request #2464 from github/robertbrignull/invocation-rate-limiter
Move the invocation rate limiter class out of helpers.ts
2023-05-31 16:45:17 +01:00
Robert
50c46b603a Remove MockGlobalStorage 2023-05-31 16:21:28 +01:00
Nora
157210ffc5 Merge pull request #2439 from github/nora/search-prompt
Feed code search results into variant analysis repo lists
2023-05-31 17:08:44 +02:00
Robert
0b6bcfdfd6 Merge pull request #2459 from github/robertbrignull/discovery-logging
Avoid vscode reference rfom discovery.ts
2023-05-31 15:12:43 +01:00
Robert
9b84e0f831 "Fix" distribution tests 2023-05-31 14:59:23 +01:00
Robert
e7a5def15f Merge pull request #2462 from github/robertbrignull/cached-operation
Move CachedOperation to a new file
2023-05-31 14:55:52 +01:00
Robert
1f6d8f215e Merge branch 'main' into robertbrignull/discovery-logging 2023-05-31 14:53:56 +01:00
Koen Vlaswinkel
c017530410 Fix incorrect order in BQRS unit test 2023-05-31 15:20:53 +02:00
Koen Vlaswinkel
c654bfa4c4 Add some comments for the auto model usages query 2023-05-31 15:20:53 +02:00
Koen Vlaswinkel
bce097d939 Create type for usage snippets by signature 2023-05-31 15:20:53 +02:00
Koen Vlaswinkel
1920a2c6b4 Remove use of Pick in auto model usages query 2023-05-31 15:20:53 +02:00
Robert
00bd7b7d3e Merge pull request #2458 from github/robertbrignull/common-vscode
Make assert-pure.ql ignore all /vscode/ directories
2023-05-31 14:09:39 +01:00
Robert
6b4726bc2b Move InvocationRateLimiter to common 2023-05-31 13:47:59 +01:00
Robert
79dccaa12f Pass in a Memento instead of a full ExtensionContext 2023-05-31 13:47:59 +01:00
Robert
b9c0f2bc14 Move InvocationRateLimiter to a separate file 2023-05-31 13:47:59 +01:00
Arthur Baars
7c47cf0968 View CFG: export selected line and column position
Fixes: #2456
2023-05-31 14:30:37 +02:00
Robert
d30e58b2cb Merge pull request #2453 from github/robertbrignull/refresh-promise
Add ability to await the discovery refresh promise
2023-05-31 13:29:35 +01:00
Nora
0739c46fed Add comments to gh api client and fix total number of returned repos 2023-05-31 11:30:31 +00:00
Nora
42436e623b Add JSDoc to db config store 2023-05-31 11:30:00 +00:00
Robert
8badc1c407 Merge pull request #2460 from github/robertbrignull/selection-commond-vscode
Move selection-commands.ts to be in the vscode directory
2023-05-31 12:27:17 +01:00
Robert
56d6f19365 Move CachedOperation to a new file 2023-05-31 11:57:26 +01:00
Koen Vlaswinkel
a4d875af8d Fix typo 2023-05-31 12:33:51 +02:00
Robert
b7a7329aff Move selection-commands.ts to be in the vscode directory 2023-05-31 11:33:12 +01:00
Koen Vlaswinkel
a117e09796 Use a single SARIF-compatible query instead of two separate queries 2023-05-31 12:32:41 +02:00
Robert
a4a67856a5 Avoid vscode reference rfom discovery.ts 2023-05-31 11:26:25 +01:00
Robert
b8b378ffd4 Make assert-pure.ql ignore all /vscode/ directories 2023-05-31 10:59:50 +01:00
Robert
a0e6317559 Keep all updates of currentDiscoveryPromise in refresh 2023-05-31 10:45:36 +01:00
Robert
d2bb1b844e Fix comment to be more accurate 2023-05-31 10:45:36 +01:00
Robert
82766d1033 Rename: getCurrentRefreshPromise => waitForCurrentRefresh 2023-05-31 10:45:32 +01:00
Robert
81fb1264e4 Merge pull request #2455 from github/robertbrignull/import-path-problem
Expand assert-pure.ql to cover common and be a path-problem query
2023-05-31 09:15:54 +01:00
Nora
4087620bf5 Polish copy 2023-05-30 14:30:07 +00:00
Alexander Eyers-Taylor
22172d5d74 Add support for quick eval count to the query runner (#2417)
* Add support for quick eval count to the query runner

This only adds support internally to the query runner,
without any UI support.

* Fix some tests
2023-05-30 14:12:47 +01:00
Alexander Eyers-Taylor
af3be543f5 Cache MRVA queries correctly (#2435) 2023-05-30 14:12:26 +01:00
Koen Vlaswinkel
5c81671e67 Retrieve external API usage snippets using SARIF 2023-05-30 13:46:14 +02:00
Robert
c462bc0243 Use edges from select clause 2023-05-30 11:42:36 +01:00
Robert
e1894afb16 Extend ImportDeclaration instead of AstNode 2023-05-30 11:39:47 +01:00
Koen Vlaswinkel
5a66d6ff2d Merge pull request #2448 from github/koesie10/auto-model
Add initial implementation of auto-modeling
2023-05-30 12:19:22 +02:00
Koen Vlaswinkel
d27f3d2699 Remove incorrect explanations 2023-05-30 11:21:01 +02:00
Koen Vlaswinkel
695dc3f883 Improve sorting of input/output arguments 2023-05-30 11:17:52 +02:00
Koen Vlaswinkel
558f51b962 Add comment to parsePredictedClassifications method 2023-05-30 11:04:13 +02:00
Koen Vlaswinkel
2e29d0cda4 Fix incorrect signature reconstruction 2023-05-30 10:04:33 +02:00
Andrew Eisenberg
3b4f236426 Merge pull request #2440 from JarLob/patch-1
Retry results download if connection times out
2023-05-26 11:31:31 -07:00
Robert
b8770a2896 Convert assert-pure.ql to be a path-problem query 2023-05-26 16:28:40 +01:00
Andrew Eisenberg
e24377f9f3 Merge pull request #2446 from github/aeisenberg/use-orig-pack-name
Use the original pack name for generated pack
2023-05-26 08:12:01 -07:00
Andrew Eisenberg
deb268465f Fix failing test 2023-05-26 07:52:49 -07:00
Koen Vlaswinkel
f52ad04afe Improve parsing of predicted classifications 2023-05-26 16:18:59 +02:00
Koen Vlaswinkel
4b54e4f31f Use 20 candidates and 100 samples 2023-05-26 13:40:12 +02:00
Robert
1f4b19cd37 Add getCurrentRefreshPromise 2023-05-26 10:15:14 +01:00
Robert
9dd7476c90 Use refresh promise in tests 2023-05-26 10:15:14 +01:00
Robert
5405b1bf29 Convert refresh to return a promise 2023-05-26 10:15:13 +01:00
Robert
5a2cb8bc41 Convert launchDiscovery to use async 2023-05-26 10:14:19 +01:00
Robert
35a7eee3c0 Merge pull request #2449 from github/robertbrignull/queries-welcome
Add welcome text for the queries panel
2023-05-25 17:01:13 +01:00
Andrew Eisenberg
efabcaefe3 Update extensions/ql-vscode/src/variant-analysis/run-remote-query.ts
Co-authored-by: Koen Vlaswinkel <koesie10@users.noreply.github.com>
2023-05-25 08:30:24 -07:00
Robert
a27b0a469e Merge pull request #2447 from github/robertbrignull/QueryDiscovery-tests
Add integration tests of QueryDiscovery
2023-05-25 16:19:37 +01:00
Robert
472b1769c5 Update extensions/ql-vscode/test/vscode-tests/minimal-workspace/queries-panel/query-discovery.test.ts
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2023-05-25 15:38:49 +01:00
Koen Vlaswinkel
7bbba38cfb Merge pull request #2450 from github/koesie10/move-database-item-refresh
Extract `DatabaseItem.refresh` method to `DatabaseManager`
2023-05-25 16:32:01 +02:00
Koen Vlaswinkel
adcc3d0b39 Remove unnecessary if-statements before slice 2023-05-25 15:52:00 +02:00
Robert
8be2dd805b Use path.sep 2023-05-25 14:44:05 +01:00
Koen Vlaswinkel
09fc0f3040 Extract DatabaseItem.refresh to DatabaseManager
This moves the `refresh` method from `DatabaseItem` to `DatabaseManager`
and makes it private. This makes the `DatabaseItem` interface smaller
and more focused and ensures that `refresh` cannot be called from
outside of the `DatabaseManager`.
2023-05-25 15:03:30 +02:00
Koen Vlaswinkel
295a08f85a Use DatabaseItemImpl where possible in DatabaseManager
This will allow us to implement specific behavior on the
`DatabaseItemImpl` which is not available on the `DatabaseItem`. This
will allow us to make the surface area of the `DatabaseItem` smaller.
2023-05-25 14:36:38 +02:00
Robert
394b51f4f3 Add welcome text 2023-05-25 12:49:01 +01:00
Koen Vlaswinkel
a88e683ebf Add initial implementation of auto-modeling 2023-05-25 13:28:32 +02:00
Nora
250089a9e3 Renaming and smaller merge comments 2023-05-25 10:02:22 +00:00
Nora
2e12b8d756 Rename command from importCodeSearch to importFromCodeSearch 2023-05-25 09:11:37 +00:00
Robert
f236e65f68 Add integration tests of QueryDiscovery 2023-05-25 09:57:52 +01:00
Robert
301149fd32 Don't create array entry if workspace contains no queries 2023-05-25 09:57:52 +01:00
Koen Vlaswinkel
b8557d337c Merge pull request #2445 from github/koesie10/move-local-databases
Split up `local-databases.ts` file into multiple files
2023-05-25 09:30:23 +02:00
Andrew Eisenberg
b4506cf6e5 Use the original pack name for generated pack
Generated variant analysis packs will use the original name
of the pack that the query is located in. This is to support
some future work where we do extra validation of data extensions.

If the query is not in a pack, the default name is used.
2023-05-24 21:46:54 +00:00
Nora
49f3f5673d Show progress information when sending search api request 2023-05-24 16:26:08 +00:00
Robert
ff88a8d491 Merge pull request #2444 from github/robertbrignull/QueryTreeDataProvider-tests
Add tests of QueryTreeDataProvider
2023-05-24 16:25:08 +01:00
Koen Vlaswinkel
0707155603 Fix imports for tests 2023-05-24 17:08:00 +02:00
Koen Vlaswinkel
c004f18720 Remove outdated comment 2023-05-24 17:04:36 +02:00
Koen Vlaswinkel
6b9c3491ec Move local-databases.ts to local-databases/index.ts 2023-05-24 17:04:14 +02:00
Koen Vlaswinkel
d608c057a4 Remove unused getUpgradesDirectories function 2023-05-24 17:03:14 +02:00
Koen Vlaswinkel
60cfc311e5 Move DatabaseManager to separate file 2023-05-24 17:02:39 +02:00
Koen Vlaswinkel
59482c2b2c Move DatabaseChangedEvent to separate file 2023-05-24 17:00:52 +02:00
Koen Vlaswinkel
7888d210c4 Move DatabaseResolver to separate file 2023-05-24 16:58:29 +02:00
Koen Vlaswinkel
67983c64ca Move DatabaseContents to separate file 2023-05-24 16:55:31 +02:00
Koen Vlaswinkel
d02e53fbd2 Move DatabaseItemImpl to separate file 2023-05-24 16:53:59 +02:00
Koen Vlaswinkel
4bb4627d30 Move DatabaseItem to separate file 2023-05-24 16:52:53 +02:00
Koen Vlaswinkel
6331cddbfd Move DatabaseOptions to separate file 2023-05-24 16:51:38 +02:00
Robert
5d7a7237a3 Merge pull request #2443 from github/robertbrignull/query-constructor
Remove member variables that could be local variables
2023-05-24 14:34:06 +01:00
Nora
2b4e302e29 Surface truncated repos when a list hits 1000 items 2023-05-24 10:58:13 +00:00
Nora
d07b7c8c05 Add db manager test 2023-05-24 10:57:13 +00:00
Robert
27a88032f7 Add QueryTreeDataProvider tests 2023-05-24 11:42:23 +01:00
Robert
b9ce91cff9 Add a QueryDiscoverer interface to make testing QueryTreeDataProvider easier 2023-05-24 11:42:23 +01:00
Robert
9dee2a132e Remove member variables that could be local variables 2023-05-24 10:37:22 +01:00
jarlob
69f9ecc2f4 Delete unfinished downloads in case of retry 2023-05-24 11:25:50 +02:00
jarlob
9bd852a71b Add error message to logging. 2023-05-24 11:20:52 +02:00
Shati Patel
7ef35af68a Don't create "." directory in queries/tests tree view (#2442) 2023-05-24 10:15:34 +01:00
Nora
dd01832ebe Add no more than 1000 items to a list plus tests 2023-05-24 08:06:31 +00:00
Nora
f76d7bfd96 Use pagination for code search api call 2023-05-24 08:05:30 +00:00
Jaroslav Lobačevski
6f6c229ca3 Update extensions/ql-vscode/src/variant-analysis/variant-analysis-manager.ts 2023-05-23 23:24:18 +02:00
jarlob
65cfd851f2 Add logging 2023-05-23 23:21:51 +02:00
jarlob
32fb4e5db6 Move max retry to a constant 2023-05-23 22:47:13 +02:00
Rasmus Wriedt Larsen
c82ba1bdff Expand description for codeQL.cli.executablePath
To match what the code actually does.
2023-05-23 12:05:19 +02:00
Robert
f6b0ae2032 Merge pull request #2437 from github/robertbrignull/query-event-emitter
Use app.createEventEmitter in QueryDiscovery
2023-05-23 10:27:20 +01:00
Jaroslav Lobačevski
e964ce6713 Retry results download if connection times out 2023-05-23 10:51:46 +02:00
Robert
57f04fcae5 Add type to onDidChangeQueriesEmitter 2023-05-23 09:46:04 +01:00
Nora
4d9e8d98b4 Ask for user input and add response to list 2023-05-23 07:13:05 +00:00
Nora
fed6158615 Add GH client method to query search endpoint 2023-05-22 15:48:41 +00:00
Robert
da5d0d2a84 Use app.createEventEmitter in QueryDiscovery 2023-05-22 14:34:44 +01:00
Robert
73f359c0d0 Merge pull request #2434 from github/robertbrignull/disposable-event-emitter
Mark AppEventEmitter as disposable
2023-05-22 13:54:34 +01:00
Robert
f855d81526 Make sure DbManager is also disposed 2023-05-22 13:34:48 +01:00
Robert
73e41f8d61 Mark AppEventEmitter as disposable 2023-05-22 12:28:24 +01:00
Robert
018440f266 Merge pull request #2433 from github/robertbrignull/query-discovery
Hook queries panel up to real data
2023-05-22 11:51:25 +01:00
Koen Vlaswinkel
189a1328cd Merge pull request #2428 from github/koesie10/unsupported-cli-version-check
Add warning when using unsupported CLI version
2023-05-22 12:49:52 +02:00
Robert
cda3483b01 Use getOnDiskWorkspaceFoldersObjects early instead of getting all folders and filtering later 2023-05-22 10:51:32 +01:00
Robert
78f11397e2 Exclude src archives and other non-normal workspace folders 2023-05-22 10:42:47 +01:00
Robert
935c9b996f Don't include bad workspace roots in the list 2023-05-22 10:41:49 +01:00
Koen Vlaswinkel
e91e9d2654 Merge branch 'main' into koesie10/unsupported-cli-version-check 2023-05-22 11:37:58 +02:00
Koen Vlaswinkel
791a445342 Update copy of deprecation warning message
Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2023-05-22 11:37:42 +02:00
Koen Vlaswinkel
4ea1bb5f1c Merge pull request #2427 from github/koesie10/export-copy-selected-text
Update export/copy buttons copy when repositories are selected
2023-05-22 11:36:31 +02:00
Koen Vlaswinkel
8f3fe7412e Merge branch 'main' into koesie10/export-copy-selected-text 2023-05-22 10:52:01 +02:00
Robert
4e46d87a77 Use name from file tree instead of calculating from path 2023-05-19 17:09:21 +01:00
Robert
a8f8990793 Hook query discovery results up to query panel 2023-05-19 17:09:21 +01:00
Robert
0a534ae360 Add QueryDiscovery class 2023-05-19 17:09:21 +01:00
Robert
13f8f19339 Add resolveQueries to CodeQL CLI 2023-05-19 17:09:21 +01:00
Robert
a3f2b7b1ca Merge pull request #2431 from github/robertbrignull/app-workspace
Add workspace folders to App interface
2023-05-19 17:08:59 +01:00
Robert
6371356b4b Merge pull request #2432 from github/robertbrignull/tree-node-shared
Pull out node classes to shared location
2023-05-19 17:06:24 +01:00
Robert
a7f6401be7 Add workspace folders to App interface 2023-05-19 15:28:04 +01:00
Robert
a5af2f2e4b Pull out node classes to shared location 2023-05-19 13:04:58 +01:00
Andrew Eisenberg
3ebd13df57 Merge pull request #2425 from github/aeisenberg/truncated-log-msg
Ensure full stack traces are included in log messages
2023-05-17 08:51:35 -07:00
Koen Vlaswinkel
d28ee6dbf1 Merge branch 'main' into koesie10/unsupported-cli-version-check 2023-05-17 17:12:23 +02:00
Andrew Eisenberg
4ad3f7cb1f Merge branch 'main' into aeisenberg/truncated-log-msg 2023-05-17 08:08:34 -07:00
Andrew Eisenberg
0f1f00dfc8 Merge pull request #2424 from github/aeisenberg/update-changelog
Update changelog
2023-05-17 08:08:07 -07:00
Koen Vlaswinkel
3e9b4273c3 Update CHANGELOG 2023-05-17 16:55:11 +02:00
Robert
b47f018b69 Merge pull request #2426 from github/robertbrignull/open-on-click
Open query file on click
2023-05-17 15:54:11 +01:00
Koen Vlaswinkel
5a7f5c2ff1 Update CHANGELOG 2023-05-17 16:46:35 +02:00
Koen Vlaswinkel
ee2d78fbfc Add warning when using unsupported CLI version
This adds a warning when the user is using an unsupported version of the
CodeQL CLI. The warning is shown once per session, and only if the
version is older than the oldest supported version.
2023-05-17 16:25:06 +02:00
shati-patel
565a7a53e0 Only implement "open file" when you click a file node (not a folder) 2023-05-17 14:43:43 +01:00
Koen Vlaswinkel
0125d10ffb Take filtered state into account for buttons text
When the user filters the repositories, the buttons should reflect that
the results are filtered and that the user is not exporting or copying
all the results. If the user has selected repositories, the buttons
should still say that they are exporting selected results.
2023-05-17 15:08:55 +02:00
Koen Vlaswinkel
fa39bd1c2c Update export/copy buttons copy when repositories are selected
This changes the text of the export/copy buttons on a variant analysis
when at least one repository is selected. This makes it more clear that
the user is only exporting/copying the results of the selected
repositories.
2023-05-17 15:03:28 +02:00
Nora
1955086cb6 Add new command and add it to db panel 2023-05-17 12:11:45 +00:00
Robert
ec1fda21d0 Open query file on click 2023-05-17 12:16:09 +01:00
Robert
baea36561d Merge pull request #2423 from github/robertbrignull/query-tree-types
Simplify types around query panel
2023-05-17 10:39:43 +01:00
Andrew Eisenberg
55b65e33ad Update changelog 2023-05-16 14:51:03 -07:00
Andrew Eisenberg
276e2cfdcf Ensure full stack traces are included in log messages
Pass in the `fullMessage` to `internalShowAndLog` so that stack traces
aren't truncated.
2023-05-16 14:48:19 -07:00
Andrew Eisenberg
91c58f3618 Update changelog
For #2422.
2023-05-16 12:32:29 -07:00
Robert
1ceccc8b4d Avoid double-declaring fields that are inherited from TreeItem 2023-05-16 16:57:02 +01:00
Robert
b0371b5075 Simplify types on TreeDataProvider methods 2023-05-16 16:55:52 +01:00
Shati Patel
9ce95a3554 Queries panel: Expand/collapse child nodes (#2419) 2023-05-16 15:45:59 +00:00
Andrew Eisenberg
1dc83c5628 Merge pull request #2422 from github/aeisenberg/compare-view-quick-eval
Allow compare view to work with quick-eval
2023-05-16 08:41:12 -07:00
Koen Vlaswinkel
d00624cc85 Merge pull request #2420 from github/koesie10/cancel-monitor-on-404
Cancel monitoring variant analysis on 404 response
2023-05-16 11:57:26 +02:00
Koen Vlaswinkel
7d41cd7ae6 Rename editor-manual to manual
There is a defined list of of valid origin values for the provenance.
This does not include `editor`, so to make sure all values are valid we
use `manual` instead.

See ac1df4de91/java/ql/lib/semmle/code/java/dataflow/internal/FlowSummaryImpl.qll (L221-L229)
2023-05-16 10:23:21 +02:00
Andrew Eisenberg
4c33c06d55 Allow compare view to work with quick-eval
The compare view typically works by matching the results sets of
queries. It only allows the results sets of queries with identical
names to be compared.

Manually run queries use `#select` as the default result set. However,
quick eval queries use a different, generated, name. Therefore, these
two kinds of queries cannot be compared.

This commit changes the heuristics so that if there are no identical;y
named results sets, the first result set of each query that is prefixed
with `#` is used (this is the default result set).

It also makes a slightly nicer error message if there are no comparable
results sets.
2023-05-15 15:51:48 -07:00
Andrew Eisenberg
2d8c6905bf Merge branch 'main' into simpler-location-url 2023-05-15 10:10:42 -07:00
Koen Vlaswinkel
dc3966e113 Add provenance support to data extensions editor
The data extensions editor was always setting the `provenance` field of
MaD to `manual`. This will change the `provenance` to be either
`editor-manual` (for models which were added by the user),
`df-generated` (for models generated by the dataflow generator), and
`df-manual` (for models generated and then edited). This makes it easier
to trace the origin of a model.
2023-05-15 17:05:35 +02:00
Koen Vlaswinkel
2d2a1fb2d1 Add tests for variant analysis monitor 2023-05-15 15:41:15 +02:00
Koen Vlaswinkel
5b9ed39f4f Restart variant analysis monitor when reauthenticating 2023-05-15 15:08:32 +02:00
Koen Vlaswinkel
9e74ae0bbf Cancel monitoring variant analysis on 404 2023-05-15 15:08:32 +02:00
Koen Vlaswinkel
927a0f0691 Track currently monitoring variant analyses 2023-05-15 14:50:13 +02:00
Shati Patel
e9552df395 Create a basic tree view for the queries panel (#2418) 2023-05-15 11:10:51 +00:00
Koen Vlaswinkel
0f3b36cf87 Resolve queries instead of hardcoding the path
This will change the data extensions editor generator to resolve the
queries based on the `modelgenerator` tag. This removes the requirement
of having a `ql` folder in the workspace.

I chose to use the path instead of the `id` for now to avoid having to
resolve the query 4 times. This also avoids the need to map the language
names to the language ID in the tag (i.e. `csharp` -> `cs`).
2023-05-11 15:02:43 +02:00
Alexander Eyers-Taylor
3e6372d6fa Better error handling for unexpected query server termination. (#2404)
* Log stdout when servers are terminated with errors.

This logs the last stdout chunk (probabaly the last line) if things
went wrong. This can sometimes be useful for debugging.

It also prints the signal when killed by a signal
(rather than printing null)

* Restart/Abort the queryserver if the process dies.

This cancels any running tasks and gives a limited number of restarts.

* Update extensions/ql-vscode/src/codeql-cli/cli.ts

Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>

* Update extensions/ql-vscode/src/query-server/query-server-client.ts

Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>

---------

Co-authored-by: Andrew Eisenberg <aeisenberg@github.com>
2023-05-11 12:39:31 +01:00
Shati Patel
d0ca885e80 Move Discovery class into common folder (#2414) 2023-05-10 16:58:26 +00:00
Shati Patel
7fd984a7d0 Add a new blank "queries" panel (#2412) 2023-05-10 13:23:43 +01:00
Koen Vlaswinkel
00f4bc1fda Merge pull request #2411 from github/koesie10/remove-deprecated-url-parse
Remove deprecated use of `url.parse`
2023-05-10 11:09:06 +02:00
Koen Vlaswinkel
7dfa6f0f58 Merge pull request #2408 from github/koesie10/replace-deprecated-storage-path
Replace deprecated `storagePath` by `storageUri`
2023-05-10 11:08:52 +02:00
Koen Vlaswinkel
8a75399cb7 Merge branch 'main' into koesie10/remove-deprecated-url-parse 2023-05-10 09:30:57 +02:00
Koen Vlaswinkel
6e5188fbbe Replace Uri.parse by Uri.file 2023-05-10 09:30:53 +02:00
Koen Vlaswinkel
87be402a57 Improve unsupported language error message 2023-05-10 09:30:11 +02:00
Koen Vlaswinkel
ddbe3cdc2b Add test cases for containsPath 2023-05-09 14:20:15 +02:00
Koen Vlaswinkel
9290f57b62 Use normalized path for checking inclusion 2023-05-09 14:20:15 +02:00
Koen Vlaswinkel
a414213804 Replace deprecated storagePath by storageUri
This replaces access to the deprecated `storagePath` and
`globalStoragePath` to use `storageUri` and `globalStorageUri` instead.
2023-05-09 14:20:15 +02:00
Andrew Eisenberg
3ad006de92 Merge pull request #2401 from github/github-action/bump-cli
Bump CLI Version to v2.13.1 for integration tests
2023-05-09 03:58:53 -07:00
Shati Patel
e722bf3e0b Merge branch 'main' into github-action/bump-cli 2023-05-09 11:19:48 +01:00
Koen Vlaswinkel
9e7678de7a Remove deprecated use of url.parse
`url.parse` is deprecated and should be replaced by the WHATWG URL API,
so this makes that change. The `protocol` and `host` properties are
unchanged, so no other changes are needed.
2023-05-09 10:15:58 +02:00
Nora
a4f1f49506 Merge pull request #2409 from github/nora/split-codeql-goto-commands
Split codeQL.goto and codeQL.previewQueryHelp command
2023-05-08 17:00:21 +02:00
Nora
6deb04bd26 Split codeQL.previewQueryHelp command 2023-05-08 12:27:12 +00:00
Nora
b6df591329 Split codeQL.goto command 2023-05-08 12:15:07 +00:00
Koen Vlaswinkel
b20a65a3a7 Use QueryLanguage type for representing query languages
This will make both the `askForLanguage` and `findLanguage` functions
return a `QueryLanguage` instead of a `string`. This will make it harder
to make mistakes when using these functions.

There are also some other changes with regards to `QueryLanguage` such
that we never need to use `as QueryLanguage` explicitly anymore, except
for the new `isQueryLanguage` function. The only remaining place that I
know of where we're using a `string` to represent the `QueryLanguage`
is in a database item's language, but this is harder to change and may
be relied upon by language authors.
2023-05-08 13:56:11 +02:00
Marcono1234
788eb2b663 Simplify location URLs if start and end line are the same 2023-05-07 19:54:49 +02:00
Andrew Eisenberg
5084b32152 Merge branch 'main' into github-action/bump-cli 2023-05-05 16:07:33 -07:00
Robert
bf9eb2469b Merge pull request #2370 from github/robertbrignull/undefined_codeflows
Avoid crashing when SARIF file contains invalid thread flow locations
2023-05-05 17:43:58 +01:00
Robert
78c4cc17e9 Revert change to generation of blank lines 2023-05-05 17:19:07 +01:00
Andrew Eisenberg
62f44c9f56 Merge pull request #2403 from github/aeisenberg/fix-integration-tests 2023-05-05 07:24:53 -07:00
Andrew Eisenberg
e4a2760470 Run integration tests on 1.77.3
This avoids a bug on 1.78.0 on linux. See
https://github.com/github/vscode-codeql/issues/2402
2023-05-05 14:04:32 +00:00
github-actions[bot]
67bd603327 Bump CLI version from v2.13.0 to v2.13.1 for integration tests 2023-05-04 18:10:07 +00:00
Elena Tanasoiu
3a5a81a599 Merge pull request #2359 from github/yer-a-ternary-choice-query
Add configuration option to turn off skeleton pack generation
2023-05-04 08:53:17 +01:00
Robert
ecfa701159 Add tests of tryGetFilePath 2023-05-03 17:24:41 +01:00
Robert
a3a6784539 Rename to teyGetFilePath to fit other methods 2023-05-03 17:20:00 +01:00
Elena Tanasoiu
9515e3bdf8 Merge branch 'main' into yer-a-ternary-choice-query 2023-05-03 17:16:50 +01:00
Robert
e097bc13fa Merge pull request #2400 from github/robertbrignull/test-plan
Update the test plan and add non-MRVA cases
2023-05-03 17:12:35 +01:00
Robert
b199d9485d Merge branch 'main' into robertbrignull/undefined_codeflows 2023-05-03 17:11:31 +01:00
Elena Tanasoiu
cc8f1fd839 Merge branch 'main' into yer-a-ternary-choice-query 2023-05-03 16:08:37 +01:00
Elena Tanasoiu
a85d9d1434 Update comment 2023-05-03 15:07:24 +00:00
Shati Patel
71611e03fe Add config options for default sorting/filtering values in variant analysis results view (#2392) 2023-05-03 14:52:35 +00:00
Robert
ff20bceaa8 Add test cases of non-MRVA areas 2023-05-03 15:21:08 +01:00
Robert
5edbb1e96c Categorise test cases as mrva / local / general 2023-05-03 14:54:56 +01:00
Robert
bcd58181bf List pre-release checks in the order you'll want to do them 2023-05-03 14:50:02 +01:00
Robert
0f5df90ee5 Add files via upload 2023-05-03 14:41:55 +01:00
Robert
992d8dd4be Update MRVA tests in test-plan.md 2023-05-03 14:38:41 +01:00
Elena Tanasoiu
9ecb5035e0 Reduce options to "ask" and "never"
And update descriptions for them.
2023-05-03 12:14:23 +00:00
Robert
70a9ee6b1d Merge pull request #2399 from github/version/bump-to-v1.8.5
Bump version to v1.8.5
2023-05-03 12:35:59 +01:00
Robert
c53bebd1ce Merge pull request #2397 from github/robertbrignull/vscode-node-version
Add note about how to find VSCode node version
2023-05-03 12:21:55 +01:00
github-actions[bot]
ba9bfb57d1 Bump version to v1.8.5 2023-05-03 11:09:07 +00:00
Robert
ab9dd6a74f Merge pull request #2398 from github/v1.8.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.8.4
2023-05-03 11:23:03 +01:00
Robert
1c2fc37175 Remove changelog entry for #2385 2023-05-03 11:07:23 +01:00
Robert
29dd24c733 Update extensions/ql-vscode/CHANGELOG.md
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2023-05-03 11:05:26 +01:00
Robert
0f6714d9f6 Update extensions/ql-vscode/CHANGELOG.md
Co-authored-by: Shati Patel <42641846+shati-patel@users.noreply.github.com>
2023-05-03 11:05:14 +01:00
Robert
3102a177fb v1.8.4 2023-05-03 10:41:14 +01:00
Robert
2111ba01ac Add missing changelog entries 2023-05-03 10:40:33 +01:00
Robert
bb4060bcb6 Add note about how to find VSCode node version 2023-05-03 10:38:06 +01:00
Elena Tanasoiu
42320fcb87 Don't try to restore setting 2023-05-03 08:35:40 +00:00
Elena Tanasoiu
530ae689d3 Use strictly type choices for config setting 2023-05-03 07:58:35 +00:00
Elena Tanasoiu
c8b0b1c769 Use parent setting for "Create Query" config 2023-05-03 07:52:37 +00:00
Elena Tanasoiu
62597f1eb5 Remove extra space 2023-05-03 07:49:22 +00:00
Elena Tanasoiu
9c47a2718c Remove "default" option
Since it's not defining a real option, we can get rid of it.
2023-05-03 07:35:49 +00:00
Robert
e8403cf5d2 Reject all file URIs 2023-05-02 17:08:52 +01:00
Robert
5ff5384551 Simplify adding indentation 2023-05-02 16:01:18 +01:00
Koen Vlaswinkel
5360f03700 Merge pull request #2396 from github/koesie10/suppress-error-message
Suppress similar error messages when monitor MRVA
2023-05-02 16:55:02 +02:00
Koen Vlaswinkel
5f3466404c Add tests for suppressing error message 2023-05-02 16:19:53 +02:00
Koen Vlaswinkel
14eb7ff564 Merge pull request #2395 from github/koesie10/bqrs-use-select
Prefer `#select` result set over other result sets
2023-05-02 15:51:52 +02:00
Koen Vlaswinkel
e8ee43d955 Suppress similar error messages when monitor MRVA
This will suppress showing the same error message when monitoring the
variant analysis fails multiple times in a row. This is useful when
e.g. the internet is disconnected or the endpoint is non-functional for
any other reason.

This will show the error message at least once, and then only show it
if there has been a successful attempt in between or when the error
message is different. This should result in a much less noisy
experience.
2023-05-02 14:39:04 +02:00
Koen Vlaswinkel
36be323c89 Prefer #select result set over other result sets
For `@kind problem` queries, it seems like the BQRS contains four
result sets: `edges`, `nodes`, `subpaths`, and `#select`. The user is
probably interested in the results of `#select` since that contains the
direct result of the query. This changes the extraction of raw (BQRS)
results to always prefer `#select` over any other result set. If it
can't find a result set named `#select`, it will fall back to the first
result set in the BQRS like before.
2023-05-02 14:22:36 +02:00
Andrew Eisenberg
467e5ce452 Merge pull request #2385 from github/aeisenberg/no-cache-contextual
Add `codeQL.contextualQueries.disableCache`
2023-05-01 07:30:34 -07:00
Andrew Eisenberg
67110d7afb Merge pull request #2393 from github/aeisenberg/fix-cfg-viewer
Fix CFG viewer
2023-05-01 07:29:26 -07:00
Andrew Eisenberg
c650afbf6e Fix CFG viewer
After some bit of refactoring, the templates are no longer being
passed to the CFG viewer and this is preventing the viewer from
running.

This change fixes it.
2023-04-28 09:19:31 -07:00
Charis Kyriakou
c319d61dd5 Merge pull request #2391 from github/charisk/move-query-testing-files
Move query testing related files to /query-testing
2023-04-28 17:04:25 +01:00
Charis Kyriakou
331487dbab Move qltest-discovery.ts to /query-testing/qltest-discovery.ts 2023-04-28 13:51:48 +00:00
Charis Kyriakou
82abaa6e13 Move discovery.ts to /query-testing/discovery.ts 2023-04-28 13:51:48 +00:00
Charis Kyriakou
feb92de0c4 Move test-ui.ts to /query-testing/test-ui.ts 2023-04-28 13:51:48 +00:00
Charis Kyriakou
6415978db5 Move test-tree-node.ts to /query-testing/test-tree-node.ts 2023-04-28 13:51:48 +00:00
Charis Kyriakou
c215072d2e Move test-runner.ts to /query-testing/test-runner.ts 2023-04-28 13:51:48 +00:00
Charis Kyriakou
7662b3900f Move test-manager-base.ts to /query-testing/test-manager-base.ts 2023-04-28 13:51:48 +00:00
Charis Kyriakou
863e7d207f Move test-adapter.ts to /query-testing/test-adapter.ts 2023-04-28 13:51:48 +00:00
Charis Kyriakou
27ebc3e67f Merge pull request #2388 from github/charisk/move-common-vscode-files
Move vscode utils to /common/vscode
2023-04-28 14:51:10 +01:00
Robert
afa7b1dea9 Merge pull request #2389 from github/robertbrignull/successful_repos_changelog
Add missing changelog entry for #2349
2023-04-28 12:31:44 +01:00
Robert
86ecd9bfad Add changelog entry for https://github.com/github/vscode-codeql/pull/2349 2023-04-28 11:52:35 +01:00
Charis Kyriakou
b034c31db8 Move progress.ts to /common/vscode/progress.ts 2023-04-28 10:14:55 +00:00
Charis Kyriakou
4f1315aeae Move authentication.ts to /common/vscode/authentication.ts 2023-04-28 10:14:55 +00:00
Charis Kyriakou
8500f20c2b Move archive-filesystem-provider.ts to /common/vscode/archive-filesystem-provider.ts 2023-04-28 10:14:55 +00:00
Charis Kyriakou
d1db456e2e Move abstract-webview.ts to /common/vscode/abstract-webview.ts 2023-04-28 09:33:02 +00:00
Charis Kyriakou
ff47310133 Move vscode-uitls/multi-file-system-watcher.ts to /common/vscode/multi-file-system-watcher.ts 2023-04-28 09:33:02 +00:00
Charis Kyriakou
5c6e8a46a3 Move vscode-uitls/external-files.ts to /common/vscode/external-files.ts 2023-04-28 09:33:02 +00:00
Charis Kyriakou
48dd3dc57c Merge pull request #2387 from github/charisk/move-some-common-files
Move some common files into /common
2023-04-28 10:22:24 +01:00
Charis Kyriakou
8b59c12701 Move log-insights/jsonl-reader.ts to /common/jsonl-reader.ts 2023-04-28 07:35:54 +00:00
Charis Kyriakou
616e2be99b Move sarif-parser.ts to /common/sarif-parser.ts 2023-04-28 07:35:54 +00:00
Andrew Eisenberg
5ce45761a0 Add codeQL.contextualQueries.disableCache
An internal option to help library authours to run and debug
the find references and find dependencies contetextual queries
without relying on the implicit cache.
2023-04-27 21:00:39 +00:00
dependabot[bot]
f4a3115a6a Bump patch-package from 6.5.0 to 7.0.0 in /extensions/ql-vscode (#2383)
Bumps [patch-package](https://github.com/ds300/patch-package) from 6.5.0 to 7.0.0.
- [Release notes](https://github.com/ds300/patch-package/releases)
- [Changelog](https://github.com/ds300/patch-package/blob/master/CHANGELOG.md)
- [Commits](https://github.com/ds300/patch-package/compare/v6.5.0...v7.0.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-27 10:04:51 -07:00
Robert
686d8749d0 Merge pull request #2384 from github/robertbrignull/makeSelected
Fix not setting database as selected if it already exists
2023-04-27 17:19:01 +01:00
Charis Kyriakou
39b890dd70 Merge pull request #2382 from github/charisk/move-mocks
Move mock GitHub API server files
2023-04-27 17:07:05 +01:00
Robert
b786b56c70 Fix tests 2023-04-27 16:53:25 +01:00
Robert
44a096202d Add changelog entry 2023-04-27 16:51:33 +01:00
Elena Tanasoiu
f10185abc8 Write correct value to setting 2023-04-27 15:42:04 +00:00
Charis Kyriakou
431988f9fd Move mock GitHub API server files
:   scripts/lint-scenarios.ts
2023-04-27 15:24:09 +00:00
Robert
e0cb1df68c Update expected args in test 2023-04-27 15:43:43 +01:00
Robert
92f23d18fb Change default value of makeSelected from false to true 2023-04-27 15:17:01 +01:00
Robert
9941a42dd9 Set makeSelected to true for two calls 2023-04-27 15:13:36 +01:00
Robert
62737146fe Make database selected even if it's already in the list 2023-04-27 15:06:46 +01:00
Charis Kyriakou
977c7f57b1 Merge pull request #2381 from github/charisk/move-cli-files
Move CodeQL CLI files
2023-04-27 14:06:13 +01:00
Elena Tanasoiu
d242117240 Fix comment to list correct options
I initially started defining an enum, but I'm not able to import it in package.json,
where the list of options is defined (under `codeQL.createQuery.autogenerateQlPacks`).
2023-04-27 12:35:06 +00:00
Elena Tanasoiu
c71a83b9c7 Correct test descriptions to say ternary instead of binary 2023-04-27 12:35:06 +00:00
Elena Tanasoiu
025ec257a5 Convert autogenerateQlPacks to use enum 2023-04-27 12:35:06 +00:00
Elena Tanasoiu
6034105462 Rename codeQL.autogenerateQlPacks -> codeQL.createQuery.autogenerateQlPacks 2023-04-27 12:35:06 +00:00
Elena Tanasoiu
9aeb520841 Rename SKELETON_WIZARD_FOLDER -> QL_PACK_LOCATION
To make it clear what it's supposed to be storing.
2023-04-27 12:35:06 +00:00
Elena Tanasoiu
4e2b26f285 Rename codeQL.createQuery.folder -> codeQL.createQuery.qlPackLocation 2023-04-27 12:35:06 +00:00
Elena Tanasoiu
c877f6cc60 Fix error in skeleton wizard tests
We modify both these options in the beforeEach(). We should reset
them in the afterEach().
2023-04-27 12:35:06 +00:00
Elena Tanasoiu
f2601432d3 Remember user's choice to not be prompted again
By writing the setting to our new `codeQL.autogenerateQlPacks` setting.
2023-04-27 12:35:04 +00:00
Elena Tanasoiu
8392284cc1 Introduce new dialog box with "No, never ask me again" option 2023-04-27 12:33:51 +00:00
Elena Tanasoiu
ae320d0fef Set up new config setting for auto generating QL packs
In the next commit we will write to this setting when the user chooses
to disable the QL pack generation and prefers to never be asked again
about it.
2023-04-27 12:33:16 +00:00
Elena Tanasoiu
3eef0e9797 Give modal methods their own describe blocks 2023-04-27 12:33:16 +00:00
Robert
562f926be5 Merge pull request #2349 from github/robertbrignull/countSuccessfulRepos
Show number of successful repos instead of completed repos in variant analysis results view header
2023-04-27 12:58:15 +01:00
Charis Kyriakou
ae8766a296 Move distribution.ts to /codeql-cli/distribution.ts 2023-04-27 11:57:07 +00:00
Charis Kyriakou
8bdb51d281 Move cli-version.ts to /codeql-cli/cli-version.ts 2023-04-27 11:57:07 +00:00
Charis Kyriakou
732c67e6cd Move cli.ts to /codeql-cli/cli.ts 2023-04-27 11:57:07 +00:00
Charis Kyriakou
84f482fcb7 Merge pull request #2379 from github/charisk/move-packaging-files
Move packaging files
2023-04-27 12:51:02 +01:00
Charis Kyriakou
287a2d1ef2 Update paths to data files to fix tests 2023-04-27 11:16:24 +00:00
Robert
9d7ea8ecd8 Make test names clearer 2023-04-27 12:10:51 +01:00
Robert
68c41d346c Merge branch 'main' into robertbrignull/countSuccessfulRepos 2023-04-27 12:09:09 +01:00
Robert
29d04837ab Merge pull request #2287 from github/robertbrignull/selection
Introduce helpers for commands that operate on selections
2023-04-27 11:38:22 +01:00
Shati Patel
988df04b0b Change internal name for variant analysis SortKey values (#2380)
Follow-up to https://github.com/github/vscode-codeql/pull/2373
2023-04-27 10:37:14 +00:00
Robert
392c59ed2c Remove unnecessary check of undefined 2023-04-27 10:56:25 +01:00
Shati Patel
af75fa9f2f Update wording in the "sorting dropdown" of the variant analysis results view (#2373) 2023-04-27 10:41:32 +01:00
Robert
37459a1405 fix typo 2023-04-27 10:33:46 +01:00
Robert
0bc756766a Merge branch 'main' into robertbrignull/selection
Conflicts:
	extensions/ql-vscode/src/databases/local-databases-ui.ts
	extensions/ql-vscode/src/query-history/query-history-manager.ts
2023-04-27 10:32:24 +01:00
Charis Kyriakou
80ac593bec Add index.ts for packaging module 2023-04-27 08:52:52 +00:00
Charis Kyriakou
38af88805c Move packaging.ts to /packaging/packaging.ts 2023-04-27 08:52:52 +00:00
Charis Kyriakou
8c9c38e1ae Merge pull request #2377 from github/charisk/move-databse-files
Move database files
2023-04-27 09:44:03 +01:00
Charis Kyriakou
0941417caf Move local-databases.ts to /databases/local-databases.ts 2023-04-26 13:52:16 +00:00
Charis Kyriakou
845197a95f Move local-databases-ui.ts to /databases/local-databases-ui.ts 2023-04-26 13:52:16 +00:00
Charis Kyriakou
2e96ba90e6 Move databaseFetcher.ts to /databases/database-fetcher.ts 2023-04-26 13:52:16 +00:00
Charis Kyriakou
57cc9657ed Merge pull request #2376 from github/charisk/move-query-evaluation-log-files
Move query evaluation logging files
2023-04-26 14:15:54 +01:00
Nora
099e8723bc Merge pull request #2375 from github/version/bump-to-v1.8.4
Bump version to v1.8.4
2023-04-26 14:59:00 +02:00
Charis Kyriakou
de36944425 Add index for query-evaluation-logging module 2023-04-26 12:32:06 +00:00
Charis Kyriakou
1edecfae57 Move eval-log-viewer.ts to query-evaluation-logging/eval-log-viewer.ts and related tests 2023-04-26 12:32:06 +00:00
Charis Kyriakou
2d4d15aed8 Move eval-log-tree-builder.ts to query-evaluation-logging/eval-log-tree-builder.ts and related tests 2023-04-26 12:32:06 +00:00
Nora
77fbaea1c7 Merge pull request #2368 from github/nora/move-files-misc1
Move contextual and ast-viewer files into language-support
2023-04-26 14:15:35 +02:00
Nora
b6b3d3b541 improve imports 2023-04-26 09:56:45 +00:00
github-actions[bot]
e1e05725cf Bump version to v1.8.4 2023-04-26 09:47:12 +00:00
Nora
9a317b7651 move ast test data files 2023-04-25 13:46:08 +00:00
Nora
ba85e98f8b move language-support/contextual/ast-builder to language-support/ast-viewer/ast-builder 2023-04-25 13:46:08 +00:00
Nora
8d3d5dbf45 move src/astViewer to src/language-support/ast-viewer/ast-viewer including test 2023-04-25 13:46:08 +00:00
Nora
3757911d34 move src/ast-cfg-commands to language-support/ast-viewer/ast-cfg-commands 2023-04-25 13:46:08 +00:00
Nora
c9f7b7aacf create index.ts and adjust imports and exports 2023-04-25 13:46:08 +00:00
Nora
e5845b1c21 move contextual -> language-support/contextual including tests and kebab-caseing 2023-04-25 13:46:08 +00:00
Robert
72c646c29b Ignore invalid file paths when parsing sarif 2023-04-25 11:21:56 +01:00
Robert
274cb9a6e8 Handle codeSnippet not being defined in markdown generation 2023-04-25 10:40:33 +01:00
Robert
0394bd5e1e Make codeSnippet optional 2023-04-25 10:40:10 +01:00
Robert
e31ef662f8 Avoid using "as ThreadFlow" to force the type system 2023-04-24 17:32:21 +01:00
Robert
14952cf7d3 Delete assertSingleQuery 2023-04-24 16:08:46 +01:00
Robert
dbf3f26d13 Convert handleExportResults to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
a6a2f9776a Convert handleCopyRepoList to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
be6f356437 Convert handleOpenOnGithub to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
1ea0f1429d Convert handleViewDil to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
9c711eda97 Convert handleViewCsvAlerts to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
b74cd15752 Convert handleViewCsvResults to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
ef93ab9e70 Convert handleViewSarifAlerts to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
288a2bf62a Convert handleShowQueryText to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
b2f0e2efd9 Convert handleCancel to use createMultiSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
28819dfe76 Convert handleShowEvalLogViewer to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
43c0d15be3 Convert handleShowEvalLogSummary to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
ccd73b2a16 Convert handleShowEvalLog to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
921cf60f5e Convert handleOpenQueryDirectory to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
21757ae9b6 Convert handleShowQueryLog to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
a0a4a06430 Convert handleItemClicked to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
b17251b36c Convert handleRenameItem to call createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
d29c24d06c Convert handleRemoveHistoryItem to use createMultiSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
0b0a03396c Convert handleOpenQuery to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
d1e528e48a Convert runQueries to use createMultiSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
491cf2a58d Convert handleAddSource to use createMultiSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
5394891691 Convert handleOpenFolder to use createMultiSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
be392b5415 Convert handleRenameDatabase to use createSingleSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
5bee5c6672 Convert handleRemoveDatabase to use createMultiSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
4a957adda3 Convert handleUpgradeDatabase to use createMultiSelectionCommand 2023-04-24 16:08:46 +01:00
Robert
40f3092244 Convert handleUpgradeDatabaseInternal to just take an array of databases 2023-04-24 16:08:46 +01:00
Robert
08eb7f811e Add functions for creation selection commands 2023-04-24 16:08:46 +01:00
Robert
b5ad37a094 Don't say analyses failed when the workflow was canceled 2023-04-19 11:52:39 +01:00
Robert
7b03a6ed14 Fix story or cancelled analysis 2023-04-18 14:52:55 +01:00
Robert
6398ede2e2 Pull icon out to function 2023-04-18 14:52:55 +01:00
Robert
276d675242 Add labels to icons 2023-04-18 14:52:53 +01:00
Robert
3db0f2bdfe Show an error if not all repos completed successfully 2023-04-18 14:52:53 +01:00
Robert
aa9e2fb5fc Remove "Succeeded warnings" text 2023-04-18 14:52:53 +01:00
Robert
8291e52a9b Pass in successfulRepositoryCount 2023-04-18 14:52:50 +01:00
Robert
612628fa98 Replace showWarning by passing in skippedRepositoryCount 2023-04-18 13:56:44 +01:00
Robert
52972f0d69 Make completedRepositoryCount non-optional
We're always passing in a non-undefined number anyway, so this optional value isn't giving us any benefit.
2023-04-18 13:23:52 +01:00
624 changed files with 112371 additions and 43866 deletions

View File

@@ -0,0 +1,37 @@
/**
* @name Unwanted dependency on vscode API
* @kind path-problem
* @problem.severity error
* @id vscode-codeql/assert-no-vscode-dependency
* @description The modules stored under `common` should not have dependencies on the VS Code API
*/
import javascript
class VSCodeImport extends ImportDeclaration {
VSCodeImport() { this.getImportedPath().getValue() = "vscode" }
}
class CommonFile extends File {
CommonFile() {
this.getRelativePath().regexpMatch(".*/src/common/.*") and
not this.getRelativePath().regexpMatch(".*/vscode/.*")
}
}
Import getANonTypeOnlyImport(Module m) {
result = m.getAnImport() and not result.(ImportDeclaration).isTypeOnly()
}
query predicate edges(AstNode a, AstNode b) {
getANonTypeOnlyImport(a) = b or
a.(Import).getImportedModule() = b
}
from Module m, VSCodeImport v
where
m.getFile() instanceof CommonFile and
edges+(m, v)
select m, m, v,
"This module is in the 'common' directory but has a transitive dependency on the vscode API imported $@",
v, "here"

View File

@@ -1,21 +0,0 @@
/**
* @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"

View File

@@ -1,3 +1,4 @@
name: vscode-codeql-custom-queries-javascript
version: 0.0.0
libraryPathDependencies: codeql-javascript
dependencies:
codeql/javascript-queries: "*"

View File

@@ -15,134 +15,145 @@
* that should be changed to fix the alert.
*/
import javascript
import javascript
/**
* The name of a VS Code command.
*/
class CommandName extends string {
CommandName() { exists(CommandUsage e | e.getCommandName() = this) }
/**
* In how many ways is this command used. Will always be at least 1.
*/
int getNumberOfUsages() { result = count(this.getAUse()) }
/**
* The name of a VS Code command.
*/
class CommandName extends string {
CommandName() { exists(CommandUsage e | e.getCommandName() = this) }
/**
* Get a usage of this command.
*/
CommandUsage getAUse() { result.getCommandName() = this }
/**
* Get the canonical first usage of this command, to use for the location
* of the alert. The implementation of this ordering of usages is arbitrary
* and the usage given may not be the one that should be changed when fixing
* the alert.
*/
CommandUsage getFirstUsage() {
result =
max(CommandUsage use |
use = this.getAUse()
|
use
order by
use.getFile().getRelativePath(), use.getLocation().getStartLine(),
use.getLocation().getStartColumn()
)
}
}
/**
* Represents a single usage of a command, either from within code or
* from the command's definition in package.json
*/
abstract class CommandUsage extends Locatable {
abstract string getCommandName();
}
/**
* A usage of a command from the typescript code, by calling `executeCommand`.
*/
class CommandUsageCallExpr extends CommandUsage, CallExpr {
CommandUsageCallExpr() {
this.getCalleeName() = "executeCommand" and
this.getArgument(0).(StringLiteral).getValue().matches("%codeQL%") and
not this.getFile().getRelativePath().matches("extensions/ql-vscode/test/%")
}
override string getCommandName() { result = this.getArgument(0).(StringLiteral).getValue() }
}
/**
* In how many ways is this command used. Will always be at least 1.
*/
int getNumberOfUsages() { result = count(this.getAUse()) }
/**
* A usage of a command from the typescript code, by calling `CommandManager.execute`.
*/
class CommandUsageCommandManagerMethodCallExpr extends CommandUsage, MethodCallExpr {
CommandUsageCommandManagerMethodCallExpr() {
this.getCalleeName() = "execute" and
this.getReceiver().getType().unfold().(TypeReference).getTypeName().getName() = "CommandManager" and
this.getArgument(0).(StringLiteral).getValue().matches("%codeQL%") and
not this.getFile().getRelativePath().matches("extensions/ql-vscode/test/%")
}
/**
* Get a usage of this command.
*/
CommandUsage getAUse() { result.getCommandName() = this }
override string getCommandName() { result = this.getArgument(0).(StringLiteral).getValue() }
}
/**
* A usage of a command from any menu that isn't the command palette.
* This means a user could invoke the command by clicking on a button in
* something like a menu or a dropdown.
*/
class CommandUsagePackageJsonMenuItem extends CommandUsage, JsonObject {
CommandUsagePackageJsonMenuItem() {
exists(this.getPropValue("command")) and
exists(PackageJson packageJson, string menuName |
packageJson
.getPropValue("contributes")
.getPropValue("menus")
.getPropValue(menuName)
.getElementValue(_) = this and
menuName != "commandPalette"
)
}
override string getCommandName() { result = this.getPropValue("command").getStringValue() }
}
/**
* Is the given command disabled for use in the command palette by
* a block with a `"when": "false"` field.
*/
predicate isDisabledInCommandPalette(string commandName) {
exists(PackageJson packageJson, JsonObject commandPaletteObject |
packageJson
.getPropValue("contributes")
.getPropValue("menus")
.getPropValue("commandPalette")
.getElementValue(_) = commandPaletteObject and
commandPaletteObject.getPropValue("command").getStringValue() = commandName and
commandPaletteObject.getPropValue("when").getStringValue() = "false"
)
}
/**
* Represents a command being usable from the command palette.
* This means that a user could choose to manually invoke the command.
*/
class CommandUsagePackageJsonCommandPalette extends CommandUsage, JsonObject {
CommandUsagePackageJsonCommandPalette() {
this.getFile().getBaseName() = "package.json" and
exists(this.getPropValue("command")) and
exists(PackageJson packageJson |
packageJson.getPropValue("contributes").getPropValue("commands").getElementValue(_) = this
) and
not isDisabledInCommandPalette(this.getPropValue("command").getStringValue())
}
override string getCommandName() { result = this.getPropValue("command").getStringValue() }
}
from CommandName c
where c.getNumberOfUsages() > 1
select c.getFirstUsage(),
"The " + c + " command is used from " + c.getNumberOfUsages() + " locations"
/**
* Get the canonical first usage of this command, to use for the location
* of the alert. The implementation of this ordering of usages is arbitrary
* and the usage given may not be the one that should be changed when fixing
* the alert.
*/
CommandUsage getFirstUsage() {
result =
max(CommandUsage use |
use = this.getAUse()
|
use
order by
use.getFile().getRelativePath(), use.getLocation().getStartLine(),
use.getLocation().getStartColumn()
)
}
}
/**
* Matches one of the members of `BuiltInVsCodeCommands` from `extensions/ql-vscode/src/common/commands.ts`.
*/
class BuiltInVSCodeCommand extends string {
BuiltInVSCodeCommand() {
exists(TypeAliasDeclaration tad |
tad.getIdentifier().getName() = "BuiltInVsCodeCommands" and
tad.getDefinition().(InterfaceTypeExpr).getAMember().getName() = this
)
}
}
/**
* Represents a single usage of a command, either from within code or
* from the command's definition in package.json
*/
abstract class CommandUsage extends Locatable {
abstract string getCommandName();
}
/**
* A usage of a command from the typescript code, by calling `executeCommand`.
*/
class CommandUsageCallExpr extends CommandUsage, CallExpr {
CommandUsageCallExpr() {
this.getCalleeName() = "executeCommand" and
this.getArgument(0).(StringLiteral).getValue().matches("%codeQL%") and
not this.getFile().getRelativePath().matches("extensions/ql-vscode/test/%")
}
override string getCommandName() { result = this.getArgument(0).(StringLiteral).getValue() }
}
/**
* A usage of a command from the typescript code, by calling `CommandManager.execute`.
*/
class CommandUsageCommandManagerMethodCallExpr extends CommandUsage, MethodCallExpr {
CommandUsageCommandManagerMethodCallExpr() {
this.getCalleeName() = "execute" and
this.getReceiver().getType().unfold().(TypeReference).getTypeName().getName() = "CommandManager" and
this.getArgument(0).(StringLiteral).getValue().matches("%codeQL%") and
not this.getFile().getRelativePath().matches("extensions/ql-vscode/test/%")
}
override string getCommandName() { result = this.getArgument(0).(StringLiteral).getValue() }
}
/**
* A usage of a command from any menu that isn't the command palette.
* This means a user could invoke the command by clicking on a button in
* something like a menu or a dropdown.
*/
class CommandUsagePackageJsonMenuItem extends CommandUsage, JsonObject {
CommandUsagePackageJsonMenuItem() {
exists(this.getPropValue("command")) and
exists(PackageJson packageJson, string menuName |
packageJson
.getPropValue("contributes")
.getPropValue("menus")
.getPropValue(menuName)
.getElementValue(_) = this and
menuName != "commandPalette"
)
}
override string getCommandName() { result = this.getPropValue("command").getStringValue() }
}
/**
* Is the given command disabled for use in the command palette by
* a block with a `"when": "false"` field.
*/
predicate isDisabledInCommandPalette(string commandName) {
exists(PackageJson packageJson, JsonObject commandPaletteObject |
packageJson
.getPropValue("contributes")
.getPropValue("menus")
.getPropValue("commandPalette")
.getElementValue(_) = commandPaletteObject and
commandPaletteObject.getPropValue("command").getStringValue() = commandName and
commandPaletteObject.getPropValue("when").getStringValue() = "false"
)
}
/**
* Represents a command being usable from the command palette.
* This means that a user could choose to manually invoke the command.
*/
class CommandUsagePackageJsonCommandPalette extends CommandUsage, JsonObject {
CommandUsagePackageJsonCommandPalette() {
this.getFile().getBaseName() = "package.json" and
exists(this.getPropValue("command")) and
exists(PackageJson packageJson |
packageJson.getPropValue("contributes").getPropValue("commands").getElementValue(_) = this
) and
not isDisabledInCommandPalette(this.getPropValue("command").getStringValue())
}
override string getCommandName() { result = this.getPropValue("command").getStringValue() }
}
from CommandName c
where c.getNumberOfUsages() > 1 and not c instanceof BuiltInVSCodeCommand
select c.getFirstUsage(),
"The " + c + " command is used from " + c.getNumberOfUsages() + " locations"

View File

@@ -22,7 +22,7 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: '16.14.2'
node-version: '16.17.1'
cache: 'npm'
cache-dependency-path: extensions/ql-vscode/package-lock.json
@@ -80,7 +80,7 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: '16.14.2'
node-version: '16.17.1'
cache: 'npm'
cache-dependency-path: extensions/ql-vscode/package-lock.json
@@ -110,6 +110,11 @@ jobs:
run: |
npm run lint:scenarios
- name: Find deadcode
working-directory: extensions/ql-vscode
run: |
npm run find-deadcode
unit-test:
name: Unit Test
runs-on: ${{ matrix.os }}
@@ -124,7 +129,7 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: '16.14.2'
node-version: '16.17.1'
cache: 'npm'
cache-dependency-path: extensions/ql-vscode/package-lock.json
@@ -158,7 +163,7 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: '16.14.2'
node-version: '16.17.1'
cache: 'npm'
cache-dependency-path: extensions/ql-vscode/package-lock.json
@@ -209,6 +214,7 @@ jobs:
name: CLI Test
runs-on: ${{ matrix.os }}
needs: [find-nightly, set-matrix]
timeout-minutes: 30
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
@@ -225,7 +231,7 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: '16.14.2'
node-version: '16.17.1'
cache: 'npm'
cache-dependency-path: extensions/ql-vscode/package-lock.json

View File

@@ -22,7 +22,7 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: '16.14.2'
node-version: '16.17.1'
- name: Install dependencies
run: |

View File

@@ -2,3 +2,4 @@
**/variant-analysis/ @github/code-scanning-secexp-reviewers
**/databases/ @github/code-scanning-secexp-reviewers
**/data-extensions-editor/ @github/code-scanning-secexp-reviewers
**/queries-panel/ @github/code-scanning-secexp-reviewers

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 193 KiB

View File

@@ -10,7 +10,7 @@
* New telemetry events are added.
* Deprecation or removal of commands.
* Accumulation of many changes, none of which are individually big enough to warrant a minor bump, but which together are. This does not include changes which are purely internal to the extension, such as refactoring, or which are only available behind a feature flag.
1. Double-check that the node version we're using matches the one used for VS Code. If it doesn't, you will then need to update the node version in the following files:
1. Double-check that the node version we're using matches the one used for VS Code. You can find this info by seleting "About Visual Studio Code" from the top menu. If it doesn't match, you will then need to update the node version in the following files:
* `.nvmrc` - this will enable `nvm` to automatically switch to the correct node version when you're in the project folder
* `.github/workflows/main.yml` - all the "node-version: '[VERSION]'" settings
* `.github/workflows/release.yml` - the "node-version: '[VERSION]'" setting

View File

@@ -11,16 +11,67 @@ We don't need to test features (and permutations of features) that are covered b
## Before releasing the VS Code extension
- Go through the required test cases listed below
- Run at least one local query and MRVA using the existing version of the extension (to generate "old" query history items).
- Go through the required test cases listed below.
- Check major PRs since the previous release for specific one-off things to test. Based on that, you might want to
choose to go through some of the Optional Test Cases.
- Run a query using the existing version of the extension (to generate an "old" query history item)
## Required Test Cases
### Test Case 1: MRVA - Running a problem path query and viewing results
### Local databases
1. Open the [UnsafeJQueryPlugin query](https://github.com/github/codeql/blob/main/javascript/ql/src/Security/CWE-079/UnsafeJQueryPlugin.ql).
#### Test case 1: Download a database from GitHub
1. Click "Download Database from GitHub" and enter `angular-cn/ng-nice` and select the javascript language if prompted
#### Test case 2: Import a database from an archive
1. Obtain a javascript database for `babel/babel`
- You can do `gh api "/repos/babel/babel/code-scanning/codeql/databases/javascript" -H "Accept: application/zip" > babel.zip` to fetch a database from GitHub.
2. Click "Choose Database from Archive" and select the file you just downloaded above.
### Local queries
#### Test case 1: Running a path problem query and viewing results
1. Open the [javascript UnsafeJQueryPlugin query](https://github.com/github/codeql/blob/main/javascript/ql/src/Security/CWE-079/UnsafeJQueryPlugin.ql).
2. Select the `angular-cn/ng-nice` database (or download it if you don't have one already)
3. Run a local query.
4. Once the query completes:
- Check that the result messages are rendered
- Check that the paths can be opened and paths are rendered correctly
- Check that alert locations can be clicked on
#### Test case 2: Running a problem query and viewing results
1. Open the [javascript ReDoS query](https://github.com/github/codeql/blob/main/javascript/ql/src/Performance/ReDoS.ql).
2. Select the `babel/babel` database (or download it if you don't have one already)
3. Run a local query.
4. Once the query completes:
- Check that the result messages are rendered
- Check that alert locations can be clicked on
#### Test case 3: Running a non-problem query and viewing results
1. Open the [cpp FunLinesOfCode query](https://github.com/github/codeql/blob/main/cpp/ql/src/Metrics/Functions/FunLinesOfCode.ql).
2. Select the `google/brotli` database (or download it if you don't have one already)
3. Run a local query.
4. Once the query completes:
- Check that the results table is rendered
- Check that result locations can be clicked on
#### Test case 3: Can use AST viewer
1. Click on any code location from a previous query to open a source file from a database
2. Open the AST viewing panel and click "View AST"
3. Once the AST is computed:
- Check that it can be navigated
### MRVA
#### Test Case 1: Running a path problem query and viewing results
1. Open the [javascript UnsafeJQueryPlugin query](https://github.com/github/codeql/blob/main/javascript/ql/src/Security/CWE-079/UnsafeJQueryPlugin.ql).
2. Run a MRVA against the following repo list:
```json
@@ -47,40 +98,44 @@ choose to go through some of the Optional Test Cases.
6. Once the query completes:
- Check that the query history item is updated to show the query status as "complete"
### Test Case 2: MRVA - Running a problem query and viewing results
#### Test Case 2: Running a problem query and viewing results
1. Open the [ReDoS query](https://github.com/github/codeql/blob/main/javascript/ql/src/Performance/ReDoS.ql).
1. Open the [javascript ReDoS query](https://github.com/github/codeql/blob/main/javascript/ql/src/Performance/ReDoS.ql).
2. Run a MRVA against the "Top 10" repositories.
3. Check that there is a notification message.
3. Check that a notification message pops up and the results view is opened.
4. Check the query history. It should:
- Show that an item has been added to the query history
- The item should be marked as "in progress".
5. Once the query starts:
- Check that a notification is shown with a link to the results view
5. Once the query completes:
- Check that the results are rendered with an alert message and a highlighted code snippet:
![highlighted-code-snippet](images/highlighted-code-snippet.png)
### Test Case 3: MRVA - Running a non-problem query and viewing results
![highlighted-code-snippet](images/highlighted-code-snippet.png)
1. Open the [FunLinesOfCode query](https://github.com/github/codeql/blob/main/cpp/ql/src/Metrics/Functions/FunLinesOfCode.ql).
#### Test Case 3: Running a non-problem query and viewing results
1. Open the [cpp FunLinesOfCode query](https://github.com/github/codeql/blob/main/cpp/ql/src/Metrics/Functions/FunLinesOfCode.ql).
2. Run a MRVA against a single repository (e.g. `google/brotli`).
3. Once the query starts:
- Open the query results
3. Check that a notification message pops up and the results view is opened.
4. Check the query history. It should:
- Show that an item has been added to the query history
- The item should be marked as "in progress".
5. Once the query completes:
- Check that the results show up in a table:
![results-table](images/results-table.png)
### Test Case 4: MRVA - Interacting with query history
![results-table](images/results-table.png)
#### Test Case 4: Interacting with query history
1. Click a history item (for MRVA):
- Check that exporting results works
- Check that sorting results works
- Check that copying repo lists works
2. Open the query results directory:
2. Click "Open Results Directory":
- Check that the correct directory is opened and there are results in it
3. View logs
3. Click "View Logs":
- Check that the correct workflow is opened
### Test Case 5: MRVA - Canceling a variant analysis run
#### Test Case 5: Canceling a variant analysis run
Run one of the above MRVAs, but cancel it from within VS Code:
@@ -88,9 +143,11 @@ Run one of the above MRVAs, but cancel it from within VS Code:
- Check that the workflow run is also canceled.
- Check that any available results are visible in VS Code.
### Test Case 6: MRVA - Change to a different colour theme
### General
Open one of the above MRVAs, try changing to a different colour theme and check that everything looks sensible.
#### Test case 1: Change to a different colour theme
Open at least one of the above MRVAs and at least one local query, then try changing to a different colour theme and check that everything looks sensible.
Are there any components that are not showing up?
## Optional Test Cases
@@ -258,10 +315,9 @@ This requires running a MRVA query and seeing the results view.
2. When the file does not exist
7. Can open query text
8. Can sort repos
1. By name
2. By results
3. By stars
4. By last updated
1. Alphabetically
2. By number of results
3. By popularity
9. Can filter repos
10. Shows correct statistics
1. Total number of results
@@ -321,6 +377,7 @@ This requires running a MRVA query and seeing the results view.
1. Make changes via config file (ensure JSON schema is helping out)
1. Close and re-open VS Code (ensure lists are there)
1. Collapse/expand tree nodes
1. Create a new list, right click and select "Add repositories with GitHub Code Search". Enter the language 'python' and the query "UserMixin". This should show a rate limiting notification after a while but eventually populate the list with roughly 770 items.
Error cases that trigger an error notification:

View File

@@ -133,4 +133,4 @@ Once the scenario has been recorded, it's often useful to remove some of the req
### Scenario data location
Pre-recorded scenarios are stored in `./src/mocks/scenarios`. However, it's possible to configure the location, by setting the `codeQL.mockGitHubApiServer.scenariosPath` configuration property in the VS Code user settings.
Pre-recorded scenarios are stored in `./src/variant-analysis/github-api/mocks/scenarios`. However, it's possible to configure the location, by setting the `codeQL.mockGitHubApiServer.scenariosPath` configuration property in the VS Code user settings.

View File

@@ -65,10 +65,6 @@ const baseConfig = {
"import/no-namespace": "off",
"import/no-unresolved": "off",
"import/no-webpack-loader-syntax": "off",
"jsx-a11y/anchor-is-valid": "off",
"jsx-a11y/no-noninteractive-element-interactions": "off",
"jsx-a11y/no-static-element-interactions": "off",
"jsx-a11y/click-events-have-key-events": "off",
"no-invalid-this": "off",
"no-fallthrough": "off",
"no-console": "off",

View File

@@ -1 +1 @@
v16.14.2
v16.17.1

View File

@@ -1,4 +1,4 @@
import type { StorybookConfig } from "@storybook/core-common";
import type { StorybookConfig } from "@storybook/react-webpack5";
const config: StorybookConfig = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
@@ -8,13 +8,13 @@ const config: StorybookConfig = {
"@storybook/addon-interactions",
"./vscode-theme-addon/preset.ts",
],
framework: "@storybook/react",
core: {
builder: "@storybook/builder-webpack5",
framework: {
name: "@storybook/react-webpack5",
options: {},
},
features: {
babelModeV7: true,
docs: {
autodocs: "tag",
},
};
module.exports = config;
export default config;

View File

@@ -1,4 +1,4 @@
import { addons } from "@storybook/addons";
import { addons } from "@storybook/manager-api";
import { themes } from "@storybook/theming";
addons.setConfig({

View File

@@ -1,31 +1,36 @@
import { Preview } from "@storybook/react";
import { themes } from "@storybook/theming";
import { action } from "@storybook/addon-actions";
// Allow all stories/components to use Codicons
import "@vscode/codicons/dist/codicon.css";
// https://storybook.js.org/docs/react/configure/overview#configure-story-rendering
export const parameters = {
// All props starting with `on` will automatically receive an action as a prop
actions: { argTypesRegex: "^on[A-Z].*" },
// All props matching these names will automatically get the correct control
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
// Use a dark theme to be aligned with VSCode
docs: {
theme: themes.dark,
},
backgrounds: {
// The background is injected by our theme CSS files
disable: true,
},
};
(window as any).acquireVsCodeApi = () => ({
postMessage: action("post-vscode-message"),
setState: action("set-vscode-state"),
});
// https://storybook.js.org/docs/react/configure/overview#configure-story-rendering
const preview: Preview = {
parameters: {
// All props starting with `on` will automatically receive an action as a prop
actions: { argTypesRegex: "^on[A-Z].*" },
// All props matching these names will automatically get the correct control
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
// Use a dark theme to be aligned with VSCode
docs: {
theme: themes.dark,
},
backgrounds: {
// The background is injected by our theme CSS files
disable: true,
},
},
};
export default preview;

View File

@@ -1,14 +1,12 @@
import * as React from "react";
import { FunctionComponent, useCallback } from "react";
import { useGlobals } from "@storybook/api";
import { useGlobals } from "@storybook/manager-api";
import {
IconButton,
Icons,
WithTooltip,
TooltipLinkList,
Link,
WithHideFn,
WithTooltip,
} from "@storybook/components";
import { themeNames, VSCodeTheme } from "./theme";
@@ -26,7 +24,7 @@ export const ThemeSelector: FunctionComponent = () => {
);
const createLinks = useCallback(
(onHide: () => void): Link[] =>
(onHide: () => void) =>
Object.values(VSCodeTheme).map((theme) => ({
id: theme,
onClick() {
@@ -44,8 +42,8 @@ export const ThemeSelector: FunctionComponent = () => {
<WithTooltip
placement="top"
trigger="click"
closeOnClick
tooltip={({ onHide }: WithHideFn) => (
closeOnOutsideClick
tooltip={({ onHide }: { onHide: () => void }) => (
<TooltipLinkList links={createLinks(onHide)} />
)}
>

View File

@@ -1,5 +1,5 @@
import * as React from "react";
import { addons, types } from "@storybook/addons";
import { addons, types } from "@storybook/manager-api";
import { ThemeSelector } from "./ThemeSelector";
const ADDON_ID = "vscode-theme-addon";

View File

@@ -1,4 +1,4 @@
export function config(entry = []) {
export function previewAnnotations(entry = []) {
return [...entry, require.resolve("./preview.ts")];
}

View File

@@ -1,6 +1,5 @@
import { useEffect, useGlobals } from "@storybook/addons";
import { useEffect } from "react";
import type {
AnyFramework,
PartialStoryFn as StoryFunction,
StoryContext,
} from "@storybook/csf";
@@ -34,11 +33,8 @@ const themeFiles: { [key in VSCodeTheme]: string } = {
.default,
};
export const withTheme = (
StoryFn: StoryFunction<AnyFramework>,
context: StoryContext<AnyFramework>,
) => {
const [{ vscodeTheme }] = useGlobals();
export const withTheme = (StoryFn: StoryFunction, context: StoryContext) => {
const { vscodeTheme } = context.globals;
useEffect(() => {
const styleSelectorId =

View File

@@ -1,5 +1,42 @@
# CodeQL for Visual Studio Code: Changelog
## 1.8.9 - 3 August 2023
- Remove "last updated" information and sorting from variant analysis results view. [#2637](https://github.com/github/vscode-codeql/pull/2637)
- Links to code on GitHub now include column numbers as well as line numbers. [#2406](https://github.com/github/vscode-codeql/pull/2406)
- No longer highlight trailing commas for jump to definition. [#2615](https://github.com/github/vscode-codeql/pull/2615)
## 1.8.8 - 17 July 2023
- Remove support for CodeQL CLI versions older than 2.9.4. [#2610](https://github.com/github/vscode-codeql/pull/2610)
- Implement syntax highlighting for the `additional` and `default` keywords. [#2609](https://github.com/github/vscode-codeql/pull/2609)
## 1.8.7 - 29 June 2023
- Show a run button on the file tab for query files, that will start a local query. This button will only show when a local database is selected in the extension. [#2544](https://github.com/github/vscode-codeql/pull/2544)
- Add a `CodeQL: Quick Evaluation Count` command to generate the count summary statistics of the results set
without spending the time to compute locations and strings. [#2475](https://github.com/github/vscode-codeql/pull/2475)
## 1.8.6 - 14 June 2023
- Add repositories to a variant analysis list with GitHub Code Search. [#2439](https://github.com/github/vscode-codeql/pull/2439) and [#2476](https://github.com/github/vscode-codeql/pull/2476)
## 1.8.5 - 6 June 2023
- Add settings `codeQL.variantAnalysis.defaultResultsFilter` and `codeQL.variantAnalysis.defaultResultsSort` for configuring how variant analysis results are filtered and sorted in the results view. The default is to show all repositories, and to sort by the number of results. [#2392](https://github.com/github/vscode-codeql/pull/2392)
- Fix bug to ensure error messages have complete stack trace in message logs. [#2425](https://github.com/github/vscode-codeql/pull/2425)
- Fix bug where the `CodeQL: Compare Query` command did not work for comparing quick-eval queries. [#2422](https://github.com/github/vscode-codeql/pull/2422)
- Update text of copy and export buttons in variant analysis results view to clarify that they only copy/export the selected/filtered results. [#2427](https://github.com/github/vscode-codeql/pull/2427)
- Add warning when using unsupported CodeQL CLI version. [#2428](https://github.com/github/vscode-codeql/pull/2428)
- Retry variant analysis results download if connection times out. [#2440](https://github.com/github/vscode-codeql/pull/2440)
## 1.8.4 - 3 May 2023
- Avoid repeated error messages when unable to monitor a variant analysis. [#2396](https://github.com/github/vscode-codeql/pull/2396)
- Fix bug where a variant analysis didn't display the `#select` results set correctly when the [query metadata](https://codeql.github.com/docs/writing-codeql-queries/about-codeql-queries/#query-metadata) didn't exactly match the query results. [#2395](https://github.com/github/vscode-codeql/pull/2395)
- On the variant analysis results page, show the count of successful analyses instead of completed analyses, and indicate the reason why analyses were not successful. [#2349](https://github.com/github/vscode-codeql/pull/2349)
- Fix bug where the "CodeQL: Set Current Database" command didn't always select the database. [#2384](https://github.com/github/vscode-codeql/pull/2384)
## 1.8.3 - 26 April 2023
- Added ability to filter repositories for a variant analysis to only those that have results [#2343](https://github.com/github/vscode-codeql/pull/2343)

View File

@@ -15,9 +15,6 @@ export const config: webpack.Configuration = {
devtool: isDevBuild ? "inline-source-map" : "source-map",
resolve: {
extensions: [".js", ".ts", ".tsx", ".json"],
fallback: {
path: require.resolve("path-browserify"),
},
},
module: {
rules: [
@@ -62,18 +59,10 @@ export const config: webpack.Configuration = {
},
{
test: /\.(woff(2)?|ttf|eot)$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "fonts/",
// We need this to make Webpack use the correct path for the fonts.
// Without this, the CSS file will use `url([object Module])`
esModule: false,
},
},
],
type: "asset/resource",
generator: {
filename: "fonts/[hash][ext][query]",
},
},
],
},

View File

@@ -30,5 +30,5 @@
"end": "^\\s*//\\s*#?endregion\\b"
}
},
"wordPattern": "(-?\\d*\\.\\d\\w*)|([^\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\.\\<\\>\\/\\?\\s]+)"
"wordPattern": "(-?\\d*\\.\\d\\w*)|([^\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\.\\<\\>\\/\\?\\s\\,]+)"
}

View File

@@ -0,0 +1 @@
<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M4 2h8v4c.341.035.677.112 1 .23V1H3v8.48l1-1.75V2zm2.14 8L5 8 4 9.75 3.29 11 1 15h8l-2.29-4-.57-1zm-3.42 4l1.72-3L5 10l.56 1 1.72 3H2.72zm6.836-6.41a3.5 3.5 0 1 1 3.888 5.82 3.5 3.5 0 0 1-3.888-5.82zm.555 4.989a2.5 2.5 0 1 0 2.778-4.157 2.5 2.5 0 0 0-2.778 4.157z" fill="#C5C5C5"/></svg>

After

Width:  |  Height:  |  Size: 431 B

View File

@@ -0,0 +1 @@
<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M4 2h8v4c.341.035.677.112 1 .23V1H3v8.48l1-1.75V2zm2.14 8L5 8 4 9.75 3.29 11 1 15h8l-2.29-4-.57-1zm-3.42 4l1.72-3L5 10l.56 1 1.72 3H2.72zm6.836-6.41a3.5 3.5 0 1 1 3.888 5.82 3.5 3.5 0 0 1-3.888-5.82zm.555 4.989a2.5 2.5 0 1 0 2.778-4.157 2.5 2.5 0 0 0-2.778 4.157z" fill="#424242"/></svg>

After

Width:  |  Height:  |  Size: 431 B

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@
"description": "CodeQL for Visual Studio Code",
"author": "GitHub",
"private": true,
"version": "1.8.3",
"version": "1.8.9",
"publisher": "GitHub",
"license": "MIT",
"icon": "media/VS-marketplace-CodeQL-icon.png",
@@ -36,6 +36,7 @@
"activationEvents": [
"onLanguage:ql",
"onLanguage:ql-summary",
"onView:codeQLQueries",
"onView:codeQLDatabases",
"onView:codeQLVariantAnalysisRepositories",
"onView:codeQLQueryHistory",
@@ -70,6 +71,7 @@
"contributes": {
"configurationDefaults": {
"[ql]": {
"debug.saveBeforeStart": "nonUntitledEditorsInActiveGroup",
"editor.wordBasedSuggestions": false
},
"[dbscheme]": {
@@ -188,7 +190,7 @@
"scope": "machine-overridable",
"type": "string",
"default": "",
"markdownDescription": "Path to the CodeQL executable that should be used by the CodeQL extension. The executable is named `codeql` on Linux/Mac and `codeql.exe` on Windows. If empty, the extension will look for a CodeQL executable on your shell PATH, or if CodeQL is not on your PATH, download and manage its own CodeQL executable."
"markdownDescription": "Path to the CodeQL executable that should be used by the CodeQL extension. The executable is named `codeql` on Linux/Mac and `codeql.exe` on Windows. If empty, the extension will look for a CodeQL executable on your shell PATH, or if CodeQL is not on your PATH, download and manage its own CodeQL executable (note: if you later introduce CodeQL on your PATH, the extension will prefer a CodeQL executable it has downloaded itself)."
},
"codeQL.runningQueries.numberOfThreads": {
"type": "integer",
@@ -245,8 +247,8 @@
},
"codeQL.runningQueries.autoSave": {
"type": "boolean",
"default": false,
"description": "Enable automatically saving a modified query file when running a query."
"description": "Enable automatically saving a modified query file when running a query.",
"markdownDeprecationMessage": "This property is deprecated and no longer has any effect. To control automatic saving of documents before running queries, use the `debug.saveBeforeStart` setting."
},
"codeQL.runningQueries.maxQueries": {
"type": "integer",
@@ -329,6 +331,34 @@
"patternErrorMessage": "Please enter a valid GitHub repository",
"markdownDescription": "[For internal use only] The name of the GitHub repository in which the GitHub Actions workflow is run when using the \"Run Variant Analysis\" command. The repository should be of the form `<owner>/<repo>`)."
},
"codeQL.variantAnalysis.defaultResultsFilter": {
"type": "string",
"default": "all",
"enum": [
"all",
"withResults"
],
"enumDescriptions": [
"Show all repositories in the results view.",
"Show only repositories with results in the results view."
],
"description": "The default filter to apply to the variant analysis results view."
},
"codeQL.variantAnalysis.defaultResultsSort": {
"type": "string",
"default": "numberOfResults",
"enum": [
"alphabetically",
"popularity",
"numberOfResults"
],
"enumDescriptions": [
"Sort repositories alphabetically in the results view.",
"Sort repositories by popularity in the results view.",
"Sort repositories by number of results in the results view."
],
"description": "The default sorting order for repositories in the variant analysis results view."
},
"codeQL.logInsights.joinOrderWarningThreshold": {
"type": "number",
"default": 50,
@@ -341,11 +371,23 @@
"default": false,
"description": "Allow database to be downloaded via HTTP. Warning: enabling this option will allow downloading from insecure servers."
},
"codeQL.createQuery.folder": {
"codeQL.createQuery.qlPackLocation": {
"type": "string",
"default": "",
"patternErrorMessage": "Please enter a valid folder",
"markdownDescription": "The name of the folder where we want to create queries and query packs via the \"CodeQL: Create Query\" command. The folder should exist."
"markdownDescription": "The name of the folder where we want to create queries and QL packs via the \"CodeQL: Create Query\" command. The folder should exist."
},
"codeQL.createQuery.autogenerateQlPacks": {
"type": "string",
"default": "ask",
"enum": [
"ask",
"never"
],
"enumDescriptions": [
"Ask to create a QL pack when a new CodeQL database is added.",
"Never create a QL pack when a new CodeQL database is added."
],
"description": "Ask the user to generate a QL pack when a new CodeQL database is downloaded."
}
}
},
@@ -414,6 +456,10 @@
"command": "codeQL.quickEval",
"title": "CodeQL: Quick Evaluation"
},
{
"command": "codeQL.quickEvalCount",
"title": "CodeQL: Quick Evaluation Count"
},
{
"command": "codeQL.quickEvalContextEditor",
"title": "CodeQL: Quick Evaluation"
@@ -434,6 +480,14 @@
"command": "codeQL.previewQueryHelp",
"title": "CodeQL: Preview Query Help"
},
{
"command": "codeQL.previewQueryHelpContextExplorer",
"title": "CodeQL: Preview Query Help"
},
{
"command": "codeQL.previewQueryHelpContextEditor",
"title": "CodeQL: Preview Query Help"
},
{
"command": "codeQL.quickQuery",
"title": "CodeQL: Quick Query"
@@ -450,6 +504,33 @@
"command": "codeQL.copyVersion",
"title": "CodeQL: Copy Version Information"
},
{
"command": "codeQLQueries.runLocalQueryFromQueriesPanel",
"title": "Run local query",
"icon": "$(run)"
},
{
"command": "codeQLQueries.runLocalQueriesFromPanel",
"title": "Run local queries",
"icon": "$(run-all)"
},
{
"command": "codeQL.runLocalQueryFromFileTab",
"title": "CodeQL: Run local query",
"icon": "$(run)"
},
{
"command": "codeQLQueries.runLocalQueryContextMenu",
"title": "Run against local database"
},
{
"command": "codeQLQueries.runLocalQueriesContextMenu",
"title": "Run against local database"
},
{
"command": "codeQLQueries.runVariantAnalysisContextMenu",
"title": "Run against variant analysis repositories"
},
{
"command": "codeQLVariantAnalysisRepositories.openConfigFile",
"title": "Open database configuration file",
@@ -465,6 +546,10 @@
"title": "Add new list",
"icon": "$(new-folder)"
},
{
"command": "codeQLVariantAnalysisRepositories.importFromCodeSearch",
"title": "Add repositories with GitHub Code Search"
},
{
"command": "codeQLVariantAnalysisRepositories.setSelectedItem",
"title": "Select"
@@ -786,6 +871,11 @@
"title": "CodeQL: Go to QL Code",
"enablement": "codeql.hasQLSource"
},
{
"command": "codeQL.gotoQLContextEditor",
"title": "CodeQL: Go to QL Code",
"enablement": "codeql.hasQLSource"
},
{
"command": "codeQL.openDataExtensionsEditor",
"title": "CodeQL: Open Data Extensions Editor"
@@ -812,6 +902,13 @@
}
],
"menus": {
"editor/title": [
{
"command": "codeQL.runLocalQueryFromFileTab",
"group": "navigation",
"when": "resourceExtname == .ql && codeQL.currentDatabaseItem"
}
],
"view/title": [
{
"command": "codeQLDatabases.sortByName",
@@ -905,6 +1002,11 @@
"when": "view == codeQLVariantAnalysisRepositories && viewItem =~ /canBeOpenedOnGitHub/",
"group": "2_qlContextMenu@1"
},
{
"command": "codeQLVariantAnalysisRepositories.importFromCodeSearch",
"when": "view == codeQLVariantAnalysisRepositories && viewItem =~ /canImportCodeSearch/",
"group": "2_qlContextMenu@1"
},
{
"command": "codeQLDatabases.setCurrentDatabase",
"group": "inline",
@@ -973,17 +1075,17 @@
{
"command": "codeQLQueryHistory.showEvalLog",
"group": "4_queryHistory@1",
"when": "codeql.supportsEvalLog && viewItem == rawResultsItem || codeql.supportsEvalLog && viewItem == interpretedResultsItem || codeql.supportsEvalLog && viewItem == cancelledResultsItem"
"when": "viewItem == rawResultsItem || viewItem == interpretedResultsItem || viewItem == cancelledResultsItem"
},
{
"command": "codeQLQueryHistory.showEvalLogSummary",
"group": "4_queryHistory@2",
"when": "codeql.supportsEvalLog && viewItem == rawResultsItem || codeql.supportsEvalLog && viewItem == interpretedResultsItem || codeql.supportsEvalLog && viewItem == cancelledResultsItem"
"when": "viewItem == rawResultsItem || viewItem == interpretedResultsItem || viewItem == cancelledResultsItem"
},
{
"command": "codeQLQueryHistory.showEvalLogViewer",
"group": "4_queryHistory@3",
"when": "config.codeQL.canary && codeql.supportsEvalLog && viewItem == rawResultsItem || config.codeQL.canary && codeql.supportsEvalLog && viewItem == interpretedResultsItem || config.codeQL.canary && codeql.supportsEvalLog && viewItem == cancelledResultsItem"
"when": "config.codeQL.canary && viewItem == rawResultsItem || config.codeQL.canary && viewItem == interpretedResultsItem || config.codeQL.canary && viewItem == cancelledResultsItem"
},
{
"command": "codeQLQueryHistory.showQueryText",
@@ -1030,6 +1132,31 @@
"group": "1_queryHistory@1",
"when": "viewItem == remoteResultsItem"
},
{
"command": "codeQLQueries.runLocalQueryFromQueriesPanel",
"group": "inline",
"when": "view == codeQLQueries && viewItem == queryFile && codeQL.currentDatabaseItem"
},
{
"command": "codeQLQueries.runLocalQueryContextMenu",
"group": "queriesPanel@1",
"when": "view == codeQLQueries && viewItem == queryFile && codeQL.currentDatabaseItem"
},
{
"command": "codeQLQueries.runLocalQueriesContextMenu",
"group": "queriesPanel@1",
"when": "view == codeQLQueries && viewItem == queryFolder && codeQL.currentDatabaseItem"
},
{
"command": "codeQLQueries.runVariantAnalysisContextMenu",
"group": "queriesPanel@1",
"when": "view == codeQLQueries && viewItem == queryFile"
},
{
"command": "codeQLQueries.runLocalQueriesFromPanel",
"group": "inline",
"when": "view == codeQLQueries && viewItem == queryFolder && codeQL.currentDatabaseItem"
},
{
"command": "codeQLTests.showOutputDifferences",
"group": "qltest@1",
@@ -1075,7 +1202,7 @@
"when": "resourceExtname == .qlref"
},
{
"command": "codeQL.previewQueryHelp",
"command": "codeQL.previewQueryHelpContextExplorer",
"group": "9_qlCommands",
"when": "resourceExtname == .qhelp && isWorkspaceTrusted"
}
@@ -1089,6 +1216,18 @@
"command": "codeQL.runQuery",
"when": "resourceLangId == ql && resourceExtname == .ql"
},
{
"command": "codeQLQueries.runLocalQueryFromQueriesPanel",
"when": "false"
},
{
"command": "codeQLQueries.runLocalQueriesFromPanel",
"when": "false"
},
{
"command": "codeQL.runLocalQueryFromFileTab",
"when": "false"
},
{
"command": "codeQL.runQueryContextEditor",
"when": "false"
@@ -1141,6 +1280,10 @@
"command": "codeQL.quickEval",
"when": "editorLangId == ql"
},
{
"command": "codeQL.quickEvalCount",
"when": "editorLangId == ql && codeql.supportsQuickEvalCount"
},
{
"command": "codeQL.quickEvalContextEditor",
"when": "false"
@@ -1161,6 +1304,14 @@
"command": "codeQL.previewQueryHelp",
"when": "resourceExtname == .qhelp && isWorkspaceTrusted"
},
{
"command": "codeQL.previewQueryHelpContextEditor",
"when": "false"
},
{
"command": "codeQL.previewQueryHelpContextExplorer",
"when": "false"
},
{
"command": "codeQL.setCurrentDatabase",
"when": "false"
@@ -1201,6 +1352,18 @@
"command": "codeQL.openDataExtensionsEditor",
"when": "config.codeQL.canary && config.codeQL.dataExtensions.editor"
},
{
"command": "codeQLQueries.runLocalQueryContextMenu",
"when": "false"
},
{
"command": "codeQLQueries.runLocalQueriesContextMenu",
"when": "false"
},
{
"command": "codeQLQueries.runVariantAnalysisContextMenu",
"when": "false"
},
{
"command": "codeQLVariantAnalysisRepositories.openConfigFile",
"when": "false"
@@ -1233,6 +1396,10 @@
"command": "codeQLVariantAnalysisRepositories.removeItemContextMenu",
"when": "false"
},
{
"command": "codeQLVariantAnalysisRepositories.importFromCodeSearch",
"when": "false"
},
{
"command": "codeQLDatabases.setCurrentDatabase",
"when": "false"
@@ -1424,6 +1591,10 @@
{
"command": "codeQLTests.acceptOutputContextTestItem",
"when": "false"
},
{
"command": "codeQL.gotoQLContextEditor",
"when": "false"
}
],
"editor/context": [
@@ -1468,11 +1639,11 @@
"when": "resourceExtname == .qlref"
},
{
"command": "codeQL.previewQueryHelp",
"command": "codeQL.previewQueryHelpContextEditor",
"when": "resourceExtname == .qhelp && isWorkspaceTrusted"
},
{
"command": "codeQL.gotoQL",
"command": "codeQL.gotoQLContextEditor",
"when": "editorLangId == ql-summary && config.codeQL.canary"
}
]
@@ -1488,6 +1659,11 @@
},
"views": {
"ql-container": [
{
"id": "codeQLQueries",
"name": "Queries",
"when": "config.codeQL.canary && config.codeQL.queriesPanel"
},
{
"id": "codeQLDatabases",
"name": "Databases"
@@ -1520,6 +1696,10 @@
"view": "codeQLQueryHistory",
"contents": "You have no query history items at the moment.\n\nSelect a database to run a CodeQL query and get your first results."
},
{
"view": "codeQLQueries",
"contents": "Looking for queries..."
},
{
"view": "codeQLDatabases",
"contents": "Add a CodeQL database:\n[From a folder](command:codeQLDatabases.chooseDatabaseFolder)\n[From an archive](command:codeQLDatabases.chooseDatabaseArchive)\n[From a URL (as a zip file)](command:codeQLDatabases.chooseDatabaseInternet)\n[From GitHub](command:codeQLDatabases.chooseDatabaseGithub)"
@@ -1545,21 +1725,23 @@
"test:vscode-integration:activated-extension": "jest --projects test/vscode-tests/activated-extension",
"test:vscode-integration:no-workspace": "jest --projects test/vscode-tests/no-workspace",
"test:vscode-integration:minimal-workspace": "jest --projects test/vscode-tests/minimal-workspace",
"test:cli-integration": "jest --projects test/vscode-tests/cli-integration",
"test:cli-integration": "jest --projects test/vscode-tests/cli-integration --verbose",
"clean-test-dir": "find . -type d -name .vscode-test -exec rm -r {} +",
"update-vscode": "node ./node_modules/vscode/bin/install",
"format": "prettier --write **/*.{ts,tsx} && eslint . --ext .ts,.tsx --fix",
"lint": "eslint . --ext .js,.ts,.tsx --max-warnings=0",
"lint:markdown": "markdownlint-cli2 \"../../**/*.{md,mdx}\" \"!**/node_modules/**\" \"!**/.vscode-test/**\" \"!**/build/cli/v*/**\"",
"find-deadcode": "ts-node scripts/find-deadcode.ts",
"format-staged": "lint-staged",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build",
"lint:scenarios": "ts-node scripts/lint-scenarios.ts",
"check-types": "find . -type f -name \"tsconfig.json\" -not -path \"./node_modules/*\" | sed -r 's|/[^/]+$||' | sort | uniq | xargs -I {} sh -c \"echo Checking types in {} && cd {} && npx tsc --noEmit\"",
"postinstall": "patch-package",
"prepare": "cd ../.. && husky install"
},
"dependencies": {
"@octokit/plugin-retry": "^3.0.9",
"@octokit/plugin-retry": "^4.1.6",
"@octokit/rest": "^19.0.4",
"@vscode/codicons": "^0.0.31",
"@vscode/debugadapter": "^1.59.0",
@@ -1568,58 +1750,63 @@
"ajv": "^8.11.0",
"child-process-promise": "^2.2.1",
"chokidar": "^3.5.3",
"classnames": "~2.2.6",
"classnames": "^2.2.6",
"d3": "^7.6.1",
"d3-graphviz": "^5.0.2",
"fs-extra": "^11.1.1",
"immutable": "^4.0.0",
"js-yaml": "^4.1.0",
"minimatch": "^9.0.0",
"minimist": "~1.2.6",
"minimist": "^1.2.6",
"msw": "^1.2.0",
"nanoid": "^3.2.0",
"node-fetch": "~2.6.7",
"node-fetch": "^2.6.7",
"p-queue": "^6.0.0",
"path-browserify": "^1.0.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"semver": "~7.3.2",
"semver": "^7.5.2",
"source-map": "^0.7.4",
"source-map-support": "^0.5.21",
"stream": "^0.0.2",
"stream-chain": "~2.2.4",
"stream-json": "~1.7.3",
"stream-chain": "^2.2.4",
"stream-json": "^1.7.3",
"styled-components": "^5.3.3",
"tmp": "^0.1.0",
"tmp-promise": "~3.0.2",
"tree-kill": "~1.2.2",
"unzipper": "~0.10.5",
"tmp-promise": "^3.0.2",
"tree-kill": "^1.2.2",
"unzipper": "^0.10.5",
"vscode-extension-telemetry": "^0.1.6",
"vscode-jsonrpc": "^8.0.2",
"vscode-languageclient": "^8.0.2",
"vscode-test-adapter-api": "~1.7.0",
"vscode-test-adapter-util": "~0.7.0",
"zip-a-folder": "~1.1.3"
"vscode-test-adapter-api": "^1.7.0",
"vscode-test-adapter-util": "^0.7.0",
"zip-a-folder": "^2.0.0"
},
"devDependencies": {
"@babel/core": "^7.18.13",
"@babel/plugin-transform-modules-commonjs": "^7.18.6",
"@faker-js/faker": "^7.5.0",
"@babel/preset-env": "^7.21.4",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.21.4",
"@faker-js/faker": "^8.0.2",
"@github/markdownlint-github": "^0.3.0",
"@octokit/plugin-throttling": "^5.0.1",
"@storybook/addon-actions": "^6.5.17-alpha.0",
"@storybook/addon-essentials": "^6.5.17-alpha.0",
"@storybook/addon-interactions": "^6.5.17-alpha.0",
"@storybook/addon-links": "^6.5.17-alpha.0",
"@storybook/builder-webpack5": "^6.5.17-alpha.0",
"@storybook/manager-webpack5": "^6.5.17-alpha.0",
"@storybook/react": "^6.5.17-alpha.0",
"@storybook/testing-library": "^0.0.13",
"@storybook/addon-actions": "^7.1.0",
"@storybook/addon-essentials": "^7.1.0",
"@storybook/addon-interactions": "^7.1.0",
"@storybook/addon-links": "^7.1.0",
"@storybook/components": "^7.1.0",
"@storybook/csf": "^0.1.1",
"@storybook/manager-api": "^7.1.0",
"@storybook/react": "^7.1.0",
"@storybook/react-webpack5": "^7.1.0",
"@storybook/theming": "^7.1.0",
"@testing-library/dom": "^9.3.0",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"@types/child-process-promise": "^2.2.1",
"@types/classnames": "~2.2.9",
"@types/classnames": "^2.2.9",
"@types/d3": "^7.4.0",
"@types/d3-graphviz": "^2.6.6",
"@types/del": "^4.0.0",
@@ -1630,41 +1817,41 @@
"@types/gulp-sourcemaps": "0.0.32",
"@types/jest": "^29.0.2",
"@types/js-yaml": "^3.12.5",
"@types/jszip": "~3.1.6",
"@types/jszip": "^3.1.6",
"@types/nanoid": "^3.0.0",
"@types/node": "^16.11.25",
"@types/node-fetch": "~2.5.2",
"@types/node-fetch": "^2.5.2",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"@types/sarif": "~2.1.2",
"@types/semver": "~7.2.0",
"@types/stream-chain": "~2.0.1",
"@types/stream-json": "~1.7.1",
"@types/sarif": "^2.1.2",
"@types/semver": "^7.2.0",
"@types/stream-chain": "^2.0.1",
"@types/stream-json": "^1.7.1",
"@types/styled-components": "^5.1.11",
"@types/tar-stream": "^2.2.2",
"@types/through2": "^2.0.36",
"@types/tmp": "^0.1.0",
"@types/unzipper": "~0.10.1",
"@types/unzipper": "^0.10.1",
"@types/vscode": "^1.67.0",
"@types/webpack": "^5.28.0",
"@types/webpack-env": "^1.18.0",
"@types/xml2js": "~0.4.4",
"@typescript-eslint/eslint-plugin": "^5.38.0",
"@typescript-eslint/parser": "^5.38.0",
"@vscode/test-electron": "^2.2.0",
"@vscode/vsce": "^2.15.0",
"@vscode/vsce": "^2.19.0",
"ansi-colors": "^4.1.1",
"applicationinsights": "^2.3.5",
"cosmiconfig": "^7.1.0",
"cross-env": "^7.0.3",
"css-loader": "~3.1.0",
"css-loader": "^6.8.1",
"del": "^6.0.0",
"esbuild": "^0.15.15",
"eslint": "^8.23.1",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-etc": "^2.0.2",
"eslint-plugin-github": "^4.4.1",
"eslint-plugin-jest-dom": "^4.0.2",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-jest-dom": "^5.0.1",
"eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-react": "^7.31.8",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-storybook": "^0.6.4",
@@ -1679,13 +1866,14 @@
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3",
"jest-runner-vscode": "^3.0.1",
"lint-staged": "~13.2.0",
"lint-staged": "^13.2.0",
"markdownlint-cli2": "^0.6.0",
"markdownlint-cli2-formatter-pretty": "^0.0.4",
"mini-css-extract-plugin": "^2.6.1",
"npm-run-all": "^4.1.5",
"patch-package": "^6.5.0",
"prettier": "^2.7.1",
"patch-package": "^7.0.0",
"prettier": "^3.0.0",
"storybook": "^7.1.0",
"tar-stream": "^3.0.0",
"through2": "^4.0.2",
"ts-jest": "^29.0.1",
@@ -1693,6 +1881,7 @@
"ts-loader": "^9.4.2",
"ts-node": "^10.7.0",
"ts-protoc-gen": "^0.9.0",
"ts-unused-exports": "^9.0.5",
"typescript": "^5.0.2",
"webpack": "^5.76.0",
"webpack-cli": "^5.0.1"

View File

@@ -18,13 +18,16 @@ import { Octokit, type RestEndpointMethodTypes } from "@octokit/rest";
import { throttling } from "@octokit/plugin-throttling";
import { getFiles } from "./util/files";
import type { GitHubApiRequest } from "../src/mocks/gh-api-request";
import { isGetVariantAnalysisRequest } from "../src/mocks/gh-api-request";
import type { GitHubApiRequest } from "../src/variant-analysis/gh-api/mocks/gh-api-request";
import { isGetVariantAnalysisRequest } from "../src/variant-analysis/gh-api/mocks/gh-api-request";
import { VariantAnalysis } from "../src/variant-analysis/gh-api/variant-analysis";
import { RepositoryWithMetadata } from "../src/variant-analysis/gh-api/repository";
const extensionDirectory = resolve(__dirname, "..");
const scenariosDirectory = resolve(extensionDirectory, "src/mocks/scenarios");
const scenariosDirectory = resolve(
extensionDirectory,
"src/variant-analysis/gh-api/mocks/scenarios",
);
// Make sure we don't run into rate limits by automatically waiting until we can
// make another request.

View File

@@ -0,0 +1,47 @@
import { basename, join, relative, resolve } from "path";
import analyzeTsConfig from "ts-unused-exports";
import { containsPath, pathsEqual } from "../src/common/files";
import { exit } from "process";
function ignoreFile(file: string): boolean {
return (
containsPath("gulpfile.ts", file) ||
containsPath(join("src", "stories"), file) ||
pathsEqual(
join("test", "vscode-tests", "jest-runner-installed-extensions.ts"),
file,
) ||
basename(file) === "jest.config.ts" ||
basename(file) === "index.tsx" ||
basename(file) === "index.ts"
);
}
function main() {
const repositoryRoot = resolve(join(__dirname, ".."));
const result = analyzeTsConfig("tsconfig.deadcode.json");
let foundUnusedExports = false;
for (const [filepath, exportNameAndLocations] of Object.entries(result)) {
const relativeFilepath = relative(repositoryRoot, filepath);
if (ignoreFile(relativeFilepath)) {
continue;
}
foundUnusedExports = true;
console.log(relativeFilepath);
for (const exportNameAndLocation of exportNameAndLocations) {
console.log(` ${exportNameAndLocation.exportName}`);
}
console.log();
}
if (foundUnusedExports) {
exit(1);
}
}
main();

View File

@@ -20,7 +20,10 @@ if (process.argv.length !== 3) {
const scenarioName = process.argv[2];
const extensionDirectory = resolve(__dirname, "..");
const scenariosDirectory = resolve(extensionDirectory, "src/mocks/scenarios");
const scenariosDirectory = resolve(
extensionDirectory,
"src/variant-analysis/gh-api/mocks/scenarios",
);
const scenarioDirectory = resolve(scenariosDirectory, scenarioName);
async function fixScenarioFiles() {

View File

@@ -8,13 +8,19 @@ import { getFiles } from "./util/files";
const extensionDirectory = resolve(__dirname, "..");
const rootDirectory = resolve(extensionDirectory, "../..");
const scenariosDirectory = resolve(extensionDirectory, "src/mocks/scenarios");
const scenariosDirectory = resolve(
extensionDirectory,
"src/variant-analysis/gh-api/mocks/scenarios",
);
const debug = process.env.RUNNER_DEBUG || process.argv.includes("--debug");
async function lintScenarios() {
const schema = createGenerator({
path: resolve(extensionDirectory, "src/mocks/gh-api-request.ts"),
path: resolve(
extensionDirectory,
"src/variant-analysis/gh-api/mocks/gh-api-request.ts",
),
tsconfig: resolve(extensionDirectory, "tsconfig.json"),
type: "GitHubApiRequest",
skipTypeCheck: true,

View File

@@ -0,0 +1,55 @@
import { AppCommandManager } from "../common/commands";
import { Uri, workspace } from "vscode";
import { join } from "path";
import { pathExists } from "fs-extra";
import { isCodespacesTemplate } from "../config";
import { showBinaryChoiceDialog } from "../common/vscode/dialog";
import { extLogger } from "../common/logging/vscode";
/**
* Check if the current workspace is the CodeTour and open the workspace folder.
* Without this, we can't run the code tour correctly.
**/
export async function prepareCodeTour(
commandManager: AppCommandManager,
): Promise<void> {
if (workspace.workspaceFolders?.length) {
const currentFolder = workspace.workspaceFolders[0].uri.fsPath;
const tutorialWorkspacePath = join(
currentFolder,
"tutorial.code-workspace",
);
const toursFolderPath = join(currentFolder, ".tours");
/** We're opening the tutorial workspace, if we detect it.
* This will only happen if the following three conditions are met:
* - the .tours folder exists
* - the tutorial.code-workspace file exists
* - the CODESPACES_TEMPLATE setting doesn't exist (it's only set if the user has already opened
* the tutorial workspace so it's a good indicator that the user is in the folder but has ignored
* the prompt to open the workspace)
*/
if (
(await pathExists(tutorialWorkspacePath)) &&
(await pathExists(toursFolderPath)) &&
!isCodespacesTemplate()
) {
const answer = await showBinaryChoiceDialog(
"We've detected you're in the CodeQL Tour repo. We will need to open the workspace file to continue. Reload?",
);
if (!answer) {
return;
}
const tutorialWorkspaceUri = Uri.file(tutorialWorkspacePath);
void extLogger.log(
`In prepareCodeTour() method, going to open the tutorial workspace file: ${tutorialWorkspacePath}`,
);
await commandManager.execute("vscode.openFolder", tutorialWorkspaceUri);
}
}
}

View File

@@ -1,7 +1,7 @@
import * as semver from "semver";
import { runCodeQlCliCommand } from "./cli";
import { Logger } from "./common";
import { getErrorMessage } from "./pure/helpers-pure";
import { Logger } from "../common/logging";
import { getErrorMessage } from "../common/helpers-pure";
/**
* Get the version of a CodeQL CLI.

View File

@@ -11,8 +11,8 @@ import tk from "tree-kill";
import { promisify } from "util";
import { CancellationToken, Disposable, Uri } from "vscode";
import { BQRSInfo, DecodedBqrsChunk } from "./pure/bqrs-cli-types";
import { allowCanaryQueryServer, CliConfig } from "./config";
import { BQRSInfo, DecodedBqrsChunk } from "../common/bqrs-cli-types";
import { allowCanaryQueryServer, CliConfig } from "../config";
import {
DistributionProvider,
FindDistributionResultKind,
@@ -21,14 +21,15 @@ import {
assertNever,
getErrorMessage,
getErrorStack,
} from "./pure/helpers-pure";
import { QueryMetadata, SortDirection } from "./pure/interface-types";
import { BaseLogger, Logger, ProgressReporter } from "./common";
import { CompilationMessage } from "./pure/legacy-messages";
import { sarifParser } from "./sarif-parser";
import { walkDirectory } from "./helpers";
import { App } from "./common/app";
import { QueryLanguage } from "./common/query-language";
} from "../common/helpers-pure";
import { walkDirectory } from "../common/files";
import { QueryMetadata, SortDirection } from "../common/interface-types";
import { BaseLogger, Logger } from "../common/logging";
import { ProgressReporter } from "../common/logging/vscode";
import { CompilationMessage } from "../query-server/legacy-messages";
import { sarifParser } from "../common/sarif-parser";
import { App } from "../common/app";
import { QueryLanguage } from "../common/query-language";
/**
* The version of the SARIF format that we are using.
@@ -134,6 +135,11 @@ export interface SourceInfo {
sourceLocationPrefix: string;
}
/**
* The expected output of `codeql resolve queries`.
*/
export type ResolvedQueries = string[];
/**
* The expected output of `codeql resolve tests`.
*/
@@ -213,7 +219,7 @@ export class CodeQLCliServer implements Disposable {
private readonly app: App,
private distributionProvider: DistributionProvider,
private cliConfig: CliConfig,
private logger: Logger,
public readonly logger: Logger,
) {
this.commandQueue = [];
this.commandInProcess = false;
@@ -325,6 +331,7 @@ export class CodeQLCliServer implements Disposable {
commandArgs: string[],
description: string,
onLine?: OnLineCallback,
silent?: boolean,
): Promise<string> {
const stderrBuffers: Buffer[] = [];
if (this.commandInProcess) {
@@ -344,7 +351,12 @@ export class CodeQLCliServer implements Disposable {
// Compute the full args array
const args = command.concat(LOGGING_FLAGS).concat(commandArgs);
const argsString = args.join(" ");
void this.logger.log(`${description} using CodeQL CLI: ${argsString}...`);
// If we are running silently, we don't want to print anything to the console.
if (!silent) {
void this.logger.log(
`${description} using CodeQL CLI: ${argsString}...`,
);
}
try {
await new Promise<void>((resolve, reject) => {
// Start listening to stdout
@@ -390,24 +402,30 @@ export class CodeQLCliServer implements Disposable {
const fullBuffer = Buffer.concat(stdoutBuffers);
// Make sure we remove the terminator;
const data = fullBuffer.toString("utf8", 0, fullBuffer.length - 1);
void this.logger.log("CLI command succeeded.");
if (!silent) {
void this.logger.log("CLI command succeeded.");
}
return data;
} catch (err) {
// Kill the process if it isn't already dead.
this.killProcessIfRunning();
// Report the error (if there is a stderr then use that otherwise just report the error cod or nodejs error)
// Report the error (if there is a stderr then use that otherwise just report the error code or nodejs error)
const newError =
stderrBuffers.length === 0
? new Error(`${description} failed: ${err}`)
? new Error(
`${description} failed with args:${EOL} ${argsString}${EOL}${err}`,
)
: new Error(
`${description} failed: ${Buffer.concat(stderrBuffers).toString(
"utf8",
)}`,
`${description} failed with args:${EOL} ${argsString}${EOL}${Buffer.concat(
stderrBuffers,
).toString("utf8")}`,
);
newError.stack += getErrorStack(err);
throw newError;
} finally {
void this.logger.log(Buffer.concat(stderrBuffers).toString("utf8"));
if (!silent) {
void this.logger.log(Buffer.concat(stderrBuffers).toString("utf8"));
}
// Remove the listeners we set up.
process.stdout.removeAllListeners("data");
process.stderr.removeAllListeners("data");
@@ -544,9 +562,11 @@ export class CodeQLCliServer implements Disposable {
{
progressReporter,
onLine,
silent = false,
}: {
progressReporter?: ProgressReporter;
onLine?: OnLineCallback;
silent?: boolean;
} = {},
): Promise<string> {
if (progressReporter) {
@@ -562,6 +582,7 @@ export class CodeQLCliServer implements Disposable {
commandArgs,
description,
onLine,
silent,
).then(resolve, reject);
} catch (err) {
reject(err);
@@ -595,10 +616,12 @@ export class CodeQLCliServer implements Disposable {
addFormat = true,
progressReporter,
onLine,
silent = false,
}: {
addFormat?: boolean;
progressReporter?: ProgressReporter;
onLine?: OnLineCallback;
silent?: boolean;
} = {},
): Promise<OutputType> {
let args: string[] = [];
@@ -609,6 +632,7 @@ export class CodeQLCliServer implements Disposable {
const result = await this.runCodeQlCliCommand(command, args, description, {
progressReporter,
onLine,
silent,
});
try {
return JSON.parse(result) as OutputType;
@@ -695,6 +719,7 @@ export class CodeQLCliServer implements Disposable {
async resolveLibraryPath(
workspaces: string[],
queryPath: string,
silent = false,
): Promise<QuerySetup> {
const subcommandArgs = [
"--query",
@@ -705,6 +730,7 @@ export class CodeQLCliServer implements Disposable {
["resolve", "library-path"],
subcommandArgs,
"Resolving library paths",
{ silent },
);
}
@@ -731,6 +757,25 @@ export class CodeQLCliServer implements Disposable {
);
}
/**
* Finds all available queries in a given directory.
* @param queryDir Root of directory tree to search for queries.
* @param silent If true, don't print logs to the CodeQL extension log.
* @returns The list of queries that were found.
*/
public async resolveQueries(
queryDir: string,
silent?: boolean,
): Promise<ResolvedQueries> {
const subcommandArgs = [queryDir];
return await this.runJsonCodeQlCliCommand<ResolvedQueries>(
["resolve", "queries"],
subcommandArgs,
"Resolving queries",
{ silent },
);
}
/**
* Finds all available QL tests in a given directory.
* @param testPath Root of directory tree to search for tests.
@@ -1031,6 +1076,7 @@ export class CodeQLCliServer implements Disposable {
resultsPath: string,
interpretedResultsPath: string,
sourceInfo?: SourceInfo,
args?: string[],
): Promise<sarif.Log> {
const additionalArgs = [
// TODO: This flag means that we don't group interpreted results
@@ -1038,6 +1084,7 @@ export class CodeQLCliServer implements Disposable {
// interpretation with and without this flag, or do some
// grouping client-side.
"--no-group-results",
...(args ?? []),
];
await this.runInterpretCommand(
@@ -1381,21 +1428,13 @@ export class CodeQLCliServer implements Disposable {
async packPacklist(dir: string, includeQueries: boolean): Promise<string[]> {
const args = includeQueries ? [dir] : ["--no-include-queries", dir];
// since 2.7.1, packlist returns an object with a "paths" property that is a list of packs.
// previous versions return a list of packs.
const results: { paths: string[] } | string[] =
await this.runJsonCodeQlCliCommand(
["pack", "packlist"],
args,
"Generating the pack list",
);
const results: { paths: string[] } = await this.runJsonCodeQlCliCommand(
["pack", "packlist"],
args,
"Generating the pack list",
);
// Once we no longer need to support 2.7.0 or earlier, we can remove this and assume all versions return an object.
if ("paths" in results) {
return results.paths;
} else {
return results;
}
return results.paths;
}
async packResolveDependencies(
@@ -1431,9 +1470,9 @@ export class CodeQLCliServer implements Disposable {
// this._version is only undefined upon config change, so we reset CLI-based context key only when necessary.
await this.app.commands.execute(
"setContext",
"codeql.supportsEvalLog",
"codeql.supportsQuickEvalCount",
newVersion.compare(
CliVersionConstraint.CLI_VERSION_WITH_PER_QUERY_EVAL_LOG,
CliVersionConstraint.CLI_VERSION_WITH_QUICK_EVAL_COUNT,
) >= 0,
);
} catch (e) {
@@ -1525,10 +1564,23 @@ export function spawnServer(
);
}
let lastStdout: any = undefined;
child.stdout!.on("data", (data) => {
lastStdout = data;
});
// Set up event listeners.
child.on("close", (code) =>
logger.log(`Child process exited with code ${code}`),
);
child.on("close", async (code, signal) => {
if (code !== null)
void logger.log(`Child process exited with code ${code}`);
if (signal)
void logger.log(
`Child process exited due to receipt of signal ${signal}`,
);
// If the process exited abnormally, log the last stdout message,
// It may be from the jvm.
if (code !== 0 && lastStdout !== undefined)
void logger.log(`Last stdout was "${lastStdout.toString()}"`);
});
child.stderr!.on("data", stderrListener);
if (stdoutListener !== undefined) {
child.stdout!.on("data", stdoutListener);
@@ -1699,31 +1751,32 @@ async function logStream(stream: Readable, logger: BaseLogger): Promise<void> {
}
}
export function shouldDebugIdeServer() {
function isEnvTrue(name: string): boolean {
return (
"IDE_SERVER_JAVA_DEBUG" in process.env &&
process.env.IDE_SERVER_JAVA_DEBUG !== "0" &&
process.env.IDE_SERVER_JAVA_DEBUG?.toLocaleLowerCase() !== "false"
name in process.env &&
process.env[name] !== "0" &&
// Use en-US since we expect the value to be either "false" or "FALSE", not a localized version.
process.env[name]?.toLocaleLowerCase("en-US") !== "false"
);
}
export function shouldDebugIdeServer() {
return isEnvTrue("IDE_SERVER_JAVA_DEBUG");
}
export function shouldDebugQueryServer() {
return (
"QUERY_SERVER_JAVA_DEBUG" in process.env &&
process.env.QUERY_SERVER_JAVA_DEBUG !== "0" &&
process.env.QUERY_SERVER_JAVA_DEBUG?.toLocaleLowerCase() !== "false"
);
return isEnvTrue("QUERY_SERVER_JAVA_DEBUG");
}
export function shouldDebugCliServer() {
return (
"CLI_SERVER_JAVA_DEBUG" in process.env &&
process.env.CLI_SERVER_JAVA_DEBUG !== "0" &&
process.env.CLI_SERVER_JAVA_DEBUG?.toLocaleLowerCase() !== "false"
);
return isEnvTrue("CLI_SERVER_JAVA_DEBUG");
}
export class CliVersionConstraint {
// The oldest version of the CLI that we support. This is used to determine
// whether to show a warning about the CLI being too old on startup.
public static OLDEST_SUPPORTED_CLI_VERSION = new SemVer("2.9.4");
/**
* CLI version where building QLX packs for remote queries is supported.
* (The options were _accepted_ by a few earlier versions, but only from
@@ -1739,21 +1792,9 @@ export class CliVersionConstraint {
);
/**
* CLI version where the `--evaluator-log` and related options to the query server were introduced,
* on a per-query server basis.
* CLI version where the `resolve extensions` subcommand exists.
*/
public static CLI_VERSION_WITH_STRUCTURED_EVAL_LOG = new SemVer("2.8.2");
/**
* CLI version that supports rotating structured logs to produce one per query.
*
* Note that 2.8.4 supports generating the evaluation logs and summaries,
* but 2.9.0 includes a new option to produce the end-of-query summary logs to
* the query server console. For simplicity we gate all features behind 2.9.0,
* but if a user is tied to the 2.8 release, we can enable evaluator logs
* and summaries for them.
*/
public static CLI_VERSION_WITH_PER_QUERY_EVAL_LOG = new SemVer("2.9.0");
public static CLI_VERSION_WITH_RESOLVE_EXTENSIONS = new SemVer("2.10.2");
/**
* CLI version that supports the `--sourcemap` option for log generation.
@@ -1782,6 +1823,20 @@ export class CliVersionConstraint {
"2.12.4",
);
public static CLI_VERSION_GLOBAL_CACHE = new SemVer("2.12.4");
/**
* CLI version where the query server supports quick-eval count mode.
*/
public static CLI_VERSION_WITH_QUICK_EVAL_COUNT = new SemVer("2.13.3");
/**
* CLI version where the langauge server supports visisbility change notifications.
*/
public static CLI_VERSION_WITH_VISIBILITY_NOTIFICATIONS = new SemVer(
"2.14.0",
);
constructor(private readonly cli: CodeQLCliServer) {
/**/
}
@@ -1800,15 +1855,9 @@ export class CliVersionConstraint {
);
}
async supportsStructuredEvalLog() {
async supportsResolveExtensions() {
return this.isVersionAtLeast(
CliVersionConstraint.CLI_VERSION_WITH_STRUCTURED_EVAL_LOG,
);
}
async supportsPerQueryEvalLog() {
return this.isVersionAtLeast(
CliVersionConstraint.CLI_VERSION_WITH_PER_QUERY_EVAL_LOG,
CliVersionConstraint.CLI_VERSION_WITH_RESOLVE_EXTENSIONS,
);
}
@@ -1851,4 +1900,20 @@ export class CliVersionConstraint {
CliVersionConstraint.CLI_VERSION_WITH_ADDITIONAL_PACKS_INSTALL,
);
}
async usesGlobalCompilationCache() {
return this.isVersionAtLeast(CliVersionConstraint.CLI_VERSION_GLOBAL_CACHE);
}
async supportsVisibilityNotifications() {
return this.isVersionAtLeast(
CliVersionConstraint.CLI_VERSION_WITH_VISIBILITY_NOTIFICATIONS,
);
}
async supportsQuickEvalCount() {
return this.isVersionAtLeast(
CliVersionConstraint.CLI_VERSION_WITH_QUICK_EVAL_COUNT,
);
}
}

View File

@@ -3,24 +3,29 @@ import { pathExists, mkdtemp, createWriteStream, remove } from "fs-extra";
import { tmpdir } from "os";
import { delimiter, dirname, join } from "path";
import * as semver from "semver";
import { parse } from "url";
import { URL } from "url";
import { ExtensionContext, Event } from "vscode";
import { DistributionConfig } from "./config";
import {
InvocationRateLimiter,
InvocationRateLimiterResultKind,
showAndLogErrorMessage,
showAndLogWarningMessage,
} from "./helpers";
import { extLogger } from "./common";
import { DistributionConfig } from "../config";
import { extLogger } from "../common/logging/vscode";
import { getCodeQlCliVersion } from "./cli-version";
import { ProgressCallback, reportStreamProgress } from "./progress";
import {
ProgressCallback,
reportStreamProgress,
} from "../common/vscode/progress";
import {
codeQlLauncherName,
deprecatedCodeQlLauncherName,
extractZipArchive,
getRequiredAssetName,
} from "./pure/distribution";
} from "../common/distribution";
import {
InvocationRateLimiter,
InvocationRateLimiterResultKind,
} from "../common/invocation-rate-limiter";
import {
showAndLogErrorMessage,
showAndLogWarningMessage,
} from "../common/logging";
/**
* distribution.ts
@@ -73,7 +78,7 @@ export class DistributionManager implements DistributionProvider {
extensionContext,
);
this.updateCheckRateLimiter = new InvocationRateLimiter(
extensionContext,
extensionContext.globalState,
"extensionSpecificDistributionUpdateCheck",
() =>
this.extensionSpecificDistributionManager.checkForUpdatesToDistribution(),
@@ -155,6 +160,7 @@ export class DistributionManager implements DistributionProvider {
if (this.config.customCodeQlPath) {
if (!(await pathExists(this.config.customCodeQlPath))) {
void showAndLogErrorMessage(
extLogger,
`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.",
@@ -502,7 +508,7 @@ class ExtensionSpecificDistributionManager {
0,
) || "";
return join(
this.extensionContext.globalStoragePath,
this.extensionContext.globalStorageUri.fsPath,
ExtensionSpecificDistributionManager._currentDistributionFolderBaseName +
distributionFolderIndex,
);
@@ -667,7 +673,7 @@ export class ReleasesApiConsumer {
redirectUrl &&
redirectCount < ReleasesApiConsumer._maxRedirects
) {
const parsedRedirectUrl = parse(redirectUrl);
const parsedRedirectUrl = new URL(redirectUrl);
if (parsedRedirectUrl.protocol !== "https:") {
throw new Error("Encountered a non-https redirect, rejecting");
}
@@ -712,7 +718,7 @@ export enum DistributionKind {
PathEnvironmentVariable,
}
export interface Distribution {
interface Distribution {
codeQlPath: string;
kind: DistributionKind;
}
@@ -770,22 +776,22 @@ type DistributionUpdateCheckResult =
| InvalidLocationResult
| UpdateAvailableResult;
export interface AlreadyCheckedRecentlyResult {
interface AlreadyCheckedRecentlyResult {
kind: DistributionUpdateCheckResultKind.AlreadyCheckedRecentlyResult;
}
export interface AlreadyUpToDateResult {
interface AlreadyUpToDateResult {
kind: DistributionUpdateCheckResultKind.AlreadyUpToDate;
}
/**
* The distribution could not be installed or updated because it is not managed by the extension.
*/
export interface InvalidLocationResult {
interface InvalidLocationResult {
kind: DistributionUpdateCheckResultKind.InvalidLocation;
}
export interface UpdateAvailableResult {
interface UpdateAvailableResult {
kind: DistributionUpdateCheckResultKind.UpdateAvailable;
updatedRelease: Release;
}
@@ -847,6 +853,7 @@ export async function getExecutableFromDirectory(
function warnDeprecatedLauncher() {
void showAndLogWarningMessage(
extLogger,
`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.`,
);
@@ -855,7 +862,7 @@ function warnDeprecatedLauncher() {
/**
* A release on GitHub.
*/
export interface Release {
interface Release {
assets: ReleaseAsset[];
/**
@@ -877,7 +884,7 @@ export interface Release {
/**
* An asset corresponding to a release on GitHub.
*/
export interface ReleaseAsset {
interface ReleaseAsset {
/**
* The id associated with the asset on GitHub.
*/
@@ -947,7 +954,10 @@ export interface GithubReleaseAsset {
}
export class GithubApiError extends Error {
constructor(public status: number, public body: string) {
constructor(
public status: number,
public body: string,
) {
super(`API call failed with status code ${status}, body: ${body}`);
}
}

View File

@@ -0,0 +1,80 @@
import { CodeQLCliServer } from "./cli";
import { Uri, window } from "vscode";
import { isQueryLanguage, QueryLanguage } from "../common/query-language";
import { getOnDiskWorkspaceFolders } from "../common/vscode/workspace-folders";
import { extLogger } from "../common/logging/vscode";
import { UserCancellationException } from "../common/vscode/progress";
import { showAndLogErrorMessage } from "../common/logging";
/**
* 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<QueryLanguage | 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 extLogger.log(`Detected query language: ${language}`);
if (isQueryLanguage(language)) {
return language;
}
void extLogger.log(
"Query language is unsupported. Select language manually.",
);
} catch (e) {
void extLogger.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<QueryLanguage | 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(
extLogger,
"Language not found. Language must be specified manually.",
);
}
return undefined;
}
if (!isQueryLanguage(language)) {
void showAndLogErrorMessage(
extLogger,
`Language '${language}' is not supported. Only languages ${Object.values(
QueryLanguage,
).join(", ")} are supported.`,
);
return undefined;
}
return language;
}

View File

@@ -0,0 +1,22 @@
import { CodeQLCliServer } from "./cli";
import { QueryMetadata } from "../common/interface-types";
import { extLogger } from "../common/logging/vscode";
/**
* 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 extLogger.log(`Couldn't resolve metadata for ${queryPath}: ${e}`);
return;
}
}

View File

@@ -1,14 +1,16 @@
import { Credentials } from "./authentication";
import { Disposable } from "../pure/disposable-object";
import { Disposable } from "./disposable-object";
import { AppEventEmitter } from "./events";
import { Logger } from "./logging";
import { NotificationLogger } from "./logging";
import { Memento } from "./memento";
import { AppCommandManager } from "./commands";
import { AppTelemetry } from "./telemetry";
export interface App {
createEventEmitter<T>(): AppEventEmitter<T>;
readonly mode: AppMode;
readonly logger: Logger;
readonly logger: NotificationLogger;
readonly telemetry?: AppTelemetry;
readonly subscriptions: Disposable[];
readonly extensionPath: string;
readonly globalStoragePath: string;
@@ -16,6 +18,7 @@ export interface App {
readonly workspaceState: Memento;
readonly credentials: Credentials;
readonly commands: AppCommandManager;
readonly environment: EnvironmentContext;
}
export enum AppMode {
@@ -23,3 +26,7 @@ export enum AppMode {
Development = 2,
Test = 3,
}
export interface EnvironmentContext {
language: string;
}

View File

@@ -1,5 +1,3 @@
export const PAGE_SIZE = 1000;
/**
* The single-character codes used in the bqrs format for the the kind
* of a result column. This namespace is intentionally not an enum, see
@@ -15,7 +13,7 @@ export namespace ColumnKindCode {
export const ENTITY = "e";
}
export type ColumnKind =
type ColumnKind =
| typeof ColumnKindCode.FLOAT
| typeof ColumnKindCode.INTEGER
| typeof ColumnKindCode.STRING
@@ -46,7 +44,7 @@ export function getResultSetSchema(
}
return undefined;
}
export interface PaginationInfo {
interface PaginationInfo {
"step-size": number;
offsets: number[];
}
@@ -115,7 +113,7 @@ export type BqrsKind =
| "Entity";
interface BqrsColumn {
name: string;
name?: string;
kind: BqrsKind;
}
export interface DecodedBqrsChunk {

View File

@@ -4,7 +4,7 @@ import {
LineColumnLocation,
WholeFileLocation,
} from "./bqrs-cli-types";
import { createRemoteFileRef } from "./location-link-utils";
import { createRemoteFileRef } from "../common/location-link-utils";
/**
* The CodeQL filesystem libraries use this pattern in `getURL()` predicates
@@ -142,5 +142,7 @@ export function tryGetRemoteLocation(
fileLink,
resolvableLocation.startLine,
resolvableLocation.endLine,
resolvableLocation.startColumn,
resolvableLocation.endColumn,
);
}

View File

@@ -1,17 +1,17 @@
import type { CommandManager } from "../packages/commands";
import type { Uri, Range, TextDocumentShowOptions } from "vscode";
import type { AstItem } from "../astViewer";
import type { AstItem } from "../language-support";
import type { DbTreeViewItem } from "../databases/ui/db-tree-view-item";
import type { DatabaseItem } from "../local-databases";
import type { DatabaseItem } from "../databases/local-databases";
import type { QueryHistoryInfo } from "../query-history/query-history-info";
import type { RepositoriesFilterSortStateWithIds } from "../pure/variant-analysis-filter-sort";
import type { TestTreeNode } from "../test-tree-node";
import type { TestTreeNode } from "../query-testing/test-tree-node";
import type {
VariantAnalysis,
VariantAnalysisScannedRepository,
VariantAnalysisScannedRepositoryResult,
} from "../variant-analysis/shared/variant-analysis";
import type { QLDebugConfiguration } from "../debugger/debug-configuration";
import type { QueryTreeViewItem } from "../queries-panel/query-tree-view-item";
// A command function matching the signature that VS Code calls when
// a command is invoked from a context menu on a TreeView with
@@ -55,7 +55,7 @@ export type ExplorerSelectionCommandFunction<Item> = (
// Builtin commands where the implementation is provided by VS Code and not by this extension.
// See https://code.visualstudio.com/api/references/commands
export type BuiltInVsCodeCommands = {
type BuiltInVsCodeCommands = {
// The codeQLDatabases.focus command is provided by VS Code because we've registered the custom view
"codeQLDatabases.focus": () => Promise<void>;
"markdown.showPreviewToSide": (uri: Uri) => Promise<void>;
@@ -115,6 +115,10 @@ export type QueryEditorCommands = {
selectedQuery: Uri,
) => Promise<void>;
"codeQL.previewQueryHelp": (selectedQuery: Uri) => Promise<void>;
"codeQL.previewQueryHelpContextEditor": (selectedQuery: Uri) => Promise<void>;
"codeQL.previewQueryHelpContextExplorer": (
selectedQuery: Uri,
) => Promise<void>;
};
// Commands used for running local queries
@@ -125,8 +129,14 @@ export type LocalQueryCommands = {
"codeQL.runQueryOnMultipleDatabasesContextEditor": (
uri?: Uri,
) => Promise<void>;
"codeQLQueries.runLocalQueryFromQueriesPanel": TreeViewContextSingleSelectionCommandFunction<QueryTreeViewItem>;
"codeQLQueries.runLocalQueryContextMenu": TreeViewContextSingleSelectionCommandFunction<QueryTreeViewItem>;
"codeQLQueries.runLocalQueriesContextMenu": TreeViewContextSingleSelectionCommandFunction<QueryTreeViewItem>;
"codeQLQueries.runLocalQueriesFromPanel": TreeViewContextSingleSelectionCommandFunction<QueryTreeViewItem>;
"codeQL.runLocalQueryFromFileTab": (uri: Uri) => Promise<void>;
"codeQL.runQueries": ExplorerSelectionCommandFunction<Uri>;
"codeQL.quickEval": (uri: Uri) => Promise<void>;
"codeQL.quickEvalCount": (uri: Uri) => Promise<void>;
"codeQL.quickEvalContextEditor": (uri: Uri) => Promise<void>;
"codeQL.codeLensQuickEval": (uri: Uri, range: Range) => Promise<void>;
"codeQL.quickQuery": () => Promise<void>;
@@ -233,10 +243,6 @@ export type VariantAnalysisCommands = {
scannedRepo: VariantAnalysisScannedRepository,
variantAnalysisSummary: VariantAnalysis,
) => Promise<void>;
"codeQL.copyVariantAnalysisRepoList": (
variantAnalysisId: number,
filterSort?: RepositoriesFilterSortStateWithIds,
) => Promise<void>;
"codeQL.loadVariantAnalysisRepoResults": (
variantAnalysisId: number,
repositoryFullName: string,
@@ -247,6 +253,9 @@ export type VariantAnalysisCommands = {
"codeQL.monitorRehydratedVariantAnalysis": (
variantAnalysis: VariantAnalysis,
) => Promise<void>;
"codeQL.monitorReauthenticatedVariantAnalysis": (
variantAnalysis: VariantAnalysis,
) => Promise<void>;
"codeQL.openVariantAnalysisLogs": (
variantAnalysisId: number,
) => Promise<void>;
@@ -255,6 +264,7 @@ export type VariantAnalysisCommands = {
) => Promise<void>;
"codeQL.runVariantAnalysis": (uri?: Uri) => Promise<void>;
"codeQL.runVariantAnalysisContextEditor": (uri?: Uri) => Promise<void>;
"codeQLQueries.runVariantAnalysisContextMenu": TreeViewContextSingleSelectionCommandFunction<QueryTreeViewItem>;
};
export type DatabasePanelCommands = {
@@ -268,6 +278,7 @@ export type DatabasePanelCommands = {
"codeQLVariantAnalysisRepositories.openOnGitHubContextMenu": TreeViewContextSingleSelectionCommandFunction<DbTreeViewItem>;
"codeQLVariantAnalysisRepositories.renameItemContextMenu": TreeViewContextSingleSelectionCommandFunction<DbTreeViewItem>;
"codeQLVariantAnalysisRepositories.removeItemContextMenu": TreeViewContextSingleSelectionCommandFunction<DbTreeViewItem>;
"codeQLVariantAnalysisRepositories.importFromCodeSearch": TreeViewContextSingleSelectionCommandFunction<DbTreeViewItem>;
};
export type AstCfgCommands = {
@@ -299,6 +310,7 @@ export type EvalLogViewerCommands = {
export type SummaryLanguageSupportCommands = {
"codeQL.gotoQL": () => Promise<void>;
"codeQL.gotoQLContextEditor": () => Promise<void>;
};
export type TestUICommands = {

View File

@@ -1,25 +1,38 @@
import { DisposableObject } from "./pure/disposable-object";
import { extLogger } from "./common";
import { getErrorMessage } from "./pure/helpers-pure";
import { DisposableObject } from "./disposable-object";
import { getErrorMessage } from "./helpers-pure";
import { Logger } from "./logging";
/**
* Base class for "discovery" operations, which scan the file system to find specific kinds of
* files. This class automatically prevents more than one discovery operation from running at the
* same time.
*/
export abstract class Discovery<T> extends DisposableObject {
private retry = false;
private discoveryInProgress = false;
export abstract class Discovery extends DisposableObject {
private restartWhenFinished = false;
private currentDiscoveryPromise: Promise<void> | undefined;
constructor(private readonly name: string) {
constructor(
protected readonly name: string,
private readonly logger: Logger,
) {
super();
}
/**
* Returns the promise of the currently running refresh operation, if one is in progress.
* Otherwise returns a promise that resolves immediately.
*/
public waitForCurrentRefresh(): Promise<void> {
return this.currentDiscoveryPromise ?? Promise.resolve();
}
/**
* Force the discovery process to run. Normally invoked by the derived class when a relevant file
* system change is detected.
*
* Returns a promise that resolves when the refresh is complete, including any retries.
*/
public refresh(): void {
public refresh(): Promise<void> {
// We avoid having multiple discovery operations in progress at the same time. Otherwise, if we
// got a storm of refresh requests due to, say, the copying or deletion of a large directory
// tree, we could potentially spawn a separate simultaneous discovery operation for each
@@ -36,14 +49,16 @@ export abstract class Discovery<T> extends DisposableObject {
// other change notifications that might be coming along. However, this would create more
// latency in the common case, in order to save a bit of latency in the uncommon case.
if (this.discoveryInProgress) {
if (this.currentDiscoveryPromise !== undefined) {
// There's already a discovery operation in progress. Tell it to restart when it's done.
this.retry = true;
this.restartWhenFinished = true;
} else {
// No discovery in progress, so start one now.
this.discoveryInProgress = true;
this.launchDiscovery();
this.currentDiscoveryPromise = this.launchDiscovery().finally(() => {
this.currentDiscoveryPromise = undefined;
});
}
return this.currentDiscoveryPromise;
}
/**
@@ -51,46 +66,28 @@ export abstract class Discovery<T> extends DisposableObject {
* discovery operation completes, the `update` function will be invoked with the results of the
* discovery.
*/
private launchDiscovery(): void {
const discoveryPromise = this.discover();
discoveryPromise
.then((results) => {
if (!this.retry) {
// Update any listeners with the results of the discovery.
this.discoveryInProgress = false;
this.update(results);
}
})
private async launchDiscovery(): Promise<void> {
try {
await this.discover();
} catch (err) {
void this.logger.log(
`${this.name} failed. Reason: ${getErrorMessage(err)}`,
);
}
.catch((err: unknown) => {
void extLogger.log(
`${this.name} failed. Reason: ${getErrorMessage(err)}`,
);
})
.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();
}
});
if (this.restartWhenFinished) {
// 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.
// We want to relaunch discovery regardless of if the initial discovery operation
// succeeded or failed.
this.restartWhenFinished = false;
await this.launchDiscovery();
}
}
/**
* Overridden by the derived class to spawn the actual discovery operation, returning the results.
*/
protected abstract discover(): Promise<T>;
/**
* Overridden by the derived class to atomically update the `Discovery` object with the results of
* the discovery operation, and to notify any listeners that the discovery results may have
* changed.
* @param results The discovery results returned by the `discover` function.
*/
protected abstract update(results: T): void;
protected abstract discover(): Promise<void>;
}

View File

@@ -1,10 +1,10 @@
import { Disposable } from "../pure/disposable-object";
import { Disposable } from "./disposable-object";
export interface AppEvent<T> {
(listener: (event: T) => void): Disposable;
}
export interface AppEventEmitter<T> {
export interface AppEventEmitter<T> extends Disposable {
event: AppEvent<T>;
fire(data: T): void;
}

View File

@@ -0,0 +1,122 @@
import { basename, dirname, join } from "path";
import { EnvironmentContext } from "./app";
/**
* A node in the tree of files. This will be either a `FileTreeDirectory` or a `FileTreeLeaf`.
*/
export abstract class FileTreeNode<T = undefined> {
constructor(
private _path: string,
private _name: string,
private _data?: T,
) {}
public get path(): string {
return this._path;
}
public get name(): string {
return this._name;
}
public get data(): T | undefined {
return this._data;
}
public abstract get children(): ReadonlyArray<FileTreeNode<T>>;
public abstract finish(): void;
}
/**
* A directory containing one or more files or other directories.
*/
export class FileTreeDirectory<T = undefined> extends FileTreeNode<T> {
constructor(
_path: string,
_name: string,
protected readonly env: EnvironmentContext,
private _children: Array<FileTreeNode<T>> = [],
) {
super(_path, _name);
}
public get children(): ReadonlyArray<FileTreeNode<T>> {
return this._children;
}
public addChild(child: FileTreeNode<T>): void {
this._children.push(child);
}
public createDirectory(relativePath: string): FileTreeDirectory<T> {
if (relativePath === ".") {
return this;
}
const dirName = dirname(relativePath);
if (dirName === ".") {
return this.createChildDirectory(relativePath);
} else {
const parent = this.createDirectory(dirName);
return parent.createDirectory(basename(relativePath));
}
}
public finish(): void {
// remove empty directories
this._children.filter(
(child) => child instanceof FileTreeLeaf || child.children.length > 0,
);
this._children.sort((a, b) =>
a.name.localeCompare(b.name, this.env.language),
);
this._children.forEach((child, i) => {
child.finish();
if (
child.children?.length === 1 &&
child.children[0] instanceof FileTreeDirectory
) {
// collapse children
const replacement = new FileTreeDirectory<T>(
child.children[0].path,
`${child.name} / ${child.children[0].name}`,
this.env,
Array.from(child.children[0].children),
);
this._children[i] = replacement;
}
});
}
private createChildDirectory(name: string): FileTreeDirectory<T> {
const existingChild = this._children.find((child) => child.name === name);
if (existingChild !== undefined) {
return existingChild as FileTreeDirectory<T>;
} else {
const newChild = new FileTreeDirectory<T>(
join(this.path, name),
name,
this.env,
);
this.addChild(newChild);
return newChild;
}
}
}
/**
* A single file.
*/
export class FileTreeLeaf<T = undefined> extends FileTreeNode<T> {
constructor(_path: string, _name: string, _data?: T) {
super(_path, _name, _data);
}
public get children(): ReadonlyArray<FileTreeNode<T>> {
return [];
}
public finish(): void {
/**/
}
}

View File

@@ -0,0 +1,129 @@
import { pathExists, stat, readdir, opendir } from "fs-extra";
import { isAbsolute, join, relative, resolve } from "path";
import { tmpdir as osTmpdir } from "os";
/**
* Recursively finds all .ql files in this set of Uris.
*
* @param paths The list of Uris to search through
*
* @returns list of ql files and a boolean describing whether or not a directory was found/
*/
export async function gatherQlFiles(
paths: string[],
): Promise<[string[], boolean]> {
const gatheredUris: Set<string> = new Set();
let dirFound = false;
for (const nextPath of paths) {
if ((await pathExists(nextPath)) && (await stat(nextPath)).isDirectory()) {
dirFound = true;
const subPaths = await readdir(nextPath);
const fullPaths = subPaths.map((p) => join(nextPath, p));
const nestedFiles = (await gatherQlFiles(fullPaths))[0];
nestedFiles.forEach((nested) => gatheredUris.add(nested));
} else if (nextPath.endsWith(".ql")) {
gatheredUris.add(nextPath);
}
}
return [Array.from(gatheredUris), dirFound];
}
/**
* Lists the names of directories inside the given path.
* @param path The path to the directory to read.
* @returns the names of the directories inside the given path.
*/
export async function getDirectoryNamesInsidePath(
path: string,
): Promise<string[]> {
if (!(await pathExists(path))) {
throw Error(`Path does not exist: ${path}`);
}
if (!(await stat(path)).isDirectory()) {
throw Error(`Path is not a directory: ${path}`);
}
const dirItems = await readdir(path, { withFileTypes: true });
const dirNames = dirItems
.filter((dirent) => dirent.isDirectory())
.map((dirent) => dirent.name);
return dirNames;
}
export function normalizePath(path: string): string {
// On Windows, "C:/", "C:\", and "c:/" are all equivalent. We need
// to normalize the paths to ensure they all get resolved to the
// same format. On Windows, we also need to do the comparison
// case-insensitively.
path = resolve(path);
if (process.platform === "win32") {
path = path.toLowerCase();
}
return path;
}
export function pathsEqual(path1: string, path2: string): boolean {
return normalizePath(path1) === normalizePath(path2);
}
/**
* Returns true if `parent` contains `child`, or if they are equal.
*/
export function containsPath(parent: string, child: string): boolean {
const relativePath = relative(parent, child);
return (
!relativePath.startsWith("..") &&
// On windows, if the two paths are in different drives, then the
// relative path will be an absolute path to the other drive.
!isAbsolute(relativePath)
);
}
export async function readDirFullPaths(path: string): Promise<string[]> {
const baseNames = await readdir(path);
return baseNames.map((baseName) => join(path, baseName));
}
/**
* 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 opendir(dir)) {
const entry = join(dir, d.name);
seenFiles.add(entry);
if (d.isDirectory()) {
yield* walkDirectory(entry);
} else if (d.isFile()) {
yield entry;
}
}
}
/**
* Error thrown from methods from the `fs` module.
*
* In practice, any error matching this is likely an instance of `NodeJS.ErrnoException`.
* If desired in the future, we could model more fields or use `NodeJS.ErrnoException` directly.
*/
export interface IOError {
readonly code: string;
}
export function isIOError(e: any): e is IOError {
return e.code !== undefined && typeof e.code === "string";
}
// This function is a wrapper around `os.tmpdir()` to make it easier to mock in tests.
export function tmpdir(): string {
return osTmpdir();
}

View File

@@ -1,4 +1,4 @@
import { OWNER_REGEX, REPO_REGEX } from "../pure/helpers-pure";
import { OWNER_REGEX, REPO_REGEX } from "./helpers-pure";
/**
* Checks if a string is a valid GitHub NWO.

View File

@@ -1 +0,0 @@
export * from "./logging";

View File

@@ -5,18 +5,22 @@ import {
ResultSetSchema,
Column,
ResolvableLocationValue,
} from "./bqrs-cli-types";
} from "../common/bqrs-cli-types";
import {
VariantAnalysis,
VariantAnalysisScannedRepositoryResult,
VariantAnalysisScannedRepositoryState,
} from "../variant-analysis/shared/variant-analysis";
import { RepositoriesFilterSortStateWithIds } from "./variant-analysis-filter-sort";
import { ErrorLike } from "./errors";
import {
RepositoriesFilterSortState,
RepositoriesFilterSortStateWithIds,
} from "../variant-analysis/shared/variant-analysis-filter-sort";
import { ErrorLike } from "../common/errors";
import { DataFlowPaths } from "../variant-analysis/shared/data-flow-paths";
import { ExternalApiUsage } from "../data-extensions-editor/external-api-usage";
import { ModeledMethod } from "../data-extensions-editor/modeled-method";
import { DataExtensionEditorViewState } from "../data-extensions-editor/shared/view-state";
import { Mode } from "../data-extensions-editor/shared/mode";
/**
* This module contains types and code that are shared between
@@ -72,11 +76,9 @@ export type GraphInterpretationData = {
dot: string[];
};
export type InterpretationData =
| SarifInterpretationData
| GraphInterpretationData;
type InterpretationData = SarifInterpretationData | GraphInterpretationData;
export interface InterpretationT<T> {
interface InterpretationT<T> {
sourceLocationPrefix: string;
numTruncatedResults: number;
numTotalResults: number;
@@ -102,7 +104,7 @@ export type SortedResultsMap = { [resultSet: string]: SortedResultSetInfo };
*
* As a result of receiving this message, listeners might want to display a loading indicator.
*/
export interface ResultsUpdatingMsg {
interface ResultsUpdatingMsg {
t: "resultsUpdating";
}
@@ -110,7 +112,7 @@ export interface ResultsUpdatingMsg {
* Message to set the initial state of the results view with a new
* query.
*/
export interface SetStateMsg {
interface SetStateMsg {
t: "setState";
resultsPath: string;
origResultsPaths: ResultsPaths;
@@ -139,7 +141,7 @@ export interface SetStateMsg {
* Message indicating that the results view should display interpreted
* results.
*/
export interface ShowInterpretedPageMsg {
interface ShowInterpretedPageMsg {
t: "showInterpretedPage";
interpretation: Interpretation;
database: DatabaseInfo;
@@ -169,7 +171,7 @@ export interface NavigateMsg {
* A message indicating that the results view should untoggle the
* "Show results in Problems view" checkbox.
*/
export interface UntoggleShowProblemsMsg {
interface UntoggleShowProblemsMsg {
t: "untoggleShowProblems";
}
@@ -199,7 +201,7 @@ export type FromResultsViewMsg =
* Message from the results view to open a database source
* file at the provided location.
*/
export interface ViewSourceFileMsg {
interface ViewSourceFileMsg {
t: "viewSourceFile";
loc: ResolvableLocationValue;
databaseUri: string;
@@ -208,7 +210,7 @@ export interface ViewSourceFileMsg {
/**
* Message from the results view to open a file in an editor.
*/
export interface OpenFileMsg {
interface OpenFileMsg {
t: "openFile";
/* Full path to the file to open. */
filePath: string;
@@ -270,7 +272,7 @@ export interface RawResultsSortState {
sortDirection: SortDirection;
}
export type InterpretedResultsSortColumn = "alert-message";
type InterpretedResultsSortColumn = "alert-message";
export interface InterpretedResultsSortState {
sortBy: InterpretedResultsSortColumn;
@@ -314,7 +316,7 @@ export type FromCompareViewMessage =
/**
* Message from the compare view to request opening a query.
*/
export interface OpenQueryMessage {
interface OpenQueryMessage {
readonly t: "openQuery";
readonly kind: "from" | "to";
}
@@ -402,63 +404,69 @@ export interface ParsedResultSets {
resultSet: ResultSet;
}
export interface SetVariantAnalysisMessage {
interface SetVariantAnalysisMessage {
t: "setVariantAnalysis";
variantAnalysis: VariantAnalysis;
}
interface SetFilterSortStateMessage {
t: "setFilterSortState";
filterSortState: RepositoriesFilterSortState;
}
export type VariantAnalysisState = {
variantAnalysisId: number;
};
export interface SetRepoResultsMessage {
interface SetRepoResultsMessage {
t: "setRepoResults";
repoResults: VariantAnalysisScannedRepositoryResult[];
}
export interface SetRepoStatesMessage {
interface SetRepoStatesMessage {
t: "setRepoStates";
repoStates: VariantAnalysisScannedRepositoryState[];
}
export interface RequestRepositoryResultsMessage {
interface RequestRepositoryResultsMessage {
t: "requestRepositoryResults";
repositoryFullName: string;
}
export interface OpenQueryFileMessage {
interface OpenQueryFileMessage {
t: "openQueryFile";
}
export interface OpenQueryTextMessage {
interface OpenQueryTextMessage {
t: "openQueryText";
}
export interface CopyRepositoryListMessage {
interface CopyRepositoryListMessage {
t: "copyRepositoryList";
filterSort?: RepositoriesFilterSortStateWithIds;
}
export interface ExportResultsMessage {
interface ExportResultsMessage {
t: "exportResults";
filterSort?: RepositoriesFilterSortStateWithIds;
}
export interface OpenLogsMessage {
interface OpenLogsMessage {
t: "openLogs";
}
export interface CancelVariantAnalysisMessage {
interface CancelVariantAnalysisMessage {
t: "cancelVariantAnalysis";
}
export interface ShowDataFlowPathsMessage {
interface ShowDataFlowPathsMessage {
t: "showDataFlowPaths";
dataFlowPaths: DataFlowPaths;
}
export type ToVariantAnalysisMessage =
| SetVariantAnalysisMessage
| SetFilterSortStateMessage
| SetRepoResultsMessage
| SetRepoStatesMessage;
@@ -473,7 +481,7 @@ export type FromVariantAnalysisMessage =
| CancelVariantAnalysisMessage
| ShowDataFlowPathsMessage;
export interface SetDataFlowPathsMessage {
interface SetDataFlowPathsMessage {
t: "setDataFlowPaths";
dataFlowPaths: DataFlowPaths;
}
@@ -482,69 +490,82 @@ export type ToDataFlowPathsMessage = SetDataFlowPathsMessage;
export type FromDataFlowPathsMessage = CommonFromViewMessages;
export interface SetExtensionPackStateMessage {
interface SetExtensionPackStateMessage {
t: "setDataExtensionEditorViewState";
viewState: DataExtensionEditorViewState;
}
export interface SetExternalApiUsagesMessage {
interface SetExternalApiUsagesMessage {
t: "setExternalApiUsages";
externalApiUsages: ExternalApiUsage[];
}
export interface ShowProgressMessage {
t: "showProgress";
step: number;
maxStep: number;
message: string;
interface LoadModeledMethodsMessage {
t: "loadModeledMethods";
modeledMethods: Record<string, ModeledMethod>;
}
export interface AddModeledMethodsMessage {
interface AddModeledMethodsMessage {
t: "addModeledMethods";
modeledMethods: Record<string, ModeledMethod>;
/**
* If true, then any existing modeled methods set to "none" will be
* overwritten by the new modeled methods. Otherwise, the "none" modeled
* methods will not be overwritten, even if the new modeled methods
* contain a better model.
*/
overrideNone?: boolean;
}
export interface JumpToUsageMessage {
interface SwitchModeMessage {
t: "switchMode";
mode: Mode;
}
interface JumpToUsageMessage {
t: "jumpToUsage";
location: ResolvableLocationValue;
}
export interface OpenExtensionPackMessage {
interface OpenDatabaseMessage {
t: "openDatabase";
}
interface OpenExtensionPackMessage {
t: "openExtensionPack";
}
export interface OpenModelFileMessage {
t: "openModelFile";
interface RefreshExternalApiUsages {
t: "refreshExternalApiUsages";
}
export interface SaveModeledMethods {
interface SaveModeledMethods {
t: "saveModeledMethods";
externalApiUsages: ExternalApiUsage[];
modeledMethods: Record<string, ModeledMethod>;
}
export interface GenerateExternalApiMessage {
interface GenerateExternalApiMessage {
t: "generateExternalApi";
}
interface GenerateExternalApiFromLlmMessage {
t: "generateExternalApiFromLlm";
externalApiUsages: ExternalApiUsage[];
modeledMethods: Record<string, ModeledMethod>;
}
interface ModelDependencyMessage {
t: "modelDependency";
}
export type ToDataExtensionsEditorMessage =
| SetExtensionPackStateMessage
| SetExternalApiUsagesMessage
| ShowProgressMessage
| LoadModeledMethodsMessage
| AddModeledMethodsMessage;
export type FromDataExtensionsEditorMessage =
| ViewLoadedMsg
| OpenModelFileMessage
| SwitchModeMessage
| RefreshExternalApiUsages
| OpenDatabaseMessage
| OpenExtensionPackMessage
| JumpToUsageMessage
| SaveModeledMethods
| GenerateExternalApiMessage;
| GenerateExternalApiMessage
| GenerateExternalApiFromLlmMessage
| ModelDependencyMessage;

View File

@@ -0,0 +1,89 @@
import { Memento } from "./memento";
/**
* Provides a utility method to invoke a function only if a minimum time interval has elapsed since
* the last invocation of that function.
*/
export class InvocationRateLimiter<T> {
constructor(
private readonly globalState: Memento,
private readonly funcIdentifier: string,
private readonly func: () => Promise<T>,
private readonly createDate: (dateString?: string) => Date = (s) =>
s ? new Date(s) : new Date(),
) {}
/**
* Invoke the function if `minSecondsSinceLastInvocation` seconds have elapsed since the last invocation.
*/
public async invokeFunctionIfIntervalElapsed(
minSecondsSinceLastInvocation: number,
): Promise<InvocationRateLimiterResult<T>> {
const updateCheckStartDate = this.createDate();
const lastInvocationDate = this.getLastInvocationDate();
if (
minSecondsSinceLastInvocation &&
lastInvocationDate &&
lastInvocationDate <= updateCheckStartDate &&
lastInvocationDate.getTime() + minSecondsSinceLastInvocation * 1000 >
updateCheckStartDate.getTime()
) {
return createRateLimitedResult();
}
const result = await this.func();
await this.setLastInvocationDate(updateCheckStartDate);
return createInvokedResult(result);
}
private getLastInvocationDate(): Date | undefined {
const maybeDateString: string | undefined = this.globalState.get(
InvocationRateLimiter._invocationRateLimiterPrefix + this.funcIdentifier,
);
return maybeDateString ? this.createDate(maybeDateString) : undefined;
}
private async setLastInvocationDate(date: Date): Promise<void> {
return await this.globalState.update(
InvocationRateLimiter._invocationRateLimiterPrefix + this.funcIdentifier,
date,
);
}
private static readonly _invocationRateLimiterPrefix =
"invocationRateLimiter_lastInvocationDate_";
}
export enum InvocationRateLimiterResultKind {
Invoked,
RateLimited,
}
/**
* The function was invoked and returned the value `result`.
*/
interface InvokedResult<T> {
kind: InvocationRateLimiterResultKind.Invoked;
result: T;
}
/**
* The function was not invoked as the minimum interval since the last invocation had not elapsed.
*/
interface RateLimitedResult {
kind: InvocationRateLimiterResultKind.RateLimited;
}
type InvocationRateLimiterResult<T> = InvokedResult<T> | RateLimitedResult;
function createInvokedResult<T>(result: T): InvokedResult<T> {
return {
kind: InvocationRateLimiterResultKind.Invoked,
result,
};
}
function createRateLimitedResult(): RateLimitedResult {
return {
kind: InvocationRateLimiterResultKind.RateLimited,
};
}

View File

@@ -0,0 +1,27 @@
import { FileLink } from "../variant-analysis/shared/analysis-result";
export function createRemoteFileRef(
fileLink: FileLink,
startLine?: number,
endLine?: number,
startColumn?: number,
endColumn?: number,
): string {
if (
startColumn &&
endColumn &&
startLine &&
endLine &&
// Verify that location information is valid; otherwise highlighting might be broken
((startLine === endLine && startColumn < endColumn) || startLine < endLine)
) {
// This relies on column highlighting of new code view on GitHub
return `${fileLink.fileLinkPrefix}/${fileLink.filePath}#L${startLine}C${startColumn}-L${endLine}C${endColumn}`;
} else if (startLine && endLine && startLine < endLine) {
return `${fileLink.fileLinkPrefix}/${fileLink.filePath}#L${startLine}-L${endLine}`;
} else if (startLine) {
return `${fileLink.fileLinkPrefix}/${fileLink.filePath}#L${startLine}`;
} else {
return `${fileLink.fileLinkPrefix}/${fileLink.filePath}`;
}
}

View File

@@ -1,4 +1,4 @@
export * from "./logger";
export * from "./notification-logger";
export * from "./notifications";
export * from "./tee-logger";
export * from "./vscode/loggers";
export * from "./vscode/output-channel-logger";

View File

@@ -0,0 +1,7 @@
import { Logger } from "./logger";
export interface NotificationLogger extends Logger {
showErrorMessage(message: string): Promise<void>;
showWarningMessage(message: string): Promise<void>;
showInformationMessage(message: string): Promise<void>;
}

View File

@@ -0,0 +1,116 @@
import { NotificationLogger } from "./notification-logger";
import { AppTelemetry } from "../telemetry";
import { RedactableError } from "../errors";
interface ShowAndLogOptions {
/**
* 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.
*/
fullMessage?: string;
}
/**
* Show an error message and log it to the console
*
* @param logger The logger that will receive the message.
* @param message The message to show.
* @param options? See individual fields on `ShowAndLogOptions` type.
*
* @return A promise that resolves to the selected item or undefined when being dismissed.
*/
export async function showAndLogErrorMessage(
logger: NotificationLogger,
message: string,
options?: ShowAndLogOptions,
): Promise<void> {
return internalShowAndLog(
logger,
dropLinesExceptInitial(message),
logger.showErrorMessage,
{ fullMessage: message, ...options },
);
}
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
*
* @param logger The logger that will receive the message.
* @param message The message to show.
* @param options? See individual fields on `ShowAndLogOptions` type.
*
* @return A promise that resolves to the selected item or undefined when being dismissed.
*/
export async function showAndLogWarningMessage(
logger: NotificationLogger,
message: string,
options?: ShowAndLogOptions,
): Promise<void> {
return internalShowAndLog(
logger,
message,
logger.showWarningMessage,
options,
);
}
/**
* Show an information message and log it to the console
*
* @param logger The logger that will receive the message.
* @param message The message to show.
* @param options? See individual fields on `ShowAndLogOptions` type.
*
* @return A promise that resolves to the selected item or undefined when being dismissed.
*/
export async function showAndLogInformationMessage(
logger: NotificationLogger,
message: string,
options?: ShowAndLogOptions,
): Promise<void> {
return internalShowAndLog(
logger,
message,
logger.showInformationMessage,
options,
);
}
async function internalShowAndLog(
logger: NotificationLogger,
message: string,
fn: (message: string) => Promise<void>,
{ fullMessage }: ShowAndLogOptions = {},
): Promise<void> {
void logger.log(fullMessage || message);
await fn.bind(logger)(message);
}
interface ShowAndLogExceptionOptions extends ShowAndLogOptions {
/** Custom properties to include in the telemetry report. */
extraTelemetryProperties?: { [key: string]: string };
}
/**
* Show an error message, log it to the console, and emit redacted information as telemetry
*
* @param logger The logger that will receive the message.
* @param telemetry The telemetry instance to use for reporting.
* @param error The error to show. Only redacted information will be included in the telemetry.
* @param options See individual fields on `ShowAndLogExceptionOptions` type.
*
* @return A promise that resolves to the selected item or undefined when being dismissed.
*/
export async function showAndLogExceptionWithTelemetry(
logger: NotificationLogger,
telemetry: AppTelemetry | undefined,
error: RedactableError,
options: ShowAndLogExceptionOptions = {},
): Promise<void> {
telemetry?.sendError(error, options.extraTelemetryProperties);
return showAndLogErrorMessage(logger, error.fullMessage, options);
}

View File

@@ -1,6 +1,6 @@
import { appendFile, ensureFile } from "fs-extra";
import { isAbsolute } from "path";
import { getErrorMessage } from "../../pure/helpers-pure";
import { getErrorMessage } from "../helpers-pure";
import { Logger, LogOptions } from "./logger";
/**

View File

@@ -0,0 +1,2 @@
export * from "./loggers";
export * from "./output-channel-logger";

View File

@@ -1,11 +1,15 @@
import { window as Window, OutputChannel, Progress } from "vscode";
import { Logger, LogOptions } from "../logger";
import { DisposableObject } from "../../../pure/disposable-object";
import { DisposableObject } from "../../disposable-object";
import { NotificationLogger } from "../notification-logger";
/**
* A logger that writes messages to an output channel in the VS Code Output tab.
*/
export class OutputChannelLogger extends DisposableObject implements Logger {
export class OutputChannelLogger
extends DisposableObject
implements Logger, NotificationLogger
{
public readonly outputChannel: OutputChannel;
isCustomLogDirectory: boolean;
@@ -42,6 +46,30 @@ export class OutputChannelLogger extends DisposableObject implements Logger {
show(preserveFocus?: boolean): void {
this.outputChannel.show(preserveFocus);
}
async showErrorMessage(message: string): Promise<void> {
await this.showMessage(message, Window.showErrorMessage);
}
async showInformationMessage(message: string): Promise<void> {
await this.showMessage(message, Window.showInformationMessage);
}
async showWarningMessage(message: string): Promise<void> {
await this.showMessage(message, Window.showWarningMessage);
}
private async showMessage(
message: string,
show: (message: string, ...items: string[]) => Thenable<string | undefined>,
): Promise<void> {
const label = "Show Log";
const result = await show(message, label);
if (result === label) {
this.show();
}
}
}
export type ProgressReporter = Progress<{ message: string }>;

View File

@@ -19,3 +19,11 @@ export const basename = (path: string): string => {
const index = path.lastIndexOf("\\");
return index === -1 ? path : path.slice(index + 1);
};
// Returns the extension of a path, including the leading dot.
export const extname = (path: string): string => {
const name = basename(path);
const index = name.lastIndexOf(".");
return index === -1 ? "" : name.slice(index);
};

View File

@@ -9,6 +9,29 @@ export enum QueryLanguage {
Swift = "swift",
}
export function getLanguageDisplayName(language: string): string {
switch (language) {
case QueryLanguage.CSharp:
return "C#";
case QueryLanguage.Cpp:
return "C / C++";
case QueryLanguage.Go:
return "Go";
case QueryLanguage.Java:
return "Java";
case QueryLanguage.Javascript:
return "JavaScript";
case QueryLanguage.Python:
return "Python";
case QueryLanguage.Ruby:
return "Ruby";
case QueryLanguage.Swift:
return "Swift";
default:
return language;
}
}
export const PACKS_BY_QUERY_LANGUAGE = {
[QueryLanguage.Cpp]: ["codeql/cpp-queries"],
[QueryLanguage.CSharp]: [
@@ -25,13 +48,17 @@ export const PACKS_BY_QUERY_LANGUAGE = {
[QueryLanguage.Ruby]: ["codeql/ruby-queries"],
};
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",
"swift.dbscheme": "swift",
export const dbSchemeToLanguage: Record<string, QueryLanguage> = {
"semmlecode.javascript.dbscheme": QueryLanguage.Javascript,
"semmlecode.cpp.dbscheme": QueryLanguage.Cpp,
"semmlecode.dbscheme": QueryLanguage.Java,
"semmlecode.python.dbscheme": QueryLanguage.Python,
"semmlecode.csharp.dbscheme": QueryLanguage.CSharp,
"go.dbscheme": QueryLanguage.Go,
"ruby.dbscheme": QueryLanguage.Ruby,
"swift.dbscheme": QueryLanguage.Swift,
};
export function isQueryLanguage(language: string): language is QueryLanguage {
return Object.values(QueryLanguage).includes(language as QueryLanguage);
}

View File

@@ -1,7 +1,7 @@
import * as Sarif from "sarif";
import { createReadStream } from "fs-extra";
import { connectTo } from "stream-json/Assembler";
import { getErrorMessage } from "./pure/helpers-pure";
import { getErrorMessage } from "./helpers-pure";
import { withParser } from "stream-json/filters/Pick";
const DUMMY_TOOL: Sarif.Tool = { driver: { name: "" } };

View File

@@ -1,8 +1,8 @@
import * as Sarif from "sarif";
import type { HighlightedRegion } from "../variant-analysis/shared/analysis-result";
import { ResolvableLocationValue } from "./bqrs-cli-types";
import { ResolvableLocationValue } from "../common/bqrs-cli-types";
export interface SarifLink {
interface SarifLink {
dest: number;
text: string;
}
@@ -24,7 +24,7 @@ type ParsedSarifLocation =
// that, and is appropriate for display in the UI.
| NoLocation;
export type SarifMessageComponent = string | SarifLink;
type SarifMessageComponent = string | SarifLink;
/**
* Unescape "[", "]" and "\\" like in sarif plain text messages
@@ -203,7 +203,7 @@ export function shouldHighlightLine(
* A line of code split into: plain text before the highlighted section, the highlighted
* text itself, and plain text after the highlighted section.
*/
export interface PartiallyHighlightedLine {
interface PartiallyHighlightedLine {
plainSection1: string;
highlightedSection: string;
plainSection2: string;

View File

@@ -0,0 +1,10 @@
import { RedactableError } from "./errors";
export interface AppTelemetry {
sendCommandUsage(name: string, executionTime: number, error?: Error): void;
sendUIInteraction(name: string): void;
sendError(
error: RedactableError,
extraProperties?: { [key: string]: string },
): void;
}

View File

@@ -2,16 +2,16 @@
* Contains an assortment of helper constants and functions for working with time, dates, and durations.
*/
export const ONE_SECOND_IN_MS = 1000;
export const ONE_MINUTE_IN_MS = ONE_SECOND_IN_MS * 60;
const ONE_SECOND_IN_MS = 1000;
const ONE_MINUTE_IN_MS = ONE_SECOND_IN_MS * 60;
export const ONE_HOUR_IN_MS = ONE_MINUTE_IN_MS * 60;
export const TWO_HOURS_IN_MS = ONE_HOUR_IN_MS * 2;
export const THREE_HOURS_IN_MS = ONE_HOUR_IN_MS * 3;
export const ONE_DAY_IN_MS = ONE_HOUR_IN_MS * 24;
// These are approximations
export const ONE_MONTH_IN_MS = ONE_DAY_IN_MS * 30;
export const ONE_YEAR_IN_MS = ONE_DAY_IN_MS * 365;
const ONE_MONTH_IN_MS = ONE_DAY_IN_MS * 30;
const ONE_YEAR_IN_MS = ONE_DAY_IN_MS * 365;
const durationFormatter = new Intl.RelativeTimeFormat("en", {
numeric: "auto",

View File

@@ -9,13 +9,9 @@ import {
} from "vscode";
import { join } from "path";
import { DisposableObject, DisposeHandler } from "./pure/disposable-object";
import { tmpDir } from "./helpers";
import {
getHtmlForWebview,
WebviewMessage,
WebviewView,
} from "./interface-utils";
import { DisposableObject, DisposeHandler } from "../disposable-object";
import { tmpDir } from "../../tmp-dir";
import { getHtmlForWebview, WebviewMessage, WebviewView } from "./webview-html";
export type WebviewPanelConfig = {
viewId: string;
@@ -23,6 +19,7 @@ export type WebviewPanelConfig = {
viewColumn: ViewColumn;
view: WebviewView;
preserveFocus?: boolean;
iconPath?: Uri | { dark: Uri; light: Uri };
additionalOptions?: WebviewPanelOptions & WebviewOptions;
allowWasmEval?: boolean;
};
@@ -90,6 +87,8 @@ export abstract class AbstractWebview<
);
this.panel = panel;
this.panel.iconPath = config.iconPath;
this.setupPanel(panel, config);
this.panelResolves.forEach((resolve) => resolve(panel));

View File

@@ -1,20 +1,23 @@
import { pathExists } from "fs-extra";
import * as unzipper from "unzipper";
import * as vscode from "vscode";
import { extLogger } from "./common";
import { extLogger } from "../logging/vscode";
// All path operations in this file must be on paths *within* the zip
// archive.
import { posix } from "path";
const path = posix;
export class File implements vscode.FileStat {
class File implements vscode.FileStat {
type: vscode.FileType;
ctime: number;
mtime: number;
size: number;
constructor(public name: string, public data: Uint8Array) {
constructor(
public name: string,
public data: Uint8Array,
) {
this.type = vscode.FileType.File;
this.ctime = Date.now();
this.mtime = Date.now();
@@ -23,7 +26,7 @@ export class File implements vscode.FileStat {
}
}
export class Directory implements vscode.FileStat {
class Directory implements vscode.FileStat {
type: vscode.FileType;
ctime: number;
mtime: number;
@@ -38,7 +41,7 @@ export class Directory implements vscode.FileStat {
}
}
export type Entry = File | Directory;
type Entry = File | Directory;
/**
* A map containing directory hierarchy information in a convenient form.
@@ -49,7 +52,7 @@ export type Entry = File | Directory;
* dirMap['/foo'] = {'bar': vscode.FileType.Directory}
* dirMap['/foo/bar'] = {'baz': vscode.FileType.File}
*/
export type DirectoryHierarchyMap = Map<string, Map<string, vscode.FileType>>;
type DirectoryHierarchyMap = Map<string, Map<string, vscode.FileType>>;
export type ZipFileReference = {
sourceArchiveZipPath: string;

View File

@@ -1,9 +1,9 @@
import * as vscode from "vscode";
import * as Octokit from "@octokit/rest";
import { retry } from "@octokit/plugin-retry";
import { Credentials } from "./common/authentication";
import { Credentials } from "../authentication";
const GITHUB_AUTH_PROVIDER_ID = "github";
export const GITHUB_AUTH_PROVIDER_ID = "github";
// We need 'repo' scope for triggering workflows, 'gist' scope for exporting results to Gist,
// and 'read:packages' for reading private CodeQL packages.

View File

@@ -1,18 +1,20 @@
import { commands, Disposable } from "vscode";
import { CommandFunction, CommandManager } from "../../packages/commands";
import { extLogger, OutputChannelLogger } from "../logging";
import {
NotificationLogger,
showAndLogWarningMessage,
showAndLogExceptionWithTelemetry,
} from "../logging";
import { extLogger } from "../logging/vscode";
import {
asError,
getErrorMessage,
getErrorStack,
} from "../../pure/helpers-pure";
import { redactableError } from "../../pure/errors";
import { UserCancellationException } from "../../progress";
import {
showAndLogExceptionWithTelemetry,
showAndLogWarningMessage,
} from "../../helpers";
import { telemetryListener } from "../../telemetry";
} from "../../common/helpers-pure";
import { redactableError } from "../../common/errors";
import { UserCancellationException } from "./progress";
import { telemetryListener } from "./telemetry";
import { AppTelemetry } from "../telemetry";
/**
* Create a command manager for VSCode, wrapping registerCommandWithErrorHandling
@@ -20,9 +22,12 @@ import { telemetryListener } from "../../telemetry";
*/
export function createVSCodeCommandManager<
Commands extends Record<string, CommandFunction>,
>(outputLogger?: OutputChannelLogger): CommandManager<Commands> {
>(
logger?: NotificationLogger,
telemetry?: AppTelemetry,
): CommandManager<Commands> {
return new CommandManager((commandId, task) => {
return registerCommandWithErrorHandling(commandId, task, outputLogger);
return registerCommandWithErrorHandling(commandId, task, logger, telemetry);
}, wrapExecuteCommand);
}
@@ -32,11 +37,14 @@ export function createVSCodeCommandManager<
* @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.
* @param logger The logger to use for error reporting.
* @param telemetry The telemetry listener to use for error reporting.
*/
export function registerCommandWithErrorHandling(
commandId: string,
task: (...args: any[]) => Promise<any>,
outputLogger = extLogger,
logger: NotificationLogger = extLogger,
telemetry: AppTelemetry | undefined = telemetryListener,
): Disposable {
return commands.registerCommand(commandId, async (...args: any[]) => {
const startTime = Date.now();
@@ -49,23 +57,20 @@ export function registerCommandWithErrorHandling(
const errorMessage = redactableError(error)`${
getErrorMessage(e) || e
} (${commandId})`;
const errorStack = getErrorStack(e);
if (e instanceof UserCancellationException) {
// User has cancelled this action manually
if (e.silent) {
void outputLogger.log(errorMessage.fullMessage);
void logger.log(errorMessage.fullMessage);
} else {
void showAndLogWarningMessage(errorMessage.fullMessage, {
outputLogger,
});
void showAndLogWarningMessage(logger, errorMessage.fullMessage);
}
} else {
// Include the full stack in the error log only.
const errorStack = getErrorStack(e);
const fullMessage = errorStack
? `${errorMessage.fullMessage}\n${errorStack}`
: errorMessage.fullMessage;
void showAndLogExceptionWithTelemetry(errorMessage, {
outputLogger,
void showAndLogExceptionWithTelemetry(logger, telemetry, errorMessage, {
fullMessage,
extraTelemetryProperties: {
command: commandId,

View File

@@ -0,0 +1,135 @@
import { env, Uri, window } from "vscode";
/**
* 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.
* @param yesTitle The text in the box indicating the affirmative choice.
* @param noTitle The text in the box indicating the negative 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,
modal = true,
yesTitle = "Yes",
noTitle = "No",
): Promise<boolean | undefined> {
const yesItem = { title: yesTitle, isCloseAffordance: false };
const noItem = { title: noTitle, isCloseAffordance: true };
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.
* @param actionMessage The call to action message.
*
* @return `true` if the user clicks the action, `false` if the user cancels the dialog.
*/
export async function showInformationMessageWithAction(
message: string,
actionMessage: string,
): Promise<boolean> {
const actionItem = { title: actionMessage, isCloseAffordance: false };
const chosenItem = await window.showInformationMessage(message, actionItem);
return chosenItem === actionItem;
}
/**
* Opens a modal dialog for the user to make a choice between yes/no/never be asked again.
*
* @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.
* @param yesTitle The text in the box indicating the affirmative choice.
* @param noTitle The text in the box indicating the negative choice.
* @param neverTitle The text in the box indicating the opt out choice.
*
* @return
* `Yes` if the user clicks 'Yes',
* `No` if the user clicks 'No' or cancels the dialog,
* `No, and never ask me again` if the user clicks 'No, and never ask me again',
* `undefined` if the dialog is closed without the user making a choice.
*/
export async function showNeverAskAgainDialog(
message: string,
modal = true,
yesTitle = "Yes",
noTitle = "No",
neverAskAgainTitle = "No, and never ask me again",
): Promise<string | undefined> {
const yesItem = { title: yesTitle, isCloseAffordance: true };
const noItem = { title: noTitle, isCloseAffordance: false };
const neverAskAgainItem = {
title: neverAskAgainTitle,
isCloseAffordance: false,
};
const chosenItem = await window.showInformationMessage(
message,
{ modal },
yesItem,
noItem,
neverAskAgainItem,
);
return chosenItem?.title;
}

View File

@@ -0,0 +1,8 @@
import { env } from "vscode";
import { EnvironmentContext } from "../app";
export class AppEnvironmentContext implements EnvironmentContext {
public get language(): string {
return env.language;
}
}

View File

@@ -1,11 +1,15 @@
import { Uri, window } from "vscode";
import { AppCommandManager } from "../common/commands";
import { AppCommandManager } from "../commands";
import { showBinaryChoiceDialog } from "./dialog";
import { redactableError } from "../../common/errors";
import {
showAndLogExceptionWithTelemetry,
showBinaryChoiceDialog,
} from "../helpers";
import { redactableError } from "../pure/errors";
import { asError, getErrorMessage, getErrorStack } from "../pure/helpers-pure";
asError,
getErrorMessage,
getErrorStack,
} from "../../common/helpers-pure";
import { showAndLogExceptionWithTelemetry } from "../logging";
import { extLogger } from "../logging/vscode";
import { telemetryListener } from "./telemetry";
export async function tryOpenExternalFile(
commandManager: AppCommandManager,
@@ -32,6 +36,8 @@ the file in the file explorer and dragging it into the workspace.`,
await commandManager.execute("revealFileInOS", uri);
} catch (e) {
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError(
asError(e),
)`Failed to reveal file in OS: ${getErrorMessage(e)}`,
@@ -40,6 +46,8 @@ the file in the file explorer and dragging it into the workspace.`,
}
} else {
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError(asError(e))`Could not open file ${fileLocation}`,
{
fullMessage: `${getErrorMessage(e)}\n${getErrorStack(e)}`,

View File

@@ -0,0 +1,272 @@
import { Discovery } from "../discovery";
import {
Event,
EventEmitter,
RelativePattern,
Uri,
WorkspaceFoldersChangeEvent,
workspace,
} from "vscode";
import { MultiFileSystemWatcher } from "./multi-file-system-watcher";
import { AppEventEmitter } from "../events";
import { extLogger } from "../logging/vscode";
import { lstat } from "fs-extra";
import { containsPath, isIOError } from "../files";
import {
getOnDiskWorkspaceFolders,
getOnDiskWorkspaceFoldersObjects,
} from "./workspace-folders";
import { getErrorMessage } from "../../common/helpers-pure";
interface PathData {
path: string;
}
/**
* Discovers and watches for changes to all files matching a given filter
* contained in the workspace. Also allows computing extra data about each
* file path, and only recomputing the data when the file changes.
*
* Scans the whole workspace on startup, and then watches for changes to files
* to do the minimum work to keep up with changes.
*
* Can configure which changes it watches for, which files are considered
* relevant, and what extra data to compute for each file.
*/
export abstract class FilePathDiscovery<T extends PathData> extends Discovery {
/**
* Has `discover` been called. This allows distinguishing between
* "no paths found" and not having scanned yet.
*/
private discoverHasCompletedOnce = false;
/** The set of known paths and associated data that we are tracking */
private pathData: T[] = [];
/** Event that fires whenever the contents of `pathData` changes */
private readonly onDidChangePathDataEmitter: AppEventEmitter<void>;
/**
* The set of file paths that may have changed on disk since the last time
* refresh was run. Whenever a watcher reports some change to a file we add
* it to this set, and then during the next refresh we will process all
* file paths from this set and update our internal state to match whatever
* we find on disk (i.e. the file exists, doesn't exist, computed data has
* changed).
*/
private readonly changedFilePaths = new Set<string>();
/**
* Watches for changes to files and directories in all workspace folders.
*/
private readonly watcher: MultiFileSystemWatcher = this.push(
new MultiFileSystemWatcher(),
);
/**
* @param name Name of the discovery operation, for logging purposes.
* @param fileWatchPattern Passed to `vscode.RelativePattern` to determine the files to watch for changes to.
*/
constructor(
name: string,
private readonly fileWatchPattern: string,
) {
super(name, extLogger);
this.onDidChangePathDataEmitter = this.push(new EventEmitter<void>());
this.push(
workspace.onDidChangeWorkspaceFolders(
this.workspaceFoldersChanged.bind(this),
),
);
this.push(this.watcher.onDidChange(this.fileChanged.bind(this)));
}
protected getPathData(): ReadonlyArray<Readonly<T>> | undefined {
if (!this.discoverHasCompletedOnce) {
return undefined;
}
return this.pathData;
}
protected get onDidChangePathData(): Event<void> {
return this.onDidChangePathDataEmitter.event;
}
/**
* Compute any extra data to be stored regarding the given path.
*/
protected abstract getDataForPath(path: string): Promise<T>;
/**
* Is the given path relevant to this discovery operation?
*/
protected abstract pathIsRelevant(path: string): boolean;
/**
* Should the given new data overwrite the existing data we have stored?
*/
protected abstract shouldOverwriteExistingData(
newData: T,
existingData: T,
): boolean;
/**
* Update the data for every path by calling `getDataForPath`.
*/
protected async recomputeAllData() {
this.pathData = await Promise.all(
this.pathData.map((p) => this.getDataForPath(p.path)),
);
this.onDidChangePathDataEmitter.fire();
}
/**
* Do the initial scan of the entire workspace and set up watchers for future changes.
*/
public async initialRefresh() {
getOnDiskWorkspaceFolders().forEach((workspaceFolder) => {
this.changedFilePaths.add(workspaceFolder);
});
this.updateWatchers();
await this.refresh();
this.onDidChangePathDataEmitter.fire();
}
private workspaceFoldersChanged(event: WorkspaceFoldersChangeEvent) {
event.added.forEach((workspaceFolder) => {
this.changedFilePaths.add(workspaceFolder.uri.fsPath);
});
event.removed.forEach((workspaceFolder) => {
this.changedFilePaths.add(workspaceFolder.uri.fsPath);
});
this.updateWatchers();
void this.refresh();
}
private updateWatchers() {
this.watcher.clear();
for (const workspaceFolder of getOnDiskWorkspaceFoldersObjects()) {
// Watch for changes to individual files
this.watcher.addWatch(
new RelativePattern(workspaceFolder, this.fileWatchPattern),
);
// need to explicitly watch for changes to directories themselves.
this.watcher.addWatch(new RelativePattern(workspaceFolder, "**/"));
}
}
private fileChanged(uri: Uri) {
this.changedFilePaths.add(uri.fsPath);
void this.refresh();
}
protected async discover() {
let pathsUpdated = false;
for (const path of this.changedFilePaths) {
try {
this.changedFilePaths.delete(path);
if (await this.handleChangedPath(path)) {
pathsUpdated = true;
}
} catch (e) {
// If we get an error while processing a path, just log it and continue.
// There aren't any network operations happening here or anything else
// that's likely to succeed on a retry, so don't bother adding it back
// to the changedFilePaths set.
void extLogger.log(
`${
this.name
} failed while processing path "${path}": ${getErrorMessage(e)}`,
);
}
}
this.discoverHasCompletedOnce = true;
if (pathsUpdated) {
this.onDidChangePathDataEmitter.fire();
}
}
private async handleChangedPath(path: string): Promise<boolean> {
try {
// If the path is not in the workspace then we don't want to be
// tracking or displaying it, so treat it as if it doesn't exist.
if (!this.pathIsInWorkspace(path)) {
return this.handleRemovedPath(path);
}
if ((await lstat(path)).isDirectory()) {
return await this.handleChangedDirectory(path);
} else {
return this.handleChangedFile(path);
}
} catch (e) {
if (isIOError(e) && e.code === "ENOENT") {
return this.handleRemovedPath(path);
}
throw e;
}
}
private pathIsInWorkspace(path: string): boolean {
return getOnDiskWorkspaceFolders().some((workspaceFolder) =>
containsPath(workspaceFolder, path),
);
}
private handleRemovedPath(path: string): boolean {
const oldLength = this.pathData.length;
this.pathData = this.pathData.filter(
(existingPathData) => !containsPath(path, existingPathData.path),
);
return this.pathData.length !== oldLength;
}
private async handleChangedDirectory(path: string): Promise<boolean> {
const newPaths = await workspace.findFiles(
new RelativePattern(path, this.fileWatchPattern),
);
let pathsUpdated = false;
for (const path of newPaths) {
if (await this.addOrUpdatePath(path.fsPath)) {
pathsUpdated = true;
}
}
return pathsUpdated;
}
private async handleChangedFile(path: string): Promise<boolean> {
if (this.pathIsRelevant(path)) {
return await this.addOrUpdatePath(path);
} else {
return false;
}
}
private async addOrUpdatePath(path: string): Promise<boolean> {
const data = await this.getDataForPath(path);
const existingPathDataIndex = this.pathData.findIndex(
(existingPathData) => existingPathData.path === path,
);
if (existingPathDataIndex !== -1) {
if (
this.shouldOverwriteExistingData(
data,
this.pathData[existingPathDataIndex],
)
) {
this.pathData.splice(existingPathDataIndex, 1, data);
return true;
} else {
return false;
}
} else {
this.pathData.push(data);
return true;
}
}
}

View File

@@ -1,4 +1,4 @@
import { DisposableObject } from "../pure/disposable-object";
import { DisposableObject } from "../disposable-object";
import { EventEmitter, Event, Uri, GlobPattern, workspace } from "vscode";
/**

View File

@@ -10,7 +10,10 @@ 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) {
constructor(
message?: string,
public readonly silent = false,
) {
super(message);
}
}
@@ -35,7 +38,7 @@ export type ProgressCallback = (p: ProgressUpdate) => void;
// Make certain properties within a type optional
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
export type ProgressOptions = Optional<VSCodeProgressOptions, "location">;
type ProgressOptions = Optional<VSCodeProgressOptions, "location">;
/**
* A task that reports progress.

View File

@@ -0,0 +1,55 @@
import {
ExplorerSelectionCommandFunction,
TreeViewContextMultiSelectionCommandFunction,
TreeViewContextSingleSelectionCommandFunction,
} from "../commands";
import { showAndLogErrorMessage, NotificationLogger } from "../logging";
// A hack to match types that are not an array, which is useful to help avoid
// misusing createSingleSelectionCommand, e.g. where T accidentally gets instantiated
// as DatabaseItem[] instead of DatabaseItem.
type NotArray = object & { length?: never };
// A way to get the type system to help assert that one type is a supertype of another.
type CreateSupertypeOf<Super, Sub extends Super> = Sub;
// This asserts that SelectionCommand is assignable to all of the different types of
// SelectionCommand defined in commands.ts. The intention is the output from the helpers
// in this file can be used with any of the select command types and can handle any of
// the inputs.
type SelectionCommand<T extends NotArray> = CreateSupertypeOf<
TreeViewContextMultiSelectionCommandFunction<T> &
TreeViewContextSingleSelectionCommandFunction<T> &
ExplorerSelectionCommandFunction<T>,
(singleItem: T, multiSelect?: T[] | undefined) => Promise<void>
>;
export function createSingleSelectionCommand<T extends NotArray>(
logger: NotificationLogger,
f: (argument: T) => Promise<void>,
itemName: string,
): SelectionCommand<T> {
return async (singleItem, multiSelect) => {
if (multiSelect === undefined || multiSelect.length === 1) {
return f(singleItem);
} else {
void showAndLogErrorMessage(
logger,
`Please select a single ${itemName}.`,
);
return;
}
};
}
export function createMultiSelectionCommand<T extends NotArray>(
f: (argument: T[]) => Promise<void>,
): SelectionCommand<T> {
return async (singleItem, multiSelect) => {
if (multiSelect !== undefined && multiSelect.length > 0) {
return f(multiSelect);
} else {
return f([singleItem]);
}
};
}

View File

@@ -13,18 +13,19 @@ import {
LOG_TELEMETRY,
isIntegrationTestMode,
isCanary,
} from "./config";
} from "../../config";
import * as appInsights from "applicationinsights";
import { extLogger } from "./common";
import { extLogger } from "../logging/vscode";
import { UserCancellationException } from "./progress";
import { showBinaryChoiceWithUrlDialog } from "./helpers";
import { RedactableError } from "./pure/errors";
import { showBinaryChoiceWithUrlDialog } from "./dialog";
import { RedactableError } from "../errors";
import { SemVer } from "semver";
import { AppTelemetry } from "../telemetry";
// Key is injected at build time through the APP_INSIGHTS_KEY environment variable.
const key = "REPLACE-APP-INSIGHTS-KEY";
export enum CommandCompletion {
enum CommandCompletion {
Success = "Success",
Failed = "Failed",
Cancelled = "Cancelled",
@@ -54,7 +55,10 @@ const baseDataPropertiesToRemove = [
const NOT_SET_CLI_VERSION = "not-set";
export class TelemetryListener extends ConfigListener {
export class ExtensionTelemetryListener
extends ConfigListener
implements AppTelemetry
{
static relevantSettings = [ENABLE_TELEMETRY, CANARY_FEATURES];
private reporter?: TelemetryReporter;
@@ -152,7 +156,7 @@ export class TelemetryListener extends ConfigListener {
void this.reporter?.dispose();
}
sendCommandUsage(name: string, executionTime: number, error?: Error) {
sendCommandUsage(name: string, executionTime: number, error?: Error): void {
if (!this.reporter) {
return;
}
@@ -174,7 +178,7 @@ export class TelemetryListener extends ConfigListener {
);
}
sendUIInteraction(name: string) {
sendUIInteraction(name: string): void {
if (!this.reporter) {
return;
}
@@ -193,7 +197,7 @@ export class TelemetryListener extends ConfigListener {
sendError(
error: RedactableError,
extraProperties?: { [key: string]: string },
) {
): void {
if (!this.reporter) {
return;
}
@@ -272,16 +276,16 @@ export class TelemetryListener extends ConfigListener {
/**
* The global Telemetry instance
*/
export let telemetryListener: TelemetryListener | undefined;
export let telemetryListener: ExtensionTelemetryListener | undefined;
export async function initializeTelemetry(
extension: Extension<any>,
ctx: ExtensionContext,
): Promise<TelemetryListener> {
): Promise<ExtensionTelemetryListener> {
if (telemetryListener !== undefined) {
throw new Error("Telemetry is already initialized");
}
telemetryListener = new TelemetryListener(
telemetryListener = new ExtensionTelemetryListener(
extension.id,
extension.packageJSON.version,
key,

View File

@@ -1,13 +1,17 @@
import * as vscode from "vscode";
import { VSCodeCredentials } from "../../authentication";
import { Disposable } from "../../pure/disposable-object";
import { App, AppMode } from "../app";
import { VSCodeCredentials } from "./authentication";
import { Disposable } from "../disposable-object";
import { App, AppMode, EnvironmentContext } from "../app";
import { AppEventEmitter } from "../events";
import { extLogger, Logger, queryServerLogger } from "../logging";
import { NotificationLogger } from "../logging";
import { extLogger, queryServerLogger } from "../logging/vscode";
import { Memento } from "../memento";
import { VSCodeAppEventEmitter } from "./events";
import { AppCommandManager, QueryServerCommandManager } from "../commands";
import { createVSCodeCommandManager } from "./commands";
import { AppEnvironmentContext } from "./environment-context";
import { AppTelemetry } from "../telemetry";
import { telemetryListener } from "./telemetry";
export class ExtensionApp implements App {
public readonly credentials: VSCodeCredentials;
@@ -54,11 +58,19 @@ export class ExtensionApp implements App {
}
}
public get logger(): Logger {
public get logger(): NotificationLogger {
return extLogger;
}
public get telemetry(): AppTelemetry | undefined {
return telemetryListener;
}
public createEventEmitter<T>(): AppEventEmitter<T> {
return new VSCodeAppEventEmitter<T>();
}
public get environment(): EnvironmentContext {
return new AppEnvironmentContext();
}
}

View File

@@ -0,0 +1,101 @@
import { ExtensionContext, Uri, Webview } from "vscode";
import { randomBytes } from "crypto";
import { EOL } from "os";
export type WebviewView =
| "results"
| "compare"
| "variant-analysis"
| "data-flow-paths"
| "data-extensions-editor";
export interface WebviewMessage {
t: string;
}
/**
* Returns HTML to populate the given webview.
* Uses a content security policy that only loads the given script.
*/
export function getHtmlForWebview(
ctx: ExtensionContext,
webview: Webview,
view: WebviewView,
{
allowInlineStyles,
allowWasmEval,
}: {
allowInlineStyles?: boolean;
allowWasmEval?: boolean;
} = {
allowInlineStyles: false,
allowWasmEval: false,
},
): string {
const scriptUriOnDisk = Uri.file(ctx.asAbsolutePath("out/webview.js"));
const stylesheetUrisOnDisk = [
Uri.file(ctx.asAbsolutePath("out/webview.css")),
];
// Convert the on-disk URIs into webview URIs.
const scriptWebviewUri = webview.asWebviewUri(scriptUriOnDisk);
const stylesheetWebviewUris = stylesheetUrisOnDisk.map(
(stylesheetUriOnDisk) => webview.asWebviewUri(stylesheetUriOnDisk),
);
// Use a nonce in the content security policy to uniquely identify the above resources.
const nonce = getNonce();
const stylesheetsHtmlLines = allowInlineStyles
? stylesheetWebviewUris.map((uri) => createStylesLinkWithoutNonce(uri))
: stylesheetWebviewUris.map((uri) => createStylesLinkWithNonce(nonce, uri));
const styleSrc = allowInlineStyles
? `${webview.cspSource} vscode-file: 'unsafe-inline'`
: `'nonce-${nonce}'`;
const fontSrc = webview.cspSource;
/*
* Content security policy:
* default-src: allow nothing by default.
* script-src:
* - allow the given script, using the nonce.
* - 'wasm-unsafe-eval: allow loading WebAssembly modules if necessary.
* style-src: allow only the given stylesheet, using the nonce.
* connect-src: only allow fetch calls to webview resource URIs
* (this is used to load BQRS result files).
*/
return `
<html>
<head>
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; script-src 'nonce-${nonce}'${
allowWasmEval ? " 'wasm-unsafe-eval'" : ""
}; font-src ${fontSrc}; style-src ${styleSrc}; connect-src ${
webview.cspSource
};">
${stylesheetsHtmlLines.join(` ${EOL}`)}
</head>
<body>
<div id=root data-view="${view}">
</div>
<script nonce="${nonce}" src="${scriptWebviewUri}">
</script>
</body>
</html>`;
}
/** Gets a nonce string created with 128 bits of entropy. */
function getNonce(): string {
return randomBytes(16).toString("base64");
}
function createStylesLinkWithNonce(nonce: string, uri: Uri): string {
return `<link nonce="${nonce}" rel="stylesheet" href="${uri}">`;
}
function createStylesLinkWithoutNonce(uri: Uri): string {
return `<link rel="stylesheet" href="${uri}">`;
}

View File

@@ -0,0 +1,64 @@
import { dirname, join } from "path";
import { workspace, WorkspaceFolder } from "vscode";
/** Returns true if the specified workspace folder is on the file system. */
export function isWorkspaceFolderOnDisk(
workspaceFolder: WorkspaceFolder,
): boolean {
return workspaceFolder.uri.scheme === "file";
}
/** Gets all active workspace folders that are on the filesystem. */
export function getOnDiskWorkspaceFoldersObjects() {
const workspaceFolders = workspace.workspaceFolders ?? [];
return workspaceFolders.filter(isWorkspaceFolderOnDisk);
}
/** Gets all active workspace folders that are on the filesystem. */
export function getOnDiskWorkspaceFolders() {
return getOnDiskWorkspaceFoldersObjects().map((folder) => folder.uri.fsPath);
}
/** Check if folder is already present in workspace */
export function isFolderAlreadyInWorkspace(folderName: string) {
const workspaceFolders = workspace.workspaceFolders || [];
return !!workspaceFolders.find(
(workspaceFolder) => workspaceFolder.name === folderName,
);
}
/**
* Returns the path of the first folder in the workspace.
* This is used to decide where to create skeleton QL packs.
*
* If the first folder is a QL pack, then the parent folder is returned.
* This is because the vscode-codeql-starter repo contains a ql pack in
* the first folder.
*
* This is a temporary workaround until we can retire the
* vscode-codeql-starter repo.
*/
export function getFirstWorkspaceFolder() {
const workspaceFolders = getOnDiskWorkspaceFolders();
if (!workspaceFolders || workspaceFolders.length === 0) {
throw new Error("No workspace folders found");
}
const firstFolderFsPath = workspaceFolders[0];
// For the vscode-codeql-starter repo, the first folder will be a ql pack
// so we need to get the parent folder
if (
firstFolderFsPath.includes(
join("vscode-codeql-starter", "codeql-custom-queries"),
)
) {
// return the parent folder
return dirname(firstFolderFsPath);
} else {
// if the first folder is not a ql pack, then we are in a normal workspace
return firstFolderFsPath;
}
}

View File

@@ -7,8 +7,9 @@ export function pluralize(
numItems: number | undefined,
singular: string,
plural: string,
numberFormatter: (value: number) => string = (value) => value.toString(),
): string {
return numItems !== undefined
? `${numItems} ${numItems === 1 ? singular : plural}`
? `${numberFormatter(numItems)} ${numItems === 1 ? singular : plural}`
: "";
}

View File

@@ -0,0 +1,12 @@
import { promisify } from "util";
import { gzip, gunzip } from "zlib";
/**
* Promisified version of zlib.gzip
*/
export const gzipEncode = promisify(gzip);
/**
* Promisified version of zlib.gunzip
*/
export const gzipDecode = promisify(gunzip);

View File

@@ -4,24 +4,27 @@ import {
FromCompareViewMessage,
ToCompareViewMessage,
QueryCompareResult,
} from "../pure/interface-types";
import { Logger } from "../common";
import { CodeQLCliServer } from "../cli";
import { DatabaseManager } from "../local-databases";
import { jumpToLocation } from "../interface-utils";
} from "../common/interface-types";
import { Logger, showAndLogExceptionWithTelemetry } from "../common/logging";
import { extLogger } from "../common/logging/vscode";
import { CodeQLCliServer } from "../codeql-cli/cli";
import { DatabaseManager } from "../databases/local-databases";
import { jumpToLocation } from "../databases/local-databases/locations";
import {
transformBqrsResultSet,
RawResultSet,
BQRSInfo,
} from "../pure/bqrs-cli-types";
} from "../common/bqrs-cli-types";
import resultsDiff from "./resultsDiff";
import { CompletedLocalQueryInfo } from "../query-results";
import { assertNever, getErrorMessage } from "../pure/helpers-pure";
import { assertNever, getErrorMessage } from "../common/helpers-pure";
import { HistoryItemLabelProvider } from "../query-history/history-item-label-provider";
import { AbstractWebview, WebviewPanelConfig } from "../abstract-webview";
import { telemetryListener } from "../telemetry";
import { redactableError } from "../pure/errors";
import { showAndLogExceptionWithTelemetry } from "../helpers";
import {
AbstractWebview,
WebviewPanelConfig,
} from "../common/vscode/abstract-webview";
import { telemetryListener } from "../common/vscode/telemetry";
import { redactableError } from "../common/errors";
interface ComparePair {
from: CompletedLocalQueryInfo;
@@ -127,7 +130,12 @@ export class CompareView extends AbstractWebview<
break;
case "viewSourceFile":
await jumpToLocation(msg, this.databaseManager, this.logger);
await jumpToLocation(
msg.databaseUri,
msg.loc,
this.databaseManager,
this.logger,
);
break;
case "openQuery":
@@ -143,6 +151,8 @@ export class CompareView extends AbstractWebview<
case "unhandledError":
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError(
msg.error,
)`Unhandled error in result comparison view: ${msg.error.message}`,
@@ -172,21 +182,40 @@ export class CompareView extends AbstractWebview<
const commonResultSetNames = fromSchemaNames.filter((name) =>
toSchemaNames.includes(name),
);
// Fall back on the default result set names if there are no common ones.
const defaultFromResultSetName = fromSchemaNames.find((name) =>
name.startsWith("#"),
);
const defaultToResultSetName = toSchemaNames.find((name) =>
name.startsWith("#"),
);
if (
commonResultSetNames.length === 0 &&
!(defaultFromResultSetName || defaultToResultSetName)
) {
throw new Error(
"No common result sets found between the two queries. Please check that the queries are compatible.",
);
}
const currentResultSetName =
selectedResultSetName || commonResultSetNames[0];
const fromResultSet = await this.getResultSet(
fromSchemas,
currentResultSetName,
currentResultSetName || defaultFromResultSetName!,
from.completedQuery.query.resultsPaths.resultsPath,
);
const toResultSet = await this.getResultSet(
toSchemas,
currentResultSetName,
currentResultSetName || defaultToResultSetName!,
to.completedQuery.query.resultsPaths.resultsPath,
);
return [
commonResultSetNames,
currentResultSetName,
currentResultSetName ||
`${defaultFromResultSetName} <-> ${defaultToResultSetName}`,
fromResultSet,
toResultSet,
];

View File

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

View File

@@ -1,14 +1,20 @@
import { DisposableObject } from "./pure/disposable-object";
import { DisposableObject } from "./common/disposable-object";
import {
workspace,
Event,
EventEmitter,
ConfigurationChangeEvent,
ConfigurationTarget,
ConfigurationScope,
} from "vscode";
import { DistributionManager } from "./distribution";
import { extLogger } from "./common";
import { ONE_DAY_IN_MS } from "./pure/time";
import { DistributionManager } from "./codeql-cli/distribution";
import { extLogger } from "./common/logging/vscode";
import { ONE_DAY_IN_MS } from "./common/time";
import {
FilterKey,
SortKey,
defaultFilterSortState,
} from "./variant-analysis/shared/variant-analysis-filter-sort";
export const ALL_SETTINGS: Setting[] = [];
@@ -39,12 +45,12 @@ export class Setting {
}
}
getValue<T>(): T {
getValue<T>(scope?: ConfigurationScope | null): T {
if (this.parent === undefined) {
throw new Error("Cannot get the value of a root setting.");
}
return workspace
.getConfiguration(this.parent.qualifiedName)
.getConfiguration(this.parent.qualifiedName, scope)
.get<T>(this.name)!;
}
@@ -58,17 +64,21 @@ export class Setting {
}
}
export interface InspectionResult<T> {
globalValue?: T;
workspaceValue?: T;
workspaceFolderValue?: T;
}
const VSCODE_DEBUG_SETTING = new Setting("debug", undefined);
export const VSCODE_SAVE_BEFORE_START_SETTING = new Setting(
"saveBeforeStart",
VSCODE_DEBUG_SETTING,
);
const ROOT_SETTING = new Setting("codeQL");
// Global configuration
const TELEMETRY_SETTING = new Setting("telemetry", ROOT_SETTING);
const AST_VIEWER_SETTING = new Setting("astViewer", ROOT_SETTING);
const CONTEXTUAL_QUERIES_SETTINGS = new Setting(
"contextualQueries",
ROOT_SETTING,
);
const GLOBAL_TELEMETRY_SETTING = new Setting("telemetry");
const LOG_INSIGHTS_SETTING = new Setting("logInsights", ROOT_SETTING);
@@ -151,10 +161,6 @@ export const NUMBER_OF_TEST_THREADS_SETTING = new Setting(
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",
@@ -479,13 +485,21 @@ export function joinOrderWarningThreshold(): number {
}
/**
* Avoids caching in the AST viewer if the user is also a canary user.
* Hidden setting: 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,
);
/**
* Hidden setting: Avoids caching in jump to def and find refs contextual queries if the user is also a canary user.
*/
export const NO_CACHE_CONTEXTUAL_QUERIES = new Setting(
"disableCache",
CONTEXTUAL_QUERIES_SETTINGS,
);
// Settings for variant analysis
const VARIANT_ANALYSIS_SETTING = new Setting("variantAnalysis", ROOT_SETTING);
@@ -529,6 +543,34 @@ export class VariantAnalysisConfigListener
}
}
const VARIANT_ANALYSIS_FILTER_RESULTS = new Setting(
"defaultResultsFilter",
VARIANT_ANALYSIS_SETTING,
);
export function getVariantAnalysisDefaultResultsFilter(): FilterKey {
const value = VARIANT_ANALYSIS_FILTER_RESULTS.getValue<string>();
if (Object.values(FilterKey).includes(value as FilterKey)) {
return value as FilterKey;
} else {
return defaultFilterSortState.filterKey;
}
}
const VARIANT_ANALYSIS_SORT_RESULTS = new Setting(
"defaultResultsSort",
VARIANT_ANALYSIS_SETTING,
);
export function getVariantAnalysisDefaultResultsSort(): SortKey {
const value = VARIANT_ANALYSIS_SORT_RESULTS.getValue<string>();
if (Object.values(SortKey).includes(value as SortKey)) {
return value as SortKey;
} else {
return defaultFilterSortState.sortKey;
}
}
/**
* The branch of "github/codeql-variant-analysis-action" to use with the "Run Variant Analysis" command.
* Default value is "main".
@@ -544,10 +586,6 @@ export function isIntegrationTestMode() {
return process.env.INTEGRATION_TEST_MODE === "true";
}
export function isVariantAnalysisLiveResultsEnabled(): boolean {
return true;
}
// Settings for mocking the GitHub API.
const MOCK_GH_API_SERVER = new Setting("mockGitHubApiServer", ROOT_SETTING);
@@ -611,27 +649,90 @@ export function isCodespacesTemplate() {
const DATABASE_DOWNLOAD_SETTING = new Setting("databaseDownload", ROOT_SETTING);
export const ALLOW_HTTP_SETTING = new Setting(
"allowHttp",
DATABASE_DOWNLOAD_SETTING,
);
const ALLOW_HTTP_SETTING = new Setting("allowHttp", DATABASE_DOWNLOAD_SETTING);
export function allowHttp(): boolean {
return ALLOW_HTTP_SETTING.getValue<boolean>() || false;
}
/**
* The name of the folder where we want to create skeleton wizard QL packs.
* Parent setting for all settings related to the "Create Query" command.
*/
const CREATE_QUERY_COMMAND = new Setting("createQuery", ROOT_SETTING);
/**
* The name of the folder where we want to create QL packs.
**/
const SKELETON_WIZARD_FOLDER = new Setting(
"folder",
new Setting("createQuery", ROOT_SETTING),
const QL_PACK_LOCATION = new Setting("qlPackLocation", CREATE_QUERY_COMMAND);
export function getQlPackLocation(): string | undefined {
return QL_PACK_LOCATION.getValue<string>() || undefined;
}
export async function setQlPackLocation(folder: string | undefined) {
await QL_PACK_LOCATION.updateValue(folder, ConfigurationTarget.Global);
}
/**
* Whether to ask the user to autogenerate a QL pack. The options are "ask" and "never".
**/
const AUTOGENERATE_QL_PACKS = new Setting(
"autogenerateQlPacks",
CREATE_QUERY_COMMAND,
);
export function getSkeletonWizardFolder(): string | undefined {
return SKELETON_WIZARD_FOLDER.getValue<string>() || undefined;
const AutogenerateQLPacksValues = ["ask", "never"] as const;
type AutogenerateQLPacks = (typeof AutogenerateQLPacksValues)[number];
export function getAutogenerateQlPacks(): AutogenerateQLPacks {
const value = AUTOGENERATE_QL_PACKS.getValue<AutogenerateQLPacks>();
return AutogenerateQLPacksValues.includes(value) ? value : "ask";
}
export async function setSkeletonWizardFolder(folder: string | undefined) {
await SKELETON_WIZARD_FOLDER.updateValue(folder, ConfigurationTarget.Global);
export async function setAutogenerateQlPacks(choice: AutogenerateQLPacks) {
await AUTOGENERATE_QL_PACKS.updateValue(choice, ConfigurationTarget.Global);
}
/**
* A flag indicating whether to show the queries panel in the QL view container.
*/
const QUERIES_PANEL = new Setting("queriesPanel", ROOT_SETTING);
export function showQueriesPanel(): boolean {
return !!QUERIES_PANEL.getValue<boolean>();
}
const DATA_EXTENSIONS = new Setting("dataExtensions", ROOT_SETTING);
const LLM_GENERATION = new Setting("llmGeneration", DATA_EXTENSIONS);
const LLM_GENERATION_V2 = new Setting("llmGenerationV2", DATA_EXTENSIONS);
const FRAMEWORK_MODE = new Setting("frameworkMode", DATA_EXTENSIONS);
const DISABLE_AUTO_NAME_EXTENSION_PACK = new Setting(
"disableAutoNameExtensionPack",
DATA_EXTENSIONS,
);
const EXTENSIONS_DIRECTORY = new Setting(
"extensionsDirectory",
DATA_EXTENSIONS,
);
export function showLlmGeneration(): boolean {
return !!LLM_GENERATION.getValue<boolean>();
}
export function useLlmGenerationV2(): boolean {
return !!LLM_GENERATION_V2.getValue<boolean>();
}
export function enableFrameworkMode(): boolean {
return !!FRAMEWORK_MODE.getValue<boolean>();
}
export function disableAutoNameExtensionPack(): boolean {
return !!DISABLE_AUTO_NAME_EXTENSION_PACK.getValue<boolean>();
}
export function getExtensionsDirectory(languageId: string): string | undefined {
return EXTENSIONS_DIRECTORY.getValue<string>({
languageId,
});
}

View File

@@ -1,198 +0,0 @@
import { writeFile, promises } from "fs-extra";
import { dump } from "js-yaml";
import { file } from "tmp-promise";
import { basename, dirname, resolve } from "path";
import {
getPrimaryDbscheme,
getQlPackForDbscheme,
getOnDiskWorkspaceFolders,
QlPacksForLanguage,
showAndLogExceptionWithTelemetry,
} from "../helpers";
import { KeyType, kindOfKeyType, nameOfKeyType, tagOfKeyType } from "./keyType";
import { CodeQLCliServer } from "../cli";
import { DatabaseItem } from "../local-databases";
import { extLogger, TeeLogger } from "../common";
import { CancellationToken } from "vscode";
import { ProgressCallback } from "../progress";
import { CoreCompletedQuery, QueryRunner } from "../query-server";
import { redactableError } from "../pure/errors";
import { QLPACK_FILENAMES } from "../pure/ql";
export async function qlpackOfDatabase(
cli: Pick<CodeQLCliServer, "resolveQlpacks">,
db: Pick<DatabaseItem, "contents">,
): 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 getPrimaryDbscheme(datasetPath);
return await 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 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 writeFile(suiteFile, dump(suiteYaml), "utf8");
const queries = await cli.resolveQueriesInSuite(
suiteFile,
getOnDiskWorkspaceFolders(),
);
return queries;
}
export async function resolveQueries(
cli: CodeQLCliServer,
qlpacks: QlPacksForLanguage,
keyType: KeyType,
): Promise<string[]> {
const packsToSearch: string[] = [];
// 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);
}
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 keyTypeName = nameOfKeyType(keyType);
const keyTypeTag = tagOfKeyType(keyType);
const joinedPacksToSearch = packsToSearch.join(", ");
const error = redactableError`No ${keyTypeName} queries (tagged "${keyTypeTag}") could be found in the \
current library path (tried searching the following packs: ${joinedPacksToSearch}). \
Try upgrading the CodeQL libraries. If that doesn't work, then ${keyTypeName} queries are not yet available \
for this language.`;
void showAndLogExceptionWithTelemetry(error);
throw error;
}
async function resolveContextualQuery(
cli: CodeQLCliServer,
query: string,
): Promise<{ packPath: string; createdTempLockFile: boolean }> {
// Contextual queries now live within the standard library packs.
// This simplifies distribution (you don't need the standard query pack to use the AST viewer),
// but if the library pack doesn't have a lockfile, we won't be able to find
// other pack dependencies of the library pack.
// Work out the enclosing pack.
const packContents = await cli.packPacklist(query, false);
const packFilePath = packContents.find((p) =>
QLPACK_FILENAMES.includes(basename(p)),
);
if (packFilePath === undefined) {
// Should not happen; we already resolved this query.
throw new Error(
`Could not find a CodeQL pack file for the pack enclosing the contextual query ${query}`,
);
}
const packPath = dirname(packFilePath);
const lockFilePath = packContents.find((p) =>
["codeql-pack.lock.yml", "qlpack.lock.yml"].includes(basename(p)),
);
let createdTempLockFile = false;
if (!lockFilePath) {
// No lock file, likely because this library pack is in the package cache.
// Create a lock file so that we can resolve dependencies and library path
// for the contextual query.
void extLogger.log(
`Library pack ${packPath} is missing a lock file; creating a temporary lock file`,
);
await cli.packResolveDependencies(packPath);
createdTempLockFile = true;
// Clear CLI server pack cache before installing dependencies,
// so that it picks up the new lock file, not the previously cached pack.
void extLogger.log("Clearing the CodeQL CLI server's pack cache");
await cli.clearCache();
// Install dependencies.
void extLogger.log(
`Installing package dependencies for library pack ${packPath}`,
);
await cli.packInstall(packPath);
}
return { packPath, createdTempLockFile };
}
async function removeTemporaryLockFile(packPath: string) {
const tempLockFilePath = resolve(packPath, "codeql-pack.lock.yml");
void extLogger.log(
`Deleting temporary package lock file at ${tempLockFilePath}`,
);
// It's fine if the file doesn't exist.
await promises.rm(resolve(packPath, "codeql-pack.lock.yml"), {
force: true,
});
}
export async function runContextualQuery(
query: string,
db: DatabaseItem,
queryStorageDir: string,
qs: QueryRunner,
cli: CodeQLCliServer,
progress: ProgressCallback,
token: CancellationToken,
templates: Record<string, string>,
): Promise<CoreCompletedQuery> {
const { packPath, createdTempLockFile } = await resolveContextualQuery(
cli,
query,
);
const queryRun = qs.createQueryRun(
db.databaseUri.fsPath,
{ queryPath: query, quickEvalPosition: undefined },
false,
getOnDiskWorkspaceFolders(),
undefined,
queryStorageDir,
undefined,
templates,
);
void extLogger.log(
`Running contextual query ${query}; results will be stored in ${queryRun.outputDir.querySaveDir}`,
);
const results = await queryRun.evaluate(
progress,
token,
new TeeLogger(qs.logger, queryRun.outputDir.logPath),
);
if (createdTempLockFile) {
await removeTemporaryLockFile(packPath);
}
return results;
}

View File

@@ -0,0 +1,34 @@
import { Credentials } from "../common/authentication";
import { OctokitResponse } from "@octokit/types";
export enum AutomodelMode {
Unspecified = "AUTOMODEL_MODE_UNSPECIFIED",
Framework = "AUTOMODEL_MODE_FRAMEWORK",
Application = "AUTOMODEL_MODE_APPLICATION",
}
export interface ModelRequest {
mode: AutomodelMode;
// Base64-encoded GZIP-compressed SARIF log
candidates: string;
}
export interface ModelResponse {
models: string;
}
export async function autoModelV2(
credentials: Credentials,
request: ModelRequest,
): Promise<ModelResponse> {
const octokit = await credentials.getOctokit();
const response: OctokitResponse<ModelResponse> = await octokit.request(
"POST /repos/github/codeql/code-scanning/codeql/auto-model",
{
data: request,
},
);
return response.data;
}

View File

@@ -0,0 +1,54 @@
import { Credentials } from "../common/authentication";
import { OctokitResponse } from "@octokit/types";
export enum ClassificationType {
Unknown = "CLASSIFICATION_TYPE_UNKNOWN",
Neutral = "CLASSIFICATION_TYPE_NEUTRAL",
Source = "CLASSIFICATION_TYPE_SOURCE",
Sink = "CLASSIFICATION_TYPE_SINK",
Summary = "CLASSIFICATION_TYPE_SUMMARY",
}
export interface Classification {
type: ClassificationType;
kind: string;
explanation: string;
}
export interface Method {
package: string;
type: string;
name: string;
signature: string;
usages: string[];
classification?: Classification;
input?: string;
output?: string;
}
export interface ModelRequest {
language: string;
candidates: Method[];
samples: Method[];
}
export interface ModelResponse {
language: string;
predicted?: Method[];
}
export async function autoModel(
credentials: Credentials,
request: ModelRequest,
): Promise<ModelResponse> {
const octokit = await credentials.getOctokit();
const response: OctokitResponse<ModelResponse> = await octokit.request(
"POST /repos/github/codeql/code-scanning/codeql/auto-model",
{
data: request,
},
);
return response.data;
}

View File

@@ -0,0 +1,230 @@
import { CodeQLCliServer, SourceInfo } from "../codeql-cli/cli";
import { QueryRunner } from "../query-server";
import { DatabaseItem } from "../databases/local-databases";
import { ProgressCallback } from "../common/vscode/progress";
import * as Sarif from "sarif";
import { qlpackOfDatabase, resolveQueries } from "../local-queries";
import { extLogger } from "../common/logging/vscode";
import { Mode } from "./shared/mode";
import { QlPacksForLanguage } from "../databases/qlpack";
import { createLockFileForStandardQuery } from "../local-queries/standard-queries";
import { CancellationToken, CancellationTokenSource } from "vscode";
import { getOnDiskWorkspaceFolders } from "../common/vscode/workspace-folders";
import { showAndLogExceptionWithTelemetry, TeeLogger } from "../common/logging";
import { QueryResultType } from "../query-server/new-messages";
import { telemetryListener } from "../common/vscode/telemetry";
import { redactableError } from "../common/errors";
import { interpretResultsSarif } from "../query-results";
import { join } from "path";
import { assertNever } from "../common/helpers-pure";
type AutoModelQueryOptions = {
queryTag: string;
mode: Mode;
cliServer: CodeQLCliServer;
queryRunner: QueryRunner;
databaseItem: DatabaseItem;
qlpack: QlPacksForLanguage;
sourceInfo: SourceInfo | undefined;
extensionPacks: string[];
queryStorageDir: string;
progress: ProgressCallback;
token: CancellationToken;
};
function modeTag(mode: Mode): string {
switch (mode) {
case Mode.Application:
return "application-mode";
case Mode.Framework:
return "framework-mode";
default:
assertNever(mode);
}
}
async function runAutoModelQuery({
queryTag,
mode,
cliServer,
queryRunner,
databaseItem,
qlpack,
sourceInfo,
extensionPacks,
queryStorageDir,
progress,
token,
}: AutoModelQueryOptions): Promise<Sarif.Log | undefined> {
// First, resolve the query that we want to run.
// All queries are tagged like this:
// internal extract automodel <mode> <queryTag>
// Example: internal extract automodel framework-mode candidates
const queries = await resolveQueries(
cliServer,
qlpack,
`Extract automodel ${queryTag}`,
{
kind: "problem",
"tags contain all": ["automodel", modeTag(mode), ...queryTag.split(" ")],
},
);
if (queries.length > 1) {
throw new Error(
`Found multiple auto model queries for ${mode} ${queryTag}. Can't continue`,
);
}
if (queries.length === 0) {
throw new Error(
`Did not found any auto model queries for ${mode} ${queryTag}. Can't continue`,
);
}
const queryPath = queries[0];
const { cleanup: cleanupLockFile } = await createLockFileForStandardQuery(
cliServer,
queryPath,
);
// Get metadata for the query. This is required to interpret the results. We already know the kind is problem
// (because of the constraint in resolveQueries), so we don't need any more checks on the metadata.
const metadata = await cliServer.resolveMetadata(queryPath);
const queryRun = queryRunner.createQueryRun(
databaseItem.databaseUri.fsPath,
{
queryPath,
quickEvalPosition: undefined,
quickEvalCountOnly: false,
},
false,
getOnDiskWorkspaceFolders(),
extensionPacks,
queryStorageDir,
undefined,
undefined,
);
const completedQuery = await queryRun.evaluate(
progress,
token,
new TeeLogger(queryRunner.logger, queryRun.outputDir.logPath),
);
await cleanupLockFile?.();
if (completedQuery.resultType !== QueryResultType.SUCCESS) {
void showAndLogExceptionWithTelemetry(
extLogger,
telemetryListener,
redactableError`Auto-model query ${queryTag} failed: ${
completedQuery.message ?? "No message"
}`,
);
return;
}
const interpretedResultsPath = join(
queryStorageDir,
`interpreted-results-${queryTag.replaceAll(" ", "-")}-${queryRun.id}.sarif`,
);
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- We only need the actual SARIF data, not the extra fields added by SarifInterpretationData
const { t, sortState, ...sarif } = await interpretResultsSarif(
cliServer,
metadata,
{
resultsPath: completedQuery.outputDir.bqrsPath,
interpretedResultsPath,
},
sourceInfo,
["--sarif-add-snippets"],
);
return sarif;
}
type AutoModelQueriesOptions = {
mode: Mode;
cliServer: CodeQLCliServer;
queryRunner: QueryRunner;
databaseItem: DatabaseItem;
queryStorageDir: string;
progress: ProgressCallback;
};
export type AutoModelQueriesResult = {
candidates: Sarif.Log;
};
export async function runAutoModelQueries({
mode,
cliServer,
queryRunner,
databaseItem,
queryStorageDir,
progress,
}: AutoModelQueriesOptions): Promise<AutoModelQueriesResult | undefined> {
// maxStep for this part is 1500
const maxStep = 1500;
const cancellationTokenSource = new CancellationTokenSource();
const qlpack = await qlpackOfDatabase(cliServer, databaseItem);
// CodeQL needs to have access to the database to be able to retrieve the
// snippets from it. The source location prefix is used to determine the
// base path of the database.
const sourceLocationPrefix = await databaseItem.getSourceLocationPrefix(
cliServer,
);
const sourceArchiveUri = databaseItem.sourceArchive;
const sourceInfo =
sourceArchiveUri === undefined
? undefined
: {
sourceArchive: sourceArchiveUri.fsPath,
sourceLocationPrefix,
};
const additionalPacks = getOnDiskWorkspaceFolders();
const extensionPacks = Object.keys(
await cliServer.resolveQlpacks(additionalPacks, true),
);
progress({
step: 0,
maxStep,
message: "Finding candidates and examples",
});
const candidates = await runAutoModelQuery({
mode,
queryTag: "candidates",
cliServer,
queryRunner,
databaseItem,
qlpack,
sourceInfo,
extensionPacks,
queryStorageDir,
progress: (update) => {
progress({
step: update.step,
maxStep,
message: "Finding candidates and examples",
});
},
token: cancellationTokenSource.token,
});
if (!candidates) {
return undefined;
}
return {
candidates,
};
}

View File

@@ -0,0 +1,140 @@
import { CancellationTokenSource } from "vscode";
import { join } from "path";
import { runQuery } from "./external-api-usage-query";
import { CodeQLCliServer } from "../codeql-cli/cli";
import { QueryRunner } from "../query-server";
import { DatabaseItem } from "../databases/local-databases";
import { interpretResultsSarif } from "../query-results";
import { ProgressCallback } from "../common/vscode/progress";
import { Mode } from "./shared/mode";
type Options = {
cliServer: CodeQLCliServer;
queryRunner: QueryRunner;
databaseItem: DatabaseItem;
queryStorageDir: string;
queryDir: string;
progress: ProgressCallback;
};
export type UsageSnippetsBySignature = Record<string, string[]>;
export async function getAutoModelUsages({
cliServer,
queryRunner,
databaseItem,
queryStorageDir,
queryDir,
progress,
}: Options): Promise<UsageSnippetsBySignature> {
const maxStep = 1500;
const cancellationTokenSource = new CancellationTokenSource();
// This will re-run the query that was already run when opening the data extensions editor. This
// might be unnecessary, but this makes it really easy to get the path to the BQRS file which we
// need to interpret the results.
const queryResult = await runQuery(Mode.Application, {
cliServer,
queryRunner,
queryStorageDir,
databaseItem,
queryDir,
progress: (update) =>
progress({
maxStep,
step: update.step,
message: update.message,
}),
token: cancellationTokenSource.token,
});
if (!queryResult) {
throw new Error("Query failed");
}
progress({
maxStep,
step: 1100,
message: "Retrieving source location prefix",
});
// CodeQL needs to have access to the database to be able to retrieve the
// snippets from it. The source location prefix is used to determine the
// base path of the database.
const sourceLocationPrefix = await databaseItem.getSourceLocationPrefix(
cliServer,
);
const sourceArchiveUri = databaseItem.sourceArchive;
const sourceInfo =
sourceArchiveUri === undefined
? undefined
: {
sourceArchive: sourceArchiveUri.fsPath,
sourceLocationPrefix,
};
progress({
maxStep,
step: 1200,
message: "Interpreting results",
});
// Convert the results to SARIF so that Codeql will retrieve the snippets
// from the datababe. This means we don't need to do that in the extension
// and everything is handled by the CodeQL CLI.
const sarif = await interpretResultsSarif(
cliServer,
{
// To interpret the results we need to provide metadata about the query. We could do this using
// `resolveMetadata` but that would be an extra call to the CodeQL CLI server and would require
// us to know the path to the query on the filesystem. Since we know what the metadata should
// look like and the only metadata that the CodeQL CLI requires is an ID and the kind, we can
// simply use constants here.
kind: "problem",
id: "usage",
},
{
resultsPath: queryResult.outputDir.bqrsPath,
interpretedResultsPath: join(
queryStorageDir,
"interpreted-results.sarif",
),
},
sourceInfo,
["--sarif-add-snippets"],
);
progress({
maxStep,
step: 1400,
message: "Parsing results",
});
const snippets: UsageSnippetsBySignature = {};
const results = sarif.runs[0]?.results;
if (!results) {
throw new Error("No results");
}
// This will group the snippets by the method signature.
for (const result of results) {
const signature = result.message.text;
const snippet =
result.locations?.[0]?.physicalLocation?.contextRegion?.snippet?.text;
if (!signature || !snippet) {
continue;
}
if (!(signature in snippets)) {
snippets[signature] = [];
}
snippets[signature].push(snippet);
}
return snippets;
}

View File

@@ -0,0 +1,40 @@
import { AutomodelMode, ModelRequest } from "./auto-model-api-v2";
import { Mode } from "./shared/mode";
import { AutoModelQueriesResult } from "./auto-model-codeml-queries";
import { assertNever } from "../common/helpers-pure";
import * as Sarif from "sarif";
import { gzipEncode } from "../common/zlib";
/**
* Encode a SARIF log to the format expected by the server: JSON, GZIP-compressed, base64-encoded
* @param log SARIF log to encode
* @returns base64-encoded GZIP-compressed SARIF log
*/
export async function encodeSarif(log: Sarif.Log): Promise<string> {
const json = JSON.stringify(log);
const buffer = Buffer.from(json, "utf-8");
const compressed = await gzipEncode(buffer);
return compressed.toString("base64");
}
export async function createAutoModelV2Request(
mode: Mode,
result: AutoModelQueriesResult,
): Promise<ModelRequest> {
let requestMode: AutomodelMode;
switch (mode) {
case Mode.Application:
requestMode = AutomodelMode.Application;
break;
case Mode.Framework:
requestMode = AutomodelMode.Framework;
break;
default:
assertNever(mode);
}
return {
mode: requestMode,
candidates: await encodeSarif(result.candidates),
};
}

View File

@@ -0,0 +1,262 @@
import { ExternalApiUsage } from "./external-api-usage";
import { ModeledMethod, ModeledMethodType } from "./modeled-method";
import {
Classification,
ClassificationType,
Method,
ModelRequest,
} from "./auto-model-api";
import type { UsageSnippetsBySignature } from "./auto-model-usages-query";
import { groupMethods, sortGroupNames, sortMethods } from "./shared/sorting";
import { Mode } from "./shared/mode";
// Soft limit on the number of candidates to send to the model.
// Note that the model may return fewer than this number of candidates.
const candidateLimit = 20;
// Soft limit on the number of samples to send to the model.
const sampleLimit = 100;
export function createAutoModelRequest(
language: string,
externalApiUsages: ExternalApiUsage[],
modeledMethods: Record<string, ModeledMethod>,
usages: UsageSnippetsBySignature,
mode: Mode,
): ModelRequest {
const request: ModelRequest = {
language,
samples: [],
candidates: [],
};
// Sort the same way as the UI so we send the first ones listed in the UI first
const grouped = groupMethods(externalApiUsages, mode);
const sortedGroupNames = sortGroupNames(grouped);
const sortedExternalApiUsages = sortedGroupNames.flatMap((name) =>
sortMethods(grouped[name]),
);
for (const externalApiUsage of sortedExternalApiUsages) {
const modeledMethod: ModeledMethod = modeledMethods[
externalApiUsage.signature
] ?? {
type: "none",
};
const usagesForMethod =
usages[externalApiUsage.signature] ??
externalApiUsage.usages.map((usage) => usage.label);
const numberOfArguments =
externalApiUsage.methodParameters === "()"
? 0
: externalApiUsage.methodParameters.split(",").length;
const candidates: Method[] = [];
const samples: Method[] = [];
for (
let argumentIndex = -1; // Start at -1 which means `this` as in `this.method()`
argumentIndex < numberOfArguments;
argumentIndex++
) {
const argumentInput: string =
argumentIndex === -1 ? "Argument[this]" : `Argument[${argumentIndex}]`;
const method: Method = {
package: externalApiUsage.packageName,
type: externalApiUsage.typeName,
name: externalApiUsage.methodName,
signature: externalApiUsage.methodParameters,
classification:
modeledMethod.type === "none"
? undefined
: toMethodClassification(modeledMethod),
usages: usagesForMethod.slice(0, 6), // At most 6 usages per argument
input: argumentInput,
};
// A method that is supported is modeled outside of the model file, so it is not a candidate.
// We also do not want it as a sample because we do not know the classification.
if (modeledMethod.type === "none" && externalApiUsage.supported) {
continue;
}
// Candidates are methods that are not currently modeled
if (modeledMethod.type === "none") {
candidates.push(method);
} else {
samples.push(method);
}
}
// If there is room for at least one candidate, add all candidates.
// This ensures that we send all arguments for a method together.
// NOTE: this might go above the candidate limit, but that's okay.
if (request.candidates.length < candidateLimit) {
request.candidates.push(...candidates);
}
// Same for samples
if (request.samples.length < sampleLimit) {
request.samples.push(...samples);
}
}
return request;
}
/**
* For now, we have a simplified model that only models methods as sinks. It does not model methods as neutral,
* so we aren't actually able to correctly determine that a method is neutral; it could still be a source or summary.
* However, to keep this method simple and give output to the user, we will model any method for which none of its
* arguments are modeled as sinks as neutral.
*
* If there are multiple arguments which are modeled as sinks, we will only model the first one.
*/
export function parsePredictedClassifications(
predicted: Method[],
): Record<string, ModeledMethod> {
const predictedBySignature: Record<string, Method[]> = {};
for (const method of predicted) {
const signature = toFullMethodSignature(method);
if (!(signature in predictedBySignature)) {
predictedBySignature[signature] = [];
}
predictedBySignature[signature].push(method);
}
const modeledMethods: Record<string, ModeledMethod> = {};
for (const signature in predictedBySignature) {
const predictedMethods = predictedBySignature[signature];
const sinks = predictedMethods.filter(
(method) => method.classification?.type === ClassificationType.Sink,
);
if (sinks.length === 0) {
// For now, model any method for which none of its arguments are modeled as sinks as neutral
modeledMethods[signature] = {
type: "neutral",
kind: "summary",
input: "",
output: "",
provenance: "ai-generated",
signature,
// predictedBySignature[signature] always has at least element
packageName: predictedMethods[0].package,
typeName: predictedMethods[0].type,
methodName: predictedMethods[0].name,
methodParameters: predictedMethods[0].signature,
};
continue;
}
// Order the sinks by the input alphabetically. This will ensure that the first argument is always
// first in the list of sinks, the second argument is always second, etc.
// If we get back "Argument[1]" and "Argument[3]", "Argument[1]" should always be first
sinks.sort((a, b) => compareInputOutput(a.input ?? "", b.input ?? ""));
const sink = sinks[0];
modeledMethods[signature] = {
type: "sink",
kind: sink.classification?.kind ?? "",
input: sink.input ?? "",
output: sink.output ?? "",
provenance: "ai-generated",
signature,
packageName: sink.package,
typeName: sink.type,
methodName: sink.name,
methodParameters: sink.signature,
};
}
return modeledMethods;
}
function toMethodClassificationType(
type: ModeledMethodType,
): ClassificationType {
switch (type) {
case "source":
return ClassificationType.Source;
case "sink":
return ClassificationType.Sink;
case "summary":
return ClassificationType.Summary;
case "neutral":
return ClassificationType.Neutral;
default:
return ClassificationType.Unknown;
}
}
function toMethodClassification(modeledMethod: ModeledMethod): Classification {
return {
type: toMethodClassificationType(modeledMethod.type),
kind: modeledMethod.kind,
explanation: "",
};
}
function toFullMethodSignature(method: Method): string {
return `${method.package}.${method.type}#${method.name}${method.signature}`;
}
const argumentRegex = /^Argument\[(\d+)]$/;
// Argument[this] is before ReturnValue
const nonNumericArgumentOrder = ["Argument[this]", "ReturnValue"];
/**
* Compare two inputs or outputs matching `Argument[<number>]`, `Argument[this]`, or `ReturnValue`.
* If they are the same, return 0. If a is less than b, returns a negative number.
* If a is greater than b, returns a positive number.
*/
export function compareInputOutput(a: string, b: string): number {
if (a === b) {
return 0;
}
const aMatch = a.match(argumentRegex);
const bMatch = b.match(argumentRegex);
// Numeric arguments are always first
if (aMatch && !bMatch) {
return -1;
}
if (!aMatch && bMatch) {
return 1;
}
// Neither is an argument
if (!aMatch && !bMatch) {
const aIndex = nonNumericArgumentOrder.indexOf(a);
const bIndex = nonNumericArgumentOrder.indexOf(b);
// If either one is unknown, it is sorted last
if (aIndex === -1 && bIndex === -1) {
// Use en-US because these are well-known strings that are not localized
return a.localeCompare(b, "en-US");
}
if (aIndex === -1) {
return 1;
}
if (bIndex === -1) {
return -1;
}
return aIndex - bIndex;
}
// This case shouldn't happen, but makes TypeScript happy
if (!aMatch || !bMatch) {
return 0;
}
// Both are arguments
const aIndex = parseInt(aMatch[1]);
const bIndex = parseInt(bMatch[1]);
return aIndex - bIndex;
}

View File

@@ -1,5 +1,11 @@
import { DecodedBqrsChunk } from "../pure/bqrs-cli-types";
import { Call, ExternalApiUsage } from "./external-api-usage";
import { DecodedBqrsChunk } from "../common/bqrs-cli-types";
import {
Call,
CallClassification,
ExternalApiUsage,
} from "./external-api-usage";
import { ModeledMethodType } from "./modeled-method";
import { parseLibraryFilename } from "./library";
export function decodeBqrsToExternalApiUsages(
chunk: DecodedBqrsChunk,
@@ -7,9 +13,13 @@ export function decodeBqrsToExternalApiUsages(
const methodsByApiName = new Map<string, ExternalApiUsage>();
chunk?.tuples.forEach((tuple) => {
const signature = tuple[0] as string;
const supported = tuple[1] as boolean;
const usage = tuple[2] as Call;
const usage = tuple[0] as Call;
const signature = tuple[1] as string;
const supported = (tuple[2] as string) === "true";
let library = tuple[4] as string;
let libraryVersion: string | undefined = tuple[5] as string;
const type = tuple[6] as ModeledMethodType;
const classification = tuple[8] as CallClassification;
const [packageWithType, methodDeclaration] = signature.split("#");
@@ -29,33 +39,42 @@ export function decodeBqrsToExternalApiUsages(
methodDeclaration.indexOf("("),
);
// For Java, we'll always get back a .jar file, and the library version may be bad because not all library authors
// properly specify the version. Therefore, we'll always try to parse the name and version from the library filename
// for Java.
if (library.endsWith(".jar") || libraryVersion === "") {
const { name, version } = parseLibraryFilename(library);
library = name;
if (version) {
libraryVersion = version;
}
}
if (libraryVersion === "") {
libraryVersion = undefined;
}
if (!methodsByApiName.has(signature)) {
methodsByApiName.set(signature, {
library,
libraryVersion,
signature,
packageName,
typeName,
methodName,
methodParameters,
supported,
supportedType: type,
usages: [],
});
}
const method = methodsByApiName.get(signature)!;
method.usages.push(usage);
method.usages.push({
...usage,
classification,
});
});
const externalApiUsages = Array.from(methodsByApiName.values());
externalApiUsages.sort((a, b) => {
// Sort first by supported, putting unmodeled methods first.
if (a.supported && !b.supported) {
return 1;
}
if (!a.supported && b.supported) {
return -1;
}
// Then sort by number of usages descending
return b.usages.length - a.usages.length;
});
return externalApiUsages;
return Array.from(methodsByApiName.values());
}

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