mirror of
https://github.com/sourcegraph/sourcegraph.git
synced 2026-02-06 16:31:47 +00:00
Vscode extension: Delete vscode extension package (#58023)
* Remove vscode from CI * Delete vscode package * Remove vscode dependencies * Update CHANGELOG.md
This commit is contained in:
parent
8543ee17c0
commit
c3e2bf4fc8
@ -326,7 +326,7 @@ See https://handbook.sourcegraph.com/community/faq#is-all-of-sourcegraph-open-so
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['client/vscode/**', 'client/browser/**', 'client/jetbrains/**'],
|
||||
files: ['client/browser/**', 'client/jetbrains/**'],
|
||||
rules: {
|
||||
'no-console': 'off',
|
||||
},
|
||||
|
||||
@ -35,6 +35,8 @@ All notable changes to Sourcegraph are documented in this file.
|
||||
- The following experimental settings in site-configuration are now deprecated and will not be read anymore: `maxReorderQueueSize`, `maxQueueMatchCount`, `maxReorderDurationMS`. [#57468](https://github.com/sourcegraph/sourcegraph/pull/57468)
|
||||
- The feature-flag `search-ranking`, which allowed to disable the improved ranking introduced in 5.1, is now deprecated and will not be read anymore. [#57468](https://github.com/sourcegraph/sourcegraph/pull/57468)
|
||||
- The GitHub Proxy service is no longer required and has been removed from deployment options. [#55290](https://github.com/sourcegraph/sourcegraph/issues/55290)
|
||||
- The VSCode search extension "Sourcegraph for VS Code" has been sunset and removed from Sourcegraph
|
||||
repository. [#58023](https://github.com/sourcegraph/sourcegraph/pull/58023)
|
||||
|
||||
## Unreleased 5.2.2
|
||||
|
||||
|
||||
@ -1,2 +0,0 @@
|
||||
# TODO(bazel): remove when no longer generated into src
|
||||
src/graphql-operations.ts
|
||||
@ -1,7 +0,0 @@
|
||||
**/graphql-operations.ts
|
||||
graphql-operations.ts
|
||||
**/node_modules/**
|
||||
dist/
|
||||
package.json
|
||||
src/vendor/*.js
|
||||
code-intel-extensions/
|
||||
5
client/vscode/.gitignore
vendored
5
client/vscode/.gitignore
vendored
@ -1,5 +0,0 @@
|
||||
dist/
|
||||
*.vsix
|
||||
.vscode-test/
|
||||
|
||||
code-intel-extensions
|
||||
@ -1,11 +0,0 @@
|
||||
{
|
||||
"extends": ["../../.stylelintrc.json"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["./src/webview/index.scss", "./src/webview/theming/highlight.scss"],
|
||||
"rules": {
|
||||
"@sourcegraph/filenames-match-regex": null
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
.editorconfig
|
||||
.eslintignore
|
||||
.eslintrc.js
|
||||
.github/**
|
||||
.gitignore
|
||||
.prettierignore
|
||||
.stylelintrc.json
|
||||
.vscode-test/**
|
||||
.vscode/**
|
||||
*.vsix
|
||||
*.map
|
||||
**/*.map
|
||||
**/*.ts
|
||||
**/tsconfig*.json
|
||||
dist/*.vsix
|
||||
node_modules/**
|
||||
out/**
|
||||
prettier.config.json
|
||||
scripts/**
|
||||
src/**
|
||||
test/**
|
||||
tests/**
|
||||
tsconfig.json
|
||||
webviews/**
|
||||
pnpm-lock.yaml
|
||||
@ -1,245 +0,0 @@
|
||||
load("@aspect_rules_js//js:defs.bzl", "js_library")
|
||||
load("@aspect_rules_ts//ts:defs.bzl", "ts_config")
|
||||
load("@npm//:defs.bzl", "npm_link_all_packages")
|
||||
load("//client/shared/dev:generate_graphql_operations.bzl", "generate_graphql_operations")
|
||||
load("//client/shared/dev:tools.bzl", "module_style_typings")
|
||||
load("//dev:defs.bzl", "sass", "ts_project")
|
||||
load("//dev:eslint.bzl", "eslint_config_and_lint_root")
|
||||
|
||||
# TODO(bazel): webpack workers?
|
||||
# gazelle:js_ignore_imports **/*.worker.ts
|
||||
|
||||
# gazelle:js_resolve **/*.module.scss :module_style_typings
|
||||
# gazelle:js_resolve vscode //:node_modules/@types/vscode
|
||||
|
||||
npm_link_all_packages(name = "node_modules")
|
||||
|
||||
eslint_config_and_lint_root()
|
||||
|
||||
ts_config(
|
||||
name = "tsconfig",
|
||||
src = "tsconfig.json",
|
||||
visibility = ["//client:__subpackages__"],
|
||||
deps = [
|
||||
"//:tsconfig",
|
||||
"//client/branded:tsconfig",
|
||||
"//client/build-config:tsconfig",
|
||||
"//client/client-api:tsconfig",
|
||||
"//client/codeintellify:tsconfig",
|
||||
"//client/common:tsconfig",
|
||||
"//client/extension-api-types:tsconfig",
|
||||
"//client/http-client:tsconfig",
|
||||
"//client/shared:tsconfig",
|
||||
"//client/wildcard:tsconfig",
|
||||
],
|
||||
)
|
||||
|
||||
module_style_typings(
|
||||
name = "module_style_typings",
|
||||
deps = ["//client/wildcard:sass-breakpoints"],
|
||||
)
|
||||
|
||||
sass(
|
||||
name = "module_styles",
|
||||
srcs = glob(["src/**/*.module.scss"]),
|
||||
deps = ["//client/wildcard:sass-breakpoints"],
|
||||
)
|
||||
|
||||
# TODO(bazel): sass - src/webview/index.scss
|
||||
|
||||
sass(
|
||||
name = "package_styles",
|
||||
srcs = glob(
|
||||
["src/**/*.scss"],
|
||||
exclude = [
|
||||
"src/**/*.module.scss",
|
||||
"src/webview/index.scss",
|
||||
],
|
||||
),
|
||||
deps = [
|
||||
"//:node_modules/@reach/tabs",
|
||||
"//client/wildcard:global-styles",
|
||||
],
|
||||
)
|
||||
|
||||
js_library(
|
||||
name = "graphql_operations_files",
|
||||
# Keep in sync with glob in client/shared/dev/generateGraphQlOperations.js
|
||||
srcs = glob(
|
||||
[
|
||||
"src/**/*.ts",
|
||||
"src/**/*.tsx",
|
||||
],
|
||||
# TODO: Ignore legacy build generated file as it conflicts with the Bazel
|
||||
# build. This can be removed after the migration.
|
||||
[
|
||||
"src/graphql-operations.ts",
|
||||
"src/**/*.module.scss.d.ts",
|
||||
],
|
||||
),
|
||||
visibility = ["//client/shared:__pkg__"],
|
||||
)
|
||||
|
||||
generate_graphql_operations(
|
||||
name = "graphql_operations_ts",
|
||||
srcs = [
|
||||
":graphql_operations_files",
|
||||
],
|
||||
out = "src/graphql-operations.ts",
|
||||
interface_name = "VSCodeGraphQlOperations",
|
||||
visibility = ["//client/shared:__pkg__"],
|
||||
)
|
||||
|
||||
ts_project(
|
||||
name = "graphql_operations",
|
||||
srcs = ["src/graphql-operations.ts"],
|
||||
tsconfig = ":tsconfig",
|
||||
deps = [
|
||||
":node_modules/@sourcegraph/shared",
|
||||
],
|
||||
)
|
||||
|
||||
ts_project(
|
||||
name = "vscode",
|
||||
srcs = [
|
||||
"code-intel-extensions.json",
|
||||
"globals.d.ts",
|
||||
"package.json",
|
||||
"src/backend/authenticatedUser.ts",
|
||||
"src/backend/blobContent.ts",
|
||||
"src/backend/eventLogger.ts",
|
||||
"src/backend/fetch.ts",
|
||||
"src/backend/files.ts",
|
||||
"src/backend/instanceVersion.ts",
|
||||
"src/backend/node-fetch-fake-for-browser.ts",
|
||||
"src/backend/proxy-agent-fake-for-browser.ts",
|
||||
"src/backend/repositoryMetadata.ts",
|
||||
"src/backend/requestGraphQl.ts",
|
||||
"src/backend/searchContexts.ts",
|
||||
"src/backend/sourcegraphSettings.ts",
|
||||
"src/backend/streamSearch.ts",
|
||||
"src/code-intel/SourcegraphDefinitionProvider.ts",
|
||||
"src/code-intel/SourcegraphHoverProvider.ts",
|
||||
"src/code-intel/SourcegraphReferenceProvider.ts",
|
||||
"src/code-intel/initialize.ts",
|
||||
"src/code-intel/languages.ts",
|
||||
"src/code-intel/location.ts",
|
||||
"src/commands/browserActionsNode.ts",
|
||||
"src/commands/browserActionsWeb.ts",
|
||||
"src/commands/git-helpers.ts",
|
||||
"src/commands/initialize.ts",
|
||||
"src/common/links.ts",
|
||||
"src/contract.ts",
|
||||
"src/extension.ts",
|
||||
"src/file-system/FileTree.ts",
|
||||
"src/file-system/FilesTreeDataProvider.ts",
|
||||
"src/file-system/SourcegraphFileSystemProvider.ts",
|
||||
"src/file-system/SourcegraphUri.ts",
|
||||
"src/file-system/commands.ts",
|
||||
"src/file-system/initialize.ts",
|
||||
"src/log.ts",
|
||||
"src/settings/LocalStorageService.ts",
|
||||
"src/settings/accessTokenSetting.ts",
|
||||
"src/settings/displayWarnings.ts",
|
||||
"src/settings/endpointSetting.ts",
|
||||
"src/settings/invalidation.ts",
|
||||
"src/settings/readConfiguration.ts",
|
||||
"src/settings/recommendations.ts",
|
||||
"src/settings/uninstall.ts",
|
||||
"src/state.ts",
|
||||
"src/vsCodeApi.ts",
|
||||
"src/webview/comlink/extensionEndpoint.ts",
|
||||
"src/webview/comlink/index.ts",
|
||||
"src/webview/comlink/webviewEndpoint.ts",
|
||||
"src/webview/commands.ts",
|
||||
"src/webview/initialize.ts",
|
||||
"src/webview/platform/AuthProvider.ts",
|
||||
"src/webview/platform/EventLogger.ts",
|
||||
"src/webview/platform/context.ts",
|
||||
"src/webview/platform/polyfills/index.ts",
|
||||
"src/webview/platform/polyfills/polyfill.ts",
|
||||
"src/webview/platform/telemetryService.ts",
|
||||
"src/webview/search-panel/MatchHandlersContext.ts",
|
||||
"src/webview/search-panel/RepoView.tsx",
|
||||
"src/webview/search-panel/SearchHomeView.tsx",
|
||||
"src/webview/search-panel/SearchResultsView.tsx",
|
||||
"src/webview/search-panel/alias/CommitSearchResult.tsx",
|
||||
"src/webview/search-panel/alias/FileMatchChildren.tsx",
|
||||
"src/webview/search-panel/alias/ModalVideo.tsx",
|
||||
"src/webview/search-panel/alias/RepoFileLink.tsx",
|
||||
"src/webview/search-panel/alias/RepoSearchResult.tsx",
|
||||
"src/webview/search-panel/alias/SymbolSearchResult.tsx",
|
||||
"src/webview/search-panel/alias/fetchSearchContext.ts",
|
||||
"src/webview/search-panel/api.ts",
|
||||
"src/webview/search-panel/components/BrandHeader.tsx",
|
||||
"src/webview/search-panel/components/ButtonDropdownCta.tsx",
|
||||
"src/webview/search-panel/components/HomeFooter.tsx",
|
||||
"src/webview/search-panel/components/SearchExamples.tsx",
|
||||
"src/webview/search-panel/components/SearchResultsInfoBar.tsx",
|
||||
"src/webview/search-panel/components/icons.tsx",
|
||||
"src/webview/search-panel/index.tsx",
|
||||
"src/webview/sidebars/auth/AuthSidebarView.tsx",
|
||||
"src/webview/sidebars/help/HelpSidebarView.tsx",
|
||||
"src/webview/sidebars/help/index.tsx",
|
||||
"src/webview/sidebars/history/HistorySidebarView.tsx",
|
||||
"src/webview/sidebars/history/components/RecentFilesSection.tsx",
|
||||
"src/webview/sidebars/history/components/RecentRepositoriesSection.tsx",
|
||||
"src/webview/sidebars/history/components/RecentSearchesSection.tsx",
|
||||
"src/webview/sidebars/search/ContextInvalidatedSidebarView.tsx",
|
||||
"src/webview/sidebars/search/SearchSidebarView.tsx",
|
||||
"src/webview/sidebars/search/api.ts",
|
||||
"src/webview/sidebars/search/extension-host/index.ts",
|
||||
"src/webview/sidebars/search/extension-host/main.worker.ts",
|
||||
"src/webview/sidebars/search/extension-host/worker.ts",
|
||||
"src/webview/sidebars/search/index.tsx",
|
||||
"src/webview/theming/sourcegraphTheme.ts",
|
||||
],
|
||||
tsconfig = ":tsconfig",
|
||||
deps = [
|
||||
":graphql_operations",
|
||||
":module_style_typings",
|
||||
":node_modules/@sourcegraph/branded",
|
||||
":node_modules/@sourcegraph/client-api",
|
||||
":node_modules/@sourcegraph/codeintellify",
|
||||
":node_modules/@sourcegraph/common",
|
||||
":node_modules/@sourcegraph/extension-api-types",
|
||||
":node_modules/@sourcegraph/http-client",
|
||||
":node_modules/@sourcegraph/shared",
|
||||
":node_modules/@sourcegraph/wildcard",
|
||||
"//:node_modules/@mdi/js",
|
||||
"//:node_modules/@reach/visually-hidden",
|
||||
"//:node_modules/@types/classnames",
|
||||
"//:node_modules/@types/history",
|
||||
"//:node_modules/@types/lodash",
|
||||
"//:node_modules/@types/node",
|
||||
"//:node_modules/@types/node-fetch",
|
||||
"//:node_modules/@types/react",
|
||||
"//:node_modules/@types/react-dom",
|
||||
"//:node_modules/@types/uuid",
|
||||
"//:node_modules/@types/vscode",
|
||||
"//:node_modules/@types/vscode-webview", #keep
|
||||
"//:node_modules/@vscode/webview-ui-toolkit",
|
||||
"//:node_modules/agent-base",
|
||||
"//:node_modules/classnames",
|
||||
"//:node_modules/comlink",
|
||||
"//:node_modules/core-js",
|
||||
"//:node_modules/execa",
|
||||
"//:node_modules/graphql",
|
||||
"//:node_modules/history",
|
||||
"//:node_modules/http-proxy-agent",
|
||||
"//:node_modules/https-proxy-agent",
|
||||
"//:node_modules/lodash",
|
||||
"//:node_modules/mdi-react",
|
||||
"//:node_modules/node-fetch",
|
||||
"//:node_modules/react",
|
||||
"//:node_modules/react-dom",
|
||||
"//:node_modules/react-router-dom",
|
||||
"//:node_modules/rxjs",
|
||||
"//:node_modules/use-deep-compare-effect",
|
||||
"//:node_modules/utility-types",
|
||||
"//:node_modules/uuid",
|
||||
"//:node_modules/zustand",
|
||||
"//client/common:common_lib", #keep
|
||||
"//client/shared:shared_lib", #keep
|
||||
],
|
||||
)
|
||||
@ -1,201 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
The Sourcegraph extension uses major.EVEN_NUMBER.patch (eg. 2.0.1) for release versions and major.ODD_NUMBER.patch (eg. 2.1.1) for pre-release versions.
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Changes
|
||||
|
||||
- Change the extension name from "Sourcegraph" to "Search by Sourcegraph" [pull/51790](https://github.com/sourcegraph/sourcegraph/pull/51790)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Various UI fixes for dark and light themes [pull/50598](https://github.com/sourcegraph/sourcegraph/pull/50598)
|
||||
|
||||
## 2.2.15
|
||||
|
||||
### Fixes
|
||||
|
||||
- Prefer `upstream` and `origin` remotes when no remote is selected [issues/2761](https://github.com/sourcegraph/sourcegraph/issues/2761) [pull/48369](https://github.com/sourcegraph/sourcegraph/pull/48369)
|
||||
- Fixes content security policy configuration: [pull/47263](https://github.com/sourcegraph/sourcegraph/pull/47263)
|
||||
|
||||
## 2.2.14
|
||||
|
||||
### Changes
|
||||
|
||||
- Implement proxy support in the process that has access to node APIs [issues/41181](https://github.com/sourcegraph/sourcegraph/issues/41181)
|
||||
|
||||
## 2.2.13
|
||||
|
||||
### Changes
|
||||
|
||||
- Support for logical multiline matches in the UI for Sourcegraph instance versions >= 3.42.0 [pull/43007](https://github.com/sourcegraph/sourcegraph/pull/43007)
|
||||
- Tokens will now be stored in secret storage and removed from user settings [issues/36731](https://github.com/sourcegraph/sourcegraph/issues/36731)
|
||||
- Users can now log in through the built-in [authentication API](https://code.visualstudio.com/api/references/vscode-api#authentication) [issues/36731](https://github.com/sourcegraph/sourcegraph/issues/36731)
|
||||
- Add log out button to `Help and Feedback` sidebar under `User` [issues/36731](https://github.com/sourcegraph/sourcegraph/issues/36731)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fix issue where pattern type was always set to `literal` for Sourcegraph instance versions earlier than v3.43.0, which was overriding regex/structural toggles [pull/43005](https://github.com/sourcegraph/sourcegraph/pull/43005)
|
||||
|
||||
## 2.2.12
|
||||
|
||||
### Fixes
|
||||
|
||||
- Vary search pattern type depending on Sourcegraph instance version: [issues/41236](https://github.com/sourcegraph/sourcegraph/issues/41236), [pull/42178](https://github.com/sourcegraph/sourcegraph/pull/42178)
|
||||
|
||||
## 2.2.10
|
||||
|
||||
### Changes
|
||||
|
||||
- Remove tracking parameters from all shareable URLs [pull/42022](https://github.com/sourcegraph/sourcegraph/pull/42022)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fix Sourcegraph blob link generation: [issues/42060](https://github.com/sourcegraph/sourcegraph/issues/42060), [pull/42065](https://github.com/sourcegraph/sourcegraph/pull/42065)
|
||||
|
||||
## 2.2.9
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fix an issue that prevented search results on some older Sourcegraph instance versions to not render properly [pull/40621](https://github.com/sourcegraph/sourcegraph/pull/40621)
|
||||
|
||||
## 2.2.8
|
||||
|
||||
### Changes
|
||||
|
||||
- `Internal:` Automate release step for Open-VSX registry: [issues/37704](https://github.com/sourcegraph/sourcegraph/issues/37704)
|
||||
- Remove integrations banners and corresponding pings: [issues/38625](https://github.com/sourcegraph/sourcegraph/issues/38625), [pull/38715](https://github.com/sourcegraph/sourcegraph/pull/38715), [pull/38862](https://github.com/sourcegraph/sourcegraph/pull/38862)
|
||||
|
||||
### Fixes
|
||||
|
||||
## 2.2.7
|
||||
|
||||
### Changes
|
||||
|
||||
- Remove references to creating an account on cloud, or configuring a cloud account [pull/38071](https://github.com/sourcegraph/sourcegraph/pull/38071)
|
||||
|
||||
### Fixes
|
||||
|
||||
## 2.2.6
|
||||
|
||||
### Changes
|
||||
|
||||
- Remove notification to add Sourcegraph extension to the workspace [issues/37772](https://github.com/sourcegraph/sourcegraph/issues/37772)
|
||||
|
||||
### Fixes
|
||||
|
||||
-
|
||||
|
||||
## 2.2.5
|
||||
|
||||
### Changes
|
||||
|
||||
- Update Sourcegraph logo in sidebar [issues/37710](https://github.com/sourcegraph/sourcegraph/issues/37710)
|
||||
- Sourcegraph extension is now listed in [Open VSX Registry](https://open-vsx.org/extension/sourcegraph/sourcegraph) [issues/36477](https://github.com/sourcegraph/sourcegraph/issues/36477)
|
||||
- Sourcegraph extension is now available for installation in all Gitpod VS Code Workspaces [issues/37760](https://github.com/sourcegraph/sourcegraph/issues/37760)
|
||||
|
||||
## 2.2.4
|
||||
|
||||
### Changes
|
||||
|
||||
- Optimize package size [issues/36192](https://github.com/sourcegraph/sourcegraph/issues/36192)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Check if default branch exists when opening files [issues/36743](https://github.com/sourcegraph/sourcegraph/issues/36743)
|
||||
|
||||
## 2.2.3
|
||||
|
||||
### Changes
|
||||
|
||||
- Update Access Token headers setting method --thanks @ptxmac for the contribution! [issues/34338](https://github.com/sourcegraph/sourcegraph/issues/34338)
|
||||
- Add options to choose between main branch or current branch when copy/open file. Always use default branch if set [issues/34591](https://github.com/sourcegraph/sourcegraph/issues/34591)
|
||||
- CTA for adding Sourcegraph extension to Workspace Recommendations [issues/34829](https://github.com/sourcegraph/sourcegraph/issues/34829)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Windows file path issue [issues/34788](https://github.com/sourcegraph/sourcegraph/issues/34788)
|
||||
- Sourcegraph icon in help sidebar now shows on light theme [issues/35672](https://github.com/sourcegraph/sourcegraph/issues/35672)
|
||||
- Highlight background color for VS Code Light & Light+ Theme [issues/35767](https://github.com/sourcegraph/sourcegraph/issues/35767)
|
||||
- Display reload button when instance URL is updated [issues/35980](https://github.com/sourcegraph/sourcegraph/issues/35980)
|
||||
|
||||
## 2.2.2
|
||||
|
||||
### Changes
|
||||
|
||||
- Display current extension version and instance version in frontend [issues/34729](https://github.com/sourcegraph/sourcegraph/issues/34729)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Remove incorrect unsupported instance error messages on first load [issues/34207](https://github.com/sourcegraph/sourcegraph/issues/34207)
|
||||
- Links to open remote file in Sourcegraph web are now decoded correctly [issues/34630](https://github.com/sourcegraph/sourcegraph/issues/34630)
|
||||
- Remove pattern restriction for basePath [issues/34731](https://github.com/sourcegraph/sourcegraph/issues/34731)
|
||||
|
||||
## 2.2.1
|
||||
|
||||
### Changes
|
||||
|
||||
- Add Help and Feedback sidebar [issue/31021](https://github.com/sourcegraph/sourcegraph/issues/31021)
|
||||
- Add CONTRIBUTING guide [issue/26536](https://github.com/sourcegraph/sourcegraph/issues/26536)
|
||||
- Display error message when connected to unsupported instances [issue/31808](https://github.com/sourcegraph/sourcegraph/issues/31808)
|
||||
- Log events with `IDEEXTENSION` as event source for instances on 3.38.0 and above [issue/32851](https://github.com/sourcegraph/sourcegraph/issues/32851)
|
||||
- Add new configuration setting: sourcegraph.basePath [issue/32633](https://github.com/sourcegraph/sourcegraph/issues/32633)
|
||||
- Add ability to open local copy of a search result if file exists in current workspace or basePath [issue/32633](https://github.com/sourcegraph/sourcegraph/issues/32633)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Improve developer scripts [issue/32741](https://github.com/sourcegraph/sourcegraph/issues/32741)
|
||||
- Code Monitor button redirect issue for non signed-in users [issues/33631](https://github.com/sourcegraph/sourcegraph/issues/33631)
|
||||
- Error regarding missing PatternType when creating save search [issues/31093](https://github.com/sourcegraph/sourcegraph/issues/31093)
|
||||
|
||||
## 2.2.0
|
||||
|
||||
### Changes
|
||||
|
||||
- Add pings for Sourcegraph ide extensions usage metrics [issue/29124](https://github.com/sourcegraph/sourcegraph/issues/29124)
|
||||
- Add input fields to update Sourcegraph instance url [issue/31804](https://github.com/sourcegraph/sourcegraph/issues/31804)
|
||||
- Clear search results on tab close [issue/30583](https://github.com/sourcegraph/sourcegraph/issues/30583)
|
||||
|
||||
## 2.0.9
|
||||
|
||||
### Changes
|
||||
|
||||
- Add Changelog for version tracking purpose [issue/28300](https://github.com/sourcegraph/sourcegraph/issues/28300)
|
||||
- Add VS Code Web support for instances on 3.36.0+ [issue/28403](https://github.com/sourcegraph/sourcegraph/issues/28403)
|
||||
- Update to use API endpoint for stream search [issue/30916](https://github.com/sourcegraph/sourcegraph/issues/30916)
|
||||
- Add new configuration setting `sourcegraph.requestHeaders` for adding custom headers [issue/30916](https://github.com/sourcegraph/sourcegraph/issues/30916)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Manage context display issue for instances under v3.36.0 [issue/31022](https://github.com/sourcegraph/sourcegraph/issues/31022)
|
||||
|
||||
## 2.0.8
|
||||
|
||||
### Fixes
|
||||
|
||||
- Files will open in the correct url scheme [issue/31095](https://github.com/sourcegraph/sourcegraph/issues/31095)
|
||||
- The 'All Search Keywords' button is now linked to Sourcegraph docs site correctly [issue/31023](https://github.com/sourcegraph/sourcegraph/issues/31023)
|
||||
- Update Sign Up links with the correct utm parameters
|
||||
|
||||
## 2.0.7
|
||||
|
||||
### Changes
|
||||
|
||||
- Remove Sign Up CTA in Sidebar for self-host instances
|
||||
|
||||
### Fixes
|
||||
|
||||
- Add backward compatibility for configuration settings from v1: `sourcegraph.defaultBranch` and `sourcegraph.remoteUrlReplacements`
|
||||
|
||||
## 2.0.6
|
||||
|
||||
### Changes
|
||||
|
||||
- Remove Sign Up CTAs in Search Result for self-host instances
|
||||
|
||||
## 2.0.1
|
||||
|
||||
### Changes
|
||||
|
||||
- Add Code Monitor
|
||||
@ -1,219 +0,0 @@
|
||||
# Contributing to Sourcegraph VS Code Extension
|
||||
|
||||
Thank you for your interest in contributing to Sourcegraph!
|
||||
The goal of this document is to provide a high-level overview of how you can contribute to the Sourcegraph VS Code Extension.
|
||||
Please refer to our [main CONTRIBUTING](https://github.com/sourcegraph/sourcegraph/blob/main/CONTRIBUTING.md) docs for general information regarding contributing to any Sourcegraph repository.
|
||||
|
||||
## License
|
||||
|
||||
Apache
|
||||
|
||||
## Feedback
|
||||
|
||||
Your feedback is important to us and is greatly appreciated. Please do not hesitate to submit your ideas or suggestions about how we can improve the extension to our [VS Code Extension Feedback Discussion Thread](https://github.com/sourcegraph/sourcegraph/discussions/34821) on GitHub.
|
||||
|
||||
## Issues / Bugs
|
||||
|
||||
New issues and feature requests can be filed through our [issue tracker](https://github.com/sourcegraph/sourcegraph/issues/new?labels=team/integrations,vscode-extension&title=VSCode+Bug+report:+&projects=Integrations%20Project%20Board) using the `vscode-extension` & `team/integrations` label.
|
||||
|
||||
## Architecture Diagram
|
||||
|
||||
┌──────────────────────────┐
|
||||
│ env: Node OR Web Worker │
|
||||
┌───────────┤ VS Code extension "Core" ├───────────────┐
|
||||
│ │ │ │
|
||||
│ └──────────────────────────┘ │
|
||||
│ │
|
||||
┌─────────────▼────────────┐ ┌──────────────▼───────────┐
|
||||
│ env: Web │ │ env: Web │
|
||||
┌───┤ "search sidebar" webview │ │ "search panel" webview │
|
||||
│ │ │ │ │
|
||||
│ └──────────────────────────┘ └──────────────────────────┘
|
||||
│
|
||||
┌▼───────────────────────────┐
|
||||
│ env: Web Worker │
|
||||
│ Sourcegraph Extension host │
|
||||
│ │
|
||||
└────────────────────────────┘
|
||||
|
||||
- See below for documentation on state management.
|
||||
- One state machine that lives in Core
|
||||
- See './contract.ts' to see the APIs for the three main components:
|
||||
- Core, search sidebar, and search panel.
|
||||
- The extension host API is exposed through the search sidebar.
|
||||
- See './webview/comlink' for documentation on _how_ communication between contexts works.
|
||||
- It is _not_ important to understand this layer to add features to the VS Code extension (that's why it exists, after all).
|
||||
|
||||
## State Management
|
||||
|
||||
This extension runs code in 4 (and counting) different execution contexts.
|
||||
Coordinating state between these contexts is a difficult task. So, instead of managing shared state in each context, we maintain one state machine in the "Core" context (see above for architecure diagram).
|
||||
All contexts listen for state updates and emit events on which the state machine may transition.
|
||||
|
||||
For example:
|
||||
|
||||
- Commands from VS Code extension core
|
||||
- The first submitted search in a session will cause the state machine to transition from the `search-home` state to the `search-results` state.
|
||||
- This new state will be reflected in both the search sidebar and search panel UIs
|
||||
|
||||
We represent a hierarchical state machine in a "flat" manner to reduce code complexity and because our state machine is simple enough to not necessitate bringing in a library.
|
||||
|
||||
```
|
||||
┌───►home
|
||||
│
|
||||
search
|
||||
│
|
||||
└───►results
|
||||
```
|
||||
|
||||
- remote-browsing
|
||||
- idle
|
||||
- context-invalidated
|
||||
becomes:
|
||||
- [search-home, search-results, remote-browsing, idle, context-invalidated]
|
||||
|
||||
Example user flow state transitions:
|
||||
|
||||
- User clicks on Sourcegraph logo in VS Code sidebar.
|
||||
- Extension activates with initial state of `search-home`
|
||||
- User submits search -> state === `search-results`
|
||||
- User clicks on a search result, which opens a file -> state === `remote-browsing`
|
||||
- User copies some code, then focuses an editor for a local file -> state === `idle`
|
||||
|
||||
## File Structure
|
||||
|
||||
Below is a quick overview of the Sourcegraph extension file structure. It does not include all the files and folders.
|
||||
|
||||
```
|
||||
client/vscode
|
||||
├── images
|
||||
├── scripts // Command line scripts, for example, script to release and publish the extension
|
||||
├── src // Extension source code
|
||||
│ └── extension.ts // Extension entry file
|
||||
│ └── backend // All graphQL queries
|
||||
│ └── code-intel // Build the extension host that processes code-intel data
|
||||
│ └── common // Commonly assets that can be shared among different contexts
|
||||
│ └── commands // Build and register commands
|
||||
│ └── browserActionsNode // Browser action commands when running as a regular extension where Node.js is available
|
||||
│ └── browserActionsWeb // Browser action commands when running as a web extension where Node.js is not available
|
||||
│ └── file-system // Build and register the custom file system
|
||||
│ └── settings // Extension settings and configurations
|
||||
│ └── webview // Components to build the search panel and sidebars
|
||||
│ └── comlink // Handle communications between contexts
|
||||
│ └── platform // Platform context for the webview
|
||||
│ └── search-panel // UI for the homepage and search panel
|
||||
│ └── alias // Alias files for Web extension. See README file in this directory for details
|
||||
│ └── sidebars // UI for all the sidebars
|
||||
│ └── theming // Styling the webview using the predefined VS Code themes
|
||||
│ └── commands.ts // Commands to build the webview views and panel
|
||||
├── tests // Extension test code
|
||||
├── .gitignore // Ignore build output and node_modules
|
||||
├── .vscodeignore // Ignore build output and node_modules
|
||||
├── CHANGELOG.md // An ordered list of changes and fixes
|
||||
├── CONTRIBUTING.md // General guide for developers and contributors
|
||||
├── package.json // Extension manifest
|
||||
├── README.md // General information about the extension
|
||||
├── tsconfig.json // TypeScript configuration
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
### Build and Run
|
||||
|
||||
#### Desktop and Web Version
|
||||
|
||||
1. `git clone` the [Sourcegraph repository](https://github.com/sourcegraph/sourcegraph)
|
||||
1. Install dependencies via `pnpm install` for the Sourcegraph repository
|
||||
1. Edit files in the `client/vscode` directory
|
||||
1. To see your changes, open the `Run and Debug` sidebar view in VS Code, and
|
||||
select `Launch VS Code Extension` (`Launch VS Code Web Extension` for VS Code Web) from the dropdown menu. (Or, in the `client/vscode` directory, run `pnpm run build`.)
|
||||
|
||||
### Integration Tests
|
||||
|
||||
To run integration tests:
|
||||
|
||||
1. In the Sourcegraph repository root, run `pnpm install`
|
||||
2. In the `client/vscode` directory:
|
||||
1. `pnpm build:test` or `pnpm watch:test`
|
||||
2. `pnpm test-integration`
|
||||
|
||||
## GitPod
|
||||
|
||||
The Sourcegraph extension for VS Code also works on GitPod.
|
||||
|
||||
#### Desktop Version
|
||||
|
||||
To install this extension on GitPod Desktop:
|
||||
|
||||
1. Open the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of your workspace
|
||||
2. Search for `Sourcegraph`
|
||||
3. Click `install` to install the Sourcegraph extension
|
||||
|
||||
#### Web Version
|
||||
|
||||
To run and test the web extension on GitPod Web (as well as VS Code and GitHub for the web), you must sideload the extension from your local machine as suggested in the following steps:
|
||||
|
||||
1. `git clone` the [Sourcegraph repository](https://github.com/sourcegraph/sourcegraph)
|
||||
1. Run `pnpm install && pnpm generate` at the root directory to install dependencies and generate the required schemas
|
||||
1. Run `pnpm -C client/vscode build` at root to build the Sourcegraph VS Code extension for Web
|
||||
1. Once the build has been completed, move to the extension’s directory: `cd client/vscode`
|
||||
1. Start an HTTP server inside the extension’s path to host the extension locally: `pnpx serve --cors -l 8988`
|
||||
1. In another terminal, generate a publicly-accessible URL from your locally running HTTP server using the localtunnel tool: `pnpx localtunnel -p 8988`
|
||||
1. A publicly-accessible URL will be generated for you in the output followed by “your url is:”
|
||||
1. Copy and then open the newly generated URL in a browser and then select “Click to Continue”
|
||||
1. Open the Command Palette in GitPod Web (a GitPod Workspace using the Open in Browser setting)
|
||||
1. Select “Developer: Install Web Extension…”
|
||||
1. Paste the newly generated URL in the input area and select Install
|
||||
1. The extension is now installed
|
||||
|
||||
### Debugging
|
||||
|
||||
Please refer to the [How to Contribute](https://github.com/microsoft/vscode/wiki/How-to-Contribute#debugging) guide by VS Code for debugging tips.
|
||||
|
||||
## Questions
|
||||
|
||||
If you need guidance or have any questions regarding Sourcegraph or the extension in general, we invite you to connect with us on the [Sourcegraph Community Slack group](https://about.sourcegraph.com/community).
|
||||
|
||||
## Resources
|
||||
|
||||
- [Changelog](https://marketplace.visualstudio.com/items/sourcegraph.sourcegraph/changelog)
|
||||
- [Code of Conduct](https://handbook.sourcegraph.com/company-info-and-process/community/code_of_conduct/)
|
||||
- [Developing Sourcegraph guide](https://docs.sourcegraph.com/dev)
|
||||
- [Developing the web clients](https://docs.sourcegraph.com/dev/background-information/web)
|
||||
- [Feedback / Feature Request](https://github.com/sourcegraph/sourcegraph/discussions/34821)
|
||||
- [Issue Tracker](https://github.com/sourcegraph/sourcegraph/labels/vscode-extension)
|
||||
- [Report a bug](https://github.com/sourcegraph/sourcegraph/issues/new?labels=team/integrations,vscode-extension&title=VSCode+Bug+report:+&projects=Integrations%20Project%20Board)
|
||||
- [Troubleshooting docs](https://docs.sourcegraph.com/admin/how-to/troubleshoot-sg-extension#vs-code-extension)
|
||||
|
||||
## Release Process
|
||||
|
||||
The release process for the VS Code Extension for Sourcegraph is currently automated.
|
||||
|
||||
#### Prerequisite
|
||||
|
||||
- Install the [VSCE CLI tool](https://code.visualstudio.com/api/working-with-extensions/publishing-extension#vsce)
|
||||
|
||||
#### Release Steps
|
||||
|
||||
1. Create a new branch when the main branch is ready for release, or use your current working branch if it is ready for release
|
||||
2. Run `pnpm --filter @sourcegraph/vscode run release:$RELEASE_TYPE` in the root directory
|
||||
- $RELEASE_TYPE: major, minor, patch, pre
|
||||
- Example: `pnpm --filter @sourcegraph/vscode run release:patch`
|
||||
- This command will:
|
||||
- Update the package.json file with the next version number
|
||||
- Update the changelog format by listing everything under `Unreleased` to the updated version number
|
||||
- Make a commit for the release and push to the current branch
|
||||
3. Open a PR to merge the current branch into main
|
||||
4. Once the main branch has the updated version number and changelog, run `git push origin main:vsce/release`
|
||||
- This will trigger the build pipeline for publishing the extension using the `pnpm release` command
|
||||
- Publish release to [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=sourcegraph.sourcegraph)
|
||||
- Publish release to [Open VSX Registry](https://open-vsx.org/extension/sourcegraph/sourcegraph)
|
||||
- The extension will be published with the correct package name via the [vsce CLI tool](https://code.visualstudio.com/api/working-with-extensions/publishing-extension#vsce)
|
||||
5. Visit the [buildkite page for the vsce/release pipeline](https://buildkite.com/sourcegraph/sourcegraph/builds?branch=vsce%2Frelease) to watch the build process
|
||||
|
||||
Once the build is completed with no error, you should see the new version being verified for the Sourcegraph extension in:
|
||||
|
||||
- VS Code Marketplace: [Marketplace Publisher Dashboard](https://marketplace.visualstudio.com/manage/publishers)
|
||||
- Open VSX Registry: [Namespaces Tab in User Settings](https://open-vsx.org/user-settings/namespaces)
|
||||
|
||||
> NOTE: It might take up to 10 minutes before the new release is published.
|
||||
@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2022 Sourcegraph, Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@ -1,127 +0,0 @@
|
||||
# Sourcegraph for Visual Studio Code
|
||||
|
||||
[](https://marketplace.visualstudio.com/items?itemName=sourcegraph.sourcegraph) [](https://marketplace.visualstudio.com/items?itemName=sourcegraph.sourcegraph)
|
||||
|
||||

|
||||
|
||||
Sourcegraph’s code search allows you to find & fix things fast across all your code.
|
||||
|
||||
Sourcegraph for VS Code allows you to search millions of open source repositories right from your VS Code IDE—for free. You can learn from helpful code examples, search best practices, and re-use code from millions of repositories across the open source universe.
|
||||
|
||||
Sourcegraph’s Code Intelligence feature provides fast, cross-repository navigation with “Go to definition” and “Find references” features, allowing you to understand new code quickly and find answers in your code across codebases of any size.
|
||||
|
||||
You can read more about Sourcegraph on our [website](https://about.sourcegraph.com/).
|
||||
|
||||
Not the extension you're looking for? Download the [Cody extension](https://marketplace.visualstudio.com/items?itemName=sourcegraph.cody-ai) for code AI assistance.
|
||||
|
||||
## Installation
|
||||
|
||||
### From the Visual Studio Marketplace:
|
||||
|
||||
1. Install Sourcegraph from the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=sourcegraph.sourcegraph).
|
||||
2. Launch VS Code, and click on the Sourcegraph (Wildcard) icon in the VS Code Activity Bar to open the Sourcegraph extension. Alternatively, you can launch the extension by pressing <kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> and searching for “Sourcegraph: Open search tab.”
|
||||
|
||||
### From within VS Code:
|
||||
|
||||
1. Open the extensions tab on the left side of VS Code (<kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd>).
|
||||
2. Search for `Sourcegraph` -> `Install` and `Reload`.
|
||||
|
||||
### From Gitpod VS Code Workspaces:
|
||||
|
||||
1. Open the `Extensions view` by clicking on the Extensions icon in the [Activity Bar](https://code.visualstudio.com/api/ux-guidelines/overview#activity-bar) on the side of your Gitpod VS Code workspace
|
||||
2. Search for [Sourcegraph](https://open-vsx.org/extension/sourcegraph/sourcegraph) -> `Install` and `Reload`.
|
||||
|
||||
## Using the Sourcegraph extension
|
||||
|
||||
To get started and open the Sourcegraph extension, simply click the Sourcegraph (Wildcard) icon in the VS Code Activity Bar.
|
||||
|
||||
Sourcegraph functions like any search engine; simply type in your search query, and Sourcegraph will populate search results.
|
||||
|
||||
Learn more about Sourcegraph search in our [docs](https://docs.sourcegraph.com/code_search).
|
||||
|
||||
For example, you can search for "auth provider" in a Go repository with a search like this one:
|
||||
|
||||
```
|
||||
repo:sourcegraph/sourcegraph lang:go auth provider
|
||||
```
|
||||
|
||||

|
||||
|
||||
## Adding and searching your own code
|
||||
|
||||
### Creating an account
|
||||
|
||||
In addition to searching open source code, you can create a Sourcegraph account to search your own private and public repositories. You can create an account and sync your repositories with the following steps:
|
||||
|
||||
1. Click the `Create an account` button in the sidebar of the Sourcegraph extension. You will be directed to sourcegraph.com in your browser.
|
||||
2. Follow the instructions to create and configure your Sourcegraph instance
|
||||
|
||||
### Connecting to your Sourcegraph instance
|
||||
|
||||
1. In Sourcegraph, in your account settings, navigate to `Access tokens`, then click `Generate new token`.
|
||||
2. Once you have generated a token, navigate to your VS Code Settings, then navigate to "Extension settings".
|
||||
3. Navigate to `Code preferences`, then click `Settings`.
|
||||
4. Search for `Sourcegraph`, and enter the newly generated access token as well as your Sourcegraph instance URL.
|
||||
5. Add custom headers using the `sourcegraph.requestHeaders` setting (added in v2.0.9) if a specific header is required to make connection to your private instance.
|
||||
|
||||
### Adding it to your workspace's recommended extensions
|
||||
|
||||
1. Create a `.vscode` folder (if not already present) in the root of your repository
|
||||
2. Inside that folder, create a new file named `extensions.json` (if it doesn't already exist) with the following structure.
|
||||
|
||||
```
|
||||
{
|
||||
"recommendations": ["sourcegraph.sourcegraph"]
|
||||
}
|
||||
```
|
||||
|
||||
3. If the file does exist, append `"sourcegraph.sourcegraph"` to the `"recommendations"` array.
|
||||
4. Push the changes to your repository for your other colleagues to share.
|
||||
|
||||
Alternatively you can use the `Extensions: Configure Recommended Extensions (Workspace Folder)` command from within VS Code.
|
||||
|
||||
## Keyboard Shortcuts:
|
||||
|
||||
| Description | Mac | Linux / Windows |
|
||||
| -------------------------------------------- | -------------------------------------------- | --------------------------------------------- |
|
||||
| Open Sourcegraph Search Tab/Search Selection | <kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>8</kbd> | <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>8</kbd> |
|
||||
| Open File in Sourcegraph Cloud | <kbd>Option</kbd>+<kbd>A</kbd> | <kbd>Alt</kbd>+<kbd>A</kbd> |
|
||||
| Search Selected Text in Sourcegraph Cloud | <kbd>Option</kbd>+<kbd>S</kbd> | <kbd>Alt</kbd>+<kbd>S</kbd> |
|
||||
|
||||
## Extension Settings
|
||||
|
||||
This extension contributes the following settings:
|
||||
|
||||
| Setting | Description | Example |
|
||||
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
|
||||
| sourcegraph.url | Specify your on-premises Sourcegraph instance here, if applicable. The extension is connected to Sourcegraph Cloud by default. | "https://your-sourcegraph.com" |
|
||||
| sourcegraph.accessToken | [Depreciated after 2.2.12] The access token to query the Sourcegraph API. Required to use this extension with private instances. Create a new access token at `${SOURCEGRAPH_URL}/users/<sourcegraph-username>/settings/tokens` | null |
|
||||
| sourcegraph.remoteUrlReplacements | Object, where each `key` is replaced by `value` in the remote url. | {"github": "gitlab", "master": "main"} |
|
||||
| sourcegraph.defaultBranch | String to set the name of the default branch. Always open files in the default branch. | "master" |
|
||||
| sourcegraph.requestHeaders | Takes object, where each value pair will be added to the request headers made to your instance. | {"Cache-Control": "no-cache", "Proxy-Authenticate": "Basic"} |
|
||||
| sourcegraph.basePath | The file path on the machine to the folder that is expected to contain all repositories. We will try to open search results using the basePath. | "/Users/USERNAME/Documents/" |
|
||||
| sourcegraph.proxyProtocol | The protocol to use when proxying requests to the Sourcegraph instance. | "http", "https" |
|
||||
| sourcegraph.proxyHost | The host to use when proxying requests to the Sourcegraph instance. It shouldn't include a protocol (like "http://") or a port (like ":7080"). When this is set, port must be set as well. | "localhost" |
|
||||
| sourcegraph.proxyPort | The port to use when proxying requests to the Sourcegraph instance. When this is set, host must be set as well. | 80, 443, 7080, 9090 |
|
||||
| sourcegraph.proxyPath | The full path to a file when proxying requests to the Sourcegraph instance via a UNIX socket. | "/home/user/path/unix.socket" |
|
||||
|
||||
## Questions & Feedback
|
||||
|
||||
Feedback and feature requests can be submitted to our [VS Code Extension Feedback Discussion Board](https://github.com/sourcegraph/sourcegraph/discussions/34821) on GitHub.
|
||||
|
||||
## Uninstallation
|
||||
|
||||
1. Open the extensions tab on the left side of VS Code (<kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd>).
|
||||
2. Search for `Sourcegraph` -> Gear icon -> `Uninstall` and `Reload`.
|
||||
|
||||
## Changelog
|
||||
|
||||
Click [here](https://marketplace.visualstudio.com/items/sourcegraph.sourcegraph/changelog) to check the full changelog.
|
||||
|
||||
VS Code will auto-update extensions to the highest version available. Even if you have opted into a pre-release version, you will be updated to the released version when a higher version is released.
|
||||
|
||||
The Sourcegraph extension uses major.EVEN_NUMBER.patch (eg. 2.0.1) for release versions and major.ODD_NUMBER.patch (eg. 2.1.1) for pre-release versions.```
|
||||
|
||||
## Development
|
||||
|
||||
Please see the [CONTRIBUTING](./CONTRIBUTING.md) document if you are interested in contributing directly to our code base.
|
||||
@ -1 +0,0 @@
|
||||
["sourcegraph/apex","sourcegraph/clojure","sourcegraph/cobol","sourcegraph/cpp","sourcegraph/csharp","sourcegraph/cuda","sourcegraph/dart","sourcegraph/elixir","sourcegraph/erlang","sourcegraph/go","sourcegraph/graphql","sourcegraph/groovy","sourcegraph/haskell","sourcegraph/java","sourcegraph/jsonnet","sourcegraph/kotlin","sourcegraph/lisp","sourcegraph/lua","sourcegraph/ocaml","sourcegraph/pascal","sourcegraph/perl","sourcegraph/php","sourcegraph/powershell","sourcegraph/protobuf","sourcegraph/python","sourcegraph/r","sourcegraph/ruby","sourcegraph/rust","sourcegraph/scala","sourcegraph/shell","sourcegraph/starlark","sourcegraph/strato","sourcegraph/swift","sourcegraph/tcl","sourcegraph/thrift","sourcegraph/typescript","sourcegraph/verilog","sourcegraph/vhdl"]
|
||||
13
client/vscode/globals.d.ts
vendored
13
client/vscode/globals.d.ts
vendored
@ -1,13 +0,0 @@
|
||||
declare module '*.scss' {
|
||||
const cssModule: string
|
||||
export default cssModule
|
||||
}
|
||||
declare module '*.css' {
|
||||
const cssModule: string
|
||||
export default cssModule
|
||||
}
|
||||
|
||||
/**
|
||||
* Set by shared/dev/jest-environment.js
|
||||
*/
|
||||
declare var jsdom: import('jsdom').JSDOM
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.6 KiB |
@ -1 +0,0 @@
|
||||
<svg width="256" height="262" viewBox="0 0 256 262" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid"><path d="m74.203 33.602 56.952 208.194c3.827 13.991 18.27 22.23 32.254 18.4 13.993-3.833 22.224-18.28 18.394-32.27l-56.962-208.2c-3.83-13.987-18.27-22.228-32.254-18.394C78.607 5.157 70.373 19.609 74.203 33.6v.002Z" fill="#F96316"/><path d="M179.662 32.813 37.046 193.858c-9.621 10.86-8.616 27.464 2.233 37.087 10.85 9.62 27.438 8.617 37.059-2.238L218.954 67.665c9.621-10.86 8.616-27.459-2.233-37.083-10.854-9.63-27.446-8.624-37.059 2.23v.001Z" fill="#B200F8"/><path d="m18.065 122.054 203.387 67.293c13.765 4.552 28.615-2.92 33.167-16.696 4.562-13.774-2.911-28.63-16.681-33.189L34.556 72.175C20.786 67.62 5.942 75.091 1.387 88.867c-4.55 13.775 2.924 28.635 16.682 33.187h-.004Z" fill="#00B4F2"/></svg>
|
||||
|
Before Width: | Height: | Size: 820 B |
@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 25.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 53.4 55.5" style="enable-background:new 0 0 53.4 55.5;" xml:space="preserve">
|
||||
<style type="text/css">
|
||||
.st0{fill:#FFFFFF;}
|
||||
.st1{fill:#FF5543;}
|
||||
.st2{fill:#A112FF;}
|
||||
.st3{fill:#00CBEC;}
|
||||
</style>
|
||||
<g>
|
||||
<g>
|
||||
<path d="M39.3,10.2c0.7-0.6,1.5-1,2.4-1.1c1.7-0.3,3.6,0.3,4.8,1.7c1.8,2.2,1.6,5.4-0.6,7.2l-7.6,6.5l-5.6-2l-2.1-0.7l-3.5-1.2
|
||||
l2.8-2.4l1.7-1.4L39.3,10.2z"/>
|
||||
<path d="M13.9,45.3c-0.7,0.6-1.5,1-2.4,1.1c-1.7,0.3-3.6-0.3-4.8-1.7c-1.8-2.2-1.6-5.4,0.6-7.2l7.6-6.5l5.6,2l2.1,0.7L26,35
|
||||
l-2.8,2.4l-1.7,1.4L13.9,45.3z"/>
|
||||
</g>
|
||||
<g>
|
||||
<path d="M17.7,7.9c-0.5-2.8,1.3-5.5,4.1-6s5.5,1.3,6,4.1l1.8,9.8l-4.5,3.8l-5.6-2L17.7,7.9z"/>
|
||||
<path d="M35.5,47.5c0.5,2.8-1.3,5.5-4.1,6c-2.8,0.5-5.5-1.3-6-4.1l-1.8-9.8l4.5-3.8l5.6,2L35.5,47.5z"/>
|
||||
</g>
|
||||
<path d="M51.3,36.5c-0.6,1.8-2.2,3-3.9,3.3c-0.9,0.2-1.8,0.1-2.6-0.2l-9.4-3.3l-2.1-0.7l-3.5-1.2l-2.1-0.7l-5.6-2L20,30.8l-3.5-1.2
|
||||
l-2.1-0.7L5,25.5C2.3,24.6,1,21.6,1.9,19c0.6-1.8,2.2-3,3.9-3.3c0.9-0.2,1.8-0.1,2.6,0.2l9.4,3.3l2.1,0.7l3.5,1.2l2.1,0.7l5.6,2
|
||||
l2.1,0.7l3.5,1.2l2.1,0.7l9.4,3.3C50.9,30.9,52.3,33.8,51.3,36.5z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 25.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 53.4 55.5" style="enable-background:new 0 0 53.4 55.5;" xml:space="preserve">
|
||||
<style type="text/css">
|
||||
.st0{fill:#FFFFFF;}
|
||||
.st1{fill:#FF5543;}
|
||||
.st2{fill:#A112FF;}
|
||||
.st3{fill:#00CBEC;}
|
||||
</style>
|
||||
<g>
|
||||
<g>
|
||||
<path class="st0" d="M39.3,10.2c0.7-0.6,1.5-1,2.4-1.1c1.7-0.3,3.6,0.3,4.8,1.7c1.8,2.2,1.6,5.4-0.6,7.2l-7.6,6.5l-5.6-2l-2.1-0.7
|
||||
l-3.5-1.2l2.8-2.4l1.7-1.4L39.3,10.2z"/>
|
||||
<path class="st0" d="M13.9,45.3c-0.7,0.6-1.5,1-2.4,1.1c-1.7,0.3-3.6-0.3-4.8-1.7c-1.8-2.2-1.6-5.4,0.6-7.2l7.6-6.5l5.6,2l2.1,0.7
|
||||
L26,35l-2.8,2.4l-1.7,1.4L13.9,45.3z"/>
|
||||
</g>
|
||||
<g>
|
||||
<path class="st0" d="M17.7,7.9c-0.5-2.8,1.3-5.5,4.1-6s5.5,1.3,6,4.1l1.8,9.8l-4.5,3.8l-5.6-2L17.7,7.9z"/>
|
||||
<path class="st0" d="M35.5,47.5c0.5,2.8-1.3,5.5-4.1,6c-2.8,0.5-5.5-1.3-6-4.1l-1.8-9.8l4.5-3.8l5.6,2L35.5,47.5z"/>
|
||||
</g>
|
||||
<path class="st0" d="M51.3,36.5c-0.6,1.8-2.2,3-3.9,3.3c-0.9,0.2-1.8,0.1-2.6-0.2l-9.4-3.3l-2.1-0.7l-3.5-1.2l-2.1-0.7l-5.6-2
|
||||
L20,30.8l-3.5-1.2l-2.1-0.7L5,25.5C2.3,24.6,1,21.6,1.9,19c0.6-1.8,2.2-3,3.9-3.3c0.9-0.2,1.8-0.1,2.6,0.2l9.4,3.3l2.1,0.7l3.5,1.2
|
||||
l2.1,0.7l5.6,2l2.1,0.7l3.5,1.2l2.1,0.7l9.4,3.3C50.9,30.9,52.3,33.8,51.3,36.5z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.4 KiB |
@ -1 +0,0 @@
|
||||
<svg viewBox="0 0 304 52" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M30.8 51.8c-2.8.5-5.5-1.3-6-4.1L17.2 6.2c-.5-2.8 1.3-5.5 4.1-6s5.5 1.3 6 4.1l7.6 41.5c.5 2.8-1.4 5.5-4.1 6z" fill="#FF5543"/><path d="M10.9 44.7C9.1 45 7.3 44.4 6 43c-1.8-2.2-1.6-5.4.6-7.2L38.7 8.5c2.2-1.8 5.4-1.6 7.2.6 1.8 2.2 1.6 5.4-.6 7.2l-32 27.3c-.7.6-1.6 1-2.4 1.1z" fill="#A112FF"/><path d="M46.8 38.1c-.9.2-1.8.1-2.6-.2L4.4 23.8c-2.7-1-4.1-3.9-3.1-6.6 1-2.7 3.9-4.1 6.6-3.1l39.7 14.1c2.7 1 4.1 3.9 3.1 6.6-.6 1.8-2.2 3-3.9 3.3z" fill="#00CBEC"/><path d="M80 33.1c0-1-.4-1.8-1.1-2.4-.7-.6-1.6-1.2-2.7-1.7s-2.3-1-3.6-1.6c-1.3-.5-2.5-1.2-3.6-2s-2-1.8-2.7-3c-.7-1.2-1.1-2.7-1.1-4.5 0-1.6.3-3 .8-4.1.5-1.2 1.3-2.1 2.3-2.9 1-.8 2.1-1.3 3.5-1.7 1.3-.4 2.8-.6 4.5-.6 1.9 0 3.7.2 5.3.5 1.6.3 3.1.8 4.1 1.4l-2 5.3c-.7-.4-1.7-.8-3.1-1.1-1.4-.4-2.8-.5-4.4-.5-1.5 0-2.6.3-3.4.9-.8.6-1.2 1.4-1.2 2.4 0 .9.4 1.7 1.1 2.3.7.6 1.6 1.2 2.7 1.7s2.3 1.1 3.6 1.6c1.3.6 2.5 1.2 3.6 2s2 1.8 2.7 2.9c.7 1.2 1.1 2.6 1.1 4.3 0 1.7-.3 3.2-.9 4.5-.6 1.3-1.4 2.3-2.4 3.1-1 .8-2.3 1.5-3.8 1.9-1.5.4-3.1.6-4.9.6-2.3 0-4.4-.2-6.1-.7-1.8-.4-3.1-.9-3.9-1.3l2-5.4c.3.2.8.4 1.3.6.5.2 1.2.4 1.8.6.7.2 1.4.3 2.2.5.8.1 1.5.2 2.3.2 1.9 0 3.3-.3 4.3-1 1.2-.6 1.7-1.5 1.7-2.8zm9.1-2.9c0-3.9 1-7 2.9-9.1 1.9-2.1 4.6-3.2 8.1-3.2 1.9 0 3.5.3 4.8.9 1.4.6 2.5 1.4 3.4 2.5.9 1.1 1.6 2.4 2 3.9.4 1.5.7 3.2.7 5 0 3.9-1 7-2.9 9.1-1.9 2.1-4.6 3.2-8.1 3.2-1.9 0-3.5-.3-4.8-.9-1.4-.6-2.5-1.4-3.4-2.5-.9-1.1-1.6-2.4-2-3.9-.5-1.5-.7-3.2-.7-5zm6.2 0c0 1 .1 2 .3 2.8.2.9.5 1.6.8 2.3.4.7.9 1.2 1.5 1.5.6.4 1.3.5 2.2.5 1.6 0 2.8-.6 3.5-1.7.8-1.1 1.2-3 1.2-5.4 0-2.1-.4-3.9-1.1-5.2-.7-1.3-1.9-2-3.6-2-1.5 0-2.7.6-3.5 1.7-.9 1.1-1.3 2.9-1.3 5.5zm24.8-11.6v13.2c0 1.9.2 3.3.7 4.1.4.8 1.3 1.3 2.6 1.3 1.1 0 2.1-.3 2.9-1 .8-.7 1.3-1.5 1.7-2.5v-15h6v16.2c0 1.3.1 2.5.2 3.7.1 1.2.3 2.3.6 3.3h-4.6l-1.1-3.4h-.2c-.7 1.2-1.7 2.2-3 2.9-1.3.8-2.8 1.2-4.5 1.2-1.2 0-2.2-.2-3.2-.5-.9-.3-1.7-.8-2.3-1.5-.6-.7-1.1-1.7-1.4-2.9-.3-1.2-.5-2.8-.5-4.7V18.6h6.1zm31.4 5.6c-1-.3-1.8-.5-2.6-.5-1.1 0-2 .3-2.7.9-.7.6-1.2 1.3-1.5 2.2v15h-6V18.6h4.7l.7 3.1h.2c.5-1.1 1.2-2 2.1-2.7.9-.7 2-.9 3.2-.9.8 0 2.5.4 3.4.8l-1.5 5.3zm19.6 16.2c-.9.7-2.1 1.2-3.4 1.6-1.3.4-2.7.5-4.1.5-1.9 0-3.4-.3-4.7-.9-1.3-.6-2.3-1.4-3.1-2.5-.8-1.1-1.4-2.4-1.7-3.9-.4-1.5-.5-3.2-.5-5 0-3.9.9-7 2.7-9.1 1.8-2.1 4.3-3.2 7.7-3.2 1.7 0 3.1.1 4.1.4 1 .3 2 .6 2.8 1.1l-1.4 4.9c-.7-.3-1.4-.6-2.1-.8-.7-.2-1.5-.3-2.4-.3-1.7 0-2.9.6-3.8 1.7-.9 1.1-1.3 2.9-1.3 5.3 0 1 .1 1.9.3 2.7.2.8.5 1.6 1 2.2.4.6 1 1.1 1.7 1.5.7.4 1.5.5 2.4.5 1 0 1.9-.1 2.6-.4.7-.3 1.3-.6 1.9-1l1.3 4.7zm21.3-.6c-.9.7-2.2 1.4-3.8 1.9-1.6.5-3.3.8-5.1.8-3.8 0-6.5-1.1-8.2-3.3-1.7-2.2-2.6-5.2-2.6-9 0-4.1 1-7.2 2.9-9.2 1.9-2 4.7-3.1 8.2-3.1 1.2 0 2.3.2 3.4.5s2.1.8 3 1.5c.9.7 1.6 1.7 2.1 2.9s.8 2.7.8 4.5c0 .7 0 1.3-.1 2.1-.1.7-.2 1.5-.3 2.3h-14c.1 2 .6 3.4 1.5 4.4.9 1 2.4 1.5 4.4 1.5 1.3 0 2.4-.2 3.4-.6 1-.4 1.8-.8 2.3-1.2l2.1 4zm-8.7-17.1c-1.6 0-2.8.5-3.5 1.4-.8.9-1.2 2.2-1.4 3.8h8.6c.1-1.7-.1-3-.8-3.9-.5-.8-1.5-1.3-2.9-1.3zm32.9 19.1c0 3.4-.9 5.9-2.7 7.5-1.8 1.6-4.4 2.4-7.7 2.4-2.2 0-4-.2-5.3-.5-1.3-.3-2.3-.6-2.9-1l1.3-4.8c.7.3 1.5.6 2.5.8 1 .2 2.1.4 3.5.4 2.1 0 3.5-.5 4.3-1.4.8-.9 1.1-2.2 1.1-3.8V40h-.2c-1.1 1.5-3 2.2-5.8 2.2-3 0-5.2-.9-6.7-2.8s-2.2-4.8-2.2-8.7c0-4.2 1-7.3 3-9.4 2-2.1 4.9-3.2 8.6-3.2 2 0 3.8.1 5.3.4 1.5.3 2.8.6 3.8 1l.1 22.3zm-10.2-4.5c1.2 0 2.1-.3 2.7-.8.6-.5 1.1-1.3 1.5-2.4V23.7c-1-.4-2.2-.6-3.6-.6-1.6 0-2.8.6-3.6 1.7-.9 1.2-1.3 3-1.3 5.6 0 2.3.4 4 1.1 5.2.7 1.2 1.8 1.7 3.2 1.7zm27.7-13.1c-1-.3-1.8-.5-2.6-.5-1.1 0-2 .3-2.7.9-.7.6-1.2 1.3-1.5 2.2v15h-6V18.6h4.7l.7 3.1h.2c.5-1.1 1.2-2 2.1-2.7.9-.7 2-.9 3.2-.9.8 0 1.7.2 2.7.5l-.8 5.6zm2.9-4.5c1.2-.6 2.1-.8 3.8-1.1 1.7-.3 3.5-.5 5.3-.5 1.6 0 3 .2 4 .6 1 .4 1.9.9 2.6 1.7.6.7 1.1 1.6 1.3 2.6.3 1 .4 2.1.4 3.3 0 1.4 0 2.7-.1 4.1-.1 1.4-.1 2.7-.2 4.1 0 1.3 0 2.6.1 3.9.1 1.3.3 2.4.7 3.6H250l-1-3.2c-.6 1-1.5 1.8-2.6 2.5s-2.5 1-4.3 1c-1.1 0-2.1-.2-2.9-.5-.9-.3-1.6-.8-2.2-1.4-.6-.6-1.1-1.3-1.4-2.1-.3-.8-.5-1.7-.5-2.8 0-1.4.3-2.6 1-3.6s1.5-1.8 2.7-2.4c1.2-.6 2.6-1 4.3-1.3 1.7-.3 3.5-.3 5.6-.2.2-1.7.1-3-.4-3.7-.5-.8-1.5-1.1-3.1-1.1-1.2 0-2.5.1-3.8.4-1.3.3-1.9.4-2.7.8l-1.7-4.7zm7.1 17.5c1.2 0 2.2-.3 2.9-.8.7-.5 1.2-1.1 1.6-1.7v-3c-1-.1-1.9-.1-2.8 0-.9.1-1.7.2-2.3.4-.6.2-1.2.5-1.6.9-.4.4-.6.9-.6 1.5 0 .9.3 1.5.8 2 .4.5 1.1.7 2 .7zm15-18.6h4.4l.7 2.8h.2c.8-1.2 1.8-2 2.9-2.6 1.1-.6 2.4-.8 4-.8 2.9 0 5.1.9 6.6 2.8s2.2 4.8 2.2 8.9c0 2-.2 3.8-.7 5.4-.5 1.6-1.2 3-2.1 4.1-.9 1.1-2 2-3.3 2.6-1.3.6-2.8.9-4.5.9-1 0-1.8-.1-2.4-.2-.6-.1-1.2-.4-1.9-.7v9.5h-6V18.6h-.1zm10.3 4.4c-1.2 0-2.1.3-2.8.9-.7.6-1.2 1.5-1.6 2.7v9.7c.4.3.9.6 1.4.8.5.2 1.2.3 2 .3 1.7 0 3-.6 3.9-1.8.9-1.2 1.3-3.2 1.3-6.1 0-2-.3-3.6-1-4.7-.6-1.2-1.7-1.8-3.2-1.8zm28.2 18.8V28.6c0-1.9-.3-3.3-.8-4.1-.5-.8-1.5-1.3-2.9-1.3-1 0-2 .3-2.8 1-.9.7-1.4 1.6-1.7 2.7v14.8h-6V9.3h6v11.9h.2c.7-1 1.7-1.8 2.7-2.4 1.1-.6 2.5-.9 4.1-.9 1.2 0 2.2.2 3.1.5.9.3 1.7.8 2.3 1.5.6.7 1.1 1.7 1.3 2.9.2 1.2.4 2.7.4 4.5v14.5h-5.9z" fill="#fff"/></svg>
|
||||
|
Before Width: | Height: | Size: 4.8 KiB |
@ -1 +0,0 @@
|
||||
<svg viewBox="0 0 304 52" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M30.8 51.8c-2.8.5-5.5-1.3-6-4.1L17.2 6.2c-.5-2.8 1.3-5.5 4.1-6s5.5 1.3 6 4.1l7.6 41.5c.5 2.8-1.4 5.5-4.1 6z" fill="#FF5543"/><path d="M10.9 44.7C9.1 45 7.3 44.4 6 43c-1.8-2.2-1.6-5.4.6-7.2L38.7 8.5c2.2-1.8 5.4-1.6 7.2.6 1.8 2.2 1.6 5.4-.6 7.2l-32 27.3c-.7.6-1.6 1-2.4 1.1z" fill="#A112FF"/><path d="M46.8 38.1c-.9.2-1.8.1-2.6-.2L4.4 23.8c-2.7-1-4.1-3.9-3.1-6.6 1-2.7 3.9-4.1 6.6-3.1l39.7 14.1c2.7 1 4.1 3.9 3.1 6.6-.6 1.8-2.2 3-3.9 3.3z" fill="#00CBEC"/><path d="M80 33.1c0-1-.4-1.8-1.1-2.4-.7-.6-1.6-1.2-2.7-1.7s-2.3-1-3.6-1.6c-1.3-.5-2.5-1.2-3.6-2s-2-1.8-2.7-3c-.7-1.2-1.1-2.7-1.1-4.5 0-1.6.3-3 .8-4.1.5-1.2 1.3-2.1 2.3-2.9 1-.8 2.1-1.3 3.5-1.7 1.3-.4 2.8-.6 4.5-.6 1.9 0 3.7.2 5.3.5 1.6.3 3.1.8 4.1 1.4l-2 5.3c-.7-.4-1.7-.8-3.1-1.1-1.4-.4-2.8-.5-4.4-.5-1.5 0-2.6.3-3.4.9-.8.6-1.2 1.4-1.2 2.4 0 .9.4 1.7 1.1 2.3.7.6 1.6 1.2 2.7 1.7s2.3 1.1 3.6 1.6c1.3.6 2.5 1.2 3.6 2s2 1.8 2.7 2.9c.7 1.2 1.1 2.6 1.1 4.3 0 1.7-.3 3.2-.9 4.5-.6 1.3-1.4 2.3-2.4 3.1-1 .8-2.3 1.5-3.8 1.9-1.5.4-3.1.6-4.9.6-2.3 0-4.4-.2-6.1-.7-1.8-.4-3.1-.9-3.9-1.3l2-5.4c.3.2.8.4 1.3.6.5.2 1.2.4 1.8.6.7.2 1.4.3 2.2.5.8.1 1.5.2 2.3.2 1.9 0 3.3-.3 4.3-1 1.2-.6 1.7-1.5 1.7-2.8zm9.1-2.9c0-3.9 1-7 2.9-9.1 1.9-2.1 4.6-3.2 8.1-3.2 1.9 0 3.5.3 4.8.9 1.4.6 2.5 1.4 3.4 2.5.9 1.1 1.6 2.4 2 3.9.4 1.5.7 3.2.7 5 0 3.9-1 7-2.9 9.1-1.9 2.1-4.6 3.2-8.1 3.2-1.9 0-3.5-.3-4.8-.9-1.4-.6-2.5-1.4-3.4-2.5-.9-1.1-1.6-2.4-2-3.9-.5-1.5-.7-3.2-.7-5zm6.2 0c0 1 .1 2 .3 2.8.2.9.5 1.6.8 2.3.4.7.9 1.2 1.5 1.5.6.4 1.3.5 2.2.5 1.6 0 2.8-.6 3.5-1.7.8-1.1 1.2-3 1.2-5.4 0-2.1-.4-3.9-1.1-5.2-.7-1.3-1.9-2-3.6-2-1.5 0-2.7.6-3.5 1.7-.9 1.1-1.3 2.9-1.3 5.5zm24.8-11.6v13.2c0 1.9.2 3.3.7 4.1.4.8 1.3 1.3 2.6 1.3 1.1 0 2.1-.3 2.9-1 .8-.7 1.3-1.5 1.7-2.5v-15h6v16.2c0 1.3.1 2.5.2 3.7.1 1.2.3 2.3.6 3.3h-4.6l-1.1-3.4h-.2c-.7 1.2-1.7 2.2-3 2.9-1.3.8-2.8 1.2-4.5 1.2-1.2 0-2.2-.2-3.2-.5-.9-.3-1.7-.8-2.3-1.5-.6-.7-1.1-1.7-1.4-2.9-.3-1.2-.5-2.8-.5-4.7V18.6h6.1zm31.4 5.6c-1-.3-1.8-.5-2.6-.5-1.1 0-2 .3-2.7.9-.7.6-1.2 1.3-1.5 2.2v15h-6V18.6h4.7l.7 3.1h.2c.5-1.1 1.2-2 2.1-2.7.9-.7 2-.9 3.2-.9.8 0 2.5.4 3.4.8l-1.5 5.3zm19.6 16.2c-.9.7-2.1 1.2-3.4 1.6-1.3.4-2.7.5-4.1.5-1.9 0-3.4-.3-4.7-.9-1.3-.6-2.3-1.4-3.1-2.5-.8-1.1-1.4-2.4-1.7-3.9-.4-1.5-.5-3.2-.5-5 0-3.9.9-7 2.7-9.1 1.8-2.1 4.3-3.2 7.7-3.2 1.7 0 3.1.1 4.1.4 1 .3 2 .6 2.8 1.1l-1.4 4.9c-.7-.3-1.4-.6-2.1-.8-.7-.2-1.5-.3-2.4-.3-1.7 0-2.9.6-3.8 1.7-.9 1.1-1.3 2.9-1.3 5.3 0 1 .1 1.9.3 2.7.2.8.5 1.6 1 2.2.4.6 1 1.1 1.7 1.5.7.4 1.5.5 2.4.5 1 0 1.9-.1 2.6-.4.7-.3 1.3-.6 1.9-1l1.3 4.7zm21.3-.6c-.9.7-2.2 1.4-3.8 1.9-1.6.5-3.3.8-5.1.8-3.8 0-6.5-1.1-8.2-3.3-1.7-2.2-2.6-5.2-2.6-9 0-4.1 1-7.2 2.9-9.2 1.9-2 4.7-3.1 8.2-3.1 1.2 0 2.3.2 3.4.5s2.1.8 3 1.5c.9.7 1.6 1.7 2.1 2.9s.8 2.7.8 4.5c0 .7 0 1.3-.1 2.1-.1.7-.2 1.5-.3 2.3h-14c.1 2 .6 3.4 1.5 4.4.9 1 2.4 1.5 4.4 1.5 1.3 0 2.4-.2 3.4-.6 1-.4 1.8-.8 2.3-1.2l2.1 4zm-8.7-17.1c-1.6 0-2.8.5-3.5 1.4-.8.9-1.2 2.2-1.4 3.8h8.6c.1-1.7-.1-3-.8-3.9-.5-.8-1.5-1.3-2.9-1.3zm32.9 19.1c0 3.4-.9 5.9-2.7 7.5-1.8 1.6-4.4 2.4-7.7 2.4-2.2 0-4-.2-5.3-.5-1.3-.3-2.3-.6-2.9-1l1.3-4.8c.7.3 1.5.6 2.5.8 1 .2 2.1.4 3.5.4 2.1 0 3.5-.5 4.3-1.4.8-.9 1.1-2.2 1.1-3.8V40h-.2c-1.1 1.5-3 2.2-5.8 2.2-3 0-5.2-.9-6.7-2.8s-2.2-4.8-2.2-8.7c0-4.2 1-7.3 3-9.4 2-2.1 4.9-3.2 8.6-3.2 2 0 3.8.1 5.3.4 1.5.3 2.8.6 3.8 1v22.3h.1zm-10.2-4.5c1.2 0 2.1-.3 2.7-.8.6-.5 1.1-1.3 1.5-2.4V23.7c-1-.4-2.2-.6-3.6-.6-1.6 0-2.8.6-3.6 1.7-.9 1.2-1.3 3-1.3 5.6 0 2.3.4 4 1.1 5.2.7 1.2 1.8 1.7 3.2 1.7zm27.7-13.1c-1-.3-1.8-.5-2.6-.5-1.1 0-2 .3-2.7.9-.7.6-1.2 1.3-1.5 2.2v15h-6V18.6h4.7l.7 3.1h.2c.5-1.1 1.2-2 2.1-2.7.9-.7 2-.9 3.2-.9.8 0 1.7.2 2.7.5l-.8 5.6zm2.9-4.5c1.2-.6 2.1-.8 3.8-1.1 1.7-.3 3.5-.5 5.3-.5 1.6 0 3 .2 4 .6 1 .4 1.9.9 2.6 1.7.6.7 1.1 1.6 1.3 2.6.3 1 .4 2.1.4 3.3 0 1.4 0 2.7-.1 4.1-.1 1.4-.1 2.7-.2 4.1 0 1.3 0 2.6.1 3.9.1 1.3.3 2.4.7 3.6H250l-1-3.2c-.6 1-1.5 1.8-2.6 2.5s-2.5 1-4.3 1c-1.1 0-2.1-.2-2.9-.5-.9-.3-1.6-.8-2.2-1.4-.6-.6-1.1-1.3-1.4-2.1-.3-.8-.5-1.7-.5-2.8 0-1.4.3-2.6 1-3.6s1.5-1.8 2.7-2.4c1.2-.6 2.6-1 4.3-1.3 1.7-.3 3.5-.3 5.6-.2.2-1.7.1-3-.4-3.7-.5-.8-1.5-1.1-3.1-1.1-1.2 0-2.5.1-3.8.4-1.3.3-1.9.4-2.7.8l-1.7-4.7zm7.1 17.5c1.2 0 2.2-.3 2.9-.8.7-.5 1.2-1.1 1.6-1.7v-3c-1-.1-1.9-.1-2.8 0-.9.1-1.7.2-2.3.4-.6.2-1.2.5-1.6.9-.4.4-.6.9-.6 1.5 0 .9.3 1.5.8 2 .4.5 1.1.7 2 .7zm15-18.6h4.4l.7 2.8h.2c.8-1.2 1.8-2 2.9-2.6 1.1-.6 2.4-.8 4-.8 2.9 0 5.1.9 6.6 2.8s2.2 4.8 2.2 8.9c0 2-.2 3.8-.7 5.4-.5 1.6-1.2 3-2.1 4.1-.9 1.1-2 2-3.3 2.6-1.3.6-2.8.9-4.5.9-1 0-1.8-.1-2.4-.2-.6-.1-1.2-.4-1.9-.7v9.5h-6V18.6h-.1zm10.3 4.4c-1.2 0-2.1.3-2.8.9-.7.6-1.2 1.5-1.6 2.7v9.7c.4.3.9.6 1.4.8.5.2 1.2.3 2 .3 1.7 0 3-.6 3.9-1.8.9-1.2 1.3-3.2 1.3-6.1 0-2-.3-3.6-1-4.7-.6-1.2-1.7-1.8-3.2-1.8zm28.2 18.8V28.6c0-1.9-.3-3.3-.8-4.1-.5-.8-1.5-1.3-2.9-1.3-1 0-2 .3-2.8 1-.9.7-1.4 1.6-1.7 2.7v14.8h-6V9.3h6v11.9h.2c.7-1 1.7-1.8 2.7-2.4 1.1-.6 2.5-.9 4.1-.9 1.2 0 2.2.2 3.1.5.9.3 1.7.8 2.3 1.5.6.7 1.1 1.7 1.3 2.9.2 1.2.4 2.7.4 4.5v14.5h-5.9z" fill="#000"/></svg>
|
||||
|
Before Width: | Height: | Size: 4.8 KiB |
@ -1,291 +0,0 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@sourcegraph/vscode",
|
||||
"displayName": "Search by Sourcegraph",
|
||||
"version": "2.2.15",
|
||||
"description": "Search all of your repositories across all branches and all code hosts",
|
||||
"publisher": "sourcegraph",
|
||||
"sideEffects": true,
|
||||
"license": "Apache-2.0",
|
||||
"icon": "images/logo.png",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sourcegraph/sourcegraph.git",
|
||||
"directory": "client/vscode"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/sourcegraph/sourcegraph/issues/new?labels=team/integrations,vscode-extension&title=VSCode+Bug+report:+&projects=Integrations%20Project%20Board"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.63.2"
|
||||
},
|
||||
"categories": [
|
||||
"Other"
|
||||
],
|
||||
"activationEvents": [
|
||||
"onStartupFinished"
|
||||
],
|
||||
"main": "./dist/node/extension.js",
|
||||
"browser": "./dist/webworker/extension.js",
|
||||
"contributes": {
|
||||
"commands": [
|
||||
{
|
||||
"command": "sourcegraph.search",
|
||||
"category": "Sourcegraph",
|
||||
"title": "Search with Sourcegraph",
|
||||
"icon": {
|
||||
"light": "images/logo.svg",
|
||||
"dark": "images/logo.svg"
|
||||
}
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.openInBrowser",
|
||||
"category": "Sourcegraph",
|
||||
"title": "Open File in Sourcegraph Web",
|
||||
"icon": {
|
||||
"light": "images/logomark_dark.svg",
|
||||
"dark": "images/logomark_light.svg"
|
||||
}
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.copyFileLink",
|
||||
"category": "Sourcegraph",
|
||||
"title": "Copy Sourcegraph File Link"
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.selectionSearchWeb",
|
||||
"category": "Sourcegraph",
|
||||
"title": "Search Selection in Sourcegraph Web"
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.removeRepoTree",
|
||||
"category": "Sourcegraph",
|
||||
"title": "Remove Repository from Sourcegraph File System",
|
||||
"icon": "$(trash)"
|
||||
}
|
||||
],
|
||||
"authentication": [
|
||||
{
|
||||
"id": "sourcegraphauth",
|
||||
"label": "Sourcegraph Auth"
|
||||
}
|
||||
],
|
||||
"viewsContainers": {
|
||||
"activitybar": [
|
||||
{
|
||||
"id": "sourcegraph-view",
|
||||
"title": "Sourcegraph Search",
|
||||
"icon": "images/logomark_dark.svg"
|
||||
}
|
||||
]
|
||||
},
|
||||
"views": {
|
||||
"sourcegraph-view": [
|
||||
{
|
||||
"type": "webview",
|
||||
"id": "sourcegraph.searchSidebar",
|
||||
"name": "Sourcegraph Search",
|
||||
"visibility": "visible"
|
||||
},
|
||||
{
|
||||
"id": "sourcegraph.files",
|
||||
"name": "Files",
|
||||
"visibility": "visible"
|
||||
},
|
||||
{
|
||||
"type": "webview",
|
||||
"id": "sourcegraph.helpSidebar",
|
||||
"name": "Help and feedback",
|
||||
"visibility": "collapsed"
|
||||
}
|
||||
]
|
||||
},
|
||||
"viewsWelcome": [
|
||||
{
|
||||
"view": "sourcegraph.files",
|
||||
"contents": "No open files."
|
||||
}
|
||||
],
|
||||
"configuration": {
|
||||
"type": "object",
|
||||
"title": "Sourcegraph extension configuration",
|
||||
"properties": {
|
||||
"sourcegraph.url": {
|
||||
"type": [
|
||||
"string"
|
||||
],
|
||||
"default": "https://sourcegraph.com",
|
||||
"description": "The base URL of the Sourcegraph instance to use."
|
||||
},
|
||||
"sourcegraph.accessToken": {
|
||||
"type": [
|
||||
null
|
||||
],
|
||||
"description": "[Depreciated after v2.2.12] The access token to query the Sourcegraph API. Create a new access token at ${SOURCEGRAPH_URL}/users/<sourcegraph-username>/settings/tokens. Unless you are using a private instance of Sourcegraph, then ${SOURCEGRAPH_URL} is https://sourcegraph.com."
|
||||
},
|
||||
"sourcegraph.remoteUrlReplacements": {
|
||||
"type": [
|
||||
"object"
|
||||
],
|
||||
"default": {},
|
||||
"examples": [
|
||||
{
|
||||
"github": "gitlab",
|
||||
"master": "main"
|
||||
}
|
||||
],
|
||||
"description": "For each item in this object, replace key with value in the remote url."
|
||||
},
|
||||
"sourcegraph.defaultBranch": {
|
||||
"type": [
|
||||
"string"
|
||||
],
|
||||
"default": "",
|
||||
"description": "Always open local files on Sourcegraph Web at this default branch."
|
||||
},
|
||||
"sourcegraph.requestHeaders": {
|
||||
"type": [
|
||||
"object"
|
||||
],
|
||||
"default": {},
|
||||
"examples": [
|
||||
{
|
||||
"Cache-Control": "no-cache",
|
||||
"Proxy-Authenticate": "Basic"
|
||||
}
|
||||
],
|
||||
"description": "Each value pair will be added to the request headers made to your instance."
|
||||
},
|
||||
"sourcegraph.basePath": {
|
||||
"description": "The file path on the machine to the folder that is expected to contain all repositories.",
|
||||
"type": "string",
|
||||
"default": null,
|
||||
"examples": [
|
||||
"/Users/USERNAME/Documents/"
|
||||
]
|
||||
},
|
||||
"sourcegraph.proxyProtocol": {
|
||||
"description": "The protocol to use when proxying requests to the Sourcegraph instance.",
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"examples": [
|
||||
"http",
|
||||
"https"
|
||||
]
|
||||
},
|
||||
"sourcegraph.proxyHost": {
|
||||
"description": "The host to use when proxying requests to the Sourcegraph instance. It shouldn't include a protocol (like \"http://\") or a port (like \":7080\"). When this is set, port must be set as well.",
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"examples": [
|
||||
"localhost",
|
||||
"1.2.3.4"
|
||||
]
|
||||
},
|
||||
"sourcegraph.proxyPort": {
|
||||
"description": "The port to use when proxying requests to the Sourcegraph instance. When this is set, host must be set as well.",
|
||||
"type": "number",
|
||||
"default": 0,
|
||||
"examples": [
|
||||
80,
|
||||
443,
|
||||
7080,
|
||||
9090
|
||||
]
|
||||
},
|
||||
"sourcegraph.proxyPath": {
|
||||
"description": "The full path to a file when proxying requests to the Sourcegraph instance via a UNIX domain socket.",
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"examples": [
|
||||
"/home/user/path/unix.socket"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"keybindings": [
|
||||
{
|
||||
"command": "sourcegraph.search",
|
||||
"key": "ctrl+shift+8",
|
||||
"mac": "cmd+shift+8"
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.openInBrowser",
|
||||
"key": "alt+a",
|
||||
"mac": "option+a"
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.selectionSearchWeb",
|
||||
"key": "alt+s",
|
||||
"mac": "option+s"
|
||||
}
|
||||
],
|
||||
"menus": {
|
||||
"editor/context": [
|
||||
{
|
||||
"command": "sourcegraph.openInBrowser",
|
||||
"group": "sourcegraph",
|
||||
"label": "sourcegraph"
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.copyFileLink",
|
||||
"group": "sourcegraph",
|
||||
"label": "sourcegraph"
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.selectionSearchWeb",
|
||||
"group": "sourcegraph",
|
||||
"when": "editorHasSelection"
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.search",
|
||||
"group": "sourcegraph"
|
||||
}
|
||||
],
|
||||
"view/title": [
|
||||
{
|
||||
"command": "sourcegraph.removeRepoTree",
|
||||
"when": "view == sourcegraph.files && sourcegraph.removeRepository",
|
||||
"group": "navigation"
|
||||
}
|
||||
],
|
||||
"editor/title": [
|
||||
{
|
||||
"command": "sourcegraph.openInBrowser",
|
||||
"when": "resourceScheme == sourcegraph && editorReadonly",
|
||||
"group": "navigation"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"lint:js": "eslint --cache '**/*.[jt]s?(x)'",
|
||||
"package": "ts-node ./scripts/package.ts",
|
||||
"prebuild": "pnpm -w run generate && pnpm build-inline-extensions",
|
||||
"build-inline-extensions": "node scripts/build-inline-extensions",
|
||||
"build": "pnpm run prebuild && NODE_ENV=development ts-node-transpile-only scripts/build.ts",
|
||||
"build:test": "IS_TEST=1 pnpm run build",
|
||||
"watch": "WATCH=1 pnpm run build",
|
||||
"watch:test": "IS_TEST=1 pnpm run watch",
|
||||
"test-integration": "TS_NODE_PROJECT=tests/tsconfig.json mocha --parallel=${CI:-\"false\"} --retries=2 ./tests/**/*.test.ts",
|
||||
"release": "ts-node ./scripts/publish.ts",
|
||||
"release:major": "VSCE_RELEASE_TYPE=major ts-node ./scripts/release.ts",
|
||||
"release:minor": "VSCE_RELEASE_TYPE=minor ts-node ./scripts/release.ts",
|
||||
"release:patch": "VSCE_RELEASE_TYPE=patch ts-node ./scripts/release.ts",
|
||||
"release:pre": "VSCE_RELEASE_TYPE=prerelease ts-node ./scripts/release.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vsce": "^2.7.0",
|
||||
"@sourcegraph/build-config": "workspace:*",
|
||||
"@sourcegraph/extension-api-types": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sourcegraph/branded": "workspace:*",
|
||||
"@sourcegraph/client-api": "workspace:*",
|
||||
"@sourcegraph/codeintellify": "workspace:*",
|
||||
"@sourcegraph/common": "workspace:*",
|
||||
"@sourcegraph/http-client": "workspace:*",
|
||||
"@sourcegraph/shared": "workspace:*",
|
||||
"@sourcegraph/wildcard": "workspace:*"
|
||||
}
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
// This file is used for esbuild's `inject` option
|
||||
// in order to load node polyfills in the webworker
|
||||
// extension host.
|
||||
// See: https://esbuild.github.io/api/#inject.
|
||||
export const Buffer = require('buffer/').Buffer
|
||||
@ -1,7 +0,0 @@
|
||||
const path = require('path')
|
||||
|
||||
const { buildCodeIntelExtensions } = require('../../shared/dev/buildCodeIntelExtensions')
|
||||
|
||||
const pathToExtensionBundles = path.join(process.cwd(), 'dist', 'extensions')
|
||||
|
||||
buildCodeIntelExtensions({ pathToExtensionBundles, revision: 'v3.41.1' })
|
||||
@ -1,156 +0,0 @@
|
||||
import { existsSync } from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
import * as esbuild from 'esbuild'
|
||||
import { rm } from 'shelljs'
|
||||
|
||||
import {
|
||||
packageResolutionPlugin,
|
||||
stylePlugin,
|
||||
workerPlugin,
|
||||
RXJS_RESOLUTIONS,
|
||||
buildTimerPlugin,
|
||||
} from '@sourcegraph/build-config/src/esbuild/plugins'
|
||||
|
||||
const minify = process.env.NODE_ENV === 'production'
|
||||
const outdir = path.join(__dirname, '../dist')
|
||||
const isTest = !!process.env.IS_TEST
|
||||
|
||||
const TARGET_TYPE = process.env.TARGET_TYPE
|
||||
|
||||
const SHARED_CONFIG = {
|
||||
outdir,
|
||||
minify,
|
||||
sourcemap: true,
|
||||
}
|
||||
|
||||
export async function build(): Promise<void> {
|
||||
if (existsSync(outdir)) {
|
||||
rm('-rf', outdir)
|
||||
}
|
||||
|
||||
const buildPromises: Promise<esbuild.BuildContext>[] = []
|
||||
|
||||
if (TARGET_TYPE === 'node' || !TARGET_TYPE) {
|
||||
buildPromises.push(
|
||||
esbuild.context({
|
||||
entryPoints: { extension: path.join(__dirname, '/../src/extension.ts') },
|
||||
bundle: true,
|
||||
format: 'cjs',
|
||||
platform: 'node',
|
||||
external: ['vscode'],
|
||||
banner: { js: 'global.Buffer = require("buffer").Buffer' },
|
||||
define: {
|
||||
'process.env.IS_TEST': isTest ? 'true' : 'false',
|
||||
},
|
||||
...SHARED_CONFIG,
|
||||
outdir: path.join(SHARED_CONFIG.outdir, 'node'),
|
||||
mainFields: ['module', 'main'], // for node-jsonc-parser; see https://github.com/microsoft/node-jsonc-parser/issues/57#issuecomment-1634726605
|
||||
})
|
||||
)
|
||||
}
|
||||
if (TARGET_TYPE === 'webworker' || !TARGET_TYPE) {
|
||||
buildPromises.push(
|
||||
esbuild.context({
|
||||
entryPoints: { extension: path.join(__dirname, '/../src/extension.ts') },
|
||||
bundle: true,
|
||||
format: 'cjs',
|
||||
platform: 'browser',
|
||||
external: ['vscode'],
|
||||
define: {
|
||||
'process.env.IS_TEST': isTest ? 'true' : 'false',
|
||||
global: 'globalThis',
|
||||
},
|
||||
inject: ['./scripts/process-shim.js', './scripts/buffer-shim.js'],
|
||||
plugins: [
|
||||
packageResolutionPlugin({
|
||||
process: require.resolve('process/browser'),
|
||||
path: require.resolve('path-browserify'),
|
||||
http: require.resolve('stream-http'),
|
||||
https: require.resolve('https-browserify'),
|
||||
stream: require.resolve('stream-browserify'),
|
||||
util: require.resolve('util'),
|
||||
events: require.resolve('events'),
|
||||
buffer: require.resolve('buffer/'),
|
||||
'./browserActionsNode': path.resolve(__dirname, '../src', 'commands', 'browserActionsWeb'),
|
||||
'http-proxy-agent': path.resolve(
|
||||
__dirname,
|
||||
'../src',
|
||||
'backend',
|
||||
'proxy-agent-fake-for-browser.ts'
|
||||
),
|
||||
'https-proxy-agent': path.resolve(
|
||||
__dirname,
|
||||
'../src',
|
||||
'backend',
|
||||
'proxy-agent-fake-for-browser.ts'
|
||||
),
|
||||
'node-fetch': path.resolve(__dirname, '../src', 'backend', 'node-fetch-fake-for-browser.ts'),
|
||||
}),
|
||||
],
|
||||
...SHARED_CONFIG,
|
||||
outdir: path.join(SHARED_CONFIG.outdir, 'webworker'),
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
buildPromises.push(
|
||||
esbuild.context({
|
||||
entryPoints: {
|
||||
helpSidebar: path.join(__dirname, '../src/webview/sidebars/help'),
|
||||
searchSidebar: path.join(__dirname, '../src/webview/sidebars/search'),
|
||||
searchPanel: path.join(__dirname, '../src/webview/search-panel'),
|
||||
style: path.join(__dirname, '../src/webview/index.scss'),
|
||||
},
|
||||
bundle: true,
|
||||
format: 'esm',
|
||||
platform: 'browser',
|
||||
splitting: true,
|
||||
plugins: [
|
||||
stylePlugin,
|
||||
workerPlugin,
|
||||
packageResolutionPlugin({
|
||||
path: require.resolve('path-browserify'),
|
||||
process: require.resolve('process/browser'),
|
||||
http: require.resolve('stream-http'), // for stream search - event source polyfills
|
||||
https: require.resolve('https-browserify'), // for stream search - event source polyfills
|
||||
...RXJS_RESOLUTIONS,
|
||||
'./RepoSearchResult': require.resolve('../src/webview/search-panel/alias/RepoSearchResult'),
|
||||
'./CommitSearchResult': require.resolve('../src/webview/search-panel/alias/CommitSearchResult'),
|
||||
'./SymbolSearchResult': require.resolve('../src/webview/search-panel/alias/SymbolSearchResult'),
|
||||
'./FileMatchChildren': require.resolve('../src/webview/search-panel/alias/FileMatchChildren'),
|
||||
'./RepoFileLink': require.resolve('../src/webview/search-panel/alias/RepoFileLink'),
|
||||
'../documentation/ModalVideo': require.resolve('../src/webview/search-panel/alias/ModalVideo'),
|
||||
}),
|
||||
buildTimerPlugin,
|
||||
],
|
||||
loader: {
|
||||
'.ttf': 'file',
|
||||
},
|
||||
define: {
|
||||
'process.env.INTEGRATION_TESTS': isTest ? 'true' : 'false',
|
||||
},
|
||||
assetNames: '[name]',
|
||||
...SHARED_CONFIG,
|
||||
outdir: path.join(SHARED_CONFIG.outdir, 'webview'),
|
||||
})
|
||||
)
|
||||
|
||||
const ctxs = await Promise.all(buildPromises)
|
||||
|
||||
await Promise.all(ctxs.map(ctx => ctx.rebuild()))
|
||||
|
||||
if (process.env.WATCH) {
|
||||
await Promise.all(ctxs.map(ctx => ctx.watch()))
|
||||
await new Promise(() => {}) // wait forever
|
||||
}
|
||||
|
||||
await Promise.all(ctxs.map(ctx => ctx.dispose()))
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
build().catch(error => {
|
||||
console.error('Error:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
@ -1,17 +0,0 @@
|
||||
import childProcess from 'child_process'
|
||||
import fs from 'fs'
|
||||
|
||||
const originalPackageJson = fs.readFileSync('package.json').toString()
|
||||
|
||||
try {
|
||||
childProcess.execSync('pnpm build-inline-extensions && pnpm build', { stdio: 'inherit' })
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const packageJson: any = JSON.parse(originalPackageJson)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
packageJson.name = 'sourcegraph'
|
||||
fs.writeFileSync('package.json', JSON.stringify(packageJson))
|
||||
|
||||
childProcess.execSync('vsce package --no-dependencies --allow-star-activation -o dist', { stdio: 'inherit' })
|
||||
} finally {
|
||||
fs.writeFileSync('package.json', originalPackageJson)
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
// This file is used for esbuild's `inject` option
|
||||
// in order to load node polyfills in the webworker
|
||||
// extension host.
|
||||
// See: https://esbuild.github.io/api/#inject.
|
||||
export const process = require('process/browser')
|
||||
@ -1,79 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
|
||||
import childProcess from 'child_process'
|
||||
import fs from 'fs'
|
||||
|
||||
import * as semver from 'semver'
|
||||
|
||||
import { version } from '../package.json'
|
||||
|
||||
/**
|
||||
* This script is used by the CI to publish the extension to the VS Code Marketplace
|
||||
* It is triggered when a commit has been made to the vsce release branch
|
||||
* Refer to our CONTRIBUTION docs to learn more about our release process
|
||||
*/
|
||||
// Get current package.json
|
||||
const originalPackageJson = fs.readFileSync('package.json').toString()
|
||||
/**
|
||||
* Build and publish the extension with the updated package name
|
||||
* using the tokens stored in the pipeline to run commands in pnpm
|
||||
* and allows all events to activate the extension
|
||||
*/
|
||||
const isPreRelease = semver.minor(version) % 2 !== 0 ? '--pre-release' : ''
|
||||
// Tokens are stored in CI pipeline
|
||||
const tokens = {
|
||||
vscode: process.env.VSCODE_MARKETPLACE_TOKEN,
|
||||
openvsx: process.env.VSCODE_OPENVSX_TOKEN,
|
||||
}
|
||||
// Assume this is for testing purpose if tokens are not found
|
||||
const hasTokens = tokens.vscode !== undefined && tokens.openvsx !== undefined
|
||||
const commands = {
|
||||
vscode_info: 'vsce show sourcegraph.sourcegraph --json',
|
||||
// To publish to VS Code Marketplace
|
||||
vscode_publish: `vsce publish ${isPreRelease} --pat $VSCODE_MARKETPLACE_TOKEN --no-dependencies --allow-star-activation`,
|
||||
// To package the extension without publishing
|
||||
vscode_package: `vsce package ${isPreRelease} --no-dependencies --allow-star-activation`,
|
||||
// To publish to the open-vsx registry
|
||||
openvsx_publish: 'npx --yes ovsx publish --no-dependencies -p $VSCODE_OPENVSX_TOKEN',
|
||||
}
|
||||
// Publish the extension with the correct extension name "sourcegraph"
|
||||
try {
|
||||
childProcess.execSync('pnpm build-inline-extensions && pnpm build', { stdio: 'inherit' })
|
||||
// Get the latest release version nubmer of the last release from VS Code Marketplace using the vsce cli tool
|
||||
const response = childProcess.execSync(commands.vscode_info).toString()
|
||||
/*
|
||||
`vscode_info` command output is extension info prepended by command name and arguments, e.g.
|
||||
$ /Users/taras/projects/sourcegraph/node_modules/.bin/vsce show sourcegraph.sourcegraph --json
|
||||
{
|
||||
...json
|
||||
}
|
||||
We cut everything before the json object so that we can parse it as json.
|
||||
*/
|
||||
const trimmedResponse = response.slice(Math.max(0, response.indexOf('{')))
|
||||
const latestVersion: string = JSON.parse(trimmedResponse).versions[0].version
|
||||
if (hasTokens && (version === latestVersion || !semver.valid(latestVersion) || !semver.valid(version))) {
|
||||
throw new Error(
|
||||
version === latestVersion
|
||||
? 'Cannot release extension with the same version number.'
|
||||
: `invalid version number: ${latestVersion} & ${version}`
|
||||
)
|
||||
}
|
||||
// Update package name from @sourcegraph/vscode to sourcegraph in package.json
|
||||
const packageJson = originalPackageJson.replace('@sourcegraph/vscode', 'sourcegraph')
|
||||
fs.writeFileSync('package.json', packageJson)
|
||||
if (hasTokens) {
|
||||
// Run the publish commands
|
||||
childProcess.execSync(commands.vscode_publish, { stdio: 'inherit' })
|
||||
childProcess.execSync(commands.openvsx_publish, { stdio: 'inherit' })
|
||||
} else {
|
||||
// Use vsce package command instead without publishing the extension for testing
|
||||
childProcess.execSync(commands.vscode_package, { stdio: 'inherit' })
|
||||
}
|
||||
console.log(`The extension has been ${hasTokens ? 'published' : 'packaged'} successfully.`)
|
||||
} catch (error) {
|
||||
console.error('Failed to publish VSCE:', error)
|
||||
console.error('You may not run this script locally to publish the extension.')
|
||||
} finally {
|
||||
// Revert changes made to package.json
|
||||
fs.writeFileSync('package.json', originalPackageJson)
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-non-null-assertion */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
|
||||
import childProcess from 'child_process'
|
||||
import fs from 'fs'
|
||||
|
||||
import * as semver from 'semver'
|
||||
|
||||
import { version } from '../package.json'
|
||||
|
||||
/**
|
||||
* This script updates the version number and changelog for release purpose
|
||||
*/
|
||||
// Get the current package.json and changelog files
|
||||
const originalPackageJson = fs.readFileSync('package.json').toString()
|
||||
const originalChangelogFile = fs.readFileSync('CHANGELOG.md').toString()
|
||||
// Only proceed the release steps if a valid release type is provided
|
||||
const vsceReleaseType = String(process.env.VSCE_RELEASE_TYPE).toLowerCase() as semver.ReleaseType
|
||||
const isValidType = ['major', 'minor', 'patch', 'prerelease'].includes(vsceReleaseType)
|
||||
if (isValidType) {
|
||||
/**
|
||||
* Generate the next version number for release purpose
|
||||
* prerelease is treated as minor update because the prerelease
|
||||
* tag in semver is not supported by VS Code
|
||||
* ref: https://code.visualstudio.com/api/working-with-extensions/publishing-extension#prerelease-extensions
|
||||
*/
|
||||
const releaseType: semver.ReleaseType = vsceReleaseType === 'prerelease' ? 'minor' : vsceReleaseType
|
||||
// Get the latest release version nubmer of the last release from VS Code Marketplace using the vsce cli tool
|
||||
// We use this to compare the current package version number with the current release version number - they should be the same
|
||||
const response = childProcess.execSync('vsce show sourcegraph.sourcegraph --json').toString()
|
||||
const latestVersion: string = JSON.parse(response).versions[0].version
|
||||
if (!semver.valid(latestVersion)) {
|
||||
throw new Error(
|
||||
'Failed to connect to VSCE to retreive the latest extension version number. Make sure you have vsce cli tool installed.'
|
||||
)
|
||||
}
|
||||
if (version !== latestVersion) {
|
||||
throw new Error('The current version number is not align with the version number of the latest release.')
|
||||
}
|
||||
// Increase minor version number by twice for minor release because ODD minor number is for pre-release
|
||||
const nextVersion =
|
||||
vsceReleaseType === 'minor'
|
||||
? semver.inc(semver.inc(latestVersion, releaseType)!, releaseType)!
|
||||
: semver.inc(latestVersion, releaseType)!
|
||||
// commit message for the release, eg. vsce: minor release v1.0.1
|
||||
if (nextVersion && nextVersion !== latestVersion) {
|
||||
try {
|
||||
// Update version number in package.json
|
||||
const packageJson = originalPackageJson.replace(`"version": "${version}"`, `"version": "${nextVersion}"`)
|
||||
fs.writeFileSync('package.json', packageJson)
|
||||
// Update Changelog with the new version number
|
||||
const changelogFile = originalChangelogFile.replace(
|
||||
'Unreleased',
|
||||
`Unreleased\n\n### Changes\n\n### Fixes\n\n## ${nextVersion}`
|
||||
)
|
||||
fs.writeFileSync('CHANGELOG.md', changelogFile)
|
||||
// Commit and push
|
||||
const releaseCommitMessage = `vsce: ${releaseType} release v${nextVersion}`
|
||||
childProcess.execSync(`git add . && git commit -m "${releaseCommitMessage}" && git push -u origin HEAD`, {
|
||||
stdio: 'inherit',
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(`Publish VSCE with ${releaseType} failed:`, error)
|
||||
// Make sure any changes made are reverted if an error has occured
|
||||
fs.writeFileSync('package.json', originalPackageJson)
|
||||
fs.writeFileSync('CHANGELOG.md', originalChangelogFile)
|
||||
}
|
||||
} else {
|
||||
throw new Error('Version number is invalid.')
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Release type is invalid: ${vsceReleaseType}`)
|
||||
}
|
||||
@ -1,44 +0,0 @@
|
||||
# Extension Source Code
|
||||
|
||||
This folder contains the source code for the extension.
|
||||
|
||||
## Contexts
|
||||
|
||||
As detailed in our CONTRIBUTING.md file, this extension runs code in the following execution contexts:
|
||||
|
||||
1. Core App
|
||||
|
||||
- The main app where all the commands, webviews, file system, and all other components are put together and registered as a single extension
|
||||
- Runs code with Node.js on Desktop clients (for example, VS Code on Desktop) as a regular extension, or Web Worker on Web clients (for example, github.dev on browser) as a web extension
|
||||
- [Web extensions](https://code.visualstudio.com/api/extension-guides/web-extensions) run in the web extension host in a Browser [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker) environment, and do not have access to Node.js globals and libraries at runtime
|
||||
|
||||
2. Sidebars
|
||||
|
||||
- This is the UI for all the sidebars used in the core app
|
||||
- Uses the [VS Code Webview API](https://code.visualstudio.com/api/extension-guides/webview) to render the webview views in search sidebar, search history sidebar, auth sidebar, and help and feedback sidebar
|
||||
|
||||
3. Search Panel
|
||||
|
||||
- This is the UI for the extension search homepage and to display search results
|
||||
- Uses the [VS Code Webview API](https://code.visualstudio.com/api/extension-guides/webview) to render the webview panel for the Sourcegraph search homepage as a distinct editor tab
|
||||
|
||||
4. Extension Host
|
||||
|
||||
- It processes the code-intel data
|
||||
- Bring Sourcegraph code-intel to IDEs via the [VS Code langauges API](https://code.visualstudio.com/api/language-extensions/programmatic-language-features)
|
||||
- Runs in [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)
|
||||
|
||||
5. Custom File System
|
||||
|
||||
- This is a custom file system implemented to display file structure of selected repositories from a search result
|
||||
- Displays file-tree for the selected repositories when opening a [virtual document](https://code.visualstudio.com/api/extension-guides/virtual-documents) using the following VS Code APIs:
|
||||
- [File System](https://code.visualstudio.com/api/references/vscode-api#FileSystemProvider)
|
||||
- [Tree View](https://code.visualstudio.com/api/extension-guides/tree-view)
|
||||
- [Virtual Document](https://code.visualstudio.com/api/extension-guides/virtual-documents)
|
||||
- A virtual document is a document file located remotely on cloud and not on the local disk
|
||||
- [Virtual Workspaces](https://code.visualstudio.com/api/extension-guides/virtual-workspaces)
|
||||
- [Text Document Content Provider](https://code.visualstudio.com/api/extension-guides/virtual-documents#textdocumentcontentprovider)
|
||||
|
||||
## List of Files and Folders
|
||||
|
||||
See the File Structure section in our CONTRIBUTING.md file to learn more about the folders and files in this directory.
|
||||
@ -1,76 +0,0 @@
|
||||
import { type Observable, ReplaySubject } from 'rxjs'
|
||||
import type * as vscode from 'vscode'
|
||||
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
import type { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import type { CurrentAuthStateResult, CurrentAuthStateVariables } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { scretTokenKey } from '../webview/platform/AuthProvider'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
// Minimal auth state for the VS Code extension.
|
||||
// Uses only old fields for backwards compatibility with old GraphQL API versions.
|
||||
const currentAuthStateQuery = gql`
|
||||
query CurrentAuthState {
|
||||
currentUser {
|
||||
__typename
|
||||
id
|
||||
databaseID
|
||||
username
|
||||
avatarURL
|
||||
email
|
||||
displayName
|
||||
siteAdmin
|
||||
url
|
||||
settingsURL
|
||||
organizations {
|
||||
nodes {
|
||||
id
|
||||
name
|
||||
displayName
|
||||
url
|
||||
settingsURL
|
||||
}
|
||||
}
|
||||
session {
|
||||
canSignOut
|
||||
}
|
||||
viewerCanAdminister
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
// Update authenticatedUser on accessToken changes
|
||||
export function observeAuthenticatedUser(secretStorage: vscode.SecretStorage): Observable<AuthenticatedUser | null> {
|
||||
const authenticatedUsers = new ReplaySubject<AuthenticatedUser | null>(1)
|
||||
|
||||
function updateAuthenticatedUser(): void {
|
||||
requestGraphQLFromVSCode<CurrentAuthStateResult, CurrentAuthStateVariables>(currentAuthStateQuery, {})
|
||||
.then(authenticatedUserResult => {
|
||||
authenticatedUsers.next(authenticatedUserResult.data ? authenticatedUserResult.data.currentUser : null)
|
||||
if (!authenticatedUserResult.data) {
|
||||
throw new Error('Not an authenticated user')
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('core auth error', error)
|
||||
// TODO surface error?
|
||||
authenticatedUsers.next(null)
|
||||
})
|
||||
}
|
||||
|
||||
// Initial authenticated user
|
||||
updateAuthenticatedUser()
|
||||
|
||||
secretStorage.onDidChange(async event => {
|
||||
if (event.key === scretTokenKey) {
|
||||
const token = await secretStorage.get(scretTokenKey)
|
||||
if (token) {
|
||||
updateAuthenticatedUser()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return authenticatedUsers
|
||||
}
|
||||
@ -1,39 +0,0 @@
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import type { BlobContentResult, BlobContentVariables } from '../graphql-operations'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
const blobContentQuery = gql`
|
||||
query BlobContent($repository: String!, $revision: String!, $path: String!) {
|
||||
repository(name: $repository) {
|
||||
commit(rev: $revision) {
|
||||
blob(path: $path) {
|
||||
content
|
||||
binary
|
||||
byteSize
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export interface FileContents {
|
||||
content: Uint8Array
|
||||
isBinary: boolean
|
||||
byteSize: number
|
||||
}
|
||||
|
||||
export async function getBlobContent(variables: BlobContentVariables): Promise<FileContents | undefined> {
|
||||
const result = await requestGraphQLFromVSCode<BlobContentResult, BlobContentVariables>(blobContentQuery, variables)
|
||||
|
||||
const blob = result.data?.repository?.commit?.blob
|
||||
if (blob) {
|
||||
return {
|
||||
content: new TextEncoder().encode(blob.content),
|
||||
isBinary: blob.binary,
|
||||
byteSize: blob.byteSize,
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
import { EMPTY, Subject } from 'rxjs'
|
||||
import { bufferTime, catchError, concatMap } from 'rxjs/operators'
|
||||
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import type { LogEventsResult, LogEventsVariables, Event } from '../graphql-operations'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
// Log events in batches.
|
||||
const events = new Subject<Event>()
|
||||
|
||||
events
|
||||
.pipe(
|
||||
bufferTime(1000),
|
||||
concatMap(events => {
|
||||
if (events.length > 0) {
|
||||
return requestGraphQLFromVSCode<LogEventsResult, LogEventsVariables>(logEventsMutation, {
|
||||
events,
|
||||
})
|
||||
}
|
||||
return EMPTY
|
||||
}),
|
||||
catchError(error => {
|
||||
console.error('Error logging events:', error)
|
||||
return []
|
||||
})
|
||||
)
|
||||
// eslint-disable-next-line rxjs/no-ignored-subscription
|
||||
.subscribe()
|
||||
|
||||
export const logEventsMutation = gql`
|
||||
mutation LogEvents($events: [Event!]) {
|
||||
logEvents(events: $events) {
|
||||
alwaysNil
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
/**
|
||||
* Log a raw user action (used to allow site admins on a Sourcegraph instance
|
||||
* to see a count of unique users on a daily, weekly, and monthly basis).
|
||||
*
|
||||
* When invoked on a non-Sourcegraph.com instance, this data is stored in the
|
||||
* instance's database, and not sent to Sourcegraph.com.
|
||||
*/
|
||||
|
||||
export function logEvent(eventVariable: Event): void {
|
||||
events.next(eventVariable)
|
||||
}
|
||||
@ -1,72 +0,0 @@
|
||||
import type net from 'net'
|
||||
|
||||
import type { ClientRequest, RequestOptions } from 'agent-base'
|
||||
import HttpProxyAgent from 'http-proxy-agent'
|
||||
import HttpsProxyAgent from 'https-proxy-agent'
|
||||
import fetch, { Headers } from 'node-fetch'
|
||||
import vscode from 'vscode'
|
||||
|
||||
export { fetch, Headers }
|
||||
export type { BodyInit, Response, HeadersInit } from 'node-fetch'
|
||||
|
||||
interface HttpsProxyAgentInterface {
|
||||
callback(req: ClientRequest, opts: RequestOptions): Promise<net.Socket>
|
||||
}
|
||||
|
||||
type HttpsProxyAgentConstructor = new (
|
||||
options: string | { [key: string]: number | boolean | string | null }
|
||||
) => HttpsProxyAgentInterface
|
||||
|
||||
export function getProxyAgent(): ((url: URL | string) => HttpsProxyAgentInterface | undefined) | undefined {
|
||||
const proxyProtocol = vscode.workspace.getConfiguration('sourcegraph').get<string>('proxyProtocol')
|
||||
const proxyHost = vscode.workspace.getConfiguration('sourcegraph').get<string>('proxyHost')
|
||||
const proxyPort = vscode.workspace.getConfiguration('sourcegraph').get<number>('proxyPort')
|
||||
const proxyPath = vscode.workspace.getConfiguration('sourcegraph').get<string>('proxyPath')
|
||||
|
||||
// Quit if we're in the browser—we don't need proxying there.
|
||||
if (HttpsProxyAgent === null) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (proxyHost && !proxyPort) {
|
||||
console.error('proxyHost is set but proxyPort is not. These two settings must be set together.')
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (proxyPort && !proxyHost) {
|
||||
console.error('proxyPort is set but proxyHost is not. These two settings must be set together.')
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (proxyHost || proxyPort || proxyPath) {
|
||||
return (url: URL | string) => {
|
||||
const protocol = getProtocol(url)
|
||||
if (protocol === undefined) {
|
||||
return undefined
|
||||
}
|
||||
const ProxyAgent = (protocol === 'http'
|
||||
? HttpProxyAgent
|
||||
: HttpsProxyAgent) as unknown as HttpsProxyAgentConstructor
|
||||
return new ProxyAgent({
|
||||
protocol: proxyProtocol === 'http' || proxyProtocol === 'https' ? proxyProtocol : 'https',
|
||||
...(proxyHost ? { host: proxyHost } : null),
|
||||
...(proxyPort ? { port: proxyPort } : null),
|
||||
...(proxyPath ? { path: proxyPath } : null),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
function getProtocol(url: URL | string): string | undefined {
|
||||
if (typeof url === 'string') {
|
||||
return url.startsWith('http:') ? 'http' : 'https'
|
||||
}
|
||||
|
||||
if (url instanceof URL) {
|
||||
return url.protocol === 'http:' ? 'http' : 'https'
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
@ -1,26 +0,0 @@
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import type { FileNamesResult, FileNamesVariables } from '../graphql-operations'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
const fileNamesQuery = gql`
|
||||
query FileNames($repository: String!, $revision: String!) {
|
||||
repository(name: $repository) {
|
||||
commit(rev: $revision) {
|
||||
fileNames
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export async function getFiles(variables: FileNamesVariables): Promise<string[]> {
|
||||
const result = await requestGraphQLFromVSCode<FileNamesResult, FileNamesVariables>(fileNamesQuery, variables)
|
||||
|
||||
if (result.data?.repository?.commit) {
|
||||
return result.data.repository.commit.fileNames
|
||||
}
|
||||
|
||||
// Debt: surface error to users.
|
||||
throw new Error(`Failed to fetch file names for ${variables.repository}@${variables.revision}`)
|
||||
}
|
||||
@ -1,110 +0,0 @@
|
||||
import { noop } from 'lodash'
|
||||
import { from, type Observable } from 'rxjs'
|
||||
import { catchError, map } from 'rxjs/operators'
|
||||
|
||||
import { dataOrThrowErrors, gql } from '@sourcegraph/http-client'
|
||||
import { EventSource } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { displayWarning } from '../settings/displayWarnings'
|
||||
import { INSTANCE_VERSION_NUMBER_KEY, type LocalStorageService } from '../settings/LocalStorageService'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
/**
|
||||
* Gets the Sourcegraph instance version number via the GrapQL API.
|
||||
*
|
||||
* @returns An Observable that emits flattened Sourcegraph instance version number or undefined in case of an error:
|
||||
* - regular instance version format: 3.38.2
|
||||
* - insiders version format: 134683_2022-03-02_5188fes0101
|
||||
*/
|
||||
export const observeInstanceVersionNumber = (
|
||||
accessToken: string,
|
||||
endpointURL: string
|
||||
): Observable<string | undefined> =>
|
||||
from(requestGraphQLFromVSCode<SiteVersionResult>(siteVersionQuery, {}, accessToken, endpointURL)).pipe(
|
||||
map(dataOrThrowErrors),
|
||||
map(data => data.site.productVersion),
|
||||
catchError(error => {
|
||||
console.error('Failed to get instance version from host:', error)
|
||||
return [undefined]
|
||||
})
|
||||
)
|
||||
|
||||
interface RegularVersion {
|
||||
major: number
|
||||
minor: number
|
||||
}
|
||||
type Version = RegularVersion | 'insiders'
|
||||
|
||||
/**
|
||||
* Parses the Sourcegraph instance version number.
|
||||
*
|
||||
* @returns Major and minor version numbers if it's a regular version, or `'insiders'` if it's an insiders version.
|
||||
*/
|
||||
const parseVersion = (version: string): Version => {
|
||||
const versionParts = version.split('.')
|
||||
if (versionParts.length === 3) {
|
||||
return {
|
||||
major: parseInt(versionParts[0], 10),
|
||||
minor: parseInt(versionParts[1], 10),
|
||||
}
|
||||
}
|
||||
return 'insiders'
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the Sourcegraph instance version is older than the given version.
|
||||
* */
|
||||
export const isOlderThan = (instanceVersion: string, comparedVersion: RegularVersion): boolean => {
|
||||
const version = parseVersion(instanceVersion)
|
||||
return (
|
||||
version !== 'insiders' &&
|
||||
(version.major < comparedVersion.major ||
|
||||
(version.major === comparedVersion.major && version.minor < comparedVersion.minor))
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* This function will return the EventSource Type based
|
||||
* on the instance version
|
||||
*/
|
||||
export function initializeInstanceVersionNumber(
|
||||
localStorageService: LocalStorageService,
|
||||
initialAccessToken: string | undefined,
|
||||
initialInstanceURL: string
|
||||
): EventSource {
|
||||
// Check only if a user is trying to connect to a private instance with a valid access token provided
|
||||
if (initialAccessToken && initialAccessToken !== undefined) {
|
||||
observeInstanceVersionNumber(initialAccessToken, initialInstanceURL)
|
||||
.toPromise()
|
||||
.then(async version => {
|
||||
if (version) {
|
||||
if (isOlderThan(version, { major: 3, minor: 32 })) {
|
||||
displayWarning(
|
||||
'Your Sourcegraph instance version is not fully compatible with the Sourcegraph extension. Please ask your site admin to upgrade to version 3.32.0 or above. Read more about version support in our [troubleshooting docs](https://docs.sourcegraph.com/admin/how-to/troubleshoot-sg-extension#unsupported-features-by-sourcegraph-version).'
|
||||
).catch(() => {})
|
||||
}
|
||||
await localStorageService.setValue(INSTANCE_VERSION_NUMBER_KEY, version)
|
||||
}
|
||||
})
|
||||
.catch(noop) // We handle potential errors in instanceVersionNumber observable
|
||||
|
||||
const version = localStorageService.getValue(INSTANCE_VERSION_NUMBER_KEY)
|
||||
// instances below 3.38.0 does not support EventSource.IDEEXTENSION and should fallback to BACKEND source
|
||||
return version && isOlderThan(version, { major: 3, minor: 38 }) ? EventSource.BACKEND : EventSource.IDEEXTENSION
|
||||
}
|
||||
return EventSource.IDEEXTENSION
|
||||
}
|
||||
|
||||
const siteVersionQuery = gql`
|
||||
query SiteProductVersion {
|
||||
site {
|
||||
productVersion
|
||||
}
|
||||
}
|
||||
`
|
||||
interface SiteVersionResult {
|
||||
site: {
|
||||
productVersion: string
|
||||
}
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
// This fake reuses the built-in "fetch" in browsers.
|
||||
|
||||
// eslint-disable-next-line import/no-default-export
|
||||
export default fetch
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
export const Headers = globalThis.Headers
|
||||
@ -1,6 +0,0 @@
|
||||
// This is a fake that we use instead of the read http-proxy-agent and https-proxy-agent modules in the browser.
|
||||
// (We don't need proxying in the browser—browser settings will determine the proxying.)
|
||||
|
||||
// Disabling ESLint because we want to match the library interfaces
|
||||
// eslint-disable-next-line import/no-default-export
|
||||
export default null
|
||||
@ -1,59 +0,0 @@
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import type { RepositoryMetadataResult, RepositoryMetadataVariables } from '../graphql-operations'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
const repositoryMetadataQuery = gql`
|
||||
query RepositoryMetadata($repositoryName: String!) {
|
||||
repositoryRedirect(name: $repositoryName) {
|
||||
... on Repository {
|
||||
id
|
||||
mirrorInfo {
|
||||
cloneInProgress
|
||||
cloneProgress
|
||||
cloned
|
||||
}
|
||||
commit(rev: "") {
|
||||
oid
|
||||
abbreviatedOID
|
||||
tree(path: "") {
|
||||
url
|
||||
}
|
||||
}
|
||||
defaultBranch {
|
||||
abbrevName
|
||||
}
|
||||
}
|
||||
... on Redirect {
|
||||
url
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export interface RepositoryMetadata {
|
||||
repositoryId: string
|
||||
defaultOID?: string
|
||||
defaultAbbreviatedOID?: string
|
||||
defaultBranch?: string
|
||||
}
|
||||
|
||||
export async function getRepositoryMetadata(
|
||||
variables: RepositoryMetadataVariables
|
||||
): Promise<RepositoryMetadata | undefined> {
|
||||
const result = await requestGraphQLFromVSCode<RepositoryMetadataResult, RepositoryMetadataVariables>(
|
||||
repositoryMetadataQuery,
|
||||
variables
|
||||
)
|
||||
if (result.data?.repositoryRedirect?.__typename === 'Repository') {
|
||||
return {
|
||||
repositoryId: result.data.repositoryRedirect.id,
|
||||
defaultOID: result.data.repositoryRedirect.commit?.oid,
|
||||
defaultAbbreviatedOID: result.data.repositoryRedirect.commit?.abbreviatedOID,
|
||||
defaultBranch: result.data.repositoryRedirect.defaultBranch?.abbrevName,
|
||||
}
|
||||
}
|
||||
// v1 Debt: surface error to user.
|
||||
return undefined
|
||||
}
|
||||
@ -1,74 +0,0 @@
|
||||
import { authentication } from 'vscode'
|
||||
|
||||
import { asError } from '@sourcegraph/common'
|
||||
import { checkOk, GRAPHQL_URI, type GraphQLResult, isHTTPAuthError } from '@sourcegraph/http-client'
|
||||
|
||||
import { handleAccessTokenError } from '../settings/accessTokenSetting'
|
||||
import { endpointRequestHeadersSetting, endpointSetting } from '../settings/endpointSetting'
|
||||
|
||||
import { fetch, getProxyAgent, Headers, type HeadersInit } from './fetch'
|
||||
|
||||
let invalidated = false
|
||||
|
||||
/**
|
||||
* To be called when Sourcegraph URL changes.
|
||||
*/
|
||||
export function invalidateClient(): void {
|
||||
invalidated = true
|
||||
}
|
||||
|
||||
export const requestGraphQLFromVSCode = async <R, V = object>(
|
||||
request: string,
|
||||
variables: V,
|
||||
overrideAccessToken?: string,
|
||||
overrideSourcegraphURL?: string
|
||||
): Promise<GraphQLResult<R>> => {
|
||||
if (invalidated) {
|
||||
throw new Error(
|
||||
'Sourcegraph GraphQL Client has been invalidated due to instance URL change. Restart VS Code to fix.'
|
||||
)
|
||||
}
|
||||
const session = await authentication.getSession(endpointSetting(), [], { createIfNone: false })
|
||||
const sourcegraphURL = overrideSourcegraphURL || endpointSetting()
|
||||
const accessToken = overrideAccessToken || session?.accessToken
|
||||
const nameMatch = request.match(/^\s*(?:query|mutation)\s+(\w+)/)
|
||||
const apiURL = `${GRAPHQL_URI}${nameMatch ? '?' + nameMatch[1] : ''}`
|
||||
const customHeaders = endpointRequestHeadersSetting()
|
||||
// create a headers container based on the custom headers configuration if there are any
|
||||
// then add Access Token to request header, contributed by @ptxmac!
|
||||
const headers = new Headers(customHeaders as HeadersInit)
|
||||
headers.set('Content-Type', 'application/json')
|
||||
if (accessToken) {
|
||||
headers.set('Authorization', `token ${accessToken}`)
|
||||
}
|
||||
try {
|
||||
const url = new URL(apiURL, sourcegraphURL).href
|
||||
// Debt: intercepted requests in integration tests
|
||||
// have 0 status codes, so don't check in test environment.
|
||||
const checkFunction = process.env.IS_TEST ? <T>(value: T): T => value : checkOk
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const options: any = {
|
||||
agent: getProxyAgent(),
|
||||
body: JSON.stringify({
|
||||
query: request,
|
||||
variables,
|
||||
}),
|
||||
method: 'POST',
|
||||
headers,
|
||||
}
|
||||
|
||||
const response = checkFunction(await fetch(url, options))
|
||||
// TODO request cancellation w/ VS Code cancellation tokens.
|
||||
return (await response.json()) as GraphQLResult<R>
|
||||
} catch (error) {
|
||||
// If `overrideAccessToken` is set, we're validating the token
|
||||
// and errors will be displayed in the UI.
|
||||
if (isHTTPAuthError(error) && !overrideAccessToken) {
|
||||
handleAccessTokenError(accessToken || '', sourcegraphURL).then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
}
|
||||
throw asError(error)
|
||||
}
|
||||
}
|
||||
@ -1,48 +0,0 @@
|
||||
import { from, type Observable, of } from 'rxjs'
|
||||
import { catchError } from 'rxjs/operators'
|
||||
import type * as vscode from 'vscode'
|
||||
|
||||
import type { GraphQLResult } from '@sourcegraph/http-client'
|
||||
import { getAvailableSearchContextSpecOrFallback } from '@sourcegraph/shared/src/search'
|
||||
|
||||
import { type LocalStorageService, SELECTED_SEARCH_CONTEXT_SPEC_KEY } from '../settings/LocalStorageService'
|
||||
import type { VSCEStateMachine } from '../state'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
// Returns an Observable so webviews can easily block rendering on init.
|
||||
export function initializeSearchContexts({
|
||||
localStorageService,
|
||||
stateMachine,
|
||||
context,
|
||||
}: {
|
||||
localStorageService: LocalStorageService
|
||||
stateMachine: VSCEStateMachine
|
||||
context: vscode.ExtensionContext
|
||||
}): void {
|
||||
const initialSearchContextSpec = localStorageService.getValue(SELECTED_SEARCH_CONTEXT_SPEC_KEY)
|
||||
|
||||
const fallbackSpec = 'global'
|
||||
|
||||
const subscription = getAvailableSearchContextSpecOrFallback({
|
||||
spec: initialSearchContextSpec || fallbackSpec,
|
||||
fallbackSpec,
|
||||
platformContext: {
|
||||
requestGraphQL: ({ request, variables }) =>
|
||||
from(requestGraphQLFromVSCode(request, variables)) as Observable<GraphQLResult<any>>,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
catchError(error => {
|
||||
console.error('Error validating search context spec:', error)
|
||||
return of(fallbackSpec)
|
||||
})
|
||||
)
|
||||
.subscribe(availableSearchContextSpecOrDefault => {
|
||||
stateMachine.emit({ type: 'set_selected_search_context_spec', spec: availableSearchContextSpecOrDefault })
|
||||
})
|
||||
|
||||
context.subscriptions.push({
|
||||
dispose: () => subscription.unsubscribe(),
|
||||
})
|
||||
}
|
||||
@ -1,57 +0,0 @@
|
||||
import { type Observable, of, ReplaySubject, Subject } from 'rxjs'
|
||||
import { catchError, map, switchMap, throttleTime } from 'rxjs/operators'
|
||||
import type * as vscode from 'vscode'
|
||||
|
||||
import { createAggregateError } from '@sourcegraph/common'
|
||||
import { viewerSettingsQuery } from '@sourcegraph/shared/src/backend/settings'
|
||||
import type { ViewerSettingsResult, ViewerSettingsVariables } from '@sourcegraph/shared/src/graphql-operations'
|
||||
import {
|
||||
EMPTY_SETTINGS_CASCADE,
|
||||
gqlToCascade,
|
||||
type Settings,
|
||||
type SettingsCascadeOrError,
|
||||
} from '@sourcegraph/shared/src/settings/settings'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
export function initializeSourcegraphSettings({ context }: { context: vscode.ExtensionContext }): {
|
||||
settings: Observable<SettingsCascadeOrError<Settings>>
|
||||
refreshSettings: () => void
|
||||
} {
|
||||
const settings = new ReplaySubject<SettingsCascadeOrError<Settings>>(1)
|
||||
|
||||
const refreshes = new Subject<void>()
|
||||
|
||||
// Throttle refreshes for one hour.
|
||||
const ONE_HOUR_MS = 60 * 60 * 1000
|
||||
|
||||
const subscription = refreshes
|
||||
.pipe(
|
||||
throttleTime(ONE_HOUR_MS, undefined, { leading: true, trailing: true }),
|
||||
switchMap(() =>
|
||||
requestGraphQLFromVSCode<ViewerSettingsResult, ViewerSettingsVariables>(viewerSettingsQuery, {})
|
||||
),
|
||||
map(({ data, errors }) => {
|
||||
if (!data?.viewerSettings) {
|
||||
throw createAggregateError(errors)
|
||||
}
|
||||
|
||||
return gqlToCascade(data.viewerSettings)
|
||||
}),
|
||||
catchError(() => of(EMPTY_SETTINGS_CASCADE))
|
||||
)
|
||||
.subscribe(settingsCascade => {
|
||||
settings.next(settingsCascade)
|
||||
})
|
||||
context.subscriptions.push({ dispose: () => subscription.unsubscribe() })
|
||||
|
||||
// Initial settings
|
||||
refreshes.next()
|
||||
|
||||
return {
|
||||
settings: settings.asObservable(),
|
||||
refreshSettings: () => {
|
||||
refreshes.next()
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -1,91 +0,0 @@
|
||||
import { of, type Subscription } from 'rxjs'
|
||||
import { map, switchMap, throttleTime } from 'rxjs/operators'
|
||||
import type * as vscode from 'vscode'
|
||||
|
||||
import { SearchMode } from '@sourcegraph/shared/src/search'
|
||||
import { appendContextFilter } from '@sourcegraph/shared/src/search/query/transformer'
|
||||
import { aggregateStreamingSearch } from '@sourcegraph/shared/src/search/stream'
|
||||
|
||||
import type { ExtensionCoreAPI } from '../contract'
|
||||
import { SearchPatternType } from '../graphql-operations'
|
||||
import type { VSCEStateMachine } from '../state'
|
||||
import { focusSearchPanel } from '../webview/commands'
|
||||
|
||||
import { isOlderThan, observeInstanceVersionNumber } from './instanceVersion'
|
||||
|
||||
export function createStreamSearch({
|
||||
context,
|
||||
stateMachine,
|
||||
sourcegraphURL,
|
||||
session,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
stateMachine: VSCEStateMachine
|
||||
sourcegraphURL: string
|
||||
session: vscode.AuthenticationSession | undefined
|
||||
}): ExtensionCoreAPI['streamSearch'] {
|
||||
// Ensure only one search is active at a time
|
||||
let previousSearchSubscription: Subscription | null
|
||||
|
||||
context.subscriptions.push({
|
||||
dispose: () => {
|
||||
previousSearchSubscription?.unsubscribe()
|
||||
},
|
||||
})
|
||||
const token = session?.accessToken === undefined ? '' : session?.accessToken
|
||||
const instanceVersionNumber = observeInstanceVersionNumber(token, sourcegraphURL)
|
||||
|
||||
return function streamSearch(query, options) {
|
||||
previousSearchSubscription?.unsubscribe()
|
||||
|
||||
stateMachine.emit({
|
||||
type: 'submit_search_query',
|
||||
submittedSearchQueryState: {
|
||||
queryState: { query },
|
||||
searchCaseSensitivity: options.caseSensitive,
|
||||
searchPatternType: options.patternType,
|
||||
searchMode: options.searchMode || SearchMode.Precise,
|
||||
},
|
||||
})
|
||||
// Focus search panel if not already focused
|
||||
// (in case e.g. user initiates search from search sidebar when panel is hidden).
|
||||
focusSearchPanel()
|
||||
|
||||
previousSearchSubscription = instanceVersionNumber
|
||||
.pipe(
|
||||
map(version => {
|
||||
let patternType = options.patternType
|
||||
|
||||
if (
|
||||
patternType === SearchPatternType.standard &&
|
||||
version &&
|
||||
isOlderThan(version, { major: 3, minor: 43 })
|
||||
) {
|
||||
/**
|
||||
* SearchPatternType.standard support was added in Sourcegraph v3.43.0.
|
||||
* Use SearchPatternType.literal for earlier versions instead (it was the default before v3.43.0).
|
||||
* See: https://docs.sourcegraph.com/CHANGELOG#3-43-0, https://github.com/sourcegraph/sourcegraph/pull/38141.
|
||||
*/
|
||||
patternType = SearchPatternType.literal
|
||||
}
|
||||
|
||||
return patternType
|
||||
}),
|
||||
switchMap(patternType =>
|
||||
aggregateStreamingSearch(
|
||||
of(appendContextFilter(query, stateMachine.state.context.selectedSearchContextSpec)),
|
||||
{ ...options, patternType, sourcegraphURL }
|
||||
).pipe(throttleTime(500, undefined, { leading: true, trailing: true }))
|
||||
)
|
||||
)
|
||||
.subscribe(searchResults => {
|
||||
if (searchResults.state === 'error') {
|
||||
// Pass only primitive copied values because Error object is not cloneable
|
||||
const { name, message, stack } = searchResults.error
|
||||
searchResults.error = { name, message, stack }
|
||||
}
|
||||
|
||||
stateMachine.emit({ type: 'received_search_results', searchResults })
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -1,72 +0,0 @@
|
||||
import type * as Comlink from 'comlink'
|
||||
import { EMPTY, of } from 'rxjs'
|
||||
import { first, switchMap } from 'rxjs/operators'
|
||||
import type * as vscode from 'vscode'
|
||||
|
||||
import { finallyReleaseProxy, wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import { makeRepoURI, parseRepoURI } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
import type { SearchSidebarAPI } from '../contract'
|
||||
import type { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
|
||||
export class SourcegraphDefinitionProvider implements vscode.DefinitionProvider {
|
||||
constructor(
|
||||
private readonly fs: SourcegraphFileSystemProvider,
|
||||
private readonly sourcegraphExtensionHostAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
) {}
|
||||
public async provideDefinition(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<vscode.Definition | undefined> {
|
||||
const uri = this.fs.sourcegraphUri(document.uri)
|
||||
const extensionHostUri = makeRepoURI({
|
||||
repoName: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
filePath: uri.path,
|
||||
})
|
||||
|
||||
const definitions = wrapRemoteObservable(
|
||||
this.sourcegraphExtensionHostAPI.getDefinition({
|
||||
textDocument: {
|
||||
uri: extensionHostUri,
|
||||
},
|
||||
position: {
|
||||
line: position.line,
|
||||
character: position.character,
|
||||
},
|
||||
})
|
||||
)
|
||||
.pipe(
|
||||
finallyReleaseProxy(),
|
||||
switchMap(({ isLoading, result }) => {
|
||||
if (isLoading) {
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
const locations = result.map(location => {
|
||||
const uri = parseRepoURI(location.uri)
|
||||
|
||||
return this.fs.toVscodeLocation({
|
||||
resource: {
|
||||
path: uri.filePath ?? '',
|
||||
repositoryName: uri.repoName,
|
||||
revision: uri.commitID ?? uri.revision ?? '',
|
||||
},
|
||||
range: location.range,
|
||||
})
|
||||
})
|
||||
|
||||
return of(locations)
|
||||
}),
|
||||
first()
|
||||
)
|
||||
.toPromise()
|
||||
|
||||
token.onCancellationRequested(() => {
|
||||
// Debt: manually create promise so we can cancel request.
|
||||
})
|
||||
|
||||
return definitions
|
||||
}
|
||||
}
|
||||
@ -1,76 +0,0 @@
|
||||
import type * as Comlink from 'comlink'
|
||||
import { EMPTY, of } from 'rxjs'
|
||||
import { first, switchMap } from 'rxjs/operators'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { finallyReleaseProxy, wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import { makeRepoURI } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
import type { SearchSidebarAPI } from '../contract'
|
||||
import type { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
|
||||
export class SourcegraphHoverProvider implements vscode.HoverProvider {
|
||||
constructor(
|
||||
private readonly fs: SourcegraphFileSystemProvider,
|
||||
private readonly sourcegraphExtensionHostAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
) {}
|
||||
public async provideHover(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<vscode.Hover | undefined> {
|
||||
const uri = this.fs.sourcegraphUri(document.uri)
|
||||
const extensionHostUri = makeRepoURI({
|
||||
repoName: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
filePath: uri.path,
|
||||
})
|
||||
|
||||
const definitions = wrapRemoteObservable(
|
||||
this.sourcegraphExtensionHostAPI.getHover({
|
||||
textDocument: {
|
||||
uri: extensionHostUri,
|
||||
},
|
||||
position: {
|
||||
line: position.line,
|
||||
character: position.character,
|
||||
},
|
||||
})
|
||||
)
|
||||
.pipe(
|
||||
finallyReleaseProxy(),
|
||||
switchMap(({ isLoading, result }) => {
|
||||
if (isLoading) {
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
const prefix =
|
||||
result?.aggregatedBadges?.reduce((prefix, badge) => {
|
||||
if (badge.linkURL) {
|
||||
return prefix + `[${badge.text}](${badge.linkURL})\n`
|
||||
}
|
||||
return prefix + `${badge.text}\n`
|
||||
}, ` `) || ''
|
||||
|
||||
return of<vscode.Hover>({
|
||||
contents: [
|
||||
...(result?.contents ?? []).map(
|
||||
content => new vscode.MarkdownString(prefix + content.value)
|
||||
),
|
||||
],
|
||||
})
|
||||
}),
|
||||
first()
|
||||
)
|
||||
.toPromise()
|
||||
|
||||
token.onCancellationRequested(() => {
|
||||
// Debt: manually create promise so we can cancel request.
|
||||
})
|
||||
|
||||
return definitions
|
||||
}
|
||||
}
|
||||
|
||||
const sourcegraphLogoDataURI =
|
||||
'data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE0IiB2aWV3Qm94PSIwIDAgNTIgNTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTMwLjggNTEuOGMtMi44LjUtNS41LTEuMy02LTQuMUwxNy4yIDYuMmMtLjUtMi44IDEuMy01LjUgNC4xLTZzNS41IDEuMyA2IDQuMWw3LjYgNDEuNWMuNSAyLjgtMS40IDUuNS00LjEgNnoiIGZpbGw9IiNGRjU1NDMiLz48cGF0aCBkPSJNMTAuOSA0NC43QzkuMSA0NSA3LjMgNDQuNCA2IDQzYy0xLjgtMi4yLTEuNi01LjQuNi03LjJMMzguNyA4LjVjMi4yLTEuOCA1LjQtMS42IDcuMi42IDEuOCAyLjIgMS42IDUuNC0uNiA3LjJsLTMyIDI3LjNjLS43LjYtMS42IDEtMi40IDEuMXoiIGZpbGw9IiNBMTEyRkYiLz48cGF0aCBkPSJNNDYuOCAzOC4xYy0uOS4yLTEuOC4xLTIuNi0uMkw0LjQgMjMuOGMtMi43LTEtNC4xLTMuOS0zLjEtNi42IDEtMi43IDMuOS00LjEgNi42LTMuMWwzOS43IDE0LjFjMi43IDEgNC4xIDMuOSAzLjEgNi42LS42IDEuOC0yLjIgMy0zLjkgMy4zeiIgZmlsbD0iIzAwQ0JFQyIvPjwvc3ZnPg=='
|
||||
@ -1,78 +0,0 @@
|
||||
import type * as Comlink from 'comlink'
|
||||
import { EMPTY, of } from 'rxjs'
|
||||
import { debounceTime, first, switchMap } from 'rxjs/operators'
|
||||
import type * as vscode from 'vscode'
|
||||
|
||||
import { finallyReleaseProxy, wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import { makeRepoURI, parseRepoURI } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
import type { SearchSidebarAPI } from '../contract'
|
||||
import type { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
|
||||
export class SourcegraphReferenceProvider implements vscode.ReferenceProvider {
|
||||
constructor(
|
||||
private readonly fs: SourcegraphFileSystemProvider,
|
||||
private readonly sourcegraphExtensionHostAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
) {}
|
||||
public async provideReferences(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
referenceContext: vscode.ReferenceContext,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<vscode.Location[] | undefined> {
|
||||
const uri = this.fs.sourcegraphUri(document.uri)
|
||||
const extensionHostUri = makeRepoURI({
|
||||
repoName: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
filePath: uri.path,
|
||||
})
|
||||
|
||||
const definitions = wrapRemoteObservable(
|
||||
this.sourcegraphExtensionHostAPI.getReferences(
|
||||
{
|
||||
textDocument: {
|
||||
uri: extensionHostUri,
|
||||
},
|
||||
position: {
|
||||
line: position.line,
|
||||
character: position.character,
|
||||
},
|
||||
},
|
||||
referenceContext
|
||||
)
|
||||
)
|
||||
.pipe(
|
||||
finallyReleaseProxy(),
|
||||
switchMap(({ isLoading, result }) => {
|
||||
if (isLoading) {
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
const locations = result.map(location => {
|
||||
// Create a sourcegraph URI from this git URI (so we need both fromGitURI and toGitURI.)`
|
||||
const uri = parseRepoURI(location.uri)
|
||||
|
||||
return this.fs.toVscodeLocation({
|
||||
resource: {
|
||||
path: uri.filePath ?? '',
|
||||
repositoryName: uri.repoName,
|
||||
revision: uri.commitID ?? uri.revision ?? '',
|
||||
},
|
||||
range: location.range,
|
||||
})
|
||||
})
|
||||
|
||||
return of(locations)
|
||||
}),
|
||||
debounceTime(1000),
|
||||
first()
|
||||
)
|
||||
.toPromise()
|
||||
|
||||
token.onCancellationRequested(() => {
|
||||
// Debt: manually create promise so we can cancel request.
|
||||
})
|
||||
|
||||
return definitions
|
||||
}
|
||||
}
|
||||
@ -1,77 +0,0 @@
|
||||
import type * as Comlink from 'comlink'
|
||||
import vscode from 'vscode'
|
||||
|
||||
import { makeRepoURI } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
import type { SearchSidebarAPI } from '../contract'
|
||||
import type { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
|
||||
import { toSourcegraphLanguage } from './languages'
|
||||
import { SourcegraphDefinitionProvider } from './SourcegraphDefinitionProvider'
|
||||
import { SourcegraphHoverProvider } from './SourcegraphHoverProvider'
|
||||
import { SourcegraphReferenceProvider } from './SourcegraphReferenceProvider'
|
||||
|
||||
export function initializeCodeIntel({
|
||||
context,
|
||||
fs,
|
||||
searchSidebarAPI,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
fs: SourcegraphFileSystemProvider
|
||||
searchSidebarAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
}): void {
|
||||
// Register language-related features (they depend on Sourcegraph extensions).
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerDefinitionProvider(
|
||||
{ scheme: 'sourcegraph' },
|
||||
new SourcegraphDefinitionProvider(fs, searchSidebarAPI)
|
||||
)
|
||||
)
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerReferenceProvider(
|
||||
{ scheme: 'sourcegraph' },
|
||||
new SourcegraphReferenceProvider(fs, searchSidebarAPI)
|
||||
)
|
||||
)
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerHoverProvider(
|
||||
{ scheme: 'sourcegraph' },
|
||||
new SourcegraphHoverProvider(fs, searchSidebarAPI)
|
||||
)
|
||||
)
|
||||
|
||||
// Debt: remove closed editors/documents
|
||||
context.subscriptions.push(
|
||||
vscode.window.onDidChangeActiveTextEditor(editor => {
|
||||
// TODO store previously active editor -> SG viewer so we can remove on change
|
||||
if (editor?.document.uri.scheme === 'sourcegraph') {
|
||||
const text = editor.document.getText()
|
||||
const sourcegraphUri = fs.sourcegraphUri(editor.document.uri)
|
||||
const languageId = toSourcegraphLanguage(editor.document.languageId)
|
||||
|
||||
const extensionHostUri = makeRepoURI({
|
||||
repoName: sourcegraphUri.repositoryName,
|
||||
revision: sourcegraphUri.revision,
|
||||
filePath: sourcegraphUri.path,
|
||||
})
|
||||
|
||||
// We'll use the viewerId return value to remove viewer, get/set text decorations.
|
||||
searchSidebarAPI
|
||||
.addTextDocumentIfNotExists({
|
||||
text,
|
||||
uri: extensionHostUri,
|
||||
languageId,
|
||||
})
|
||||
.then(() =>
|
||||
searchSidebarAPI.addViewerIfNotExists({
|
||||
type: 'CodeEditor',
|
||||
resource: extensionHostUri,
|
||||
selections: [],
|
||||
isActive: true,
|
||||
})
|
||||
)
|
||||
.catch(error => console.error(error))
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
@ -1,14 +0,0 @@
|
||||
/**
|
||||
* Converts VS Code language ID to Sourcegraph-compatible language ID
|
||||
* if necessary (e.g. "typescriptreact" -> "typescript")
|
||||
*/
|
||||
export function toSourcegraphLanguage(vscodeLanguageID: string): string {
|
||||
if (vscodeLanugageIDReplacements[vscodeLanguageID]) {
|
||||
return vscodeLanugageIDReplacements[vscodeLanguageID]!
|
||||
}
|
||||
return vscodeLanguageID
|
||||
}
|
||||
|
||||
const vscodeLanugageIDReplacements: Record<string, string | undefined> = {
|
||||
typescriptreact: 'typescript',
|
||||
}
|
||||
@ -1,10 +0,0 @@
|
||||
import type { Range } from '@sourcegraph/extension-api-types'
|
||||
|
||||
export interface LocationNode {
|
||||
resource: {
|
||||
path: string
|
||||
repositoryName: string
|
||||
revision: string
|
||||
}
|
||||
range?: Range
|
||||
}
|
||||
@ -1,68 +0,0 @@
|
||||
import vscode, { env } from 'vscode'
|
||||
|
||||
import { getSourcegraphFileUrl, repoInfo } from './git-helpers'
|
||||
import { generateSourcegraphBlobLink } from './initialize'
|
||||
|
||||
/**
|
||||
* Open active file in the browser on the configured Sourcegraph instance.
|
||||
*/
|
||||
export async function browserActions(action: string, logRedirectEvent: (uri: string) => void): Promise<void> {
|
||||
const editor = vscode.window.activeTextEditor
|
||||
if (!editor) {
|
||||
throw new Error('No active editor')
|
||||
}
|
||||
const uri = editor.document.uri
|
||||
const instanceUrl =
|
||||
vscode.workspace.getConfiguration('sourcegraph').get<string>('url') || 'https://sourcegraph.com/'
|
||||
let sourcegraphUrl = ''
|
||||
// check if the current file is a remote file or not
|
||||
if (uri.scheme === 'sourcegraph') {
|
||||
sourcegraphUrl = generateSourcegraphBlobLink(
|
||||
uri,
|
||||
editor.selection.start.line,
|
||||
editor.selection.start.character,
|
||||
editor.selection.end.line,
|
||||
editor.selection.end.character
|
||||
)
|
||||
} else {
|
||||
const repositoryInfo = await repoInfo(editor.document.uri.fsPath)
|
||||
if (!repositoryInfo) {
|
||||
await vscode.window.showErrorMessage('Cannot get git info for this repository.')
|
||||
return
|
||||
}
|
||||
let { remoteURL, branch, fileRelative } = repositoryInfo
|
||||
// construct sourcegraph url for current file
|
||||
// Ask if user want to open file in HEAD instead if set current branch or default branch
|
||||
// do not exist on Sourcegraph
|
||||
if (!branch) {
|
||||
const userChoice = await vscode.window.showInformationMessage(
|
||||
'Current (or default) branch does not exist on Sourcegraph. Publish your branch or continue to main branch.',
|
||||
'Continue to main',
|
||||
'Cancel'
|
||||
)
|
||||
branch = userChoice === 'Continue to main' ? 'HEAD' : ''
|
||||
if (!branch) {
|
||||
return
|
||||
}
|
||||
}
|
||||
sourcegraphUrl = getSourcegraphFileUrl(instanceUrl, remoteURL, branch, fileRelative, editor)
|
||||
}
|
||||
// Decode URI
|
||||
const decodedUri = decodeURIComponent(sourcegraphUrl)
|
||||
// Log redirect events
|
||||
logRedirectEvent(sourcegraphUrl)
|
||||
// Open in browser or Copy file link
|
||||
switch (action) {
|
||||
case 'open': {
|
||||
await vscode.env.openExternal(vscode.Uri.parse(decodedUri))
|
||||
break
|
||||
}
|
||||
case 'copy': {
|
||||
await env.clipboard.writeText(decodedUri).then(() => vscode.window.showInformationMessage('Copied!'))
|
||||
break
|
||||
}
|
||||
default: {
|
||||
throw new Error(`Failed to ${action} file link: invalid URL`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,47 +0,0 @@
|
||||
import vscode, { env } from 'vscode'
|
||||
|
||||
import { generateSourcegraphBlobLink } from './initialize'
|
||||
|
||||
/**
|
||||
* browser Actions for Web does not run node modules to get git info
|
||||
* Open active file in the browser on the configured Sourcegraph instance.
|
||||
*/
|
||||
export async function browserActions(action: string, logRedirectEvent: (uri: string) => void): Promise<void> {
|
||||
const editor = vscode.window.activeTextEditor
|
||||
if (!editor) {
|
||||
throw new Error('No active editor')
|
||||
}
|
||||
const uri = editor.document.uri
|
||||
const instanceUrl = vscode.workspace.getConfiguration('sourcegraph').get('url')
|
||||
let sourcegraphUrl = String()
|
||||
// check if the current file is a remote file or not
|
||||
if (uri.scheme === 'sourcegraph') {
|
||||
sourcegraphUrl = generateSourcegraphBlobLink(
|
||||
uri,
|
||||
editor.selection.start.line,
|
||||
editor.selection.start.character,
|
||||
editor.selection.end.line,
|
||||
editor.selection.end.character
|
||||
)
|
||||
} else if (uri.authority === 'github' && typeof instanceUrl === 'string') {
|
||||
// For remote github files
|
||||
const repoInfo = uri.fsPath.split('/')
|
||||
const repositoryName = `${repoInfo[1]}/${repoInfo[2]}`
|
||||
const filePath = repoInfo.length === 4 ? repoInfo[3] : repoInfo.slice(3).join('/')
|
||||
sourcegraphUrl = `${instanceUrl}github.com/${repositoryName}/-/blob/${filePath || ''}`
|
||||
} else {
|
||||
await vscode.window.showInformationMessage('Non-Remote files are not supported on VS Code Web currently')
|
||||
}
|
||||
// Log redirect events
|
||||
logRedirectEvent(sourcegraphUrl)
|
||||
|
||||
// Open in browser or Copy file link
|
||||
if (action === 'open' && sourcegraphUrl) {
|
||||
await vscode.env.openExternal(vscode.Uri.parse(sourcegraphUrl))
|
||||
} else if (action === 'copy' && sourcegraphUrl) {
|
||||
const decodedUri = decodeURIComponent(sourcegraphUrl)
|
||||
await env.clipboard.writeText(decodedUri).then(() => vscode.window.showInformationMessage('Copied!'))
|
||||
} else {
|
||||
throw new Error(`Failed to ${action} file link: invalid URL`)
|
||||
}
|
||||
}
|
||||
@ -1,268 +0,0 @@
|
||||
import * as path from 'path'
|
||||
|
||||
import execa from 'execa'
|
||||
import vscode, { type TextEditor } from 'vscode'
|
||||
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import { version } from '../../package.json'
|
||||
import { requestGraphQLFromVSCode } from '../backend/requestGraphQl'
|
||||
import { log } from '../log'
|
||||
|
||||
interface RepositoryInfo extends Branch, RemoteName {
|
||||
/** Git repository remote URL */
|
||||
remoteURL: string
|
||||
|
||||
/** File path relative to the repository root */
|
||||
fileRelative: string
|
||||
}
|
||||
|
||||
export type GitHelpers = typeof gitHelpers
|
||||
|
||||
export interface RemoteName {
|
||||
/**
|
||||
* Remote name of the upstream repository,
|
||||
* or the first found remote name if no upstream is found
|
||||
*/
|
||||
remoteName: string
|
||||
}
|
||||
|
||||
export interface Branch {
|
||||
/**
|
||||
* Remote branch name, or 'HEAD' if it isn't found because
|
||||
* e.g. detached HEAD state, upstream branch points to a local branch
|
||||
*/
|
||||
branch: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Git repository remote URL, the current branch, and the file path
|
||||
* relative to the repository root. Returns undefined if no remote is found
|
||||
*/
|
||||
export async function repoInfo(filePath: string): Promise<RepositoryInfo | undefined> {
|
||||
try {
|
||||
// Determine repository root directory.
|
||||
const fileDirectory = path.dirname(filePath)
|
||||
const repoRoot = await gitHelpers.rootDirectory(fileDirectory)
|
||||
// Determine file path relative to repository root, then replace slashes
|
||||
// as \\ does not work in Sourcegraphl links
|
||||
const fileRelative = filePath.slice(repoRoot.length + 1).replaceAll('\\', '/')
|
||||
let { branch, remoteName } = await gitRemoteNameAndBranch(repoRoot, gitHelpers, log)
|
||||
const remoteURL = await gitRemoteUrlWithReplacements(repoRoot, remoteName, gitHelpers, log)
|
||||
// check if the default branch or branch exist remotely
|
||||
branch = (await isOnSourcegraph(remoteURL, getDefaultBranch() || branch)) ? getDefaultBranch() || branch : ''
|
||||
return { remoteURL, branch, fileRelative, remoteName }
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export async function gitRemoteNameAndBranch(
|
||||
repoDirectory: string,
|
||||
git: Pick<GitHelpers, 'branch' | 'remotes' | 'upstreamAndBranch'>,
|
||||
log?: {
|
||||
appendLine: (value: string) => void
|
||||
}
|
||||
): Promise<RemoteName & Branch> {
|
||||
let remoteName: string | undefined
|
||||
|
||||
// Used to determine which part of upstreamAndBranch is the remote name, or as fallback if no upstream is set
|
||||
const remotes = await git.remotes(repoDirectory)
|
||||
const branch = await git.branch(repoDirectory)
|
||||
|
||||
try {
|
||||
const upstreamAndBranch = await git.upstreamAndBranch(repoDirectory)
|
||||
// Subtract $BRANCH_NAME from $UPSTREAM_REMOTE/$BRANCH_NAME.
|
||||
// We can't just split on the delineating `/`, since refnames can include `/`:
|
||||
// https://sourcegraph.com/github.com/git/git@454cb6bd52a4de614a3633e4f547af03d5c3b640/-/blob/refs.c#L52-67
|
||||
|
||||
// Example:
|
||||
// stdout: remote/two/tj/feature
|
||||
// remoteName: remote/two, branch: tj/feature
|
||||
|
||||
const branchPosition = upstreamAndBranch.lastIndexOf(branch)
|
||||
const maybeRemote = upstreamAndBranch.slice(0, branchPosition - 1)
|
||||
if (branchPosition !== -1 && maybeRemote) {
|
||||
remoteName = maybeRemote
|
||||
}
|
||||
} catch {
|
||||
// noop. upstream may not be set
|
||||
}
|
||||
|
||||
// If we cannot find the remote name from the branch name, we use the remote list in this order:
|
||||
// - "upstream"
|
||||
// - "origin"
|
||||
// - the first remote alphabetically
|
||||
if (!remoteName && remotes.length > 0) {
|
||||
if (remotes.includes('upstream')) {
|
||||
remoteName = 'upstream'
|
||||
} else if (remotes.includes('origin')) {
|
||||
remoteName = 'origin'
|
||||
} else {
|
||||
log?.appendLine(`no upstream found, using first git remote: ${remotes[0]}`)
|
||||
remoteName = remotes[0]
|
||||
}
|
||||
}
|
||||
|
||||
// Throw if a remote still isn't found
|
||||
if (!remoteName) {
|
||||
throw new Error('no configured git remotes')
|
||||
}
|
||||
|
||||
return { remoteName, branch }
|
||||
}
|
||||
|
||||
export const gitHelpers = {
|
||||
/**
|
||||
* Returns the repository root directory for any directory within the
|
||||
* repository.
|
||||
*/
|
||||
async rootDirectory(repoDirectory: string): Promise<string> {
|
||||
const { stdout } = await execa('git', ['rev-parse', '--show-toplevel'], { cwd: repoDirectory })
|
||||
return stdout
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the names of all git remotes, e.g. ["origin", "foobar"]
|
||||
*/
|
||||
async remotes(repoDirectory: string): Promise<string[]> {
|
||||
const { stdout } = await execa('git', ['remote'], { cwd: repoDirectory })
|
||||
return stdout.split('\n')
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the remote URL for the given remote name.
|
||||
* e.g. `origin` -> `git@github.com:foo/bar`
|
||||
*/
|
||||
async remoteUrl(remoteName: string, repoDirectory: string): Promise<string> {
|
||||
const { stdout } = await execa('git', ['remote', 'get-url', remoteName], { cwd: repoDirectory })
|
||||
return stdout
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns either the current branch name of the repository OR in all
|
||||
* other cases (e.g. detached HEAD state), it returns "HEAD".
|
||||
*/
|
||||
async branch(repoDirectory: string): Promise<string> {
|
||||
const { stdout } = await execa('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repoDirectory })
|
||||
return stdout
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a string in the format $UPSTREAM_REMOTE/$BRANCH_NAME, e.g. "origin/branch-name", throws if not found
|
||||
*/
|
||||
async upstreamAndBranch(repoDirectory: string): Promise<string> {
|
||||
const { stdout } = await execa('git', ['rev-parse', '--abbrev-ref', 'HEAD@{upstream}'], { cwd: repoDirectory })
|
||||
return stdout
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the remote URL for the given remote name with remote URL replacements.
|
||||
* e.g. `origin` -> `git@github.com:foo/bar`
|
||||
*/
|
||||
export async function gitRemoteUrlWithReplacements(
|
||||
repoDirectory: string,
|
||||
remoteName: string,
|
||||
gitHelpers: Pick<GitHelpers, 'remoteUrl'>,
|
||||
log?: { appendLine: (value: string) => void }
|
||||
): Promise<string> {
|
||||
let stdout = await gitHelpers.remoteUrl(remoteName, repoDirectory)
|
||||
const replacementsList = getRemoteUrlReplacements()
|
||||
|
||||
const stdoutBefore = stdout
|
||||
|
||||
for (const replacement in replacementsList) {
|
||||
if (typeof replacement === 'string') {
|
||||
stdout = stdout.replace(replacement, replacementsList[replacement])
|
||||
}
|
||||
}
|
||||
|
||||
log?.appendLine(`${stdoutBefore} became ${stdout}`)
|
||||
return stdout
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses editor endpoint to construct sourcegraph file URL
|
||||
*/
|
||||
export function getSourcegraphFileUrl(
|
||||
SourcegraphUrl: string,
|
||||
remoteURL: string,
|
||||
branch: string,
|
||||
fileRelative: string,
|
||||
editor: TextEditor
|
||||
): string {
|
||||
const parameters = {
|
||||
remote_url: encodeURIComponent(remoteURL),
|
||||
branch: encodeURIComponent(branch),
|
||||
file: encodeURIComponent(fileRelative),
|
||||
editor: encodeURIComponent('VSCode'),
|
||||
version: encodeURIComponent(version),
|
||||
start_row: encodeURIComponent(String(editor.selection.start.line)),
|
||||
start_col: encodeURIComponent(String(editor.selection.start.character)),
|
||||
end_row: encodeURIComponent(String(editor.selection.end.line)),
|
||||
end_col: encodeURIComponent(String(editor.selection.end.character)),
|
||||
}
|
||||
const uri = new URL('/-/editor', SourcegraphUrl)
|
||||
const parametersString = new URLSearchParams({ ...parameters }).toString()
|
||||
uri.search = parametersString
|
||||
return uri.href
|
||||
}
|
||||
|
||||
function getRemoteUrlReplacements(): Record<string, string> {
|
||||
// has default value
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const replacements = vscode.workspace
|
||||
.getConfiguration('sourcegraph')
|
||||
.get<Record<string, string>>('remoteUrlReplacements')!
|
||||
return replacements
|
||||
}
|
||||
|
||||
export function getDefaultBranch(): string {
|
||||
// has default value
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return vscode.workspace.getConfiguration('sourcegraph').get<string>('defaultBranch')!
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if branch exists on Sourcegraph instance
|
||||
* Return 'HEAD' if it does not exists remotely
|
||||
*/
|
||||
export async function isOnSourcegraph(remoteURL: string, currentBranch: string): Promise<boolean> {
|
||||
const repoNameRegex = /(\w+(:\/\/|@))(.+@)*([\w.]+)(:?)(\d+){0,1}\/*(.*)(\.git)(\/)?/
|
||||
const repoNameRegexMatches = remoteURL.match(repoNameRegex)
|
||||
const repoName =
|
||||
repoNameRegexMatches?.[4] && repoNameRegexMatches?.[7]
|
||||
? repoNameRegexMatches?.[4] + '/' + repoNameRegexMatches?.[7]
|
||||
: remoteURL.replace('git@', '').replace('https://', '').replace('.git', '').replace(':', '/')
|
||||
const isOnSourcegraph = await requestGraphQLFromVSCode<CheckBranchResult>(checkBranchQuery, {
|
||||
repoName,
|
||||
branchName: currentBranch,
|
||||
})
|
||||
.then(response => response.data?.repository.branches.nodes)
|
||||
.then(nodes => nodes?.filter(branch => branch.name.replace('refs/heads/', '') === currentBranch))
|
||||
.then(filtered => filtered?.length === 1)
|
||||
.catch(error => console.error(error))
|
||||
console.log(isOnSourcegraph)
|
||||
return isOnSourcegraph || false
|
||||
}
|
||||
|
||||
const checkBranchQuery = gql`
|
||||
query CheckBranch($repoName: String!, $branchName: String) {
|
||||
repository(name: $repoName) {
|
||||
branches(query: $branchName) {
|
||||
nodes {
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
interface CheckBranchResult {
|
||||
repository: {
|
||||
branches: {
|
||||
nodes: { name: string }[]
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,86 +0,0 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
import type { EventSource } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { version } from '../../package.json'
|
||||
import { logEvent } from '../backend/eventLogger'
|
||||
import { SourcegraphUri } from '../file-system/SourcegraphUri'
|
||||
import { type LocalStorageService, ANONYMOUS_USER_ID_KEY } from '../settings/LocalStorageService'
|
||||
|
||||
import { browserActions } from './browserActionsNode'
|
||||
|
||||
export function initializeCodeSharingCommands(
|
||||
context: vscode.ExtensionContext,
|
||||
eventSourceType: EventSource,
|
||||
localStorageService: LocalStorageService
|
||||
): void {
|
||||
// Open local file or remote Sourcegraph file in browser
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.openInBrowser', async () => {
|
||||
await browserActions('open', logRedirectEvent)
|
||||
})
|
||||
)
|
||||
// Copy Sourcegraph link to file
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.copyFileLink', async () => {
|
||||
await browserActions('copy', logRedirectEvent)
|
||||
})
|
||||
)
|
||||
// Search Selected Text in Sourcegraph Search Tab
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.selectionSearchWeb', async () => {
|
||||
const instanceUrl =
|
||||
vscode.workspace.getConfiguration('sourcegraph').get<string>('url') || 'https://sourcegraph.com'
|
||||
const editor = vscode.window.activeTextEditor
|
||||
const selectedQuery = editor?.document.getText(editor.selection)
|
||||
if (!editor || !selectedQuery) {
|
||||
throw new Error('No selection detected')
|
||||
}
|
||||
const uri = `${instanceUrl}/search?q=context:global+${encodeURIComponent(
|
||||
selectedQuery
|
||||
)}&patternType=literal`
|
||||
await vscode.env.openExternal(vscode.Uri.parse(uri))
|
||||
})
|
||||
)
|
||||
// Log Redirect Event
|
||||
function logRedirectEvent(sourcegraphUrl: string): void {
|
||||
const userEventVariables = {
|
||||
event: 'IDERedirected',
|
||||
userCookieID: localStorageService.getValue(ANONYMOUS_USER_ID_KEY),
|
||||
referrer: 'VSCE',
|
||||
url: sourcegraphUrl,
|
||||
source: eventSourceType,
|
||||
argument: JSON.stringify({ editor: 'vscode', version }),
|
||||
}
|
||||
logEvent(userEventVariables)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a link to a blob on a Sourcegraph instance.
|
||||
*
|
||||
* @param uri - The VSCode URI of the blob.
|
||||
* @param startLine - The zero-based line value.
|
||||
* @param startChar - The zero-based character value.
|
||||
* @param endLine - The zero-based line value.
|
||||
* @param endChar - The zero-based character value.
|
||||
*/
|
||||
export function generateSourcegraphBlobLink(
|
||||
uri: vscode.Uri,
|
||||
startLine: number,
|
||||
startChar: number,
|
||||
endLine: number,
|
||||
endChar: number
|
||||
): string {
|
||||
const instanceUrl = new URL(
|
||||
vscode.workspace.getConfiguration('sourcegraph').get<string>('url') || 'https://sourcegraph.com'
|
||||
)
|
||||
// Using SourcegraphUri.parse to properly decode repo revision
|
||||
const decodedUri = SourcegraphUri.parse(uri.toString())
|
||||
const finalUri = new URL(decodedUri.uri)
|
||||
// Sourcegraph expects 1-based line and character values
|
||||
finalUri.search = `L${encodeURIComponent(String(startLine + 1))}:${encodeURIComponent(
|
||||
String(startChar + 1)
|
||||
)}-${encodeURIComponent(String(endLine + 1))}:${encodeURIComponent(String(endChar + 1))}`
|
||||
return finalUri.href.replace(finalUri.protocol, instanceUrl.protocol)
|
||||
}
|
||||
@ -1,59 +0,0 @@
|
||||
/**
|
||||
* All Sourcegraph Cloud related links
|
||||
* MAIN
|
||||
*/
|
||||
export const VSCE_LINK_DOTCOM = 'https://sourcegraph.com'
|
||||
export const VSCE_LINK_TOKEN_CALLBACK =
|
||||
'https://sourcegraph.com/sign-in?returnTo=user/settings/tokens/new/callback?requestFrom=VSCEAUTH'
|
||||
export const VSCE_LINK_TOKEN_CALLBACK_TEST =
|
||||
'https://sourcegraph.test:3443/sign-in?returnTo=user/settings/tokens/new/callback?requestFrom=VSCEAUTH'
|
||||
/**
|
||||
* UNRELEASED FEATURE
|
||||
* Token Callback Page
|
||||
*/
|
||||
// const VSCE_CALLBACK_CODE = 'VSCEAUTH'
|
||||
// const VSCE_LINK_PARAMS_TOKEN_REDIRECT = {
|
||||
// returnTo: `user/settings/tokens/new/callback?requestFrom=${VSCE_CALLBACK_CODE}`,
|
||||
// }
|
||||
/**
|
||||
* Params
|
||||
*/
|
||||
export const VSCE_SIDEBAR_PARAMS = '?utm_medium=VSCODE&utm_source=sidebar&utm_campaign=vsce-sign-up&utm_content=sign-up'
|
||||
const VSCE_LINK_PARAMS_TOKEN_REDIRECT = {
|
||||
returnTo: 'user/settings/tokens/new',
|
||||
}
|
||||
const VSCE_LINK_PARAMS_EDITOR = { editor: 'vscode' }
|
||||
// UTM for Sidebar actions
|
||||
const VSCE_LINK_PARAMS_UTM_SIDEBAR = {
|
||||
utm_campaign: 'vsce-sign-up',
|
||||
utm_medium: 'VSCODE',
|
||||
utm_source: 'sidebar',
|
||||
utm_content: 'sign-up',
|
||||
}
|
||||
// MISC
|
||||
export const VSCE_LINK_MARKETPLACE = 'https://marketplace.visualstudio.com/items?itemName=sourcegraph.sourcegraph'
|
||||
export const VSCE_LINK_USER_DOCS =
|
||||
'https://docs.sourcegraph.com/cli/how-tos/creating_an_access_token' + VSCE_SIDEBAR_PARAMS
|
||||
export const VSCE_LINK_FEEDBACK = 'https://github.com/sourcegraph/sourcegraph/discussions/categories/feedback'
|
||||
export const VSCE_LINK_ISSUES =
|
||||
'https://github.com/sourcegraph/sourcegraph/issues/new?labels=team/integrations,vscode-extension&title=VSCode+Bug+report:+&projects=Integrations%20Project%20Board'
|
||||
export const VSCE_LINK_TROUBLESHOOT =
|
||||
'https://docs.sourcegraph.com/admin/how-to/troubleshoot-sg-extension#vs-code-extension'
|
||||
export const VSCE_SG_LOGOMARK_LIGHT =
|
||||
'https://raw.githubusercontent.com/sourcegraph/sourcegraph/fd431743e811ba756490e5e7bd88aa2362b6453e/client/vscode/images/logomark_light.svg'
|
||||
export const VSCE_SG_LOGOMARK_DARK =
|
||||
'https://raw.githubusercontent.com/sourcegraph/sourcegraph/2636c64c9f323d78281a68dd4bdf432d9a97835a/client/vscode/images/logomark_dark.svg'
|
||||
export const VSCE_LINK_SIGNUP = 'https://about.sourcegraph.com/get-started/cloud' + VSCE_SIDEBAR_PARAMS
|
||||
|
||||
// Generate sign-in and sign-up links using the above params
|
||||
export const VSCE_LINK_AUTH = (mode: 'sign-in' | 'sign-up'): string => {
|
||||
const uri = new URL(VSCE_LINK_DOTCOM)
|
||||
const parameters = new URLSearchParams({
|
||||
...VSCE_LINK_PARAMS_UTM_SIDEBAR,
|
||||
...VSCE_LINK_PARAMS_EDITOR,
|
||||
...VSCE_LINK_PARAMS_TOKEN_REDIRECT,
|
||||
}).toString()
|
||||
uri.pathname = mode
|
||||
uri.search = parameters
|
||||
return uri.href
|
||||
}
|
||||
@ -1,79 +0,0 @@
|
||||
import type { GraphQLResult } from '@sourcegraph/http-client'
|
||||
import type { FlatExtensionHostAPI } from '@sourcegraph/shared/src/api/contract'
|
||||
import type { ProxySubscribable } from '@sourcegraph/shared/src/api/extension/api/common'
|
||||
import type { ViewerData, ViewerId } from '@sourcegraph/shared/src/api/viewerTypes'
|
||||
import type { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import type { EventSource } from '@sourcegraph/shared/src/graphql-operations'
|
||||
import type { SearchMatch, StreamSearchOptions } from '@sourcegraph/shared/src/search/stream'
|
||||
import type { SettingsCascadeOrError } from '@sourcegraph/shared/src/settings/settings'
|
||||
|
||||
import type { Event } from './graphql-operations'
|
||||
import type { VSCEQueryState, VSCEState, VSCEStateMachine } from './state'
|
||||
|
||||
export interface ExtensionCoreAPI {
|
||||
/** For search panel webview to signal that it is ready for messages. */
|
||||
panelInitialized: (panelId: string) => void
|
||||
|
||||
requestGraphQL: (
|
||||
request: string,
|
||||
variables: any,
|
||||
overrideAccessToken?: string,
|
||||
overrideSourcegraphURL?: string
|
||||
) => Promise<GraphQLResult<any>>
|
||||
observeSourcegraphSettings: () => ProxySubscribable<SettingsCascadeOrError>
|
||||
getAuthenticatedUser: () => ProxySubscribable<AuthenticatedUser | null>
|
||||
/** Endpoint settings */
|
||||
getInstanceURL: () => ProxySubscribable<string>
|
||||
getAccessToken: Promise<string | undefined>
|
||||
removeAccessToken: () => Promise<void>
|
||||
setEndpointUri: (accessToken: string, uri: string) => Promise<void>
|
||||
/**
|
||||
* Observe search box query state.
|
||||
* Used to send current query from panel to sidebar.
|
||||
*
|
||||
* v1 Debt: Transient query state isn't stored in state machine for performance
|
||||
* as it would lead to re-rendering the whole search panel on each keystroke.
|
||||
* Implement selector system w/ key path for state machine. Alternatively,
|
||||
* aggressively memoize top-level "View" components (i.e. don't just take whole state as prop).
|
||||
*/
|
||||
observePanelQueryState: () => ProxySubscribable<VSCEQueryState>
|
||||
/** State Management*/
|
||||
observeState: () => ProxySubscribable<VSCEState>
|
||||
emit: VSCEStateMachine['emit']
|
||||
/** Opens a remote file given a serialized SourcegraphUri */
|
||||
openSourcegraphFile: (uri: string) => Promise<void>
|
||||
openLink: (uri: string) => Promise<void>
|
||||
copyLink: (uri: string) => Promise<void>
|
||||
reloadWindow: () => void
|
||||
focusSearchPanel: () => void
|
||||
/** Cancels previous search when called. */
|
||||
streamSearch: (query: string, options: StreamSearchOptions) => void
|
||||
fetchStreamSuggestions: (query: string, sourcegraphURL: string) => ProxySubscribable<SearchMatch[]>
|
||||
setSelectedSearchContextSpec: (spec: string) => void
|
||||
/** Used to send current query from panel to sidebar. */
|
||||
setSidebarQueryState: (queryState: VSCEQueryState) => void
|
||||
/** Local Storage Item */
|
||||
getLocalStorageItem: (key: string) => string
|
||||
setLocalStorageItem: (key: string, value: string) => Promise<boolean>
|
||||
/** For Telemetry Service / logging */
|
||||
logEvents: (variables: Event) => void
|
||||
/** Get EventSource Type to use based on instance version */
|
||||
getEventSource: EventSource
|
||||
/** Get EventSource Type to use based on instance version */
|
||||
getEditorTheme: string
|
||||
}
|
||||
|
||||
export interface SearchPanelAPI {
|
||||
ping: () => ProxySubscribable<'pong'>
|
||||
|
||||
focusSearchBox: () => void
|
||||
}
|
||||
|
||||
export interface SearchSidebarAPI
|
||||
extends Pick<FlatExtensionHostAPI, 'addTextDocumentIfNotExists' | 'getDefinition' | 'getHover' | 'getReferences'> {
|
||||
ping: () => ProxySubscribable<'pong'>
|
||||
|
||||
addViewerIfNotExists: (viewer: ViewerData) => Promise<ViewerId>
|
||||
}
|
||||
|
||||
export interface HelpSidebarAPI {}
|
||||
@ -1,126 +0,0 @@
|
||||
import { of, ReplaySubject } from 'rxjs'
|
||||
import vscode from 'vscode'
|
||||
|
||||
import { proxySubscribable } from '@sourcegraph/shared/src/api/extension/api/common'
|
||||
import polyfillEventSource from '@sourcegraph/shared/src/polyfills/vendor/eventSource'
|
||||
import { fetchStreamSuggestions } from '@sourcegraph/shared/src/search/suggestions'
|
||||
|
||||
import { observeAuthenticatedUser } from './backend/authenticatedUser'
|
||||
import { logEvent } from './backend/eventLogger'
|
||||
import { getProxyAgent } from './backend/fetch'
|
||||
import { initializeInstanceVersionNumber } from './backend/instanceVersion'
|
||||
import { requestGraphQLFromVSCode } from './backend/requestGraphQl'
|
||||
import { initializeSearchContexts } from './backend/searchContexts'
|
||||
import { initializeSourcegraphSettings } from './backend/sourcegraphSettings'
|
||||
import { createStreamSearch } from './backend/streamSearch'
|
||||
import { initializeCodeSharingCommands } from './commands/initialize'
|
||||
import type { ExtensionCoreAPI } from './contract'
|
||||
import { openSourcegraphUriCommand } from './file-system/commands'
|
||||
import { initializeSourcegraphFileSystem } from './file-system/initialize'
|
||||
import { SourcegraphUri } from './file-system/SourcegraphUri'
|
||||
import type { Event } from './graphql-operations'
|
||||
import { accessTokenSetting, processOldToken } from './settings/accessTokenSetting'
|
||||
import { endpointRequestHeadersSetting, endpointSetting } from './settings/endpointSetting'
|
||||
import { invalidateContextOnSettingsChange } from './settings/invalidation'
|
||||
import { LocalStorageService, SELECTED_SEARCH_CONTEXT_SPEC_KEY } from './settings/LocalStorageService'
|
||||
import { watchUninstall } from './settings/uninstall'
|
||||
import { createVSCEStateMachine, type VSCEQueryState } from './state'
|
||||
import { copySourcegraphLinks, focusSearchPanel, openSourcegraphLinks, registerWebviews } from './webview/commands'
|
||||
import { scretTokenKey, SourcegraphAuthActions, SourcegraphAuthProvider } from './webview/platform/AuthProvider'
|
||||
|
||||
/**
|
||||
* See CONTRIBUTING docs for the Architecture Diagram
|
||||
*/
|
||||
export async function activate(context: vscode.ExtensionContext): Promise<void> {
|
||||
const secretStorage = context.secrets
|
||||
// Register SourcegraphAuthProvider
|
||||
context.subscriptions.push(
|
||||
vscode.authentication.registerAuthenticationProvider(
|
||||
endpointSetting(),
|
||||
scretTokenKey,
|
||||
new SourcegraphAuthProvider(secretStorage)
|
||||
)
|
||||
)
|
||||
await processOldToken(secretStorage)
|
||||
const initialInstanceURL = endpointSetting()
|
||||
const initialAccessToken = await secretStorage.get(scretTokenKey)
|
||||
const createIfNone = initialAccessToken ? { createIfNone: true } : { createIfNone: false }
|
||||
const session = await vscode.authentication.getSession(endpointSetting(), [], createIfNone)
|
||||
const authenticatedUser = observeAuthenticatedUser(secretStorage)
|
||||
const localStorageService = new LocalStorageService(context.globalState)
|
||||
const stateMachine = createVSCEStateMachine({ localStorageService })
|
||||
invalidateContextOnSettingsChange({ context, stateMachine })
|
||||
initializeSearchContexts({ localStorageService, stateMachine, context })
|
||||
const sourcegraphSettings = initializeSourcegraphSettings({ context })
|
||||
const editorTheme = vscode.ColorThemeKind[vscode.window.activeColorTheme.kind]
|
||||
const eventSourceType = initializeInstanceVersionNumber(localStorageService, initialAccessToken, initialInstanceURL)
|
||||
// Sets global `EventSource` for Node, which is required for streaming search.
|
||||
// Add custom headers to `EventSource` Authorization header when provided
|
||||
const customHeaders = endpointRequestHeadersSetting()
|
||||
polyfillEventSource(
|
||||
initialAccessToken ? { Authorization: `token ${initialAccessToken}`, ...customHeaders } : {},
|
||||
getProxyAgent()
|
||||
)
|
||||
|
||||
// For search panel webview to signal that it is ready for messages.
|
||||
// Replay subject with large buffer size just in case panels are opened in quick succession.
|
||||
const initializedPanelIDs = new ReplaySubject<string>(7)
|
||||
// Used to observe search box query state from sidebar
|
||||
const sidebarQueryStates = new ReplaySubject<VSCEQueryState>(1)
|
||||
// Use for file tree panel
|
||||
const { fs } = initializeSourcegraphFileSystem({ context, initialInstanceURL })
|
||||
// Use api endpoint for stream search
|
||||
const streamSearch = createStreamSearch({
|
||||
context,
|
||||
stateMachine,
|
||||
sourcegraphURL: `${initialInstanceURL}/.api`,
|
||||
session,
|
||||
})
|
||||
const authActions = new SourcegraphAuthActions(secretStorage)
|
||||
const extensionCoreAPI: ExtensionCoreAPI = {
|
||||
panelInitialized: panelId => initializedPanelIDs.next(panelId),
|
||||
observeState: () => proxySubscribable(stateMachine.observeState()),
|
||||
observePanelQueryState: () => proxySubscribable(sidebarQueryStates.asObservable()),
|
||||
emit: event => stateMachine.emit(event),
|
||||
requestGraphQL: requestGraphQLFromVSCode,
|
||||
observeSourcegraphSettings: () => proxySubscribable(sourcegraphSettings.settings),
|
||||
// Debt: converting Promises into Observables for ease of use with
|
||||
// `useObservable` hook. Add `usePromise`s hook to fix.
|
||||
getAuthenticatedUser: () => proxySubscribable(authenticatedUser),
|
||||
getInstanceURL: () => proxySubscribable(of(initialInstanceURL)),
|
||||
openSourcegraphFile: (uri: string) => openSourcegraphUriCommand(fs, SourcegraphUri.parse(uri)),
|
||||
openLink: uri => openSourcegraphLinks(uri),
|
||||
copyLink: uri => copySourcegraphLinks(uri),
|
||||
getAccessToken: accessTokenSetting(context.secrets),
|
||||
removeAccessToken: () => authActions.logout(),
|
||||
setEndpointUri: (accessToken, uri) => authActions.login(accessToken, uri),
|
||||
reloadWindow: () => vscode.commands.executeCommand('workbench.action.reloadWindow'),
|
||||
focusSearchPanel,
|
||||
streamSearch,
|
||||
fetchStreamSuggestions: (query, sourcegraphURL) =>
|
||||
// Use api endpoint for stream search
|
||||
proxySubscribable(fetchStreamSuggestions(query, `${sourcegraphURL}/.api`)),
|
||||
setSelectedSearchContextSpec: spec => {
|
||||
stateMachine.emit({ type: 'set_selected_search_context_spec', spec })
|
||||
return localStorageService.setValue(SELECTED_SEARCH_CONTEXT_SPEC_KEY, spec)
|
||||
},
|
||||
setSidebarQueryState: sidebarQueryState => sidebarQueryStates.next(sidebarQueryState),
|
||||
getLocalStorageItem: key => localStorageService.getValue(key),
|
||||
setLocalStorageItem: (key: string, value: string) => localStorageService.setValue(key, value),
|
||||
logEvents: (variables: Event) => logEvent(variables),
|
||||
getEventSource: eventSourceType,
|
||||
getEditorTheme: editorTheme,
|
||||
}
|
||||
// Also initializes code intel.
|
||||
registerWebviews({
|
||||
context,
|
||||
extensionCoreAPI,
|
||||
initializedPanelIDs,
|
||||
sourcegraphSettings,
|
||||
fs,
|
||||
instanceURL: initialInstanceURL,
|
||||
})
|
||||
initializeCodeSharingCommands(context, eventSourceType, localStorageService)
|
||||
// Watch for uninstall to log uninstall event
|
||||
watchUninstall(eventSourceType, localStorageService)
|
||||
}
|
||||
@ -1,114 +0,0 @@
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
/**
|
||||
* Helper class to represent a flat list of relative file paths (type `string[]`) as a hierarchical file tree.
|
||||
*/
|
||||
export class FileTree {
|
||||
constructor(public readonly uri: SourcegraphUri, public readonly files: string[]) {
|
||||
files.sort()
|
||||
}
|
||||
|
||||
public toString(): string {
|
||||
return `FileTree(${this.uri.uri}, files.length=${this.files.length})`
|
||||
}
|
||||
|
||||
public directChildren(directory: string): string[] {
|
||||
return this.directChildrenInternal(directory, true)
|
||||
}
|
||||
|
||||
private directChildrenInternal(directory: string, allowRecursion: boolean): string[] {
|
||||
const depth = this.depth(directory)
|
||||
const directFiles = new Set<string>()
|
||||
const directDirectories = new Set<string>()
|
||||
const isRoot = directory === ''
|
||||
if (!isRoot && !directory.endsWith('/')) {
|
||||
directory = directory + '/'
|
||||
}
|
||||
let index = this.binarySearchDirectoryStart(directory)
|
||||
while (index < this.files.length) {
|
||||
const startIndex = index
|
||||
const file = this.files[index]
|
||||
if (file === '') {
|
||||
index++
|
||||
continue
|
||||
}
|
||||
if (file.startsWith(directory)) {
|
||||
const fileDepth = this.depth(file)
|
||||
const isFile = isRoot ? fileDepth === 0 : fileDepth === depth + 1
|
||||
let path = isFile ? file : file.slice(0, file.indexOf('/', directory.length))
|
||||
let nestedChildren = allowRecursion && !isFile ? this.directChildrenInternal(path, false) : []
|
||||
while (allowRecursion && nestedChildren.length === 1) {
|
||||
const child = SourcegraphUri.parse(nestedChildren[0])
|
||||
if (child.isDirectory()) {
|
||||
path = child.path || ''
|
||||
nestedChildren = this.directChildrenInternal(path, false)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
const uri = SourcegraphUri.fromParts(this.uri.host, this.uri.repositoryName, {
|
||||
revision: this.uri.revision,
|
||||
path,
|
||||
isDirectory: !isFile,
|
||||
}).uri
|
||||
if (isFile) {
|
||||
directFiles.add(uri)
|
||||
} else {
|
||||
index = this.binarySearchDirectoryEnd(path + '/', index + 1)
|
||||
directDirectories.add(uri)
|
||||
}
|
||||
}
|
||||
if (index === startIndex) {
|
||||
index++
|
||||
}
|
||||
}
|
||||
return [...directDirectories, ...directFiles]
|
||||
}
|
||||
|
||||
private binarySearchDirectoryStart(directory: string): number {
|
||||
if (directory === '') {
|
||||
return 0
|
||||
}
|
||||
return this.binarySearch(
|
||||
{ low: 0, high: this.files.length },
|
||||
midpoint => this.files[midpoint].localeCompare(directory) > 0
|
||||
)
|
||||
}
|
||||
|
||||
private binarySearchDirectoryEnd(directory: string, low: number): number {
|
||||
while (low < this.files.length && this.files[low].localeCompare(directory) <= 0) {
|
||||
low++
|
||||
}
|
||||
return this.binarySearch(
|
||||
{ low, high: this.files.length },
|
||||
midpoint => !this.files[midpoint].startsWith(directory)
|
||||
)
|
||||
}
|
||||
|
||||
private binarySearch({ low, high }: SearchRange, isGreater: (midpoint: number) => boolean): number {
|
||||
while (low < high) {
|
||||
const midpoint = Math.floor(low + (high - low) / 2)
|
||||
if (isGreater(midpoint)) {
|
||||
high = midpoint
|
||||
} else {
|
||||
low = midpoint + 1
|
||||
}
|
||||
}
|
||||
return high
|
||||
}
|
||||
|
||||
private depth(path: string): number {
|
||||
let result = 0
|
||||
for (const char of path) {
|
||||
if (char === '/') {
|
||||
result += 1
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
interface SearchRange {
|
||||
low: number
|
||||
high: number
|
||||
}
|
||||
@ -1,248 +0,0 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { log } from '../log'
|
||||
|
||||
import type { SourcegraphFileSystemProvider } from './SourcegraphFileSystemProvider'
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
export class FilesTreeDataProvider implements vscode.TreeDataProvider<string> {
|
||||
constructor(public readonly fs: SourcegraphFileSystemProvider) {
|
||||
fs.onDidDownloadRepositoryFilenames(() => this.didChangeTreeData.fire(undefined))
|
||||
}
|
||||
|
||||
private _isViewVisible = false
|
||||
private isExpandedNode = new Set<string>()
|
||||
private treeView: vscode.TreeView<string> | undefined
|
||||
private activeUri: vscode.Uri | undefined
|
||||
private selectedRepository: string | undefined
|
||||
private didFocusToken = new vscode.CancellationTokenSource()
|
||||
private treeItemCache = new Map<string, vscode.TreeItem>()
|
||||
private readonly didChangeTreeData = new vscode.EventEmitter<string | undefined>()
|
||||
public readonly onDidChangeTreeData: vscode.Event<string | undefined> = this.didChangeTreeData.event
|
||||
|
||||
public activeTextDocument(): SourcegraphUri | undefined {
|
||||
return this.activeUri && this.activeUri.scheme === 'sourcegraph'
|
||||
? this.fs.sourcegraphUri(this.activeUri)
|
||||
: undefined
|
||||
}
|
||||
public isViewVisible(): boolean {
|
||||
return this._isViewVisible
|
||||
}
|
||||
public setTreeView(treeView: vscode.TreeView<string>): void {
|
||||
this.treeView = treeView
|
||||
treeView.onDidChangeSelection(async event => {
|
||||
// Check if a repository is selected for removing purpose
|
||||
await this.isRepository(event.selection[0])
|
||||
})
|
||||
treeView.onDidChangeVisibility(async event => {
|
||||
const didBecomeVisible = !this._isViewVisible && event.visible
|
||||
this._isViewVisible = event.visible
|
||||
if (didBecomeVisible) {
|
||||
// NOTE: do not remove the line below even if you think it
|
||||
// doesn't have an effect. Before you remove this line, make
|
||||
// sure that the following steps don't cause the "Collapse All"
|
||||
// button to become disabled:
|
||||
// 1. Close "Files" view.
|
||||
// 2. Execute "Reload window" command.
|
||||
// 3. After VS Code loads, open the "Files" view.
|
||||
this.didChangeTreeData.fire(undefined)
|
||||
await this.didFocus(this.activeUri)
|
||||
}
|
||||
})
|
||||
treeView.onDidExpandElement(async event => {
|
||||
await this.isRepository(event.element)
|
||||
this.isExpandedNode.add(event.element)
|
||||
})
|
||||
treeView.onDidCollapseElement(async event => {
|
||||
await this.isRepository(event.element)
|
||||
this.isExpandedNode.delete(event.element)
|
||||
})
|
||||
}
|
||||
|
||||
public async isRepository(selectedUri: string): Promise<void> {
|
||||
const isRepo = [...this.fs.allRepositoryUris()].includes(selectedUri)
|
||||
this.selectedRepository = isRepo ? selectedUri : undefined
|
||||
await vscode.commands.executeCommand('setContext', 'sourcegraph.removeRepository', isRepo)
|
||||
}
|
||||
|
||||
public async getParent(uriString?: string): Promise<string | undefined> {
|
||||
// log.appendLine(`getParent(${uriString})`)
|
||||
try {
|
||||
// Implementation note: this method is not implemented as
|
||||
// `SourcegraphUri.parse(uri).parentUri()` because that would return
|
||||
// URIs to directories that don't exist because they have no siblings
|
||||
// and are therefore automatically merged with their parent. For example,
|
||||
// imagine the following folder structure:
|
||||
// .gitignore
|
||||
// .github/workflows/ci.yml
|
||||
// src/command.ts
|
||||
// src/browse.ts
|
||||
// The parent of `.github/workflows/ci.yml` is `.github/` because the `workflows/`
|
||||
// directory has no sibling.
|
||||
if (!uriString) {
|
||||
return undefined
|
||||
}
|
||||
const uri = SourcegraphUri.parse(uriString)
|
||||
if (!uri.path) {
|
||||
return undefined
|
||||
}
|
||||
let ancestor: string | undefined = uri.repositoryUri()
|
||||
let children = await this.getChildren(ancestor)
|
||||
while (ancestor) {
|
||||
const isParent = children?.includes(uriString)
|
||||
if (isParent) {
|
||||
break
|
||||
}
|
||||
ancestor = children?.find(childUri => {
|
||||
const child = SourcegraphUri.parse(childUri)
|
||||
return child.path && uri.path?.startsWith(child.path + '/')
|
||||
})
|
||||
if (!ancestor) {
|
||||
log.errorAndThrow(`getParent(${uriString || 'undefined'}) nothing startsWith`)
|
||||
}
|
||||
children = await this.getChildren(ancestor)
|
||||
}
|
||||
return ancestor
|
||||
} catch (error) {
|
||||
log.errorAndThrow(`getParent(${uriString || 'undefined'})`, error)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
public async getChildren(uriString?: string): Promise<string[] | undefined> {
|
||||
try {
|
||||
if (!uriString) {
|
||||
const repos = [...this.fs.allRepositoryUris()]
|
||||
return repos.map(repo => repo.replace('https://', 'sourcegraph://'))
|
||||
}
|
||||
const uri = SourcegraphUri.parse(uriString)
|
||||
const tree = await this.fs.getFileTree(uri)
|
||||
const directChildren = tree.directChildren(uri.path || '')
|
||||
for (const child of directChildren) {
|
||||
this.treeItemCache.set(child, this.newTreeItem(SourcegraphUri.parse(child), uri, directChildren.length))
|
||||
}
|
||||
return directChildren
|
||||
} catch (error) {
|
||||
return log.errorAndThrow(`getChildren(${uriString || ''})`, error)
|
||||
}
|
||||
}
|
||||
|
||||
public async focusActiveFile(): Promise<void> {
|
||||
await vscode.commands.executeCommand('sourcegraph.files.focus')
|
||||
await this.didFocus(this.activeUri)
|
||||
}
|
||||
|
||||
public async didFocus(vscodeUri: vscode.Uri | undefined): Promise<void> {
|
||||
this.didFocusToken.cancel()
|
||||
this.didFocusToken = new vscode.CancellationTokenSource()
|
||||
this.activeUri = vscodeUri
|
||||
await vscode.commands.executeCommand(
|
||||
'setContext',
|
||||
'sourcegraph.canFocusActiveDocument',
|
||||
vscodeUri?.scheme === 'sourcegraph'
|
||||
)
|
||||
if (vscodeUri && vscodeUri.scheme === 'sourcegraph' && this.treeView && this._isViewVisible) {
|
||||
const uri = this.fs.sourcegraphUri(vscodeUri)
|
||||
if (uri.uri === this.fs.emptyFileUri()) {
|
||||
return
|
||||
}
|
||||
await this.fs.downloadFiles(uri)
|
||||
await this.didFocusString(uri, true, this.didFocusToken.token)
|
||||
}
|
||||
}
|
||||
|
||||
public isSourcegrapeRemoteFile(vscodeUri: vscode.Uri | undefined): boolean {
|
||||
if (vscodeUri && vscodeUri.scheme === 'sourcegraph' && this.treeView && this._isViewVisible) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public async getTreeItem(uriString: string): Promise<vscode.TreeItem> {
|
||||
try {
|
||||
const fromCache = this.treeItemCache.get(uriString)
|
||||
if (fromCache) {
|
||||
return fromCache
|
||||
}
|
||||
const uri = SourcegraphUri.parse(uriString)
|
||||
const parentUri = await this.getParent(uri.uri)
|
||||
return this.newTreeItem(uri, parentUri ? SourcegraphUri.parse(parentUri) : undefined, 0)
|
||||
} catch (error) {
|
||||
log.errorAndThrow(`getTreeItem(${uriString})`, error)
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
private async didFocusString(
|
||||
uri: SourcegraphUri,
|
||||
isDestinationNode: boolean,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (this.treeView) {
|
||||
const parent = await this.getParent(uri.uri)
|
||||
if (parent) {
|
||||
await this.didFocusString(SourcegraphUri.parse(parent), false, token)
|
||||
} else {
|
||||
await this.getChildren(undefined)
|
||||
}
|
||||
if (token.isCancellationRequested) {
|
||||
return
|
||||
}
|
||||
await this.treeView.reveal(uri.uri, {
|
||||
focus: true,
|
||||
select: isDestinationNode,
|
||||
expand: !isDestinationNode,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
log.error(`didFocusString(${uri.uri})`, error)
|
||||
}
|
||||
}
|
||||
|
||||
// Remove selected repo from tree
|
||||
public async removeTreeItem(): Promise<void> {
|
||||
if (this.selectedRepository) {
|
||||
this.fs.removeRepository(this.selectedRepository)
|
||||
}
|
||||
this.selectedRepository = undefined
|
||||
await vscode.commands.executeCommand('setContext', 'sourcegraph.removeRepository', false)
|
||||
return this.didChangeTreeData.fire(undefined)
|
||||
}
|
||||
|
||||
private newTreeItem(
|
||||
uri: SourcegraphUri,
|
||||
parent: SourcegraphUri | undefined,
|
||||
parentChildrenCount: number
|
||||
): vscode.TreeItem {
|
||||
const command = uri.isFile()
|
||||
? {
|
||||
command: 'sourcegraph.openFile',
|
||||
title: 'Open file',
|
||||
toolbar: 'test',
|
||||
arguments: [uri.uri],
|
||||
}
|
||||
: undefined
|
||||
// Check if this is a currently selected file
|
||||
let selectedFile = false
|
||||
if (
|
||||
vscode.window.activeTextEditor?.document &&
|
||||
uri.path === SourcegraphUri.parse(vscode.window.activeTextEditor?.document.uri.toString()).path
|
||||
) {
|
||||
selectedFile = true
|
||||
}
|
||||
return {
|
||||
id: uri.uri,
|
||||
label: uri.treeItemLabel(parent),
|
||||
tooltip: uri.uri.replace('sourcegraph://', 'https://'),
|
||||
collapsibleState: uri.isFile()
|
||||
? vscode.TreeItemCollapsibleState.None
|
||||
: parentChildrenCount === 0
|
||||
? vscode.TreeItemCollapsibleState.Expanded
|
||||
: vscode.TreeItemCollapsibleState.Collapsed,
|
||||
command,
|
||||
resourceUri: vscode.Uri.parse(uri.uri),
|
||||
contextValue: !uri.isFile() ? 'directory' : selectedFile ? 'selected' : 'file',
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,316 +0,0 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { getBlobContent } from '../backend/blobContent'
|
||||
import { getFiles } from '../backend/files'
|
||||
import { getRepositoryMetadata, type RepositoryMetadata } from '../backend/repositoryMetadata'
|
||||
import type { LocationNode } from '../code-intel/location'
|
||||
import { log } from '../log'
|
||||
import { endpointHostnameSetting } from '../settings/endpointSetting'
|
||||
|
||||
import { FileTree } from './FileTree'
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
export interface RepositoryFileNames {
|
||||
repositoryUri: string
|
||||
repositoryName: string
|
||||
fileNames: string[]
|
||||
}
|
||||
|
||||
export interface Blob {
|
||||
uri: string
|
||||
repositoryName: string
|
||||
revision: string
|
||||
path: string
|
||||
content: Uint8Array
|
||||
isBinaryFile: boolean
|
||||
byteSize: number
|
||||
time: number
|
||||
type: vscode.FileType
|
||||
}
|
||||
|
||||
export class SourcegraphFileSystemProvider implements vscode.FileSystemProvider {
|
||||
constructor(private instanceURL: string) {}
|
||||
|
||||
private fileNamesByRepository: Map<string, Promise<string[]>> = new Map()
|
||||
private metadata: Map<string, RepositoryMetadata> = new Map()
|
||||
private didDownloadFilenames = new vscode.EventEmitter<string>()
|
||||
|
||||
// ======================
|
||||
// FileSystemProvider API
|
||||
// ======================
|
||||
|
||||
// We don't implement this because Sourcegraph files are read-only.
|
||||
private didChangeFile = new vscode.EventEmitter<vscode.FileChangeEvent[]>() // Never used.
|
||||
public readonly onDidChangeFile: vscode.Event<vscode.FileChangeEvent[]> = this.didChangeFile.event
|
||||
public async stat(vscodeUri: vscode.Uri): Promise<vscode.FileStat> {
|
||||
const uri = this.sourcegraphUri(vscodeUri)
|
||||
const now = Date.now()
|
||||
if (uri.uri === this.emptyFileUri()) {
|
||||
return { mtime: now, ctime: now, size: 0, type: vscode.FileType.File }
|
||||
}
|
||||
const files = await this.downloadFiles(uri)
|
||||
const isFile = uri.path && files.includes(uri.path)
|
||||
const type = isFile ? vscode.FileType.File : vscode.FileType.Directory
|
||||
// log.appendLine(
|
||||
// `stat(${uri.uri}) path=${uri.path || '""'} files.length=${files.length} type=${vscode.FileType[type]}`
|
||||
// )
|
||||
return {
|
||||
// It seems to be OK to return hardcoded values for the timestamps
|
||||
// and the byte size. If it turns out the byte size needs to be
|
||||
// correct for some reason, then we can use
|
||||
// `this.fetchBlob(uri).byteSize` to get the value for files.
|
||||
mtime: now,
|
||||
ctime: now,
|
||||
size: 1337,
|
||||
type,
|
||||
}
|
||||
}
|
||||
|
||||
public emptyFileUri(): string {
|
||||
return 'sourcegraph://sourcegraph.com/empty-file.txt'
|
||||
}
|
||||
|
||||
public async readFile(vscodeUri: vscode.Uri): Promise<Uint8Array> {
|
||||
const uri = this.sourcegraphUri(vscodeUri)
|
||||
if (uri.uri === this.emptyFileUri()) {
|
||||
return new Uint8Array()
|
||||
}
|
||||
const blob = await this.fetchBlob(uri)
|
||||
return blob.content
|
||||
}
|
||||
|
||||
public async readDirectory(vscodeUri: vscode.Uri): Promise<[string, vscode.FileType][]> {
|
||||
const uri = this.sourcegraphUri(vscodeUri)
|
||||
if (uri.uri.endsWith('/-')) {
|
||||
return []
|
||||
}
|
||||
const tree = await this.getFileTree(uri)
|
||||
const children = tree.directChildren(uri.path || '')
|
||||
return children.map(childUri => {
|
||||
const child = SourcegraphUri.parse(childUri)
|
||||
const type = child.isDirectory() ? vscode.FileType.Directory : vscode.FileType.File
|
||||
return [child.basename(), type]
|
||||
})
|
||||
}
|
||||
|
||||
public createDirectory(uri: vscode.Uri): void {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
public writeFile(
|
||||
_uri: vscode.Uri,
|
||||
_content: Uint8Array,
|
||||
_options: { create: boolean; overwrite: boolean }
|
||||
): void | Thenable<void> {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
public delete(_uri: vscode.Uri, _options: { recursive: boolean }): void {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
public rename(_oldUri: vscode.Uri, _newUri: vscode.Uri, _options: { overwrite: boolean }): void {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
public watch(_uri: vscode.Uri, _options: { recursive: boolean; excludes: string[] }): vscode.Disposable {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
|
||||
// ===============================
|
||||
// Helper methods for external use
|
||||
// ===============================
|
||||
|
||||
public onDidDownloadRepositoryFilenames: vscode.Event<string> = this.didDownloadFilenames.event
|
||||
|
||||
public allRepositoryUris(): string[] {
|
||||
return [...this.fileNamesByRepository.keys()]
|
||||
}
|
||||
|
||||
public resetFileTree(): void {
|
||||
return this.fileNamesByRepository.clear()
|
||||
}
|
||||
|
||||
// Remove Currently Selected Repository from Tree
|
||||
public removeRepository(uriString: string): void {
|
||||
this.fileNamesByRepository.delete(uriString)
|
||||
}
|
||||
|
||||
public async allFilesFromOpenRepositories(folder?: SourcegraphUri): Promise<RepositoryFileNames[]> {
|
||||
const promises: RepositoryFileNames[] = []
|
||||
const folderRepositoryUri = folder?.repositoryUri()
|
||||
for (const [repositoryUri, downloadingFileNames] of this.fileNamesByRepository.entries()) {
|
||||
if (folderRepositoryUri && repositoryUri !== folderRepositoryUri) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const fileNames = await downloadingFileNames
|
||||
const uri = SourcegraphUri.parse(repositoryUri)
|
||||
promises.push({
|
||||
repositoryUri: uri.repositoryUri(),
|
||||
repositoryName: `${uri.repositoryName}${uri.revisionPart()}`,
|
||||
fileNames,
|
||||
})
|
||||
} catch {
|
||||
log.error(`failed to download files for repository '${repositoryUri}'`)
|
||||
}
|
||||
}
|
||||
return promises
|
||||
}
|
||||
|
||||
public toVscodeLocation(node: LocationNode): vscode.Location {
|
||||
const metadata = this.metadata.get(node.resource.repositoryName)
|
||||
let revision = node.resource.revision
|
||||
if (metadata?.defaultBranch && revision === metadata?.defaultOID) {
|
||||
revision = metadata.defaultBranch
|
||||
}
|
||||
|
||||
let rangeOrPosition: vscode.Range | vscode.Position
|
||||
if (node.range) {
|
||||
rangeOrPosition = new vscode.Range(
|
||||
new vscode.Position(node.range.start.line, node.range.start.character),
|
||||
new vscode.Position(node.range.end.line, node.range.end.character)
|
||||
)
|
||||
} else {
|
||||
rangeOrPosition = new vscode.Position(0, 0)
|
||||
}
|
||||
|
||||
return new vscode.Location(
|
||||
vscode.Uri.parse(
|
||||
SourcegraphUri.fromParts(endpointHostnameSetting(), node.resource.repositoryName, {
|
||||
revision,
|
||||
path: node.resource.path,
|
||||
}).uri
|
||||
),
|
||||
rangeOrPosition
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns the URI of a file in the given repository. The file is the
|
||||
* toplevel readme file if it exists, otherwise it's the file with the
|
||||
* shortest name in the repository.
|
||||
*/
|
||||
public async defaultFileUri(repositoryName: string): Promise<SourcegraphUri> {
|
||||
const defaultBranch = (await this.repositoryMetadata(repositoryName))?.defaultBranch
|
||||
if (!defaultBranch) {
|
||||
log.errorAndThrow(`repository '${repositoryName}' has no default branch`)
|
||||
}
|
||||
const uri = SourcegraphUri.fromParts(endpointHostnameSetting(), repositoryName, { revision: defaultBranch })
|
||||
const files = await this.downloadFiles(uri)
|
||||
const readmes = files.filter(name => name.match(/readme/i))
|
||||
const candidates = readmes.length > 0 ? readmes : files
|
||||
let readme: string | undefined
|
||||
for (const candidate of candidates) {
|
||||
if (candidate === '' || candidate === 'lsif-java.json') {
|
||||
// Skip auto-generated file for JVM packages
|
||||
continue
|
||||
}
|
||||
if (!readme) {
|
||||
readme = candidate
|
||||
} else if (candidate.length < readme.length) {
|
||||
readme = candidate
|
||||
}
|
||||
}
|
||||
const defaultFile = readme || files[0]
|
||||
return SourcegraphUri.fromParts(endpointHostnameSetting(), repositoryName, {
|
||||
revision: defaultBranch,
|
||||
path: defaultFile,
|
||||
})
|
||||
}
|
||||
|
||||
public async fetchBlob(uri: SourcegraphUri): Promise<Blob> {
|
||||
await this.repositoryMetadata(uri.repositoryName)
|
||||
if (!uri.revision) {
|
||||
log.errorAndThrow(`missing revision for URI '${uri.uri}'`)
|
||||
}
|
||||
const path = uri.path || ''
|
||||
const content = await getBlobContent({
|
||||
repository: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
path,
|
||||
})
|
||||
|
||||
if (content) {
|
||||
const toCacheResult: Blob = {
|
||||
uri: uri.uri,
|
||||
repositoryName: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
content: content.content,
|
||||
isBinaryFile: content.isBinary,
|
||||
byteSize: content.byteSize,
|
||||
path,
|
||||
time: new Date().getMilliseconds(),
|
||||
type: vscode.FileType.File,
|
||||
}
|
||||
|
||||
// Start downloading the repository files in the background.
|
||||
this.downloadFiles(uri).then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
|
||||
return toCacheResult
|
||||
}
|
||||
return log.errorAndThrow(`fetchBlob(${uri.uri}) not found`)
|
||||
}
|
||||
|
||||
public async repositoryMetadata(repositoryName: string): Promise<RepositoryMetadata | undefined> {
|
||||
let metadata = this.metadata.get(repositoryName)
|
||||
if (metadata) {
|
||||
return metadata
|
||||
}
|
||||
metadata = await getRepositoryMetadata({ repositoryName })
|
||||
if (metadata) {
|
||||
this.metadata.set(repositoryName, metadata)
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
public downloadFiles(uri: SourcegraphUri): Promise<string[]> {
|
||||
const key = uri.repositoryUri()
|
||||
const fileNamesByRepository = this.fileNamesByRepository
|
||||
let downloadingFiles = this.fileNamesByRepository.get(key)
|
||||
if (!downloadingFiles) {
|
||||
downloadingFiles = getFiles({ repository: uri.repositoryName, revision: uri.revision })
|
||||
vscode.window
|
||||
.withProgress(
|
||||
{
|
||||
location: vscode.ProgressLocation.Window,
|
||||
title: `Loading ${uri.repositoryName}`,
|
||||
},
|
||||
async progress => {
|
||||
try {
|
||||
await downloadingFiles
|
||||
this.didDownloadFilenames.fire(key)
|
||||
} catch (error) {
|
||||
log.error(`downloadFiles(${key})`, error)
|
||||
fileNamesByRepository.delete(key)
|
||||
}
|
||||
progress.report({ increment: 100 })
|
||||
}
|
||||
)
|
||||
.then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
|
||||
this.fileNamesByRepository.set(key, downloadingFiles)
|
||||
}
|
||||
return downloadingFiles
|
||||
}
|
||||
|
||||
public sourcegraphUri(uri: vscode.Uri): SourcegraphUri {
|
||||
const sourcegraphUri = SourcegraphUri.parse(uri.toString(true))
|
||||
if (sourcegraphUri.host !== new URL(this.instanceURL).host) {
|
||||
const message = 'Sourcegraph instance URL has changed. Close files opened through the previous instance.'
|
||||
vscode.window.showWarningMessage(message).then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
throw new Error(message)
|
||||
}
|
||||
return sourcegraphUri
|
||||
}
|
||||
|
||||
public async getFileTree(uri: SourcegraphUri): Promise<FileTree> {
|
||||
const files = await this.downloadFiles(uri)
|
||||
return new FileTree(uri, files)
|
||||
}
|
||||
}
|
||||
@ -1,225 +0,0 @@
|
||||
import type { Position } from '@sourcegraph/extension-api-types'
|
||||
import { parseQueryAndHash, parseRepoRevision } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
export interface SourcegraphUriOptionals {
|
||||
revision?: string
|
||||
path?: string
|
||||
position?: Position
|
||||
isDirectory?: boolean
|
||||
isCommit?: boolean
|
||||
compareRange?: CompareRange
|
||||
}
|
||||
|
||||
export interface CompareRange {
|
||||
base: string
|
||||
head: string
|
||||
}
|
||||
|
||||
/**
|
||||
* SourcegraphUri encodes a URI like `sourcegraph://HOST/REPOSITORY@REVISION/-/blob/PATH?L1337`.
|
||||
*
|
||||
* This class is used in both webviews and extensions, so try to avoid state management in this class or module.
|
||||
*/
|
||||
export class SourcegraphUri {
|
||||
private constructor(
|
||||
public readonly uri: string,
|
||||
public readonly host: string,
|
||||
public readonly repositoryName: string,
|
||||
public readonly revision: string,
|
||||
public readonly path: string | undefined,
|
||||
public readonly position: Position | undefined,
|
||||
public readonly compareRange: CompareRange | undefined
|
||||
) {}
|
||||
|
||||
public withRevision(newRevision: string | undefined): SourcegraphUri {
|
||||
const newRevisionPath = newRevision ? `@${newRevision}` : ''
|
||||
return SourcegraphUri.parse(
|
||||
`sourcegraph://${this.host}/${this.repositoryName}${newRevisionPath}/-/blob/${
|
||||
this.path || ''
|
||||
}${this.positionSuffix()}`
|
||||
)
|
||||
}
|
||||
|
||||
public with(optionals: SourcegraphUriOptionals): SourcegraphUri {
|
||||
return SourcegraphUri.fromParts(this.host, this.repositoryName, {
|
||||
path: this.path,
|
||||
revision: this.revision,
|
||||
compareRange: this.compareRange,
|
||||
position: this.position,
|
||||
...optionals,
|
||||
})
|
||||
}
|
||||
|
||||
public withPath(newPath: string): SourcegraphUri {
|
||||
return SourcegraphUri.parse(`${this.repositoryUri()}/-/blob/${newPath}${this.positionSuffix()}`)
|
||||
}
|
||||
|
||||
public basename(): string {
|
||||
const parts = (this.path || '').split('/')
|
||||
return parts.at(-1)!
|
||||
}
|
||||
|
||||
public dirname(): string {
|
||||
const parts = (this.path || '').split('/')
|
||||
return parts.slice(0, -1).join('/')
|
||||
}
|
||||
|
||||
public parentUri(): string | undefined {
|
||||
if (typeof this.path === 'string') {
|
||||
const slash = this.uri.lastIndexOf('/')
|
||||
if (slash < 0 || !this.path.includes('/')) {
|
||||
return `sourcegraph://${this.host}/${this.repositoryName}${this.revisionPart()}`
|
||||
}
|
||||
const parent = this.uri.slice(0, slash).replace('/-/blob/', '/-/tree/')
|
||||
return parent
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
public withIsDirectory(isDirectory: boolean): SourcegraphUri {
|
||||
return SourcegraphUri.fromParts(this.host, this.repositoryName, {
|
||||
isDirectory,
|
||||
path: this.path,
|
||||
revision: this.revision,
|
||||
position: this.position,
|
||||
})
|
||||
}
|
||||
|
||||
public isCommit(): boolean {
|
||||
return this.uri.includes('/-/commit/')
|
||||
}
|
||||
|
||||
public isCompare(): boolean {
|
||||
return this.uri.includes('/-/compare/') && this.compareRange !== undefined
|
||||
}
|
||||
|
||||
public isDirectory(): boolean {
|
||||
return this.uri.includes('/-/tree/')
|
||||
}
|
||||
|
||||
public isFile(): boolean {
|
||||
return this.uri.includes('/-/blob/')
|
||||
}
|
||||
|
||||
public static fromParts(host: string, repositoryName: string, optional?: SourcegraphUriOptionals): SourcegraphUri {
|
||||
const revisionPart = optional?.revision ? `@${optional.revision}` : ''
|
||||
const directoryPart = optional?.isDirectory
|
||||
? 'tree'
|
||||
: optional?.isCommit
|
||||
? 'commit'
|
||||
: optional?.compareRange
|
||||
? 'compare'
|
||||
: 'blob'
|
||||
const pathPart = optional?.compareRange
|
||||
? `/-/compare/${optional.compareRange.base}...${optional.compareRange.head}`
|
||||
: optional?.isCommit && optional.revision
|
||||
? `/-/commit/${optional.revision}`
|
||||
: optional?.path
|
||||
? `/-/${directoryPart}/${optional?.path}`
|
||||
: ''
|
||||
const uri = `sourcegraph://${host}/${repositoryName}${revisionPart}${pathPart}`
|
||||
return new SourcegraphUri(
|
||||
uri,
|
||||
host,
|
||||
repositoryName,
|
||||
optional?.revision || '',
|
||||
optional?.path,
|
||||
optional?.position,
|
||||
optional?.compareRange
|
||||
)
|
||||
}
|
||||
public repositoryUri(): string {
|
||||
return `sourcegraph://${this.host}/${this.repositoryName}${this.revisionPart()}`
|
||||
}
|
||||
public treeItemLabel(parent?: SourcegraphUri): string {
|
||||
if (this.path) {
|
||||
if (parent?.path) {
|
||||
return this.path.slice(parent.path.length + 1)
|
||||
}
|
||||
return this.path
|
||||
}
|
||||
return `${this.repositoryName}`
|
||||
}
|
||||
public revisionPart(): string {
|
||||
return this.revision ? `@${this.revision}` : ''
|
||||
}
|
||||
public positionSuffix(): string {
|
||||
return this.position === undefined ? '' : `?L${this.position.line}:${this.position.character}`
|
||||
}
|
||||
|
||||
// Debt: refactor and use shared functions. Below is based on parseBrowserRepoURL
|
||||
// https://sourcegraph.com/github.com/sourcegraph/sourcegraph@56dfaaa3e3172f9afd4a29a4780a7f1a34198238/-/blob/client/shared/src/util/url.ts?L287
|
||||
// In the browser, pass in window.URL. When we use the shared implementation, pass in the URL module from Node.
|
||||
public static parse(uri: string, URLModule = URL): SourcegraphUri {
|
||||
uri = uri.replace('https://', 'sourcegraph://')
|
||||
const url = new URLModule(uri.replace('sourcegraph://', 'https://'))
|
||||
let pathname = url.pathname.slice(1) // trim leading '/'
|
||||
if (pathname.endsWith('/')) {
|
||||
pathname = pathname.slice(0, -1) // trim trailing '/'
|
||||
}
|
||||
|
||||
const indexOfSeparator = pathname.indexOf('/-/')
|
||||
|
||||
// examples:
|
||||
// - 'github.com/gorilla/mux'
|
||||
// - 'github.com/gorilla/mux@revision'
|
||||
// - 'foo/bar' (from 'sourcegraph.mycompany.com/foo/bar')
|
||||
// - 'foo/bar@revision' (from 'sourcegraph.mycompany.com/foo/bar@revision')
|
||||
// - 'foobar' (from 'sourcegraph.mycompany.com/foobar')
|
||||
// - 'foobar@revision' (from 'sourcegraph.mycompany.com/foobar@revision')
|
||||
let repoRevision: string
|
||||
if (indexOfSeparator === -1) {
|
||||
repoRevision = pathname // the whole string
|
||||
} else {
|
||||
repoRevision = pathname.slice(0, indexOfSeparator) // the whole string leading up to the separator (allows revision to be multiple path parts)
|
||||
}
|
||||
let { repoName, revision } = parseRepoRevision(repoRevision)
|
||||
|
||||
let path: string | undefined
|
||||
let compareRange: CompareRange | undefined
|
||||
const treeSeparator = pathname.indexOf('/-/tree/')
|
||||
const blobSeparator = pathname.indexOf('/-/blob/')
|
||||
const commitSeparator = pathname.indexOf('/-/commit/')
|
||||
const comparisonSeparator = pathname.indexOf('/-/compare/')
|
||||
if (treeSeparator !== -1) {
|
||||
path = decodeURIComponent(pathname.slice(treeSeparator + '/-/tree/'.length))
|
||||
}
|
||||
if (blobSeparator !== -1) {
|
||||
path = decodeURIComponent(pathname.slice(blobSeparator + '/-/blob/'.length))
|
||||
}
|
||||
if (commitSeparator !== -1) {
|
||||
path = decodeURIComponent(pathname.slice(commitSeparator + '/-/commit/'.length))
|
||||
}
|
||||
if (comparisonSeparator !== -1) {
|
||||
const range = pathname.slice(comparisonSeparator + '/-/compare/'.length)
|
||||
const parts = range.split('...')
|
||||
if (parts.length === 2) {
|
||||
const [base, head] = parts
|
||||
compareRange = { base, head }
|
||||
}
|
||||
}
|
||||
let position: Position | undefined
|
||||
|
||||
const parsedHash = parseQueryAndHash(url.search, url.hash)
|
||||
if (parsedHash.line) {
|
||||
position = {
|
||||
line: parsedHash.line,
|
||||
character: parsedHash.character || 0,
|
||||
}
|
||||
}
|
||||
const isDirectory = uri.includes('/-/tree/')
|
||||
const isCommit = uri.includes('/-/commit/')
|
||||
if (isCommit) {
|
||||
revision = url.pathname.replace(new RegExp('.*/-/commit/([^/]+).*'), (_unused, oid: string) => oid)
|
||||
path = path?.slice(`${revision}/`.length)
|
||||
}
|
||||
return SourcegraphUri.fromParts(url.host, repoName, {
|
||||
revision,
|
||||
path,
|
||||
position,
|
||||
isDirectory,
|
||||
isCommit,
|
||||
compareRange,
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -1,105 +0,0 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import type { SourcegraphFileSystemProvider } from './SourcegraphFileSystemProvider'
|
||||
import type { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
/**
|
||||
* Try to find local copy of the search result file first
|
||||
* Remote copy will be opened instead if basePath is not set or local copy cannot be found
|
||||
**/
|
||||
export async function openSourcegraphUriCommand(fs: SourcegraphFileSystemProvider, uri: SourcegraphUri): Promise<void> {
|
||||
if (uri.compareRange) {
|
||||
// noop. v2 Debt: implement. Open in browser for v1
|
||||
return
|
||||
}
|
||||
let textDocument
|
||||
try {
|
||||
textDocument = await getLocalCopy(uri)
|
||||
} catch (error) {
|
||||
console.error('Failed to get local copy:', error)
|
||||
if (!uri.revision) {
|
||||
const metadata = await fs.repositoryMetadata(uri.repositoryName)
|
||||
uri = uri.withRevision(metadata?.defaultBranch || 'HEAD')
|
||||
}
|
||||
// Load Remote Copy instead
|
||||
textDocument = await vscode.workspace.openTextDocument(vscode.Uri.parse(uri.uri))
|
||||
}
|
||||
const selection = getSelection(uri, textDocument)
|
||||
await vscode.window.showTextDocument(textDocument, {
|
||||
selection,
|
||||
viewColumn: vscode.ViewColumn.Active,
|
||||
preview: false,
|
||||
})
|
||||
}
|
||||
|
||||
async function getLocalCopy(remoteUri: SourcegraphUri): Promise<vscode.TextDocument> {
|
||||
const repoName = remoteUri.repositoryName.split('/').pop() || '' // ex: github.com/sourcegraph/sourcegraph => sourcegraph
|
||||
const filePath = remoteUri.path || '' // ex: "client/vscode/package.json"
|
||||
// Get basePath from configuration
|
||||
const basePath = vscode.workspace.getConfiguration('sourcegraph').get<string>('basePath') || null
|
||||
const workspaceFilePath = await vscode.workspace
|
||||
.findFiles(filePath, null, 1)
|
||||
.then(result => result[0]?.path || null)
|
||||
// If basePath is not configured, we will try to find file in the current workspace
|
||||
const absolutePath = basePath
|
||||
? vscode.Uri.file(vscode.Uri.joinPath(vscode.Uri.parse(basePath), repoName, filePath).path)
|
||||
: workspaceFilePath
|
||||
? vscode.Uri.file(workspaceFilePath)
|
||||
: null
|
||||
// if both basePath and workspaceFilePath are null, the operation will fail
|
||||
if (!absolutePath) {
|
||||
throw new Error('Try to configure your basePath to open this file.')
|
||||
}
|
||||
// Set current workspace folder path as basePath if it doesn't exist
|
||||
if (!basePath && workspaceFilePath) {
|
||||
// get current workspace folder uri
|
||||
const workspaceFolderUri = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(workspaceFilePath))?.uri
|
||||
if (workspaceFolderUri) {
|
||||
// go one level up and set that as the new basePath
|
||||
const newBasePath = vscode.Uri.file(vscode.Uri.joinPath(workspaceFolderUri, '../').fsPath).path
|
||||
await vscode.workspace
|
||||
.getConfiguration('sourcegraph')
|
||||
.update('basePath', newBasePath, vscode.ConfigurationTarget.Global)
|
||||
}
|
||||
}
|
||||
const textDocument = await vscode.workspace.openTextDocument(absolutePath)
|
||||
return textDocument
|
||||
}
|
||||
|
||||
function getSelection(uri: SourcegraphUri, textDocument: vscode.TextDocument): vscode.Range | undefined {
|
||||
if (uri?.position?.line !== undefined && uri?.position?.character !== undefined) {
|
||||
return offsetRange(uri.position.line, uri.position.character)
|
||||
}
|
||||
if (uri?.position?.line !== undefined) {
|
||||
return offsetRange(uri.position.line, 0)
|
||||
}
|
||||
// There's no explicitly provided line number. Instead of focusing on the
|
||||
// first line (which usually contains lots of imports), we use a heuristic
|
||||
// to guess the location where the "main symbol" is defined (a
|
||||
// function/class/struct/interface with the same name as the filename).
|
||||
if (uri.path && isFilenameThatMayDefineSymbols(uri.path)) {
|
||||
const fileNames = uri.path.split('/')
|
||||
const fileName = fileNames.at(-1)!
|
||||
const symbolName = fileName.split('.')[0]
|
||||
const text = textDocument.getText()
|
||||
const symbolMatches = new RegExp(` ${symbolName}\\b`).exec(text)
|
||||
if (symbolMatches) {
|
||||
const position = textDocument.positionAt(symbolMatches.index + 1)
|
||||
return new vscode.Range(position, position)
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function offsetRange(line: number, character: number): vscode.Range {
|
||||
const position = new vscode.Position(line, character)
|
||||
return new vscode.Range(position, position)
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns true if this file may contain code from a programming language that
|
||||
* defines symbol.
|
||||
*/
|
||||
function isFilenameThatMayDefineSymbols(path: string): boolean {
|
||||
return !(path.endsWith('.md') || path.endsWith('.markdown') || path.endsWith('.txt') || path.endsWith('.log'))
|
||||
}
|
||||
@ -1,48 +0,0 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
import { log } from '../log'
|
||||
|
||||
import { openSourcegraphUriCommand } from './commands'
|
||||
import { FilesTreeDataProvider } from './FilesTreeDataProvider'
|
||||
import { SourcegraphFileSystemProvider } from './SourcegraphFileSystemProvider'
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
export function initializeSourcegraphFileSystem({
|
||||
context,
|
||||
initialInstanceURL,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
initialInstanceURL: string
|
||||
}): { fs: SourcegraphFileSystemProvider } {
|
||||
const fs = new SourcegraphFileSystemProvider(initialInstanceURL)
|
||||
context.subscriptions.push(vscode.workspace.registerFileSystemProvider('sourcegraph', fs, { isReadonly: true }))
|
||||
|
||||
const files = new FilesTreeDataProvider(fs)
|
||||
|
||||
const filesTreeView = vscode.window.createTreeView<string>('sourcegraph.files', {
|
||||
treeDataProvider: files,
|
||||
showCollapseAll: true,
|
||||
})
|
||||
files.setTreeView(filesTreeView)
|
||||
context.subscriptions.push(filesTreeView)
|
||||
|
||||
// Open remote Sourcegraph file from remote file tree
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.openFile', async uri => {
|
||||
if (typeof uri === 'string') {
|
||||
await openSourcegraphUriCommand(fs, SourcegraphUri.parse(uri))
|
||||
} else {
|
||||
log.error(`extension.openRemoteFile(${uri}) argument is not a string`)
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
// Remove Selected Repository from File Tree
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.removeRepoTree', async () => {
|
||||
await files.removeTreeItem()
|
||||
})
|
||||
)
|
||||
|
||||
return { fs }
|
||||
}
|
||||
@ -1,34 +0,0 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
const outputChannel = vscode.window.createOutputChannel('Sourcegraph')
|
||||
|
||||
export const log = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
error: (what: string, error?: any): void => {
|
||||
outputChannel.appendLine(`ERROR ${errorMessage(what, error)}`)
|
||||
},
|
||||
errorAndThrow: (what: string, error?: any): never => {
|
||||
log.error(what, error)
|
||||
throw new Error(errorMessage(what, error))
|
||||
},
|
||||
debug: (what: any): void => {
|
||||
for (const key of Object.keys(what)) {
|
||||
const value = JSON.stringify(what[key])
|
||||
outputChannel.appendLine(`${key}=${value}`)
|
||||
}
|
||||
},
|
||||
appendLine: (message: string): void => {
|
||||
outputChannel.appendLine(message)
|
||||
},
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function errorMessage(what: string, error?: any): string {
|
||||
const errorMessage =
|
||||
error instanceof Error
|
||||
? ` ${error.message} ${error.stack || ''}`
|
||||
: error !== undefined
|
||||
? ` ${JSON.stringify(error)}`
|
||||
: ''
|
||||
return what + errorMessage
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
// VS Code Docs https://code.visualstudio.com/api/references/vscode-api#Memento
|
||||
// A memento represents a storage utility. It can store and retrieve values.
|
||||
import type { Memento } from 'vscode'
|
||||
|
||||
export class LocalStorageService {
|
||||
constructor(private storage: Memento) {}
|
||||
|
||||
public getValue(key: string): string {
|
||||
return this.storage.get<string>(key, '')
|
||||
}
|
||||
|
||||
public async setValue(key: string, value: string): Promise<boolean> {
|
||||
try {
|
||||
await this.storage.update(key, value)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const SELECTED_SEARCH_CONTEXT_SPEC_KEY = 'selected-search-context-spec'
|
||||
export const INSTANCE_VERSION_NUMBER_KEY = 'sourcegraphVersionNumber'
|
||||
export const ANONYMOUS_USER_ID_KEY = 'sourcegraphAnonymousUid'
|
||||
export const DISMISS_WORKSPACERECS_CTA_KEY = 'sourcegraphWorkspaceRecsCtaDismissed'
|
||||
@ -1,65 +0,0 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { isOlderThan, observeInstanceVersionNumber } from '../backend/instanceVersion'
|
||||
import { scretTokenKey } from '../webview/platform/AuthProvider'
|
||||
|
||||
import { endpointHostnameSetting, endpointProtocolSetting } from './endpointSetting'
|
||||
import { readConfiguration } from './readConfiguration'
|
||||
|
||||
// IMPORTANT: Call this function only once when extention is first activated
|
||||
export async function processOldToken(secretStorage: vscode.SecretStorage): Promise<void> {
|
||||
// Process the token that lives in user configuration
|
||||
// Move them to secrets and then remove them by setting it as undefined
|
||||
const storageToken = await secretStorage.get(scretTokenKey)
|
||||
const oldToken = vscode.workspace.getConfiguration().get<string>('sourcegraph.accessToken') || ''
|
||||
if (!storageToken && oldToken.length > 8) {
|
||||
await secretStorage.store(scretTokenKey, oldToken)
|
||||
await removeOldAccessTokenSetting()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
export async function accessTokenSetting(secretStorage: vscode.SecretStorage): Promise<string> {
|
||||
const currentToken = await secretStorage.get(scretTokenKey)
|
||||
return currentToken || ''
|
||||
}
|
||||
|
||||
export async function removeOldAccessTokenSetting(): Promise<void> {
|
||||
await readConfiguration().update('accessToken', undefined, vscode.ConfigurationTarget.Global)
|
||||
await readConfiguration().update('accessToken', undefined, vscode.ConfigurationTarget.Workspace)
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure that only one access token error message is shown at a time.
|
||||
let showingAccessTokenErrorMessage = false
|
||||
|
||||
export async function handleAccessTokenError(badToken: string, endpointURL: string): Promise<void> {
|
||||
if (badToken !== undefined && !showingAccessTokenErrorMessage) {
|
||||
showingAccessTokenErrorMessage = true
|
||||
|
||||
const message = !badToken
|
||||
? `A valid access token is required to connect to ${endpointURL}`
|
||||
: `Connection to ${endpointURL} failed. Please try reloading VS Code if your Sourcegraph instance URL has been updated.`
|
||||
|
||||
const version = await observeInstanceVersionNumber(badToken, endpointURL).toPromise()
|
||||
const supportsTokenCallback = version && isOlderThan(version, { major: 3, minor: 41 })
|
||||
const action = await vscode.window.showErrorMessage(message, 'Get Token', 'Reload Window')
|
||||
|
||||
if (action === 'Reload Window') {
|
||||
await vscode.commands.executeCommand('workbench.action.reloadWindow')
|
||||
} else if (action === 'Get Token') {
|
||||
const path = supportsTokenCallback ? '/user/settings/tokens/new/callback' : '/user/settings/'
|
||||
const query = supportsTokenCallback ? 'requestFrom=VSCEAUTH' : ''
|
||||
|
||||
await vscode.env.openExternal(
|
||||
vscode.Uri.from({
|
||||
scheme: endpointProtocolSetting().slice(0, -1),
|
||||
authority: endpointHostnameSetting(),
|
||||
path,
|
||||
query,
|
||||
})
|
||||
)
|
||||
}
|
||||
showingAccessTokenErrorMessage = false
|
||||
}
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
export async function displayWarning(warning: string): Promise<void> {
|
||||
await vscode.window.showErrorMessage(warning)
|
||||
}
|
||||
@ -1,47 +0,0 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { readConfiguration } from './readConfiguration'
|
||||
|
||||
export function endpointSetting(): string {
|
||||
const url = vscode.workspace.getConfiguration().get<string>('sourcegraph.url') || 'https://sourcegraph.com'
|
||||
return removeEndingSlash(url)
|
||||
}
|
||||
|
||||
export async function setEndpoint(newEndpoint: string): Promise<void> {
|
||||
const newEndpointURL = newEndpoint ? removeEndingSlash(newEndpoint) : 'https://sourcegraph.com'
|
||||
const currentEndpointHostname = new URL(endpointSetting()).hostname
|
||||
const newEndpointHostname = new URL(newEndpointURL).hostname
|
||||
if (currentEndpointHostname !== newEndpointHostname) {
|
||||
await readConfiguration().update('url', newEndpointURL)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
export function endpointHostnameSetting(): string {
|
||||
return new URL(endpointSetting()).hostname
|
||||
}
|
||||
|
||||
export function endpointPortSetting(): number {
|
||||
const port = new URL(endpointSetting()).port
|
||||
return port ? parseInt(port, 10) : 443
|
||||
}
|
||||
|
||||
export function endpointProtocolSetting(): string {
|
||||
return new URL(endpointSetting()).protocol
|
||||
}
|
||||
|
||||
export function endpointRequestHeadersSetting(): object {
|
||||
return vscode.workspace.getConfiguration().get<object>('sourcegraph.requestHeaders') || {}
|
||||
}
|
||||
|
||||
function removeEndingSlash(uri: string): string {
|
||||
if (uri.endsWith('/')) {
|
||||
return uri.slice(0, -1)
|
||||
}
|
||||
return uri
|
||||
}
|
||||
|
||||
export function isSourcegraphDotCom(): boolean {
|
||||
const hostname = new URL(endpointSetting()).hostname
|
||||
return hostname === 'sourcegraph.com' || hostname === 'www.sourcegraph.com'
|
||||
}
|
||||
@ -1,37 +0,0 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { invalidateClient } from '../backend/requestGraphQl'
|
||||
import type { VSCEStateMachine } from '../state'
|
||||
|
||||
/**
|
||||
* Listens for Sourcegraph URL and invalidates the GraphQL client
|
||||
* to prevent data "contamination" (e.g. sending private repo names to Cloud instance).
|
||||
*/
|
||||
export function invalidateContextOnSettingsChange({
|
||||
context,
|
||||
stateMachine,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
stateMachine: VSCEStateMachine
|
||||
}): void {
|
||||
function disposeAllResources(): void {
|
||||
for (const subscription of context.subscriptions) {
|
||||
subscription.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.workspace.onDidChangeConfiguration(async config => {
|
||||
if (config.affectsConfiguration('sourcegraph.url')) {
|
||||
invalidateClient()
|
||||
disposeAllResources()
|
||||
stateMachine.emit({ type: 'sourcegraph_url_change' })
|
||||
// Swallow errors since if `showInformationMessage` fails, we assume that something is wrong
|
||||
// with the VS Code extension host and don't retry.
|
||||
await vscode.window.showInformationMessage(
|
||||
'Restart VS Code to use the Sourcegraph extension after URL change.'
|
||||
)
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
export function readConfiguration(): vscode.WorkspaceConfiguration {
|
||||
return vscode.workspace.getConfiguration('sourcegraph')
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
/**
|
||||
* Disabled due to violation of the VS Code's UX guidelines for notifications
|
||||
* To be revaluated in the future: https://code.visualstudio.com/api/ux-guidelines/notifications
|
||||
* This functions add Sourcegraph to workspace recommendations if haven't already
|
||||
* eg: recommendSourcegraph(localStorageService).catch(() => {})
|
||||
*/
|
||||
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { DISMISS_WORKSPACERECS_CTA_KEY, type LocalStorageService } from './LocalStorageService'
|
||||
|
||||
/**
|
||||
* Ask if user wants to add Sourcegraph to their Workspace Recommendations list by displaying built-in popup
|
||||
* It will not show popup if the user already has Sourcegraph added to their recommendations list
|
||||
* or has dismissed the message previously
|
||||
*/
|
||||
export async function recommendSourcegraph(localStorageService: LocalStorageService): Promise<void> {
|
||||
// Check if user has clicked on the 'Don't show again' button previously
|
||||
// Reset stored value for testing: await localStorageService.setValue(DISMISS_WORKSPACERECS_CTA_KEY, '')
|
||||
const isDismissed = localStorageService.getValue(DISMISS_WORKSPACERECS_CTA_KEY)
|
||||
if (isDismissed === 'true') {
|
||||
return
|
||||
}
|
||||
const rootPath = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders[0].uri.fsPath : null
|
||||
if (!rootPath) {
|
||||
return
|
||||
}
|
||||
// File path of the workspace recommendations file
|
||||
const filePath = vscode.Uri.file(`${rootPath}/.vscode/extensions.json`)
|
||||
// Check if sourcegraph is already added to their Workspace Recommendations
|
||||
const bytes = await vscode.workspace.fs.readFile(filePath)
|
||||
const decoded = new TextDecoder('utf-8').decode(bytes)
|
||||
// Assume sourcegraph is in the recommendation list if 'sourcegraph.sourcegraph' exists in the file
|
||||
if (decoded.includes('sourcegraph.sourcegraph')) {
|
||||
return
|
||||
}
|
||||
// Display Cta
|
||||
await vscode.window
|
||||
.showInformationMessage('Add Sourcegraph to your workspace recommendations', '👍 Yes', "Don't show again")
|
||||
.then(async answer => {
|
||||
if (answer === '👍 Yes') {
|
||||
await vscode.commands.executeCommand(
|
||||
'workbench.extensions.action.addExtensionToWorkspaceRecommendations',
|
||||
'sourcegraph.sourcegraph'
|
||||
)
|
||||
}
|
||||
// Store as dismissed so it won't show user again when answer No or after being added
|
||||
await localStorageService.setValue(DISMISS_WORKSPACERECS_CTA_KEY, 'true')
|
||||
})
|
||||
}
|
||||
@ -1,69 +0,0 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
import type { EventSource } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { version } from '../../package.json'
|
||||
import { logEvent } from '../backend/eventLogger'
|
||||
|
||||
import { ANONYMOUS_USER_ID_KEY, type LocalStorageService } from './LocalStorageService'
|
||||
|
||||
// This function allows us to watch for uninstall event while still having access to the VS Code API
|
||||
export function watchUninstall(eventSourceType: EventSource, localStorageService: LocalStorageService): void {
|
||||
const extensionName = 'sourcegraph.sourcegraph'
|
||||
try {
|
||||
const extensionPath = vscode.extensions.getExtension(extensionName)?.extensionPath
|
||||
const pathComponents = extensionPath?.split('/').slice(0, -1)
|
||||
const extensionsDirectoryPath = pathComponents?.join('/')
|
||||
// All upgrades, downgrades, and uninstalls will be logged in the .obsolete file
|
||||
pathComponents?.push('.obsolete')
|
||||
const uninstalledPath = pathComponents?.join('/')
|
||||
if (extensionsDirectoryPath && uninstalledPath) {
|
||||
// Watch the .obsolete file - it does not exist when VS Code is started
|
||||
// Check if uninstall has happened when the file was created or when changes are made
|
||||
const watchPattern = new vscode.RelativePattern(extensionsDirectoryPath, '.obsolete')
|
||||
const watchFileListener = vscode.workspace.createFileSystemWatcher(watchPattern)
|
||||
watchFileListener.onDidCreate(() => checkUninstall(uninstalledPath, extensionsDirectoryPath))
|
||||
watchFileListener.onDidChange(() => checkUninstall(uninstalledPath, extensionsDirectoryPath))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('failed to invoke uninstall:', error)
|
||||
}
|
||||
|
||||
/**
|
||||
* Assume the extension has been uninstalled if the count of all the versions listed in
|
||||
* the .obsolete file is equal to the count of all the version-divided directories.
|
||||
* For example, if there are 5 versions of the extension were installed while there
|
||||
* are 4 versions of the extension listed in the .obsolete file pending to be deleted,
|
||||
* it means 1 version of the extension is still installed, therefore no uninstallation
|
||||
* has happened
|
||||
**/
|
||||
function checkUninstall(uninstalledPath: string, extensionsDirectoryPath: string): void {
|
||||
Promise.all([
|
||||
// .obsolete file includes all extensions versions that need to be remove at restart
|
||||
vscode.workspace.fs.readFile(vscode.Uri.file(uninstalledPath)),
|
||||
// Each versions of the extension has its own directory
|
||||
vscode.workspace.fs.readDirectory(vscode.Uri.parse(extensionsDirectoryPath)),
|
||||
])
|
||||
.then(([obsoleteExtensionsRaw, extensionsDirectory]) => {
|
||||
const obsoleteExtensionsCount = Object.keys(JSON.parse(obsoleteExtensionsRaw.toString())).filter(id =>
|
||||
id.includes(extensionName)
|
||||
).length
|
||||
const downloadedExtensionsCount = extensionsDirectory
|
||||
.map(([name]) => name)
|
||||
.filter(id => id.includes(extensionName)).length
|
||||
// Compare count of extension name in .obsolete file vs count of directories with the same extension name
|
||||
if (downloadedExtensionsCount === obsoleteExtensionsCount) {
|
||||
logEvent({
|
||||
event: 'IDEUninstalled',
|
||||
userCookieID: localStorageService.getValue(ANONYMOUS_USER_ID_KEY),
|
||||
referrer: 'VSCE',
|
||||
url: '',
|
||||
source: eventSourceType,
|
||||
argument: JSON.stringify({ editor: 'vscode', version }),
|
||||
publicArgument: JSON.stringify({ editor: 'vscode', version }),
|
||||
})
|
||||
}
|
||||
})
|
||||
.catch(error => console.error(error))
|
||||
}
|
||||
}
|
||||
@ -1,295 +0,0 @@
|
||||
import { cloneDeep } from 'lodash'
|
||||
import { BehaviorSubject, type Observable } from 'rxjs'
|
||||
|
||||
import type { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import type { SearchQueryState } from '@sourcegraph/shared/src/search'
|
||||
import type { AggregateStreamingSearchResults } from '@sourcegraph/shared/src/search/stream'
|
||||
|
||||
import { type LocalStorageService, SELECTED_SEARCH_CONTEXT_SPEC_KEY } from './settings/LocalStorageService'
|
||||
|
||||
/**
|
||||
* One state machine that lives in Core
|
||||
* See CONTRIBUTING docs to learn how state management works in this extension
|
||||
*/
|
||||
export interface VSCEStateMachine {
|
||||
state: VSCEState
|
||||
/**
|
||||
* Returns an Observable that emits the current state and
|
||||
* on subsequent state updates.
|
||||
*/
|
||||
observeState: () => Observable<VSCEState>
|
||||
emit: (event: VSCEEvent) => void
|
||||
}
|
||||
export type VSCEState = SearchHomeState | SearchResultsState | RemoteBrowsingState | IdleState | ContextInvalidatedState
|
||||
|
||||
export interface SearchHomeState {
|
||||
status: 'search-home'
|
||||
context: CommonContext
|
||||
}
|
||||
|
||||
export interface SearchResultsState {
|
||||
status: 'search-results'
|
||||
context: CommonContext & {
|
||||
submittedSearchQueryState: Pick<SearchQueryState, 'queryState' | 'searchCaseSensitivity' | 'searchPatternType'>
|
||||
}
|
||||
}
|
||||
export interface RemoteBrowsingState {
|
||||
status: 'remote-browsing'
|
||||
context: CommonContext
|
||||
}
|
||||
|
||||
export interface IdleState {
|
||||
status: 'idle'
|
||||
context: CommonContext
|
||||
}
|
||||
|
||||
export interface ContextInvalidatedState {
|
||||
status: 'context-invalidated'
|
||||
context: CommonContext
|
||||
}
|
||||
|
||||
/**
|
||||
* Subset of SearchQueryState that's necessary and clone-able (`postMessage`) for the VS Code extension.
|
||||
*/
|
||||
export type VSCEQueryState = Pick<
|
||||
SearchQueryState,
|
||||
'queryState' | 'searchCaseSensitivity' | 'searchPatternType' | 'searchMode'
|
||||
> | null
|
||||
|
||||
interface CommonContext {
|
||||
authenticatedUser: AuthenticatedUser | null
|
||||
|
||||
submittedSearchQueryState: VSCEQueryState
|
||||
|
||||
searchSidebarQueryState: {
|
||||
proposedQueryState: VSCEQueryState
|
||||
/**
|
||||
* The current query state as known to the sidebar.
|
||||
* Used to "anchor" query state updates to the correct state
|
||||
* in case the panel's search query state has changed since
|
||||
* the sidebar event.
|
||||
*
|
||||
* Debt: we don't use this yet.
|
||||
*/
|
||||
currentQueryState: VSCEQueryState
|
||||
}
|
||||
|
||||
searchResults: AggregateStreamingSearchResults | null
|
||||
|
||||
selectedSearchContextSpec: string | undefined
|
||||
}
|
||||
|
||||
function createInitialState({ localStorageService }: { localStorageService: LocalStorageService }): VSCEState {
|
||||
return {
|
||||
status: 'search-home',
|
||||
context: {
|
||||
authenticatedUser: null,
|
||||
submittedSearchQueryState: null,
|
||||
searchResults: null,
|
||||
selectedSearchContextSpec: localStorageService.getValue(SELECTED_SEARCH_CONTEXT_SPEC_KEY) || undefined,
|
||||
searchSidebarQueryState: {
|
||||
proposedQueryState: null,
|
||||
currentQueryState: null,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Temporary placeholder events. We will replace these with the actual events as we implement the webviews.
|
||||
|
||||
export type VSCEEvent = SearchEvent | TabsEvent | SettingsEvent
|
||||
|
||||
type SearchEvent =
|
||||
| { type: 'set_query_state' }
|
||||
| {
|
||||
type: 'submit_search_query'
|
||||
submittedSearchQueryState: NonNullable<CommonContext['submittedSearchQueryState']>
|
||||
}
|
||||
| { type: 'received_search_results'; searchResults: AggregateStreamingSearchResults }
|
||||
| { type: 'set_selected_search_context_spec'; spec: string } // TODO see how this handles instance change
|
||||
| { type: 'sidebar_query_update'; proposedQueryState: VSCEQueryState; currentQueryState: VSCEQueryState }
|
||||
|
||||
type TabsEvent =
|
||||
| { type: 'search_panel_disposed' }
|
||||
| { type: 'search_panel_unfocused' }
|
||||
| { type: 'search_panel_focused' }
|
||||
| { type: 'remote_file_focused' }
|
||||
| { type: 'remote_file_unfocused' }
|
||||
|
||||
interface SettingsEvent {
|
||||
type: 'sourcegraph_url_change'
|
||||
}
|
||||
|
||||
export function createVSCEStateMachine({
|
||||
localStorageService,
|
||||
}: {
|
||||
localStorageService: LocalStorageService
|
||||
}): VSCEStateMachine {
|
||||
const states = new BehaviorSubject<VSCEState>(createInitialState({ localStorageService }))
|
||||
|
||||
function reducer(state: VSCEState, event: VSCEEvent): VSCEState {
|
||||
// End state.
|
||||
if (state.status === 'context-invalidated') {
|
||||
return state
|
||||
}
|
||||
|
||||
// Events with the same behavior regardless of current state
|
||||
if (event.type === 'sourcegraph_url_change') {
|
||||
return {
|
||||
status: 'context-invalidated',
|
||||
context: {
|
||||
...createInitialState({ localStorageService }).context,
|
||||
},
|
||||
}
|
||||
}
|
||||
if (event.type === 'set_selected_search_context_spec') {
|
||||
return {
|
||||
...state,
|
||||
context: {
|
||||
...state.context,
|
||||
selectedSearchContextSpec: event.spec,
|
||||
},
|
||||
} as VSCEState
|
||||
// Type assertion is safe since existing context should be assignable to the existing state.
|
||||
// debt: refactor switch statement to elegantly handle this event safely.
|
||||
}
|
||||
if (event.type === 'sidebar_query_update') {
|
||||
return {
|
||||
...state,
|
||||
context: {
|
||||
...state.context,
|
||||
searchSidebarQueryState: {
|
||||
proposedQueryState: event.proposedQueryState,
|
||||
currentQueryState: event.currentQueryState,
|
||||
},
|
||||
},
|
||||
} as VSCEState
|
||||
// Type assertion is safe since existing context should be assignable to the existing state.
|
||||
// debt: refactor switch statement to elegantly handle this event safely.
|
||||
}
|
||||
if (event.type === 'submit_search_query') {
|
||||
return {
|
||||
status: 'search-results',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: event.submittedSearchQueryState,
|
||||
searchResults: null, // Null out previous results.
|
||||
},
|
||||
}
|
||||
}
|
||||
if (event.type === 'received_search_results' && state.context.submittedSearchQueryState) {
|
||||
return {
|
||||
status: 'search-results',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: state.context.submittedSearchQueryState,
|
||||
searchResults: event.searchResults,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
switch (state.status) {
|
||||
case 'search-home':
|
||||
case 'search-results': {
|
||||
switch (event.type) {
|
||||
case 'search_panel_disposed': {
|
||||
return {
|
||||
...state,
|
||||
status: 'search-home',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: null,
|
||||
searchResults: null,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
case 'search_panel_unfocused': {
|
||||
return {
|
||||
...state,
|
||||
status: 'idle',
|
||||
}
|
||||
}
|
||||
|
||||
case 'remote_file_focused': {
|
||||
return {
|
||||
...state,
|
||||
status: 'remote-browsing',
|
||||
}
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
case 'remote-browsing': {
|
||||
switch (event.type) {
|
||||
case 'search_panel_focused': {
|
||||
if (state.context.submittedSearchQueryState) {
|
||||
return {
|
||||
status: 'search-results',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: state.context.submittedSearchQueryState,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
status: 'search-home',
|
||||
}
|
||||
}
|
||||
case 'remote_file_unfocused': {
|
||||
return {
|
||||
...state,
|
||||
status: 'idle',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
case 'idle': {
|
||||
switch (event.type) {
|
||||
case 'search_panel_focused': {
|
||||
if (state.context.submittedSearchQueryState) {
|
||||
return {
|
||||
status: 'search-results',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: state.context.submittedSearchQueryState,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
status: 'search-home',
|
||||
}
|
||||
}
|
||||
|
||||
case 'remote_file_focused': {
|
||||
return {
|
||||
...state,
|
||||
status: 'remote-browsing',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return state
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get state() {
|
||||
return cloneDeep(states.value)
|
||||
},
|
||||
observeState: () => states.asObservable(),
|
||||
emit: event => {
|
||||
const nextState = reducer(states.value, event)
|
||||
states.next(nextState)
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -1,10 +0,0 @@
|
||||
/**
|
||||
* Built-in VS Code API exposed to webviews to communicate with the "Core" extension.
|
||||
* We typically use this as a low-level building block for the APIs used in our webviews
|
||||
* (wrapped w/ Comlink).
|
||||
*/
|
||||
export interface VsCodeApi<State = any> {
|
||||
postMessage: (message: any) => void
|
||||
getState: () => State | undefined
|
||||
setState: (state: State) => void
|
||||
}
|
||||
@ -1,147 +0,0 @@
|
||||
import * as Comlink from 'comlink'
|
||||
import type vscode from 'vscode'
|
||||
|
||||
import type { EndpointPair } from '@sourcegraph/shared/src/platform/context'
|
||||
|
||||
import {
|
||||
generateUUID,
|
||||
isNestedConnection,
|
||||
isProxyMarked,
|
||||
isUnsubscribable,
|
||||
type NestedConnectionData,
|
||||
type RelationshipType,
|
||||
} from '.'
|
||||
|
||||
// Used to scope message to panel (and `connectionId` further scopes to function call).
|
||||
let nextPanelId = 1
|
||||
|
||||
const endpointFactories = new Map<string, ((connectionId: string) => Comlink.Endpoint) | undefined>()
|
||||
|
||||
const vscodeExtensionProxyTransferHandler: Comlink.TransferHandler<
|
||||
object,
|
||||
// Receive panelId (in deserialize), no need to send it.
|
||||
// Return proxyMarkedValue in serialize so we can expose it in postMessage, but
|
||||
// only end up sending the nestedConnectionId
|
||||
{ nestedConnectionId: string; proxyMarkedValue?: object; panelId?: string; relationshipType: RelationshipType }
|
||||
> = {
|
||||
canHandle: isProxyMarked,
|
||||
serialize: proxyMarkedValue => {
|
||||
const nestedConnectionId = generateUUID()
|
||||
// Defer endpoint creation/object exposition to `postMessage` (to scope it to panel)
|
||||
|
||||
return [{ nestedConnectionId, proxyMarkedValue, relationshipType: 'webToNode' }, []]
|
||||
},
|
||||
deserialize: serialized => {
|
||||
// Create endpoint, return wrapped proxy.
|
||||
const endpointFactory = endpointFactories.get(serialized.panelId!)!
|
||||
const endpoint = endpointFactory(serialized.nestedConnectionId)
|
||||
const proxy = Comlink.wrap(endpoint)
|
||||
|
||||
return proxy
|
||||
},
|
||||
}
|
||||
|
||||
Comlink.transferHandlers.set('proxy', vscodeExtensionProxyTransferHandler)
|
||||
|
||||
export function createEndpointsForWebview(
|
||||
panel: Pick<vscode.WebviewPanel, 'onDidDispose' | 'webview'>
|
||||
): EndpointPair & { panelId: string } {
|
||||
const listenerDisposables = new WeakMap<EventListenerOrEventListenerObject, vscode.Disposable>()
|
||||
const panelId = nextPanelId.toString()
|
||||
nextPanelId++
|
||||
let disposed = false
|
||||
|
||||
// Keep track of proxied unsubscribables to clean up when a webview is closed. In that case,
|
||||
// the webview will likely be unable to send an unsubscribe message.
|
||||
const proxiedUnsubscribables = new Set<{ unsubscribe: () => unknown }>()
|
||||
|
||||
/**
|
||||
* Handles values sent to webviews that are marked to be proxied.
|
||||
*/
|
||||
function toWireValue(value: NestedConnectionData): void {
|
||||
const proxyMarkedValue = value.proxyMarkedValue!
|
||||
// The proxyMarkedValue is probably not cloneable, so don't
|
||||
// send it "over the wire"
|
||||
delete value.proxyMarkedValue
|
||||
|
||||
if (isUnsubscribable(proxyMarkedValue)) {
|
||||
proxiedUnsubscribables.add(proxyMarkedValue)
|
||||
// Debt: ideally remove unsubscribable from set when we receive a unsubscribe message.
|
||||
}
|
||||
|
||||
const endpoint = createEndpoint(value.nestedConnectionId)
|
||||
Comlink.expose(proxyMarkedValue, endpoint)
|
||||
}
|
||||
|
||||
function createEndpoint(connectionId: string): Comlink.Endpoint {
|
||||
return {
|
||||
postMessage: (message: any) => {
|
||||
const value = message.value
|
||||
const argumentList = message.argumentList
|
||||
|
||||
if (isNestedConnection(value)) {
|
||||
toWireValue(value)
|
||||
}
|
||||
if (Array.isArray(argumentList)) {
|
||||
for (const argument of argumentList) {
|
||||
const value = argument.value
|
||||
if (isNestedConnection(value)) {
|
||||
toWireValue(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!disposed) {
|
||||
panel.webview.postMessage({ ...message, connectionId, panelId }).then(
|
||||
() => {},
|
||||
error => console.error('postMessage error', error)
|
||||
)
|
||||
}
|
||||
},
|
||||
addEventListener: (type, listener) => {
|
||||
// This event listener will be called for all proxy method calls.
|
||||
// Comlink will send the message to the appropriate caller
|
||||
// based on UUID (generated internally).
|
||||
function onMessage(message: any): void {
|
||||
if (message?.connectionId === connectionId) {
|
||||
// Comlink is listening for a message event, only uses the `data` property.
|
||||
const messageEvent = {
|
||||
data: message,
|
||||
} as MessageEvent
|
||||
|
||||
return typeof listener === 'function'
|
||||
? listener(messageEvent)
|
||||
: listener.handleEvent(messageEvent)
|
||||
}
|
||||
}
|
||||
|
||||
const disposable = panel.webview.onDidReceiveMessage(onMessage)
|
||||
listenerDisposables.set(listener, disposable)
|
||||
},
|
||||
removeEventListener: (type, listener) => {
|
||||
const disposable = listenerDisposables.get(listener)
|
||||
disposable?.dispose()
|
||||
listenerDisposables.delete(listener)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
endpointFactories.set(panelId, createEndpoint)
|
||||
panel.onDidDispose(() => {
|
||||
disposed = true
|
||||
endpointFactories.delete(panelId)
|
||||
|
||||
for (const unsubscribable of proxiedUnsubscribables) {
|
||||
unsubscribable.unsubscribe()
|
||||
}
|
||||
})
|
||||
|
||||
const webviewEndpoint = createEndpoint('webview')
|
||||
const extensionEndpoint = createEndpoint('extension')
|
||||
|
||||
return {
|
||||
proxy: webviewEndpoint,
|
||||
expose: extensionEndpoint,
|
||||
panelId,
|
||||
}
|
||||
}
|
||||
@ -1,56 +0,0 @@
|
||||
import * as Comlink from 'comlink'
|
||||
import { isObject } from 'lodash'
|
||||
|
||||
import { hasProperty } from '@sourcegraph/common'
|
||||
|
||||
// Sourcegraph VS Code extension Comlink "communication layer" documentation
|
||||
// -----
|
||||
// NOTE: This is a working work-in-progress. We should be able to swap out this
|
||||
// "communication layer" with either our own VS Code webview RPC solution
|
||||
// or by applying this adapter to a fork of Comlink.
|
||||
|
||||
// MOTIVATION:
|
||||
// Comlink is a great library that makes it easy to work with Web Workers: https://github.com/GoogleChromeLabs/comlink.
|
||||
// We use it to implement a bi-directional communication channel between our web application/browser extension and
|
||||
// our Sourcegraph extension host. Given the need to sync state between {search panel <- extension "Core" -> search webview},
|
||||
// Comlink was a natural fit. However, we needed to implement some hacky adapters to get it to work for our needs:
|
||||
|
||||
// web <-> web: Default Comlink use case. Depends on ability to transfer `MessageChannel`s, which
|
||||
// is built into browsers.
|
||||
// web <-> node: Cannot transfer `MessageChannel`s between VS Code webviews and Node.js extension "Core",
|
||||
// so we have to hijack Comlink's Proxy transfer handler to manage nested Proxied objects ourselves.
|
||||
// Since the transfer handler registry is global, a web context that needs to communicate with Node.js will
|
||||
// have pushed out the default Proxy transfer handler out and therefore needs to manage web to web messages as well.
|
||||
|
||||
// Consequently, there are three endpoint generators (all return endpoints for both directions):
|
||||
// - extension <-> webview (extension context)
|
||||
// - web <-> extension (webview context)
|
||||
// - web <-> web (webview context, used for Sourcegraph extension host Web Worker)
|
||||
|
||||
export function generateUUID(): string {
|
||||
return new Array(4)
|
||||
.fill(0)
|
||||
.map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))
|
||||
.join('-')
|
||||
}
|
||||
|
||||
export type RelationshipType = 'webToWeb' | 'webToNode'
|
||||
|
||||
export interface NestedConnectionData {
|
||||
nestedConnectionId: string
|
||||
proxyMarkedValue?: object
|
||||
panelId: string
|
||||
relationshipType?: RelationshipType
|
||||
}
|
||||
|
||||
export function isNestedConnection(value: unknown): value is NestedConnectionData {
|
||||
return isObject(value) && hasProperty('nestedConnectionId')(value) && hasProperty('proxyMarkedValue')(value)
|
||||
}
|
||||
|
||||
export function isProxyMarked(value: unknown): value is Comlink.ProxyMarked {
|
||||
return isObject(value) && (value as Comlink.ProxyMarked)[Comlink.proxyMarker]
|
||||
}
|
||||
|
||||
export function isUnsubscribable(value: object): value is { unsubscribe: () => unknown } {
|
||||
return hasProperty('unsubscribe')(value) && typeof value.unsubscribe === 'function'
|
||||
}
|
||||
@ -1,199 +0,0 @@
|
||||
import * as Comlink from 'comlink'
|
||||
import { isObject } from 'lodash'
|
||||
|
||||
import type { EndpointPair } from '@sourcegraph/shared/src/platform/context'
|
||||
|
||||
import type { VsCodeApi } from '../../vsCodeApi'
|
||||
|
||||
import { generateUUID, isNestedConnection, type NestedConnectionData, type RelationshipType } from '.'
|
||||
|
||||
const panelId = self.document ? self.document.documentElement.dataset.panelId! : 'web-worker'
|
||||
|
||||
const endpointFactories: {
|
||||
webToWeb?: (connectionId: string) => Comlink.Endpoint
|
||||
webToNode?: (connectionId: string) => Comlink.Endpoint
|
||||
} = {}
|
||||
|
||||
const vscodeWebviewProxyTransferHandler: Comlink.TransferHandler<
|
||||
object,
|
||||
// Send panelId (in serialize), no need to receive it.
|
||||
// Return proxyMarkedValue in serialize so we can expose it in postMessage, but
|
||||
// only end up sending the nestedConnectionId (and relationshipType for `webToWeb`)
|
||||
{ nestedConnectionId: string; proxyMarkedValue?: object; relationshipType?: RelationshipType; panelId?: string }
|
||||
> = {
|
||||
canHandle: (value): value is Comlink.ProxyMarked =>
|
||||
isObject(value) && (value as Comlink.ProxyMarked)[Comlink.proxyMarker],
|
||||
serialize: proxyMarkedValue => {
|
||||
const nestedConnectionId = generateUUID()
|
||||
|
||||
// Add relationshipType in `postMessage`
|
||||
return [{ nestedConnectionId, proxyMarkedValue, panelId }, []]
|
||||
},
|
||||
deserialize: serialized => {
|
||||
// Get endpoint factory based on relationship type
|
||||
const endpointFactory =
|
||||
endpointFactories[serialized.relationshipType === 'webToWeb' ? 'webToWeb' : 'webToNode']!
|
||||
|
||||
// Create endpoint, return wrapped proxy.
|
||||
const endpoint = endpointFactory(serialized.nestedConnectionId)
|
||||
const proxy = Comlink.wrap(endpoint)
|
||||
|
||||
return proxy
|
||||
},
|
||||
}
|
||||
|
||||
Comlink.transferHandlers.set('proxy', vscodeWebviewProxyTransferHandler)
|
||||
|
||||
/**
|
||||
*
|
||||
* @param target Typically a WebWorker or `self` from a WebWorker (`Endpoint` for main thread).
|
||||
*/
|
||||
export function createEndpointsForWebToWeb(target: Comlink.Endpoint): {
|
||||
webview: Comlink.Endpoint
|
||||
worker: Comlink.Endpoint
|
||||
} {
|
||||
const onMessages = new WeakMap<EventListenerOrEventListenerObject, EventListener>()
|
||||
|
||||
/**
|
||||
* Handles values sent to webviews that are marked to be proxied.
|
||||
*/
|
||||
function toWireValue(value: NestedConnectionData): void {
|
||||
const proxyMarkedValue = value.proxyMarkedValue!
|
||||
// The proxyMarkedValue is probably not cloneable, so don't
|
||||
// send it "over the wire"
|
||||
delete value.proxyMarkedValue
|
||||
|
||||
value.relationshipType = 'webToWeb'
|
||||
|
||||
const endpoint = createEndpoint(value.nestedConnectionId)
|
||||
Comlink.expose(proxyMarkedValue, endpoint)
|
||||
}
|
||||
|
||||
function createEndpoint(connectionId: string): Comlink.Endpoint {
|
||||
return {
|
||||
postMessage: message => {
|
||||
// Add relationship type to all nested connection values (i.e values to be proxied).
|
||||
// TODO is the above necessary for this endpoint type?
|
||||
const value = message.value
|
||||
const argumentList = message.argumentList
|
||||
|
||||
if (isNestedConnection(value)) {
|
||||
toWireValue(value)
|
||||
}
|
||||
if (Array.isArray(argumentList)) {
|
||||
for (const argument of argumentList) {
|
||||
const value = argument.value
|
||||
if (isNestedConnection(value)) {
|
||||
toWireValue(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
target.postMessage({ ...message, connectionId, panelId })
|
||||
},
|
||||
|
||||
addEventListener: (type, listener) => {
|
||||
// This event listener will be called for all proxy method calls.
|
||||
// Comlink will send the message to the appropriate caller
|
||||
// based on UUID (generated internally).
|
||||
|
||||
function onMessage(event: MessageEvent): void {
|
||||
if (event.data?.connectionId === connectionId) {
|
||||
return typeof listener === 'function' ? listener(event) : listener.handleEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
onMessages.set(listener, onMessage as EventListener)
|
||||
|
||||
target.addEventListener('message', onMessage as EventListener)
|
||||
},
|
||||
removeEventListener: (type, listener) => {
|
||||
const onMessage = onMessages.get(listener)
|
||||
target.removeEventListener('message', onMessage ?? listener)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
endpointFactories.webToWeb = createEndpoint
|
||||
|
||||
const webview = createEndpoint('webview')
|
||||
const worker = createEndpoint('worker')
|
||||
|
||||
return {
|
||||
webview,
|
||||
worker,
|
||||
}
|
||||
}
|
||||
|
||||
export function createEndpointsForWebToNode(vscodeApi: VsCodeApi): EndpointPair {
|
||||
const onMessages = new WeakMap<EventListenerOrEventListenerObject, EventListener>()
|
||||
|
||||
/**
|
||||
* Handles values sent to the VS Code extension that are marked to be proxied.
|
||||
*/
|
||||
function toWireValue(value: NestedConnectionData): void {
|
||||
const proxyMarkedValue = value.proxyMarkedValue!
|
||||
// The proxyMarkedValue is probably not cloneable, so don't
|
||||
// send it "over the wire"
|
||||
delete value.proxyMarkedValue
|
||||
|
||||
value.relationshipType = 'webToNode'
|
||||
|
||||
const endpoint = createEndpoint(value.nestedConnectionId)
|
||||
Comlink.expose(proxyMarkedValue, endpoint)
|
||||
}
|
||||
|
||||
function createEndpoint(connectionId: string): Comlink.Endpoint {
|
||||
return {
|
||||
postMessage: message => {
|
||||
// Add relationship type to all nested connection values (i.e values to be proxied).
|
||||
// TODO is the above necessary for this endpoint type?
|
||||
const value = message.value
|
||||
const argumentList = message.argumentList
|
||||
|
||||
if (isNestedConnection(value)) {
|
||||
toWireValue(value)
|
||||
}
|
||||
if (Array.isArray(argumentList)) {
|
||||
for (const argument of argumentList) {
|
||||
const value = argument.value
|
||||
if (isNestedConnection(value)) {
|
||||
toWireValue(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vscodeApi.postMessage({ ...message, connectionId, panelId })
|
||||
},
|
||||
|
||||
addEventListener: (type, listener) => {
|
||||
// This event listener will be called for all proxy method calls.
|
||||
// Comlink will send the message to the appropriate caller
|
||||
// based on UUID (generated internally).
|
||||
function onMessage(event: MessageEvent): void {
|
||||
if (event.data?.connectionId === connectionId) {
|
||||
return typeof listener === 'function' ? listener(event) : listener.handleEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
onMessages.set(listener, onMessage as EventListener)
|
||||
|
||||
window.addEventListener('message', onMessage)
|
||||
},
|
||||
removeEventListener: (type, listener) => {
|
||||
const onMessage = onMessages.get(listener)
|
||||
window.removeEventListener('message', onMessage ?? listener)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
endpointFactories.webToNode = createEndpoint
|
||||
|
||||
const extensionEndpoint = createEndpoint('extension')
|
||||
const webviewEndpoint = createEndpoint('webview')
|
||||
|
||||
return {
|
||||
proxy: extensionEndpoint,
|
||||
expose: webviewEndpoint,
|
||||
}
|
||||
}
|
||||
@ -1,256 +0,0 @@
|
||||
import type { Observable } from 'rxjs'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import polyfillEventSource from '@sourcegraph/shared/src/polyfills/vendor/eventSource'
|
||||
import { LATEST_VERSION } from '@sourcegraph/shared/src/search/stream'
|
||||
|
||||
import { getProxyAgent } from '../backend/fetch'
|
||||
import type { initializeSourcegraphSettings } from '../backend/sourcegraphSettings'
|
||||
import { initializeCodeIntel } from '../code-intel/initialize'
|
||||
import type { ExtensionCoreAPI } from '../contract'
|
||||
import type { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
import { SearchPatternType } from '../graphql-operations'
|
||||
import { endpointRequestHeadersSetting, endpointSetting } from '../settings/endpointSetting'
|
||||
|
||||
import {
|
||||
initializeHelpSidebarWebview,
|
||||
initializeSearchPanelWebview,
|
||||
initializeSearchSidebarWebview,
|
||||
} from './initialize'
|
||||
import { scretTokenKey } from './platform/AuthProvider'
|
||||
|
||||
// Track current active webview panel to make sure only one panel exists at a time
|
||||
let currentSearchPanel: vscode.WebviewPanel | 'initializing' | undefined
|
||||
let searchSidebarWebviewView: vscode.WebviewView | 'initializing' | undefined
|
||||
|
||||
export function registerWebviews({
|
||||
context,
|
||||
extensionCoreAPI,
|
||||
initializedPanelIDs,
|
||||
sourcegraphSettings,
|
||||
fs,
|
||||
instanceURL,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
extensionCoreAPI: ExtensionCoreAPI
|
||||
initializedPanelIDs: Observable<string>
|
||||
sourcegraphSettings: ReturnType<typeof initializeSourcegraphSettings>
|
||||
fs: SourcegraphFileSystemProvider
|
||||
instanceURL: string
|
||||
}): void {
|
||||
// TODO if remote files are open from previous session, we need
|
||||
// to focus search sidebar to activate code intel (load extension host)
|
||||
|
||||
// Register URI Handler to resolve data sending back from Browser
|
||||
const handleUri = async (uri: vscode.Uri): Promise<void> => {
|
||||
const token = new URLSearchParams(uri.query).get('code')
|
||||
// TODO: Decrypt token
|
||||
// TODO: Match returnedNonce to stored nonce
|
||||
if (token && token.length > 8) {
|
||||
await context.secrets.store(scretTokenKey, token)
|
||||
await vscode.window.showInformationMessage('Token has been retreived and updated successfully')
|
||||
}
|
||||
}
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerUriHandler({
|
||||
handleUri,
|
||||
})
|
||||
)
|
||||
|
||||
// Update `EventSource` Authorization header on access token / headers change.
|
||||
// It will also be changed when the token has been changed --handled by Auth Provider
|
||||
context.subscriptions.push(
|
||||
vscode.workspace.onDidChangeConfiguration(async config => {
|
||||
const session = await vscode.authentication.getSession(endpointSetting(), [], { forceNewSession: false })
|
||||
if (config.affectsConfiguration('sourcegraph.requestHeaders') && session) {
|
||||
const newCustomHeaders = endpointRequestHeadersSetting()
|
||||
polyfillEventSource(
|
||||
session.accessToken ? { Authorization: `token ${session.accessToken}`, ...newCustomHeaders } : {},
|
||||
getProxyAgent()
|
||||
)
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
// Open Sourcegraph search tab on `sourcegraph.search` command.
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.search', async () => {
|
||||
// If text selected, submit search for it. Capture selection first.
|
||||
const activeEditor = vscode.window.activeTextEditor
|
||||
const selection = activeEditor?.selection
|
||||
const selectedQuery = activeEditor?.document.getText(selection)
|
||||
|
||||
// Focus search sidebar in case this command was the activation event,
|
||||
// as opposed to visibiilty of sidebar.
|
||||
if (!searchSidebarWebviewView) {
|
||||
focusSearchSidebar()
|
||||
}
|
||||
|
||||
if (currentSearchPanel && currentSearchPanel !== 'initializing') {
|
||||
currentSearchPanel.reveal()
|
||||
} else if (!currentSearchPanel) {
|
||||
sourcegraphSettings.refreshSettings()
|
||||
|
||||
currentSearchPanel = 'initializing'
|
||||
|
||||
const { webviewPanel, searchPanelAPI } = await initializeSearchPanelWebview({
|
||||
extensionUri: context.extensionUri,
|
||||
extensionCoreAPI,
|
||||
initializedPanelIDs,
|
||||
})
|
||||
|
||||
currentSearchPanel = webviewPanel
|
||||
|
||||
webviewPanel.onDidChangeViewState(() => {
|
||||
if (webviewPanel.active) {
|
||||
extensionCoreAPI.emit({ type: 'search_panel_focused' })
|
||||
focusSearchSidebar()
|
||||
searchPanelAPI.focusSearchBox().catch(() => {})
|
||||
}
|
||||
|
||||
if (webviewPanel.visible) {
|
||||
searchPanelAPI.focusSearchBox().catch(() => {})
|
||||
}
|
||||
|
||||
if (!webviewPanel.visible) {
|
||||
// TODO emit event (should go to idle state if not remote browsing)
|
||||
extensionCoreAPI.emit({ type: 'search_panel_unfocused' })
|
||||
}
|
||||
})
|
||||
|
||||
webviewPanel.onDidDispose(() => {
|
||||
currentSearchPanel = undefined
|
||||
// Ideally focus last used sidebar tab on search panel close. In lieu of that (for v1),
|
||||
// just focus the file explorer if the search sidebar is currently focused.
|
||||
if (searchSidebarWebviewView !== 'initializing' && searchSidebarWebviewView?.visible) {
|
||||
focusFileExplorer()
|
||||
}
|
||||
// Clear search result
|
||||
extensionCoreAPI.emit({ type: 'search_panel_disposed' })
|
||||
})
|
||||
}
|
||||
|
||||
if (selectedQuery) {
|
||||
extensionCoreAPI.streamSearch(selectedQuery, {
|
||||
patternType: SearchPatternType.standard,
|
||||
caseSensitive: false,
|
||||
version: LATEST_VERSION,
|
||||
trace: undefined,
|
||||
sourcegraphURL: instanceURL,
|
||||
})
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerWebviewViewProvider(
|
||||
'sourcegraph.searchSidebar',
|
||||
{
|
||||
// This typically will be called only once since `retainContextWhenHidden` is set to `true`.
|
||||
resolveWebviewView: (webviewView, _context, _token) => {
|
||||
const { searchSidebarAPI } = initializeSearchSidebarWebview({
|
||||
extensionUri: context.extensionUri,
|
||||
extensionCoreAPI,
|
||||
webviewView,
|
||||
})
|
||||
searchSidebarWebviewView = webviewView
|
||||
// Initialize search panel.
|
||||
openSearchPanelCommand()
|
||||
|
||||
initializeCodeIntel({ context, fs, searchSidebarAPI })
|
||||
|
||||
// Bring search panel back if it was previously closed on sidebar visibility change
|
||||
webviewView.onDidChangeVisibility(() => {
|
||||
if (webviewView.visible) {
|
||||
openSearchPanelCommand()
|
||||
}
|
||||
})
|
||||
},
|
||||
},
|
||||
{ webviewOptions: { retainContextWhenHidden: true } }
|
||||
)
|
||||
)
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerWebviewViewProvider(
|
||||
'sourcegraph.helpSidebar',
|
||||
{
|
||||
// This typically will be called only once since `retainContextWhenHidden` is set to `true`.
|
||||
resolveWebviewView: (webviewView, _context, _token) => {
|
||||
initializeHelpSidebarWebview({
|
||||
extensionUri: context.extensionUri,
|
||||
extensionCoreAPI,
|
||||
webviewView,
|
||||
})
|
||||
},
|
||||
},
|
||||
{ webviewOptions: { retainContextWhenHidden: true } }
|
||||
)
|
||||
)
|
||||
|
||||
// Clone Remote Git Repos Locally using VS Code Git API
|
||||
// https://github.com/microsoft/vscode/issues/48428
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.gitClone', async () => {
|
||||
const editor = vscode.window.activeTextEditor
|
||||
if (!editor) {
|
||||
throw new Error('No active editor')
|
||||
}
|
||||
const uri = editor.document.uri.path
|
||||
const gitUrl = `https:/${uri.split('@')[0]}.git`
|
||||
const vsCodeCloneUrl = `vscode://vscode.git/clone?url=${gitUrl}`
|
||||
await vscode.env.openExternal(vscode.Uri.parse(vsCodeCloneUrl))
|
||||
// vscode://vscode.git/clone?url=${gitUrl}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function openSearchPanelCommand(): void {
|
||||
vscode.commands.executeCommand('sourcegraph.search').then(
|
||||
() => {},
|
||||
error => {
|
||||
console.error(error)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function focusSearchSidebar(): void {
|
||||
vscode.commands.executeCommand('sourcegraph.searchSidebar.focus').then(
|
||||
() => {},
|
||||
error => {
|
||||
console.error(error)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export function focusSearchPanel(): void {
|
||||
if (currentSearchPanel && currentSearchPanel !== 'initializing') {
|
||||
currentSearchPanel.reveal()
|
||||
}
|
||||
}
|
||||
|
||||
function focusFileExplorer(): void {
|
||||
vscode.commands.executeCommand('workbench.view.explorer').then(
|
||||
() => {},
|
||||
error => {
|
||||
console.error(error)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export async function openSourcegraphLinks(uri: string): Promise<void> {
|
||||
await vscode.env.openExternal(vscode.Uri.parse(uri))
|
||||
return
|
||||
}
|
||||
|
||||
export async function copySourcegraphLinks(uri: string): Promise<void> {
|
||||
try {
|
||||
await vscode.env.clipboard.writeText(uri)
|
||||
await vscode.window.showInformationMessage('Link Copied!')
|
||||
} catch (error) {
|
||||
console.error('Error copying search link to clipboard:', error)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@ -1,131 +0,0 @@
|
||||
// Global styles provided by @reach packages. Should be imported once in the global scope.
|
||||
@import '@reach/tabs/styles';
|
||||
|
||||
@import 'wildcard/src/global-styles/base';
|
||||
@import './theming/highlight';
|
||||
|
||||
:root {
|
||||
// v2/debt: redefine our CSS variables using VS Code's CSS variables
|
||||
// instead of hackily overriding the necessary classes' properties.
|
||||
.theme-light,
|
||||
.theme-dark {
|
||||
--body-color: var(--vscode-foreground);
|
||||
--code-bg: var(--vscode-editor-background);
|
||||
--color-bg-1: var(--vscode-editor-background);
|
||||
--color-bg-2: var(--vscode-editorWidget-background);
|
||||
--border-color: var(--vscode-editor-lineHighlightBorder);
|
||||
--border-color-2: var(--vscode-editor-lineHighlightBorder);
|
||||
|
||||
// VS Code themes cannot change border radius, so we can safely hardcode it.
|
||||
--border-radius: 0;
|
||||
--popover-border-radius: 0;
|
||||
--dropdown-bg: var(--vscode-dropdown-background);
|
||||
--dropdown-border-color: var(--vscode-dropdown-border);
|
||||
--dropdown-header-color: var(--vscode-panelTitle-activeForeground);
|
||||
|
||||
.dropdown-menu {
|
||||
--body-color: var(--vscode-dropdown-foreground);
|
||||
--primary: var(--vscode-textLink-foreground); // hover background
|
||||
--color-bg-3: var(--color-bg-3); // active background
|
||||
|
||||
/* stylelint-disable-next-line scss/selector-no-redundant-nesting-selector */
|
||||
& input {
|
||||
background-color: var(--vscode-input-background) !important;
|
||||
}
|
||||
}
|
||||
|
||||
--input-bg: var(--vscode-editorWidget-background);
|
||||
--input-border-color: var(--vscode-input-border);
|
||||
--border-active-color: var(--vscode-focusBorder);
|
||||
--link-color: var(--vscode-textLink-foreground);
|
||||
--search-filter-keyword-color: var(--vscode-textLink-foreground);
|
||||
--body-bg: var(--vscode-editor-background);
|
||||
--text-muted: var(--vscode-descriptionForeground);
|
||||
--primary: var(--vscode-button-background);
|
||||
|
||||
// Debt: alert overrides
|
||||
--info-3: var(--vscode-inputValidation-infoBorder);
|
||||
--danger: var(--vscode-inputValidation-errorBackground);
|
||||
}
|
||||
|
||||
.theme-dark {
|
||||
.sourcegraph-tooltip {
|
||||
--tooltip-bg: var(--vscode-input-background);
|
||||
--tooltip-color: var(--vscode-editorWidget-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.theme-light {
|
||||
// Ensure tooltip always has a dark background with light text.
|
||||
.sourcegraph-tooltip {
|
||||
--tooltip-bg: var(--vscode-editorWidget-foreground);
|
||||
--tooltip-color: var(--vscode-input-background);
|
||||
}
|
||||
}
|
||||
|
||||
--max-homepage-container-width: 65rem;
|
||||
|
||||
// Media breakpoints
|
||||
--media-sm: 576px;
|
||||
--media-md: 768px;
|
||||
--media-lg: 992px;
|
||||
--media-xl: 1200px;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--vscode-font-family);
|
||||
font-weight: var(--vscode-font-weight);
|
||||
font-size: var(--vscode-editor-font-size);
|
||||
|
||||
--body-color: var(--vscode-dropdown-foreground);
|
||||
|
||||
&.search-sidebar {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--vscode-editor-font-family) !important;
|
||||
font-weight: var(--vscode-editor-font-weight) !important;
|
||||
font-size: var(--vscode-editor-font-size) !important;
|
||||
color: var(--vscode-editor-foreground);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
color: var(--vscode-button-foreground) !important;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--vscode-button-hoverBackground) !important;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
background-color: var(--vscode-button-secondaryBackground) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.btn-text-link {
|
||||
color: var(--vscode-textLink-foreground) !important;
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
font-weight: var(--vscode-editor-font-weight) !important;
|
||||
font-size: var(--vscode-editor-font-size) !important;
|
||||
background-color: transparent !important;
|
||||
text-align: left;
|
||||
|
||||
&:hover,
|
||||
&:focus {
|
||||
color: var(--vscode-foreground) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.input,
|
||||
.form-control {
|
||||
background-color: var(--vscode-input-background);
|
||||
color: var(--vscode-input-foreground);
|
||||
padding: 0.5rem;
|
||||
|
||||
&:focus {
|
||||
background-color: var(--vscode-input-background);
|
||||
color: var(--vscode-input-foreground);
|
||||
}
|
||||
}
|
||||
@ -1,197 +0,0 @@
|
||||
import * as Comlink from 'comlink'
|
||||
import type { Observable } from 'rxjs'
|
||||
import { filter, first } from 'rxjs/operators'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import type { ExtensionCoreAPI, HelpSidebarAPI, SearchPanelAPI, SearchSidebarAPI } from '../contract'
|
||||
import { endpointSetting } from '../settings/endpointSetting'
|
||||
|
||||
import { createEndpointsForWebview } from './comlink/extensionEndpoint'
|
||||
|
||||
interface SourcegraphWebviewConfig {
|
||||
extensionUri: vscode.Uri
|
||||
extensionCoreAPI: ExtensionCoreAPI
|
||||
}
|
||||
|
||||
export async function initializeSearchPanelWebview({
|
||||
extensionUri,
|
||||
extensionCoreAPI,
|
||||
initializedPanelIDs,
|
||||
}: SourcegraphWebviewConfig & {
|
||||
initializedPanelIDs: Observable<string>
|
||||
}): Promise<{
|
||||
searchPanelAPI: Comlink.Remote<SearchPanelAPI>
|
||||
webviewPanel: vscode.WebviewPanel
|
||||
}> {
|
||||
const webviewPath = vscode.Uri.joinPath(extensionUri, 'dist', 'webview')
|
||||
const extensionsDistributionPath = vscode.Uri.joinPath(extensionUri, 'dist', 'extensions')
|
||||
|
||||
const panel = vscode.window.createWebviewPanel('sourcegraphSearch', 'Sourcegraph', vscode.ViewColumn.One, {
|
||||
enableScripts: true,
|
||||
retainContextWhenHidden: true,
|
||||
enableFindWidget: true,
|
||||
localResourceRoots: [webviewPath, extensionsDistributionPath],
|
||||
})
|
||||
|
||||
const extensionsDistributionWebviewPath = panel.webview.asWebviewUri(extensionsDistributionPath)
|
||||
const scriptSource = panel.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'searchPanel.js'))
|
||||
const cssModuleSource = panel.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'searchPanel.css'))
|
||||
const styleSource = panel.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'style.css'))
|
||||
|
||||
const { proxy, expose, panelId } = createEndpointsForWebview(panel)
|
||||
|
||||
// Wait for the webview to initialize or else messages will be dropped
|
||||
const hasInitialized = initializedPanelIDs
|
||||
.pipe(
|
||||
filter(initializedPanelId => initializedPanelId === panelId),
|
||||
first()
|
||||
)
|
||||
.toPromise()
|
||||
|
||||
// Get a proxy for the search panel API to communicate with the Webview.
|
||||
const searchPanelAPI = Comlink.wrap<SearchPanelAPI>(proxy)
|
||||
|
||||
// Expose the "Core" extension API to the Webview.
|
||||
Comlink.expose(extensionCoreAPI, expose)
|
||||
|
||||
panel.iconPath = vscode.Uri.joinPath(extensionUri, 'images', 'logo.svg')
|
||||
|
||||
// Apply Content-Security-Policy
|
||||
// panel.webview.cspSource comes from the webview object
|
||||
panel.webview.html = `<!DOCTYPE html>
|
||||
<html lang="en" data-panel-id="${panelId}" data-extensions-dist-path=${extensionsDistributionWebviewPath.toString()}>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; child-src data: ${
|
||||
panel.webview.cspSource
|
||||
}; img-src data: vscode-resource: https:; script-src ${panel.webview.cspSource}; style-src data: ${
|
||||
panel.webview.cspSource
|
||||
} vscode-resource: 'unsafe-inline' http: https: data:; connect-src 'self' http: https:; frame-src https:; font-src ${
|
||||
panel.webview.cspSource
|
||||
};">
|
||||
<title>Sourcegraph Search</title>
|
||||
<link rel="stylesheet" href="${styleSource.toString()}" />
|
||||
<link rel="stylesheet" href="${cssModuleSource.toString()}" />
|
||||
</head>
|
||||
<body class="search-panel">
|
||||
<div id="root" />
|
||||
<script type="module" src="${scriptSource.toString()}"></script>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
await hasInitialized
|
||||
|
||||
return {
|
||||
searchPanelAPI,
|
||||
webviewPanel: panel,
|
||||
}
|
||||
}
|
||||
|
||||
// TODO expand CSP for Sourcegraph extension loading
|
||||
export function initializeSearchSidebarWebview({
|
||||
extensionUri,
|
||||
extensionCoreAPI,
|
||||
webviewView,
|
||||
}: SourcegraphWebviewConfig & {
|
||||
webviewView: vscode.WebviewView
|
||||
}): {
|
||||
searchSidebarAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
} {
|
||||
const webviewPath = vscode.Uri.joinPath(extensionUri, 'dist', 'webview')
|
||||
const extensionsDistributionPath = vscode.Uri.joinPath(extensionUri, 'dist', 'extensions')
|
||||
const extensionsDistributionWebviewPath = webviewView.webview.asWebviewUri(extensionsDistributionPath)
|
||||
|
||||
webviewView.webview.options = {
|
||||
enableScripts: true,
|
||||
localResourceRoots: [webviewPath, extensionsDistributionPath],
|
||||
}
|
||||
|
||||
const scriptSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'searchSidebar.js'))
|
||||
const cssModuleSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'searchSidebar.css'))
|
||||
const styleSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'style.css'))
|
||||
|
||||
const { proxy, expose, panelId } = createEndpointsForWebview(webviewView)
|
||||
|
||||
// Get a proxy for the Sourcegraph Webview API to communicate with the Webview.
|
||||
const searchSidebarAPI = Comlink.wrap<SearchSidebarAPI>(proxy)
|
||||
|
||||
// Expose the Sourcegraph VS Code Extension API to the Webview.
|
||||
Comlink.expose(extensionCoreAPI, expose)
|
||||
|
||||
// Apply Content-Security-Policy
|
||||
webviewView.webview.html = `<!DOCTYPE html>
|
||||
<html lang="en" data-panel-id="${panelId}" data-instance-url=${endpointSetting()} data-extensions-dist-path=${extensionsDistributionWebviewPath.toString()}>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; child-src data: ${
|
||||
webviewView.webview.cspSource
|
||||
}; worker-src blob: data:; img-src data: https:; script-src blob: https:; style-src 'unsafe-inline' ${
|
||||
webviewView.webview.cspSource
|
||||
} http: https: data:; connect-src 'self' http: https:; font-src vscode-resource: blob: https:;">
|
||||
<title>Sourcegraph Search</title>
|
||||
<link rel="stylesheet" href="${styleSource.toString()}" />
|
||||
<link rel="stylesheet" href="${cssModuleSource.toString()}" />
|
||||
</head>
|
||||
<body class="search-sidebar">
|
||||
<div id="root" />
|
||||
<script type="module" src="${scriptSource.toString()}"></script>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
return {
|
||||
searchSidebarAPI,
|
||||
}
|
||||
}
|
||||
|
||||
export function initializeHelpSidebarWebview({
|
||||
extensionUri,
|
||||
extensionCoreAPI,
|
||||
webviewView,
|
||||
}: SourcegraphWebviewConfig & {
|
||||
webviewView: vscode.WebviewView
|
||||
}): {
|
||||
helpSidebarAPI: Comlink.Remote<HelpSidebarAPI>
|
||||
} {
|
||||
const webviewPath = vscode.Uri.joinPath(extensionUri, 'dist', 'webview')
|
||||
|
||||
webviewView.webview.options = {
|
||||
enableScripts: true,
|
||||
localResourceRoots: [webviewPath],
|
||||
}
|
||||
|
||||
const scriptSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'helpSidebar.js'))
|
||||
const cssModuleSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'helpSidebar.css'))
|
||||
const styleSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'style.css'))
|
||||
|
||||
const { proxy, expose, panelId } = createEndpointsForWebview(webviewView)
|
||||
|
||||
// Get a proxy for the Sourcegraph Webview API to communicate with the Webview.
|
||||
const helpSidebarAPI = Comlink.wrap<HelpSidebarAPI>(proxy)
|
||||
|
||||
// Expose the Sourcegraph VS Code Extension API to the Webview.
|
||||
Comlink.expose(extensionCoreAPI, expose)
|
||||
|
||||
// Apply Content-Security-Policy
|
||||
webviewView.webview.html = `<!DOCTYPE html>
|
||||
<html lang="en" data-panel-id="${panelId}" >
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data: https:; font-src ${
|
||||
webviewView.webview.cspSource
|
||||
}; style-src ${webviewView.webview.cspSource}; script-src ${webviewView.webview.cspSource};">
|
||||
<title>Help and Feedback</title>
|
||||
<link rel="stylesheet" href="${styleSource.toString()}" />
|
||||
<link rel="stylesheet" href="${cssModuleSource.toString()}" />
|
||||
</head>
|
||||
<div id="root" />
|
||||
<script type="module" src="${scriptSource.toString()}"></script>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
return {
|
||||
helpSidebarAPI,
|
||||
}
|
||||
}
|
||||
@ -1,154 +0,0 @@
|
||||
import {
|
||||
authentication,
|
||||
type AuthenticationProvider,
|
||||
type AuthenticationProviderAuthenticationSessionsChangeEvent,
|
||||
type AuthenticationSession,
|
||||
commands,
|
||||
Disposable,
|
||||
type Event,
|
||||
EventEmitter,
|
||||
type SecretStorage,
|
||||
} from 'vscode'
|
||||
|
||||
import polyfillEventSource from '@sourcegraph/shared/src/polyfills/vendor/eventSource'
|
||||
|
||||
import { getProxyAgent } from '../../backend/fetch'
|
||||
import { endpointRequestHeadersSetting, endpointSetting, setEndpoint } from '../../settings/endpointSetting'
|
||||
|
||||
export const scretTokenKey = 'SOURCEGRAPH_AUTH'
|
||||
|
||||
class SourcegraphAuthSession implements AuthenticationSession {
|
||||
public readonly account = {
|
||||
id: SourcegraphAuthProvider.id,
|
||||
label: SourcegraphAuthProvider.label,
|
||||
}
|
||||
public readonly id = SourcegraphAuthProvider.id
|
||||
public readonly scopes = []
|
||||
|
||||
constructor(public readonly accessToken: string) {}
|
||||
}
|
||||
|
||||
export class SourcegraphAuthProvider implements AuthenticationProvider, Disposable {
|
||||
public static id = endpointSetting()
|
||||
private static secretKey = scretTokenKey
|
||||
public static label = scretTokenKey
|
||||
|
||||
// Kept track of token changes through out the session
|
||||
private currentToken: string | undefined
|
||||
private initializedDisposable: Disposable | undefined
|
||||
private _onDidChangeSessions = new EventEmitter<AuthenticationProviderAuthenticationSessionsChangeEvent>()
|
||||
public get onDidChangeSessions(): Event<AuthenticationProviderAuthenticationSessionsChangeEvent> {
|
||||
return this._onDidChangeSessions.event
|
||||
}
|
||||
|
||||
constructor(private readonly secretStorage: SecretStorage) {}
|
||||
|
||||
public dispose(): void {
|
||||
this.initializedDisposable?.dispose()
|
||||
}
|
||||
|
||||
private async ensureInitialized(): Promise<void> {
|
||||
if (this.initializedDisposable === undefined) {
|
||||
await this.cacheTokenFromStorage()
|
||||
this.initializedDisposable = Disposable.from(
|
||||
this.secretStorage.onDidChange(async event => {
|
||||
if (event.key === SourcegraphAuthProvider.secretKey) {
|
||||
await this.checkForUpdates()
|
||||
}
|
||||
}),
|
||||
authentication.onDidChangeSessions(async event => {
|
||||
if (event.provider.id === SourcegraphAuthProvider.id) {
|
||||
await this.checkForUpdates()
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if token has been updated across VS Code
|
||||
private async checkForUpdates(): Promise<void> {
|
||||
const added: AuthenticationSession[] = []
|
||||
const removed: AuthenticationSession[] = []
|
||||
const changed: AuthenticationSession[] = []
|
||||
const previousToken = this.currentToken
|
||||
const session = (await this.getSessions())[0]
|
||||
if (session?.accessToken && !previousToken) {
|
||||
added.push(session)
|
||||
} else if (!session?.accessToken && previousToken) {
|
||||
removed.push(session)
|
||||
} else if (session?.accessToken !== previousToken) {
|
||||
changed.push(session)
|
||||
} else {
|
||||
return
|
||||
}
|
||||
await this.cacheTokenFromStorage()
|
||||
// Update the polyfillEventSource on token changes
|
||||
polyfillEventSource(
|
||||
this.currentToken
|
||||
? { Authorization: `token ${this.currentToken}`, ...endpointRequestHeadersSetting() }
|
||||
: {},
|
||||
getProxyAgent()
|
||||
)
|
||||
this._onDidChangeSessions.fire({ added, removed, changed })
|
||||
}
|
||||
|
||||
// Get token from Storage
|
||||
private async cacheTokenFromStorage(): Promise<string | undefined> {
|
||||
const token = await this.secretStorage.get(SourcegraphAuthProvider.secretKey)
|
||||
this.currentToken = token
|
||||
return this.currentToken
|
||||
}
|
||||
|
||||
// This is called first when `vscode.authentication.getSessions` is called.
|
||||
public async getSessions(_scopes?: string[]): Promise<readonly AuthenticationSession[]> {
|
||||
await this.ensureInitialized()
|
||||
const token = await this.cacheTokenFromStorage()
|
||||
return token ? [new SourcegraphAuthSession(token)] : []
|
||||
}
|
||||
|
||||
// This is called after `this.getSessions` is called,
|
||||
// and only when `createIfNone` or `forceNewSession` are set to true
|
||||
public async createSession(_scopes: string[]): Promise<AuthenticationSession> {
|
||||
await this.ensureInitialized()
|
||||
// Get token from scret storage
|
||||
let token = await this.secretStorage.get(SourcegraphAuthProvider.secretKey)
|
||||
if (token) {
|
||||
console.log('Successfully logged in to Sourcegraph', token)
|
||||
await this.secretStorage.store(SourcegraphAuthProvider.secretKey, token)
|
||||
}
|
||||
if (!token) {
|
||||
token = ''
|
||||
}
|
||||
return new SourcegraphAuthSession(token)
|
||||
}
|
||||
|
||||
// To sign out
|
||||
public async removeSession(_sessionId: string): Promise<void> {
|
||||
await this.secretStorage.delete(SourcegraphAuthProvider.secretKey)
|
||||
console.log('Successfully logged out of Sourcegraph')
|
||||
}
|
||||
}
|
||||
|
||||
export class SourcegraphAuthActions {
|
||||
private currentEndpoint = endpointSetting()
|
||||
|
||||
constructor(private readonly secretStorage: SecretStorage) {}
|
||||
|
||||
public async login(newtoken: string, newuri: string): Promise<void> {
|
||||
try {
|
||||
await this.secretStorage.store(scretTokenKey, newtoken)
|
||||
if (this.currentEndpoint !== newuri) {
|
||||
await setEndpoint(newuri)
|
||||
}
|
||||
return
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
public async logout(): Promise<void> {
|
||||
await this.secretStorage.delete(scretTokenKey)
|
||||
await commands.executeCommand('workbench.action.reloadWindow')
|
||||
return
|
||||
}
|
||||
}
|
||||
@ -1,170 +0,0 @@
|
||||
import type * as Comlink from 'comlink'
|
||||
import * as uuid from 'uuid'
|
||||
|
||||
import { EventSource, type Event as EventType } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { version } from '../../../package.json'
|
||||
import type { ExtensionCoreAPI } from '../../contract'
|
||||
import { ANONYMOUS_USER_ID_KEY } from '../../settings/LocalStorageService'
|
||||
|
||||
import type { VsceTelemetryService } from './telemetryService'
|
||||
|
||||
// Event Logger for VS Code Extension
|
||||
export class EventLogger implements VsceTelemetryService {
|
||||
private anonymousUserID = ''
|
||||
private evenSourceType = EventSource.BACKEND || EventSource.IDEEXTENSION
|
||||
private eventID = 0
|
||||
private listeners: Set<(eventName: string) => void> = new Set()
|
||||
private vsceAPI: Comlink.Remote<ExtensionCoreAPI>
|
||||
private newInstall = false
|
||||
private editorInfo = { editor: 'vscode', version }
|
||||
|
||||
constructor(extensionAPI: Comlink.Remote<ExtensionCoreAPI>) {
|
||||
this.vsceAPI = extensionAPI
|
||||
this.initializeLogParameters()
|
||||
.then(() => {})
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use logPageView instead
|
||||
*
|
||||
* Log a pageview event (by sending it to the server).
|
||||
*/
|
||||
public logViewEvent(pageTitle: string, eventProperties?: any, publicArgument?: any, url?: string): void {
|
||||
if (pageTitle) {
|
||||
this.tracker(
|
||||
`View${pageTitle}`,
|
||||
{ ...eventProperties, ...this.editorInfo },
|
||||
{ ...publicArgument, ...this.editorInfo },
|
||||
url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a pageview.
|
||||
* Page titles should be specific and human-readable in pascal case, e.g. "SearchResults" or "Blob" or "NewOrg"
|
||||
*/
|
||||
public logPageView(eventName: string, eventProperties?: any, publicArgument?: any, url?: string): void {
|
||||
if (eventName) {
|
||||
this.tracker(
|
||||
`${eventName}Viewed`,
|
||||
{ ...eventProperties, ...this.editorInfo },
|
||||
{ ...publicArgument, ...this.editorInfo },
|
||||
url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a user action or event.
|
||||
* Event labels should be specific and follow a ${noun}${verb} structure in pascal case, e.g. "ButtonClicked" or "SignInInitiated"
|
||||
*
|
||||
* @param eventLabel: the event name.
|
||||
* @param eventProperties: event properties. These get logged to our database, but do not get
|
||||
* sent to our analytics systems. This may contain private info such as repository names or search queries.
|
||||
* @param publicArgument: event properties that include only public information. Do NOT
|
||||
* include any private information, such as full URLs that may contain private repo names or
|
||||
* search queries. The contents of this parameter are sent to our analytics systems.
|
||||
*/
|
||||
public log(eventLabel: string, eventProperties?: any, publicArgument?: any, uri?: string): void {
|
||||
if (!eventLabel) {
|
||||
return
|
||||
}
|
||||
switch (eventLabel) {
|
||||
case 'DynamicFilterClicked': {
|
||||
eventLabel = 'VSCESidebarDynamicFiltersClick'
|
||||
break
|
||||
}
|
||||
case 'SearchSnippetClicked': {
|
||||
eventLabel = 'VSCESidebarRepositoriesClick'
|
||||
break
|
||||
}
|
||||
case 'SearchReferenceOpened': {
|
||||
eventLabel = 'VSCESidebarSearchReferenceClick'
|
||||
break
|
||||
}
|
||||
}
|
||||
for (const listener of this.listeners) {
|
||||
listener(eventLabel)
|
||||
}
|
||||
this.tracker(
|
||||
eventLabel,
|
||||
{ ...eventProperties, ...this.editorInfo },
|
||||
{ ...publicArgument, ...this.editorInfo },
|
||||
uri
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the anonymous user ID and cohort ID of the user from VSCE storage utility.
|
||||
* If user doesn't have an anonymous user ID yet, a new one is generated
|
||||
* And a new ide install event will be logged
|
||||
*/
|
||||
private async initializeLogParameters(): Promise<void> {
|
||||
let anonymousUserID = await this.vsceAPI.getLocalStorageItem(ANONYMOUS_USER_ID_KEY)
|
||||
const source = await this.vsceAPI.getEventSource
|
||||
if (!anonymousUserID) {
|
||||
anonymousUserID = uuid.v4()
|
||||
this.newInstall = true
|
||||
await this.vsceAPI.setLocalStorageItem(ANONYMOUS_USER_ID_KEY, anonymousUserID)
|
||||
}
|
||||
this.anonymousUserID = anonymousUserID
|
||||
this.evenSourceType = source
|
||||
if (this.newInstall) {
|
||||
this.log('IDEInstalled')
|
||||
this.newInstall = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the anonymous identifier for this user (used to allow site admins
|
||||
* on a Sourcegraph instance to see a count of unique users on a daily,
|
||||
* weekly, and monthly basis).
|
||||
*/
|
||||
public getAnonymousUserID(): string {
|
||||
return this.anonymousUserID
|
||||
}
|
||||
|
||||
/**
|
||||
* Regular instance version format: 3.38.2
|
||||
* Insider version format: 134683_2022-03-02_5188fes0101
|
||||
*/
|
||||
public getEventSourceType(): EventSource {
|
||||
return this.evenSourceType
|
||||
}
|
||||
|
||||
/**
|
||||
* Event ID is used to deduplicate events in Amplitude.
|
||||
* This is used in the case that multiple events with the same userID and timestamp
|
||||
* are sent. https://developers.amplitude.com/docs/http-api-v2#optional-keys
|
||||
*/
|
||||
public getEventID(): number {
|
||||
this.eventID++
|
||||
return this.eventID
|
||||
}
|
||||
|
||||
public addEventLogListener(callback: (eventName: string) => void): () => void {
|
||||
this.listeners.add(callback)
|
||||
return () => this.listeners.delete(callback)
|
||||
}
|
||||
|
||||
public tracker(eventName: string, eventProperties?: unknown, publicArgument?: unknown, uri?: string): void {
|
||||
const userEventVariables: EventType = {
|
||||
event: eventName,
|
||||
userCookieID: this.getAnonymousUserID(),
|
||||
referrer: 'VSCE',
|
||||
url: uri || '',
|
||||
source: this.getEventSourceType(),
|
||||
argument: eventProperties ? JSON.stringify(eventProperties) : null,
|
||||
publicArgument: JSON.stringify(publicArgument),
|
||||
deviceID: this.getAnonymousUserID(),
|
||||
eventID: this.getEventID(),
|
||||
}
|
||||
this.vsceAPI
|
||||
.logEvents(userEventVariables)
|
||||
.then(() => {})
|
||||
.catch(error => console.log(error))
|
||||
}
|
||||
}
|
||||
@ -1,119 +0,0 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
|
||||
import type * as Comlink from 'comlink'
|
||||
import { print } from 'graphql'
|
||||
import { from, type Observable } from 'rxjs'
|
||||
|
||||
import { checkOk, type GraphQLResult } from '@sourcegraph/http-client'
|
||||
import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import type { ExecutableExtension } from '@sourcegraph/shared/src/api/extension/activation'
|
||||
import type { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import type { PlatformContext } from '@sourcegraph/shared/src/platform/context'
|
||||
import type { ExtensionManifest } from '@sourcegraph/shared/src/schema/extensionSchema'
|
||||
import type { SettingsCascadeOrError } from '@sourcegraph/shared/src/settings/settings'
|
||||
|
||||
// list of extensionID generated by build-inline-extensions script
|
||||
import extensions from '../../../code-intel-extensions.json'
|
||||
import type { ExtensionCoreAPI } from '../../contract'
|
||||
|
||||
import { EventLogger } from './EventLogger'
|
||||
import type { VsceTelemetryService } from './telemetryService'
|
||||
|
||||
export interface VSCodePlatformContext
|
||||
extends Pick<
|
||||
PlatformContext,
|
||||
| 'updateSettings'
|
||||
| 'settings'
|
||||
| 'getGraphQLClient'
|
||||
| 'getStaticExtensions'
|
||||
| 'telemetryService'
|
||||
| 'clientApplication'
|
||||
> {
|
||||
// Ensure telemetryService is non-nullable.
|
||||
telemetryService: VsceTelemetryService
|
||||
requestGraphQL: <R, V = object>(options: {
|
||||
request: string
|
||||
variables: V
|
||||
mightContainPrivateInfo: boolean
|
||||
overrideAccessToken?: string
|
||||
overrideSourcegraphURL?: string
|
||||
}) => Observable<GraphQLResult<R>>
|
||||
}
|
||||
|
||||
export function createPlatformContext(extensionCoreAPI: Comlink.Remote<ExtensionCoreAPI>): VSCodePlatformContext {
|
||||
const context: VSCodePlatformContext = {
|
||||
requestGraphQL({ request, variables, overrideAccessToken, overrideSourcegraphURL }) {
|
||||
return from(
|
||||
extensionCoreAPI.requestGraphQL(request, variables, overrideAccessToken, overrideSourcegraphURL)
|
||||
)
|
||||
},
|
||||
// TODO add true Apollo Client support for v2
|
||||
getGraphQLClient: () =>
|
||||
Promise.resolve({
|
||||
watchQuery: ({ variables, query }) =>
|
||||
from(extensionCoreAPI.requestGraphQL(print(query), variables)) as any,
|
||||
}),
|
||||
settings: wrapRemoteObservable(extensionCoreAPI.observeSourcegraphSettings()),
|
||||
// TODO: implement GQL mutation, settings refresh (called by extensions, impl w/ ext. host).
|
||||
updateSettings: () => Promise.resolve(),
|
||||
telemetryService: new EventLogger(extensionCoreAPI),
|
||||
clientApplication: 'other', // TODO add 'vscode-extension' to `clientApplication`,
|
||||
getStaticExtensions: () => getInlineExtensions(),
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
export interface WebviewPageProps {
|
||||
extensionCoreAPI: Comlink.Remote<ExtensionCoreAPI>
|
||||
platformContext: VSCodePlatformContext
|
||||
authenticatedUser: AuthenticatedUser | null
|
||||
settingsCascade: SettingsCascadeOrError
|
||||
instanceURL: string
|
||||
}
|
||||
|
||||
// Webview page context. Used to pass to aliased components.
|
||||
export const WebviewPageContext = createContext<WebviewPageProps | undefined>(undefined)
|
||||
|
||||
export function useWebviewPageContext(): WebviewPageProps {
|
||||
const context = useContext(WebviewPageContext)
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useWebviewPageContext must be used within a WebviewPageContextProvider')
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function getInlineExtensions(): Observable<ExecutableExtension[]> {
|
||||
const promises: Promise<ExecutableExtension>[] = []
|
||||
|
||||
for (const extensionID of extensions) {
|
||||
const { manifestURL, scriptURL } = getURLsForInlineExtension(extensionID)
|
||||
promises.push(
|
||||
fetch(manifestURL)
|
||||
.then(response => checkOk(response).json())
|
||||
.then(
|
||||
(manifest: ExtensionManifest): ExecutableExtension => ({
|
||||
id: extensionID,
|
||||
manifest,
|
||||
scriptURL,
|
||||
})
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return from(Promise.all(promises))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the manifest URL and script URL for a Sourcegraph extension which is inline (bundled with the browser add-on).
|
||||
*/
|
||||
function getURLsForInlineExtension(extensionID: string): { manifestURL: string; scriptURL: string } {
|
||||
const extensionsDistributionPath = document.documentElement.dataset.extensionsDistPath!
|
||||
const kebabCaseExtensionID = extensionID.replace(/^sourcegraph\//, 'sourcegraph-')
|
||||
return {
|
||||
manifestURL: `${extensionsDistributionPath}/${kebabCaseExtensionID}/package.json`,
|
||||
scriptURL: `${extensionsDistributionPath}/${kebabCaseExtensionID}/extension.js`,
|
||||
}
|
||||
}
|
||||
@ -1,2 +0,0 @@
|
||||
import '@sourcegraph/shared/src/polyfills/configure-core-js'
|
||||
import './polyfill'
|
||||
@ -1,3 +0,0 @@
|
||||
// Polyfill URL because Chrome and Firefox are not spec-compliant
|
||||
// Hostnames of URIs with custom schemes (e.g. git) are not parsed out
|
||||
import 'core-js/web/url'
|
||||
@ -1,51 +0,0 @@
|
||||
import { noop } from 'lodash'
|
||||
|
||||
import type { TelemetryService } from '@sourcegraph/shared/src/telemetry/telemetryService'
|
||||
|
||||
/**
|
||||
* Props interface that can be extended by React components depending on the TelemetryService.
|
||||
*/
|
||||
export interface VsceTelemetryProps {
|
||||
/**
|
||||
* A telemetry service implementation to log events.
|
||||
*/
|
||||
telemetryService: VsceTelemetryService
|
||||
}
|
||||
|
||||
/**
|
||||
* The telemetry service logs events.
|
||||
*/
|
||||
export interface VsceTelemetryService extends TelemetryService {
|
||||
/**
|
||||
* Log an event (by sending it to the server).
|
||||
* Provide uri manually for some events (e.g ViewRepository, ViewBlob) as webview does not provide link location
|
||||
*/
|
||||
log(eventName: string, eventProperties?: any, publicArgument?: any, uri?: string): void
|
||||
/**
|
||||
* @deprecated use logPageView instead
|
||||
*
|
||||
* Log a pageview event (by sending it to the server).
|
||||
*/
|
||||
logViewEvent(eventName: string, eventProperties?: any, publicArgument?: any, uri?: string): void
|
||||
/**
|
||||
* Log a pageview event (by sending it to the server).
|
||||
* Adheres to the new event naming policy
|
||||
*/
|
||||
logPageView(eventName: string, eventProperties?: any, publicArgument?: any, uri?: string): void
|
||||
/**
|
||||
* Listen for event logs
|
||||
*
|
||||
* @returns a cleanup/removeEventListener function
|
||||
*/
|
||||
addEventLogListener?(callback: (eventName: string) => void): () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* A noop telemetry service.
|
||||
* * Provide uri manually for some events
|
||||
*/
|
||||
export const NOOP_TELEMETRY_SERVICE: VsceTelemetryService = {
|
||||
log: noop,
|
||||
logViewEvent: noop,
|
||||
logPageView: noop,
|
||||
}
|
||||
@ -1,126 +0,0 @@
|
||||
import { createContext, useContext, useMemo } from 'react'
|
||||
|
||||
import type * as Comlink from 'comlink'
|
||||
import { noop } from 'lodash'
|
||||
|
||||
import type { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import type { RepositoryMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
|
||||
import type { ExtensionCoreAPI } from '../../contract'
|
||||
import { SourcegraphUri, type SourcegraphUriOptionals } from '../../file-system/SourcegraphUri'
|
||||
import type { VSCodePlatformContext } from '../platform/context'
|
||||
|
||||
type MinimalRepositoryMatch = Pick<RepositoryMatch, 'repository' | 'branches' | 'description'>
|
||||
|
||||
export interface MatchHandlersContext {
|
||||
openRepo: (repository: MinimalRepositoryMatch) => void
|
||||
openFile: (repositoryName: string, optional?: SourcegraphUriOptionals) => void
|
||||
openSymbol: (symbolUrl: string) => void
|
||||
openCommit: (commitUrl: string) => void
|
||||
instanceURL: string
|
||||
}
|
||||
export const MatchHandlersContext = createContext<MatchHandlersContext>({
|
||||
// Initialize in `SearchResultsView` (via `useMatchHandlers`)
|
||||
openRepo: noop,
|
||||
openFile: noop,
|
||||
openSymbol: noop,
|
||||
openCommit: noop,
|
||||
instanceURL: '',
|
||||
})
|
||||
|
||||
export function useMatchHandlers({
|
||||
platformContext,
|
||||
extensionCoreAPI,
|
||||
onRepoSelected,
|
||||
authenticatedUser,
|
||||
instanceURL,
|
||||
}: {
|
||||
platformContext: VSCodePlatformContext
|
||||
extensionCoreAPI: Comlink.Remote<ExtensionCoreAPI>
|
||||
onRepoSelected: (repositoryMatch: MinimalRepositoryMatch) => void
|
||||
authenticatedUser: AuthenticatedUser | null
|
||||
instanceURL: string
|
||||
}): Omit<MatchHandlersContext, 'instanceURL'> {
|
||||
const host = useMemo(() => new URL(instanceURL).host, [instanceURL])
|
||||
|
||||
const matchHandlers: Omit<MatchHandlersContext, 'instanceURL'> = useMemo(
|
||||
() => ({
|
||||
openRepo: repositoryMatch => {
|
||||
// noop, implementation in SearchResultsView component since the repo page depends on its state.
|
||||
// nvm, pass "onRepoSelected" prop
|
||||
onRepoSelected(repositoryMatch)
|
||||
|
||||
extensionCoreAPI
|
||||
.openSourcegraphFile(`sourcegraph://${host}/${repositoryMatch.repository}`)
|
||||
.catch(error => {
|
||||
console.error('Error opening Sourcegraph repository', error)
|
||||
})
|
||||
// Log View Event to sync search history
|
||||
// URL must be provided to render Recent Searches on Web
|
||||
platformContext.telemetryService.logPageView(
|
||||
'Repository',
|
||||
null,
|
||||
authenticatedUser !== null,
|
||||
`https://${host}/${repositoryMatch.repository}`
|
||||
)
|
||||
},
|
||||
openFile: (repositoryName, optionals) => {
|
||||
// Create sourcegraph URI
|
||||
const sourcegraphUri = SourcegraphUri.fromParts(host, repositoryName, optionals)
|
||||
|
||||
const uri = sourcegraphUri.uri + sourcegraphUri.positionSuffix()
|
||||
|
||||
// Log View Event to sync search history
|
||||
platformContext.telemetryService.logPageView(
|
||||
'Blob',
|
||||
null,
|
||||
authenticatedUser !== null,
|
||||
sourcegraphUri.uri.replace('sourcegraph://', 'https://')
|
||||
)
|
||||
|
||||
extensionCoreAPI
|
||||
.openSourcegraphFile(uri)
|
||||
.catch(error => console.error('Error opening Sourcegraph file', error))
|
||||
},
|
||||
openSymbol: (symbolUrl: string) => {
|
||||
const {
|
||||
path,
|
||||
position,
|
||||
revision,
|
||||
repositoryName,
|
||||
host: codeHost,
|
||||
} = SourcegraphUri.parse(`https:/${symbolUrl}`, window.URL)
|
||||
const sourcegraphUri = SourcegraphUri.fromParts(host, `${codeHost}/${repositoryName}`, {
|
||||
revision,
|
||||
path,
|
||||
position: position
|
||||
? {
|
||||
line: position.line - 1, // Convert to 1-based
|
||||
character: position.character - 1,
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
const uri = sourcegraphUri.uri + sourcegraphUri.positionSuffix()
|
||||
|
||||
extensionCoreAPI.openSourcegraphFile(uri).catch(error => {
|
||||
console.error('Error opening Sourcegraph file', error)
|
||||
})
|
||||
},
|
||||
openCommit: commitUrl => {
|
||||
const commitURL = new URL(commitUrl, instanceURL)
|
||||
extensionCoreAPI.openLink(commitURL.href).catch(error => {
|
||||
console.error('Error opening commit in browser', error)
|
||||
})
|
||||
|
||||
// Roadmap: open diff in VS Code instead of Sourcegraph Web.
|
||||
},
|
||||
}),
|
||||
[extensionCoreAPI, platformContext, authenticatedUser, onRepoSelected, host, instanceURL]
|
||||
)
|
||||
|
||||
return matchHandlers
|
||||
}
|
||||
|
||||
export function useOpenSearchResultsContext(): MatchHandlersContext {
|
||||
return useContext(MatchHandlersContext)
|
||||
}
|
||||
@ -1,51 +0,0 @@
|
||||
.tree-entries-section {
|
||||
// To avoid having empty columns (and thus the items appearing not flush with the left margin),
|
||||
// the component only applies this class when there are >= 6 items. This number is chosen
|
||||
// because it is greater than the maximum number of columns that will be shown and ensures that
|
||||
// at least 1 column has more than 1 item.
|
||||
// See also MIN_ENTRIES_FOR_COLUMN_LAYOUT.
|
||||
&--columns {
|
||||
column-gap: 1.5rem;
|
||||
column-width: 13rem;
|
||||
column-rule: 1px solid var(--border-color);
|
||||
border-right: solid 1px var(--border-color);
|
||||
|
||||
@media (--sm-breakpoint-up) {
|
||||
column-count: 1;
|
||||
}
|
||||
@media (--md-breakpoint-up) {
|
||||
column-count: 3;
|
||||
}
|
||||
@media (--md-breakpoint-down) {
|
||||
column-count: 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tree-entry {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
margin-left: -0.25rem;
|
||||
margin-right: -0.25rem;
|
||||
padding: 0.125rem 0.25rem;
|
||||
|
||||
break-inside: avoid-column;
|
||||
|
||||
--focus-box-shadow: none;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--color-bg-1);
|
||||
}
|
||||
|
||||
&--no-columns {
|
||||
max-width: 18rem;
|
||||
}
|
||||
}
|
||||
|
||||
.section {
|
||||
width: 100%;
|
||||
max-width: var(--media-xl);
|
||||
}
|
||||
@ -1,146 +0,0 @@
|
||||
import React, { useMemo, useState } from 'react'
|
||||
|
||||
import { mdiArrowLeft, mdiFileDocumentOutline, mdiFolderOutline, mdiSourceRepository } from '@mdi/js'
|
||||
import { VSCodeProgressRing } from '@vscode/webview-ui-toolkit/react'
|
||||
import classNames from 'classnames'
|
||||
import { catchError } from 'rxjs/operators'
|
||||
|
||||
import { fetchTreeEntries } from '@sourcegraph/shared/src/backend/repo'
|
||||
import { displayRepoName } from '@sourcegraph/shared/src/components/RepoLink'
|
||||
import type { QueryState } from '@sourcegraph/shared/src/search'
|
||||
import type { RepositoryMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
import { Icon, PageHeader, useObservable, H4, Text, Button } from '@sourcegraph/wildcard'
|
||||
|
||||
import type { WebviewPageProps } from '../platform/context'
|
||||
|
||||
import styles from './RepoView.module.scss'
|
||||
|
||||
interface RepoViewProps extends Pick<WebviewPageProps, 'extensionCoreAPI' | 'platformContext' | 'instanceURL'> {
|
||||
onBackToSearchResults: () => void
|
||||
// Debt: just use repository name and make GraphQL Repository query to get metadata.
|
||||
// This will enable more info (like description) when navigating here from file matches.
|
||||
repositoryMatch: Pick<RepositoryMatch, 'repository' | 'branches' | 'description'>
|
||||
setQueryState: (query: QueryState) => void
|
||||
}
|
||||
|
||||
export const RepoView: React.FunctionComponent<React.PropsWithChildren<RepoViewProps>> = ({
|
||||
extensionCoreAPI,
|
||||
platformContext,
|
||||
repositoryMatch,
|
||||
onBackToSearchResults,
|
||||
instanceURL,
|
||||
setQueryState,
|
||||
}) => {
|
||||
const [directoryStack, setDirectoryStack] = useState<string[]>([])
|
||||
|
||||
// File tree results are memoized, so going back isn't expensive.
|
||||
const treeEntries = useObservable(
|
||||
useMemo(
|
||||
() =>
|
||||
fetchTreeEntries({
|
||||
repoName: repositoryMatch.repository,
|
||||
commitID: '',
|
||||
revision: repositoryMatch.branches?.[0] ?? 'HEAD',
|
||||
filePath: directoryStack.length > 0 ? directoryStack.at(-1)! : '',
|
||||
requestGraphQL: platformContext.requestGraphQL,
|
||||
}).pipe(
|
||||
catchError(error => {
|
||||
console.error(error, { repositoryMatch })
|
||||
// TODO: remove and add error boundary in searchresultsview
|
||||
return []
|
||||
})
|
||||
),
|
||||
[platformContext, repositoryMatch, directoryStack]
|
||||
)
|
||||
)
|
||||
|
||||
const onPreviousDirectory = (): void => {
|
||||
const newDirectoryStack = directoryStack.slice(0, -1)
|
||||
setQueryState({
|
||||
query: `repo:^${repositoryMatch.repository}$ ${
|
||||
newDirectoryStack.length > 0 ? `file:^${newDirectoryStack.at(-1)}` : ''
|
||||
}`,
|
||||
})
|
||||
setDirectoryStack(newDirectoryStack)
|
||||
}
|
||||
|
||||
const onSelect = (isDirectory: boolean, path: string, url: string): void => {
|
||||
const host = new URL(instanceURL).host
|
||||
if (isDirectory) {
|
||||
setQueryState({ query: `repo:^${repositoryMatch.repository}$ file:^${path}` })
|
||||
setDirectoryStack([...directoryStack, path])
|
||||
} else {
|
||||
extensionCoreAPI.openSourcegraphFile(`sourcegraph://${host}${url}`).catch(error => {
|
||||
console.error('Error opening Sourcegraph file', error)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mb-3 p-2">
|
||||
<Button
|
||||
variant="link"
|
||||
outline={true}
|
||||
size="sm"
|
||||
onClick={onBackToSearchResults}
|
||||
className="test-back-to-search-view-btn shadow-none"
|
||||
>
|
||||
<Icon aria-hidden={true} className="mr-1" svgPath={mdiArrowLeft} />
|
||||
Back to search view
|
||||
</Button>
|
||||
{directoryStack.length > 0 && (
|
||||
<Button variant="link" outline={true} size="sm" onClick={onPreviousDirectory} className="shadow-none">
|
||||
<Icon aria-hidden={true} className="mr-1" svgPath={mdiArrowLeft} />
|
||||
Back to previous directory
|
||||
</Button>
|
||||
)}
|
||||
<PageHeader
|
||||
path={[{ icon: mdiSourceRepository, text: displayRepoName(repositoryMatch.repository) }]}
|
||||
className="mb-1 mt-3 test-tree-page-title"
|
||||
/>
|
||||
{repositoryMatch.description && <Text className="mt-0 text-muted">{repositoryMatch.description}</Text>}
|
||||
<div className={classNames(styles.section)}>
|
||||
<H4>Files and directories</H4>
|
||||
{treeEntries === undefined ? (
|
||||
<VSCodeProgressRing />
|
||||
) : (
|
||||
<div className={classNames('pr-2', styles.treeEntriesSectionColumns)}>
|
||||
{treeEntries.entries.map(entry => (
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
key={entry.name}
|
||||
className={classNames(
|
||||
'test-page-file-decorable shadow-none',
|
||||
styles.treeEntry,
|
||||
entry.isDirectory && 'font-weight-bold',
|
||||
`test-tree-entry-${entry.isDirectory ? 'directory' : 'file'}`,
|
||||
treeEntries.entries.length < 7 && styles.treeEntryNoColumns
|
||||
)}
|
||||
title={entry.path}
|
||||
data-testid="tree-entry"
|
||||
onClick={() => onSelect(entry.isDirectory, entry.path, entry.url)}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
'd-flex align-items-center justify-content-between test-file-decorable-name overflow-hidden'
|
||||
)}
|
||||
>
|
||||
<span>
|
||||
<Icon
|
||||
aria-label={entry.isDirectory ? 'Folder' : 'File'}
|
||||
className="mr-1 text-muted"
|
||||
svgPath={entry.isDirectory ? mdiFolderOutline : mdiFileDocumentOutline}
|
||||
/>
|
||||
{entry.name}
|
||||
{entry.isDirectory && '/'}
|
||||
</span>
|
||||
</div>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@ -1,200 +0,0 @@
|
||||
import React, { useCallback, useMemo, useState } from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import type { Observable } from 'rxjs'
|
||||
import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect'
|
||||
|
||||
import { SearchBox } from '@sourcegraph/branded'
|
||||
import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import { getUserSearchContextNamespaces, type QueryState, SearchMode } from '@sourcegraph/shared/src/search'
|
||||
import { collectMetrics } from '@sourcegraph/shared/src/search/query/metrics'
|
||||
import { appendContextFilter, sanitizeQueryForTelemetry } from '@sourcegraph/shared/src/search/query/transformer'
|
||||
import { LATEST_VERSION, type SearchMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
import { useIsLightTheme } from '@sourcegraph/shared/src/theme'
|
||||
|
||||
import { SearchPatternType } from '../../graphql-operations'
|
||||
import type { SearchHomeState } from '../../state'
|
||||
import type { WebviewPageProps } from '../platform/context'
|
||||
|
||||
import { fetchSearchContexts } from './alias/fetchSearchContext'
|
||||
import { BrandHeader } from './components/BrandHeader'
|
||||
import { HomeFooter } from './components/HomeFooter'
|
||||
|
||||
import styles from './index.module.scss'
|
||||
|
||||
export interface SearchHomeViewProps extends WebviewPageProps {
|
||||
context: SearchHomeState['context']
|
||||
}
|
||||
|
||||
export const SearchHomeView: React.FunctionComponent<React.PropsWithChildren<SearchHomeViewProps>> = ({
|
||||
extensionCoreAPI,
|
||||
authenticatedUser,
|
||||
platformContext,
|
||||
settingsCascade,
|
||||
context,
|
||||
instanceURL,
|
||||
}) => {
|
||||
const isLightTheme = useIsLightTheme()
|
||||
|
||||
// Toggling case sensitivity or pattern type does NOT trigger a new search on home view.
|
||||
const [caseSensitive, setCaseSensitivity] = useState(false)
|
||||
const [patternType, setPatternType] = useState(SearchPatternType.standard)
|
||||
const [searchMode, setSearchMode] = useState(SearchMode.SmartSearch)
|
||||
|
||||
const [userQueryState, setUserQueryState] = useState<QueryState>({
|
||||
query: '',
|
||||
})
|
||||
|
||||
const isSourcegraphDotCom = useMemo(() => {
|
||||
const hostname = new URL(instanceURL).hostname
|
||||
return hostname === 'sourcegraph.com' || hostname === 'www.sourcegraph.com'
|
||||
}, [instanceURL])
|
||||
|
||||
const onSubmit = useCallback(() => {
|
||||
extensionCoreAPI
|
||||
.streamSearch(userQueryState.query, {
|
||||
caseSensitive,
|
||||
patternType,
|
||||
searchMode,
|
||||
version: LATEST_VERSION,
|
||||
trace: undefined,
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users? Errors will typically be caught and
|
||||
// surfaced throught streaming search reuls.
|
||||
console.error(error)
|
||||
})
|
||||
|
||||
extensionCoreAPI
|
||||
.setSidebarQueryState({
|
||||
queryState: { query: userQueryState.query },
|
||||
searchCaseSensitivity: caseSensitive,
|
||||
searchPatternType: patternType,
|
||||
searchMode,
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users
|
||||
console.error('Error updating sidebar query state from panel', error)
|
||||
})
|
||||
|
||||
// Log Search History
|
||||
const hostname = new URL(instanceURL).hostname
|
||||
let queryString = `${userQueryState.query}${caseSensitive ? ' case:yes' : ''}`
|
||||
if (context.selectedSearchContextSpec) {
|
||||
queryString = appendContextFilter(queryString, context.selectedSearchContextSpec)
|
||||
}
|
||||
const metrics = queryString ? collectMetrics(queryString) : undefined
|
||||
platformContext.telemetryService.log(
|
||||
'SearchResultsQueried',
|
||||
{
|
||||
code_search: {
|
||||
query_data: {
|
||||
query: metrics,
|
||||
combined: queryString,
|
||||
empty: !queryString,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
code_search: {
|
||||
query_data: {
|
||||
// 🚨 PRIVACY: never provide any private query data in the
|
||||
// { code_search: query_data: query } property,
|
||||
// which is also potentially exported in pings data.
|
||||
query: metrics,
|
||||
|
||||
// 🚨 PRIVACY: Only collect the full query string for unauthenticated users
|
||||
// on Sourcegraph.com, and only after sanitizing to remove certain filters.
|
||||
combined:
|
||||
!authenticatedUser && isSourcegraphDotCom
|
||||
? sanitizeQueryForTelemetry(queryString)
|
||||
: undefined,
|
||||
empty: !queryString,
|
||||
},
|
||||
},
|
||||
},
|
||||
`https://${hostname}/search?q=${encodeURIComponent(queryString)}&patternType=${patternType}`
|
||||
)
|
||||
}, [
|
||||
extensionCoreAPI,
|
||||
userQueryState.query,
|
||||
caseSensitive,
|
||||
patternType,
|
||||
searchMode,
|
||||
instanceURL,
|
||||
context.selectedSearchContextSpec,
|
||||
platformContext.telemetryService,
|
||||
authenticatedUser,
|
||||
isSourcegraphDotCom,
|
||||
])
|
||||
|
||||
// Update local query state on sidebar query state updates.
|
||||
useDeepCompareEffectNoCheck(() => {
|
||||
if (context.searchSidebarQueryState.proposedQueryState?.queryState) {
|
||||
setUserQueryState(context.searchSidebarQueryState.proposedQueryState?.queryState)
|
||||
}
|
||||
}, [context.searchSidebarQueryState.proposedQueryState?.queryState])
|
||||
|
||||
const setSelectedSearchContextSpec = useCallback(
|
||||
(spec: string) => {
|
||||
extensionCoreAPI.setSelectedSearchContextSpec(spec).catch(error => {
|
||||
console.error('Error persisting search context spec.', error)
|
||||
})
|
||||
},
|
||||
[extensionCoreAPI]
|
||||
)
|
||||
|
||||
const fetchStreamSuggestions = useCallback(
|
||||
(query: string): Observable<SearchMatch[]> =>
|
||||
wrapRemoteObservable(extensionCoreAPI.fetchStreamSuggestions(query, instanceURL)),
|
||||
[extensionCoreAPI, instanceURL]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="d-flex flex-column align-items-center">
|
||||
<BrandHeader isLightTheme={isLightTheme} />
|
||||
|
||||
<div className={styles.homeSearchBoxContainer}>
|
||||
{/* eslint-disable-next-line react/forbid-elements */}
|
||||
<form
|
||||
className="d-flex my-2"
|
||||
onSubmit={event => {
|
||||
event.preventDefault()
|
||||
onSubmit()
|
||||
}}
|
||||
>
|
||||
<SearchBox
|
||||
caseSensitive={caseSensitive}
|
||||
setCaseSensitivity={setCaseSensitivity}
|
||||
patternType={patternType}
|
||||
setPatternType={setPatternType}
|
||||
searchMode={searchMode}
|
||||
setSearchMode={setSearchMode}
|
||||
isSourcegraphDotCom={isSourcegraphDotCom}
|
||||
structuralSearchDisabled={false}
|
||||
queryState={userQueryState}
|
||||
onChange={setUserQueryState}
|
||||
onSubmit={onSubmit}
|
||||
authenticatedUser={authenticatedUser}
|
||||
searchContextsEnabled={true}
|
||||
showSearchContext={true}
|
||||
showSearchContextManagement={false}
|
||||
setSelectedSearchContextSpec={setSelectedSearchContextSpec}
|
||||
selectedSearchContextSpec={context.selectedSearchContextSpec}
|
||||
fetchSearchContexts={fetchSearchContexts}
|
||||
getUserSearchContextNamespaces={getUserSearchContextNamespaces}
|
||||
fetchStreamSuggestions={fetchStreamSuggestions}
|
||||
settingsCascade={settingsCascade}
|
||||
telemetryService={platformContext.telemetryService}
|
||||
platformContext={platformContext}
|
||||
className={classNames('flex-grow-1 flex-shrink-past-contents', styles.searchBox)}
|
||||
containerClassName={styles.searchBoxContainer}
|
||||
autoFocus={true}
|
||||
/>
|
||||
</form>
|
||||
|
||||
<HomeFooter setQuery={setUserQueryState} telemetryService={platformContext.telemetryService} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,420 +0,0 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import type { Observable } from 'rxjs'
|
||||
import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect'
|
||||
|
||||
import { type IEditor, SearchBox, StreamingProgress, StreamingSearchResultsList } from '@sourcegraph/branded'
|
||||
import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import { type FetchFileParameters, fetchHighlightedFileLineRanges } from '@sourcegraph/shared/src/backend/file'
|
||||
import { getUserSearchContextNamespaces, type QueryState, type SearchMode } from '@sourcegraph/shared/src/search'
|
||||
import { collectMetrics } from '@sourcegraph/shared/src/search/query/metrics'
|
||||
import {
|
||||
appendContextFilter,
|
||||
sanitizeQueryForTelemetry,
|
||||
updateFilters,
|
||||
} from '@sourcegraph/shared/src/search/query/transformer'
|
||||
import { LATEST_VERSION, type RepositoryMatch, type SearchMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
import { buildSearchURLQuery } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
import type { SearchPatternType } from '../../graphql-operations'
|
||||
import type { SearchResultsState } from '../../state'
|
||||
import type { WebviewPageProps } from '../platform/context'
|
||||
|
||||
import { fetchSearchContexts } from './alias/fetchSearchContext'
|
||||
import { setFocusSearchBox } from './api'
|
||||
import { SearchResultsInfoBar } from './components/SearchResultsInfoBar'
|
||||
import { MatchHandlersContext, useMatchHandlers } from './MatchHandlersContext'
|
||||
import { RepoView } from './RepoView'
|
||||
|
||||
import styles from './index.module.scss'
|
||||
|
||||
export interface SearchResultsViewProps extends WebviewPageProps {
|
||||
context: SearchResultsState['context']
|
||||
}
|
||||
|
||||
export const SearchResultsView: React.FunctionComponent<React.PropsWithChildren<SearchResultsViewProps>> = ({
|
||||
extensionCoreAPI,
|
||||
authenticatedUser,
|
||||
platformContext,
|
||||
settingsCascade,
|
||||
context,
|
||||
instanceURL,
|
||||
}) => {
|
||||
const [userQueryState, setUserQueryState] = useState<QueryState>(context.submittedSearchQueryState.queryState)
|
||||
const [repoToShow, setRepoToShow] = useState<Pick<
|
||||
RepositoryMatch,
|
||||
'repository' | 'branches' | 'description'
|
||||
> | null>(null)
|
||||
|
||||
const isSourcegraphDotCom = useMemo(() => {
|
||||
const hostname = new URL(instanceURL).hostname
|
||||
return hostname === 'sourcegraph.com' || hostname === 'www.sourcegraph.com'
|
||||
}, [instanceURL])
|
||||
|
||||
// Editor focus.
|
||||
const editorReference = useRef<IEditor>()
|
||||
const setEditor = useCallback((editor: IEditor) => {
|
||||
editorReference.current = editor
|
||||
setTimeout(() => editor.focus(), 0)
|
||||
}, [])
|
||||
|
||||
// TODO explain
|
||||
useEffect(() => {
|
||||
setFocusSearchBox(() => editorReference.current?.focus())
|
||||
|
||||
return () => {
|
||||
setFocusSearchBox(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const onChange = useCallback(
|
||||
(newState: QueryState) => {
|
||||
setUserQueryState(newState)
|
||||
|
||||
extensionCoreAPI
|
||||
.setSidebarQueryState({
|
||||
queryState: newState,
|
||||
searchCaseSensitivity: context.submittedSearchQueryState?.searchCaseSensitivity,
|
||||
searchPatternType: context.submittedSearchQueryState?.searchPatternType,
|
||||
searchMode: context.submittedSearchQueryState?.searchMode,
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users
|
||||
console.error('Error updating sidebar query state from panel', error)
|
||||
})
|
||||
},
|
||||
[
|
||||
extensionCoreAPI,
|
||||
context.submittedSearchQueryState.searchCaseSensitivity,
|
||||
context.submittedSearchQueryState.searchPatternType,
|
||||
context.submittedSearchQueryState.searchMode,
|
||||
]
|
||||
)
|
||||
|
||||
const [allExpanded, setAllExpanded] = useState(false)
|
||||
const onExpandAllResultsToggle = useCallback(() => {
|
||||
setAllExpanded(oldValue => !oldValue)
|
||||
platformContext.telemetryService.log(allExpanded ? 'allResultsExpanded' : 'allResultsCollapsed')
|
||||
}, [allExpanded, platformContext])
|
||||
|
||||
// Update local query state on sidebar query state updates.
|
||||
useDeepCompareEffectNoCheck(() => {
|
||||
if (context.searchSidebarQueryState.proposedQueryState?.queryState) {
|
||||
setUserQueryState(context.searchSidebarQueryState.proposedQueryState?.queryState)
|
||||
}
|
||||
}, [context.searchSidebarQueryState.proposedQueryState?.queryState])
|
||||
|
||||
// Update local search query state on sidebar search submission.
|
||||
useDeepCompareEffectNoCheck(() => {
|
||||
setUserQueryState(context.submittedSearchQueryState.queryState)
|
||||
// It's a whole new object on each state update, so we need
|
||||
// to compare (alternatively, construct full query TODO)
|
||||
|
||||
// Clear repo view
|
||||
setRepoToShow(null)
|
||||
}, [context.submittedSearchQueryState.queryState])
|
||||
|
||||
// Track sidebar + keyboard shortcut search submissions
|
||||
useEffect(() => {
|
||||
platformContext.telemetryService.log('IDESearchSubmitted')
|
||||
}, [platformContext, context.submittedSearchQueryState.queryState.query])
|
||||
|
||||
const onSubmit = useCallback(
|
||||
(options?: {
|
||||
caseSensitive?: boolean
|
||||
patternType?: SearchPatternType
|
||||
newQuery?: string
|
||||
searchMode?: SearchMode
|
||||
}) => {
|
||||
const previousSearchQueryState = context.submittedSearchQueryState
|
||||
|
||||
const query = options?.newQuery ?? userQueryState.query
|
||||
const caseSensitive = options?.caseSensitive ?? previousSearchQueryState.searchCaseSensitivity
|
||||
const patternType = options?.patternType ?? previousSearchQueryState.searchPatternType
|
||||
const searchMode = options?.searchMode ?? previousSearchQueryState.searchMode
|
||||
|
||||
extensionCoreAPI
|
||||
.streamSearch(query, {
|
||||
caseSensitive,
|
||||
patternType,
|
||||
searchMode,
|
||||
version: LATEST_VERSION,
|
||||
trace: undefined,
|
||||
chunkMatches: true,
|
||||
})
|
||||
.then(() => {
|
||||
editorReference.current?.focus()
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users? Errors will typically be caught and
|
||||
// surfaced throught streaming search reuls.
|
||||
console.error(error)
|
||||
})
|
||||
|
||||
extensionCoreAPI
|
||||
.setSidebarQueryState({
|
||||
queryState: { query },
|
||||
searchCaseSensitivity: caseSensitive,
|
||||
searchPatternType: patternType,
|
||||
searchMode,
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users
|
||||
console.error('Error updating sidebar query state from panel', error)
|
||||
})
|
||||
|
||||
// Log Search History
|
||||
const hostname = new URL(instanceURL).hostname
|
||||
let queryString = `${userQueryState.query}${caseSensitive ? ' case:yes' : ''}`
|
||||
if (context.selectedSearchContextSpec) {
|
||||
queryString = appendContextFilter(queryString, context.selectedSearchContextSpec)
|
||||
}
|
||||
const metrics = queryString ? collectMetrics(queryString) : undefined
|
||||
platformContext.telemetryService.log(
|
||||
'SearchResultsQueried',
|
||||
{
|
||||
code_search: {
|
||||
query_data: {
|
||||
query: metrics,
|
||||
combined: queryString,
|
||||
empty: !queryString,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
code_search: {
|
||||
query_data: {
|
||||
// 🚨 PRIVACY: never provide any private query data in the
|
||||
// { code_search: query_data: query } property,
|
||||
// which is also potentially exported in pings data.
|
||||
query: metrics,
|
||||
|
||||
// 🚨 PRIVACY: Only collect the full query string for unauthenticated users
|
||||
// on Sourcegraph.com, and only after sanitizing to remove certain filters.
|
||||
combined:
|
||||
!authenticatedUser && isSourcegraphDotCom
|
||||
? sanitizeQueryForTelemetry(queryString)
|
||||
: undefined,
|
||||
empty: !queryString,
|
||||
},
|
||||
},
|
||||
},
|
||||
`https://${hostname}/search?q=${encodeURIComponent(queryString)}&patternType=${patternType}`
|
||||
)
|
||||
// Clear repo view
|
||||
setRepoToShow(null)
|
||||
},
|
||||
[
|
||||
context.submittedSearchQueryState,
|
||||
context.selectedSearchContextSpec,
|
||||
userQueryState.query,
|
||||
extensionCoreAPI,
|
||||
instanceURL,
|
||||
platformContext.telemetryService,
|
||||
authenticatedUser,
|
||||
isSourcegraphDotCom,
|
||||
]
|
||||
)
|
||||
|
||||
// Submit new search on change
|
||||
const setCaseSensitivity = useCallback(
|
||||
(caseSensitive: boolean) => {
|
||||
onSubmit({ caseSensitive })
|
||||
},
|
||||
[onSubmit]
|
||||
)
|
||||
|
||||
// Submit new search on change
|
||||
const setPatternType = useCallback(
|
||||
(patternType: SearchPatternType) => {
|
||||
onSubmit({ patternType })
|
||||
},
|
||||
[onSubmit]
|
||||
)
|
||||
|
||||
const setSearchMode = useCallback(
|
||||
(searchMode: SearchMode) => {
|
||||
onSubmit({ searchMode })
|
||||
},
|
||||
[onSubmit]
|
||||
)
|
||||
|
||||
const fetchHighlightedFileLineRangesWithContext = useCallback(
|
||||
(parameters: FetchFileParameters) => fetchHighlightedFileLineRanges({ ...parameters, platformContext }),
|
||||
[platformContext]
|
||||
)
|
||||
|
||||
const fetchStreamSuggestions = useCallback(
|
||||
(query: string): Observable<SearchMatch[]> =>
|
||||
wrapRemoteObservable(extensionCoreAPI.fetchStreamSuggestions(query, instanceURL)),
|
||||
[extensionCoreAPI, instanceURL]
|
||||
)
|
||||
|
||||
const setSelectedSearchContextSpec = useCallback(
|
||||
(spec: string) => {
|
||||
extensionCoreAPI
|
||||
.setSelectedSearchContextSpec(spec)
|
||||
.catch(error => {
|
||||
console.error('Error persisting search context spec.', error)
|
||||
})
|
||||
.finally(() => {
|
||||
// Execute search with new context state
|
||||
onSubmit()
|
||||
})
|
||||
},
|
||||
[extensionCoreAPI, onSubmit]
|
||||
)
|
||||
|
||||
const onSearchAgain = useCallback(
|
||||
(additionalFilters: string[]) => {
|
||||
platformContext.telemetryService.log('SearchSkippedResultsAgainClicked')
|
||||
onSubmit({
|
||||
newQuery: applyAdditionalFilters(context.submittedSearchQueryState.queryState.query, additionalFilters),
|
||||
})
|
||||
},
|
||||
[context.submittedSearchQueryState.queryState, platformContext, onSubmit]
|
||||
)
|
||||
|
||||
const onShareResultsClick = useCallback(async (): Promise<void> => {
|
||||
const queryState = context.submittedSearchQueryState
|
||||
|
||||
const path = `/search?${buildSearchURLQuery(
|
||||
queryState.queryState.query,
|
||||
queryState.searchPatternType,
|
||||
queryState.searchCaseSensitivity,
|
||||
context.selectedSearchContextSpec
|
||||
)}&utm_campaign=vscode-extension&utm_medium=direct_traffic&utm_source=vscode-extension&utm_content=save-search`
|
||||
await extensionCoreAPI.copyLink(new URL(path, instanceURL).href)
|
||||
platformContext.telemetryService.log('VSCEShareLinkClick')
|
||||
}, [context, instanceURL, extensionCoreAPI, platformContext])
|
||||
|
||||
const fullQuery = useMemo(
|
||||
() =>
|
||||
appendContextFilter(
|
||||
context.submittedSearchQueryState.queryState.query ?? '',
|
||||
context.selectedSearchContextSpec
|
||||
),
|
||||
[context]
|
||||
)
|
||||
|
||||
const matchHandlers = useMatchHandlers({
|
||||
platformContext,
|
||||
extensionCoreAPI,
|
||||
authenticatedUser,
|
||||
onRepoSelected: setRepoToShow,
|
||||
instanceURL,
|
||||
})
|
||||
|
||||
const clearRepositoryToShow = (): void => setRepoToShow(null)
|
||||
|
||||
return (
|
||||
<div className={styles.resultsViewLayout}>
|
||||
{/* eslint-disable-next-line react/forbid-elements */}
|
||||
<form
|
||||
className="d-flex w-100 my-2 pb-2 border-bottom"
|
||||
onSubmit={event => {
|
||||
event.preventDefault()
|
||||
onSubmit()
|
||||
}}
|
||||
>
|
||||
<SearchBox
|
||||
caseSensitive={context.submittedSearchQueryState?.searchCaseSensitivity}
|
||||
setCaseSensitivity={setCaseSensitivity}
|
||||
patternType={context.submittedSearchQueryState?.searchPatternType}
|
||||
setPatternType={setPatternType}
|
||||
searchMode={context.submittedSearchQueryState?.searchMode}
|
||||
setSearchMode={setSearchMode}
|
||||
isSourcegraphDotCom={isSourcegraphDotCom}
|
||||
structuralSearchDisabled={false}
|
||||
queryState={userQueryState}
|
||||
onChange={onChange}
|
||||
onSubmit={onSubmit}
|
||||
authenticatedUser={authenticatedUser}
|
||||
searchContextsEnabled={true}
|
||||
showSearchContext={true}
|
||||
showSearchContextManagement={false}
|
||||
setSelectedSearchContextSpec={setSelectedSearchContextSpec}
|
||||
selectedSearchContextSpec={context.selectedSearchContextSpec}
|
||||
fetchSearchContexts={fetchSearchContexts}
|
||||
getUserSearchContextNamespaces={getUserSearchContextNamespaces}
|
||||
fetchStreamSuggestions={fetchStreamSuggestions}
|
||||
settingsCascade={settingsCascade}
|
||||
telemetryService={platformContext.telemetryService}
|
||||
platformContext={platformContext}
|
||||
className={classNames('flex-grow-1 flex-shrink-past-contents', styles.searchBox)}
|
||||
containerClassName={styles.searchBoxContainer}
|
||||
autoFocus={true}
|
||||
onEditorCreated={setEditor}
|
||||
/>
|
||||
</form>
|
||||
|
||||
{!repoToShow ? (
|
||||
<div className={styles.resultsViewScrollContainer}>
|
||||
<SearchResultsInfoBar
|
||||
onShareResultsClick={onShareResultsClick}
|
||||
extensionCoreAPI={extensionCoreAPI}
|
||||
patternType={context.submittedSearchQueryState.searchPatternType}
|
||||
authenticatedUser={authenticatedUser}
|
||||
platformContext={platformContext}
|
||||
stats={
|
||||
<StreamingProgress
|
||||
query={context.submittedSearchQueryState.queryState.query}
|
||||
progress={
|
||||
context.searchResults?.progress || { durationMs: 0, matchCount: 0, skipped: [] }
|
||||
}
|
||||
state={context.searchResults?.state || 'loading'}
|
||||
onSearchAgain={onSearchAgain}
|
||||
showTrace={false}
|
||||
telemetryService={platformContext.telemetryService}
|
||||
/>
|
||||
}
|
||||
allExpanded={allExpanded}
|
||||
onExpandAllResultsToggle={onExpandAllResultsToggle}
|
||||
instanceURL={instanceURL}
|
||||
fullQuery={fullQuery}
|
||||
/>
|
||||
<MatchHandlersContext.Provider value={{ ...matchHandlers, instanceURL }}>
|
||||
<StreamingSearchResultsList
|
||||
settingsCascade={settingsCascade}
|
||||
telemetryService={platformContext.telemetryService}
|
||||
allExpanded={allExpanded}
|
||||
// Debt: dotcom prop used only for "run search" link
|
||||
// for search examples. Fix on VSCE.
|
||||
isSourcegraphDotCom={false}
|
||||
searchContextsEnabled={true}
|
||||
platformContext={platformContext}
|
||||
results={context.searchResults ?? undefined}
|
||||
fetchHighlightedFileLineRanges={fetchHighlightedFileLineRangesWithContext}
|
||||
executedQuery={context.submittedSearchQueryState.queryState.query}
|
||||
resultClassName="mr-0"
|
||||
showQueryExamplesOnNoResultsPage={true}
|
||||
setQueryState={setUserQueryState}
|
||||
selectedSearchContextSpec={context.selectedSearchContextSpec}
|
||||
/>
|
||||
</MatchHandlersContext.Provider>
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.resultsViewScrollContainer}>
|
||||
<RepoView
|
||||
extensionCoreAPI={extensionCoreAPI}
|
||||
platformContext={platformContext}
|
||||
onBackToSearchResults={clearRepositoryToShow}
|
||||
repositoryMatch={repoToShow}
|
||||
setQueryState={setUserQueryState}
|
||||
instanceURL={instanceURL}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const applyAdditionalFilters = (query: string, additionalFilters: string[]): string => {
|
||||
let newQuery = query
|
||||
for (const filter of additionalFilters) {
|
||||
const fieldValue = filter.split(':', 2)
|
||||
newQuery = updateFilters(newQuery, fieldValue[0], fieldValue[1])
|
||||
}
|
||||
return newQuery
|
||||
}
|
||||
@ -1,112 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
import VisuallyHidden from '@reach/visually-hidden'
|
||||
|
||||
import { SearchResultStyles as styles, LegacyResultContainer, CommitSearchResultMatch } from '@sourcegraph/branded'
|
||||
import { Timestamp } from '@sourcegraph/branded/src/components/Timestamp'
|
||||
import { displayRepoName } from '@sourcegraph/shared/src/components/RepoLink'
|
||||
import type { PlatformContextProps } from '@sourcegraph/shared/src/platform/context'
|
||||
import { type CommitMatch, getCommitMatchUrl } from '@sourcegraph/shared/src/search/stream'
|
||||
import { Button, Code } from '@sourcegraph/wildcard'
|
||||
|
||||
import { useOpenSearchResultsContext } from '../MatchHandlersContext'
|
||||
|
||||
interface Props extends PlatformContextProps<'requestGraphQL'> {
|
||||
result: CommitMatch
|
||||
repoName: string
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
onSelect: () => void
|
||||
openInNewTab?: boolean
|
||||
containerClassName?: string
|
||||
as?: React.ElementType
|
||||
index: number
|
||||
}
|
||||
|
||||
export const CommitSearchResult: React.FunctionComponent<Props> = ({
|
||||
result,
|
||||
icon,
|
||||
platformContext,
|
||||
onSelect,
|
||||
openInNewTab,
|
||||
containerClassName,
|
||||
as,
|
||||
index,
|
||||
}) => {
|
||||
/**
|
||||
* Use the custom hook useIsTruncated to check if overflow: ellipsis is activated for the element
|
||||
* We want to do it on mouse enter as browser window size might change after the element has been
|
||||
* loaded initially
|
||||
*/
|
||||
const { openRepo, openCommit, instanceURL } = useOpenSearchResultsContext()
|
||||
|
||||
const renderTitle = (): JSX.Element => (
|
||||
<div className={styles.title}>
|
||||
<span className="test-search-result-label ml-1 flex-shrink-past-contents text-truncate">
|
||||
<>
|
||||
<Button
|
||||
className="btn-text-link"
|
||||
onClick={() =>
|
||||
openRepo({
|
||||
repository: result.repository,
|
||||
branches: [result.oid],
|
||||
})
|
||||
}
|
||||
>
|
||||
{displayRepoName(result.repository)}
|
||||
</Button>
|
||||
{' › '}
|
||||
<Button className="btn-text-link" onClick={() => openCommit(getCommitMatchUrl(result))}>
|
||||
{result.authorName}
|
||||
</Button>
|
||||
<span aria-hidden={true}>{': '}</span>
|
||||
<Button className="btn-text-link" onClick={() => openCommit(getCommitMatchUrl(result))}>
|
||||
{result.message.split('\n', 1)[0]}
|
||||
</Button>
|
||||
</>
|
||||
</span>
|
||||
<span className={styles.spacer} />
|
||||
{result.type === 'commit' && (
|
||||
<Button className="btn-text-link" onClick={() => openCommit(getCommitMatchUrl(result))}>
|
||||
<Code className={styles.commitOid}>
|
||||
<VisuallyHidden>Commit hash:</VisuallyHidden>
|
||||
{result.oid.slice(0, 7)}
|
||||
<VisuallyHidden>,</VisuallyHidden>
|
||||
</Code>{' '}
|
||||
<VisuallyHidden>Committed</VisuallyHidden>
|
||||
<Timestamp date={result.authorDate} noAbout={true} strict={true} />
|
||||
</Button>
|
||||
)}
|
||||
{result.repoStars && <div className={styles.divider} />}
|
||||
</div>
|
||||
)
|
||||
|
||||
const renderBody = (): JSX.Element => (
|
||||
<CommitSearchResultMatch
|
||||
key={result.url}
|
||||
item={{
|
||||
...result,
|
||||
// Make it an absolute URL to open in browser.
|
||||
url: new URL(result.url, instanceURL).href,
|
||||
}}
|
||||
platformContext={platformContext}
|
||||
openInNewTab={openInNewTab}
|
||||
/>
|
||||
)
|
||||
|
||||
return (
|
||||
<LegacyResultContainer
|
||||
as={as}
|
||||
index={index}
|
||||
icon={icon}
|
||||
collapsible={false}
|
||||
defaultExpanded={true}
|
||||
title={renderTitle()}
|
||||
resultType={result.type}
|
||||
onResultClicked={onSelect}
|
||||
expandedChildren={renderBody()}
|
||||
className={containerClassName}
|
||||
repoName={result.repository}
|
||||
repoStars={result.repoStars}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@ -1,315 +0,0 @@
|
||||
import React, { type MouseEvent, type KeyboardEvent, useCallback } from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import type * as H from 'history'
|
||||
import type { Observable } from 'rxjs'
|
||||
import { map } from 'rxjs/operators'
|
||||
|
||||
import { FileMatchChildrenStyles as styles, CodeExcerpt } from '@sourcegraph/branded'
|
||||
import type { HoverMerged } from '@sourcegraph/client-api'
|
||||
import type { Hoverifier } from '@sourcegraph/codeintellify'
|
||||
import { appendLineRangeQueryParameter, toPositionOrRangeQueryParameter } from '@sourcegraph/common'
|
||||
import type { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem'
|
||||
import type { FetchFileParameters } from '@sourcegraph/shared/src/backend/file'
|
||||
import type { MatchGroup } from '@sourcegraph/shared/src/components/ranking/PerFileResultRanking'
|
||||
import type { Controller as ExtensionsController } from '@sourcegraph/shared/src/extensions/controller'
|
||||
import type { HoverContext } from '@sourcegraph/shared/src/hover/HoverOverlay.types'
|
||||
import {
|
||||
type ContentMatch,
|
||||
type SymbolMatch,
|
||||
type PathMatch,
|
||||
getFileMatchUrl,
|
||||
} from '@sourcegraph/shared/src/search/stream'
|
||||
import { isSettingsValid, type SettingsCascadeProps } from '@sourcegraph/shared/src/settings/settings'
|
||||
import { SymbolKind } from '@sourcegraph/shared/src/symbols/SymbolKind'
|
||||
import type { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
|
||||
import { Button, Code } from '@sourcegraph/wildcard'
|
||||
|
||||
import type { HighlightLineRange } from '../../../graphql-operations'
|
||||
import { useOpenSearchResultsContext } from '../MatchHandlersContext'
|
||||
|
||||
interface FileMatchProps extends SettingsCascadeProps, TelemetryProps {
|
||||
location?: H.Location
|
||||
result: ContentMatch | SymbolMatch | PathMatch
|
||||
grouped: MatchGroup[]
|
||||
/* Clicking on a match opens the link in a new tab */
|
||||
openInNewTab?: boolean
|
||||
fetchHighlightedFileLineRanges: (parameters: FetchFileParameters, force?: boolean) => Observable<string[][]>
|
||||
extensionsController?: Pick<ExtensionsController, 'extHostAPI'>
|
||||
hoverifier?: Hoverifier<HoverContext, HoverMerged, ActionItemAction>
|
||||
}
|
||||
|
||||
/**
|
||||
* This helper function determines whether a mouse/click event was triggered as
|
||||
* a result of selecting text in search results.
|
||||
* There are at least to ways to do this:
|
||||
*
|
||||
* - Tracking `mouseup`, `mousemove` and `mousedown` events. The occurrence of
|
||||
* a `mousemove` event would indicate a text selection. However, users
|
||||
* might slightly move the mouse while clicking, and solutions that would
|
||||
* take this into account seem fragile.
|
||||
* - (implemented here) Inspect the Selection object returned by
|
||||
* `window.getSelection()`.
|
||||
*
|
||||
* CAVEAT: Chromium and Firefox (and maybe other browsers) behave
|
||||
* differently when a search result is clicked *after* text selection was
|
||||
* made:
|
||||
*
|
||||
* - Firefox will clear the selection before executing the click event
|
||||
* handler, i.e. the search result will be opened.
|
||||
* - Chrome will only clear the selection if the click happens *outside*
|
||||
* of the selected text (in which case the search result will be
|
||||
* opened). If the click happens inside the selected text the selection
|
||||
* will be cleared only *after* executing the click event handler.
|
||||
*/
|
||||
function isTextSelectionEvent(event: MouseEvent<HTMLElement>): boolean {
|
||||
const selection = window.getSelection()
|
||||
|
||||
// Text selections are always ranges. Should the type not be set, verify
|
||||
// that the selection is not empty.
|
||||
if (selection && (selection.type === 'Range' || selection.toString() !== '')) {
|
||||
// Firefox specific: Because our code excerpts are implemented as tables,
|
||||
// CTRL+click would select the table cell. Since users don't know that we
|
||||
// use tables, the most likely wanted to open the search results in a new
|
||||
// tab instead though.
|
||||
if ((event.ctrlKey || event.metaKey) && selection.anchorNode?.nodeName === 'TR') {
|
||||
// Ugly side effect: We don't want the table cell to be highlighted.
|
||||
// The focus style that Firefox uses doesn't seem to be affected by
|
||||
// CSS so instead we clear the selection.
|
||||
selection.empty()
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper function to replicate browser behavior when clicking on links.
|
||||
* A very common interaction is to open links in a new in the _background_ via
|
||||
* CTRL/CMD + click or middle click.
|
||||
* Unfortunately `window.open` doesn't give us much control over how the new
|
||||
* window/tab should be opened, and the behavior is inconcistent between
|
||||
* browsers.
|
||||
* In order to replicate the standard behvior as much as possible this function
|
||||
* dynamically creates an `<a>` element and triggers a click event on it.
|
||||
*/
|
||||
function openLinkInNewTab(
|
||||
url: string,
|
||||
event: Pick<MouseEvent, 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>,
|
||||
button: 'primary' | 'middle'
|
||||
): void {
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.style.display = 'none'
|
||||
link.target = '_blank'
|
||||
link.rel = 'noopener noreferrer'
|
||||
const clickEvent = new window.MouseEvent('click', {
|
||||
bubbles: false,
|
||||
altKey: event.altKey,
|
||||
shiftKey: event.shiftKey,
|
||||
// Regarding middle click: Setting "button: 1:" doesn't seem to suffice:
|
||||
// Firefox doesn't react to the event at all, Chromium opens the tab in
|
||||
// the foreground. So in order to simulate a middle click, we set
|
||||
// ctrlKey and metaKey to `true` instead.
|
||||
ctrlKey: button === 'middle' ? true : event.ctrlKey,
|
||||
metaKey: button === 'middle' ? true : event.metaKey,
|
||||
view: window,
|
||||
})
|
||||
|
||||
// It looks the link has to be part of the document, otherwise Firefox won't
|
||||
// trigger the default behavior (it works without appending in Chromium).
|
||||
document.body.append(link)
|
||||
link.dispatchEvent(clickEvent)
|
||||
link.remove()
|
||||
}
|
||||
|
||||
/**
|
||||
* Since we are not using a real link anymore, we have to simulate opening
|
||||
* the file in a new tab when the search result is clicked on with the
|
||||
* middle mouse button.
|
||||
* This handler is bound to the `mouseup` event because the `auxclick`
|
||||
* (https://w3c.github.io/uievents/#event-type-auxclick) event is not
|
||||
* support by all browsers yet (https://caniuse.com/?search=auxclick)
|
||||
*/
|
||||
function navigateToFileOnMiddleMouseButtonClick(event: MouseEvent<HTMLElement>): void {
|
||||
const href = event.currentTarget.getAttribute('data-href')
|
||||
if (href && event.button === 1) {
|
||||
openLinkInNewTab(href, event, 'middle')
|
||||
}
|
||||
}
|
||||
|
||||
export const FileMatchChildren: React.FunctionComponent<React.PropsWithChildren<FileMatchProps>> = props => {
|
||||
const { result, grouped, fetchHighlightedFileLineRanges, telemetryService } = props
|
||||
|
||||
const { openFile, openSymbol } = useOpenSearchResultsContext()
|
||||
|
||||
const fetchHighlightedFileRangeLines = React.useCallback(
|
||||
(startLine: number, endLine: number) => {
|
||||
const startTime = Date.now()
|
||||
return fetchHighlightedFileLineRanges(
|
||||
{
|
||||
repoName: result.repository,
|
||||
commitID: result.commit || '',
|
||||
filePath: result.path,
|
||||
disableTimeout: false,
|
||||
ranges: grouped.map(
|
||||
(group): HighlightLineRange => ({
|
||||
startLine: group.startLine,
|
||||
endLine: group.endLine,
|
||||
})
|
||||
),
|
||||
},
|
||||
false
|
||||
).pipe(
|
||||
map(lines => {
|
||||
telemetryService.log(
|
||||
'search.latencies.frontend.code-load',
|
||||
{ durationMs: Date.now() - startTime },
|
||||
{ durationMs: Date.now() - startTime }
|
||||
)
|
||||
return lines[grouped.findIndex(group => group.startLine === startLine && group.endLine === endLine)]
|
||||
})
|
||||
)
|
||||
},
|
||||
[result, fetchHighlightedFileLineRanges, grouped, telemetryService]
|
||||
)
|
||||
|
||||
const createCodeExcerptLink = (group: MatchGroup): string => {
|
||||
const positionOrRangeQueryParameter = toPositionOrRangeQueryParameter({ position: group.position })
|
||||
return appendLineRangeQueryParameter(getFileMatchUrl(result), positionOrRangeQueryParameter)
|
||||
}
|
||||
|
||||
/**
|
||||
* This handler implements the logic to simulate the click/keyboard
|
||||
* activation behavior of links, while also allowing the selection of text
|
||||
* inside the element.
|
||||
* Because a click event is dispatched in both cases (clicking the search
|
||||
* result to open it as well as selecting text within it), we have to be
|
||||
* able to distinguish between those two actions.
|
||||
* If we detect a text selection action, we don't have to do anything.
|
||||
*
|
||||
* CAVEATS:
|
||||
* - In Firefox, Shift+click will open the URL in a new tab instead of
|
||||
* a window (unlike Chromium which seems to show the same behavior as with
|
||||
* native links).
|
||||
* - Firefox will insert \t\n in between table rows, causing the copied
|
||||
* text to be different from what is in the file/search result.
|
||||
*/
|
||||
const navigateToFile = useCallback(
|
||||
(
|
||||
event: KeyboardEvent<HTMLElement> | MouseEvent<HTMLElement>,
|
||||
{ line, character }: { line: number; character: number }
|
||||
): void => {
|
||||
// Testing for text selection is only necessary for mouse/click
|
||||
// events. Middle-click (event.button === 1) is already handled in the `onMouseUp` callback.
|
||||
if (
|
||||
(event.type === 'click' &&
|
||||
!isTextSelectionEvent(event as MouseEvent<HTMLElement>) &&
|
||||
(event as MouseEvent<HTMLElement>).button !== 1) ||
|
||||
(event as KeyboardEvent<HTMLElement>).key === 'Enter'
|
||||
) {
|
||||
const href = event.currentTarget.getAttribute('data-href')
|
||||
if (!event.defaultPrevented && href) {
|
||||
event.preventDefault()
|
||||
|
||||
openFile(result.repository, {
|
||||
path: result.path,
|
||||
revision: result.commit,
|
||||
position: {
|
||||
line: line - 1,
|
||||
character: character - 1,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
[openFile, result]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className={styles.fileMatchChildren} data-testid="file-match-children">
|
||||
{/* Path */}
|
||||
{result.type === 'path' && (
|
||||
<div className={styles.item} data-testid="file-match-children-item">
|
||||
<small>Path match</small>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Symbols */}
|
||||
{((result.type === 'symbol' && result.symbols) || []).map(symbol => (
|
||||
<Button
|
||||
className={classNames('test-file-match-children-item', styles.item, 'btn-text-link')}
|
||||
key={`symbol:${symbol.name}${String(symbol.containerName)}${symbol.url}`}
|
||||
data-testid="file-match-children-item"
|
||||
onClick={() => openSymbol(symbol.url)}
|
||||
>
|
||||
<SymbolKind
|
||||
kind={symbol.kind}
|
||||
className="mr-1"
|
||||
symbolKindTags={
|
||||
isSettingsValid(props.settingsCascade) &&
|
||||
props.settingsCascade.final.experimentalFeatures?.symbolKindTags
|
||||
}
|
||||
/>
|
||||
<Code>
|
||||
{symbol.name}{' '}
|
||||
{symbol.containerName && <span className="text-muted">{symbol.containerName}</span>}
|
||||
</Code>
|
||||
</Button>
|
||||
))}
|
||||
|
||||
{/* Line matches */}
|
||||
{grouped && (
|
||||
<div>
|
||||
{grouped.map((group, index) => (
|
||||
<div
|
||||
key={`linematch:${getFileMatchUrl(result)}${group.position.line}:${
|
||||
group.position.character
|
||||
}`}
|
||||
className={classNames('test-file-match-children-item-wrapper', styles.itemCodeWrapper)}
|
||||
>
|
||||
<div
|
||||
data-href={createCodeExcerptLink(group)}
|
||||
className={classNames(
|
||||
'test-file-match-children-item',
|
||||
styles.item,
|
||||
styles.itemClickable
|
||||
)}
|
||||
onClick={event =>
|
||||
navigateToFile(event, {
|
||||
line: group.position.line,
|
||||
character: group.position.character,
|
||||
})
|
||||
}
|
||||
onMouseUp={navigateToFileOnMiddleMouseButtonClick}
|
||||
onKeyDown={event =>
|
||||
navigateToFile(event, {
|
||||
line: group.position.line,
|
||||
character: group.position.character,
|
||||
})
|
||||
}
|
||||
data-testid="file-match-children-item"
|
||||
tabIndex={0}
|
||||
role="link"
|
||||
>
|
||||
<CodeExcerpt
|
||||
repoName={result.repository}
|
||||
commitID={result.commit || ''}
|
||||
filePath={result.path}
|
||||
startLine={group.startLine}
|
||||
endLine={group.endLine}
|
||||
highlightRanges={group.matches}
|
||||
fetchHighlightedFileRangeLines={fetchHighlightedFileRangeLines}
|
||||
blobLines={group.blobLines}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
@import 'wildcard/src/global-styles/breakpoints';
|
||||
|
||||
.wrapper {
|
||||
&:hover button {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
figure {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.thumbnail-button {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--border-radius);
|
||||
background-color: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.thumbnail-image {
|
||||
width: 100%;
|
||||
// Note: This is to reduce cumulative layout shift
|
||||
// It should be as close as possible to the source image aspect ratio
|
||||
aspect-ratio: 176/115;
|
||||
}
|
||||
|
||||
.play-icon-wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal {
|
||||
width: 70vw;
|
||||
@media (--lg-breakpoint-down) {
|
||||
width: 90vw;
|
||||
}
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.iframe-video-wrapper {
|
||||
position: relative;
|
||||
// stylelint-disable-next-line declaration-property-unit-allowed-list
|
||||
padding-top: 56.25%;
|
||||
}
|
||||
|
||||
.iframe-video {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
@ -1,115 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
|
||||
import { Button } from '@sourcegraph/wildcard'
|
||||
|
||||
import { useWebviewPageContext } from '../../platform/context'
|
||||
|
||||
import styles from './ModalVideo.module.scss'
|
||||
|
||||
// We can't play video in VS Code Desktop: https://stackoverflow.com/a/57512681
|
||||
// Open video in YouTube instead.
|
||||
|
||||
interface ModalVideoProps {
|
||||
id: string
|
||||
title: string
|
||||
src: string
|
||||
thumbnail?: { src: string; alt: string }
|
||||
onToggle?: (isOpen: boolean) => void
|
||||
showCaption?: boolean
|
||||
className?: string
|
||||
assetsRoot?: string
|
||||
}
|
||||
|
||||
export const ModalVideo: React.FunctionComponent<React.PropsWithChildren<ModalVideoProps>> = ({
|
||||
title,
|
||||
src,
|
||||
thumbnail,
|
||||
onToggle,
|
||||
showCaption = false,
|
||||
className,
|
||||
assetsRoot = '',
|
||||
}) => {
|
||||
const { extensionCoreAPI } = useWebviewPageContext()
|
||||
|
||||
const onClick = (): void => {
|
||||
onToggle?.(false)
|
||||
extensionCoreAPI.openLink(src).catch(error => {
|
||||
console.error(`Error opening video at ${src}`, error)
|
||||
})
|
||||
}
|
||||
|
||||
let thumbnailElement = thumbnail ? (
|
||||
<button type="button" className={classNames(styles.thumbnailButton, 'border-0')} onClick={onClick}>
|
||||
<img
|
||||
src={`${assetsRoot}/${thumbnail.src}`}
|
||||
alt={thumbnail.alt}
|
||||
className={classNames(styles.thumbnailImage, 'rounded border opacity-75')}
|
||||
/>
|
||||
<div className={styles.playIconWrapper}>
|
||||
<PlayIcon />
|
||||
</div>
|
||||
</button>
|
||||
) : null
|
||||
|
||||
if (showCaption) {
|
||||
thumbnailElement = (
|
||||
<figure>
|
||||
{thumbnailElement}
|
||||
<figcaption>
|
||||
<Button variant="link" onClick={onClick}>
|
||||
{title}
|
||||
</Button>
|
||||
</figcaption>
|
||||
</figure>
|
||||
)
|
||||
}
|
||||
|
||||
return <div className={classNames(styles.wrapper, className)}>{thumbnailElement}</div>
|
||||
}
|
||||
|
||||
const PlayIcon = React.memo(() => (
|
||||
<svg width="50" height="53" viewBox="0 0 50 53" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g filter="url(#filter0_dd_268:5695)">
|
||||
<path d="M37.5 26.5L12.75 40.7894L12.75 12.2106L37.5 26.5Z" fill="white" />
|
||||
</g>
|
||||
<defs>
|
||||
<filter
|
||||
id="filter0_dd_268:5695"
|
||||
x="0.75"
|
||||
y="0.210449"
|
||||
width="48.75"
|
||||
height="52.5791"
|
||||
filterUnits="userSpaceOnUse"
|
||||
colorInterpolationFilters="sRGB"
|
||||
>
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
type="matrix"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
result="hardAlpha"
|
||||
/>
|
||||
<feOffset />
|
||||
<feGaussianBlur stdDeviation="6" />
|
||||
<feColorMatrix
|
||||
type="matrix"
|
||||
values="0 0 0 0 0.00505209 0 0 0 0 0.0449636 0 0 0 0 0.404167 0 0 0 0.25 0"
|
||||
/>
|
||||
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_268:5695" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
type="matrix"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
result="hardAlpha"
|
||||
/>
|
||||
<feOffset dy="4" />
|
||||
<feGaussianBlur stdDeviation="2" />
|
||||
<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0.055 0 0 0 0 0.25 0 0 0 0.25 0" />
|
||||
<feBlend mode="normal" in2="effect1_dropShadow_268:5695" result="effect2_dropShadow_268:5695" />
|
||||
<feBlend mode="normal" in="SourceGraphic" in2="effect2_dropShadow_268:5695" result="shape" />
|
||||
</filter>
|
||||
</defs>
|
||||
</svg>
|
||||
))
|
||||
@ -1,19 +0,0 @@
|
||||
# Aliased files
|
||||
|
||||
Lots of shared client code used in the initial implementation of the VS Code
|
||||
To expedite the implementation and review processes, we decided to "fork"
|
||||
code that would require significant refactoring to work in the VS Code
|
||||
extension context.
|
||||
|
||||
Our plan is remove the need for these aliased/forked files (method TBD).
|
||||
Resolving this divergence will reduce the risk of regressions introduced
|
||||
by changes in the way that base code interacts with forked code.
|
||||
|
||||
- Search result handling
|
||||
- We can't use relative links like in the web app, for most search result types (and eventually all),
|
||||
we need click handlers that call VS Code extension APIs.
|
||||
- Forked components: `FileMatchChildren`, `SearchResult`, `RepoFileLink`
|
||||
- What's changed:
|
||||
- Create a React context to wrap around `StreamingSearchResultsList` (shared) to pass
|
||||
VS Code extension APIs to forked search result components.
|
||||
- Change links to buttons, call VS Code file handlers from context on click.
|
||||
@ -1,95 +0,0 @@
|
||||
import * as React from 'react'
|
||||
|
||||
import { displayRepoName } from '@sourcegraph/shared/src/components/RepoLink'
|
||||
import { parseRepoRevision } from '@sourcegraph/shared/src/util/url'
|
||||
import { Button, Tooltip, useIsTruncated } from '@sourcegraph/wildcard'
|
||||
|
||||
import { useOpenSearchResultsContext } from '../MatchHandlersContext'
|
||||
|
||||
/**
|
||||
* Splits the repository name into the dir and base components.
|
||||
*/
|
||||
export function splitPath(path: string): [string, string] {
|
||||
const components = path.split('/')
|
||||
return [components.slice(0, -1).join('/'), components.at(-1)!]
|
||||
}
|
||||
|
||||
interface Props {
|
||||
repoName: string
|
||||
repoURL: string
|
||||
filePath: string
|
||||
fileURL: string
|
||||
repoDisplayName?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A link to a repository or a file within a repository, formatted as "repo" or "repo > file". Unless you
|
||||
* absolutely need breadcrumb-like behavior, use this instead of FilePathBreadcrumb.
|
||||
*/
|
||||
export const RepoFileLink: React.FunctionComponent<React.PropsWithChildren<Props>> = ({
|
||||
repoDisplayName,
|
||||
repoName,
|
||||
repoURL,
|
||||
filePath,
|
||||
className,
|
||||
}) => {
|
||||
/**
|
||||
* Use the custom hook useIsTruncated to check if overflow: ellipsis is activated for the element
|
||||
* We want to do it on mouse enter as browser window size might change after the element has been
|
||||
* loaded initially
|
||||
*/
|
||||
const [titleReference, truncated, checkTruncation] = useIsTruncated()
|
||||
|
||||
const [fileBase, fileName] = splitPath(filePath)
|
||||
|
||||
const { openRepo, openFile } = useOpenSearchResultsContext()
|
||||
|
||||
const getRepoAndRevision = (): { repoName: string; revision: string | undefined } => {
|
||||
// Example: `/github.com/sourcegraph/sourcegraph@main`
|
||||
const indexOfSeparator = repoURL.indexOf('/-/')
|
||||
let repoRevision: string
|
||||
if (indexOfSeparator === -1) {
|
||||
repoRevision = repoURL // the whole string
|
||||
} else {
|
||||
repoRevision = repoURL.slice(0, indexOfSeparator) // the whole string leading up to the separator (allows revision to be multiple path parts)
|
||||
}
|
||||
let { repoName, revision } = parseRepoRevision(repoRevision)
|
||||
// Remove leading slash
|
||||
if (repoName.startsWith('/')) {
|
||||
repoName = repoName.slice(1)
|
||||
}
|
||||
return { repoName, revision }
|
||||
}
|
||||
|
||||
const onRepoClick = (): void => {
|
||||
const { repoName, revision } = getRepoAndRevision()
|
||||
|
||||
openRepo({
|
||||
repository: repoName,
|
||||
branches: revision ? [revision] : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
const onFileClick = (): void => {
|
||||
const { repoName, revision } = getRepoAndRevision()
|
||||
openFile(repoName, { path: filePath, revision })
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip content={truncated ? (fileBase ? `${fileBase}/${fileName}` : fileName) : null}>
|
||||
<span>
|
||||
<div ref={titleReference} className={className} onMouseEnter={checkTruncation}>
|
||||
<Button onClick={onRepoClick} className="btn-text-link">
|
||||
{repoDisplayName || displayRepoName(repoName)}
|
||||
</Button>{' '}
|
||||
›{' '}
|
||||
<Button onClick={onFileClick} className="btn-text-link">
|
||||
{fileBase ? `${fileBase}/` : null}
|
||||
<strong>{fileName}</strong>
|
||||
</Button>
|
||||
</div>
|
||||
</span>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@ -1,130 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
import { mdiSourceFork, mdiArchive, mdiLock } from '@mdi/js'
|
||||
import classNames from 'classnames'
|
||||
import SourceRepositoryIcon from 'mdi-react/SourceRepositoryIcon'
|
||||
|
||||
import { SearchResultStyles as styles, LegacyResultContainer } from '@sourcegraph/branded'
|
||||
import { displayRepoName } from '@sourcegraph/shared/src/components/RepoLink'
|
||||
import { getRepoMatchLabel, type RepositoryMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
import { Button, Icon } from '@sourcegraph/wildcard'
|
||||
|
||||
import { useOpenSearchResultsContext } from '../MatchHandlersContext'
|
||||
|
||||
export interface RepoSearchResultProps {
|
||||
result: RepositoryMatch
|
||||
repoName: string
|
||||
onSelect: () => void
|
||||
containerClassName?: string
|
||||
as?: React.ElementType
|
||||
index: number
|
||||
}
|
||||
|
||||
export const RepoSearchResult: React.FunctionComponent<RepoSearchResultProps> = ({
|
||||
result,
|
||||
onSelect,
|
||||
containerClassName,
|
||||
as,
|
||||
index,
|
||||
}) => {
|
||||
/**
|
||||
* Use the custom hook useIsTruncated to check if overflow: ellipsis is activated for the element
|
||||
* We want to do it on mouse enter as browser window size might change after the element has been
|
||||
* loaded initially
|
||||
*/
|
||||
const { openRepo } = useOpenSearchResultsContext()
|
||||
|
||||
const renderTitle = (): JSX.Element => (
|
||||
<div className={styles.title}>
|
||||
<span className="test-search-result-label ml-1 flex-shrink-past-contents text-truncate">
|
||||
<Button className="btn-text-link" onClick={() => openRepo(result)}>
|
||||
{displayRepoName(getRepoMatchLabel(result))}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
|
||||
const renderBody = (): JSX.Element => (
|
||||
<div data-testid="search-repo-result">
|
||||
<div className={classNames(styles.searchResultMatch, 'p-2 flex-column')}>
|
||||
<div className="d-flex align-items-center flex-row">
|
||||
<div className={styles.matchType}>
|
||||
<small>Repository match</small>
|
||||
</div>
|
||||
{result.fork && (
|
||||
<>
|
||||
<div className={styles.divider} />
|
||||
<div>
|
||||
<Icon
|
||||
className={classNames('flex-shrink-0 text-muted', styles.icon)}
|
||||
aria-label="Forked repository"
|
||||
svgPath={mdiSourceFork}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<small>Fork</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{result.archived && (
|
||||
<>
|
||||
<div className={styles.divider} />
|
||||
<div>
|
||||
<Icon
|
||||
className={classNames('flex-shrink-0 text-muted', styles.icon)}
|
||||
aria-label="Archived repository"
|
||||
svgPath={mdiArchive}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<small>Archived</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{result.private && (
|
||||
<>
|
||||
<div className={styles.divider} />
|
||||
<div>
|
||||
<Icon
|
||||
className={classNames('flex-shrink-0 text-muted', styles.icon)}
|
||||
aria-label="Private repository"
|
||||
svgPath={mdiLock}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<small>Private</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{result.description && (
|
||||
<>
|
||||
<div className={styles.dividerVertical} />
|
||||
<div>
|
||||
<small>
|
||||
<em>{result.description}</em>
|
||||
</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<LegacyResultContainer
|
||||
as={as}
|
||||
index={index}
|
||||
icon={SourceRepositoryIcon}
|
||||
collapsible={false}
|
||||
defaultExpanded={true}
|
||||
title={renderTitle()}
|
||||
resultType={result.type}
|
||||
onResultClicked={onSelect}
|
||||
expandedChildren={renderBody()}
|
||||
className={containerClassName}
|
||||
repoName={result.repository}
|
||||
repoStars={result.repoStars}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@ -1,183 +0,0 @@
|
||||
import React, { useCallback } from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import type { Observable } from 'rxjs'
|
||||
import { map } from 'rxjs/operators'
|
||||
|
||||
import {
|
||||
SymbolSearchResultStyles as styles,
|
||||
SearchResultStyles as searchResultStyles,
|
||||
CodeExcerpt,
|
||||
navigateToFileOnMiddleMouseButtonClick,
|
||||
ResultContainer,
|
||||
CopyPathAction,
|
||||
} from '@sourcegraph/branded'
|
||||
import type { FetchFileParameters } from '@sourcegraph/shared/src/backend/file'
|
||||
import { getFileMatchUrl, getRepositoryUrl, getRevision, type SymbolMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
import { isSettingsValid, type SettingsCascadeProps } from '@sourcegraph/shared/src/settings/settings'
|
||||
import { SymbolKind } from '@sourcegraph/shared/src/symbols/SymbolKind'
|
||||
import type { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
|
||||
import { codeCopiedEvent } from '@sourcegraph/shared/src/tracking/event-log-creators'
|
||||
|
||||
import { type HighlightLineRange, HighlightResponseFormat } from '../../../graphql-operations'
|
||||
import { useOpenSearchResultsContext } from '../MatchHandlersContext'
|
||||
|
||||
import { RepoFileLink } from './RepoFileLink'
|
||||
|
||||
export interface SymbolSearchResultProps extends TelemetryProps, SettingsCascadeProps {
|
||||
result: SymbolMatch
|
||||
openInNewTab?: boolean
|
||||
repoDisplayName: string
|
||||
containerClassName?: string
|
||||
index: number
|
||||
onSelect: () => void
|
||||
fetchHighlightedFileLineRanges: (parameters: FetchFileParameters, force?: boolean) => Observable<string[][]>
|
||||
}
|
||||
|
||||
export const SymbolSearchResult: React.FunctionComponent<SymbolSearchResultProps> = ({
|
||||
result,
|
||||
repoDisplayName,
|
||||
onSelect,
|
||||
containerClassName,
|
||||
index,
|
||||
telemetryService,
|
||||
settingsCascade,
|
||||
fetchHighlightedFileLineRanges,
|
||||
}) => {
|
||||
const enableLazyFileResultSyntaxHighlighting =
|
||||
isSettingsValid(settingsCascade) &&
|
||||
settingsCascade.final.experimentalFeatures?.enableLazyFileResultSyntaxHighlighting
|
||||
|
||||
const repoAtRevisionURL = getRepositoryUrl(result.repository, result.branches)
|
||||
const revisionDisplayName = getRevision(result.branches, result.commit)
|
||||
|
||||
const { openSymbol } = useOpenSearchResultsContext()
|
||||
|
||||
const title = (
|
||||
<span className="d-flex align-items-center">
|
||||
<RepoFileLink
|
||||
repoName={result.repository}
|
||||
repoURL={repoAtRevisionURL}
|
||||
filePath={result.path}
|
||||
fileURL={getFileMatchUrl(result)}
|
||||
repoDisplayName={
|
||||
repoDisplayName
|
||||
? `${repoDisplayName}${revisionDisplayName ? `@${revisionDisplayName}` : ''}`
|
||||
: undefined
|
||||
}
|
||||
className={classNames(searchResultStyles.titleInner)}
|
||||
/>
|
||||
<CopyPathAction
|
||||
filePath={result.path}
|
||||
className={searchResultStyles.copyButton}
|
||||
telemetryService={telemetryService}
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
|
||||
const logEventOnCopy = useCallback(() => {
|
||||
telemetryService.log(...codeCopiedEvent('file-match'))
|
||||
}, [telemetryService])
|
||||
|
||||
const fetchSymbolMatchLineRanges = useCallback(
|
||||
(startLine: number, endLine: number, format: HighlightResponseFormat) => {
|
||||
const startTime = Date.now()
|
||||
return fetchHighlightedFileLineRanges({
|
||||
repoName: result.repository,
|
||||
commitID: result.commit || '',
|
||||
filePath: result.path,
|
||||
disableTimeout: false,
|
||||
format,
|
||||
ranges: result.symbols.map(
|
||||
(symbol): HighlightLineRange => ({
|
||||
startLine: symbol.line - 1,
|
||||
endLine: symbol.line,
|
||||
})
|
||||
),
|
||||
}).pipe(
|
||||
map(lines => {
|
||||
const endTime = Date.now()
|
||||
telemetryService.log(
|
||||
'search.latencies.frontend.code-load',
|
||||
{ durationMs: endTime - startTime },
|
||||
{ durationMs: endTime - startTime }
|
||||
)
|
||||
return lines[
|
||||
result.symbols.findIndex(symbol => symbol.line - 1 === startLine && symbol.line === endLine)
|
||||
]
|
||||
})
|
||||
)
|
||||
},
|
||||
[result, fetchHighlightedFileLineRanges, telemetryService]
|
||||
)
|
||||
|
||||
const fetchHighlightedSymbolMatchLineRanges = useCallback(
|
||||
(startLine: number, endLine: number) =>
|
||||
fetchSymbolMatchLineRanges(startLine, endLine, HighlightResponseFormat.HTML_HIGHLIGHT),
|
||||
[fetchSymbolMatchLineRanges]
|
||||
)
|
||||
|
||||
const fetchPlainTextSymbolMatchLineRanges = useCallback(
|
||||
(startLine: number, endLine: number) =>
|
||||
fetchSymbolMatchLineRanges(startLine, endLine, HighlightResponseFormat.HTML_PLAINTEXT),
|
||||
[fetchSymbolMatchLineRanges]
|
||||
)
|
||||
|
||||
return (
|
||||
<ResultContainer
|
||||
index={index}
|
||||
title={title}
|
||||
resultType={result.type}
|
||||
onResultClicked={onSelect}
|
||||
repoName={result.repository}
|
||||
repoStars={result.repoStars}
|
||||
className={classNames(searchResultStyles.copyButtonContainer, containerClassName)}
|
||||
resultClassName={styles.symbolsOverride}
|
||||
repoLastFetched={result.repoLastFetched}
|
||||
>
|
||||
<div className={styles.symbols}>
|
||||
{result.symbols.map(symbol => (
|
||||
<div
|
||||
key={`symbol:${symbol.name}${String(symbol.containerName)}${symbol.url}`}
|
||||
className={styles.symbol}
|
||||
data-href={symbol.url}
|
||||
role="link"
|
||||
data-testid="symbol-search-result"
|
||||
tabIndex={0}
|
||||
onClick={() => openSymbol(symbol.url)}
|
||||
onMouseUp={navigateToFileOnMiddleMouseButtonClick}
|
||||
onKeyDown={() => openSymbol(symbol.url)}
|
||||
>
|
||||
<div className="mr-2 flex-shrink-0">
|
||||
<SymbolKind
|
||||
kind={symbol.kind}
|
||||
symbolKindTags={
|
||||
isSettingsValid(settingsCascade) &&
|
||||
settingsCascade.final.experimentalFeatures?.symbolKindTags
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.symbolCodeExcerpt}>
|
||||
<CodeExcerpt
|
||||
className="a11y-ignore"
|
||||
repoName={result.repository}
|
||||
commitID={result.commit || ''}
|
||||
filePath={result.path}
|
||||
startLine={symbol.line - 1}
|
||||
endLine={symbol.line}
|
||||
fetchHighlightedFileRangeLines={fetchHighlightedSymbolMatchLineRanges}
|
||||
fetchPlainTextFileRangeLines={
|
||||
enableLazyFileResultSyntaxHighlighting
|
||||
? fetchPlainTextSymbolMatchLineRanges
|
||||
: undefined
|
||||
}
|
||||
onCopy={logEventOnCopy}
|
||||
highlightRanges={[]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ResultContainer>
|
||||
)
|
||||
}
|
||||
@ -1,181 +0,0 @@
|
||||
import type { Observable } from 'rxjs'
|
||||
import { map } from 'rxjs/operators'
|
||||
|
||||
import { gql, dataOrThrowErrors } from '@sourcegraph/http-client'
|
||||
import type { PlatformContext } from '@sourcegraph/shared/src/platform/context'
|
||||
|
||||
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }
|
||||
export type Maybe<T> = T | null
|
||||
|
||||
/** All built-in and custom scalars, mapped to their actual values */
|
||||
export interface Scalars {
|
||||
ID: string
|
||||
String: string
|
||||
Boolean: boolean
|
||||
Int: number
|
||||
Float: number
|
||||
/** A quadruple that represents all possible states of the published value: true, false, 'draft', or null. */
|
||||
PublishedValue: boolean | 'draft'
|
||||
/** A valid JSON value. */
|
||||
JSONValue: unknown
|
||||
/** A string that contains valid JSON, with additional support for //-style comments and trailing commas. */
|
||||
JSONCString: string
|
||||
/** A Git object ID (SHA-1 hash, 40 hexadecimal characters). */
|
||||
GitObjectID: string
|
||||
/** An arbitrarily large integer encoded as a decimal string. */
|
||||
BigInt: string
|
||||
/**
|
||||
* An RFC 3339-encoded UTC date string, such as 1973-11-29T21:33:09Z. This value can be parsed into a
|
||||
* JavaScript Date using Date.parse. To produce this value from a JavaScript Date instance, use
|
||||
* Date#toISOString.
|
||||
*/
|
||||
DateTime: string
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a copy of the fetchSearchContexts function from @sourcegraph/search created for VSCE use
|
||||
* We have removed `query` from SearchContext to support instances below v3.36.0
|
||||
* as query does not exist in Search Context type in older instances
|
||||
* More context in https://github.com/sourcegraph/sourcegraph/issues/31022
|
||||
**/
|
||||
|
||||
const searchContextFragment = gql`
|
||||
fragment SearchContextFields on SearchContext {
|
||||
__typename
|
||||
id
|
||||
name
|
||||
namespace {
|
||||
__typename
|
||||
id
|
||||
namespaceName
|
||||
}
|
||||
spec
|
||||
description
|
||||
public
|
||||
autoDefined
|
||||
updatedAt
|
||||
viewerCanManage
|
||||
viewerHasStarred
|
||||
viewerHasAsDefault
|
||||
repositories {
|
||||
__typename
|
||||
repository {
|
||||
name
|
||||
}
|
||||
revisions
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export function fetchSearchContexts({
|
||||
first,
|
||||
namespaces,
|
||||
query,
|
||||
after,
|
||||
orderBy,
|
||||
descending,
|
||||
platformContext,
|
||||
}: {
|
||||
first: number
|
||||
query?: string
|
||||
namespaces?: Maybe<Scalars['ID']>[]
|
||||
after?: string
|
||||
orderBy?: SearchContextsOrderBy
|
||||
descending?: boolean
|
||||
platformContext: Pick<PlatformContext, 'requestGraphQL'>
|
||||
}): Observable<ListSearchContextsResult['searchContexts']> {
|
||||
return platformContext
|
||||
.requestGraphQL<ListSearchContextsResult, ListSearchContextsVariables>({
|
||||
request: gql`
|
||||
query ListSearchContexts(
|
||||
$first: Int!
|
||||
$after: String
|
||||
$query: String
|
||||
$namespaces: [ID]
|
||||
$orderBy: SearchContextsOrderBy
|
||||
$descending: Boolean
|
||||
) {
|
||||
searchContexts(
|
||||
first: $first
|
||||
after: $after
|
||||
query: $query
|
||||
namespaces: $namespaces
|
||||
orderBy: $orderBy
|
||||
descending: $descending
|
||||
) {
|
||||
nodes {
|
||||
...SearchContextFields
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
totalCount
|
||||
}
|
||||
}
|
||||
${searchContextFragment}
|
||||
`,
|
||||
variables: {
|
||||
first,
|
||||
after: after ?? null,
|
||||
query: query ?? null,
|
||||
namespaces: namespaces ?? [],
|
||||
orderBy: orderBy ?? SearchContextsOrderBy.SEARCH_CONTEXT_SPEC,
|
||||
descending: descending ?? false,
|
||||
},
|
||||
mightContainPrivateInfo: true,
|
||||
})
|
||||
.pipe(
|
||||
map(dataOrThrowErrors),
|
||||
map(data => data.searchContexts)
|
||||
)
|
||||
}
|
||||
|
||||
export interface SearchContextFields {
|
||||
__typename: 'SearchContext'
|
||||
id: string
|
||||
name: string
|
||||
spec: string
|
||||
description: string
|
||||
public: boolean
|
||||
autoDefined: boolean
|
||||
updatedAt: string
|
||||
viewerCanManage: boolean
|
||||
viewerHasAsDefault: boolean
|
||||
viewerHasStarred: boolean
|
||||
query: string
|
||||
namespace: Maybe<
|
||||
| { __typename: 'User'; id: string; namespaceName: string }
|
||||
| { __typename: 'Org'; id: string; namespaceName: string }
|
||||
>
|
||||
repositories: {
|
||||
__typename: 'SearchContextRepositoryRevisions'
|
||||
revisions: string[]
|
||||
repository: { __typename?: 'Repository'; name: string }
|
||||
}[]
|
||||
}
|
||||
|
||||
export type ListSearchContextsVariables = Exact<{
|
||||
first: Scalars['Int']
|
||||
after: Maybe<Scalars['String']>
|
||||
query: Maybe<Scalars['String']>
|
||||
namespaces: Maybe<Maybe<Scalars['ID']>[]>
|
||||
orderBy: Maybe<SearchContextsOrderBy>
|
||||
descending: Maybe<Scalars['Boolean']>
|
||||
}>
|
||||
|
||||
export interface ListSearchContextsResult {
|
||||
__typename?: 'Query'
|
||||
searchContexts: {
|
||||
__typename?: 'SearchContextConnection'
|
||||
totalCount: number
|
||||
nodes: ({ __typename?: 'SearchContext' } & SearchContextFields)[]
|
||||
pageInfo: { __typename?: 'PageInfo'; hasNextPage: boolean; endCursor: Maybe<string> }
|
||||
}
|
||||
}
|
||||
|
||||
/** SearchContextsOrderBy enumerates the ways a search contexts list can be ordered. */
|
||||
export enum SearchContextsOrderBy {
|
||||
SEARCH_CONTEXT_SPEC = 'SEARCH_CONTEXT_SPEC',
|
||||
SEARCH_CONTEXT_UPDATED_AT = 'SEARCH_CONTEXT_UPDATED_AT',
|
||||
}
|
||||
@ -1,24 +0,0 @@
|
||||
import { of } from 'rxjs'
|
||||
|
||||
import { proxySubscribable } from '@sourcegraph/shared/src/api/extension/api/common'
|
||||
|
||||
import type { SearchPanelAPI } from '../../contract'
|
||||
|
||||
export const searchPanelAPI: SearchPanelAPI = {
|
||||
ping: () => {
|
||||
console.log('ping called')
|
||||
return proxySubscribable(of('pong'))
|
||||
},
|
||||
focusSearchBox: () => {
|
||||
// Call dynamic `focusSearchBox`.
|
||||
focusSearchBox()
|
||||
},
|
||||
}
|
||||
let focusSearchBox = (): void => {
|
||||
// Initially a noop. Waiting for search box init.
|
||||
}
|
||||
|
||||
// TODO move to api.ts file
|
||||
export const setFocusSearchBox = (replacementFocusSearchBox: (() => void) | null): void => {
|
||||
focusSearchBox = replacementFocusSearchBox || (() => {})
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
|
||||
import styles from '../index.module.scss'
|
||||
|
||||
interface BrandHeaderProps {
|
||||
isLightTheme: boolean
|
||||
}
|
||||
|
||||
export const BrandHeader: React.FunctionComponent<BrandHeaderProps> = ({ isLightTheme }) => (
|
||||
<>
|
||||
<img
|
||||
className={classNames(styles.logo)}
|
||||
src={`https://sourcegraph.com/.assets/img/sourcegraph-logo-${isLightTheme ? 'light' : 'dark'}.svg`}
|
||||
alt="Sourcegraph logo"
|
||||
/>
|
||||
<div data-testid="brand-header" className={classNames(styles.logoText)}>
|
||||
Search millions of open source repositories
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user