diff --git a/.eslintrc.js b/.eslintrc.js
index 85ad69fa986..11713cfd816 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -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',
},
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26abd07cd19..36992921ba0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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
diff --git a/client/vscode/.bazelignore b/client/vscode/.bazelignore
deleted file mode 100644
index 52c902c991f..00000000000
--- a/client/vscode/.bazelignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# TODO(bazel): remove when no longer generated into src
-src/graphql-operations.ts
diff --git a/client/vscode/.eslintignore b/client/vscode/.eslintignore
deleted file mode 100644
index d344db7454c..00000000000
--- a/client/vscode/.eslintignore
+++ /dev/null
@@ -1,7 +0,0 @@
-**/graphql-operations.ts
-graphql-operations.ts
-**/node_modules/**
-dist/
-package.json
-src/vendor/*.js
-code-intel-extensions/
diff --git a/client/vscode/.gitignore b/client/vscode/.gitignore
deleted file mode 100644
index 3445a80e301..00000000000
--- a/client/vscode/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-dist/
-*.vsix
-.vscode-test/
-
-code-intel-extensions
diff --git a/client/vscode/.stylelintrc.json b/client/vscode/.stylelintrc.json
deleted file mode 100644
index cf84c40f41e..00000000000
--- a/client/vscode/.stylelintrc.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "extends": ["../../.stylelintrc.json"],
- "overrides": [
- {
- "files": ["./src/webview/index.scss", "./src/webview/theming/highlight.scss"],
- "rules": {
- "@sourcegraph/filenames-match-regex": null
- }
- }
- ]
-}
diff --git a/client/vscode/.vscodeignore b/client/vscode/.vscodeignore
deleted file mode 100644
index f2d9ad6283d..00000000000
--- a/client/vscode/.vscodeignore
+++ /dev/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
diff --git a/client/vscode/BUILD.bazel b/client/vscode/BUILD.bazel
deleted file mode 100644
index 848a62d1019..00000000000
--- a/client/vscode/BUILD.bazel
+++ /dev/null
@@ -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
- ],
-)
diff --git a/client/vscode/CHANGELOG.md b/client/vscode/CHANGELOG.md
deleted file mode 100644
index b0756f8b768..00000000000
--- a/client/vscode/CHANGELOG.md
+++ /dev/null
@@ -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
diff --git a/client/vscode/CONTRIBUTING.md b/client/vscode/CONTRIBUTING.md
deleted file mode 100644
index 1d79161568f..00000000000
--- a/client/vscode/CONTRIBUTING.md
+++ /dev/null
@@ -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.
diff --git a/client/vscode/LICENSE b/client/vscode/LICENSE
deleted file mode 100644
index c3ad6a1758f..00000000000
--- a/client/vscode/LICENSE
+++ /dev/null
@@ -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.
diff --git a/client/vscode/README.md b/client/vscode/README.md
deleted file mode 100644
index 542506327d2..00000000000
--- a/client/vscode/README.md
+++ /dev/null
@@ -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 Cmd+Shift+P or Ctrl+Shift+P and searching for “Sourcegraph: Open search tab.”
-
-### From within VS Code:
-
-1. Open the extensions tab on the left side of VS Code (Cmd+Shift+X or Ctrl+Shift+X).
-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 | Cmd+Shift+8 | Ctrl+Shift+8 |
-| Open File in Sourcegraph Cloud | Option+A | Alt+A |
-| Search Selected Text in Sourcegraph Cloud | Option+S | Alt+S |
-
-## 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//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 (Cmd+Shift+X or Ctrl+Shift+X).
-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.
diff --git a/client/vscode/code-intel-extensions.json b/client/vscode/code-intel-extensions.json
deleted file mode 100644
index f342297748f..00000000000
--- a/client/vscode/code-intel-extensions.json
+++ /dev/null
@@ -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"]
\ No newline at end of file
diff --git a/client/vscode/globals.d.ts b/client/vscode/globals.d.ts
deleted file mode 100644
index 732c035e585..00000000000
--- a/client/vscode/globals.d.ts
+++ /dev/null
@@ -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
diff --git a/client/vscode/images/logo.png b/client/vscode/images/logo.png
deleted file mode 100644
index ee37f172658..00000000000
Binary files a/client/vscode/images/logo.png and /dev/null differ
diff --git a/client/vscode/images/logo.svg b/client/vscode/images/logo.svg
deleted file mode 100644
index 27ac88b18eb..00000000000
--- a/client/vscode/images/logo.svg
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/client/vscode/images/logomark_dark.svg b/client/vscode/images/logomark_dark.svg
deleted file mode 100644
index e017293e6ba..00000000000
--- a/client/vscode/images/logomark_dark.svg
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
diff --git a/client/vscode/images/logomark_light.svg b/client/vscode/images/logomark_light.svg
deleted file mode 100644
index ae0423535c9..00000000000
--- a/client/vscode/images/logomark_light.svg
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
diff --git a/client/vscode/images/sourcegraph-logo-dark.svg b/client/vscode/images/sourcegraph-logo-dark.svg
deleted file mode 100644
index e44ad04a1ba..00000000000
--- a/client/vscode/images/sourcegraph-logo-dark.svg
+++ /dev/null
@@ -1 +0,0 @@
-
\ No newline at end of file
diff --git a/client/vscode/images/sourcegraph-logo-light.svg b/client/vscode/images/sourcegraph-logo-light.svg
deleted file mode 100644
index fa931a6bc9a..00000000000
--- a/client/vscode/images/sourcegraph-logo-light.svg
+++ /dev/null
@@ -1 +0,0 @@
-
\ No newline at end of file
diff --git a/client/vscode/package.json b/client/vscode/package.json
deleted file mode 100644
index 92f0894437d..00000000000
--- a/client/vscode/package.json
+++ /dev/null
@@ -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//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:*"
- }
-}
diff --git a/client/vscode/scripts/buffer-shim.js b/client/vscode/scripts/buffer-shim.js
deleted file mode 100644
index 9f0abdf2d81..00000000000
--- a/client/vscode/scripts/buffer-shim.js
+++ /dev/null
@@ -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
diff --git a/client/vscode/scripts/build-inline-extensions.js b/client/vscode/scripts/build-inline-extensions.js
deleted file mode 100644
index 96694c1235a..00000000000
--- a/client/vscode/scripts/build-inline-extensions.js
+++ /dev/null
@@ -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' })
diff --git a/client/vscode/scripts/build.ts b/client/vscode/scripts/build.ts
deleted file mode 100644
index 80cf1c048d4..00000000000
--- a/client/vscode/scripts/build.ts
+++ /dev/null
@@ -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 {
- if (existsSync(outdir)) {
- rm('-rf', outdir)
- }
-
- const buildPromises: Promise[] = []
-
- 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)
- })
-}
diff --git a/client/vscode/scripts/package.ts b/client/vscode/scripts/package.ts
deleted file mode 100644
index 2541e6168c5..00000000000
--- a/client/vscode/scripts/package.ts
+++ /dev/null
@@ -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)
-}
diff --git a/client/vscode/scripts/process-shim.js b/client/vscode/scripts/process-shim.js
deleted file mode 100644
index 33a4a9d1465..00000000000
--- a/client/vscode/scripts/process-shim.js
+++ /dev/null
@@ -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')
diff --git a/client/vscode/scripts/publish.ts b/client/vscode/scripts/publish.ts
deleted file mode 100644
index df9f9a4d85a..00000000000
--- a/client/vscode/scripts/publish.ts
+++ /dev/null
@@ -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)
-}
diff --git a/client/vscode/scripts/release.ts b/client/vscode/scripts/release.ts
deleted file mode 100644
index 4c02048b564..00000000000
--- a/client/vscode/scripts/release.ts
+++ /dev/null
@@ -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}`)
-}
diff --git a/client/vscode/src/README.md b/client/vscode/src/README.md
deleted file mode 100644
index 29c811bfde4..00000000000
--- a/client/vscode/src/README.md
+++ /dev/null
@@ -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.
diff --git a/client/vscode/src/backend/authenticatedUser.ts b/client/vscode/src/backend/authenticatedUser.ts
deleted file mode 100644
index 743ea6e0761..00000000000
--- a/client/vscode/src/backend/authenticatedUser.ts
+++ /dev/null
@@ -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 {
- const authenticatedUsers = new ReplaySubject(1)
-
- function updateAuthenticatedUser(): void {
- requestGraphQLFromVSCode(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
-}
diff --git a/client/vscode/src/backend/blobContent.ts b/client/vscode/src/backend/blobContent.ts
deleted file mode 100644
index 6bb9668a45a..00000000000
--- a/client/vscode/src/backend/blobContent.ts
+++ /dev/null
@@ -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 {
- const result = await requestGraphQLFromVSCode(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
-}
diff --git a/client/vscode/src/backend/eventLogger.ts b/client/vscode/src/backend/eventLogger.ts
deleted file mode 100644
index 81ccde9fa8d..00000000000
--- a/client/vscode/src/backend/eventLogger.ts
+++ /dev/null
@@ -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()
-
-events
- .pipe(
- bufferTime(1000),
- concatMap(events => {
- if (events.length > 0) {
- return requestGraphQLFromVSCode(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)
-}
diff --git a/client/vscode/src/backend/fetch.ts b/client/vscode/src/backend/fetch.ts
deleted file mode 100644
index f1bd1c9cca5..00000000000
--- a/client/vscode/src/backend/fetch.ts
+++ /dev/null
@@ -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
-}
-
-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('proxyProtocol')
- const proxyHost = vscode.workspace.getConfiguration('sourcegraph').get('proxyHost')
- const proxyPort = vscode.workspace.getConfiguration('sourcegraph').get('proxyPort')
- const proxyPath = vscode.workspace.getConfiguration('sourcegraph').get('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
-}
diff --git a/client/vscode/src/backend/files.ts b/client/vscode/src/backend/files.ts
deleted file mode 100644
index 21bd83ab5ad..00000000000
--- a/client/vscode/src/backend/files.ts
+++ /dev/null
@@ -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 {
- const result = await requestGraphQLFromVSCode(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}`)
-}
diff --git a/client/vscode/src/backend/instanceVersion.ts b/client/vscode/src/backend/instanceVersion.ts
deleted file mode 100644
index d019616d6d9..00000000000
--- a/client/vscode/src/backend/instanceVersion.ts
+++ /dev/null
@@ -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 =>
- from(requestGraphQLFromVSCode(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
- }
-}
diff --git a/client/vscode/src/backend/node-fetch-fake-for-browser.ts b/client/vscode/src/backend/node-fetch-fake-for-browser.ts
deleted file mode 100644
index 354dbe2afc4..00000000000
--- a/client/vscode/src/backend/node-fetch-fake-for-browser.ts
+++ /dev/null
@@ -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
diff --git a/client/vscode/src/backend/proxy-agent-fake-for-browser.ts b/client/vscode/src/backend/proxy-agent-fake-for-browser.ts
deleted file mode 100644
index 7e8e87183bf..00000000000
--- a/client/vscode/src/backend/proxy-agent-fake-for-browser.ts
+++ /dev/null
@@ -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
diff --git a/client/vscode/src/backend/repositoryMetadata.ts b/client/vscode/src/backend/repositoryMetadata.ts
deleted file mode 100644
index 403c758c0ef..00000000000
--- a/client/vscode/src/backend/repositoryMetadata.ts
+++ /dev/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 {
- const result = await requestGraphQLFromVSCode(
- 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
-}
diff --git a/client/vscode/src/backend/requestGraphQl.ts b/client/vscode/src/backend/requestGraphQl.ts
deleted file mode 100644
index b5fb3982206..00000000000
--- a/client/vscode/src/backend/requestGraphQl.ts
+++ /dev/null
@@ -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 (
- request: string,
- variables: V,
- overrideAccessToken?: string,
- overrideSourcegraphURL?: string
-): Promise> => {
- 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 ? (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
- } 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)
- }
-}
diff --git a/client/vscode/src/backend/searchContexts.ts b/client/vscode/src/backend/searchContexts.ts
deleted file mode 100644
index fa9e5b8c3cb..00000000000
--- a/client/vscode/src/backend/searchContexts.ts
+++ /dev/null
@@ -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>,
- },
- })
- .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(),
- })
-}
diff --git a/client/vscode/src/backend/sourcegraphSettings.ts b/client/vscode/src/backend/sourcegraphSettings.ts
deleted file mode 100644
index 3f56622ddaf..00000000000
--- a/client/vscode/src/backend/sourcegraphSettings.ts
+++ /dev/null
@@ -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>
- refreshSettings: () => void
-} {
- const settings = new ReplaySubject>(1)
-
- const refreshes = new Subject()
-
- // 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(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()
- },
- }
-}
diff --git a/client/vscode/src/backend/streamSearch.ts b/client/vscode/src/backend/streamSearch.ts
deleted file mode 100644
index 7d740f36309..00000000000
--- a/client/vscode/src/backend/streamSearch.ts
+++ /dev/null
@@ -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 })
- })
- }
-}
diff --git a/client/vscode/src/code-intel/SourcegraphDefinitionProvider.ts b/client/vscode/src/code-intel/SourcegraphDefinitionProvider.ts
deleted file mode 100644
index 816dc4ef152..00000000000
--- a/client/vscode/src/code-intel/SourcegraphDefinitionProvider.ts
+++ /dev/null
@@ -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
- ) {}
- public async provideDefinition(
- document: vscode.TextDocument,
- position: vscode.Position,
- token: vscode.CancellationToken
- ): Promise {
- 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
- }
-}
diff --git a/client/vscode/src/code-intel/SourcegraphHoverProvider.ts b/client/vscode/src/code-intel/SourcegraphHoverProvider.ts
deleted file mode 100644
index d399782a9d7..00000000000
--- a/client/vscode/src/code-intel/SourcegraphHoverProvider.ts
+++ /dev/null
@@ -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
- ) {}
- public async provideHover(
- document: vscode.TextDocument,
- position: vscode.Position,
- token: vscode.CancellationToken
- ): Promise {
- 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({
- 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=='
diff --git a/client/vscode/src/code-intel/SourcegraphReferenceProvider.ts b/client/vscode/src/code-intel/SourcegraphReferenceProvider.ts
deleted file mode 100644
index e844cf74957..00000000000
--- a/client/vscode/src/code-intel/SourcegraphReferenceProvider.ts
+++ /dev/null
@@ -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
- ) {}
- public async provideReferences(
- document: vscode.TextDocument,
- position: vscode.Position,
- referenceContext: vscode.ReferenceContext,
- token: vscode.CancellationToken
- ): Promise {
- 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
- }
-}
diff --git a/client/vscode/src/code-intel/initialize.ts b/client/vscode/src/code-intel/initialize.ts
deleted file mode 100644
index a0dd3558079..00000000000
--- a/client/vscode/src/code-intel/initialize.ts
+++ /dev/null
@@ -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
-}): 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))
- }
- })
- )
-}
diff --git a/client/vscode/src/code-intel/languages.ts b/client/vscode/src/code-intel/languages.ts
deleted file mode 100644
index 6651660ab03..00000000000
--- a/client/vscode/src/code-intel/languages.ts
+++ /dev/null
@@ -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 = {
- typescriptreact: 'typescript',
-}
diff --git a/client/vscode/src/code-intel/location.ts b/client/vscode/src/code-intel/location.ts
deleted file mode 100644
index 8bf581f47ce..00000000000
--- a/client/vscode/src/code-intel/location.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { Range } from '@sourcegraph/extension-api-types'
-
-export interface LocationNode {
- resource: {
- path: string
- repositoryName: string
- revision: string
- }
- range?: Range
-}
diff --git a/client/vscode/src/commands/browserActionsNode.ts b/client/vscode/src/commands/browserActionsNode.ts
deleted file mode 100644
index 2898f1354a7..00000000000
--- a/client/vscode/src/commands/browserActionsNode.ts
+++ /dev/null
@@ -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 {
- 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') || '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`)
- }
- }
-}
diff --git a/client/vscode/src/commands/browserActionsWeb.ts b/client/vscode/src/commands/browserActionsWeb.ts
deleted file mode 100644
index 43df9a6e5d8..00000000000
--- a/client/vscode/src/commands/browserActionsWeb.ts
+++ /dev/null
@@ -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 {
- 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`)
- }
-}
diff --git a/client/vscode/src/commands/git-helpers.ts b/client/vscode/src/commands/git-helpers.ts
deleted file mode 100644
index 5e0017abf30..00000000000
--- a/client/vscode/src/commands/git-helpers.ts
+++ /dev/null
@@ -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 {
- 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,
- log?: {
- appendLine: (value: string) => void
- }
-): Promise {
- 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 {
- 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 {
- 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 {
- 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 {
- 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 {
- 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,
- log?: { appendLine: (value: string) => void }
-): Promise {
- 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 {
- // has default value
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- const replacements = vscode.workspace
- .getConfiguration('sourcegraph')
- .get>('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('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 {
- 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(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 }[]
- }
- }
-}
diff --git a/client/vscode/src/commands/initialize.ts b/client/vscode/src/commands/initialize.ts
deleted file mode 100644
index 5827ed1480a..00000000000
--- a/client/vscode/src/commands/initialize.ts
+++ /dev/null
@@ -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('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('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)
-}
diff --git a/client/vscode/src/common/links.ts b/client/vscode/src/common/links.ts
deleted file mode 100644
index a565be90717..00000000000
--- a/client/vscode/src/common/links.ts
+++ /dev/null
@@ -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
-}
diff --git a/client/vscode/src/contract.ts b/client/vscode/src/contract.ts
deleted file mode 100644
index 5e933643397..00000000000
--- a/client/vscode/src/contract.ts
+++ /dev/null
@@ -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>
- observeSourcegraphSettings: () => ProxySubscribable
- getAuthenticatedUser: () => ProxySubscribable
- /** Endpoint settings */
- getInstanceURL: () => ProxySubscribable
- getAccessToken: Promise
- removeAccessToken: () => Promise
- setEndpointUri: (accessToken: string, uri: string) => Promise
- /**
- * 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
- /** State Management*/
- observeState: () => ProxySubscribable
- emit: VSCEStateMachine['emit']
- /** Opens a remote file given a serialized SourcegraphUri */
- openSourcegraphFile: (uri: string) => Promise
- openLink: (uri: string) => Promise
- copyLink: (uri: string) => Promise
- reloadWindow: () => void
- focusSearchPanel: () => void
- /** Cancels previous search when called. */
- streamSearch: (query: string, options: StreamSearchOptions) => void
- fetchStreamSuggestions: (query: string, sourcegraphURL: string) => ProxySubscribable
- 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
- /** 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 {
- ping: () => ProxySubscribable<'pong'>
-
- addViewerIfNotExists: (viewer: ViewerData) => Promise
-}
-
-export interface HelpSidebarAPI {}
diff --git a/client/vscode/src/extension.ts b/client/vscode/src/extension.ts
deleted file mode 100644
index dc586785ec7..00000000000
--- a/client/vscode/src/extension.ts
+++ /dev/null
@@ -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 {
- 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(7)
- // Used to observe search box query state from sidebar
- const sidebarQueryStates = new ReplaySubject(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)
-}
diff --git a/client/vscode/src/file-system/FileTree.ts b/client/vscode/src/file-system/FileTree.ts
deleted file mode 100644
index 903eb598b96..00000000000
--- a/client/vscode/src/file-system/FileTree.ts
+++ /dev/null
@@ -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()
- const directDirectories = new Set()
- 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
-}
diff --git a/client/vscode/src/file-system/FilesTreeDataProvider.ts b/client/vscode/src/file-system/FilesTreeDataProvider.ts
deleted file mode 100644
index 586675acbe5..00000000000
--- a/client/vscode/src/file-system/FilesTreeDataProvider.ts
+++ /dev/null
@@ -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 {
- constructor(public readonly fs: SourcegraphFileSystemProvider) {
- fs.onDidDownloadRepositoryFilenames(() => this.didChangeTreeData.fire(undefined))
- }
-
- private _isViewVisible = false
- private isExpandedNode = new Set()
- private treeView: vscode.TreeView | undefined
- private activeUri: vscode.Uri | undefined
- private selectedRepository: string | undefined
- private didFocusToken = new vscode.CancellationTokenSource()
- private treeItemCache = new Map()
- private readonly didChangeTreeData = new vscode.EventEmitter()
- public readonly onDidChangeTreeData: vscode.Event = 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): 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 {
- 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 {
- // 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 {
- 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 {
- await vscode.commands.executeCommand('sourcegraph.files.focus')
- await this.didFocus(this.activeUri)
- }
-
- public async didFocus(vscodeUri: vscode.Uri | undefined): Promise {
- 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 {
- 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 {
- 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 {
- 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',
- }
- }
-}
diff --git a/client/vscode/src/file-system/SourcegraphFileSystemProvider.ts b/client/vscode/src/file-system/SourcegraphFileSystemProvider.ts
deleted file mode 100644
index 77a4f9b913e..00000000000
--- a/client/vscode/src/file-system/SourcegraphFileSystemProvider.ts
+++ /dev/null
@@ -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> = new Map()
- private metadata: Map = new Map()
- private didDownloadFilenames = new vscode.EventEmitter()
-
- // ======================
- // FileSystemProvider API
- // ======================
-
- // We don't implement this because Sourcegraph files are read-only.
- private didChangeFile = new vscode.EventEmitter() // Never used.
- public readonly onDidChangeFile: vscode.Event = this.didChangeFile.event
- public async stat(vscodeUri: vscode.Uri): Promise {
- 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 {
- 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 {
- 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 = 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 {
- 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 {
- 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 {
- 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 {
- 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 {
- 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 {
- const files = await this.downloadFiles(uri)
- return new FileTree(uri, files)
- }
-}
diff --git a/client/vscode/src/file-system/SourcegraphUri.ts b/client/vscode/src/file-system/SourcegraphUri.ts
deleted file mode 100644
index 4701007ceae..00000000000
--- a/client/vscode/src/file-system/SourcegraphUri.ts
+++ /dev/null
@@ -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,
- })
- }
-}
diff --git a/client/vscode/src/file-system/commands.ts b/client/vscode/src/file-system/commands.ts
deleted file mode 100644
index 72f0981bc40..00000000000
--- a/client/vscode/src/file-system/commands.ts
+++ /dev/null
@@ -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 {
- 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 {
- 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('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'))
-}
diff --git a/client/vscode/src/file-system/initialize.ts b/client/vscode/src/file-system/initialize.ts
deleted file mode 100644
index fc2bc85a095..00000000000
--- a/client/vscode/src/file-system/initialize.ts
+++ /dev/null
@@ -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('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 }
-}
diff --git a/client/vscode/src/log.ts b/client/vscode/src/log.ts
deleted file mode 100644
index cf922443570..00000000000
--- a/client/vscode/src/log.ts
+++ /dev/null
@@ -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
-}
diff --git a/client/vscode/src/settings/LocalStorageService.ts b/client/vscode/src/settings/LocalStorageService.ts
deleted file mode 100644
index c8ed178a7a3..00000000000
--- a/client/vscode/src/settings/LocalStorageService.ts
+++ /dev/null
@@ -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(key, '')
- }
-
- public async setValue(key: string, value: string): Promise {
- 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'
diff --git a/client/vscode/src/settings/accessTokenSetting.ts b/client/vscode/src/settings/accessTokenSetting.ts
deleted file mode 100644
index 7cb7f502074..00000000000
--- a/client/vscode/src/settings/accessTokenSetting.ts
+++ /dev/null
@@ -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 {
- // 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('sourcegraph.accessToken') || ''
- if (!storageToken && oldToken.length > 8) {
- await secretStorage.store(scretTokenKey, oldToken)
- await removeOldAccessTokenSetting()
- }
- return
-}
-
-export async function accessTokenSetting(secretStorage: vscode.SecretStorage): Promise {
- const currentToken = await secretStorage.get(scretTokenKey)
- return currentToken || ''
-}
-
-export async function removeOldAccessTokenSetting(): Promise {
- 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 {
- 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
- }
-}
diff --git a/client/vscode/src/settings/displayWarnings.ts b/client/vscode/src/settings/displayWarnings.ts
deleted file mode 100644
index 4b8e53abf94..00000000000
--- a/client/vscode/src/settings/displayWarnings.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import vscode from 'vscode'
-
-export async function displayWarning(warning: string): Promise {
- await vscode.window.showErrorMessage(warning)
-}
diff --git a/client/vscode/src/settings/endpointSetting.ts b/client/vscode/src/settings/endpointSetting.ts
deleted file mode 100644
index f845454664f..00000000000
--- a/client/vscode/src/settings/endpointSetting.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import * as vscode from 'vscode'
-
-import { readConfiguration } from './readConfiguration'
-
-export function endpointSetting(): string {
- const url = vscode.workspace.getConfiguration().get('sourcegraph.url') || 'https://sourcegraph.com'
- return removeEndingSlash(url)
-}
-
-export async function setEndpoint(newEndpoint: string): Promise {
- 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