mirror of
https://github.com/sourcegraph/sourcegraph.git
synced 2026-02-06 15:51:43 +00:00
vsce: implement search UI (#30084)
Co-authored-by: Beatrix <68532117+abeatrix@users.noreply.github.com> Co-authored-by: Alex Isken <alex.isken@sourcegraph.com> Co-authored-by: Sara Lee <87138876+jjinnii@users.noreply.github.com> Co-authored-by: Philipp Spiess <hello@philippspiess.com> Co-authored-by: Giselle Northy <northyg@oregonstate.edu> Co-authored-by: Beatrix <beatrix@sourcegraph.com>
This commit is contained in:
parent
7328f08ba6
commit
17918fd041
2
.vscode/launch.json
vendored
2
.vscode/launch.json
vendored
@ -15,6 +15,7 @@
|
||||
"args": [
|
||||
"--extensionDevelopmentPath=${workspaceRoot}/client/vscode",
|
||||
"--disable-extension=kandalatj.sourcegraph-preview",
|
||||
"--disable-extension=sourcegraph.sourcegraph",
|
||||
],
|
||||
"stopOnEntry": false,
|
||||
"sourceMaps": true,
|
||||
@ -28,6 +29,7 @@
|
||||
"args": [
|
||||
"--extensionDevelopmentPath=${workspaceRoot}/client/vscode",
|
||||
"--disable-extension=kandalatj.sourcegraph-preview",
|
||||
"--disable-extension=sourcegraph.sourcegraph",
|
||||
"--extensionDevelopmentKind=web",
|
||||
"--disable-web-security",
|
||||
],
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
export * from './components'
|
||||
export * from './input/toggles'
|
||||
export * from './input/SearchBox'
|
||||
export * from './input/useQueryIntelligence'
|
||||
export * from './documentation/ModalVideo'
|
||||
export * from './results/StreamingSearchResultsList'
|
||||
export * from './results/progress/StreamingProgress'
|
||||
|
||||
@ -11,8 +11,6 @@ import {
|
||||
CaseSensitivityProps,
|
||||
SearchPatternTypeProps,
|
||||
SearchContextProps,
|
||||
useQueryIntelligence,
|
||||
useQueryDiagnostics,
|
||||
} from '@sourcegraph/search'
|
||||
import { MonacoEditor } from '@sourcegraph/shared/src/components/MonacoEditor'
|
||||
import { KeyboardShortcut } from '@sourcegraph/shared/src/keyboardShortcuts'
|
||||
@ -23,6 +21,7 @@ import { fetchStreamSuggestions as defaultFetchStreamSuggestions } from '@source
|
||||
import { ThemeProps } from '@sourcegraph/shared/src/theme'
|
||||
|
||||
import { IEditor } from './LazyMonacoQueryInput'
|
||||
import { useQueryDiagnostics, useQueryIntelligence } from './useQueryIntelligence'
|
||||
|
||||
import styles from './MonacoQueryInput.module.scss'
|
||||
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import React, { useCallback } from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import * as H from 'history'
|
||||
import AlphaSBoxIcon from 'mdi-react/AlphaSBoxIcon'
|
||||
import FileDocumentIcon from 'mdi-react/FileDocumentIcon'
|
||||
import FileIcon from 'mdi-react/FileIcon'
|
||||
import SourceCommitIcon from 'mdi-react/SourceCommitIcon'
|
||||
import SourceRepositoryIcon from 'mdi-react/SourceRepositoryIcon'
|
||||
import { useLocation } from 'react-router'
|
||||
import { Observable } from 'rxjs'
|
||||
|
||||
import { HoverMerged } from '@sourcegraph/client-api'
|
||||
@ -48,7 +48,6 @@ export interface StreamingSearchResultsListProps
|
||||
PlatformContextProps<'requestGraphQL'> {
|
||||
isSourcegraphDotCom: boolean
|
||||
results?: AggregateStreamingSearchResults
|
||||
location: H.Location
|
||||
allExpanded: boolean
|
||||
fetchHighlightedFileLineRanges: (parameters: FetchFileParameters, force?: boolean) => Observable<string[][]>
|
||||
authenticatedUser: AuthenticatedUser | null
|
||||
@ -75,7 +74,6 @@ export interface StreamingSearchResultsListProps
|
||||
|
||||
export const StreamingSearchResultsList: React.FunctionComponent<StreamingSearchResultsListProps> = ({
|
||||
results,
|
||||
location,
|
||||
allExpanded,
|
||||
fetchHighlightedFileLineRanges,
|
||||
settingsCascade,
|
||||
@ -96,6 +94,7 @@ export const StreamingSearchResultsList: React.FunctionComponent<StreamingSearch
|
||||
}) => {
|
||||
const resultsNumber = results?.results.length || 0
|
||||
const { itemsToShow, handleBottomHit } = useItemsToShow(executedQuery, resultsNumber)
|
||||
const location = useLocation()
|
||||
|
||||
const logSearchResultClicked = useCallback(
|
||||
(index: number, type: string) => {
|
||||
|
||||
@ -40,7 +40,7 @@ export interface SearchSidebarProps
|
||||
|
||||
/**
|
||||
* Not yet implemented in the VS Code extension (blocked on Apollo Client integration).
|
||||
* */
|
||||
*/
|
||||
getRevisions?: (revisionsProps: Omit<RevisionsProps, 'query'>) => (query: string) => JSX.Element
|
||||
|
||||
/**
|
||||
|
||||
@ -20,7 +20,6 @@ export * from './backend'
|
||||
export * from './searchQueryState'
|
||||
export * from './helpers'
|
||||
export * from './graphql-operations'
|
||||
export * from './useQueryIntelligence'
|
||||
export * from './helpers/queryExample'
|
||||
|
||||
export interface SearchPatternTypeProps {
|
||||
|
||||
@ -10,6 +10,7 @@ const WEB_FOLDER = path.resolve(ROOT_FOLDER, './client/web')
|
||||
const BROWSER_FOLDER = path.resolve(ROOT_FOLDER, './client/browser')
|
||||
const SHARED_FOLDER = path.resolve(ROOT_FOLDER, './client/shared')
|
||||
const SEARCH_FOLDER = path.resolve(ROOT_FOLDER, './client/search')
|
||||
const VSCODE_FOLDER = path.resolve(ROOT_FOLDER, './client/vscode')
|
||||
const SCHEMA_PATH = path.join(ROOT_FOLDER, './cmd/frontend/graphqlbackend/*.graphql')
|
||||
|
||||
const SHARED_DOCUMENTS_GLOB = [
|
||||
@ -32,9 +33,17 @@ const BROWSER_DOCUMENTS_GLOB = [
|
||||
|
||||
const SEARCH_DOCUMENTS_GLOB = [`${SEARCH_FOLDER}/src/**/*.{ts,tsx}`]
|
||||
|
||||
const VSCODE_DOCUMENTS_GLOB = [`${VSCODE_FOLDER}/src/**/*.{ts,tsx}`]
|
||||
|
||||
// Define ALL_DOCUMENTS_GLOB as the union of the previous glob arrays.
|
||||
const ALL_DOCUMENTS_GLOB = [
|
||||
...new Set([...SHARED_DOCUMENTS_GLOB, ...WEB_DOCUMENTS_GLOB, ...BROWSER_DOCUMENTS_GLOB, ...SEARCH_DOCUMENTS_GLOB]),
|
||||
...new Set([
|
||||
...SHARED_DOCUMENTS_GLOB,
|
||||
...WEB_DOCUMENTS_GLOB,
|
||||
...BROWSER_DOCUMENTS_GLOB,
|
||||
...SEARCH_DOCUMENTS_GLOB,
|
||||
...VSCODE_DOCUMENTS_GLOB,
|
||||
]),
|
||||
]
|
||||
|
||||
const SHARED_PLUGINS = [
|
||||
@ -122,6 +131,17 @@ async function generateGraphQlOperations() {
|
||||
},
|
||||
plugins: SHARED_PLUGINS,
|
||||
},
|
||||
|
||||
[path.join(VSCODE_FOLDER, './src/graphql-operations.ts')]: {
|
||||
documents: VSCODE_DOCUMENTS_GLOB,
|
||||
config: {
|
||||
onlyOperationTypes: true,
|
||||
noExport: false,
|
||||
enumValues: '@sourcegraph/shared/src/graphql-operations',
|
||||
interfaceNameForOperations: 'VSCodeGraphQlOperations',
|
||||
},
|
||||
plugins: SHARED_PLUGINS,
|
||||
},
|
||||
},
|
||||
},
|
||||
true
|
||||
|
||||
@ -87,6 +87,9 @@ export async function createExtensionHostClientConnection(
|
||||
}
|
||||
|
||||
comlink.expose(clientAPI, endpoints.expose)
|
||||
proxy.mainThreadAPIInitialized().catch(() => {
|
||||
console.error('Error notifying extension host of main thread API init.')
|
||||
})
|
||||
|
||||
// TODO(tj): return MainThreadAPI and add to Controller interface
|
||||
// to allow app to interact with APIs whose state lives in the main thread
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { Remote } from 'comlink'
|
||||
import { BehaviorSubject, combineLatest, from, Observable, Subscription } from 'rxjs'
|
||||
import { catchError, concatMap, distinctUntilChanged, map, tap } from 'rxjs/operators'
|
||||
import { catchError, concatMap, distinctUntilChanged, first, map, switchMap, tap } from 'rxjs/operators'
|
||||
import sourcegraph from 'sourcegraph'
|
||||
|
||||
import { Contributions } from '@sourcegraph/client-api'
|
||||
@ -16,13 +16,18 @@ import { parseContributionExpressions } from './api/contribution'
|
||||
import { ExtensionHostState } from './extensionHostState'
|
||||
|
||||
export function observeActiveExtensions(
|
||||
mainAPI: Remote<MainThreadAPI>
|
||||
mainAPI: Remote<MainThreadAPI>,
|
||||
mainThreadAPIInitializations: Observable<boolean>
|
||||
): {
|
||||
activeLanguages: ExtensionHostState['activeLanguages']
|
||||
activeExtensions: ExtensionHostState['activeExtensions']
|
||||
} {
|
||||
const activeLanguages = new BehaviorSubject<ReadonlySet<string>>(new Set())
|
||||
const enabledExtensions = wrapRemoteObservable(mainAPI.getEnabledExtensions())
|
||||
// Wait until the main thread API has initialized since this runs during extension host init.
|
||||
const enabledExtensions = mainThreadAPIInitializations.pipe(
|
||||
first(initialized => initialized),
|
||||
switchMap(() => wrapRemoteObservable(mainAPI.getEnabledExtensions()))
|
||||
)
|
||||
const activatedExtensionIDs = new Set<string>()
|
||||
|
||||
const activeExtensions: Observable<(ConfiguredExtension | ExecutableExtension)[]> = combineLatest([
|
||||
@ -59,6 +64,7 @@ export function activateExtensions(
|
||||
state: Pick<ExtensionHostState, 'activeExtensions' | 'contributions' | 'haveInitialExtensionsLoaded' | 'settings'>,
|
||||
mainAPI: Remote<Pick<MainThreadAPI, 'getScriptURLForExtension' | 'logEvent'>>,
|
||||
createExtensionAPI: (extensionID: string) => typeof sourcegraph,
|
||||
mainThreadAPIInitializations: Observable<boolean>,
|
||||
/**
|
||||
* Function that activates an extension.
|
||||
* Returns a promise that resolves once the extension is activated.
|
||||
@ -72,14 +78,19 @@ export function activateExtensions(
|
||||
): Subscription {
|
||||
const getScriptURLs = memoizeObservable(
|
||||
() =>
|
||||
from(mainAPI.getScriptURLForExtension()).pipe(
|
||||
map(getScriptURL => {
|
||||
function getBundleURLs(urls: string[]): Promise<(string | ErrorLike)[]> {
|
||||
return getScriptURL ? getScriptURL(urls) : Promise.resolve(urls)
|
||||
}
|
||||
mainThreadAPIInitializations.pipe(
|
||||
first(initialized => initialized),
|
||||
switchMap(() =>
|
||||
from(mainAPI.getScriptURLForExtension()).pipe(
|
||||
map(getScriptURL => {
|
||||
function getBundleURLs(urls: string[]): Promise<(string | ErrorLike)[]> {
|
||||
return getScriptURL ? getScriptURL(urls) : Promise.resolve(urls)
|
||||
}
|
||||
|
||||
return getBundleURLs
|
||||
})
|
||||
return getBundleURLs
|
||||
})
|
||||
)
|
||||
)
|
||||
),
|
||||
() => 'getScriptURL'
|
||||
)
|
||||
|
||||
@ -7,4 +7,9 @@ export type ExtensionHostAPIFactory = (initData: InitData) => ExtensionHostAPI
|
||||
|
||||
export interface ExtensionHostAPI extends ProxyMarked, FlatExtensionHostAPI {
|
||||
ping(): 'pong'
|
||||
/**
|
||||
* Main thread calls this to notify the extension host that `MainThreadAPI` has
|
||||
* been created and exposed.
|
||||
* */
|
||||
mainThreadAPIInitialized: () => void
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import * as comlink from 'comlink'
|
||||
import { isMatch } from 'lodash'
|
||||
import { Subscription, Unsubscribable } from 'rxjs'
|
||||
import { ReplaySubject, Subscription, Unsubscribable } from 'rxjs'
|
||||
import * as sourcegraph from 'sourcegraph'
|
||||
|
||||
import { EndpointPair } from '../../platform/context'
|
||||
@ -113,18 +113,28 @@ function createExtensionAndExtensionHostAPIs(
|
||||
|
||||
registerComlinkTransferHandlers()
|
||||
|
||||
/**
|
||||
* Used to wait until the main thread API has been initialized. Ensures
|
||||
* that message of main thread API calls (e.g. getActiveExtensions)
|
||||
* during extension host initialization are not dropped.
|
||||
*
|
||||
* Debt: ensure this works holds true for all clients.
|
||||
* If not, add `waitForMainThread` parameter to make this opt-in.
|
||||
*/
|
||||
const mainThreadAPIInitializations = new ReplaySubject<boolean>(1)
|
||||
|
||||
/** Proxy to main thread */
|
||||
const proxy = comlink.wrap<ClientAPI>(endpoints.proxy)
|
||||
|
||||
// Create extension host state
|
||||
const extensionHostState = createExtensionHostState(initData, proxy)
|
||||
const extensionHostState = createExtensionHostState(initData, proxy, mainThreadAPIInitializations)
|
||||
// Create extension host API
|
||||
const extensionHostAPINew = createExtensionHostAPI(extensionHostState)
|
||||
// Create extension API factory
|
||||
const createExtensionAPI = createExtensionAPIFactory(extensionHostState, proxy, initData)
|
||||
|
||||
// Activate extensions. Create extension APIs on extension activation.
|
||||
subscription.add(activateExtensions(extensionHostState, proxy, createExtensionAPI))
|
||||
subscription.add(activateExtensions(extensionHostState, proxy, createExtensionAPI, mainThreadAPIInitializations))
|
||||
|
||||
// Observe settings and update active loggers state
|
||||
subscription.add(setActiveLoggers(extensionHostState))
|
||||
@ -134,6 +144,9 @@ function createExtensionAndExtensionHostAPIs(
|
||||
[comlink.proxyMarker]: true,
|
||||
|
||||
ping: () => 'pong',
|
||||
mainThreadAPIInitialized: () => {
|
||||
mainThreadAPIInitializations.next(true)
|
||||
},
|
||||
...extensionHostAPINew,
|
||||
}
|
||||
|
||||
|
||||
@ -26,9 +26,10 @@ import { ReferenceCounter } from './utils/ReferenceCounter'
|
||||
|
||||
export function createExtensionHostState(
|
||||
initData: Pick<InitData, 'initialSettings' | 'clientApplication'>,
|
||||
mainAPI: comlink.Remote<MainThreadAPI>
|
||||
mainAPI: comlink.Remote<MainThreadAPI>,
|
||||
mainThreadAPIInitializations: Observable<boolean>
|
||||
): ExtensionHostState {
|
||||
const { activeLanguages, activeExtensions } = observeActiveExtensions(mainAPI)
|
||||
const { activeLanguages, activeExtensions } = observeActiveExtensions(mainAPI, mainThreadAPIInitializations)
|
||||
|
||||
return {
|
||||
haveInitialExtensionsLoaded: new BehaviorSubject<boolean>(false),
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { BehaviorSubject } from 'rxjs'
|
||||
import { BehaviorSubject, of } from 'rxjs'
|
||||
import { filter, first } from 'rxjs/operators'
|
||||
import sinon from 'sinon'
|
||||
import sourcegraph from 'sourcegraph'
|
||||
@ -51,6 +51,7 @@ describe('Extension activation', () => {
|
||||
function createExtensionAPI() {
|
||||
return {} as typeof sourcegraph
|
||||
},
|
||||
of(true),
|
||||
noopPromise,
|
||||
noopPromise
|
||||
)
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { Remote } from 'comlink'
|
||||
import { BehaviorSubject } from 'rxjs'
|
||||
|
||||
import { ClientAPI } from '../../client/api/api'
|
||||
import { FlatExtensionHostAPI } from '../../contract'
|
||||
@ -14,7 +15,11 @@ export function initializeExtensionHostTest(
|
||||
mockMainThreadAPI: Remote<ClientAPI> = pretendRemote<ClientAPI>({}),
|
||||
extensionID: string = 'TEST'
|
||||
): { extensionHostAPI: FlatExtensionHostAPI; extensionAPI: ReturnType<ReturnType<typeof createExtensionAPIFactory>> } {
|
||||
const extensionHostState = createExtensionHostState(initData, mockMainThreadAPI)
|
||||
// Since the mock main thread API is in the same thread and a connection is synchronously established,
|
||||
// we can mock `mainThreadInitializations` as well.
|
||||
const mainThreadInitializations = new BehaviorSubject(true)
|
||||
|
||||
const extensionHostState = createExtensionHostState(initData, mockMainThreadAPI, mainThreadInitializations)
|
||||
|
||||
const extensionHostAPI = createExtensionHostAPI(extensionHostState)
|
||||
const extensionAPIFactory = createExtensionAPIFactory(extensionHostState, mockMainThreadAPI, initData)
|
||||
|
||||
70
client/shared/src/backend/file.ts
Normal file
70
client/shared/src/backend/file.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import { Observable } from 'rxjs'
|
||||
import { map } from 'rxjs/operators'
|
||||
|
||||
import { createAggregateError, memoizeObservable } from '@sourcegraph/common'
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import { FetchFileParameters } from '../components/CodeExcerpt'
|
||||
import { HighlightedFileResult, HighlightedFileVariables } from '../graphql-operations'
|
||||
import { PlatformContext } from '../platform/context'
|
||||
import { makeRepoURI } from '../util/url'
|
||||
|
||||
/**
|
||||
* Fetches the specified highlighted file line ranges (`FetchFileParameters.ranges`) and returns
|
||||
* them as a list of ranges, each describing a list of lines in the form of HTML table '<tr>...</tr>'.
|
||||
*/
|
||||
export const fetchHighlightedFileLineRanges = memoizeObservable(
|
||||
(
|
||||
{
|
||||
platformContext,
|
||||
...context
|
||||
}: FetchFileParameters & {
|
||||
platformContext: Pick<PlatformContext, 'requestGraphQL'>
|
||||
},
|
||||
force?: boolean
|
||||
): Observable<string[][]> =>
|
||||
platformContext
|
||||
.requestGraphQL<HighlightedFileResult, HighlightedFileVariables>({
|
||||
request: gql`
|
||||
query HighlightedFile(
|
||||
$repoName: String!
|
||||
$commitID: String!
|
||||
$filePath: String!
|
||||
$disableTimeout: Boolean!
|
||||
$ranges: [HighlightLineRange!]!
|
||||
) {
|
||||
repository(name: $repoName) {
|
||||
commit(rev: $commitID) {
|
||||
file(path: $filePath) {
|
||||
isDirectory
|
||||
richHTML
|
||||
highlight(disableTimeout: $disableTimeout) {
|
||||
aborted
|
||||
lineRanges(ranges: $ranges)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
variables: { ...context, disableTimeout: !!context.disableTimeout },
|
||||
mightContainPrivateInfo: true,
|
||||
})
|
||||
.pipe(
|
||||
map(({ data, errors }) => {
|
||||
if (!data?.repository?.commit?.file?.highlight) {
|
||||
throw createAggregateError(errors)
|
||||
}
|
||||
const file = data.repository.commit.file
|
||||
if (file.isDirectory) {
|
||||
return []
|
||||
}
|
||||
return file.highlight.lineRanges
|
||||
})
|
||||
),
|
||||
context =>
|
||||
makeRepoURI(context) +
|
||||
`?disableTimeout=${String(context.disableTimeout)}&ranges=${context.ranges
|
||||
.map(range => `${range.startLine}:${range.endLine}`)
|
||||
.join(',')}`
|
||||
)
|
||||
@ -1,12 +1,13 @@
|
||||
import { from, Observable } from 'rxjs'
|
||||
import { map } from 'rxjs/operators'
|
||||
|
||||
import { memoizeObservable } from '@sourcegraph/common'
|
||||
import { createAggregateError, memoizeObservable } from '@sourcegraph/common'
|
||||
import { dataOrThrowErrors, gql } from '@sourcegraph/http-client'
|
||||
|
||||
import { TreeEntriesResult, TreeFields } from '../graphql-operations'
|
||||
import { PlatformContext } from '../platform/context'
|
||||
import * as GQL from '../schema'
|
||||
import { RepoSpec } from '../util/url'
|
||||
import { AbsoluteRepoFile, makeRepoURI, RepoSpec } from '../util/url'
|
||||
|
||||
import { CloneInProgressError, RepoNotFoundError } from './errors'
|
||||
|
||||
@ -47,3 +48,57 @@ export const resolveRawRepoName = memoizeObservable(
|
||||
),
|
||||
({ repoName }) => repoName
|
||||
)
|
||||
|
||||
export const fetchTreeEntries = memoizeObservable(
|
||||
({
|
||||
requestGraphQL,
|
||||
...args
|
||||
}: AbsoluteRepoFile & { first?: number } & Pick<PlatformContext, 'requestGraphQL'>): Observable<TreeFields> =>
|
||||
requestGraphQL<TreeEntriesResult>({
|
||||
request: gql`
|
||||
query TreeEntries(
|
||||
$repoName: String!
|
||||
$revision: String!
|
||||
$commitID: String!
|
||||
$filePath: String!
|
||||
$first: Int
|
||||
) {
|
||||
repository(name: $repoName) {
|
||||
commit(rev: $commitID, inputRevspec: $revision) {
|
||||
tree(path: $filePath) {
|
||||
...TreeFields
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fragment TreeFields on GitTree {
|
||||
isRoot
|
||||
url
|
||||
entries(first: $first, recursiveSingleChild: true) {
|
||||
...TreeEntryFields
|
||||
}
|
||||
}
|
||||
fragment TreeEntryFields on TreeEntry {
|
||||
name
|
||||
path
|
||||
isDirectory
|
||||
url
|
||||
submodule {
|
||||
url
|
||||
commit
|
||||
}
|
||||
isSingleChild
|
||||
}
|
||||
`,
|
||||
variables: args,
|
||||
mightContainPrivateInfo: true,
|
||||
}).pipe(
|
||||
map(({ data, errors }) => {
|
||||
if (errors || !data?.repository?.commit?.tree) {
|
||||
throw createAggregateError(errors)
|
||||
}
|
||||
return data.repository.commit.tree
|
||||
})
|
||||
),
|
||||
({ first, requestGraphQL, ...args }) => `${makeRepoURI(args)}:first-${String(first)}`
|
||||
)
|
||||
|
||||
@ -113,7 +113,7 @@ export const FileMatch: React.FunctionComponent<Props> = props => {
|
||||
|
||||
// The number of lines of context to show before and after each match.
|
||||
const context = useMemo(() => {
|
||||
if (props.location.pathname === '/search') {
|
||||
if (props.location?.pathname === '/search') {
|
||||
// Check if search.contextLines is configured in settings.
|
||||
const contextLinesSetting =
|
||||
isSettingsValid(props.settingsCascade) &&
|
||||
|
||||
@ -33,7 +33,7 @@ import { MatchGroup } from './ranking/PerFileResultRanking'
|
||||
import styles from './FileMatchChildren.module.scss'
|
||||
|
||||
interface FileMatchProps extends SettingsCascadeProps, TelemetryProps {
|
||||
location: H.Location
|
||||
location?: H.Location
|
||||
result: ContentMatch | SymbolMatch | PathMatch
|
||||
grouped: MatchGroup[]
|
||||
/* Clicking on a match opens the link in a new tab */
|
||||
@ -41,7 +41,6 @@ interface FileMatchProps extends SettingsCascadeProps, TelemetryProps {
|
||||
/* Called when the first result has fully loaded. */
|
||||
onFirstResultLoad?: () => void
|
||||
fetchHighlightedFileLineRanges: (parameters: FetchFileParameters, force?: boolean) => Observable<string[][]>
|
||||
|
||||
extensionsController?: Pick<ExtensionsController, 'extHostAPI'>
|
||||
hoverifier?: Hoverifier<HoverContext, HoverMerged, ActionItemAction>
|
||||
}
|
||||
|
||||
@ -53,7 +53,24 @@ export interface ExtensionsControllerProps<K extends keyof Controller = keyof Co
|
||||
* There should only be a single controller for the entire client application. The controller's model represents
|
||||
* all of the client application state that the client needs to know.
|
||||
*/
|
||||
export function createController(context: PlatformContext): Controller {
|
||||
export function createController(
|
||||
context: Pick<
|
||||
PlatformContext,
|
||||
| 'updateSettings'
|
||||
| 'settings'
|
||||
| 'getGraphQLClient'
|
||||
| 'requestGraphQL'
|
||||
| 'showMessage'
|
||||
| 'showInputBox'
|
||||
| 'sideloadedExtensionURL'
|
||||
| 'getScriptURLForExtension'
|
||||
| 'getStaticExtensions'
|
||||
| 'telemetryService'
|
||||
| 'clientApplication'
|
||||
| 'sourcegraphURL'
|
||||
| 'createExtensionHost'
|
||||
>
|
||||
): Controller {
|
||||
const subscriptions = new Subscription()
|
||||
|
||||
const initData: Omit<InitData, 'initialSettings'> = {
|
||||
|
||||
@ -8,6 +8,11 @@ import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
|
||||
import { SearchPatternType } from '../graphql-operations'
|
||||
import { SymbolKind } from '../schema'
|
||||
|
||||
// The latest supported version of our search syntax. Users should never be able to determine the search version.
|
||||
// The version is set based on the release tag of the instance. Anything before 3.9.0 will not pass a version parameter,
|
||||
// and will therefore default to V1.
|
||||
export const LATEST_VERSION = 'V2'
|
||||
|
||||
/** All values that are valid for the `type:` filter. `null` represents default code search. */
|
||||
export type SearchType = 'file' | 'repo' | 'path' | 'symbol' | 'diff' | 'commit' | null
|
||||
|
||||
|
||||
@ -583,3 +583,26 @@ export function buildGetStartedURL(source: string, returnTo?: string): string {
|
||||
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
/** The results of parsing a repo-revision string like "my/repo@my/revision". */
|
||||
export interface ParsedRepoRevision {
|
||||
repoName: string
|
||||
|
||||
/** The URI-decoded revision (e.g., "my#branch" in "my/repo@my%23branch"). */
|
||||
revision?: string
|
||||
|
||||
/** The raw revision (e.g., "my%23branch" in "my/repo@my%23branch"). */
|
||||
rawRevision?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a repo-revision string like "my/repo@my/revision" to the repo and revision components.
|
||||
*/
|
||||
export function parseRepoRevision(repoRevision: string): ParsedRepoRevision {
|
||||
const [repository, revision] = repoRevision.split('@', 2) as [string, string | undefined]
|
||||
return {
|
||||
repoName: decodeURIComponent(repository),
|
||||
revision: revision && decodeURIComponent(revision),
|
||||
rawRevision: revision,
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,2 +1,3 @@
|
||||
dist/
|
||||
package.json
|
||||
src/polyfills/eventSource.js
|
||||
|
||||
1
client/vscode/.gitignore
vendored
1
client/vscode/.gitignore
vendored
@ -1,2 +1,3 @@
|
||||
dist/
|
||||
*.vsix
|
||||
.vscode-test/
|
||||
|
||||
@ -12,3 +12,8 @@ test/**
|
||||
tsconfig.json
|
||||
.eslintrc.js
|
||||
.eslintignore
|
||||
.vscode
|
||||
node_modules
|
||||
out/
|
||||
src/
|
||||
webpack.config.js
|
||||
|
||||
69
client/vscode/CHANGELOG.md
Normal file
69
client/vscode/CHANGELOG.md
Normal file
@ -0,0 +1,69 @@
|
||||
# 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.
|
||||
|
||||
## Next Release - 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)
|
||||
|
||||
### 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
|
||||
55
client/vscode/CONTRIBUTING.md
Normal file
55
client/vscode/CONTRIBUTING.md
Normal file
@ -0,0 +1,55 @@
|
||||
# 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.
|
||||
|
||||
## 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 [GitHub Feedback discussion board](https://github.com/sourcegraph/sourcegraph/discussions/categories/feedback).
|
||||
|
||||
## Issues / Bugs
|
||||
|
||||
New issues and feature requests can be filed through our [issue tracker](https://github.com/sourcegraph/sourcegraph/issues/new/choose) using the `vscode-extension` label.
|
||||
|
||||
## Development
|
||||
|
||||
### Build and run
|
||||
|
||||
1. `git clone` the [Sourcegraph repository](https://github.com/sourcegraph/sourcegraph)
|
||||
1. Install dependencies via `yarn` for the Sourcegraph repository
|
||||
1. Run `yarn generate` at the root directory to generate the required schemas
|
||||
1. Make your changes to the files within the `client/vscode` directory with VS Code
|
||||
1. Run `yarn build-vsce` to build or `yarn watch-vsce` to build and watch the tasks in the `client/vscode` directory
|
||||
1. Select `Launch VS Code Extension` (`Launch VS Code Web Extension` for VS Code Web) from the dropdown menu in the `Run and Debug` sidebar view to see your changes
|
||||
|
||||
### Tests
|
||||
|
||||
1. In the Sourcegraph repository:
|
||||
1. `yarn`
|
||||
2. `yarn generate`
|
||||
2. In the `client/vscode` directory:
|
||||
1. `yarn build`
|
||||
2. `yarn package`
|
||||
3. `yarn test`
|
||||
|
||||
### 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)
|
||||
- [Issue Tracker](https://github.com/sourcegraph/sourcegraph/labels/vscode-extension)
|
||||
- [Troubleshooting docs](https://docs.sourcegraph.com/admin/how-to/troubleshoot-sg-extension#vs-code-extension)
|
||||
|
||||
## License
|
||||
|
||||
Apache
|
||||
201
client/vscode/LICENSE
Normal file
201
client/vscode/LICENSE
Normal file
@ -0,0 +1,201 @@
|
||||
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 [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
119
client/vscode/README.md
Normal file
119
client/vscode/README.md
Normal file
@ -0,0 +1,119 @@
|
||||
# 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.
|
||||
|
||||
Plus, with a free Sourcegraph Cloud account, you can sync your own private and public repositories and search all of your code in a single view in VS Code. 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/).
|
||||
|
||||
## Installation
|
||||
|
||||
### From the Visual Studio Marketplace:
|
||||
|
||||
1. Install Sourcegraph from the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=sourcegraph.sourcegraph).
|
||||
2. Launch VS Code, and click on the Sourcegraph (Wildcard) icon in the VS Code Activity Bar to open the Sourcegraph extension. Alternatively, you can launch the extension by pressing <kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> and searching for “Sourcegraph: Open search tab.”
|
||||
|
||||
### From within VS Code:
|
||||
|
||||
1. Open the extensions tab on the left side of VS Code (<kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd>).
|
||||
2. Search for `Sourcegraph` -> `Install` and `Reload`.
|
||||
|
||||
## 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.
|
||||
|
||||
Sourcegraph offers 3 different ways to search:
|
||||
|
||||
1. [Literal search](https://learn.sourcegraph.com/how-to-search-code-with-sourcegraph-using-literal-patterns)
|
||||
2. [Structural search](https://learn.sourcegraph.com/how-to-search-with-sourcegraph-using-structural-patterns)
|
||||
3. [Regular expressions](https://learn.sourcegraph.com/how-to-search-with-sourcegraph-using-regular-expression-patterns)
|
||||
|
||||
Sourcegraph also accepts filters to narrow down search results, such as `repo`, `file`, and `lang`. Check out our search [cheat sheet](https://learn.sourcegraph.com/how-to-search-code-with-sourcegraph-a-cheat-sheet).
|
||||
|
||||
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 Cloud 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. Create an account using your email or connect directly to your code host.
|
||||
3. Once you have created an account, navigate to Sourcegraph Cloud. Click on your profile icon in the navigation bar to go to `Your repositories`.
|
||||
4. Click `Manage repositories`. From here, you can add your repositories to be synced to Sourcegraph.
|
||||
|
||||
### Connecting Sourcegraph Cloud account
|
||||
|
||||
Once you have repositories synced to Sourcegraph, you can generate an access token to connect your VS Code extension back to your Sourcegraph Cloud account.
|
||||
|
||||
1. Back in Sourcegraph Cloud, in your account settings, navigate to `Access tokens`, then click `Generate new token`.
|
||||
2. Once you have generated a token, navigate back to the Sourcegraph extension. In the sidebar, under `Create an account`, click `Have an account?`.
|
||||
3. Copy and paste the generated token from step 4 into the input field in the sidebar.
|
||||
4. Alternatively, you can copy and paste the generated token from step 4 in this format: `“sourcegraph.accessToken": "e4234234123112312”` into your VS Code Setting by going to `Code` > `Preference` > `Settings` > Search for "Sourcegraph" > `Edit in settings.json`.
|
||||
5. The Editor will be reloaded automatically to use the newly added token.
|
||||
|
||||
### Connecting to a private 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.
|
||||
|
||||
## Keyboard Shortcuts:
|
||||
|
||||
| Description | Mac | Linux / Windows |
|
||||
| -------------------------------------------- | -------------------------------------------- | --------------------------------------------- |
|
||||
| Open Sourcegraph Search Tab/Search Selection | <kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>8</kbd> | <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>8</kbd> |
|
||||
| Open File in Sourcegraph Cloud | <kbd>Option</kbd>+<kbd>A</kbd> | <kbd>Alt</kbd>+<kbd>A</kbd> |
|
||||
| Search Selected Text in Sourcegraph Cloud | <kbd>Option</kbd>+<kbd>S</kbd> | <kbd>Alt</kbd>+<kbd>S</kbd> |
|
||||
|
||||
## Extension Settings
|
||||
|
||||
This extension contributes the following settings:
|
||||
|
||||
| Setting | Description | Example |
|
||||
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ |
|
||||
| `sourcegraph.url` | Specify your on-premises Sourcegraph instance here, if applicable. The extension is connected to Sourcegraph Cloud by default. | "https://your-sourcegraph.com" |
|
||||
| `sourcegraph.accessToken` | The access token to query the Sourcegraph API. Required to use this extension with private instances. | "6dfc880b320dff712d9f6cfcac5cbd13ebfad1d8" |
|
||||
| `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"} |
|
||||
|
||||
## Questions & Feedback
|
||||
|
||||
Please take a look at our [troubleshooting docs](https://docs.sourcegraph.com/admin/how-to/troubleshoot-sg-extension#vs-code-extension) for [known issues](https://docs.sourcegraph.com/admin/how-to/troubleshoot-sg-extension#unsupported-features-by-sourcegraph-version) and common issues in the VS Code extension.
|
||||
|
||||
New issues and feature requests can be submitted at https://github.com/sourcegraph/sourcegraph-vscode/issues/new.
|
||||
|
||||
## Uninstallation
|
||||
|
||||
1. Open the extensions tab on the left side of VS Code (<kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd>).
|
||||
2. Search for `Sourcegraph` -> Gear icon -> `Uninstall` and `Reload`.
|
||||
|
||||
## Changelog
|
||||
|
||||
Click [here](https://marketplace.visualstudio.com/items/sourcegraph.sourcegraph/changelog) to check the full changelog.
|
||||
|
||||
VS Code will auto-update extensions to the highest version available. Even if you have opted into a pre-release version, you will be updated to the released version when a higher version is released.
|
||||
|
||||
The Sourcegraph extension uses major.EVEN_NUMBER.patch (eg. 2.0.1) for release versions and major.ODD_NUMBER.patch (eg. 2.1.1) for pre-release versions.```
|
||||
|
||||
## Development
|
||||
|
||||
Please see the [CONTRIBUTING](./CONTRIBUTING.md) document if you are interested in contributing directly to our code base.
|
||||
91
client/vscode/gulpfile.js
Normal file
91
client/vscode/gulpfile.js
Normal file
@ -0,0 +1,91 @@
|
||||
const path = require('path')
|
||||
|
||||
require('ts-node').register({
|
||||
transpileOnly: true,
|
||||
// Use config with "module": "commonjs" because not all modules involved in tasks are esnext modules.
|
||||
project: path.resolve(__dirname, './tsconfig.json'),
|
||||
})
|
||||
|
||||
const log = require('fancy-log')
|
||||
const gulp = require('gulp')
|
||||
const createWebpackCompiler = require('webpack')
|
||||
|
||||
const {
|
||||
graphQlSchema,
|
||||
graphQlOperations,
|
||||
schema,
|
||||
watchGraphQlSchema,
|
||||
watchGraphQlOperations,
|
||||
watchSchema,
|
||||
cssModulesTypings,
|
||||
watchCSSModulesTypings,
|
||||
} = require('../shared/gulpfile')
|
||||
|
||||
const createWebpackConfig = require('./webpack.config')
|
||||
|
||||
const WEBPACK_STATS_OPTIONS = {
|
||||
all: false,
|
||||
timings: true,
|
||||
errors: true,
|
||||
warnings: true,
|
||||
colors: true,
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('webpack').Stats} stats
|
||||
*/
|
||||
const logWebpackStats = stats => {
|
||||
log(stats.toString(WEBPACK_STATS_OPTIONS))
|
||||
}
|
||||
|
||||
async function webpack() {
|
||||
const webpackConfig = await createWebpackConfig()
|
||||
const compiler = createWebpackCompiler(webpackConfig)
|
||||
/** @type {import('webpack').Stats} */
|
||||
const stats = await new Promise((resolve, reject) => {
|
||||
compiler.run((error, stats) => (error ? reject(error) : resolve(stats)))
|
||||
})
|
||||
logWebpackStats(stats)
|
||||
if (stats.hasErrors()) {
|
||||
throw Object.assign(new Error('Failed to compile'), { showStack: false })
|
||||
}
|
||||
}
|
||||
|
||||
async function watchWebpack() {
|
||||
const webpackConfig = await createWebpackConfig()
|
||||
const compiler = createWebpackCompiler(webpackConfig)
|
||||
compiler.hooks.watchRun.tap('Notify', () => log('Webpack compiling...'))
|
||||
await new Promise(() => {
|
||||
compiler.watch({ aggregateTimeout: 300 }, (error, stats) => {
|
||||
logWebpackStats(stats)
|
||||
if (error || stats.hasErrors()) {
|
||||
log.error('Webpack compilation error')
|
||||
} else {
|
||||
log('Webpack compilation done')
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure the typings that TypeScript depends on are build to avoid first-time-run errors
|
||||
const generate = gulp.parallel(schema, graphQlSchema, graphQlOperations, cssModulesTypings)
|
||||
|
||||
// Watches code generation only, rebuilds on file changes
|
||||
const watchGenerators = gulp.parallel(watchSchema, watchGraphQlSchema, watchGraphQlOperations, watchCSSModulesTypings)
|
||||
|
||||
/**
|
||||
* Builds everything.
|
||||
*/
|
||||
const build = gulp.series(generate, webpack)
|
||||
|
||||
/**
|
||||
* Watches everything, rebuilds on file changes and writes the bundle to disk.
|
||||
* Useful to running integration tests.
|
||||
*/
|
||||
const watch = gulp.series(
|
||||
// Ensure the typings that TypeScript depends on are build to avoid first-time-run errors
|
||||
generate,
|
||||
gulp.parallel(watchGenerators, watchWebpack)
|
||||
)
|
||||
|
||||
module.exports = { build, watch, webpack, watchWebpack }
|
||||
26
client/vscode/images/logomark_dark.svg
Normal file
26
client/vscode/images/logomark_dark.svg
Normal file
@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 25.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 53.4 55.5" style="enable-background:new 0 0 53.4 55.5;" xml:space="preserve">
|
||||
<style type="text/css">
|
||||
.st0{fill:#FFFFFF;}
|
||||
.st1{fill:#FF5543;}
|
||||
.st2{fill:#A112FF;}
|
||||
.st3{fill:#00CBEC;}
|
||||
</style>
|
||||
<g>
|
||||
<g>
|
||||
<path d="M39.3,10.2c0.7-0.6,1.5-1,2.4-1.1c1.7-0.3,3.6,0.3,4.8,1.7c1.8,2.2,1.6,5.4-0.6,7.2l-7.6,6.5l-5.6-2l-2.1-0.7l-3.5-1.2
|
||||
l2.8-2.4l1.7-1.4L39.3,10.2z"/>
|
||||
<path d="M13.9,45.3c-0.7,0.6-1.5,1-2.4,1.1c-1.7,0.3-3.6-0.3-4.8-1.7c-1.8-2.2-1.6-5.4,0.6-7.2l7.6-6.5l5.6,2l2.1,0.7L26,35
|
||||
l-2.8,2.4l-1.7,1.4L13.9,45.3z"/>
|
||||
</g>
|
||||
<g>
|
||||
<path d="M17.7,7.9c-0.5-2.8,1.3-5.5,4.1-6s5.5,1.3,6,4.1l1.8,9.8l-4.5,3.8l-5.6-2L17.7,7.9z"/>
|
||||
<path d="M35.5,47.5c0.5,2.8-1.3,5.5-4.1,6c-2.8,0.5-5.5-1.3-6-4.1l-1.8-9.8l4.5-3.8l5.6,2L35.5,47.5z"/>
|
||||
</g>
|
||||
<path d="M51.3,36.5c-0.6,1.8-2.2,3-3.9,3.3c-0.9,0.2-1.8,0.1-2.6-0.2l-9.4-3.3l-2.1-0.7l-3.5-1.2l-2.1-0.7l-5.6-2L20,30.8l-3.5-1.2
|
||||
l-2.1-0.7L5,25.5C2.3,24.6,1,21.6,1.9,19c0.6-1.8,2.2-3,3.9-3.3c0.9-0.2,1.8-0.1,2.6,0.2l9.4,3.3l2.1,0.7l3.5,1.2l2.1,0.7l5.6,2
|
||||
l2.1,0.7l3.5,1.2l2.1,0.7l9.4,3.3C50.9,30.9,52.3,33.8,51.3,36.5z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
26
client/vscode/images/logomark_light.svg
Normal file
26
client/vscode/images/logomark_light.svg
Normal file
@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 25.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 53.4 55.5" style="enable-background:new 0 0 53.4 55.5;" xml:space="preserve">
|
||||
<style type="text/css">
|
||||
.st0{fill:#FFFFFF;}
|
||||
.st1{fill:#FF5543;}
|
||||
.st2{fill:#A112FF;}
|
||||
.st3{fill:#00CBEC;}
|
||||
</style>
|
||||
<g>
|
||||
<g>
|
||||
<path class="st0" d="M39.3,10.2c0.7-0.6,1.5-1,2.4-1.1c1.7-0.3,3.6,0.3,4.8,1.7c1.8,2.2,1.6,5.4-0.6,7.2l-7.6,6.5l-5.6-2l-2.1-0.7
|
||||
l-3.5-1.2l2.8-2.4l1.7-1.4L39.3,10.2z"/>
|
||||
<path class="st0" d="M13.9,45.3c-0.7,0.6-1.5,1-2.4,1.1c-1.7,0.3-3.6-0.3-4.8-1.7c-1.8-2.2-1.6-5.4,0.6-7.2l7.6-6.5l5.6,2l2.1,0.7
|
||||
L26,35l-2.8,2.4l-1.7,1.4L13.9,45.3z"/>
|
||||
</g>
|
||||
<g>
|
||||
<path class="st0" d="M17.7,7.9c-0.5-2.8,1.3-5.5,4.1-6s5.5,1.3,6,4.1l1.8,9.8l-4.5,3.8l-5.6-2L17.7,7.9z"/>
|
||||
<path class="st0" d="M35.5,47.5c0.5,2.8-1.3,5.5-4.1,6c-2.8,0.5-5.5-1.3-6-4.1l-1.8-9.8l4.5-3.8l5.6,2L35.5,47.5z"/>
|
||||
</g>
|
||||
<path class="st0" d="M51.3,36.5c-0.6,1.8-2.2,3-3.9,3.3c-0.9,0.2-1.8,0.1-2.6-0.2l-9.4-3.3l-2.1-0.7l-3.5-1.2l-2.1-0.7l-5.6-2
|
||||
L20,30.8l-3.5-1.2l-2.1-0.7L5,25.5C2.3,24.6,1,21.6,1.9,19c0.6-1.8,2.2-3,3.9-3.3c0.9-0.2,1.8-0.1,2.6,0.2l9.4,3.3l2.1,0.7l3.5,1.2
|
||||
l2.1,0.7l5.6,2l2.1,0.7l3.5,1.2l2.1,0.7l9.4,3.3C50.9,30.9,52.3,33.8,51.3,36.5z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
1
client/vscode/images/sourcegraph-logo-dark.svg
Normal file
1
client/vscode/images/sourcegraph-logo-dark.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 304 52" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M30.8 51.8c-2.8.5-5.5-1.3-6-4.1L17.2 6.2c-.5-2.8 1.3-5.5 4.1-6s5.5 1.3 6 4.1l7.6 41.5c.5 2.8-1.4 5.5-4.1 6z" fill="#FF5543"/><path d="M10.9 44.7C9.1 45 7.3 44.4 6 43c-1.8-2.2-1.6-5.4.6-7.2L38.7 8.5c2.2-1.8 5.4-1.6 7.2.6 1.8 2.2 1.6 5.4-.6 7.2l-32 27.3c-.7.6-1.6 1-2.4 1.1z" fill="#A112FF"/><path d="M46.8 38.1c-.9.2-1.8.1-2.6-.2L4.4 23.8c-2.7-1-4.1-3.9-3.1-6.6 1-2.7 3.9-4.1 6.6-3.1l39.7 14.1c2.7 1 4.1 3.9 3.1 6.6-.6 1.8-2.2 3-3.9 3.3z" fill="#00CBEC"/><path d="M80 33.1c0-1-.4-1.8-1.1-2.4-.7-.6-1.6-1.2-2.7-1.7s-2.3-1-3.6-1.6c-1.3-.5-2.5-1.2-3.6-2s-2-1.8-2.7-3c-.7-1.2-1.1-2.7-1.1-4.5 0-1.6.3-3 .8-4.1.5-1.2 1.3-2.1 2.3-2.9 1-.8 2.1-1.3 3.5-1.7 1.3-.4 2.8-.6 4.5-.6 1.9 0 3.7.2 5.3.5 1.6.3 3.1.8 4.1 1.4l-2 5.3c-.7-.4-1.7-.8-3.1-1.1-1.4-.4-2.8-.5-4.4-.5-1.5 0-2.6.3-3.4.9-.8.6-1.2 1.4-1.2 2.4 0 .9.4 1.7 1.1 2.3.7.6 1.6 1.2 2.7 1.7s2.3 1.1 3.6 1.6c1.3.6 2.5 1.2 3.6 2s2 1.8 2.7 2.9c.7 1.2 1.1 2.6 1.1 4.3 0 1.7-.3 3.2-.9 4.5-.6 1.3-1.4 2.3-2.4 3.1-1 .8-2.3 1.5-3.8 1.9-1.5.4-3.1.6-4.9.6-2.3 0-4.4-.2-6.1-.7-1.8-.4-3.1-.9-3.9-1.3l2-5.4c.3.2.8.4 1.3.6.5.2 1.2.4 1.8.6.7.2 1.4.3 2.2.5.8.1 1.5.2 2.3.2 1.9 0 3.3-.3 4.3-1 1.2-.6 1.7-1.5 1.7-2.8zm9.1-2.9c0-3.9 1-7 2.9-9.1 1.9-2.1 4.6-3.2 8.1-3.2 1.9 0 3.5.3 4.8.9 1.4.6 2.5 1.4 3.4 2.5.9 1.1 1.6 2.4 2 3.9.4 1.5.7 3.2.7 5 0 3.9-1 7-2.9 9.1-1.9 2.1-4.6 3.2-8.1 3.2-1.9 0-3.5-.3-4.8-.9-1.4-.6-2.5-1.4-3.4-2.5-.9-1.1-1.6-2.4-2-3.9-.5-1.5-.7-3.2-.7-5zm6.2 0c0 1 .1 2 .3 2.8.2.9.5 1.6.8 2.3.4.7.9 1.2 1.5 1.5.6.4 1.3.5 2.2.5 1.6 0 2.8-.6 3.5-1.7.8-1.1 1.2-3 1.2-5.4 0-2.1-.4-3.9-1.1-5.2-.7-1.3-1.9-2-3.6-2-1.5 0-2.7.6-3.5 1.7-.9 1.1-1.3 2.9-1.3 5.5zm24.8-11.6v13.2c0 1.9.2 3.3.7 4.1.4.8 1.3 1.3 2.6 1.3 1.1 0 2.1-.3 2.9-1 .8-.7 1.3-1.5 1.7-2.5v-15h6v16.2c0 1.3.1 2.5.2 3.7.1 1.2.3 2.3.6 3.3h-4.6l-1.1-3.4h-.2c-.7 1.2-1.7 2.2-3 2.9-1.3.8-2.8 1.2-4.5 1.2-1.2 0-2.2-.2-3.2-.5-.9-.3-1.7-.8-2.3-1.5-.6-.7-1.1-1.7-1.4-2.9-.3-1.2-.5-2.8-.5-4.7V18.6h6.1zm31.4 5.6c-1-.3-1.8-.5-2.6-.5-1.1 0-2 .3-2.7.9-.7.6-1.2 1.3-1.5 2.2v15h-6V18.6h4.7l.7 3.1h.2c.5-1.1 1.2-2 2.1-2.7.9-.7 2-.9 3.2-.9.8 0 2.5.4 3.4.8l-1.5 5.3zm19.6 16.2c-.9.7-2.1 1.2-3.4 1.6-1.3.4-2.7.5-4.1.5-1.9 0-3.4-.3-4.7-.9-1.3-.6-2.3-1.4-3.1-2.5-.8-1.1-1.4-2.4-1.7-3.9-.4-1.5-.5-3.2-.5-5 0-3.9.9-7 2.7-9.1 1.8-2.1 4.3-3.2 7.7-3.2 1.7 0 3.1.1 4.1.4 1 .3 2 .6 2.8 1.1l-1.4 4.9c-.7-.3-1.4-.6-2.1-.8-.7-.2-1.5-.3-2.4-.3-1.7 0-2.9.6-3.8 1.7-.9 1.1-1.3 2.9-1.3 5.3 0 1 .1 1.9.3 2.7.2.8.5 1.6 1 2.2.4.6 1 1.1 1.7 1.5.7.4 1.5.5 2.4.5 1 0 1.9-.1 2.6-.4.7-.3 1.3-.6 1.9-1l1.3 4.7zm21.3-.6c-.9.7-2.2 1.4-3.8 1.9-1.6.5-3.3.8-5.1.8-3.8 0-6.5-1.1-8.2-3.3-1.7-2.2-2.6-5.2-2.6-9 0-4.1 1-7.2 2.9-9.2 1.9-2 4.7-3.1 8.2-3.1 1.2 0 2.3.2 3.4.5s2.1.8 3 1.5c.9.7 1.6 1.7 2.1 2.9s.8 2.7.8 4.5c0 .7 0 1.3-.1 2.1-.1.7-.2 1.5-.3 2.3h-14c.1 2 .6 3.4 1.5 4.4.9 1 2.4 1.5 4.4 1.5 1.3 0 2.4-.2 3.4-.6 1-.4 1.8-.8 2.3-1.2l2.1 4zm-8.7-17.1c-1.6 0-2.8.5-3.5 1.4-.8.9-1.2 2.2-1.4 3.8h8.6c.1-1.7-.1-3-.8-3.9-.5-.8-1.5-1.3-2.9-1.3zm32.9 19.1c0 3.4-.9 5.9-2.7 7.5-1.8 1.6-4.4 2.4-7.7 2.4-2.2 0-4-.2-5.3-.5-1.3-.3-2.3-.6-2.9-1l1.3-4.8c.7.3 1.5.6 2.5.8 1 .2 2.1.4 3.5.4 2.1 0 3.5-.5 4.3-1.4.8-.9 1.1-2.2 1.1-3.8V40h-.2c-1.1 1.5-3 2.2-5.8 2.2-3 0-5.2-.9-6.7-2.8s-2.2-4.8-2.2-8.7c0-4.2 1-7.3 3-9.4 2-2.1 4.9-3.2 8.6-3.2 2 0 3.8.1 5.3.4 1.5.3 2.8.6 3.8 1l.1 22.3zm-10.2-4.5c1.2 0 2.1-.3 2.7-.8.6-.5 1.1-1.3 1.5-2.4V23.7c-1-.4-2.2-.6-3.6-.6-1.6 0-2.8.6-3.6 1.7-.9 1.2-1.3 3-1.3 5.6 0 2.3.4 4 1.1 5.2.7 1.2 1.8 1.7 3.2 1.7zm27.7-13.1c-1-.3-1.8-.5-2.6-.5-1.1 0-2 .3-2.7.9-.7.6-1.2 1.3-1.5 2.2v15h-6V18.6h4.7l.7 3.1h.2c.5-1.1 1.2-2 2.1-2.7.9-.7 2-.9 3.2-.9.8 0 1.7.2 2.7.5l-.8 5.6zm2.9-4.5c1.2-.6 2.1-.8 3.8-1.1 1.7-.3 3.5-.5 5.3-.5 1.6 0 3 .2 4 .6 1 .4 1.9.9 2.6 1.7.6.7 1.1 1.6 1.3 2.6.3 1 .4 2.1.4 3.3 0 1.4 0 2.7-.1 4.1-.1 1.4-.1 2.7-.2 4.1 0 1.3 0 2.6.1 3.9.1 1.3.3 2.4.7 3.6H250l-1-3.2c-.6 1-1.5 1.8-2.6 2.5s-2.5 1-4.3 1c-1.1 0-2.1-.2-2.9-.5-.9-.3-1.6-.8-2.2-1.4-.6-.6-1.1-1.3-1.4-2.1-.3-.8-.5-1.7-.5-2.8 0-1.4.3-2.6 1-3.6s1.5-1.8 2.7-2.4c1.2-.6 2.6-1 4.3-1.3 1.7-.3 3.5-.3 5.6-.2.2-1.7.1-3-.4-3.7-.5-.8-1.5-1.1-3.1-1.1-1.2 0-2.5.1-3.8.4-1.3.3-1.9.4-2.7.8l-1.7-4.7zm7.1 17.5c1.2 0 2.2-.3 2.9-.8.7-.5 1.2-1.1 1.6-1.7v-3c-1-.1-1.9-.1-2.8 0-.9.1-1.7.2-2.3.4-.6.2-1.2.5-1.6.9-.4.4-.6.9-.6 1.5 0 .9.3 1.5.8 2 .4.5 1.1.7 2 .7zm15-18.6h4.4l.7 2.8h.2c.8-1.2 1.8-2 2.9-2.6 1.1-.6 2.4-.8 4-.8 2.9 0 5.1.9 6.6 2.8s2.2 4.8 2.2 8.9c0 2-.2 3.8-.7 5.4-.5 1.6-1.2 3-2.1 4.1-.9 1.1-2 2-3.3 2.6-1.3.6-2.8.9-4.5.9-1 0-1.8-.1-2.4-.2-.6-.1-1.2-.4-1.9-.7v9.5h-6V18.6h-.1zm10.3 4.4c-1.2 0-2.1.3-2.8.9-.7.6-1.2 1.5-1.6 2.7v9.7c.4.3.9.6 1.4.8.5.2 1.2.3 2 .3 1.7 0 3-.6 3.9-1.8.9-1.2 1.3-3.2 1.3-6.1 0-2-.3-3.6-1-4.7-.6-1.2-1.7-1.8-3.2-1.8zm28.2 18.8V28.6c0-1.9-.3-3.3-.8-4.1-.5-.8-1.5-1.3-2.9-1.3-1 0-2 .3-2.8 1-.9.7-1.4 1.6-1.7 2.7v14.8h-6V9.3h6v11.9h.2c.7-1 1.7-1.8 2.7-2.4 1.1-.6 2.5-.9 4.1-.9 1.2 0 2.2.2 3.1.5.9.3 1.7.8 2.3 1.5.6.7 1.1 1.7 1.3 2.9.2 1.2.4 2.7.4 4.5v14.5h-5.9z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 4.8 KiB |
1
client/vscode/images/sourcegraph-logo-light.svg
Normal file
1
client/vscode/images/sourcegraph-logo-light.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 304 52" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M30.8 51.8c-2.8.5-5.5-1.3-6-4.1L17.2 6.2c-.5-2.8 1.3-5.5 4.1-6s5.5 1.3 6 4.1l7.6 41.5c.5 2.8-1.4 5.5-4.1 6z" fill="#FF5543"/><path d="M10.9 44.7C9.1 45 7.3 44.4 6 43c-1.8-2.2-1.6-5.4.6-7.2L38.7 8.5c2.2-1.8 5.4-1.6 7.2.6 1.8 2.2 1.6 5.4-.6 7.2l-32 27.3c-.7.6-1.6 1-2.4 1.1z" fill="#A112FF"/><path d="M46.8 38.1c-.9.2-1.8.1-2.6-.2L4.4 23.8c-2.7-1-4.1-3.9-3.1-6.6 1-2.7 3.9-4.1 6.6-3.1l39.7 14.1c2.7 1 4.1 3.9 3.1 6.6-.6 1.8-2.2 3-3.9 3.3z" fill="#00CBEC"/><path d="M80 33.1c0-1-.4-1.8-1.1-2.4-.7-.6-1.6-1.2-2.7-1.7s-2.3-1-3.6-1.6c-1.3-.5-2.5-1.2-3.6-2s-2-1.8-2.7-3c-.7-1.2-1.1-2.7-1.1-4.5 0-1.6.3-3 .8-4.1.5-1.2 1.3-2.1 2.3-2.9 1-.8 2.1-1.3 3.5-1.7 1.3-.4 2.8-.6 4.5-.6 1.9 0 3.7.2 5.3.5 1.6.3 3.1.8 4.1 1.4l-2 5.3c-.7-.4-1.7-.8-3.1-1.1-1.4-.4-2.8-.5-4.4-.5-1.5 0-2.6.3-3.4.9-.8.6-1.2 1.4-1.2 2.4 0 .9.4 1.7 1.1 2.3.7.6 1.6 1.2 2.7 1.7s2.3 1.1 3.6 1.6c1.3.6 2.5 1.2 3.6 2s2 1.8 2.7 2.9c.7 1.2 1.1 2.6 1.1 4.3 0 1.7-.3 3.2-.9 4.5-.6 1.3-1.4 2.3-2.4 3.1-1 .8-2.3 1.5-3.8 1.9-1.5.4-3.1.6-4.9.6-2.3 0-4.4-.2-6.1-.7-1.8-.4-3.1-.9-3.9-1.3l2-5.4c.3.2.8.4 1.3.6.5.2 1.2.4 1.8.6.7.2 1.4.3 2.2.5.8.1 1.5.2 2.3.2 1.9 0 3.3-.3 4.3-1 1.2-.6 1.7-1.5 1.7-2.8zm9.1-2.9c0-3.9 1-7 2.9-9.1 1.9-2.1 4.6-3.2 8.1-3.2 1.9 0 3.5.3 4.8.9 1.4.6 2.5 1.4 3.4 2.5.9 1.1 1.6 2.4 2 3.9.4 1.5.7 3.2.7 5 0 3.9-1 7-2.9 9.1-1.9 2.1-4.6 3.2-8.1 3.2-1.9 0-3.5-.3-4.8-.9-1.4-.6-2.5-1.4-3.4-2.5-.9-1.1-1.6-2.4-2-3.9-.5-1.5-.7-3.2-.7-5zm6.2 0c0 1 .1 2 .3 2.8.2.9.5 1.6.8 2.3.4.7.9 1.2 1.5 1.5.6.4 1.3.5 2.2.5 1.6 0 2.8-.6 3.5-1.7.8-1.1 1.2-3 1.2-5.4 0-2.1-.4-3.9-1.1-5.2-.7-1.3-1.9-2-3.6-2-1.5 0-2.7.6-3.5 1.7-.9 1.1-1.3 2.9-1.3 5.5zm24.8-11.6v13.2c0 1.9.2 3.3.7 4.1.4.8 1.3 1.3 2.6 1.3 1.1 0 2.1-.3 2.9-1 .8-.7 1.3-1.5 1.7-2.5v-15h6v16.2c0 1.3.1 2.5.2 3.7.1 1.2.3 2.3.6 3.3h-4.6l-1.1-3.4h-.2c-.7 1.2-1.7 2.2-3 2.9-1.3.8-2.8 1.2-4.5 1.2-1.2 0-2.2-.2-3.2-.5-.9-.3-1.7-.8-2.3-1.5-.6-.7-1.1-1.7-1.4-2.9-.3-1.2-.5-2.8-.5-4.7V18.6h6.1zm31.4 5.6c-1-.3-1.8-.5-2.6-.5-1.1 0-2 .3-2.7.9-.7.6-1.2 1.3-1.5 2.2v15h-6V18.6h4.7l.7 3.1h.2c.5-1.1 1.2-2 2.1-2.7.9-.7 2-.9 3.2-.9.8 0 2.5.4 3.4.8l-1.5 5.3zm19.6 16.2c-.9.7-2.1 1.2-3.4 1.6-1.3.4-2.7.5-4.1.5-1.9 0-3.4-.3-4.7-.9-1.3-.6-2.3-1.4-3.1-2.5-.8-1.1-1.4-2.4-1.7-3.9-.4-1.5-.5-3.2-.5-5 0-3.9.9-7 2.7-9.1 1.8-2.1 4.3-3.2 7.7-3.2 1.7 0 3.1.1 4.1.4 1 .3 2 .6 2.8 1.1l-1.4 4.9c-.7-.3-1.4-.6-2.1-.8-.7-.2-1.5-.3-2.4-.3-1.7 0-2.9.6-3.8 1.7-.9 1.1-1.3 2.9-1.3 5.3 0 1 .1 1.9.3 2.7.2.8.5 1.6 1 2.2.4.6 1 1.1 1.7 1.5.7.4 1.5.5 2.4.5 1 0 1.9-.1 2.6-.4.7-.3 1.3-.6 1.9-1l1.3 4.7zm21.3-.6c-.9.7-2.2 1.4-3.8 1.9-1.6.5-3.3.8-5.1.8-3.8 0-6.5-1.1-8.2-3.3-1.7-2.2-2.6-5.2-2.6-9 0-4.1 1-7.2 2.9-9.2 1.9-2 4.7-3.1 8.2-3.1 1.2 0 2.3.2 3.4.5s2.1.8 3 1.5c.9.7 1.6 1.7 2.1 2.9s.8 2.7.8 4.5c0 .7 0 1.3-.1 2.1-.1.7-.2 1.5-.3 2.3h-14c.1 2 .6 3.4 1.5 4.4.9 1 2.4 1.5 4.4 1.5 1.3 0 2.4-.2 3.4-.6 1-.4 1.8-.8 2.3-1.2l2.1 4zm-8.7-17.1c-1.6 0-2.8.5-3.5 1.4-.8.9-1.2 2.2-1.4 3.8h8.6c.1-1.7-.1-3-.8-3.9-.5-.8-1.5-1.3-2.9-1.3zm32.9 19.1c0 3.4-.9 5.9-2.7 7.5-1.8 1.6-4.4 2.4-7.7 2.4-2.2 0-4-.2-5.3-.5-1.3-.3-2.3-.6-2.9-1l1.3-4.8c.7.3 1.5.6 2.5.8 1 .2 2.1.4 3.5.4 2.1 0 3.5-.5 4.3-1.4.8-.9 1.1-2.2 1.1-3.8V40h-.2c-1.1 1.5-3 2.2-5.8 2.2-3 0-5.2-.9-6.7-2.8s-2.2-4.8-2.2-8.7c0-4.2 1-7.3 3-9.4 2-2.1 4.9-3.2 8.6-3.2 2 0 3.8.1 5.3.4 1.5.3 2.8.6 3.8 1v22.3h.1zm-10.2-4.5c1.2 0 2.1-.3 2.7-.8.6-.5 1.1-1.3 1.5-2.4V23.7c-1-.4-2.2-.6-3.6-.6-1.6 0-2.8.6-3.6 1.7-.9 1.2-1.3 3-1.3 5.6 0 2.3.4 4 1.1 5.2.7 1.2 1.8 1.7 3.2 1.7zm27.7-13.1c-1-.3-1.8-.5-2.6-.5-1.1 0-2 .3-2.7.9-.7.6-1.2 1.3-1.5 2.2v15h-6V18.6h4.7l.7 3.1h.2c.5-1.1 1.2-2 2.1-2.7.9-.7 2-.9 3.2-.9.8 0 1.7.2 2.7.5l-.8 5.6zm2.9-4.5c1.2-.6 2.1-.8 3.8-1.1 1.7-.3 3.5-.5 5.3-.5 1.6 0 3 .2 4 .6 1 .4 1.9.9 2.6 1.7.6.7 1.1 1.6 1.3 2.6.3 1 .4 2.1.4 3.3 0 1.4 0 2.7-.1 4.1-.1 1.4-.1 2.7-.2 4.1 0 1.3 0 2.6.1 3.9.1 1.3.3 2.4.7 3.6H250l-1-3.2c-.6 1-1.5 1.8-2.6 2.5s-2.5 1-4.3 1c-1.1 0-2.1-.2-2.9-.5-.9-.3-1.6-.8-2.2-1.4-.6-.6-1.1-1.3-1.4-2.1-.3-.8-.5-1.7-.5-2.8 0-1.4.3-2.6 1-3.6s1.5-1.8 2.7-2.4c1.2-.6 2.6-1 4.3-1.3 1.7-.3 3.5-.3 5.6-.2.2-1.7.1-3-.4-3.7-.5-.8-1.5-1.1-3.1-1.1-1.2 0-2.5.1-3.8.4-1.3.3-1.9.4-2.7.8l-1.7-4.7zm7.1 17.5c1.2 0 2.2-.3 2.9-.8.7-.5 1.2-1.1 1.6-1.7v-3c-1-.1-1.9-.1-2.8 0-.9.1-1.7.2-2.3.4-.6.2-1.2.5-1.6.9-.4.4-.6.9-.6 1.5 0 .9.3 1.5.8 2 .4.5 1.1.7 2 .7zm15-18.6h4.4l.7 2.8h.2c.8-1.2 1.8-2 2.9-2.6 1.1-.6 2.4-.8 4-.8 2.9 0 5.1.9 6.6 2.8s2.2 4.8 2.2 8.9c0 2-.2 3.8-.7 5.4-.5 1.6-1.2 3-2.1 4.1-.9 1.1-2 2-3.3 2.6-1.3.6-2.8.9-4.5.9-1 0-1.8-.1-2.4-.2-.6-.1-1.2-.4-1.9-.7v9.5h-6V18.6h-.1zm10.3 4.4c-1.2 0-2.1.3-2.8.9-.7.6-1.2 1.5-1.6 2.7v9.7c.4.3.9.6 1.4.8.5.2 1.2.3 2 .3 1.7 0 3-.6 3.9-1.8.9-1.2 1.3-3.2 1.3-6.1 0-2-.3-3.6-1-4.7-.6-1.2-1.7-1.8-3.2-1.8zm28.2 18.8V28.6c0-1.9-.3-3.3-.8-4.1-.5-.8-1.5-1.3-2.9-1.3-1 0-2 .3-2.8 1-.9.7-1.4 1.6-1.7 2.7v14.8h-6V9.3h6v11.9h.2c.7-1 1.7-1.8 2.7-2.4 1.1-.6 2.5-.9 4.1-.9 1.2 0 2.2.2 3.1.5.9.3 1.7.8 2.3 1.5.6.7 1.1 1.7 1.3 2.9.2 1.2.4 2.7.4 4.5v14.5h-5.9z" fill="#000"/></svg>
|
||||
|
After Width: | Height: | Size: 4.8 KiB |
@ -1,27 +1,29 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "sourcegraph-preview",
|
||||
"displayName": "Sourcegraph - preview",
|
||||
"version": "0.0.2",
|
||||
"name": "@sourcegraph/vscode",
|
||||
"displayName": "Sourcegraph",
|
||||
"version": "2.2.1",
|
||||
"description": "Sourcegraph for VS Code",
|
||||
"publisher": "kandalatj",
|
||||
"publisher": "sourcegraph",
|
||||
"sideEffects": false,
|
||||
"license": "Apache-2.0",
|
||||
"icon": "images/logo.png",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sourcegraph/sourcegraph.git"
|
||||
"url": "https://github.com/sourcegraph/sourcegraph.git",
|
||||
"directory": "client/vscode"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/sourcegraph/sourcegraph/issues"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.61.0"
|
||||
"vscode": "^1.63.2"
|
||||
},
|
||||
"categories": [
|
||||
"Other"
|
||||
],
|
||||
"activationEvents": [
|
||||
"onCommand:sourcegraph.search",
|
||||
"onView:sourcegraph.searchSidebar",
|
||||
"onWebviewPanel:sourcegraphSearch"
|
||||
"*"
|
||||
],
|
||||
"main": "./dist/node/extension.js",
|
||||
"browser": "./dist/webworker/extension.js",
|
||||
@ -30,7 +32,36 @@
|
||||
{
|
||||
"command": "sourcegraph.search",
|
||||
"category": "Sourcegraph",
|
||||
"title": "Open Sourcegraph Search Tab"
|
||||
"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)"
|
||||
}
|
||||
],
|
||||
"viewsContainers": {
|
||||
@ -53,8 +84,13 @@
|
||||
{
|
||||
"id": "sourcegraph.files",
|
||||
"name": "Files",
|
||||
"visibility": "visible",
|
||||
"when": "sourcegraph.state == 'remote-browsing'"
|
||||
"visibility": "visible"
|
||||
},
|
||||
{
|
||||
"type": "webview",
|
||||
"id": "sourcegraph.helpSidebar",
|
||||
"name": "Help and feedback",
|
||||
"visibility": "collapsed"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -81,6 +117,39 @@
|
||||
],
|
||||
"default": "",
|
||||
"description": "The access token to query the Sourcegraph API. Create a new access token at ${SOURCEGRAPH_URL}/users/settings/tokens"
|
||||
},
|
||||
"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."
|
||||
}
|
||||
}
|
||||
},
|
||||
@ -89,21 +158,64 @@
|
||||
"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"
|
||||
},
|
||||
{
|
||||
"command": "sourcegraph.copyFileLink",
|
||||
"group": "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": {
|
||||
"eslint": "eslint --cache '**/*.[jt]s?(x)'",
|
||||
"test": "echo \"No tests exist yet\" && exit 1",
|
||||
"package": "echo \"package script not implemented yet\" && exit 1",
|
||||
"build": "webpack --mode=development --config-name extension:node --config-name extension:webworker --config-name webviews",
|
||||
"build:node": "webpack --mode=development --config-name extension:node --config-name webviews",
|
||||
"build:web": "webpack --mode=development --config-name extension:webworker --config-name webviews",
|
||||
"watch:node": "webpack --mode=development --watch --config-name extension:node --config-name webviews",
|
||||
"watch:web": "webpack --mode=development --watch --config-name extension:node --config-name webviews"
|
||||
"test": "ts-node ./tests/runTests.ts",
|
||||
"package": "ts-node ./scripts/package.ts",
|
||||
"task:gulp": "cross-env NODE_OPTIONS=\"--max_old_space_size=8192\" gulp",
|
||||
"build": "yarn task:gulp webpack",
|
||||
"build:node": "TARGET_TYPE=node yarn task:gulp webpack",
|
||||
"build:web": "TARGET_TYPE=webworker yarn task:gulp webpack",
|
||||
"watch": "yarn task:gulp watchWebpack",
|
||||
"watch:node": "NODE_ENV=development TARGET_TYPE=node yarn task:gulp watchWebpack",
|
||||
"watch:web": "NODE_ENV=development TARGET_TYPE=webworker yarn task:gulp watchWebpack"
|
||||
}
|
||||
}
|
||||
|
||||
17
client/vscode/scripts/package.ts
Normal file
17
client/vscode/scripts/package.ts
Normal file
@ -0,0 +1,17 @@
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
||||
import childProcess from 'child_process'
|
||||
import fs from 'fs'
|
||||
|
||||
const originalPackageJson = fs.readFileSync('package.json').toString()
|
||||
|
||||
try {
|
||||
// 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('yarn vsce package --yarn --allow-star-activation -o dist', { stdio: 'inherit' })
|
||||
} finally {
|
||||
fs.writeFileSync('package.json', originalPackageJson)
|
||||
}
|
||||
@ -1,11 +1,46 @@
|
||||
import { Observable, ReplaySubject } from 'rxjs'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { AuthenticatedUser, currentAuthStateQuery } from '@sourcegraph/shared/src/auth'
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
import { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import { CurrentAuthStateResult, CurrentAuthStateVariables } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
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
|
||||
tags
|
||||
url
|
||||
settingsURL
|
||||
organizations {
|
||||
nodes {
|
||||
id
|
||||
name
|
||||
displayName
|
||||
url
|
||||
settingsURL
|
||||
}
|
||||
}
|
||||
session {
|
||||
canSignOut
|
||||
}
|
||||
viewerCanAdminister
|
||||
tags
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
// Update authenticatedUser on accessToken changes
|
||||
export function observeAuthenticatedUser({
|
||||
context,
|
||||
|
||||
39
client/vscode/src/backend/blobContent.ts
Normal file
39
client/vscode/src/backend/blobContent.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import { BlobContentResult, BlobContentVariables } from '../graphql-operations'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
const blobContentQuery = gql`
|
||||
query BlobContent($repository: String!, $revision: String!, $path: String!) {
|
||||
repository(name: $repository) {
|
||||
commit(rev: $revision) {
|
||||
blob(path: $path) {
|
||||
content
|
||||
binary
|
||||
byteSize
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export interface FileContents {
|
||||
content: Uint8Array
|
||||
isBinary: boolean
|
||||
byteSize: number
|
||||
}
|
||||
|
||||
export async function getBlobContent(variables: BlobContentVariables): Promise<FileContents | undefined> {
|
||||
const result = await requestGraphQLFromVSCode<BlobContentResult, BlobContentVariables>(blobContentQuery, variables)
|
||||
|
||||
const blob = result.data?.repository?.commit?.blob
|
||||
if (blob) {
|
||||
return {
|
||||
content: new TextEncoder().encode(blob.content),
|
||||
isBinary: blob.binary,
|
||||
byteSize: blob.byteSize,
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
49
client/vscode/src/backend/eventLogger.ts
Normal file
49
client/vscode/src/backend/eventLogger.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import { EMPTY, Subject } from 'rxjs'
|
||||
import { bufferTime, catchError, concatMap } from 'rxjs/operators'
|
||||
|
||||
import { gql } from '@sourcegraph/http-client/src/graphql/graphql'
|
||||
import { LogEventsResult, LogEventsVariables, Event } from '@sourcegraph/web/src/graphql-operations'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
// Log events in batches.
|
||||
const events = new Subject<Event>()
|
||||
|
||||
events
|
||||
.pipe(
|
||||
bufferTime(1000),
|
||||
concatMap(events => {
|
||||
if (events.length > 0) {
|
||||
return requestGraphQLFromVSCode<LogEventsResult, LogEventsVariables>(logEventsMutation, {
|
||||
events,
|
||||
})
|
||||
}
|
||||
return EMPTY
|
||||
}),
|
||||
catchError(error => {
|
||||
console.error('Error logging events:', error)
|
||||
return []
|
||||
})
|
||||
)
|
||||
// eslint-disable-next-line rxjs/no-ignored-subscription
|
||||
.subscribe()
|
||||
|
||||
export const logEventsMutation = gql`
|
||||
mutation LogEvents($events: [Event!]) {
|
||||
logEvents(events: $events) {
|
||||
alwaysNil
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
/**
|
||||
* Log a raw user action (used to allow site admins on a Sourcegraph instance
|
||||
* to see a count of unique users on a daily, weekly, and monthly basis).
|
||||
*
|
||||
* When invoked on a non-Sourcegraph.com instance, this data is stored in the
|
||||
* instance's database, and not sent to Sourcegraph.com.
|
||||
*/
|
||||
|
||||
export function logEvent(eventVariable: Event): void {
|
||||
events.next(eventVariable)
|
||||
}
|
||||
26
client/vscode/src/backend/files.ts
Normal file
26
client/vscode/src/backend/files.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import { FileNamesResult, FileNamesVariables } from '../graphql-operations'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
const fileNamesQuery = gql`
|
||||
query FileNames($repository: String!, $revision: String!) {
|
||||
repository(name: $repository) {
|
||||
commit(rev: $revision) {
|
||||
fileNames
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export async function getFiles(variables: FileNamesVariables): Promise<string[]> {
|
||||
const result = await requestGraphQLFromVSCode<FileNamesResult, FileNamesVariables>(fileNamesQuery, variables)
|
||||
|
||||
if (result.data?.repository?.commit) {
|
||||
return result.data.repository.commit.fileNames
|
||||
}
|
||||
|
||||
// Debt: surface error to users.
|
||||
throw new Error(`Failed to fetch file names for ${variables.repository}@${variables.revision}`)
|
||||
}
|
||||
45
client/vscode/src/backend/instanceVersion.ts
Normal file
45
client/vscode/src/backend/instanceVersion.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
import { EventSource } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { INSTANCE_VERSION_NUMBER_KEY, LocalStorageService } from '../settings/LocalStorageService'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
/**
|
||||
* Regular instance version format: ex 3.38.2
|
||||
* Insider version format: ex 134683_2022-03-02_5188fes0101
|
||||
* This function will return the EventSource Type based
|
||||
* on the instance version
|
||||
*/
|
||||
export function initializeInstantVersionNumber(localStorageService: LocalStorageService): EventSource {
|
||||
requestGraphQLFromVSCode<SiteVersionResult>(siteVersionQuery, {})
|
||||
.then(async siteVersionResult => {
|
||||
if (siteVersionResult.data) {
|
||||
// assume instance version longer than 8 is using insider version
|
||||
const flattenVersion =
|
||||
siteVersionResult.data.site.productVersion.length > 8
|
||||
? '999999'
|
||||
: siteVersionResult.data.site.productVersion.split('.').join('')
|
||||
await localStorageService.setValue(INSTANCE_VERSION_NUMBER_KEY, flattenVersion)
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Failed to get instance version from host:', error)
|
||||
})
|
||||
const versionNumber = localStorageService.getValue(INSTANCE_VERSION_NUMBER_KEY)
|
||||
// instances below 3.38.0 does not support EventSource.IDEEXTENSION and should fallback to BACKEND source
|
||||
return versionNumber >= '3380' ? EventSource.IDEEXTENSION : EventSource.BACKEND
|
||||
}
|
||||
|
||||
const siteVersionQuery = gql`
|
||||
query {
|
||||
site {
|
||||
productVersion
|
||||
}
|
||||
}
|
||||
`
|
||||
interface SiteVersionResult {
|
||||
site: {
|
||||
productVersion: string
|
||||
}
|
||||
}
|
||||
59
client/vscode/src/backend/repositoryMetadata.ts
Normal file
59
client/vscode/src/backend/repositoryMetadata.ts
Normal file
@ -0,0 +1,59 @@
|
||||
import { gql } from '@sourcegraph/http-client'
|
||||
|
||||
import { RepositoryMetadataResult, RepositoryMetadataVariables } from '../graphql-operations'
|
||||
|
||||
import { requestGraphQLFromVSCode } from './requestGraphQl'
|
||||
|
||||
const repositoryMetadataQuery = gql`
|
||||
query RepositoryMetadata($repositoryName: String!) {
|
||||
repositoryRedirect(name: $repositoryName) {
|
||||
... on Repository {
|
||||
id
|
||||
mirrorInfo {
|
||||
cloneInProgress
|
||||
cloneProgress
|
||||
cloned
|
||||
}
|
||||
commit(rev: "") {
|
||||
oid
|
||||
abbreviatedOID
|
||||
tree(path: "") {
|
||||
url
|
||||
}
|
||||
}
|
||||
defaultBranch {
|
||||
abbrevName
|
||||
}
|
||||
}
|
||||
... on Redirect {
|
||||
url
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export interface RepositoryMetadata {
|
||||
repositoryId: string
|
||||
defaultOID?: string
|
||||
defaultAbbreviatedOID?: string
|
||||
defaultBranch?: string
|
||||
}
|
||||
|
||||
export async function getRepositoryMetadata(
|
||||
variables: RepositoryMetadataVariables
|
||||
): Promise<RepositoryMetadata | undefined> {
|
||||
const result = await requestGraphQLFromVSCode<RepositoryMetadataResult, RepositoryMetadataVariables>(
|
||||
repositoryMetadataQuery,
|
||||
variables
|
||||
)
|
||||
if (result.data?.repositoryRedirect?.__typename === 'Repository') {
|
||||
return {
|
||||
repositoryId: result.data.repositoryRedirect.id,
|
||||
defaultOID: result.data.repositoryRedirect.commit?.oid,
|
||||
defaultAbbreviatedOID: result.data.repositoryRedirect.commit?.abbreviatedOID,
|
||||
defaultBranch: result.data.repositoryRedirect.defaultBranch?.abbrevName,
|
||||
}
|
||||
}
|
||||
// v1 Debt: surface error to user.
|
||||
return undefined
|
||||
}
|
||||
@ -2,7 +2,7 @@ import { asError } from '@sourcegraph/common'
|
||||
import { checkOk, GraphQLResult, GRAPHQL_URI, isHTTPAuthError } from '@sourcegraph/http-client'
|
||||
|
||||
import { accessTokenSetting, handleAccessTokenError } from '../settings/accessTokenSetting'
|
||||
import { endpointSetting } from '../settings/endpointSetting'
|
||||
import { endpointSetting, endpointRequestHeadersSetting } from '../settings/endpointSetting'
|
||||
|
||||
let invalidated = false
|
||||
|
||||
@ -16,7 +16,8 @@ export function invalidateClient(): void {
|
||||
export const requestGraphQLFromVSCode = async <R, V = object>(
|
||||
request: string,
|
||||
variables: V,
|
||||
overrideAccessToken?: string
|
||||
overrideAccessToken?: string,
|
||||
overrideSourcegraphURL?: string
|
||||
): Promise<GraphQLResult<R>> => {
|
||||
if (invalidated) {
|
||||
throw new Error(
|
||||
@ -26,9 +27,11 @@ export const requestGraphQLFromVSCode = async <R, V = object>(
|
||||
|
||||
const nameMatch = request.match(/^\s*(?:query|mutation)\s+(\w+)/)
|
||||
const apiURL = `${GRAPHQL_URI}${nameMatch ? '?' + nameMatch[1] : ''}`
|
||||
|
||||
const headers: HeadersInit = []
|
||||
const sourcegraphURL = endpointSetting()
|
||||
// load custom headers from user setting if any
|
||||
const customHeaders = endpointRequestHeadersSetting()
|
||||
// return empty array if no custom header is provided in configuration
|
||||
const headers: HeadersInit = Object.entries(customHeaders)
|
||||
const sourcegraphURL = overrideSourcegraphURL || endpointSetting()
|
||||
const accessToken = accessTokenSetting()
|
||||
|
||||
// Add Access Token to request header
|
||||
|
||||
48
client/vscode/src/backend/searchContexts.ts
Normal file
48
client/vscode/src/backend/searchContexts.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import { from, Observable, of } from 'rxjs'
|
||||
import { catchError } from 'rxjs/operators'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { GraphQLResult } from '@sourcegraph/http-client'
|
||||
import { getAvailableSearchContextSpecOrDefault } from '@sourcegraph/search'
|
||||
|
||||
import { LocalStorageService, SELECTED_SEARCH_CONTEXT_SPEC_KEY } from '../settings/LocalStorageService'
|
||||
import { 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 defaultSpec = 'global'
|
||||
|
||||
const subscription = getAvailableSearchContextSpecOrDefault({
|
||||
spec: initialSearchContextSpec || defaultSpec,
|
||||
defaultSpec,
|
||||
platformContext: {
|
||||
requestGraphQL: ({ request, variables }) =>
|
||||
from(requestGraphQLFromVSCode(request, variables)) as Observable<GraphQLResult<any>>,
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
catchError(error => {
|
||||
console.error('Error validating search context spec:', error)
|
||||
return of(defaultSpec)
|
||||
})
|
||||
)
|
||||
.subscribe(availableSearchContextSpecOrDefault => {
|
||||
stateMachine.emit({ type: 'set_selected_search_context_spec', spec: availableSearchContextSpecOrDefault })
|
||||
})
|
||||
|
||||
context.subscriptions.push({
|
||||
dispose: () => subscription.unsubscribe(),
|
||||
})
|
||||
}
|
||||
@ -2,8 +2,9 @@ import { Observable, of, ReplaySubject, Subject } from 'rxjs'
|
||||
import { catchError, map, switchMap, throttleTime } from 'rxjs/operators'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { createAggregateError } from '@sourcegraph/common'
|
||||
import { createAggregateError, isErrorLike } from '@sourcegraph/common'
|
||||
import { viewerSettingsQuery } from '@sourcegraph/shared/src/backend/settings'
|
||||
import { getEnabledExtensionsForSubject } from '@sourcegraph/shared/src/extensions/extensions'
|
||||
import { ViewerSettingsResult, ViewerSettingsVariables } from '@sourcegraph/shared/src/graphql-operations'
|
||||
import { ISettingsCascade } from '@sourcegraph/shared/src/schema'
|
||||
import {
|
||||
@ -43,6 +44,7 @@ export function initializeSourcegraphSettings({
|
||||
|
||||
return gqlToCascade(data?.viewerSettings as ISettingsCascade)
|
||||
}),
|
||||
map(settingsCascade => stripNonDefaultExtensions(settingsCascade)),
|
||||
catchError(() => of(EMPTY_SETTINGS_CASCADE))
|
||||
)
|
||||
.subscribe(settingsCascade => {
|
||||
@ -60,3 +62,19 @@ export function initializeSourcegraphSettings({
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutates settings cascade to remove all non-default Sourcegraph extensions.
|
||||
* Remove when non-programming language extension features are implemented
|
||||
* for the VS Code extension.
|
||||
*/
|
||||
function stripNonDefaultExtensions(settingsCascade: SettingsCascadeOrError): SettingsCascadeOrError {
|
||||
if (!settingsCascade.final || isErrorLike(settingsCascade.final)) {
|
||||
return settingsCascade
|
||||
}
|
||||
|
||||
const defaultExtensions = getEnabledExtensionsForSubject(settingsCascade, 'DefaultSettings') || {}
|
||||
settingsCascade.final.extensions = defaultExtensions
|
||||
|
||||
return settingsCascade
|
||||
}
|
||||
|
||||
63
client/vscode/src/backend/streamSearch.ts
Normal file
63
client/vscode/src/backend/streamSearch.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { of, Subscription } from 'rxjs'
|
||||
import { throttleTime } from 'rxjs/operators'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { appendContextFilter } from '@sourcegraph/shared/src/search/query/transformer'
|
||||
import { aggregateStreamingSearch } from '@sourcegraph/shared/src/search/stream'
|
||||
|
||||
import { ExtensionCoreAPI } from '../contract'
|
||||
import { VSCEStateMachine } from '../state'
|
||||
import { focusSearchPanel } from '../webview/commands'
|
||||
|
||||
export function createStreamSearch({
|
||||
context,
|
||||
stateMachine,
|
||||
sourcegraphURL,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
stateMachine: VSCEStateMachine
|
||||
sourcegraphURL: string
|
||||
}): ExtensionCoreAPI['streamSearch'] {
|
||||
// Ensure only one search is active at a time
|
||||
let previousSearchSubscription: Subscription | null
|
||||
|
||||
context.subscriptions.push({
|
||||
dispose: () => {
|
||||
previousSearchSubscription?.unsubscribe()
|
||||
},
|
||||
})
|
||||
|
||||
return function streamSearch(query, options) {
|
||||
previousSearchSubscription?.unsubscribe()
|
||||
|
||||
stateMachine.emit({
|
||||
type: 'submit_search_query',
|
||||
submittedSearchQueryState: {
|
||||
queryState: { query },
|
||||
searchCaseSensitivity: options.caseSensitive,
|
||||
searchPatternType: options.patternType,
|
||||
},
|
||||
})
|
||||
// Focus search panel if not already focused
|
||||
// (in case e.g. user initiates search from search sidebar when panel is hidden).
|
||||
focusSearchPanel()
|
||||
|
||||
previousSearchSubscription = aggregateStreamingSearch(
|
||||
of(appendContextFilter(query, stateMachine.state.context.selectedSearchContextSpec)),
|
||||
{
|
||||
...options,
|
||||
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 })
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,72 @@
|
||||
import * 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, parseRepoURI } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
import { SearchSidebarAPI } from '../contract'
|
||||
import { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
|
||||
export class SourcegraphDefinitionProvider implements vscode.DefinitionProvider {
|
||||
constructor(
|
||||
private readonly fs: SourcegraphFileSystemProvider,
|
||||
private readonly sourcegraphExtensionHostAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
) {}
|
||||
public async provideDefinition(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<vscode.Definition | undefined> {
|
||||
const uri = this.fs.sourcegraphUri(document.uri)
|
||||
const extensionHostUri = makeRepoURI({
|
||||
repoName: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
filePath: uri.path,
|
||||
})
|
||||
|
||||
const definitions = wrapRemoteObservable(
|
||||
this.sourcegraphExtensionHostAPI.getDefinition({
|
||||
textDocument: {
|
||||
uri: extensionHostUri,
|
||||
},
|
||||
position: {
|
||||
line: position.line,
|
||||
character: position.character,
|
||||
},
|
||||
})
|
||||
)
|
||||
.pipe(
|
||||
finallyReleaseProxy(),
|
||||
switchMap(({ isLoading, result }) => {
|
||||
if (isLoading) {
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
const locations = result.map(location => {
|
||||
const uri = parseRepoURI(location.uri)
|
||||
|
||||
return this.fs.toVscodeLocation({
|
||||
resource: {
|
||||
path: uri.filePath ?? '',
|
||||
repositoryName: uri.repoName,
|
||||
revision: uri.commitID ?? uri.revision ?? '',
|
||||
},
|
||||
range: location.range,
|
||||
})
|
||||
})
|
||||
|
||||
return of(locations)
|
||||
}),
|
||||
first()
|
||||
)
|
||||
.toPromise()
|
||||
|
||||
token.onCancellationRequested(() => {
|
||||
// Debt: manually create promise so we can cancel request.
|
||||
})
|
||||
|
||||
return definitions
|
||||
}
|
||||
}
|
||||
76
client/vscode/src/code-intel/SourcegraphHoverProvider.ts
Normal file
76
client/vscode/src/code-intel/SourcegraphHoverProvider.ts
Normal file
@ -0,0 +1,76 @@
|
||||
import * 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 { SearchSidebarAPI } from '../contract'
|
||||
import { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
|
||||
export class SourcegraphHoverProvider implements vscode.HoverProvider {
|
||||
constructor(
|
||||
private readonly fs: SourcegraphFileSystemProvider,
|
||||
private readonly sourcegraphExtensionHostAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
) {}
|
||||
public async provideHover(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<vscode.Hover | undefined> {
|
||||
const uri = this.fs.sourcegraphUri(document.uri)
|
||||
const extensionHostUri = makeRepoURI({
|
||||
repoName: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
filePath: uri.path,
|
||||
})
|
||||
|
||||
const definitions = wrapRemoteObservable(
|
||||
this.sourcegraphExtensionHostAPI.getHover({
|
||||
textDocument: {
|
||||
uri: extensionHostUri,
|
||||
},
|
||||
position: {
|
||||
line: position.line,
|
||||
character: position.character,
|
||||
},
|
||||
})
|
||||
)
|
||||
.pipe(
|
||||
finallyReleaseProxy(),
|
||||
switchMap(({ isLoading, result }) => {
|
||||
if (isLoading) {
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
const prefix =
|
||||
result?.aggregatedBadges?.reduce((prefix, badge) => {
|
||||
if (badge.linkURL) {
|
||||
return prefix + `[${badge.text}](${badge.linkURL})\n`
|
||||
}
|
||||
return prefix + `${badge.text}\n`
|
||||
}, ` `) || ''
|
||||
|
||||
return of<vscode.Hover>({
|
||||
contents: [
|
||||
...(result?.contents ?? []).map(
|
||||
content => new vscode.MarkdownString(prefix + content.value)
|
||||
),
|
||||
],
|
||||
})
|
||||
}),
|
||||
first()
|
||||
)
|
||||
.toPromise()
|
||||
|
||||
token.onCancellationRequested(() => {
|
||||
// Debt: manually create promise so we can cancel request.
|
||||
})
|
||||
|
||||
return definitions
|
||||
}
|
||||
}
|
||||
|
||||
const sourcegraphLogoDataURI =
|
||||
'data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE0IiB2aWV3Qm94PSIwIDAgNTIgNTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTMwLjggNTEuOGMtMi44LjUtNS41LTEuMy02LTQuMUwxNy4yIDYuMmMtLjUtMi44IDEuMy01LjUgNC4xLTZzNS41IDEuMyA2IDQuMWw3LjYgNDEuNWMuNSAyLjgtMS40IDUuNS00LjEgNnoiIGZpbGw9IiNGRjU1NDMiLz48cGF0aCBkPSJNMTAuOSA0NC43QzkuMSA0NSA3LjMgNDQuNCA2IDQzYy0xLjgtMi4yLTEuNi01LjQuNi03LjJMMzguNyA4LjVjMi4yLTEuOCA1LjQtMS42IDcuMi42IDEuOCAyLjIgMS42IDUuNC0uNiA3LjJsLTMyIDI3LjNjLS43LjYtMS42IDEtMi40IDEuMXoiIGZpbGw9IiNBMTEyRkYiLz48cGF0aCBkPSJNNDYuOCAzOC4xYy0uOS4yLTEuOC4xLTIuNi0uMkw0LjQgMjMuOGMtMi43LTEtNC4xLTMuOS0zLjEtNi42IDEtMi43IDMuOS00LjEgNi42LTMuMWwzOS43IDE0LjFjMi43IDEgNC4xIDMuOSAzLjEgNi42LS42IDEuOC0yLjIgMy0zLjkgMy4zeiIgZmlsbD0iIzAwQ0JFQyIvPjwvc3ZnPg=='
|
||||
78
client/vscode/src/code-intel/SourcegraphReferenceProvider.ts
Normal file
78
client/vscode/src/code-intel/SourcegraphReferenceProvider.ts
Normal file
@ -0,0 +1,78 @@
|
||||
import * as Comlink from 'comlink'
|
||||
import { EMPTY, of } from 'rxjs'
|
||||
import { debounceTime, first, switchMap } from 'rxjs/operators'
|
||||
import * 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 { SearchSidebarAPI } from '../contract'
|
||||
import { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
|
||||
export class SourcegraphReferenceProvider implements vscode.ReferenceProvider {
|
||||
constructor(
|
||||
private readonly fs: SourcegraphFileSystemProvider,
|
||||
private readonly sourcegraphExtensionHostAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
) {}
|
||||
public async provideReferences(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
referenceContext: vscode.ReferenceContext,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<vscode.Location[] | undefined> {
|
||||
const uri = this.fs.sourcegraphUri(document.uri)
|
||||
const extensionHostUri = makeRepoURI({
|
||||
repoName: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
filePath: uri.path,
|
||||
})
|
||||
|
||||
const definitions = wrapRemoteObservable(
|
||||
this.sourcegraphExtensionHostAPI.getReferences(
|
||||
{
|
||||
textDocument: {
|
||||
uri: extensionHostUri,
|
||||
},
|
||||
position: {
|
||||
line: position.line,
|
||||
character: position.character,
|
||||
},
|
||||
},
|
||||
referenceContext
|
||||
)
|
||||
)
|
||||
.pipe(
|
||||
finallyReleaseProxy(),
|
||||
switchMap(({ isLoading, result }) => {
|
||||
if (isLoading) {
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
const locations = result.map(location => {
|
||||
// Create a sourcegraph URI from this git URI (so we need both fromGitURI and toGitURI.)`
|
||||
const uri = parseRepoURI(location.uri)
|
||||
|
||||
return this.fs.toVscodeLocation({
|
||||
resource: {
|
||||
path: uri.filePath ?? '',
|
||||
repositoryName: uri.repoName,
|
||||
revision: uri.commitID ?? uri.revision ?? '',
|
||||
},
|
||||
range: location.range,
|
||||
})
|
||||
})
|
||||
|
||||
return of(locations)
|
||||
}),
|
||||
debounceTime(1000),
|
||||
first()
|
||||
)
|
||||
.toPromise()
|
||||
|
||||
token.onCancellationRequested(() => {
|
||||
// Debt: manually create promise so we can cancel request.
|
||||
})
|
||||
|
||||
return definitions
|
||||
}
|
||||
}
|
||||
77
client/vscode/src/code-intel/initialize.ts
Normal file
77
client/vscode/src/code-intel/initialize.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import * as Comlink from 'comlink'
|
||||
import vscode from 'vscode'
|
||||
|
||||
import { makeRepoURI } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
import { SearchSidebarAPI } from '../contract'
|
||||
import { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
|
||||
import { toSourcegraphLanguage } from './languages'
|
||||
import { SourcegraphDefinitionProvider } from './SourcegraphDefinitionProvider'
|
||||
import { SourcegraphHoverProvider } from './SourcegraphHoverProvider'
|
||||
import { SourcegraphReferenceProvider } from './SourcegraphReferenceProvider'
|
||||
|
||||
export function initializeCodeIntel({
|
||||
context,
|
||||
fs,
|
||||
searchSidebarAPI,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
fs: SourcegraphFileSystemProvider
|
||||
searchSidebarAPI: Comlink.Remote<SearchSidebarAPI>
|
||||
}): void {
|
||||
// Register language-related features (they depend on Sourcegraph extensions).
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerDefinitionProvider(
|
||||
{ scheme: 'sourcegraph' },
|
||||
new SourcegraphDefinitionProvider(fs, searchSidebarAPI)
|
||||
)
|
||||
)
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerReferenceProvider(
|
||||
{ scheme: 'sourcegraph' },
|
||||
new SourcegraphReferenceProvider(fs, searchSidebarAPI)
|
||||
)
|
||||
)
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerHoverProvider(
|
||||
{ scheme: 'sourcegraph' },
|
||||
new SourcegraphHoverProvider(fs, searchSidebarAPI)
|
||||
)
|
||||
)
|
||||
|
||||
// Debt: remove closed editors/documents
|
||||
context.subscriptions.push(
|
||||
vscode.window.onDidChangeActiveTextEditor(editor => {
|
||||
// TODO store previously active editor -> SG viewer so we can remove on change
|
||||
if (editor?.document.uri.scheme === 'sourcegraph') {
|
||||
const text = editor.document.getText()
|
||||
const sourcegraphUri = fs.sourcegraphUri(editor.document.uri)
|
||||
const languageId = toSourcegraphLanguage(editor.document.languageId)
|
||||
|
||||
const extensionHostUri = makeRepoURI({
|
||||
repoName: sourcegraphUri.repositoryName,
|
||||
revision: sourcegraphUri.revision,
|
||||
filePath: sourcegraphUri.path,
|
||||
})
|
||||
|
||||
// We'll use the viewerId return value to remove viewer, get/set text decorations.
|
||||
searchSidebarAPI
|
||||
.addTextDocumentIfNotExists({
|
||||
text,
|
||||
uri: extensionHostUri,
|
||||
languageId,
|
||||
})
|
||||
.then(() =>
|
||||
searchSidebarAPI.addViewerIfNotExists({
|
||||
type: 'CodeEditor',
|
||||
resource: extensionHostUri,
|
||||
selections: [],
|
||||
isActive: true,
|
||||
})
|
||||
)
|
||||
.catch(error => console.error(error))
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
14
client/vscode/src/code-intel/languages.ts
Normal file
14
client/vscode/src/code-intel/languages.ts
Normal file
@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Converts VS Code language ID to Sourcegraph-compatible language ID
|
||||
* if necessary (e.g. "typescriptreact" -> "typescript")
|
||||
*/
|
||||
export function toSourcegraphLanguage(vscodeLanguageID: string): string {
|
||||
if (vscodeLanugageIDReplacements[vscodeLanguageID]) {
|
||||
return vscodeLanugageIDReplacements[vscodeLanguageID]!
|
||||
}
|
||||
return vscodeLanguageID
|
||||
}
|
||||
|
||||
const vscodeLanugageIDReplacements: Record<string, string | undefined> = {
|
||||
typescriptreact: 'typescript',
|
||||
}
|
||||
10
client/vscode/src/code-intel/location.ts
Normal file
10
client/vscode/src/code-intel/location.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import { Range } from '@sourcegraph/extension-api-types'
|
||||
|
||||
export interface LocationNode {
|
||||
resource: {
|
||||
path: string
|
||||
repositoryName: string
|
||||
revision: string
|
||||
}
|
||||
range?: Range
|
||||
}
|
||||
@ -1,35 +1,83 @@
|
||||
import { GraphQLResult } from '@sourcegraph/http-client'
|
||||
import { FlatExtensionHostAPI } from '@sourcegraph/shared/src/api/contract'
|
||||
import { ProxySubscribable } from '@sourcegraph/shared/src/api/extension/api/common'
|
||||
import { ViewerData, ViewerId } from '@sourcegraph/shared/src/api/viewerTypes'
|
||||
import { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import { EventSource } from '@sourcegraph/shared/src/graphql-operations'
|
||||
import { SearchMatch, StreamSearchOptions } from '@sourcegraph/shared/src/search/stream'
|
||||
import { SettingsCascadeOrError } from '@sourcegraph/shared/src/settings/settings'
|
||||
import { Event } from '@sourcegraph/web/src/graphql-operations'
|
||||
|
||||
import { VSCEState, VSCEStateMachine } from './state'
|
||||
import { 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) => Promise<GraphQLResult<any>>
|
||||
requestGraphQL: (
|
||||
request: string,
|
||||
variables: any,
|
||||
overrideAccessToken?: string,
|
||||
overrideSourcegraphURL?: string
|
||||
) => Promise<GraphQLResult<any>>
|
||||
observeSourcegraphSettings: () => ProxySubscribable<SettingsCascadeOrError>
|
||||
getAuthenticatedUser: () => ProxySubscribable<AuthenticatedUser | null>
|
||||
getInstanceURL: () => ProxySubscribable<string>
|
||||
setAccessToken: (accessToken: string) => void
|
||||
setEndpointUri: (uri: string) => void
|
||||
/**
|
||||
* Observe search box query state.
|
||||
* Used to send current query from panel to sidebar.
|
||||
*
|
||||
* v1 Debt: Transient query state isn't stored in state machine for performance
|
||||
* as it would lead to re-rendering the whole search panel on each keystroke.
|
||||
* Implement selector system w/ key path for state machine. Alternatively,
|
||||
* aggressively memoize top-level "View" components (i.e. don't just take whole state as prop).
|
||||
*/
|
||||
observePanelQueryState: () => ProxySubscribable<VSCEQueryState>
|
||||
|
||||
observeState: () => ProxySubscribable<VSCEState>
|
||||
emit: VSCEStateMachine['emit']
|
||||
|
||||
/** Opens a remote file given a serialized SourcegraphUri */
|
||||
openSourcegraphFile: (uri: string) => void
|
||||
openLink: (uri: string) => void
|
||||
copyLink: (uri: string) => void
|
||||
reloadWindow: () => void
|
||||
focusSearchPanel: () => void
|
||||
|
||||
/**
|
||||
* Cancels previous search when called.
|
||||
*/
|
||||
streamSearch: (query: string, options: StreamSearchOptions) => void
|
||||
fetchStreamSuggestions: (query: string, sourcegraphURL: string) => ProxySubscribable<SearchMatch[]>
|
||||
setSelectedSearchContextSpec: (spec: string) => void
|
||||
/**
|
||||
* Used to send current query from panel to sidebar.
|
||||
*/
|
||||
setSidebarQueryState: (queryState: VSCEQueryState) => void
|
||||
|
||||
getLocalStorageItem: (key: string) => string
|
||||
setLocalStorageItem: (key: string, value: string) => Promise<boolean>
|
||||
|
||||
// For Telemetry Service
|
||||
logEvents: (variables: Event) => void
|
||||
|
||||
// Get EventSource Type to use based on instance version
|
||||
getEventSource: EventSource
|
||||
}
|
||||
|
||||
export interface SearchPanelAPI {
|
||||
// TODO remove once other methods are implemented
|
||||
ping: () => ProxySubscribable<'pong'>
|
||||
|
||||
focusSearchBox: () => void
|
||||
}
|
||||
|
||||
export interface SearchSidebarAPI extends Pick<FlatExtensionHostAPI, 'addTextDocumentIfNotExists'> {
|
||||
// TODO remove once other methods are implemented
|
||||
export interface SearchSidebarAPI
|
||||
extends Pick<FlatExtensionHostAPI, 'addTextDocumentIfNotExists' | 'getDefinition' | 'getHover' | 'getReferences'> {
|
||||
ping: () => ProxySubscribable<'pong'>
|
||||
// TODO: ExtensionHostAPI methods
|
||||
|
||||
addViewerIfNotExists: (viewer: ViewerData) => Promise<ViewerId>
|
||||
}
|
||||
|
||||
export interface HelpSidebarAPI {}
|
||||
|
||||
@ -1,18 +1,33 @@
|
||||
import 'cross-fetch/polyfill'
|
||||
|
||||
import { of, ReplaySubject } from 'rxjs'
|
||||
import * as vscode from 'vscode'
|
||||
import vscode, { env } from 'vscode'
|
||||
|
||||
import { proxySubscribable } from '@sourcegraph/shared/src/api/extension/api/common'
|
||||
import { fetchStreamSuggestions } from '@sourcegraph/shared/src/search/suggestions'
|
||||
|
||||
import { observeAuthenticatedUser } from './backend/authenticatedUser'
|
||||
import { logEvent } from './backend/eventLogger'
|
||||
import { initializeInstantVersionNumber } from './backend/instanceVersion'
|
||||
import { requestGraphQLFromVSCode } from './backend/requestGraphQl'
|
||||
import { initializeSearchContexts } from './backend/searchContexts'
|
||||
import { initializeSourcegraphSettings } from './backend/sourcegraphSettings'
|
||||
import { createStreamSearch } from './backend/streamSearch'
|
||||
import { ExtensionCoreAPI } from './contract'
|
||||
import { updateAccessTokenSetting } from './settings/accessTokenSetting'
|
||||
import { endpointSetting } from './settings/endpointSetting'
|
||||
import { openSourcegraphUriCommand } from './file-system/commands'
|
||||
import { initializeSourcegraphFileSystem } from './file-system/initialize'
|
||||
import { SourcegraphUri } from './file-system/SourcegraphUri'
|
||||
import { Event } from './graphql-operations'
|
||||
import { initializeCodeSharingCommands } from './link-commands/initialize'
|
||||
import polyfillEventSource from './polyfills/eventSource'
|
||||
import { accessTokenSetting, updateAccessTokenSetting } from './settings/accessTokenSetting'
|
||||
import { displayInstanceVersionWarnings } from './settings/displayWarnings'
|
||||
import { endpointRequestHeadersSetting, endpointSetting, updateEndpointSetting } from './settings/endpointSetting'
|
||||
import { invalidateContextOnSettingsChange } from './settings/invalidation'
|
||||
import { createVSCEStateMachine } from './state'
|
||||
import { registerWebviews } from './webview/commands'
|
||||
import { LocalStorageService, SELECTED_SEARCH_CONTEXT_SPEC_KEY } from './settings/LocalStorageService'
|
||||
import { watchUninstall } from './settings/uninstall'
|
||||
import { createVSCEStateMachine, VSCEQueryState } from './state'
|
||||
import { focusSearchPanel, registerWebviews } from './webview/commands'
|
||||
|
||||
// Sourcegraph VS Code extension architecture
|
||||
// -----
|
||||
@ -45,32 +60,51 @@ import { registerWebviews } from './webview/commands'
|
||||
// VS Code extension (that's why it exists, after all).
|
||||
|
||||
export function activate(context: vscode.ExtensionContext): void {
|
||||
const stateMachine = createVSCEStateMachine()
|
||||
|
||||
const localStorageService = new LocalStorageService(context.globalState)
|
||||
const stateMachine = createVSCEStateMachine({ localStorageService })
|
||||
invalidateContextOnSettingsChange({ context, stateMachine })
|
||||
initializeSearchContexts({ localStorageService, stateMachine, context })
|
||||
const eventSourceType = initializeInstantVersionNumber(localStorageService)
|
||||
const sourcegraphSettings = initializeSourcegraphSettings({ context })
|
||||
const authenticatedUser = observeAuthenticatedUser({ context })
|
||||
const initialInstanceURL = endpointSetting()
|
||||
|
||||
// Add state to VS Code context to be used in context keys.
|
||||
// Used e.g. by file tree view to only be visible in `remote-browsing` state.
|
||||
const subscription = stateMachine.observeState().subscribe(state => {
|
||||
vscode.commands.executeCommand('setContext', 'sourcegraph.state', state.status).then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
})
|
||||
context.subscriptions.push({
|
||||
dispose: () => subscription.unsubscribe(),
|
||||
})
|
||||
|
||||
// Sets global `EventSource` for Node, which is required for streaming search.
|
||||
// Used for VS Code web as well to be able to add Authorization header.
|
||||
const initialAccessToken = accessTokenSetting()
|
||||
// Add custom headers to `EventSource` Authorization header when provided
|
||||
const customHeaders = endpointRequestHeadersSetting()
|
||||
polyfillEventSource(initialAccessToken ? { Authorization: `token ${initialAccessToken}`, ...customHeaders } : {})
|
||||
// Update `EventSource` Authorization header on access token / headers change.
|
||||
context.subscriptions.push(
|
||||
vscode.workspace.onDidChangeConfiguration(config => {
|
||||
if (
|
||||
config.affectsConfiguration('sourcegraph.accessToken') ||
|
||||
config.affectsConfiguration('sourcegraph.requestHeaders')
|
||||
) {
|
||||
const newAccessToken = accessTokenSetting()
|
||||
const newCustomHeaders = endpointRequestHeadersSetting()
|
||||
polyfillEventSource(
|
||||
newAccessToken ? { Authorization: `token ${newAccessToken}`, ...newCustomHeaders } : {}
|
||||
)
|
||||
}
|
||||
})
|
||||
)
|
||||
// For search panel webview to signal that it is ready for messages.
|
||||
// Replay subject with large buffer size just in case panels are opened in quick succession.
|
||||
const initializedPanelIDs = new ReplaySubject<string>(7)
|
||||
|
||||
// Used to observe search box query state from sidebar
|
||||
const sidebarQueryStates = new ReplaySubject<VSCEQueryState>(1)
|
||||
|
||||
const { fs } = initializeSourcegraphFileSystem({ context, initialInstanceURL })
|
||||
// Use api endpoint for stream search
|
||||
const streamSearch = createStreamSearch({ context, stateMachine, sourcegraphURL: `${initialInstanceURL}/.api` })
|
||||
|
||||
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),
|
||||
@ -78,14 +112,38 @@ export function activate(context: vscode.ExtensionContext): void {
|
||||
// `useObservable` hook. Add `usePromise`s hook to fix.
|
||||
getAuthenticatedUser: () => proxySubscribable(authenticatedUser),
|
||||
getInstanceURL: () => proxySubscribable(of(initialInstanceURL)),
|
||||
openLink: async uri => {
|
||||
await vscode.env.openExternal(vscode.Uri.parse(uri))
|
||||
},
|
||||
openSourcegraphFile: (uri: string) => openSourcegraphUriCommand(fs, SourcegraphUri.parse(uri)),
|
||||
openLink: (uri: string) => vscode.env.openExternal(vscode.Uri.parse(uri)),
|
||||
copyLink: (uri: string) =>
|
||||
env.clipboard.writeText(uri).then(() => vscode.window.showInformationMessage('Link Copied!')),
|
||||
setAccessToken: accessToken => updateAccessTokenSetting(accessToken),
|
||||
setEndpointUri: uri => updateEndpointSetting(uri),
|
||||
reloadWindow: () => vscode.commands.executeCommand('workbench.action.reloadWindow'),
|
||||
focusSearchPanel,
|
||||
streamSearch,
|
||||
fetchStreamSuggestions: (query, sourcegraphURL) =>
|
||||
proxySubscribable(fetchStreamSuggestions(query, sourcegraphURL)),
|
||||
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,
|
||||
}
|
||||
|
||||
registerWebviews({ context, extensionCoreAPI, initializedPanelIDs, sourcegraphSettings })
|
||||
// TODO: registerCodeSharingCommands()
|
||||
// TODO: registerCodeIntel()
|
||||
// Also initializes code intel.
|
||||
registerWebviews({
|
||||
context,
|
||||
extensionCoreAPI,
|
||||
initializedPanelIDs,
|
||||
sourcegraphSettings,
|
||||
fs,
|
||||
instanceURL: initialInstanceURL,
|
||||
})
|
||||
initializeCodeSharingCommands(context, eventSourceType, localStorageService)
|
||||
displayInstanceVersionWarnings(localStorageService)
|
||||
watchUninstall(eventSourceType, localStorageService)
|
||||
}
|
||||
|
||||
114
client/vscode/src/file-system/FileTree.ts
Normal file
114
client/vscode/src/file-system/FileTree.ts
Normal file
@ -0,0 +1,114 @@
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
/**
|
||||
* Helper class to represent a flat list of relative file paths (type `string[]`) as a hierarchical file tree.
|
||||
*/
|
||||
export class FileTree {
|
||||
constructor(public readonly uri: SourcegraphUri, public readonly files: string[]) {
|
||||
files.sort()
|
||||
}
|
||||
|
||||
public toString(): string {
|
||||
return `FileTree(${this.uri.uri}, files.length=${this.files.length})`
|
||||
}
|
||||
|
||||
public directChildren(directory: string): string[] {
|
||||
return this.directChildrenInternal(directory, true)
|
||||
}
|
||||
|
||||
private directChildrenInternal(directory: string, allowRecursion: boolean): string[] {
|
||||
const depth = this.depth(directory)
|
||||
const directFiles = new Set<string>()
|
||||
const directDirectories = new Set<string>()
|
||||
const isRoot = directory === ''
|
||||
if (!isRoot && !directory.endsWith('/')) {
|
||||
directory = directory + '/'
|
||||
}
|
||||
let index = this.binarySearchDirectoryStart(directory)
|
||||
while (index < this.files.length) {
|
||||
const startIndex = index
|
||||
const file = this.files[index]
|
||||
if (file === '') {
|
||||
index++
|
||||
continue
|
||||
}
|
||||
if (file.startsWith(directory)) {
|
||||
const fileDepth = this.depth(file)
|
||||
const isFile = isRoot ? fileDepth === 0 : fileDepth === depth + 1
|
||||
let path = isFile ? file : file.slice(0, file.indexOf('/', directory.length))
|
||||
let nestedChildren = allowRecursion && !isFile ? this.directChildrenInternal(path, false) : []
|
||||
while (allowRecursion && nestedChildren.length === 1) {
|
||||
const child = SourcegraphUri.parse(nestedChildren[0])
|
||||
if (child.isDirectory()) {
|
||||
path = child.path || ''
|
||||
nestedChildren = this.directChildrenInternal(path, false)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
const uri = SourcegraphUri.fromParts(this.uri.host, this.uri.repositoryName, {
|
||||
revision: this.uri.revision,
|
||||
path,
|
||||
isDirectory: !isFile,
|
||||
}).uri
|
||||
if (isFile) {
|
||||
directFiles.add(uri)
|
||||
} else {
|
||||
index = this.binarySearchDirectoryEnd(path + '/', index + 1)
|
||||
directDirectories.add(uri)
|
||||
}
|
||||
}
|
||||
if (index === startIndex) {
|
||||
index++
|
||||
}
|
||||
}
|
||||
return [...directDirectories, ...directFiles]
|
||||
}
|
||||
|
||||
private binarySearchDirectoryStart(directory: string): number {
|
||||
if (directory === '') {
|
||||
return 0
|
||||
}
|
||||
return this.binarySearch(
|
||||
{ low: 0, high: this.files.length },
|
||||
midpoint => this.files[midpoint].localeCompare(directory) > 0
|
||||
)
|
||||
}
|
||||
|
||||
private binarySearchDirectoryEnd(directory: string, low: number): number {
|
||||
while (low < this.files.length && this.files[low].localeCompare(directory) <= 0) {
|
||||
low++
|
||||
}
|
||||
return this.binarySearch(
|
||||
{ low, high: this.files.length },
|
||||
midpoint => !this.files[midpoint].startsWith(directory)
|
||||
)
|
||||
}
|
||||
|
||||
private binarySearch({ low, high }: SearchRange, isGreater: (midpoint: number) => boolean): number {
|
||||
while (low < high) {
|
||||
const midpoint = Math.floor(low + (high - low) / 2)
|
||||
if (isGreater(midpoint)) {
|
||||
high = midpoint
|
||||
} else {
|
||||
low = midpoint + 1
|
||||
}
|
||||
}
|
||||
return high
|
||||
}
|
||||
|
||||
private depth(path: string): number {
|
||||
let result = 0
|
||||
for (const char of path) {
|
||||
if (char === '/') {
|
||||
result += 1
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
interface SearchRange {
|
||||
low: number
|
||||
high: number
|
||||
}
|
||||
248
client/vscode/src/file-system/FilesTreeDataProvider.ts
Normal file
248
client/vscode/src/file-system/FilesTreeDataProvider.ts
Normal file
@ -0,0 +1,248 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { log } from '../log'
|
||||
|
||||
import { SourcegraphFileSystemProvider } from './SourcegraphFileSystemProvider'
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
export class FilesTreeDataProvider implements vscode.TreeDataProvider<string> {
|
||||
constructor(public readonly fs: SourcegraphFileSystemProvider) {
|
||||
fs.onDidDownloadRepositoryFilenames(() => this.didChangeTreeData.fire(undefined))
|
||||
}
|
||||
|
||||
private _isViewVisible = false
|
||||
private isExpandedNode = new Set<string>()
|
||||
private treeView: vscode.TreeView<string> | undefined
|
||||
private activeUri: vscode.Uri | undefined
|
||||
private selectedRepository: string | undefined
|
||||
private didFocusToken = new vscode.CancellationTokenSource()
|
||||
private treeItemCache = new Map<string, vscode.TreeItem>()
|
||||
private readonly didChangeTreeData = new vscode.EventEmitter<string | undefined>()
|
||||
public readonly onDidChangeTreeData: vscode.Event<string | undefined> = this.didChangeTreeData.event
|
||||
|
||||
public activeTextDocument(): SourcegraphUri | undefined {
|
||||
return this.activeUri && this.activeUri.scheme === 'sourcegraph'
|
||||
? this.fs.sourcegraphUri(this.activeUri)
|
||||
: undefined
|
||||
}
|
||||
public isViewVisible(): boolean {
|
||||
return this._isViewVisible
|
||||
}
|
||||
public setTreeView(treeView: vscode.TreeView<string>): void {
|
||||
this.treeView = treeView
|
||||
treeView.onDidChangeSelection(async event => {
|
||||
// Check if a repository is selected for removing purpose
|
||||
await this.isRepository(event.selection[0])
|
||||
})
|
||||
treeView.onDidChangeVisibility(async event => {
|
||||
const didBecomeVisible = !this._isViewVisible && event.visible
|
||||
this._isViewVisible = event.visible
|
||||
if (didBecomeVisible) {
|
||||
// NOTE: do not remove the line below even if you think it
|
||||
// doesn't have an effect. Before you remove this line, make
|
||||
// sure that the following steps don't cause the "Collapse All"
|
||||
// button to become disabled:
|
||||
// 1. Close "Files" view.
|
||||
// 2. Execute "Reload window" command.
|
||||
// 3. After VS Code loads, open the "Files" view.
|
||||
this.didChangeTreeData.fire(undefined)
|
||||
await this.didFocus(this.activeUri)
|
||||
}
|
||||
})
|
||||
treeView.onDidExpandElement(async event => {
|
||||
await this.isRepository(event.element)
|
||||
this.isExpandedNode.add(event.element)
|
||||
})
|
||||
treeView.onDidCollapseElement(async event => {
|
||||
await this.isRepository(event.element)
|
||||
this.isExpandedNode.delete(event.element)
|
||||
})
|
||||
}
|
||||
|
||||
public async isRepository(selectedUri: string): Promise<void> {
|
||||
const isRepo = [...this.fs.allRepositoryUris()].includes(selectedUri)
|
||||
this.selectedRepository = isRepo ? selectedUri : undefined
|
||||
await vscode.commands.executeCommand('setContext', 'sourcegraph.removeRepository', isRepo)
|
||||
}
|
||||
|
||||
public async getParent(uriString?: string): Promise<string | undefined> {
|
||||
// log.appendLine(`getParent(${uriString})`)
|
||||
try {
|
||||
// Implementation note: this method is not implemented as
|
||||
// `SourcegraphUri.parse(uri).parentUri()` because that would return
|
||||
// URIs to directories that don't exist because they have no siblings
|
||||
// and are therefore automatically merged with their parent. For example,
|
||||
// imagine the following folder structure:
|
||||
// .gitignore
|
||||
// .github/workflows/ci.yml
|
||||
// src/command.ts
|
||||
// src/browse.ts
|
||||
// The parent of `.github/workflows/ci.yml` is `.github/` because the `workflows/`
|
||||
// directory has no sibling.
|
||||
if (!uriString) {
|
||||
return undefined
|
||||
}
|
||||
const uri = SourcegraphUri.parse(uriString)
|
||||
if (!uri.path) {
|
||||
return undefined
|
||||
}
|
||||
let ancestor: string | undefined = uri.repositoryUri()
|
||||
let children = await this.getChildren(ancestor)
|
||||
while (ancestor) {
|
||||
const isParent = children?.includes(uriString)
|
||||
if (isParent) {
|
||||
break
|
||||
}
|
||||
ancestor = children?.find(childUri => {
|
||||
const child = SourcegraphUri.parse(childUri)
|
||||
return child.path && uri.path?.startsWith(child.path + '/')
|
||||
})
|
||||
if (!ancestor) {
|
||||
log.errorAndThrow(`getParent(${uriString || 'undefined'}) nothing startsWith`)
|
||||
}
|
||||
children = await this.getChildren(ancestor)
|
||||
}
|
||||
return ancestor
|
||||
} catch (error) {
|
||||
log.errorAndThrow(`getParent(${uriString || 'undefined'})`, error)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
public async getChildren(uriString?: string): Promise<string[] | undefined> {
|
||||
try {
|
||||
if (!uriString) {
|
||||
const repos = [...this.fs.allRepositoryUris()]
|
||||
return repos.map(repo => repo.replace('https://', 'sourcegraph://'))
|
||||
}
|
||||
const uri = SourcegraphUri.parse(uriString)
|
||||
const tree = await this.fs.getFileTree(uri)
|
||||
const directChildren = tree.directChildren(uri.path || '')
|
||||
for (const child of directChildren) {
|
||||
this.treeItemCache.set(child, this.newTreeItem(SourcegraphUri.parse(child), uri, directChildren.length))
|
||||
}
|
||||
return directChildren
|
||||
} catch (error) {
|
||||
return log.errorAndThrow(`getChildren(${uriString || ''})`, error)
|
||||
}
|
||||
}
|
||||
|
||||
public async focusActiveFile(): Promise<void> {
|
||||
await vscode.commands.executeCommand('sourcegraph.files.focus')
|
||||
await this.didFocus(this.activeUri)
|
||||
}
|
||||
|
||||
public async didFocus(vscodeUri: vscode.Uri | undefined): Promise<void> {
|
||||
this.didFocusToken.cancel()
|
||||
this.didFocusToken = new vscode.CancellationTokenSource()
|
||||
this.activeUri = vscodeUri
|
||||
await vscode.commands.executeCommand(
|
||||
'setContext',
|
||||
'sourcegraph.canFocusActiveDocument',
|
||||
vscodeUri?.scheme === 'sourcegraph'
|
||||
)
|
||||
if (vscodeUri && vscodeUri.scheme === 'sourcegraph' && this.treeView && this._isViewVisible) {
|
||||
const uri = this.fs.sourcegraphUri(vscodeUri)
|
||||
if (uri.uri === this.fs.emptyFileUri()) {
|
||||
return
|
||||
}
|
||||
await this.fs.downloadFiles(uri)
|
||||
await this.didFocusString(uri, true, this.didFocusToken.token)
|
||||
}
|
||||
}
|
||||
|
||||
public isSourcegrapeRemoteFile(vscodeUri: vscode.Uri | undefined): boolean {
|
||||
if (vscodeUri && vscodeUri.scheme === 'sourcegraph' && this.treeView && this._isViewVisible) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public async getTreeItem(uriString: string): Promise<vscode.TreeItem> {
|
||||
try {
|
||||
const fromCache = this.treeItemCache.get(uriString)
|
||||
if (fromCache) {
|
||||
return fromCache
|
||||
}
|
||||
const uri = SourcegraphUri.parse(uriString)
|
||||
const parentUri = await this.getParent(uri.uri)
|
||||
return this.newTreeItem(uri, parentUri ? SourcegraphUri.parse(parentUri) : undefined, 0)
|
||||
} catch (error) {
|
||||
log.errorAndThrow(`getTreeItem(${uriString})`, error)
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
private async didFocusString(
|
||||
uri: SourcegraphUri,
|
||||
isDestinationNode: boolean,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (this.treeView) {
|
||||
const parent = await this.getParent(uri.uri)
|
||||
if (parent) {
|
||||
await this.didFocusString(SourcegraphUri.parse(parent), false, token)
|
||||
} else {
|
||||
await this.getChildren(undefined)
|
||||
}
|
||||
if (token.isCancellationRequested) {
|
||||
return
|
||||
}
|
||||
await this.treeView.reveal(uri.uri, {
|
||||
focus: true,
|
||||
select: isDestinationNode,
|
||||
expand: !isDestinationNode,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
log.error(`didFocusString(${uri.uri})`, error)
|
||||
}
|
||||
}
|
||||
|
||||
// Remove selected repo from tree
|
||||
public async removeTreeItem(): Promise<void> {
|
||||
if (this.selectedRepository) {
|
||||
this.fs.removeRepository(this.selectedRepository)
|
||||
}
|
||||
this.selectedRepository = undefined
|
||||
await vscode.commands.executeCommand('setContext', 'sourcegraph.removeRepository', false)
|
||||
return this.didChangeTreeData.fire(undefined)
|
||||
}
|
||||
|
||||
private newTreeItem(
|
||||
uri: SourcegraphUri,
|
||||
parent: SourcegraphUri | undefined,
|
||||
parentChildrenCount: number
|
||||
): vscode.TreeItem {
|
||||
const command = uri.isFile()
|
||||
? {
|
||||
command: 'sourcegraph.openFile',
|
||||
title: 'Open file',
|
||||
toolbar: 'test',
|
||||
arguments: [uri.uri],
|
||||
}
|
||||
: undefined
|
||||
// Check if this is a currently selected file
|
||||
let selectedFile = false
|
||||
if (
|
||||
vscode.window.activeTextEditor?.document &&
|
||||
uri.path === SourcegraphUri.parse(vscode.window.activeTextEditor?.document.uri.toString()).path
|
||||
) {
|
||||
selectedFile = true
|
||||
}
|
||||
return {
|
||||
id: uri.uri,
|
||||
label: uri.treeItemLabel(parent),
|
||||
tooltip: uri.uri.replace('sourcegraph://', 'https://'),
|
||||
collapsibleState: uri.isFile()
|
||||
? vscode.TreeItemCollapsibleState.None
|
||||
: parentChildrenCount === 0
|
||||
? vscode.TreeItemCollapsibleState.Expanded
|
||||
: vscode.TreeItemCollapsibleState.Collapsed,
|
||||
command,
|
||||
resourceUri: vscode.Uri.parse(uri.uri),
|
||||
contextValue: !uri.isFile() ? 'directory' : selectedFile ? 'selected' : 'file',
|
||||
}
|
||||
}
|
||||
}
|
||||
317
client/vscode/src/file-system/SourcegraphFileSystemProvider.ts
Normal file
317
client/vscode/src/file-system/SourcegraphFileSystemProvider.ts
Normal file
@ -0,0 +1,317 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { getBlobContent } from '../backend/blobContent'
|
||||
import { getFiles } from '../backend/files'
|
||||
import { getRepositoryMetadata, RepositoryMetadata } from '../backend/repositoryMetadata'
|
||||
import { LocationNode } from '../code-intel/location'
|
||||
import { log } from '../log'
|
||||
import { endpointHostnameSetting } from '../settings/endpointSetting'
|
||||
|
||||
import { FileTree } from './FileTree'
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
export interface RepositoryFileNames {
|
||||
repositoryUri: string
|
||||
repositoryName: string
|
||||
fileNames: string[]
|
||||
}
|
||||
|
||||
export interface Blob {
|
||||
uri: string
|
||||
repositoryName: string
|
||||
revision: string
|
||||
path: string
|
||||
content: Uint8Array
|
||||
isBinaryFile: boolean
|
||||
byteSize: number
|
||||
time: number
|
||||
type: vscode.FileType
|
||||
}
|
||||
|
||||
export class SourcegraphFileSystemProvider implements vscode.FileSystemProvider {
|
||||
constructor(private instanceURL: string) {}
|
||||
|
||||
private fileNamesByRepository: Map<string, Promise<string[]>> = new Map()
|
||||
private metadata: Map<string, RepositoryMetadata> = new Map()
|
||||
private didDownloadFilenames = new vscode.EventEmitter<string>()
|
||||
|
||||
// ======================
|
||||
// FileSystemProvider API
|
||||
// ======================
|
||||
|
||||
// We don't implement this because Sourcegraph files are read-only.
|
||||
private didChangeFile = new vscode.EventEmitter<vscode.FileChangeEvent[]>() // Never used.
|
||||
public readonly onDidChangeFile: vscode.Event<vscode.FileChangeEvent[]> = this.didChangeFile.event
|
||||
public async stat(vscodeUri: vscode.Uri): Promise<vscode.FileStat> {
|
||||
const uri = this.sourcegraphUri(vscodeUri)
|
||||
const now = Date.now()
|
||||
if (uri.uri === this.emptyFileUri()) {
|
||||
return { mtime: now, ctime: now, size: 0, type: vscode.FileType.File }
|
||||
}
|
||||
const files = await this.downloadFiles(uri)
|
||||
const isFile = uri.path && files.includes(uri.path)
|
||||
const type = isFile ? vscode.FileType.File : vscode.FileType.Directory
|
||||
// log.appendLine(
|
||||
// `stat(${uri.uri}) path=${uri.path || '""'} files.length=${files.length} type=${vscode.FileType[type]}`
|
||||
// )
|
||||
return {
|
||||
// It seems to be OK to return hardcoded values for the timestamps
|
||||
// and the byte size. If it turns out the byte size needs to be
|
||||
// correct for some reason, then we can use
|
||||
// `this.fetchBlob(uri).byteSize` to get the value for files.
|
||||
mtime: now,
|
||||
ctime: now,
|
||||
size: 1337,
|
||||
type,
|
||||
}
|
||||
}
|
||||
|
||||
public emptyFileUri(): string {
|
||||
return 'sourcegraph://sourcegraph.com/empty-file.txt'
|
||||
}
|
||||
|
||||
public async readFile(vscodeUri: vscode.Uri): Promise<Uint8Array> {
|
||||
const uri = this.sourcegraphUri(vscodeUri)
|
||||
if (uri.uri === this.emptyFileUri()) {
|
||||
return new Uint8Array()
|
||||
}
|
||||
const blob = await this.fetchBlob(uri)
|
||||
return blob.content
|
||||
}
|
||||
|
||||
public async readDirectory(vscodeUri: vscode.Uri): Promise<[string, vscode.FileType][]> {
|
||||
const uri = this.sourcegraphUri(vscodeUri)
|
||||
if (uri.uri.endsWith('/-')) {
|
||||
return []
|
||||
}
|
||||
const tree = await this.getFileTree(uri)
|
||||
const children = tree.directChildren(uri.path || '')
|
||||
return children.map(childUri => {
|
||||
const child = SourcegraphUri.parse(childUri)
|
||||
const type = child.isDirectory() ? vscode.FileType.Directory : vscode.FileType.File
|
||||
return [child.basename(), type]
|
||||
})
|
||||
}
|
||||
|
||||
public createDirectory(uri: vscode.Uri): void {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
public writeFile(
|
||||
_uri: vscode.Uri,
|
||||
_content: Uint8Array,
|
||||
_options: { create: boolean; overwrite: boolean }
|
||||
): void | Thenable<void> {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
public delete(_uri: vscode.Uri, _options: { recursive: boolean }): void {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
public rename(_oldUri: vscode.Uri, _newUri: vscode.Uri, _options: { overwrite: boolean }): void {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
public watch(_uri: vscode.Uri, _options: { recursive: boolean; excludes: string[] }): vscode.Disposable {
|
||||
throw new Error('Method not supported in read-only file system.')
|
||||
}
|
||||
|
||||
// ===============================
|
||||
// Helper methods for external use
|
||||
// ===============================
|
||||
|
||||
public onDidDownloadRepositoryFilenames: vscode.Event<string> = this.didDownloadFilenames.event
|
||||
|
||||
public allRepositoryUris(): string[] {
|
||||
return [...this.fileNamesByRepository.keys()]
|
||||
}
|
||||
|
||||
public resetFileTree(): void {
|
||||
return this.fileNamesByRepository.clear()
|
||||
}
|
||||
|
||||
// Remove Currently Selected Repository from Tree
|
||||
public removeRepository(uriString: string): void {
|
||||
this.fileNamesByRepository.delete(uriString)
|
||||
}
|
||||
|
||||
public async allFilesFromOpenRepositories(folder?: SourcegraphUri): Promise<RepositoryFileNames[]> {
|
||||
const promises: RepositoryFileNames[] = []
|
||||
const folderRepositoryUri = folder?.repositoryUri()
|
||||
for (const [repositoryUri, downloadingFileNames] of this.fileNamesByRepository.entries()) {
|
||||
if (folderRepositoryUri && repositoryUri !== folderRepositoryUri) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const fileNames = await downloadingFileNames
|
||||
const uri = SourcegraphUri.parse(repositoryUri)
|
||||
promises.push({
|
||||
repositoryUri: uri.repositoryUri(),
|
||||
repositoryName: `${uri.repositoryName}${uri.revisionPart()}`,
|
||||
fileNames,
|
||||
})
|
||||
} catch {
|
||||
log.error(`failed to download files for repository '${repositoryUri}'`)
|
||||
}
|
||||
}
|
||||
return promises
|
||||
}
|
||||
|
||||
public toVscodeLocation(node: LocationNode): vscode.Location {
|
||||
const metadata = this.metadata.get(node.resource.repositoryName)
|
||||
let revision = node.resource.revision
|
||||
if (metadata?.defaultBranch && revision === metadata?.defaultOID) {
|
||||
revision = metadata.defaultBranch
|
||||
}
|
||||
|
||||
let rangeOrPosition: vscode.Range | vscode.Position
|
||||
if (node.range) {
|
||||
rangeOrPosition = new vscode.Range(
|
||||
new vscode.Position(node.range.start.line, node.range.start.character),
|
||||
new vscode.Position(node.range.end.line, node.range.end.character)
|
||||
)
|
||||
} else {
|
||||
rangeOrPosition = new vscode.Position(0, 0)
|
||||
}
|
||||
|
||||
return new vscode.Location(
|
||||
vscode.Uri.parse(
|
||||
SourcegraphUri.fromParts(endpointHostnameSetting(), node.resource.repositoryName, {
|
||||
revision,
|
||||
path: node.resource.path,
|
||||
}).uri
|
||||
),
|
||||
rangeOrPosition
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns the URI of a file in the given repository. The file is the
|
||||
* toplevel readme file if it exists, otherwise it's the file with the
|
||||
* shortest name in the repository.
|
||||
*/
|
||||
public async defaultFileUri(repositoryName: string): Promise<SourcegraphUri> {
|
||||
const defaultBranch = (await this.repositoryMetadata(repositoryName))?.defaultBranch
|
||||
if (!defaultBranch) {
|
||||
log.errorAndThrow(`repository '${repositoryName}' has no default branch`)
|
||||
}
|
||||
const uri = SourcegraphUri.fromParts(endpointHostnameSetting(), repositoryName, { revision: defaultBranch })
|
||||
const files = await this.downloadFiles(uri)
|
||||
const readmes = files.filter(name => name.match(/readme/i))
|
||||
const candidates = readmes.length > 0 ? readmes : files
|
||||
let readme: string | undefined
|
||||
for (const candidate of candidates) {
|
||||
if (candidate === '' || candidate === 'lsif-java.json') {
|
||||
// Skip auto-generated file for JVM packages
|
||||
continue
|
||||
}
|
||||
if (!readme) {
|
||||
readme = candidate
|
||||
} else if (candidate.length < readme.length) {
|
||||
readme = candidate
|
||||
}
|
||||
}
|
||||
const defaultFile = readme || files[0]
|
||||
return SourcegraphUri.fromParts(endpointHostnameSetting(), repositoryName, {
|
||||
revision: defaultBranch,
|
||||
path: defaultFile,
|
||||
})
|
||||
}
|
||||
|
||||
public async fetchBlob(uri: SourcegraphUri): Promise<Blob> {
|
||||
await this.repositoryMetadata(uri.repositoryName)
|
||||
if (!uri.revision) {
|
||||
log.errorAndThrow(`missing revision for URI '${uri.uri}'`)
|
||||
}
|
||||
const path = uri.path || ''
|
||||
const content = await getBlobContent({
|
||||
repository: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
path,
|
||||
})
|
||||
|
||||
if (content) {
|
||||
const toCacheResult: Blob = {
|
||||
uri: uri.uri,
|
||||
repositoryName: uri.repositoryName,
|
||||
revision: uri.revision,
|
||||
content: content.content,
|
||||
isBinaryFile: content.isBinary,
|
||||
byteSize: content.byteSize,
|
||||
path,
|
||||
time: new Date().getMilliseconds(),
|
||||
type: vscode.FileType.File,
|
||||
}
|
||||
|
||||
// Start downloading the repository files in the background.
|
||||
this.downloadFiles(uri).then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
|
||||
return toCacheResult
|
||||
}
|
||||
return log.errorAndThrow(`fetchBlob(${uri.uri}) not found`)
|
||||
}
|
||||
|
||||
public async repositoryMetadata(repositoryName: string): Promise<RepositoryMetadata | undefined> {
|
||||
let metadata = this.metadata.get(repositoryName)
|
||||
if (metadata) {
|
||||
return metadata
|
||||
}
|
||||
metadata = await getRepositoryMetadata({ repositoryName })
|
||||
if (metadata) {
|
||||
this.metadata.set(repositoryName, metadata)
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
public downloadFiles(uri: SourcegraphUri): Promise<string[]> {
|
||||
const key = uri.repositoryUri()
|
||||
const fileNamesByRepository = this.fileNamesByRepository
|
||||
let downloadingFiles = this.fileNamesByRepository.get(key)
|
||||
if (!downloadingFiles) {
|
||||
downloadingFiles = getFiles({ repository: uri.repositoryName, revision: uri.revision })
|
||||
vscode.window
|
||||
.withProgress(
|
||||
{
|
||||
location: vscode.ProgressLocation.Window,
|
||||
title: `Loading ${uri.repositoryName}`,
|
||||
},
|
||||
async progress => {
|
||||
try {
|
||||
await downloadingFiles
|
||||
this.didDownloadFilenames.fire(key)
|
||||
} catch (error) {
|
||||
log.error(`downloadFiles(${key})`, error)
|
||||
fileNamesByRepository.delete(key)
|
||||
}
|
||||
progress.report({ increment: 100 })
|
||||
}
|
||||
)
|
||||
.then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
|
||||
this.fileNamesByRepository.set(key, downloadingFiles)
|
||||
}
|
||||
return downloadingFiles
|
||||
}
|
||||
|
||||
public sourcegraphUri(uri: vscode.Uri): SourcegraphUri {
|
||||
const sourcegraphUri = SourcegraphUri.parse(uri.toString(true))
|
||||
if (sourcegraphUri.host !== new URL(this.instanceURL).host) {
|
||||
const message = 'Sourcegraph instance URL has changed. Close files opened through the previous instance.'
|
||||
vscode.window.showWarningMessage(message).then(
|
||||
() => {},
|
||||
() => {}
|
||||
)
|
||||
throw new Error(message)
|
||||
}
|
||||
return sourcegraphUri
|
||||
}
|
||||
|
||||
public async getFileTree(uri: SourcegraphUri): Promise<FileTree> {
|
||||
const files = await this.downloadFiles(uri)
|
||||
return new FileTree(uri, files)
|
||||
}
|
||||
}
|
||||
225
client/vscode/src/file-system/SourcegraphUri.ts
Normal file
225
client/vscode/src/file-system/SourcegraphUri.ts
Normal file
@ -0,0 +1,225 @@
|
||||
import { 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[parts.length - 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 typeof 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,
|
||||
})
|
||||
}
|
||||
}
|
||||
62
client/vscode/src/file-system/commands.ts
Normal file
62
client/vscode/src/file-system/commands.ts
Normal file
@ -0,0 +1,62 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { SourcegraphFileSystemProvider } from './SourcegraphFileSystemProvider'
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
export async function openSourcegraphUriCommand(fs: SourcegraphFileSystemProvider, uri: SourcegraphUri): Promise<void> {
|
||||
if (uri.compareRange) {
|
||||
// noop. v2 Debt: implement. Open in browser for v1
|
||||
return
|
||||
}
|
||||
if (!uri.revision) {
|
||||
const metadata = await fs.repositoryMetadata(uri.repositoryName)
|
||||
uri = uri.withRevision(metadata?.defaultBranch || 'HEAD')
|
||||
}
|
||||
const 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,
|
||||
})
|
||||
}
|
||||
|
||||
function getSelection(uri: SourcegraphUri, textDocument: vscode.TextDocument): vscode.Range | undefined {
|
||||
if (typeof uri?.position?.line !== 'undefined' && typeof uri?.position?.character !== 'undefined') {
|
||||
return offsetRange(uri.position.line, uri.position.character)
|
||||
}
|
||||
if (typeof 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[fileNames.length - 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'))
|
||||
}
|
||||
49
client/vscode/src/file-system/initialize.ts
Normal file
49
client/vscode/src/file-system/initialize.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
import { log } from '../log'
|
||||
|
||||
import { openSourcegraphUriCommand } from './commands'
|
||||
import { FilesTreeDataProvider } from './FilesTreeDataProvider'
|
||||
import { SourcegraphFileSystemProvider } from './SourcegraphFileSystemProvider'
|
||||
import { SourcegraphUri } from './SourcegraphUri'
|
||||
|
||||
export function initializeSourcegraphFileSystem({
|
||||
context,
|
||||
initialInstanceURL,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
initialInstanceURL: string
|
||||
}): { fs: SourcegraphFileSystemProvider } {
|
||||
const fs = new SourcegraphFileSystemProvider(initialInstanceURL)
|
||||
context.subscriptions.push(vscode.workspace.registerFileSystemProvider('sourcegraph', fs, { isReadonly: true }))
|
||||
|
||||
const files = new FilesTreeDataProvider(fs)
|
||||
|
||||
const filesTreeView = vscode.window.createTreeView<string>('sourcegraph.files', {
|
||||
treeDataProvider: files,
|
||||
showCollapseAll: true,
|
||||
})
|
||||
files.setTreeView(filesTreeView)
|
||||
context.subscriptions.push(filesTreeView)
|
||||
|
||||
// Open remote Sourcegraph file from remote file tree
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.openFile', async uri => {
|
||||
if (typeof uri === 'string') {
|
||||
await openSourcegraphUriCommand(fs, SourcegraphUri.parse(uri))
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
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 }
|
||||
}
|
||||
49
client/vscode/src/link-commands/browserActionsNode.ts
Normal file
49
client/vscode/src/link-commands/browserActionsNode.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import vscode, { env } from 'vscode'
|
||||
|
||||
import { getSourcegraphFileUrl, repoInfo } from './git-helpers'
|
||||
import { generateSourcegraphBlobLink, vsceUtms } from './initialize'
|
||||
/**
|
||||
* Open active file in the browser on the configured Sourcegraph instance.
|
||||
*/
|
||||
|
||||
export async function browserActions(action: string, logRedirectEvent: (uri: string) => void): Promise<void> {
|
||||
const editor = vscode.window.activeTextEditor
|
||||
if (!editor) {
|
||||
throw new Error('No active editor')
|
||||
}
|
||||
const uri = editor.document.uri
|
||||
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 {
|
||||
const repositoryInfo = await repoInfo(editor.document.uri.fsPath)
|
||||
if (!repositoryInfo) {
|
||||
return
|
||||
}
|
||||
const { remoteURL, branch, fileRelative } = repositoryInfo
|
||||
const instanceUrl = vscode.workspace.getConfiguration('sourcegraph').get('url')
|
||||
if (typeof instanceUrl === 'string') {
|
||||
// construct sourcegraph url for current file
|
||||
sourcegraphUrl = getSourcegraphFileUrl(instanceUrl, remoteURL, branch, fileRelative, editor) + vsceUtms
|
||||
}
|
||||
}
|
||||
// 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`)
|
||||
}
|
||||
}
|
||||
47
client/vscode/src/link-commands/browserActionsWeb.ts
Normal file
47
client/vscode/src/link-commands/browserActionsWeb.ts
Normal file
@ -0,0 +1,47 @@
|
||||
import vscode, { env } from 'vscode'
|
||||
|
||||
import { generateSourcegraphBlobLink, vsceUtms } from './initialize'
|
||||
|
||||
/**
|
||||
* browser Actions for Web does not run node modules to get git info
|
||||
* Open active file in the browser on the configured Sourcegraph instance.
|
||||
*/
|
||||
export async function browserActions(action: string, logRedirectEvent: (uri: string) => void): Promise<void> {
|
||||
const editor = vscode.window.activeTextEditor
|
||||
if (!editor) {
|
||||
throw new Error('No active editor')
|
||||
}
|
||||
const uri = editor.document.uri
|
||||
const instanceUrl = vscode.workspace.getConfiguration('sourcegraph').get('url')
|
||||
let sourcegraphUrl = String()
|
||||
// check if the current file is a remote file or not
|
||||
if (uri.scheme === 'sourcegraph') {
|
||||
sourcegraphUrl = generateSourcegraphBlobLink(
|
||||
uri,
|
||||
editor.selection.start.line,
|
||||
editor.selection.start.character,
|
||||
editor.selection.end.line,
|
||||
editor.selection.end.character
|
||||
)
|
||||
} else if (uri.authority === 'github' && typeof instanceUrl === 'string') {
|
||||
// For remote github files
|
||||
const repoInfo = uri.fsPath.split('/')
|
||||
const repositoryName = `${repoInfo[1]}/${repoInfo[2]}`
|
||||
const filePath = repoInfo.length === 4 ? repoInfo[3] : repoInfo.slice(3).join('/')
|
||||
sourcegraphUrl = `${instanceUrl}github.com/${repositoryName}/-/blob/${filePath || ''}${vsceUtms}`
|
||||
} 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`)
|
||||
}
|
||||
}
|
||||
221
client/vscode/src/link-commands/git-helpers.ts
Normal file
221
client/vscode/src/link-commands/git-helpers.ts
Normal file
@ -0,0 +1,221 @@
|
||||
import * as path from 'path'
|
||||
|
||||
import execa from 'execa'
|
||||
import vscode, { TextEditor } from 'vscode'
|
||||
|
||||
import { version } from '../../package.json'
|
||||
import { log } from '../log'
|
||||
|
||||
interface RepositoryInfo extends Branch, RemoteName {
|
||||
/** Git repository remote URL */
|
||||
remoteURL: string
|
||||
|
||||
/** File path relative to the repository root */
|
||||
fileRelative: string
|
||||
}
|
||||
|
||||
export type GitHelpers = typeof gitHelpers
|
||||
|
||||
export interface RemoteName {
|
||||
/**
|
||||
* Remote name of the upstream repository,
|
||||
* or the first found remote name if no upstream is found
|
||||
*/
|
||||
remoteName: string
|
||||
}
|
||||
|
||||
export interface Branch {
|
||||
/**
|
||||
* Remote branch name, or 'HEAD' if it isn't found because
|
||||
* e.g. detached HEAD state, upstream branch points to a local branch
|
||||
*/
|
||||
branch: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Git repository remote URL, the current branch, and the file path
|
||||
* relative to the repository root. Returns undefined if no remote is found
|
||||
*/
|
||||
export async function repoInfo(filePath: string): Promise<RepositoryInfo | undefined> {
|
||||
try {
|
||||
// Determine repository root directory.
|
||||
const fileDirectory = path.dirname(filePath)
|
||||
const repoRoot = await gitHelpers.rootDirectory(fileDirectory)
|
||||
|
||||
// Determine file path relative to repository root.
|
||||
let fileRelative = filePath.slice(repoRoot.length + 1)
|
||||
|
||||
let { branch, remoteName } = await gitRemoteNameAndBranch(repoRoot, gitHelpers, log)
|
||||
|
||||
branch = getDefaultBranch() || branch
|
||||
|
||||
const remoteURL = await gitRemoteUrlWithReplacements(repoRoot, remoteName, gitHelpers, log)
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
fileRelative = fileRelative.replace(/\\/g, '/')
|
||||
}
|
||||
return { remoteURL, branch, fileRelative, remoteName }
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export async function gitRemoteNameAndBranch(
|
||||
repoDirectory: string,
|
||||
git: Pick<GitHelpers, 'branch' | 'remotes' | 'upstreamAndBranch'>,
|
||||
log?: {
|
||||
appendLine: (value: string) => void
|
||||
}
|
||||
): Promise<RemoteName & Branch> {
|
||||
let remoteName: string | undefined
|
||||
|
||||
// Used to determine which part of upstreamAndBranch is the remote name, or as fallback if no upstream is set
|
||||
const remotes = await git.remotes(repoDirectory)
|
||||
const branch = await git.branch(repoDirectory)
|
||||
|
||||
try {
|
||||
const upstreamAndBranch = await git.upstreamAndBranch(repoDirectory)
|
||||
// Subtract $BRANCH_NAME from $UPSTREAM_REMOTE/$BRANCH_NAME.
|
||||
// We can't just split on the delineating `/`, since refnames can include `/`:
|
||||
// https://sourcegraph.com/github.com/git/git@454cb6bd52a4de614a3633e4f547af03d5c3b640/-/blob/refs.c#L52-67
|
||||
|
||||
// Example:
|
||||
// stdout: remote/two/tj/feature
|
||||
// remoteName: remote/two, branch: tj/feature
|
||||
|
||||
const branchPosition = upstreamAndBranch.lastIndexOf(branch)
|
||||
const maybeRemote = upstreamAndBranch.slice(0, branchPosition - 1)
|
||||
if (branchPosition !== -1 && maybeRemote) {
|
||||
remoteName = maybeRemote
|
||||
}
|
||||
} catch {
|
||||
// noop. upstream may not be set
|
||||
}
|
||||
|
||||
// If we cannot find the remote name deterministically, we use the first
|
||||
// Git remote found.
|
||||
if (!remoteName) {
|
||||
if (remotes.length > 1) {
|
||||
log?.appendLine(`no upstream found, using first git remote: ${remotes[0]}`)
|
||||
}
|
||||
remoteName = remotes[0]
|
||||
}
|
||||
|
||||
// Throw if a remote still isn't found
|
||||
if (!remoteName) {
|
||||
throw new Error('no configured git remotes')
|
||||
}
|
||||
|
||||
return { remoteName, branch }
|
||||
}
|
||||
|
||||
export const gitHelpers = {
|
||||
/**
|
||||
* Returns the repository root directory for any directory within the
|
||||
* repository.
|
||||
*/
|
||||
async rootDirectory(repoDirectory: string): Promise<string> {
|
||||
const { stdout } = await execa('git', ['rev-parse', '--show-toplevel'], { cwd: repoDirectory })
|
||||
return stdout
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the names of all git remotes, e.g. ["origin", "foobar"]
|
||||
*/
|
||||
async remotes(repoDirectory: string): Promise<string[]> {
|
||||
const { stdout } = await execa('git', ['remote'], { cwd: repoDirectory })
|
||||
return stdout.split('\n')
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the remote URL for the given remote name.
|
||||
* e.g. `origin` -> `git@github.com:foo/bar`
|
||||
*/
|
||||
async remoteUrl(remoteName: string, repoDirectory: string): Promise<string> {
|
||||
const { stdout } = await execa('git', ['remote', 'get-url', remoteName], { cwd: repoDirectory })
|
||||
return stdout
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns either the current branch name of the repository OR in all
|
||||
* other cases (e.g. detached HEAD state), it returns "HEAD".
|
||||
*/
|
||||
async branch(repoDirectory: string): Promise<string> {
|
||||
const { stdout } = await execa('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repoDirectory })
|
||||
return stdout
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a string in the format $UPSTREAM_REMOTE/$BRANCH_NAME, e.g. "origin/branch-name", throws if not found
|
||||
*/
|
||||
async upstreamAndBranch(repoDirectory: string): Promise<string> {
|
||||
const { stdout } = await execa('git', ['rev-parse', '--abbrev-ref', 'HEAD@{upstream}'], { cwd: repoDirectory })
|
||||
return stdout
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the remote URL for the given remote name with remote URL replacements.
|
||||
* e.g. `origin` -> `git@github.com:foo/bar`
|
||||
*/
|
||||
export async function gitRemoteUrlWithReplacements(
|
||||
repoDirectory: string,
|
||||
remoteName: string,
|
||||
gitHelpers: Pick<GitHelpers, 'remoteUrl'>,
|
||||
log?: { appendLine: (value: string) => void }
|
||||
): Promise<string> {
|
||||
let stdout = await gitHelpers.remoteUrl(remoteName, repoDirectory)
|
||||
const replacementsList = getRemoteUrlReplacements()
|
||||
|
||||
const stdoutBefore = stdout
|
||||
|
||||
for (const replacement in replacementsList) {
|
||||
if (typeof replacement === 'string') {
|
||||
stdout = stdout.replace(replacement, replacementsList[replacement])
|
||||
}
|
||||
}
|
||||
|
||||
log?.appendLine(`${stdoutBefore} became ${stdout}`)
|
||||
return stdout
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses editor endpoint to construct sourcegraph file URL
|
||||
*/
|
||||
export function getSourcegraphFileUrl(
|
||||
SourcegraphUrl: string,
|
||||
remoteURL: string,
|
||||
branch: string,
|
||||
fileRelative: string,
|
||||
editor: TextEditor
|
||||
): string {
|
||||
return (
|
||||
`${SourcegraphUrl}/-/editor` +
|
||||
`?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))}`
|
||||
)
|
||||
}
|
||||
|
||||
function getRemoteUrlReplacements(): Record<string, string> {
|
||||
// has default value
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const replacements = vscode.workspace
|
||||
.getConfiguration('sourcegraph')
|
||||
.get<Record<string, string>>('remoteUrlReplacements')!
|
||||
return replacements
|
||||
}
|
||||
|
||||
export function getDefaultBranch(): string {
|
||||
// has default value
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const branch = vscode.workspace.getConfiguration('sourcegraph').get<string>('defaultBranch')!
|
||||
|
||||
return branch
|
||||
}
|
||||
77
client/vscode/src/link-commands/initialize.ts
Normal file
77
client/vscode/src/link-commands/initialize.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
import { EventSource } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { version } from '../../package.json'
|
||||
import { logEvent } from '../backend/eventLogger'
|
||||
import { SourcegraphUri } from '../file-system/SourcegraphUri'
|
||||
import { LocalStorageService, ANONYMOUS_USER_ID_KEY } from '../settings/LocalStorageService'
|
||||
|
||||
import { browserActions } from './browserActionsNode'
|
||||
|
||||
export function initializeCodeSharingCommands(
|
||||
context: vscode.ExtensionContext,
|
||||
eventSourceType: EventSource,
|
||||
localStorageService: LocalStorageService
|
||||
): void {
|
||||
// Open local file or remote Sourcegraph file in browser
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.openInBrowser', async () => {
|
||||
await browserActions('open', logRedirectEvent)
|
||||
})
|
||||
)
|
||||
// Copy Sourcegraph link to file
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.copyFileLink', async () => {
|
||||
await browserActions('copy', logRedirectEvent)
|
||||
})
|
||||
)
|
||||
// Search Selected Text in Sourcegraph Search Tab
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.selectionSearchWeb', async () => {
|
||||
const instanceUrl =
|
||||
vscode.workspace.getConfiguration('sourcegraph').get<string>('url') || 'https://sourcegraph.com'
|
||||
const editor = vscode.window.activeTextEditor
|
||||
const selectedQuery = editor?.document.getText(editor.selection)
|
||||
if (!editor || !selectedQuery) {
|
||||
throw new Error('No selection detected')
|
||||
}
|
||||
const uri = `${instanceUrl}/search?q=context:global+${encodeURIComponent(
|
||||
selectedQuery
|
||||
)}&patternType=literal${vsceUtms}`
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
export const vsceUtms =
|
||||
'&utm_campaign=vscode-extension&utm_medium=direct_traffic&utm_source=vscode-extension&utm_content=vsce-commands'
|
||||
|
||||
export function generateSourcegraphBlobLink(
|
||||
uri: vscode.Uri,
|
||||
startLine: number,
|
||||
startChar: number,
|
||||
endLine: number,
|
||||
endChar: number
|
||||
): string {
|
||||
const instanceUrl = vscode.workspace.getConfiguration('sourcegraph').get<string>('url') || 'https://sourcegraph.com'
|
||||
// Using SourcegraphUri.parse to properly decode repo revision
|
||||
const decodedUri = SourcegraphUri.parse(uri.toString()).uri
|
||||
return `${decodedUri.replace(uri.scheme, instanceUrl.startsWith('https') ? 'https' : 'http')}?L${encodeURIComponent(
|
||||
String(startLine)
|
||||
)}:${encodeURIComponent(String(startChar))}-${encodeURIComponent(String(endLine))}:${encodeURIComponent(
|
||||
String(endChar)
|
||||
)}${vsceUtms}`
|
||||
}
|
||||
34
client/vscode/src/log.ts
Normal file
34
client/vscode/src/log.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
const outputChannel = vscode.window.createOutputChannel('Sourcegraph')
|
||||
|
||||
export const log = {
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @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
|
||||
}
|
||||
2
client/vscode/src/polyfills/eventSource.d.ts
vendored
Normal file
2
client/vscode/src/polyfills/eventSource.d.ts
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
function polyfillEventSource(headers: { [name: string]: string }): void
|
||||
export default polyfillEventSource
|
||||
485
client/vscode/src/polyfills/eventSource.js
Normal file
485
client/vscode/src/polyfills/eventSource.js
Normal file
@ -0,0 +1,485 @@
|
||||
// From https://github.com/EventSource/eventsource.
|
||||
// Sets global `EventSource` for Node, which is required for streaming search.
|
||||
// Used for VS Code web as well to be able to add Authorization header.
|
||||
|
||||
const original = require('original')
|
||||
|
||||
const parse = require('url').parse
|
||||
const events = require('events')
|
||||
const http = require('http')
|
||||
const https = require('https')
|
||||
const util = require('util')
|
||||
|
||||
let fixedHeaders = {}
|
||||
|
||||
module.exports = function polyfillEventSource(headers) {
|
||||
fixedHeaders = { ...headers }
|
||||
|
||||
global.EventSource = EventSource
|
||||
global.MessageEvent = MessageEvent
|
||||
global.Event = Event
|
||||
}
|
||||
|
||||
const httpsOptions = new Set([
|
||||
'pfx',
|
||||
'key',
|
||||
'passphrase',
|
||||
'cert',
|
||||
'ca',
|
||||
'ciphers',
|
||||
'rejectUnauthorized',
|
||||
'secureProtocol',
|
||||
'servername',
|
||||
'checkServerIdentity',
|
||||
])
|
||||
|
||||
const bom = [239, 187, 191]
|
||||
const colon = 58
|
||||
const space = 32
|
||||
const lineFeed = 10
|
||||
const carriageReturn = 13
|
||||
|
||||
function hasBom(buf) {
|
||||
return bom.every((charCode, index) => buf[index] === charCode)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new EventSource object
|
||||
*
|
||||
* @param {string} url the URL to which to connect
|
||||
* @param {Object} [eventSourceInitDict] extra init params. See README for details.
|
||||
* @api public
|
||||
**/
|
||||
function EventSource(url, eventSourceInitDict) {
|
||||
let readyState = EventSource.CONNECTING
|
||||
Object.defineProperty(this, 'readyState', {
|
||||
get() {
|
||||
return readyState
|
||||
},
|
||||
})
|
||||
|
||||
Object.defineProperty(this, 'url', {
|
||||
get() {
|
||||
return url
|
||||
},
|
||||
})
|
||||
|
||||
const self = this
|
||||
self.reconnectInterval = 1000
|
||||
self.connectionInProgress = false
|
||||
|
||||
function onConnectionClosed(message) {
|
||||
if (readyState === EventSource.CLOSED) {
|
||||
return
|
||||
}
|
||||
readyState = EventSource.CONNECTING
|
||||
_emit('error', new Event('error', { message }))
|
||||
|
||||
// The url may have been changed by a temporary
|
||||
// redirect. If that's the case, revert it now.
|
||||
if (reconnectUrl) {
|
||||
url = reconnectUrl
|
||||
reconnectUrl = null
|
||||
}
|
||||
setTimeout(() => {
|
||||
if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {
|
||||
return
|
||||
}
|
||||
self.connectionInProgress = true
|
||||
connect()
|
||||
}, self.reconnectInterval)
|
||||
}
|
||||
|
||||
let request
|
||||
let lastEventId = ''
|
||||
if (eventSourceInitDict && eventSourceInitDict.headers && eventSourceInitDict.headers['Last-Event-ID']) {
|
||||
lastEventId = eventSourceInitDict.headers['Last-Event-ID']
|
||||
delete eventSourceInitDict.headers['Last-Event-ID']
|
||||
}
|
||||
|
||||
let discardTrailingNewline = false
|
||||
let data = ''
|
||||
let eventName = ''
|
||||
|
||||
var reconnectUrl = null
|
||||
|
||||
function connect() {
|
||||
const options = parse(url)
|
||||
let isSecure = options.protocol === 'https:'
|
||||
options.headers = {
|
||||
Accept: 'text/event-stream',
|
||||
...fixedHeaders,
|
||||
}
|
||||
if (lastEventId) {
|
||||
options.headers['Last-Event-ID'] = lastEventId
|
||||
}
|
||||
if (eventSourceInitDict && eventSourceInitDict.headers) {
|
||||
for (const index in eventSourceInitDict.headers) {
|
||||
const header = eventSourceInitDict.headers[index]
|
||||
if (header) {
|
||||
options.headers[index] = header
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`,
|
||||
// but for now exists as a backwards-compatibility layer
|
||||
options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized)
|
||||
|
||||
if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) {
|
||||
options.createConnection = eventSourceInitDict.createConnection
|
||||
}
|
||||
|
||||
// If specify http proxy, make the request to sent to the proxy server,
|
||||
// and include the original url in path and Host headers
|
||||
const useProxy = eventSourceInitDict && eventSourceInitDict.proxy
|
||||
if (useProxy) {
|
||||
const proxy = parse(eventSourceInitDict.proxy)
|
||||
isSecure = proxy.protocol === 'https:'
|
||||
|
||||
options.protocol = isSecure ? 'https:' : 'http:'
|
||||
options.path = url
|
||||
options.headers.Host = options.host
|
||||
options.hostname = proxy.hostname
|
||||
options.host = proxy.host
|
||||
options.port = proxy.port
|
||||
}
|
||||
|
||||
// If https options are specified, merge them into the request options
|
||||
if (eventSourceInitDict && eventSourceInitDict.https) {
|
||||
for (const optName in eventSourceInitDict.https) {
|
||||
if (!httpsOptions.has(optName)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const option = eventSourceInitDict.https[optName]
|
||||
if (option !== undefined) {
|
||||
options[optName] = option
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass this on to the XHR
|
||||
if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) {
|
||||
options.withCredentials = eventSourceInitDict.withCredentials
|
||||
}
|
||||
|
||||
request = (isSecure ? https : http).request(options, res => {
|
||||
self.connectionInProgress = false
|
||||
// Handle HTTP errors
|
||||
if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
|
||||
_emit('error', new Event('error', { status: res.statusCode, message: res.statusMessage }))
|
||||
onConnectionClosed()
|
||||
return
|
||||
}
|
||||
|
||||
// Handle HTTP redirects
|
||||
if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
|
||||
if (!res.headers.location) {
|
||||
// Server sent redirect response without Location header.
|
||||
_emit('error', new Event('error', { status: res.statusCode, message: res.statusMessage }))
|
||||
return
|
||||
}
|
||||
if (res.statusCode === 307) {
|
||||
reconnectUrl = url
|
||||
}
|
||||
url = res.headers.location
|
||||
process.nextTick(connect)
|
||||
return
|
||||
}
|
||||
|
||||
if (res.statusCode !== 200) {
|
||||
_emit('error', new Event('error', { status: res.statusCode, message: res.statusMessage }))
|
||||
return self.close()
|
||||
}
|
||||
|
||||
readyState = EventSource.OPEN
|
||||
res.on('close', () => {
|
||||
res.removeAllListeners('close')
|
||||
res.removeAllListeners('end')
|
||||
onConnectionClosed()
|
||||
})
|
||||
|
||||
res.on('end', () => {
|
||||
res.removeAllListeners('close')
|
||||
res.removeAllListeners('end')
|
||||
onConnectionClosed()
|
||||
})
|
||||
_emit('open', new Event('open'))
|
||||
|
||||
// text/event-stream parser adapted from webkit's
|
||||
// Source/WebCore/page/EventSource.cpp
|
||||
let isFirst = true
|
||||
let buf
|
||||
let startingPosition = 0
|
||||
let startingFieldLength = -1
|
||||
res.on('data', chunk => {
|
||||
buf = buf ? Buffer.concat([buf, chunk]) : chunk
|
||||
if (isFirst && hasBom(buf)) {
|
||||
buf = buf.slice(bom.length)
|
||||
}
|
||||
|
||||
isFirst = false
|
||||
let position = 0
|
||||
const length = buf.length
|
||||
|
||||
while (position < length) {
|
||||
if (discardTrailingNewline) {
|
||||
if (buf[position] === lineFeed) {
|
||||
++position
|
||||
}
|
||||
discardTrailingNewline = false
|
||||
}
|
||||
|
||||
let lineLength = -1
|
||||
let fieldLength = startingFieldLength
|
||||
var c
|
||||
|
||||
for (let index = startingPosition; lineLength < 0 && index < length; ++index) {
|
||||
c = buf[index]
|
||||
if (c === colon) {
|
||||
if (fieldLength < 0) {
|
||||
fieldLength = index - position
|
||||
}
|
||||
} else if (c === carriageReturn) {
|
||||
discardTrailingNewline = true
|
||||
lineLength = index - position
|
||||
} else if (c === lineFeed) {
|
||||
lineLength = index - position
|
||||
}
|
||||
}
|
||||
|
||||
if (lineLength < 0) {
|
||||
startingPosition = length - position
|
||||
startingFieldLength = fieldLength
|
||||
break
|
||||
} else {
|
||||
startingPosition = 0
|
||||
startingFieldLength = -1
|
||||
}
|
||||
|
||||
parseEventStreamLine(buf, position, fieldLength, lineLength)
|
||||
|
||||
position += lineLength + 1
|
||||
}
|
||||
|
||||
if (position === length) {
|
||||
buf = void 0
|
||||
} else if (position > 0) {
|
||||
buf = buf.slice(position)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
request.on('error', error => {
|
||||
self.connectionInProgress = false
|
||||
onConnectionClosed(error.message)
|
||||
})
|
||||
|
||||
if (request.setNoDelay) {
|
||||
request.setNoDelay(true)
|
||||
}
|
||||
request.end()
|
||||
}
|
||||
|
||||
connect()
|
||||
|
||||
function _emit() {
|
||||
if (self.listeners(arguments[0]).length > 0) {
|
||||
self.emit.apply(self, arguments)
|
||||
}
|
||||
}
|
||||
|
||||
this._close = function () {
|
||||
if (readyState === EventSource.CLOSED) {
|
||||
return
|
||||
}
|
||||
readyState = EventSource.CLOSED
|
||||
if (request.abort) {
|
||||
request.abort()
|
||||
}
|
||||
if (request.xhr && request.xhr.abort) {
|
||||
request.xhr.abort()
|
||||
}
|
||||
}
|
||||
|
||||
function parseEventStreamLine(buf, position, fieldLength, lineLength) {
|
||||
if (lineLength === 0) {
|
||||
if (data.length > 0) {
|
||||
const type = eventName || 'message'
|
||||
_emit(
|
||||
type,
|
||||
new MessageEvent(type, {
|
||||
data: data.slice(0, -1), // remove trailing newline
|
||||
lastEventId,
|
||||
origin: original(url),
|
||||
})
|
||||
)
|
||||
data = ''
|
||||
}
|
||||
eventName = void 0
|
||||
} else if (fieldLength > 0) {
|
||||
const noValue = fieldLength < 0
|
||||
let step = 0
|
||||
const field = buf.slice(position, position + (noValue ? lineLength : fieldLength)).toString()
|
||||
|
||||
if (noValue) {
|
||||
step = lineLength
|
||||
} else if (buf[position + fieldLength + 1] !== space) {
|
||||
step = fieldLength + 1
|
||||
} else {
|
||||
step = fieldLength + 2
|
||||
}
|
||||
position += step
|
||||
|
||||
const valueLength = lineLength - step
|
||||
const value = buf.slice(position, position + valueLength).toString()
|
||||
|
||||
if (field === 'data') {
|
||||
data += value + '\n'
|
||||
} else if (field === 'event') {
|
||||
eventName = value
|
||||
} else if (field === 'id') {
|
||||
lastEventId = value
|
||||
} else if (field === 'retry') {
|
||||
const retry = parseInt(value, 10)
|
||||
if (!Number.isNaN(retry)) {
|
||||
self.reconnectInterval = retry
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// module.exports = EventSource
|
||||
|
||||
util.inherits(EventSource, events.EventEmitter)
|
||||
EventSource.prototype.constructor = EventSource // make stacktraces readable
|
||||
;['open', 'error', 'message'].forEach(method => {
|
||||
Object.defineProperty(EventSource.prototype, 'on' + method, {
|
||||
/**
|
||||
* Returns the current listener
|
||||
*
|
||||
* @returns {Mixed} the set function or undefined
|
||||
* @api private
|
||||
*/
|
||||
get: function get() {
|
||||
const listener = this.listeners(method)[0]
|
||||
return listener ? (listener._listener ? listener._listener : listener) : undefined
|
||||
},
|
||||
|
||||
/**
|
||||
* Start listening for events
|
||||
*
|
||||
* @param {Function} listener the listener
|
||||
* @returns {Mixed} the set function or undefined
|
||||
* @api private
|
||||
*/
|
||||
set: function set(listener) {
|
||||
this.removeAllListeners(method)
|
||||
this.addEventListener(method, listener)
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Ready states
|
||||
*/
|
||||
Object.defineProperty(EventSource, 'CONNECTING', { enumerable: true, value: 0 })
|
||||
Object.defineProperty(EventSource, 'OPEN', { enumerable: true, value: 1 })
|
||||
Object.defineProperty(EventSource, 'CLOSED', { enumerable: true, value: 2 })
|
||||
|
||||
EventSource.prototype.CONNECTING = 0
|
||||
EventSource.prototype.OPEN = 1
|
||||
EventSource.prototype.CLOSED = 2
|
||||
|
||||
/**
|
||||
* Closes the connection, if one is made, and sets the readyState attribute to 2 (closed)
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close
|
||||
* @api public
|
||||
*/
|
||||
EventSource.prototype.close = function () {
|
||||
this._close()
|
||||
}
|
||||
|
||||
/**
|
||||
* Emulates the W3C Browser based WebSocket interface using addEventListener.
|
||||
*
|
||||
* @param {string} type A string representing the event type to listen out for
|
||||
* @param {Function} listener callback
|
||||
* @see https://developer.mozilla.org/en/DOM/element.addEventListener
|
||||
* @see http://dev.w3.org/html5/websockets/#the-websocket-interface
|
||||
* @api public
|
||||
*/
|
||||
EventSource.prototype.addEventListener = function addEventListener(type, listener) {
|
||||
if (typeof listener === 'function') {
|
||||
// store a reference so we can return the original function again
|
||||
listener._listener = listener
|
||||
this.on(type, listener)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emulates the W3C Browser based WebSocket interface using dispatchEvent.
|
||||
*
|
||||
* @param {Event} event An event to be dispatched
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
|
||||
* @api public
|
||||
*/
|
||||
EventSource.prototype.dispatchEvent = function dispatchEvent(event) {
|
||||
if (!event.type) {
|
||||
throw new Error('UNSPECIFIED_EVENT_TYPE_ERR')
|
||||
}
|
||||
// if event is instance of an CustomEvent (or has 'details' property),
|
||||
// send the detail object as the payload for the event
|
||||
this.emit(event.type, event.detail)
|
||||
}
|
||||
|
||||
/**
|
||||
* Emulates the W3C Browser based WebSocket interface using removeEventListener.
|
||||
*
|
||||
* @param {string} type A string representing the event type to remove
|
||||
* @param {Function} listener callback
|
||||
* @see https://developer.mozilla.org/en/DOM/element.removeEventListener
|
||||
* @see http://dev.w3.org/html5/websockets/#the-websocket-interface
|
||||
* @api public
|
||||
*/
|
||||
EventSource.prototype.removeEventListener = function removeEventListener(type, listener) {
|
||||
if (typeof listener === 'function') {
|
||||
listener._listener = undefined
|
||||
this.removeListener(type, listener)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* W3C Event
|
||||
*
|
||||
* @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
|
||||
* @api private
|
||||
*/
|
||||
function Event(type, optionalProperties) {
|
||||
Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
|
||||
if (optionalProperties) {
|
||||
for (const f in optionalProperties) {
|
||||
if (optionalProperties.hasOwnProperty(f)) {
|
||||
Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* W3C MessageEvent
|
||||
*
|
||||
* @see http://www.w3.org/TR/webmessaging/#event-definitions
|
||||
* @api private
|
||||
*/
|
||||
function MessageEvent(type, eventInitDict) {
|
||||
Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
|
||||
for (const f in eventInitDict) {
|
||||
if (eventInitDict.hasOwnProperty(f)) {
|
||||
Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
25
client/vscode/src/settings/LocalStorageService.ts
Normal file
25
client/vscode/src/settings/LocalStorageService.ts
Normal file
@ -0,0 +1,25 @@
|
||||
// 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 { Memento } from 'vscode'
|
||||
|
||||
export class LocalStorageService {
|
||||
constructor(private storage: Memento) {}
|
||||
|
||||
public getValue(key: string): string {
|
||||
return this.storage.get<string>(key, '')
|
||||
}
|
||||
|
||||
public async setValue(key: string, value: string): Promise<boolean> {
|
||||
try {
|
||||
await this.storage.update(key, value)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const SELECTED_SEARCH_CONTEXT_SPEC_KEY = 'selected-search-context-spec'
|
||||
export const INSTANCE_VERSION_NUMBER_KEY = 'sourcegraphVersionNumber'
|
||||
export const ANONYMOUS_USER_ID_KEY = 'sourcegraphAnonymousUid'
|
||||
export const DISMISS_SEARCH_CTA_KEY = 'sourcegraphSearchCtaDismissed'
|
||||
20
client/vscode/src/settings/displayWarnings.ts
Normal file
20
client/vscode/src/settings/displayWarnings.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
import { INSTANCE_VERSION_NUMBER_KEY, LocalStorageService } from './LocalStorageService'
|
||||
|
||||
export async function displayWarning(warning: string): Promise<void> {
|
||||
await vscode.window.showErrorMessage(warning)
|
||||
}
|
||||
|
||||
export function displayInstanceVersionWarnings(localStorageService: LocalStorageService): void {
|
||||
const versionNumber = localStorageService.getValue(INSTANCE_VERSION_NUMBER_KEY)
|
||||
if (!versionNumber) {
|
||||
displayWarning('Cannot determine instance version number').catch(() => {})
|
||||
}
|
||||
if (versionNumber < '3320') {
|
||||
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(() => {})
|
||||
}
|
||||
return
|
||||
}
|
||||
@ -1,13 +1,12 @@
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { readConfiguration } from './readConfiguration'
|
||||
|
||||
export function endpointSetting(): string {
|
||||
// has default value
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const url = readConfiguration().get<string>('url')!
|
||||
if (url.endsWith('/')) {
|
||||
return url.slice(0, -1)
|
||||
}
|
||||
return url
|
||||
return removeEndingSlash(url)
|
||||
}
|
||||
|
||||
export function endpointHostnameSetting(): string {
|
||||
@ -25,3 +24,24 @@ export function endpointAccessTokenSetting(): boolean {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function endpointRequestHeadersSetting(): object {
|
||||
return readConfiguration().get<object>('requestHeaders') || {}
|
||||
}
|
||||
|
||||
export async function updateEndpointSetting(newEndpoint: string): Promise<boolean> {
|
||||
const newEndpointURL = removeEndingSlash(newEndpoint)
|
||||
try {
|
||||
await readConfiguration().update('url', newEndpointURL, vscode.ConfigurationTarget.Global)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function removeEndingSlash(uri: string): string {
|
||||
if (uri.endsWith('/')) {
|
||||
return uri.slice(0, -1)
|
||||
}
|
||||
return uri
|
||||
}
|
||||
|
||||
69
client/vscode/src/settings/uninstall.ts
Normal file
69
client/vscode/src/settings/uninstall.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import vscode from 'vscode'
|
||||
|
||||
import { EventSource } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { version } from '../../package.json'
|
||||
import { logEvent } from '../backend/eventLogger'
|
||||
|
||||
import { ANONYMOUS_USER_ID_KEY, LocalStorageService } from './LocalStorageService'
|
||||
|
||||
// This function allows us to watch for uninstall event while still having access to the VS Code API
|
||||
export function watchUninstall(eventSourceType: EventSource, localStorageService: LocalStorageService): void {
|
||||
const extensionName = 'sourcegraph.sourcegraph'
|
||||
try {
|
||||
const extensionPath = vscode.extensions.getExtension(extensionName)?.extensionPath
|
||||
const pathComponents = extensionPath?.split('/').slice(0, -1)
|
||||
const extensionsDirectoryPath = pathComponents?.join('/')
|
||||
// All upgrades, downgrades, and uninstalls will be logged in the .obsolete file
|
||||
pathComponents?.push('.obsolete')
|
||||
const uninstalledPath = pathComponents?.join('/')
|
||||
if (extensionsDirectoryPath && uninstalledPath) {
|
||||
// Watch the .obsolete file - it does not exist when VS Code is started
|
||||
// Check if uninstall has happened when the file was created or when changes are made
|
||||
const watchPattern = new vscode.RelativePattern(extensionsDirectoryPath, '.obsolete')
|
||||
const watchFileListener = vscode.workspace.createFileSystemWatcher(watchPattern)
|
||||
watchFileListener.onDidCreate(() => checkUninstall(uninstalledPath, extensionsDirectoryPath))
|
||||
watchFileListener.onDidChange(() => checkUninstall(uninstalledPath, extensionsDirectoryPath))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('failed to invoke uninstall:', error)
|
||||
}
|
||||
|
||||
/**
|
||||
* Assume the extension has been uninstalled if the count of all the versions listed in
|
||||
* the .obsolete file is equal to the count of all the version-divided directories.
|
||||
* For example, if there are 5 versions of the extension were installed while there
|
||||
* are 4 versions of the extension listed in the .obsolete file pending to be deleted,
|
||||
* it means 1 version of the extension is still installed, therefore no uninstallation
|
||||
* has happened
|
||||
**/
|
||||
function checkUninstall(uninstalledPath: string, extensionsDirectoryPath: string): void {
|
||||
Promise.all([
|
||||
// .obsolete file includes all extensions versions that need to be remove at restart
|
||||
vscode.workspace.fs.readFile(vscode.Uri.file(uninstalledPath)),
|
||||
// Each versions of the extension has its own directory
|
||||
vscode.workspace.fs.readDirectory(vscode.Uri.parse(extensionsDirectoryPath)),
|
||||
])
|
||||
.then(([obsoleteExtensionsRaw, extensionsDirectory]) => {
|
||||
const obsoleteExtensionsCount = Object.keys(JSON.parse(obsoleteExtensionsRaw.toString())).filter(id =>
|
||||
id.includes(extensionName)
|
||||
).length
|
||||
const downloadedExtensionsCount = extensionsDirectory
|
||||
.map(([name]) => name)
|
||||
.filter(id => id.includes(extensionName)).length
|
||||
// Compare count of extension name in .obsolete file vs count of directories with the same extension name
|
||||
if (downloadedExtensionsCount === obsoleteExtensionsCount) {
|
||||
logEvent({
|
||||
event: 'IDEUninstalled',
|
||||
userCookieID: localStorageService.getValue(ANONYMOUS_USER_ID_KEY),
|
||||
referrer: 'VSCE',
|
||||
url: '',
|
||||
source: eventSourceType,
|
||||
argument: JSON.stringify({ editor: 'vscode', version }),
|
||||
publicArgument: JSON.stringify({ editor: 'vscode', version }),
|
||||
})
|
||||
}
|
||||
})
|
||||
.catch(error => console.error(error))
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,11 @@
|
||||
import { cloneDeep } from 'lodash'
|
||||
import { BehaviorSubject, Observable } from 'rxjs'
|
||||
|
||||
import { SearchQueryState } from '@sourcegraph/search'
|
||||
import { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import { AggregateStreamingSearchResults } from '@sourcegraph/shared/src/search/stream'
|
||||
|
||||
import { LocalStorageService, SELECTED_SEARCH_CONTEXT_SPEC_KEY } from './settings/LocalStorageService'
|
||||
|
||||
// State management in the Sourcegraph VS Code extension
|
||||
// -----
|
||||
@ -52,21 +56,23 @@ export type VSCEState = SearchHomeState | SearchResultsState | RemoteBrowsingSta
|
||||
|
||||
export interface SearchHomeState {
|
||||
status: 'search-home'
|
||||
context: CommonContext & {}
|
||||
context: CommonContext
|
||||
}
|
||||
|
||||
export interface SearchResultsState {
|
||||
status: 'search-results'
|
||||
context: CommonContext & {}
|
||||
context: CommonContext & {
|
||||
submittedSearchQueryState: Pick<SearchQueryState, 'queryState' | 'searchCaseSensitivity' | 'searchPatternType'>
|
||||
}
|
||||
}
|
||||
export interface RemoteBrowsingState {
|
||||
status: 'remote-browsing'
|
||||
context: CommonContext & {}
|
||||
context: CommonContext
|
||||
}
|
||||
|
||||
export interface IdleState {
|
||||
status: 'idle'
|
||||
context: CommonContext & {}
|
||||
context: CommonContext
|
||||
}
|
||||
|
||||
export interface ContextInvalidatedState {
|
||||
@ -74,21 +80,66 @@ export interface ContextInvalidatedState {
|
||||
context: CommonContext
|
||||
}
|
||||
|
||||
/**
|
||||
* Subset of SearchQueryState that's necessary and clone-able (`postMessage`) for the VS Code extension.
|
||||
*/
|
||||
export type VSCEQueryState = Pick<SearchQueryState, 'queryState' | 'searchCaseSensitivity' | 'searchPatternType'> | null
|
||||
|
||||
interface CommonContext {
|
||||
authenticatedUser: AuthenticatedUser | null
|
||||
// Whether a search has already been submitted.
|
||||
dirty: boolean
|
||||
|
||||
submittedSearchQueryState: VSCEQueryState
|
||||
|
||||
searchSidebarQueryState: {
|
||||
proposedQueryState: VSCEQueryState
|
||||
/**
|
||||
* The current query state as known to the sidebar.
|
||||
* Used to "anchor" query state updates to the correct state
|
||||
* in case the panel's search query state has changed since
|
||||
* the sidebar event.
|
||||
*
|
||||
* Debt: we don't use this yet.
|
||||
*/
|
||||
currentQueryState: VSCEQueryState
|
||||
}
|
||||
|
||||
searchResults: AggregateStreamingSearchResults | null
|
||||
|
||||
selectedSearchContextSpec: string | undefined
|
||||
}
|
||||
|
||||
const INITIAL_STATE: VSCEState = { status: 'search-home', context: { authenticatedUser: null, dirty: false } }
|
||||
function createInitialState({ localStorageService }: { localStorageService: LocalStorageService }): VSCEState {
|
||||
return {
|
||||
status: 'search-home',
|
||||
context: {
|
||||
authenticatedUser: null,
|
||||
submittedSearchQueryState: null,
|
||||
searchResults: null,
|
||||
selectedSearchContextSpec: localStorageService.getValue(SELECTED_SEARCH_CONTEXT_SPEC_KEY) || undefined,
|
||||
searchSidebarQueryState: {
|
||||
proposedQueryState: null,
|
||||
currentQueryState: null,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Temporary placeholder events. We will replace these with the actual events as we implement the webviews.
|
||||
|
||||
export type VSCEEvent = SearchEvent | TabsEvent | SettingsEvent
|
||||
|
||||
type SearchEvent = { type: 'set_query_state' } | { type: 'submit_search_query' }
|
||||
type SearchEvent =
|
||||
| { type: 'set_query_state' }
|
||||
| {
|
||||
type: 'submit_search_query'
|
||||
submittedSearchQueryState: NonNullable<CommonContext['submittedSearchQueryState']>
|
||||
}
|
||||
| { type: 'received_search_results'; searchResults: AggregateStreamingSearchResults }
|
||||
| { type: 'set_selected_search_context_spec'; spec: string } // TODO see how this handles instance change
|
||||
| { type: 'sidebar_query_update'; proposedQueryState: VSCEQueryState; currentQueryState: VSCEQueryState }
|
||||
|
||||
type TabsEvent =
|
||||
| { type: 'search_panel_disposed' }
|
||||
| { type: 'search_panel_unfocused' }
|
||||
| { type: 'search_panel_focused' }
|
||||
| { type: 'remote_file_focused' }
|
||||
@ -98,8 +149,12 @@ interface SettingsEvent {
|
||||
type: 'sourcegraph_url_change'
|
||||
}
|
||||
|
||||
export function createVSCEStateMachine(): VSCEStateMachine {
|
||||
const states = new BehaviorSubject<VSCEState>(INITIAL_STATE)
|
||||
export function createVSCEStateMachine({
|
||||
localStorageService,
|
||||
}: {
|
||||
localStorageService: LocalStorageService
|
||||
}): VSCEStateMachine {
|
||||
const states = new BehaviorSubject<VSCEState>(createInitialState({ localStorageService }))
|
||||
|
||||
function reducer(state: VSCEState, event: VSCEEvent): VSCEState {
|
||||
// End state.
|
||||
@ -112,7 +167,52 @@ export function createVSCEStateMachine(): VSCEStateMachine {
|
||||
return {
|
||||
status: 'context-invalidated',
|
||||
context: {
|
||||
...INITIAL_STATE.context,
|
||||
...createInitialState({ localStorageService }).context,
|
||||
},
|
||||
}
|
||||
}
|
||||
if (event.type === 'set_selected_search_context_spec') {
|
||||
return {
|
||||
...state,
|
||||
context: {
|
||||
...state.context,
|
||||
selectedSearchContextSpec: event.spec,
|
||||
},
|
||||
} as VSCEState
|
||||
// Type assertion is safe since existing context should be assignable to the existing state.
|
||||
// debt: refactor switch statement to elegantly handle this event safely.
|
||||
}
|
||||
if (event.type === 'sidebar_query_update') {
|
||||
return {
|
||||
...state,
|
||||
context: {
|
||||
...state.context,
|
||||
searchSidebarQueryState: {
|
||||
proposedQueryState: event.proposedQueryState,
|
||||
currentQueryState: event.currentQueryState,
|
||||
},
|
||||
},
|
||||
} as VSCEState
|
||||
// Type assertion is safe since existing context should be assignable to the existing state.
|
||||
// debt: refactor switch statement to elegantly handle this event safely.
|
||||
}
|
||||
if (event.type === 'submit_search_query') {
|
||||
return {
|
||||
status: 'search-results',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: event.submittedSearchQueryState,
|
||||
searchResults: null, // Null out previous results.
|
||||
},
|
||||
}
|
||||
}
|
||||
if (event.type === 'received_search_results' && state.context.submittedSearchQueryState) {
|
||||
return {
|
||||
status: 'search-results',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: state.context.submittedSearchQueryState,
|
||||
searchResults: event.searchResults,
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -121,12 +221,14 @@ export function createVSCEStateMachine(): VSCEStateMachine {
|
||||
case 'search-home':
|
||||
case 'search-results':
|
||||
switch (event.type) {
|
||||
case 'submit_search_query':
|
||||
case 'search_panel_disposed':
|
||||
return {
|
||||
status: 'search-results',
|
||||
...state,
|
||||
status: 'search-home',
|
||||
context: {
|
||||
...state.context,
|
||||
dirty: true,
|
||||
submittedSearchQueryState: null,
|
||||
searchResults: null,
|
||||
},
|
||||
}
|
||||
|
||||
@ -146,12 +248,22 @@ export function createVSCEStateMachine(): VSCEStateMachine {
|
||||
|
||||
case 'remote-browsing':
|
||||
switch (event.type) {
|
||||
case 'search_panel_focused':
|
||||
return {
|
||||
...state,
|
||||
status: state.context.dirty ? 'search-results' : 'search-home',
|
||||
case 'search_panel_focused': {
|
||||
if (state.context.submittedSearchQueryState) {
|
||||
return {
|
||||
status: 'search-results',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: state.context.submittedSearchQueryState,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
status: 'search-home',
|
||||
}
|
||||
}
|
||||
case 'remote_file_unfocused':
|
||||
return {
|
||||
...state,
|
||||
@ -163,11 +275,22 @@ export function createVSCEStateMachine(): VSCEStateMachine {
|
||||
|
||||
case 'idle':
|
||||
switch (event.type) {
|
||||
case 'search_panel_focused':
|
||||
case 'search_panel_focused': {
|
||||
if (state.context.submittedSearchQueryState) {
|
||||
return {
|
||||
status: 'search-results',
|
||||
context: {
|
||||
...state.context,
|
||||
submittedSearchQueryState: state.context.submittedSearchQueryState,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
status: state.context.dirty ? 'search-results' : 'search-home',
|
||||
status: 'search-home',
|
||||
}
|
||||
}
|
||||
|
||||
case 'remote_file_focused':
|
||||
return {
|
||||
|
||||
@ -3,7 +3,14 @@ import vscode from 'vscode'
|
||||
|
||||
import { EndpointPair } from '@sourcegraph/shared/src/platform/context'
|
||||
|
||||
import { generateUUID, isNestedConnection, isProxyMarked, NestedConnectionData, RelationshipType } from '.'
|
||||
import {
|
||||
generateUUID,
|
||||
isNestedConnection,
|
||||
isProxyMarked,
|
||||
isUnsubscribable,
|
||||
NestedConnectionData,
|
||||
RelationshipType,
|
||||
} from '.'
|
||||
|
||||
// Used to scope message to panel (and `connectionId` further scopes to function call).
|
||||
let nextPanelId = 1
|
||||
@ -44,6 +51,10 @@ export function createEndpointsForWebview(
|
||||
nextPanelId++
|
||||
let disposed = false
|
||||
|
||||
// Keep track of proxied unsubscribables to clean up when a webview is closed. In that case,
|
||||
// the webview will likely be unable to send an unsubscribe message.
|
||||
const proxiedUnsubscribables = new Set<{ unsubscribe: () => unknown }>()
|
||||
|
||||
/**
|
||||
* Handles values sent to webviews that are marked to be proxied.
|
||||
*/
|
||||
@ -53,6 +64,11 @@ export function createEndpointsForWebview(
|
||||
// send it "over the wire"
|
||||
delete value.proxyMarkedValue
|
||||
|
||||
if (isUnsubscribable(proxyMarkedValue)) {
|
||||
proxiedUnsubscribables.add(proxyMarkedValue)
|
||||
// Debt: ideally remove unsubscribable from set when we receive a unsubscribe message.
|
||||
}
|
||||
|
||||
const endpoint = createEndpoint(value.nestedConnectionId)
|
||||
Comlink.expose(proxyMarkedValue, endpoint)
|
||||
}
|
||||
@ -114,6 +130,10 @@ export function createEndpointsForWebview(
|
||||
panel.onDidDispose(() => {
|
||||
disposed = true
|
||||
endpointFactories.delete(panelId)
|
||||
|
||||
for (const unsubscribable of proxiedUnsubscribables) {
|
||||
unsubscribable.unsubscribe()
|
||||
}
|
||||
})
|
||||
|
||||
const webviewEndpoint = createEndpoint('webview')
|
||||
|
||||
@ -50,3 +50,7 @@ export function isNestedConnection(value: unknown): value is NestedConnectionDat
|
||||
export function isProxyMarked(value: unknown): value is Comlink.ProxyMarked {
|
||||
return isObject(value) && (value as Comlink.ProxyMarked)[Comlink.proxyMarker]
|
||||
}
|
||||
|
||||
export function isUnsubscribable(value: object): value is { unsubscribe: () => unknown } {
|
||||
return hasProperty('unsubscribe')(value) && typeof value.unsubscribe === 'function'
|
||||
}
|
||||
|
||||
@ -1,56 +1,80 @@
|
||||
import { Observable } from 'rxjs'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { initializeSourcegraphSettings } from '../backend/sourcegraphSettings'
|
||||
import { ExtensionCoreAPI } from '../contract'
|
||||
import { LATEST_VERSION } from '@sourcegraph/shared/src/search/stream'
|
||||
|
||||
import { initializeSearchPanelWebview, initializeSearchSidebarWebview } from './initialize'
|
||||
import { initializeSourcegraphSettings } from '../backend/sourcegraphSettings'
|
||||
import { initializeCodeIntel } from '../code-intel/initialize'
|
||||
import { ExtensionCoreAPI } from '../contract'
|
||||
import { SourcegraphFileSystemProvider } from '../file-system/SourcegraphFileSystemProvider'
|
||||
import { SearchPatternType } from '../graphql-operations'
|
||||
|
||||
import {
|
||||
initializeHelpSidebarWebview,
|
||||
initializeSearchPanelWebview,
|
||||
initializeSearchSidebarWebview,
|
||||
} from './initialize'
|
||||
|
||||
// Track current active webview panel to make sure only one panel exists at a time
|
||||
let currentSearchPanel: vscode.WebviewPanel | 'initializing' | undefined
|
||||
let searchSidebarWebviewView: vscode.WebviewView | 'initializing' | undefined
|
||||
|
||||
export function registerWebviews({
|
||||
context,
|
||||
extensionCoreAPI,
|
||||
initializedPanelIDs,
|
||||
sourcegraphSettings,
|
||||
fs,
|
||||
instanceURL,
|
||||
}: {
|
||||
context: vscode.ExtensionContext
|
||||
extensionCoreAPI: ExtensionCoreAPI
|
||||
initializedPanelIDs: Observable<string>
|
||||
sourcegraphSettings: ReturnType<typeof initializeSourcegraphSettings>
|
||||
fs: SourcegraphFileSystemProvider
|
||||
instanceURL: string
|
||||
}): void {
|
||||
// Track current active webview panel to make sure only one panel exists at a time
|
||||
let currentActiveWebviewPanel: vscode.WebviewPanel | undefined
|
||||
let searchSidebarWebviewView: vscode.WebviewView | undefined
|
||||
|
||||
// TODO if remote files are open from previous session, we need
|
||||
// to focus search sidebar to activate code intel (load extension host),
|
||||
// and to do that we need to make sourcegraph:// file opening an activation event.
|
||||
// to focus search sidebar to activate code intel (load extension host)
|
||||
|
||||
// Open Sourcegraph search tab on `sourcegraph.search` command.
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.search', async () => {
|
||||
// If text selected, submit search for it. Capture selection first.
|
||||
const activeEditor = vscode.window.activeTextEditor
|
||||
const selection = activeEditor?.selection
|
||||
const selectedQuery = activeEditor?.document.getText(selection)
|
||||
|
||||
// Focus search sidebar in case this command was the activation event,
|
||||
// as opposed to visibiilty of sidebar.
|
||||
if (!searchSidebarWebviewView) {
|
||||
focusSearchSidebar()
|
||||
}
|
||||
|
||||
if (currentActiveWebviewPanel) {
|
||||
currentActiveWebviewPanel.reveal()
|
||||
} else {
|
||||
if (currentSearchPanel && currentSearchPanel !== 'initializing') {
|
||||
currentSearchPanel.reveal()
|
||||
} else if (!currentSearchPanel) {
|
||||
sourcegraphSettings.refreshSettings()
|
||||
|
||||
const { webviewPanel } = await initializeSearchPanelWebview({
|
||||
currentSearchPanel = 'initializing'
|
||||
|
||||
const { webviewPanel, searchPanelAPI } = await initializeSearchPanelWebview({
|
||||
extensionUri: context.extensionUri,
|
||||
extensionCoreAPI,
|
||||
initializedPanelIDs,
|
||||
})
|
||||
|
||||
currentActiveWebviewPanel = webviewPanel
|
||||
currentSearchPanel = webviewPanel
|
||||
|
||||
webviewPanel.onDidChangeViewState(() => {
|
||||
if (webviewPanel.active) {
|
||||
extensionCoreAPI.emit({ type: 'search_panel_focused' })
|
||||
focusSearchSidebar()
|
||||
searchPanelAPI.focusSearchBox().catch(() => {})
|
||||
}
|
||||
|
||||
if (webviewPanel.visible) {
|
||||
searchPanelAPI.focusSearchBox().catch(() => {})
|
||||
}
|
||||
|
||||
if (!webviewPanel.visible) {
|
||||
@ -60,12 +84,24 @@ export function registerWebviews({
|
||||
})
|
||||
|
||||
webviewPanel.onDidDispose(() => {
|
||||
currentActiveWebviewPanel = undefined
|
||||
currentSearchPanel = undefined
|
||||
// Ideally focus last used sidebar tab on search panel close. In lieu of that (for v1),
|
||||
// just focus the file explorer if the search sidebar is currently focused.
|
||||
if (searchSidebarWebviewView?.visible) {
|
||||
if (searchSidebarWebviewView !== 'initializing' && searchSidebarWebviewView?.visible) {
|
||||
focusFileExplorer()
|
||||
}
|
||||
// Clear search result
|
||||
extensionCoreAPI.emit({ type: 'search_panel_disposed' })
|
||||
})
|
||||
}
|
||||
|
||||
if (selectedQuery) {
|
||||
extensionCoreAPI.streamSearch(selectedQuery, {
|
||||
patternType: SearchPatternType.literal,
|
||||
caseSensitive: false,
|
||||
version: LATEST_VERSION,
|
||||
trace: undefined,
|
||||
sourcegraphURL: instanceURL,
|
||||
})
|
||||
}
|
||||
})
|
||||
@ -77,7 +113,7 @@ export function registerWebviews({
|
||||
{
|
||||
// This typically will be called only once since `retainContextWhenHidden` is set to `true`.
|
||||
resolveWebviewView: (webviewView, _context, _token) => {
|
||||
initializeSearchSidebarWebview({
|
||||
const { searchSidebarAPI } = initializeSearchSidebarWebview({
|
||||
extensionUri: context.extensionUri,
|
||||
extensionCoreAPI,
|
||||
webviewView,
|
||||
@ -86,6 +122,8 @@ export function registerWebviews({
|
||||
// Initialize search panel.
|
||||
openSearchPanelCommand()
|
||||
|
||||
initializeCodeIntel({ context, fs, searchSidebarAPI })
|
||||
|
||||
// Bring search panel back if it was previously closed on sidebar visibility change
|
||||
webviewView.onDidChangeVisibility(() => {
|
||||
if (webviewView.visible) {
|
||||
@ -97,6 +135,39 @@ export function registerWebviews({
|
||||
{ webviewOptions: { retainContextWhenHidden: true } }
|
||||
)
|
||||
)
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerWebviewViewProvider(
|
||||
'sourcegraph.helpSidebar',
|
||||
{
|
||||
// This typically will be called only once since `retainContextWhenHidden` is set to `true`.
|
||||
resolveWebviewView: (webviewView, _context, _token) => {
|
||||
initializeHelpSidebarWebview({
|
||||
extensionUri: context.extensionUri,
|
||||
extensionCoreAPI,
|
||||
webviewView,
|
||||
})
|
||||
},
|
||||
},
|
||||
{ webviewOptions: { retainContextWhenHidden: true } }
|
||||
)
|
||||
)
|
||||
|
||||
// Clone Remote Git Repos Locally using VS Code Git API
|
||||
// https://github.com/microsoft/vscode/issues/48428
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand('sourcegraph.gitClone', async () => {
|
||||
const editor = vscode.window.activeTextEditor
|
||||
if (!editor) {
|
||||
throw new Error('No active editor')
|
||||
}
|
||||
const uri = editor.document.uri.path
|
||||
const gitUrl = `https:/${uri.split('@')[0]}.git`
|
||||
const vsCodeCloneUrl = `vscode://vscode.git/clone?url=${gitUrl}`
|
||||
await vscode.env.openExternal(vscode.Uri.parse(vsCodeCloneUrl))
|
||||
// vscode://vscode.git/clone?url=${gitUrl}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function openSearchPanelCommand(): void {
|
||||
@ -117,6 +188,12 @@ function focusSearchSidebar(): void {
|
||||
)
|
||||
}
|
||||
|
||||
export function focusSearchPanel(): void {
|
||||
if (currentSearchPanel && currentSearchPanel !== 'initializing') {
|
||||
currentSearchPanel.reveal()
|
||||
}
|
||||
}
|
||||
|
||||
function focusFileExplorer(): void {
|
||||
vscode.commands.executeCommand('workbench.view.explorer').then(
|
||||
() => {},
|
||||
|
||||
182
client/vscode/src/webview/forkedBranded.scss
Normal file
182
client/vscode/src/webview/forkedBranded.scss
Normal file
@ -0,0 +1,182 @@
|
||||
@import '../../../branded/src/global-styles/colors.scss';
|
||||
@import '../../../branded/src/global-styles/border-radius.scss';
|
||||
|
||||
// Bootstrap configuration before Bootstrap is imported
|
||||
$border-radius: var(--border-radius);
|
||||
$border-radius-sm: var(--border-radius);
|
||||
$border-radius-lg: var(--border-radius);
|
||||
$popover-border-radius: var(--popover-border-radius);
|
||||
|
||||
$font-size-base: 0.875rem;
|
||||
$line-height-base: (20/14);
|
||||
|
||||
$box-shadow: var(--box-shadow);
|
||||
|
||||
$grid-gutter-width: 1.5rem;
|
||||
|
||||
// No max width except for xl.
|
||||
$container-max-widths: (
|
||||
xl: 1140px,
|
||||
);
|
||||
|
||||
$border-color: var(--border-color);
|
||||
|
||||
// Links
|
||||
|
||||
$link-color: var(--link-color);
|
||||
$link-hover-color: var(--link-hover-color);
|
||||
|
||||
// Forms
|
||||
|
||||
$form-check-input-margin-y: var(--form-check-input-margin-y);
|
||||
$form-feedback-font-size: 0.75rem;
|
||||
$input-btn-focus-width: 2px;
|
||||
// The default focus ring for buttons is very hard to see, raise opacity.
|
||||
// We only show the focus ring when using the keyboard, when the focus ring
|
||||
// should be clearly visible.
|
||||
$btn-focus-box-shadow: var(--focus-box-shadow);
|
||||
$btn-link-disabled-color: var(--btn-link-disabled-color);
|
||||
$btn-padding-y-sm: var(--btn-padding-y-sm);
|
||||
|
||||
// Forms don't manipulate the colors at compile time,
|
||||
// which is why we can use CSS variables for theming here
|
||||
// That's nice because the forms theming CSS would otherwise
|
||||
// be way more complex than it is for other components
|
||||
$input-bg: var(--input-bg);
|
||||
$input-disabled-bg: var(--input-disabled-bg);
|
||||
$input-border-color: var(--input-border-color);
|
||||
$input-color: var(--input-color);
|
||||
$input-placeholder-color: var(--input-placeholder-color);
|
||||
$input-group-addon-color: var(--input-group-addon-color);
|
||||
$input-group-addon-bg: var(--input-group-addon-bg);
|
||||
$input-group-addon-border-color: var(--input-group-addon-border-color);
|
||||
$input-focus-border-color: var(--input-focus-border-color);
|
||||
$input-focus-box-shadow: var(--input-focus-box-shadow);
|
||||
|
||||
// Custom Selects
|
||||
$custom-select-bg-size: 16px 16px;
|
||||
$custom-select-disabled-bg: var(--input-disabled-bg);
|
||||
$custom-select-focus-box-shadow: var(--input-focus-box-shadow);
|
||||
// Icon: mdi-react/ChevronDownIcon
|
||||
$custom-select-indicator: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' fill='#{$gray-06}' viewBox='0 0 24 24'><path d='M7.41 8.58L12 13.17l4.59-4.59L18 10l-6 6-6-6 1.41-1.42z'/></svg>");
|
||||
// Hide feedback icon for custom-select
|
||||
$custom-select-feedback-icon-size: 0;
|
||||
|
||||
// Dropdown
|
||||
$dropdown-bg: var(--dropdown-bg);
|
||||
$dropdown-border-color: var(--dropdown-border-color);
|
||||
$dropdown-divider-bg: var(--border-color);
|
||||
$dropdown-link-color: var(--body-color);
|
||||
$dropdown-link-hover-color: var(--body-color);
|
||||
$dropdown-link-hover-bg: var(--dropdown-link-hover-bg);
|
||||
$dropdown-link-active-color: #ffffff;
|
||||
$dropdown-link-active-bg: var(--primary);
|
||||
$dropdown-link-disabled-color: var(--text-muted);
|
||||
$dropdown-header-color: var(--dropdown-header-color);
|
||||
$dropdown-item-padding-y: 0.25rem;
|
||||
$dropdown-item-padding-x: 0.5rem;
|
||||
$dropdown-padding-y: $dropdown-item-padding-y;
|
||||
|
||||
// Tables
|
||||
|
||||
$table-cell-padding: 0.625rem;
|
||||
$table-border-color: var(--border-color);
|
||||
|
||||
$hr-border-color: var(--border-color);
|
||||
$hr-margin-y: 0.25rem;
|
||||
|
||||
// Disable transitions
|
||||
$input-transition: none;
|
||||
|
||||
// Spacer
|
||||
$spacer: 1rem;
|
||||
|
||||
:root {
|
||||
--spacer: #{$spacer};
|
||||
}
|
||||
|
||||
// Apply static variables before Bootstrap imports.
|
||||
@import 'bootstrap/scss/functions';
|
||||
@import 'bootstrap/scss/variables';
|
||||
@import 'bootstrap/scss/mixins';
|
||||
@import 'bootstrap/scss/reboot';
|
||||
@import 'bootstrap/scss/utilities';
|
||||
@import 'bootstrap/scss/grid';
|
||||
@import 'bootstrap/scss/transitions';
|
||||
|
||||
// Modified in `./buttons.scss`
|
||||
@import 'bootstrap/scss/buttons';
|
||||
|
||||
// Modified in `./forms.scss`
|
||||
@import 'bootstrap/scss/forms';
|
||||
@import 'bootstrap/scss/custom-forms';
|
||||
@import 'bootstrap/scss/input-group';
|
||||
|
||||
// Global styles provided by @reach packages. Should be imported once in the global scope.
|
||||
@import '@reach/tabs/styles';
|
||||
|
||||
@import 'wildcard/src/global-styles/breakpoints';
|
||||
@import 'shared/src/global-styles/icons';
|
||||
@import '../../../branded/src/global-styles/background';
|
||||
@import '../../../branded/src/global-styles/dropdown';
|
||||
@import '../../../branded/src/global-styles/meter';
|
||||
@import '../../../branded/src/global-styles/popover';
|
||||
@import '../../../branded/src/global-styles/nav';
|
||||
@import '../../../branded/src/global-styles/list-group';
|
||||
@import '../../../branded/src/global-styles/typography';
|
||||
@import '../../../branded/src/global-styles/tables';
|
||||
@import '../../../branded/src/global-styles/code';
|
||||
@import '../../../branded/src/global-styles/buttons';
|
||||
@import '../../../branded/src/global-styles/button-group';
|
||||
@import '../../../branded/src/global-styles/forms';
|
||||
@import '../../../branded/src/global-styles/tabs';
|
||||
@import '../../../branded/src/global-styles/progress';
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
// Our simple popovers only need these styles. We don't want the caret or special font sizes from
|
||||
// Bootstrap's popover CSS.
|
||||
.popover-inner {
|
||||
background-color: var(--color-bg-1);
|
||||
border: solid 1px var(--border-color);
|
||||
box-shadow: var(--dropdown-shadow);
|
||||
border-radius: var(--popover-border-radius);
|
||||
// Ensure content is clipped by border
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
// Show a focus ring when performing keyboard navigation. Uses the polyfill at
|
||||
// https://github.com/WICG/focus-visible because few browsers support :focus-visible.
|
||||
:focus:not(:focus-visible) {
|
||||
outline: none;
|
||||
}
|
||||
:focus-visible {
|
||||
outline: 0;
|
||||
box-shadow: var(--focus-box-shadow);
|
||||
}
|
||||
|
||||
.cursor-pointer,
|
||||
input[type='radio'],
|
||||
input[type='checkbox'] {
|
||||
&:not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
// Replace the old '../../../branded/src/global-styles/card' file
|
||||
$card-spacer-y: 0.5rem;
|
||||
$card-spacer-x: 0.5rem;
|
||||
$card-bg: var(--card-bg);
|
||||
$card-border-color: var(--card-border-color);
|
||||
$card-cap-bg: var(--color-bg-2);
|
||||
|
||||
.card {
|
||||
--card-bg: var(--color-bg-1);
|
||||
--card-border-color: var(--border-color);
|
||||
--card-spacer-y: #{$card-spacer-y};
|
||||
--card-spacer-x: #{$card-spacer-x};
|
||||
}
|
||||
|
||||
@import 'bootstrap/scss/card';
|
||||
@ -1,10 +1,75 @@
|
||||
@import '../../../branded/src/global-styles/index.scss';
|
||||
@import './forkedBranded.scss';
|
||||
@import './theming/highlight.scss';
|
||||
@import './theming/monaco.scss';
|
||||
@import '~@vscode/codicons/dist/codicon.css';
|
||||
|
||||
:root {
|
||||
--border-color: rgba(0, 0, 0, 0.125);
|
||||
--mark-bg: var(--mark-bg-light);
|
||||
// v2/debt: redefine our CSS variables using VS Code's CSS variables
|
||||
// instead of hackily overriding the necessary classes' properties.
|
||||
.theme-light,
|
||||
.theme-dark {
|
||||
--body-color: var(--vscode-foreground);
|
||||
--code-bg: var(--vscode-editor-background);
|
||||
--color-bg-1: var(--vscode-editor-background);
|
||||
--color-bg-2: var(--vscode-editorWidget-background);
|
||||
|
||||
--border-color: var(--vscode-editor-lineHighlightBorder);
|
||||
--border-color-2: var(--vscode-editor-lineHighlightBorder);
|
||||
|
||||
// VS Code themes cannot change border radius, so we can safely hardcode it.
|
||||
--border-radius: 0;
|
||||
--popover-border-radius: 0;
|
||||
|
||||
--dropdown-bg: var(--vscode-dropdown-background);
|
||||
--dropdown-border-color: var(--vscode-dropdown-border);
|
||||
--dropdown-header-color: var(--vscode-panelTitle-activeForeground);
|
||||
|
||||
.dropdown-menu {
|
||||
--body-color: var(--vscode-dropdown-foreground);
|
||||
--primary: var(--vscode-textLink-foreground); // hover background
|
||||
--color-bg-3: var(--color-bg-3); // active background
|
||||
|
||||
& input {
|
||||
background-color: var(--vscode-input-background) !important;
|
||||
}
|
||||
}
|
||||
|
||||
--input-bg: var(--vscode-editorWidget-background);
|
||||
--input-border-color: var(--vscode-input-border);
|
||||
--border-active-color: var(--vscode-focusBorder);
|
||||
--link-color: var(--vscode-textLink-foreground);
|
||||
--search-filter-keyword-color: var(--vscode-textLink-foreground);
|
||||
--body-bg: var(--vscode-editor-background);
|
||||
--text-muted: var(--vscode-descriptionForeground);
|
||||
--primary: var(--vscode-button-background);
|
||||
|
||||
// Debt: alert overrides
|
||||
--info-3: var(--vscode-inputValidation-infoBorder);
|
||||
--danger: var(--vscode-inputValidation-errorBackground);
|
||||
}
|
||||
|
||||
.theme-dark {
|
||||
.sourcegraph-tooltip {
|
||||
--tooltip-bg: var(--vscode-input-background);
|
||||
--tooltip-color: var(--vscode-editorWidget-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.theme-light {
|
||||
// Ensure tooltip always has a dark background with light text.
|
||||
.sourcegraph-tooltip {
|
||||
--tooltip-bg: var(--vscode-editorWidget-foreground);
|
||||
--tooltip-color: var(--vscode-input-background);
|
||||
}
|
||||
}
|
||||
|
||||
--max-homepage-container-width: 65rem;
|
||||
|
||||
// Media breakpoints
|
||||
--media-sm: 576px;
|
||||
--media-md: 768px;
|
||||
--media-lg: 992px;
|
||||
--media-xl: 1200px;
|
||||
}
|
||||
|
||||
// stylelint-disable-next-line selector-max-id
|
||||
@ -14,49 +79,25 @@ body,
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.selection-highlight,
|
||||
.selection-highlight-sticky {
|
||||
background-color: var(--mark-bg);
|
||||
}
|
||||
|
||||
// Used for <MonacoQueryInput/>
|
||||
.flex-shrink-past-contents {
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
small {
|
||||
color: var(--vscode-foreground) !important;
|
||||
}
|
||||
|
||||
// Adapt to VS Code appearance.
|
||||
body {
|
||||
background-color: transparent;
|
||||
// color: var(--vscode-textPreformat-foreground);
|
||||
font-family: var(--vscode-font-family);
|
||||
font-weight: var(--vscode-font-weight);
|
||||
font-size: var(--vscode-font-size);
|
||||
font-size: var(--vscode-editor-font-size);
|
||||
--body-color: var(--vscode-dropdown-foreground);
|
||||
|
||||
&.search-sidebar {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--vscode-editor-font-family) !important;
|
||||
font-weight: var(--vscode-editor-font-weight) !important;
|
||||
font-size: var(--vscode-editor-font-size) !important;
|
||||
color: var(--vscode-editor-foreground) !important;
|
||||
}
|
||||
|
||||
input {
|
||||
background-color: var(--vscode-input-background) !important;
|
||||
}
|
||||
|
||||
a,
|
||||
.btn-link,
|
||||
.btm-link-sm {
|
||||
color: var(--vscode-textLink-foreground) !important;
|
||||
color: var(--vscode-editor-foreground);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: var(--vscode-button-background) !important;
|
||||
color: var(--vscode-button-foreground) !important;
|
||||
|
||||
&:hover {
|
||||
@ -68,41 +109,21 @@ a,
|
||||
}
|
||||
}
|
||||
|
||||
.textarea {
|
||||
background-color: var(--vscode-input-background) !important;
|
||||
}
|
||||
|
||||
.cta-card {
|
||||
background-color: var(--vscode-textCodeBlock-background) !important;
|
||||
}
|
||||
|
||||
.mtk13 {
|
||||
color: var(--vscode-textLink-foreground) !important;
|
||||
}
|
||||
|
||||
.search-filter-keyword {
|
||||
color: var(--vscode-textLink-foreground) !important;
|
||||
|
||||
&:hover {
|
||||
color: var(--vscode-button-background) !important;
|
||||
background-color: var(--vscode-button-foreground) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.text {
|
||||
color: var(--vscode-foreground);
|
||||
.btn-text-link {
|
||||
color: var(--vscode-textLink-foreground);
|
||||
padding: 0;
|
||||
font-weight: var(--vscode-editor-font-weight) !important;
|
||||
font-size: var(--vscode-editor-font-size) !important;
|
||||
}
|
||||
|
||||
.vsce-text {
|
||||
color: var(--vscode-foreground);
|
||||
font-size: var(--vscode-editor-font-size) !important;
|
||||
}
|
||||
.input,
|
||||
.form-control {
|
||||
background-color: var(--vscode-input-background);
|
||||
color: var(--vscode-input-foreground);
|
||||
padding: 0.5rem;
|
||||
|
||||
.btn-outline-secondary {
|
||||
color: var(--vscode-foreground) !important;
|
||||
|
||||
&:hover {
|
||||
background: transparent !important;
|
||||
&:focus {
|
||||
background-color: var(--vscode-input-background);
|
||||
color: var(--vscode-input-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,7 +3,8 @@ import { Observable } from 'rxjs'
|
||||
import { filter, first } from 'rxjs/operators'
|
||||
import * as vscode from 'vscode'
|
||||
|
||||
import { ExtensionCoreAPI, SearchPanelAPI, SearchSidebarAPI } from '../contract'
|
||||
import { ExtensionCoreAPI, HelpSidebarAPI, SearchPanelAPI, SearchSidebarAPI } from '../contract'
|
||||
import { endpointSetting } from '../settings/endpointSetting'
|
||||
|
||||
import { createEndpointsForWebview } from './comlink/extensionEndpoint'
|
||||
|
||||
@ -25,6 +26,7 @@ export async function initializeSearchPanelWebview({
|
||||
const panel = vscode.window.createWebviewPanel('sourcegraphSearch', 'Sourcegraph', vscode.ViewColumn.One, {
|
||||
enableScripts: true,
|
||||
retainContextWhenHidden: true,
|
||||
enableFindWidget: true,
|
||||
localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'dist', 'webview')],
|
||||
})
|
||||
|
||||
@ -33,6 +35,7 @@ export async function initializeSearchPanelWebview({
|
||||
const scriptSource = panel.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'searchPanel.js'))
|
||||
const cssModuleSource = panel.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'searchPanel.css'))
|
||||
const styleSource = panel.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'style.css'))
|
||||
const codiconFontSource = panel.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'codicon.ttf'))
|
||||
|
||||
const { proxy, expose, panelId } = createEndpointsForWebview(panel)
|
||||
|
||||
@ -57,19 +60,30 @@ export async function initializeSearchPanelWebview({
|
||||
|
||||
// Apply Content-Security-Policy
|
||||
// panel.webview.cspSource comes from the webview object
|
||||
// debt: load codicon ourselves.
|
||||
panel.webview.html = `<!DOCTYPE html>
|
||||
<html lang="en" data-panel-id="${panelId}">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data: vscode-resource: vscode-webview: https:; script-src 'nonce-${nonce}' vscode-webview:; style-src data: ${
|
||||
<style nonce="${nonce}">
|
||||
@font-face {
|
||||
font-family: 'codicon';
|
||||
src: url(${codiconFontSource.toString()})
|
||||
}
|
||||
</style>
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; child-src data: ${
|
||||
panel.webview.cspSource
|
||||
}; img-src data: vscode-resource: https:; script-src 'nonce-${nonce}'; style-src data: ${
|
||||
panel.webview.cspSource
|
||||
} vscode-resource: vscode-webview: 'unsafe-inline' http: https: data:; connect-src 'self' vscode-webview: http: https:; frame-src https:; font-src: https: vscode-resource: vscode-webview:;">
|
||||
} vscode-resource: 'unsafe-inline' http: https: data:; connect-src 'self' http: https:; frame-src https:; font-src ${
|
||||
panel.webview.cspSource
|
||||
};">
|
||||
<title>Sourcegraph Search</title>
|
||||
<link rel="stylesheet" href="${styleSource.toString()}" />
|
||||
<link rel="stylesheet" href="${cssModuleSource.toString()}" />
|
||||
</head>
|
||||
<body>
|
||||
<body class="search-panel">
|
||||
<div id="root" />
|
||||
<script nonce="${nonce}" src="${scriptSource.toString()}"></script>
|
||||
</body>
|
||||
@ -95,6 +109,7 @@ export function initializeSearchSidebarWebview({
|
||||
} {
|
||||
webviewView.webview.options = {
|
||||
enableScripts: true,
|
||||
localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'dist', 'webview')],
|
||||
}
|
||||
|
||||
const webviewPath = vscode.Uri.joinPath(extensionUri, 'dist', 'webview')
|
||||
@ -102,6 +117,7 @@ export function initializeSearchSidebarWebview({
|
||||
const scriptSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'searchSidebar.js'))
|
||||
const cssModuleSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'searchSidebar.css'))
|
||||
const styleSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'style.css'))
|
||||
const codiconFontSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'codicon.ttf'))
|
||||
|
||||
const { proxy, expose, panelId } = createEndpointsForWebview(webviewView)
|
||||
|
||||
@ -111,26 +127,31 @@ export function initializeSearchSidebarWebview({
|
||||
// Expose the Sourcegraph VS Code Extension API to the Webview.
|
||||
Comlink.expose(extensionCoreAPI, expose)
|
||||
|
||||
// Specific scripts to run using nonce
|
||||
const nonce = getNonce()
|
||||
|
||||
// Apply Content-Security-Policy
|
||||
// panel.webview.cspSource comes from the webview object
|
||||
// debt: load codicon ourselves.
|
||||
webviewView.webview.html = `<!DOCTYPE html>
|
||||
<html lang="en" data-panel-id="${panelId}">
|
||||
<html lang="en" data-panel-id="${panelId}" data-instance-url=${endpointSetting()}>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data: vscode-webview: vscode-resource: https:; script-src 'nonce-${nonce}' vscode-webview:; style-src data: ${
|
||||
<style>
|
||||
@font-face {
|
||||
font-family: 'codicon';
|
||||
src: url(${codiconFontSource.toString()})
|
||||
}
|
||||
</style>
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; child-src data: ${
|
||||
webviewView.webview.cspSource
|
||||
}; worker-src blob: data:; img-src data: https:; script-src blob: https:; style-src 'unsafe-inline' ${
|
||||
webviewView.webview.cspSource
|
||||
} vscode-resource: http: https: data:; connect-src 'self' http: https:; font-src: https: vscode-resource: vscode-webview:;">
|
||||
} http: https: data:; connect-src 'self' http: https:; font-src vscode-resource: blob: https:;">
|
||||
<title>Sourcegraph Search</title>
|
||||
<link rel="stylesheet" href="${styleSource.toString()}" />
|
||||
<link rel="stylesheet" href="${cssModuleSource.toString()}" />
|
||||
</head>
|
||||
<body>
|
||||
<body class="search-sidebar">
|
||||
<div id="root" />
|
||||
<script nonce="${nonce}" src="${scriptSource.toString()}"></script>
|
||||
<script src="${scriptSource.toString()}"></script>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
@ -139,6 +160,57 @@ export function initializeSearchSidebarWebview({
|
||||
}
|
||||
}
|
||||
|
||||
export function initializeHelpSidebarWebview({
|
||||
extensionUri,
|
||||
extensionCoreAPI,
|
||||
webviewView,
|
||||
}: SourcegraphWebviewConfig & {
|
||||
webviewView: vscode.WebviewView
|
||||
}): {
|
||||
helpSidebarAPI: Comlink.Remote<HelpSidebarAPI>
|
||||
} {
|
||||
webviewView.webview.options = {
|
||||
enableScripts: true,
|
||||
localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'dist', 'webview')],
|
||||
}
|
||||
|
||||
const webviewPath = vscode.Uri.joinPath(extensionUri, 'dist', 'webview')
|
||||
|
||||
const scriptSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'helpSidebar.js'))
|
||||
const cssModuleSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'helpSidebar.css'))
|
||||
const styleSource = webviewView.webview.asWebviewUri(vscode.Uri.joinPath(webviewPath, 'style.css'))
|
||||
|
||||
const { proxy, expose, panelId } = createEndpointsForWebview(webviewView)
|
||||
|
||||
// Get a proxy for the Sourcegraph Webview API to communicate with the Webview.
|
||||
const helpSidebarAPI = Comlink.wrap<HelpSidebarAPI>(proxy)
|
||||
|
||||
// Expose the Sourcegraph VS Code Extension API to the Webview.
|
||||
Comlink.expose(extensionCoreAPI, expose)
|
||||
|
||||
// Apply Content-Security-Policy
|
||||
webviewView.webview.html = `<!DOCTYPE html>
|
||||
<html lang="en" data-panel-id="${panelId}" >
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data: https:; font-src ${
|
||||
webviewView.webview.cspSource
|
||||
}; style-src ${webviewView.webview.cspSource}; script-src ${webviewView.webview.cspSource};">
|
||||
<title>Help and Feedback</title>
|
||||
<link rel="stylesheet" href="${styleSource.toString()}" />
|
||||
<link rel="stylesheet" href="${cssModuleSource.toString()}" />
|
||||
</head>
|
||||
<div id="root" />
|
||||
<script src="${scriptSource.toString()}"></script>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
return {
|
||||
helpSidebarAPI,
|
||||
}
|
||||
}
|
||||
|
||||
export function getNonce(): string {
|
||||
let text = ''
|
||||
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
|
||||
|
||||
155
client/vscode/src/webview/platform/EventLogger.ts
Normal file
155
client/vscode/src/webview/platform/EventLogger.ts
Normal file
@ -0,0 +1,155 @@
|
||||
import * as Comlink from 'comlink'
|
||||
import * as uuid from 'uuid'
|
||||
|
||||
import { EventSource, Event as EventType } from '@sourcegraph/shared/src/graphql-operations'
|
||||
|
||||
import { version } from '../../../package.json'
|
||||
import { ExtensionCoreAPI } from '../../contract'
|
||||
import { ANONYMOUS_USER_ID_KEY } from '../../settings/LocalStorageService'
|
||||
|
||||
import { VsceTelemetryService } from './telemetryService'
|
||||
|
||||
// Event Logger for VS Code Extension
|
||||
export class EventLogger implements VsceTelemetryService {
|
||||
private anonymousUserID = ''
|
||||
private evenSourceType = EventSource.BACKEND || EventSource.IDEEXTENSION
|
||||
private eventID = 0
|
||||
private listeners: Set<(eventName: string) => void> = new Set()
|
||||
private vsceAPI: Comlink.Remote<ExtensionCoreAPI>
|
||||
private newInstall = false
|
||||
private editorInfo = { editor: 'vscode', version }
|
||||
|
||||
constructor(extensionAPI: Comlink.Remote<ExtensionCoreAPI>) {
|
||||
this.vsceAPI = extensionAPI
|
||||
this.initializeLogParameters()
|
||||
.then(() => {})
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a pageview.
|
||||
* Page titles should be specific and human-readable in pascal case, e.g. "SearchResults" or "Blob" or "NewOrg"
|
||||
*/
|
||||
public logViewEvent(pageTitle: string, eventProperties?: any, publicArgument?: any, url?: string): void {
|
||||
if (pageTitle) {
|
||||
this.tracker(
|
||||
`View${pageTitle}`,
|
||||
{ ...eventProperties, ...this.editorInfo },
|
||||
{ ...publicArgument, ...this.editorInfo },
|
||||
url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
public logPageView(): void {
|
||||
// Debt: migrate VS Code `logViewEvent` calls to `logPageView`
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a user action or event.
|
||||
* Event labels should be specific and follow a ${noun}${verb} structure in pascal case, e.g. "ButtonClicked" or "SignInInitiated"
|
||||
*
|
||||
* @param eventLabel: the event name.
|
||||
* @param eventProperties: event properties. These get logged to our database, but do not get
|
||||
* sent to our analytics systems. This may contain private info such as repository names or search queries.
|
||||
* @param publicArgument: event properties that include only public information. Do NOT
|
||||
* include any private information, such as full URLs that may contain private repo names or
|
||||
* search queries. The contents of this parameter are sent to our analytics systems.
|
||||
*/
|
||||
public log(eventLabel: string, eventProperties?: any, publicArgument?: any, uri?: string): void {
|
||||
if (!eventLabel) {
|
||||
return
|
||||
}
|
||||
switch (eventLabel) {
|
||||
case 'DynamicFilterClicked':
|
||||
eventLabel = 'VSCESidebarDynamicFiltersClick'
|
||||
break
|
||||
case 'SearchSnippetClicked':
|
||||
eventLabel = 'VSCESidebarRepositoriesClick'
|
||||
break
|
||||
case 'SearchReferenceOpened':
|
||||
eventLabel = 'VSCESidebarSearchReferenceClick'
|
||||
break
|
||||
}
|
||||
for (const listener of this.listeners) {
|
||||
listener(eventLabel)
|
||||
}
|
||||
this.tracker(
|
||||
eventLabel,
|
||||
{ ...eventProperties, ...this.editorInfo },
|
||||
{ ...publicArgument, ...this.editorInfo },
|
||||
uri
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the anonymous user ID and cohort ID of the user from VSCE storage utility.
|
||||
* If user doesn't have an anonymous user ID yet, a new one is generated
|
||||
* And a new ide install event will be logged
|
||||
*/
|
||||
private async initializeLogParameters(): Promise<void> {
|
||||
let anonymousUserID = await this.vsceAPI.getLocalStorageItem(ANONYMOUS_USER_ID_KEY)
|
||||
const source = await this.vsceAPI.getEventSource
|
||||
if (!anonymousUserID) {
|
||||
anonymousUserID = uuid.v4()
|
||||
this.newInstall = true
|
||||
await this.vsceAPI.setLocalStorageItem(ANONYMOUS_USER_ID_KEY, anonymousUserID)
|
||||
}
|
||||
this.anonymousUserID = anonymousUserID
|
||||
this.evenSourceType = source
|
||||
if (this.newInstall) {
|
||||
this.log('IDEInstalled')
|
||||
this.newInstall = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the anonymous identifier for this user (used to allow site admins
|
||||
* on a Sourcegraph instance to see a count of unique users on a daily,
|
||||
* weekly, and monthly basis).
|
||||
*/
|
||||
public getAnonymousUserID(): string {
|
||||
return this.anonymousUserID
|
||||
}
|
||||
|
||||
/**
|
||||
* Regular instance version format: 3.38.2
|
||||
* Insider version format: 134683_2022-03-02_5188fes0101
|
||||
*/
|
||||
public getEventSourceType(): EventSource {
|
||||
return this.evenSourceType
|
||||
}
|
||||
|
||||
/**
|
||||
* Event ID is used to deduplicate events in Amplitude.
|
||||
* This is used in the case that multiple events with the same userID and timestamp
|
||||
* are sent. https://developers.amplitude.com/docs/http-api-v2#optional-keys
|
||||
*/
|
||||
public getEventID(): number {
|
||||
this.eventID++
|
||||
return this.eventID
|
||||
}
|
||||
|
||||
public addEventLogListener(callback: (eventName: string) => void): () => void {
|
||||
this.listeners.add(callback)
|
||||
return () => this.listeners.delete(callback)
|
||||
}
|
||||
|
||||
public tracker(eventName: string, eventProperties?: unknown, publicArgument?: unknown, uri?: string): void {
|
||||
const userEventVariables: EventType = {
|
||||
event: eventName,
|
||||
userCookieID: this.getAnonymousUserID(),
|
||||
referrer: 'VSCE',
|
||||
url: uri || '',
|
||||
source: this.getEventSourceType(),
|
||||
argument: eventProperties ? JSON.stringify(eventProperties) : null,
|
||||
publicArgument: JSON.stringify(publicArgument),
|
||||
deviceID: this.getAnonymousUserID(),
|
||||
eventID: this.getEventID(),
|
||||
}
|
||||
this.vsceAPI
|
||||
.logEvents(userEventVariables)
|
||||
.then(() => {})
|
||||
.catch(error => console.log(error))
|
||||
}
|
||||
}
|
||||
@ -1,15 +1,20 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
|
||||
import * as Comlink from 'comlink'
|
||||
import { print } from 'graphql'
|
||||
import { BehaviorSubject, from, Observable } from 'rxjs'
|
||||
|
||||
import { GraphQLResult } from '@sourcegraph/http-client'
|
||||
import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import { PlatformContext } from '@sourcegraph/shared/src/platform/context'
|
||||
import { TelemetryService } from '@sourcegraph/shared/src/telemetry/telemetryService'
|
||||
import { SettingsCascadeOrError } from '@sourcegraph/shared/src/settings/settings'
|
||||
import { TooltipController } from '@sourcegraph/wildcard'
|
||||
|
||||
import { ExtensionCoreAPI } from '../../contract'
|
||||
|
||||
import { vscodeTelemetryService } from './telemetryService'
|
||||
import { EventLogger } from './EventLogger'
|
||||
import { VsceTelemetryService } from './telemetryService'
|
||||
|
||||
export interface VSCodePlatformContext
|
||||
extends Pick<
|
||||
@ -24,21 +29,25 @@ export interface VSCodePlatformContext
|
||||
| 'getStaticExtensions'
|
||||
| 'telemetryService'
|
||||
| 'clientApplication'
|
||||
| 'forceUpdateTooltip'
|
||||
> {
|
||||
// Ensure telemetryService is non-nullable.
|
||||
telemetryService: TelemetryService
|
||||
telemetryService: VsceTelemetryService
|
||||
requestGraphQL: <R, V = object>(options: {
|
||||
request: string
|
||||
variables: V
|
||||
mightContainPrivateInfo: boolean
|
||||
overrideAccessToken?: string
|
||||
overrideSourcegraphURL?: string
|
||||
}) => Observable<GraphQLResult<R>>
|
||||
}
|
||||
|
||||
export function createPlatformContext(extensionCoreAPI: Comlink.Remote<ExtensionCoreAPI>): VSCodePlatformContext {
|
||||
const context: VSCodePlatformContext = {
|
||||
requestGraphQL({ request, variables, overrideAccessToken }) {
|
||||
return from(extensionCoreAPI.requestGraphQL(request, variables, overrideAccessToken))
|
||||
requestGraphQL({ request, variables, overrideAccessToken, overrideSourcegraphURL }) {
|
||||
return from(
|
||||
extensionCoreAPI.requestGraphQL(request, variables, overrideAccessToken, overrideSourcegraphURL)
|
||||
)
|
||||
},
|
||||
// TODO add true Apollo Client support for v2
|
||||
getGraphQLClient: () =>
|
||||
@ -49,12 +58,13 @@ export function createPlatformContext(extensionCoreAPI: Comlink.Remote<Extension
|
||||
settings: wrapRemoteObservable(extensionCoreAPI.observeSourcegraphSettings()),
|
||||
// TODO: implement GQL mutation, settings refresh (called by extensions, impl w/ ext. host).
|
||||
updateSettings: () => Promise.resolve(),
|
||||
telemetryService: vscodeTelemetryService,
|
||||
telemetryService: new EventLogger(extensionCoreAPI),
|
||||
sideloadedExtensionURL: new BehaviorSubject<string | null>(null),
|
||||
clientApplication: 'other', // TODO add 'vscode-extension' to `clientApplication`,
|
||||
getScriptURLForExtension: () => undefined,
|
||||
// TODO showMessage
|
||||
forceUpdateTooltip: () => TooltipController.forceUpdate(),
|
||||
// TODO showInputBox
|
||||
// TODO showMessage
|
||||
}
|
||||
|
||||
return context
|
||||
@ -64,5 +74,20 @@ export interface WebviewPageProps {
|
||||
extensionCoreAPI: Comlink.Remote<ExtensionCoreAPI>
|
||||
platformContext: VSCodePlatformContext
|
||||
theme: 'theme-dark' | 'theme-light'
|
||||
authenticatedUser: AuthenticatedUser | null
|
||||
settingsCascade: SettingsCascadeOrError
|
||||
instanceURL: string
|
||||
}
|
||||
|
||||
// Webview page context. Used to pass to aliased components.
|
||||
export const WebviewPageContext = createContext<WebviewPageProps | undefined>(undefined)
|
||||
|
||||
export function useWebviewPageContext(): WebviewPageProps {
|
||||
const context = useContext(WebviewPageContext)
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useWebviewPageContext must be used within a WebviewPageContextProvider')
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
2
client/vscode/src/webview/platform/polyfills/index.ts
Normal file
2
client/vscode/src/webview/platform/polyfills/index.ts
Normal file
@ -0,0 +1,2 @@
|
||||
import '@sourcegraph/shared/src/polyfills/configure-core-js'
|
||||
import './polyfill'
|
||||
3
client/vscode/src/webview/platform/polyfills/polyfill.ts
Normal file
3
client/vscode/src/webview/platform/polyfills/polyfill.ts
Normal file
@ -0,0 +1,3 @@
|
||||
// Polyfill URL because Chrome and Firefox are not spec-compliant
|
||||
// Hostnames of URIs with custom schemes (e.g. git) are not parsed out
|
||||
import 'core-js/web/url'
|
||||
@ -1,10 +1,44 @@
|
||||
import { noop } from 'lodash'
|
||||
|
||||
import { TelemetryService } from '@sourcegraph/shared/src/telemetry/telemetryService'
|
||||
|
||||
export const vscodeTelemetryService: TelemetryService = {
|
||||
// TODO: generate and store anon user id.
|
||||
// store w Memento
|
||||
|
||||
log: () => {},
|
||||
logViewEvent: () => {},
|
||||
logPageView: () => {},
|
||||
/**
|
||||
* Props interface that can be extended by React components depending on the TelemetryService.
|
||||
*/
|
||||
export interface VsceTelemetryProps {
|
||||
/**
|
||||
* A telemetry service implementation to log events.
|
||||
*/
|
||||
telemetryService: VsceTelemetryService
|
||||
}
|
||||
|
||||
/**
|
||||
* The telemetry service logs events.
|
||||
*/
|
||||
export interface VsceTelemetryService extends TelemetryService {
|
||||
/**
|
||||
* Log an event (by sending it to the server).
|
||||
* Provide uri manually for some events (e.g ViewRepository, ViewBlob) as webview does not provide link location
|
||||
*/
|
||||
log(eventName: string, eventProperties?: any, publicArgument?: any, uri?: string): void
|
||||
/**
|
||||
* Log a pageview event (by sending it to the server).
|
||||
*/
|
||||
logViewEvent(eventName: string, eventProperties?: any, publicArgument?: any, uri?: string): void
|
||||
/**
|
||||
* Listen for event logs
|
||||
*
|
||||
* @returns a cleanup/removeEventListener function
|
||||
*/
|
||||
addEventLogListener?(callback: (eventName: string) => void): () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* A noop telemetry service.
|
||||
* * Provide uri manually for some events
|
||||
*/
|
||||
export const NOOP_TELEMETRY_SERVICE: VsceTelemetryService = {
|
||||
log: noop,
|
||||
logViewEvent: noop,
|
||||
logPageView: noop,
|
||||
}
|
||||
|
||||
123
client/vscode/src/webview/search-panel/MatchHandlersContext.ts
Normal file
123
client/vscode/src/webview/search-panel/MatchHandlersContext.ts
Normal file
@ -0,0 +1,123 @@
|
||||
import { createContext, useContext, useMemo } from 'react'
|
||||
|
||||
import * as Comlink from 'comlink'
|
||||
import { noop } from 'lodash'
|
||||
|
||||
import { AuthenticatedUser } from '@sourcegraph/shared/src/auth'
|
||||
import { RepositoryMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
|
||||
import { ExtensionCoreAPI } from '../../contract'
|
||||
import { SourcegraphUri, SourcegraphUriOptionals } from '../../file-system/SourcegraphUri'
|
||||
import { VSCodePlatformContext } from '../platform/context'
|
||||
|
||||
type MinimalRepositoryMatch = Pick<RepositoryMatch, 'repository' | 'branches' | 'description'>
|
||||
|
||||
export interface MatchHandlersContext {
|
||||
openRepo: (repository: MinimalRepositoryMatch) => void
|
||||
openFile: (repositoryName: string, optional?: SourcegraphUriOptionals) => void
|
||||
openSymbol: (symbolUrl: string) => void
|
||||
openCommit: (commitUrl: string) => void
|
||||
instanceURL: string
|
||||
}
|
||||
export const MatchHandlersContext = createContext<MatchHandlersContext>({
|
||||
// Initialize in `SearchResultsView` (via `useMatchHandlers`)
|
||||
openRepo: noop,
|
||||
openFile: noop,
|
||||
openSymbol: noop,
|
||||
openCommit: noop,
|
||||
instanceURL: '',
|
||||
})
|
||||
|
||||
export function useMatchHandlers({
|
||||
platformContext,
|
||||
extensionCoreAPI,
|
||||
onRepoSelected,
|
||||
authenticatedUser,
|
||||
instanceURL,
|
||||
}: {
|
||||
platformContext: VSCodePlatformContext
|
||||
extensionCoreAPI: Comlink.Remote<ExtensionCoreAPI>
|
||||
onRepoSelected: (repositoryMatch: MinimalRepositoryMatch) => void
|
||||
authenticatedUser: AuthenticatedUser | null
|
||||
instanceURL: string
|
||||
}): Omit<MatchHandlersContext, 'instanceURL'> {
|
||||
const host = useMemo(() => new URL(instanceURL).host, [instanceURL])
|
||||
|
||||
const matchHandlers: Omit<MatchHandlersContext, 'instanceURL'> = useMemo(
|
||||
() => ({
|
||||
openRepo: repositoryMatch => {
|
||||
// noop, implementation in SearchResultsView component since the repo page depends on its state.
|
||||
// nvm, pass "onRepoSelected" prop
|
||||
onRepoSelected(repositoryMatch)
|
||||
|
||||
extensionCoreAPI
|
||||
.openSourcegraphFile(`sourcegraph://${host}/${repositoryMatch.repository}`)
|
||||
.catch(error => {
|
||||
console.error('Error opening Sourcegraph repository', error)
|
||||
})
|
||||
// Log View Event to sync search history
|
||||
// URL must be provided to render Recent Searches on Web
|
||||
platformContext.telemetryService.logViewEvent(
|
||||
'Repository',
|
||||
null,
|
||||
authenticatedUser !== null,
|
||||
`https://${host}/${repositoryMatch.repository}`
|
||||
)
|
||||
},
|
||||
openFile: (repositoryName, optionals) => {
|
||||
// Create sourcegraph URI
|
||||
const sourcegraphUri = SourcegraphUri.fromParts(host, repositoryName, optionals)
|
||||
|
||||
const uri = sourcegraphUri.uri + sourcegraphUri.positionSuffix()
|
||||
|
||||
// Log View Event to sync search history
|
||||
platformContext.telemetryService.logViewEvent(
|
||||
'Blob',
|
||||
null,
|
||||
authenticatedUser !== null,
|
||||
sourcegraphUri.uri.replace('sourcegraph://', 'https://')
|
||||
)
|
||||
|
||||
extensionCoreAPI
|
||||
.openSourcegraphFile(uri)
|
||||
.catch(error => console.error('Error opening Sourcegraph file', error))
|
||||
},
|
||||
openSymbol: (symbolUrl: string) => {
|
||||
const { path, position, revision, repositoryName, host: codeHost } = SourcegraphUri.parse(
|
||||
`https:/${symbolUrl}`,
|
||||
window.URL
|
||||
)
|
||||
const sourcegraphUri = SourcegraphUri.fromParts(host, `${codeHost}/${repositoryName}`, {
|
||||
revision,
|
||||
path,
|
||||
position: position
|
||||
? {
|
||||
line: position.line - 1, // Convert to 1-based
|
||||
character: position.character - 1,
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
const uri = sourcegraphUri.uri + sourcegraphUri.positionSuffix()
|
||||
|
||||
extensionCoreAPI.openSourcegraphFile(uri).catch(error => {
|
||||
console.error('Error opening Sourcegraph file', error)
|
||||
})
|
||||
},
|
||||
openCommit: commitUrl => {
|
||||
const commitURL = new URL(commitUrl, instanceURL)
|
||||
extensionCoreAPI.openLink(commitURL.href).catch(error => {
|
||||
console.error('Error opening commit in browser', error)
|
||||
})
|
||||
|
||||
// Roadmap: open diff in VS Code instead of Sourcegraph Web.
|
||||
},
|
||||
}),
|
||||
[extensionCoreAPI, platformContext, authenticatedUser, onRepoSelected, host, instanceURL]
|
||||
)
|
||||
|
||||
return matchHandlers
|
||||
}
|
||||
|
||||
export function useOpenSearchResultsContext(): MatchHandlersContext {
|
||||
return useContext(MatchHandlersContext)
|
||||
}
|
||||
51
client/vscode/src/webview/search-panel/RepoView.module.scss
Normal file
51
client/vscode/src/webview/search-panel/RepoView.module.scss
Normal file
@ -0,0 +1,51 @@
|
||||
.tree-entries-section {
|
||||
// To avoid having empty columns (and thus the items appearing not flush with the left margin),
|
||||
// the component only applies this class when there are >= 6 items. This number is chosen
|
||||
// because it is greater than the maximum number of columns that will be shown and ensures that
|
||||
// at least 1 column has more than 1 item.
|
||||
// See also MIN_ENTRIES_FOR_COLUMN_LAYOUT.
|
||||
&--columns {
|
||||
column-gap: 1.5rem;
|
||||
column-width: 13rem;
|
||||
column-rule: 1px solid var(--border-color);
|
||||
border-right: solid 1px var(--border-color);
|
||||
|
||||
@media (--sm-breakpoint-up) {
|
||||
column-count: 1;
|
||||
}
|
||||
@media (--md-breakpoint-up) {
|
||||
column-count: 3;
|
||||
}
|
||||
@media (--md-breakpoint-down) {
|
||||
column-count: 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tree-entry {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
margin-left: -0.25rem;
|
||||
margin-right: -0.25rem;
|
||||
padding: 0.125rem 0.25rem;
|
||||
|
||||
break-inside: avoid-column;
|
||||
|
||||
--focus-box-shadow: none;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--color-bg-1);
|
||||
}
|
||||
|
||||
&--no-columns {
|
||||
max-width: 18rem;
|
||||
}
|
||||
}
|
||||
|
||||
.section {
|
||||
width: 100%;
|
||||
max-width: var(--media-xl);
|
||||
}
|
||||
152
client/vscode/src/webview/search-panel/RepoView.tsx
Normal file
152
client/vscode/src/webview/search-panel/RepoView.tsx
Normal file
@ -0,0 +1,152 @@
|
||||
import React, { useMemo, useState } from 'react'
|
||||
|
||||
import { VSCodeProgressRing } from '@vscode/webview-ui-toolkit/react'
|
||||
import classNames from 'classnames'
|
||||
import ArrowLeftIcon from 'mdi-react/ArrowLeftIcon'
|
||||
import FileDocumentOutlineIcon from 'mdi-react/FileDocumentOutlineIcon'
|
||||
import FolderOutlineIcon from 'mdi-react/FolderOutlineIcon'
|
||||
import SourceRepositoryIcon from 'mdi-react/SourceRepositoryIcon'
|
||||
import { catchError } from 'rxjs/operators'
|
||||
|
||||
import { QueryState } from '@sourcegraph/search'
|
||||
import { fetchTreeEntries } from '@sourcegraph/shared/src/backend/repo'
|
||||
import { displayRepoName } from '@sourcegraph/shared/src/components/RepoFileLink'
|
||||
import { RepositoryMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
import { PageHeader, useObservable } from '@sourcegraph/wildcard'
|
||||
|
||||
import { WebviewPageProps } from '../platform/context'
|
||||
|
||||
import styles from './RepoView.module.scss'
|
||||
|
||||
interface RepoViewProps extends Pick<WebviewPageProps, 'extensionCoreAPI' | 'platformContext' | 'instanceURL'> {
|
||||
onBackToSearchResults: () => void
|
||||
// Debt: just use repository name and make GraphQL Repository query to get metadata.
|
||||
// This will enable more info (like description) when navigating here from file matches.
|
||||
repositoryMatch: Pick<RepositoryMatch, 'repository' | 'branches' | 'description'>
|
||||
setQueryState: (query: QueryState) => void
|
||||
}
|
||||
|
||||
export const RepoView: React.FunctionComponent<RepoViewProps> = ({
|
||||
extensionCoreAPI,
|
||||
platformContext,
|
||||
repositoryMatch,
|
||||
onBackToSearchResults,
|
||||
instanceURL,
|
||||
setQueryState,
|
||||
}) => {
|
||||
const [directoryStack, setDirectoryStack] = useState<string[]>([])
|
||||
|
||||
// File tree results are memoized, so going back isn't expensive.
|
||||
const treeEntries = useObservable(
|
||||
useMemo(
|
||||
() =>
|
||||
fetchTreeEntries({
|
||||
repoName: repositoryMatch.repository,
|
||||
commitID: '',
|
||||
revision: repositoryMatch.branches?.[0] ?? 'HEAD',
|
||||
filePath: directoryStack.length > 0 ? directoryStack[directoryStack.length - 1] : '',
|
||||
requestGraphQL: platformContext.requestGraphQL,
|
||||
}).pipe(
|
||||
catchError(error => {
|
||||
console.error(error, { repositoryMatch })
|
||||
// TODO: remove and add error boundary in searchresultsview
|
||||
return []
|
||||
})
|
||||
),
|
||||
[platformContext, repositoryMatch, directoryStack]
|
||||
)
|
||||
)
|
||||
|
||||
const onPreviousDirectory = (): void => {
|
||||
const newDirectoryStack = directoryStack.slice(0, -1)
|
||||
setQueryState({
|
||||
query: `repo:^${repositoryMatch.repository}$ ${
|
||||
newDirectoryStack.length > 0 ? `file:^${newDirectoryStack[newDirectoryStack.length - 1]}` : ''
|
||||
}`,
|
||||
})
|
||||
setDirectoryStack(newDirectoryStack)
|
||||
}
|
||||
|
||||
const onSelect = (isDirectory: boolean, path: string, url: string): void => {
|
||||
const host = new URL(instanceURL).host
|
||||
if (isDirectory) {
|
||||
setQueryState({ query: `repo:^${repositoryMatch.repository}$ file:^${path}` })
|
||||
setDirectoryStack([...directoryStack, path])
|
||||
} else {
|
||||
extensionCoreAPI.openSourcegraphFile(`sourcegraph://${host}${url}`).catch(error => {
|
||||
console.error('Error opening Sourcegraph file', error)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mb-3 p-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBackToSearchResults}
|
||||
className="btn btn-sm btn-link btn-outline-secondary text-decoration-none border-0"
|
||||
>
|
||||
<ArrowLeftIcon className="icon-inline mr-1" />
|
||||
Back to search view
|
||||
</button>
|
||||
{directoryStack.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onPreviousDirectory}
|
||||
className="btn btn-sm btn-link btn-outline-secondary text-decoration-none border-0"
|
||||
>
|
||||
<ArrowLeftIcon className="icon-inline mr-1" />
|
||||
Back to previous directory
|
||||
</button>
|
||||
)}
|
||||
<PageHeader
|
||||
path={[{ icon: SourceRepositoryIcon, text: displayRepoName(repositoryMatch.repository) }]}
|
||||
className="mb-1 mt-3 test-tree-page-title"
|
||||
/>
|
||||
{repositoryMatch.description && <p className="mt-0 text-muted">{repositoryMatch.description}</p>}
|
||||
<div className={classNames(styles.section)}>
|
||||
<h4>Files and directories</h4>
|
||||
{treeEntries === undefined ? (
|
||||
<VSCodeProgressRing />
|
||||
) : (
|
||||
<div className={classNames('pr-2', styles.treeEntriesSectionColumns)}>
|
||||
{treeEntries.entries.map(entry => (
|
||||
<button
|
||||
type="button"
|
||||
key={entry.name}
|
||||
className={classNames(
|
||||
'btn btn-sm btn-link',
|
||||
'test-page-file-decorable',
|
||||
styles.treeEntry,
|
||||
entry.isDirectory && 'font-weight-bold',
|
||||
`test-tree-entry-${entry.isDirectory ? 'directory' : 'file'}`,
|
||||
treeEntries.entries.length < 7 && styles.treeEntryNoColumns
|
||||
)}
|
||||
title={entry.path}
|
||||
data-testid="tree-entry"
|
||||
onClick={() => onSelect(entry.isDirectory, entry.path, entry.url)}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
'd-flex align-items-center justify-content-between test-file-decorable-name overflow-hidden'
|
||||
)}
|
||||
>
|
||||
<span>
|
||||
{entry.isDirectory && (
|
||||
<FolderOutlineIcon className="icon-inline mr-1 text-muted" />
|
||||
)}
|
||||
{!entry.isDirectory && (
|
||||
<FileDocumentOutlineIcon className="icon-inline mr-1 text-muted" />
|
||||
)}
|
||||
{entry.name}
|
||||
{entry.isDirectory && '/'}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
209
client/vscode/src/webview/search-panel/SearchHomeView.tsx
Normal file
209
client/vscode/src/webview/search-panel/SearchHomeView.tsx
Normal file
@ -0,0 +1,209 @@
|
||||
import React, { useCallback, useMemo, useState } from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import { Observable } from 'rxjs'
|
||||
import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect'
|
||||
|
||||
import {
|
||||
SearchPatternType,
|
||||
getUserSearchContextNamespaces,
|
||||
fetchAutoDefinedSearchContexts,
|
||||
QueryState,
|
||||
} from '@sourcegraph/search'
|
||||
import { SearchBox } from '@sourcegraph/search-ui'
|
||||
import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import { collectMetrics } from '@sourcegraph/shared/src/search/query/metrics'
|
||||
import { appendContextFilter, sanitizeQueryForTelemetry } from '@sourcegraph/shared/src/search/query/transformer'
|
||||
import { LATEST_VERSION, SearchMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
import { globbingEnabledFromSettings } from '@sourcegraph/shared/src/util/globbing'
|
||||
|
||||
import { SearchHomeState } from '../../state'
|
||||
import { WebviewPageProps } from '../platform/context'
|
||||
|
||||
import { fetchSearchContexts } from './alias/fetchSearchContext'
|
||||
import { BrandHeader } from './components/BrandHeader'
|
||||
import { HomeFooter } from './components/HomeFooter'
|
||||
|
||||
import styles from './index.module.scss'
|
||||
export interface SearchHomeViewProps extends WebviewPageProps {
|
||||
context: SearchHomeState['context']
|
||||
}
|
||||
|
||||
export const SearchHomeView: React.FunctionComponent<SearchHomeViewProps> = ({
|
||||
extensionCoreAPI,
|
||||
authenticatedUser,
|
||||
platformContext,
|
||||
settingsCascade,
|
||||
theme,
|
||||
context,
|
||||
instanceURL,
|
||||
}) => {
|
||||
// Toggling case sensitivity or pattern type does NOT trigger a new search on home view.
|
||||
const [caseSensitive, setCaseSensitivity] = useState(false)
|
||||
const [patternType, setPatternType] = useState(SearchPatternType.literal)
|
||||
|
||||
const [userQueryState, setUserQueryState] = useState<QueryState>({
|
||||
query: '',
|
||||
})
|
||||
|
||||
const isSourcegraphDotCom = useMemo(() => {
|
||||
const hostname = new URL(instanceURL).hostname
|
||||
return hostname === 'sourcegraph.com' || hostname === 'www.sourcegraph.com'
|
||||
}, [instanceURL])
|
||||
|
||||
const onSubmit = useCallback(() => {
|
||||
extensionCoreAPI
|
||||
.streamSearch(userQueryState.query, {
|
||||
caseSensitive,
|
||||
patternType,
|
||||
version: LATEST_VERSION,
|
||||
trace: undefined,
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users? Errors will typically be caught and
|
||||
// surfaced throught streaming search reuls.
|
||||
console.error(error)
|
||||
})
|
||||
|
||||
extensionCoreAPI
|
||||
.setSidebarQueryState({
|
||||
queryState: { query: userQueryState.query },
|
||||
searchCaseSensitivity: caseSensitive,
|
||||
searchPatternType: patternType,
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users
|
||||
console.error('Error updating sidebar query state from panel', error)
|
||||
})
|
||||
|
||||
// Log Search History
|
||||
const hostname = new URL(instanceURL).hostname
|
||||
let queryString = `${userQueryState.query}${caseSensitive ? ' case:yes' : ''}`
|
||||
if (context.selectedSearchContextSpec) {
|
||||
queryString = appendContextFilter(queryString, context.selectedSearchContextSpec)
|
||||
}
|
||||
const metrics = queryString ? collectMetrics(queryString) : undefined
|
||||
platformContext.telemetryService.log(
|
||||
'SearchResultsQueried',
|
||||
{
|
||||
code_search: {
|
||||
query_data: {
|
||||
query: metrics,
|
||||
combined: queryString,
|
||||
empty: !queryString,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
code_search: {
|
||||
query_data: {
|
||||
// 🚨 PRIVACY: never provide any private query data in the
|
||||
// { code_search: query_data: query } property,
|
||||
// which is also potentially exported in pings data.
|
||||
query: metrics,
|
||||
|
||||
// 🚨 PRIVACY: Only collect the full query string for unauthenticated users
|
||||
// on Sourcegraph.com, and only after sanitizing to remove certain filters.
|
||||
combined:
|
||||
!authenticatedUser && isSourcegraphDotCom
|
||||
? sanitizeQueryForTelemetry(queryString)
|
||||
: undefined,
|
||||
empty: !queryString,
|
||||
},
|
||||
},
|
||||
},
|
||||
`https://${hostname}/search?q=${encodeURIComponent(queryString)}&patternType=${patternType}`
|
||||
)
|
||||
}, [
|
||||
extensionCoreAPI,
|
||||
userQueryState.query,
|
||||
caseSensitive,
|
||||
patternType,
|
||||
instanceURL,
|
||||
context.selectedSearchContextSpec,
|
||||
platformContext.telemetryService,
|
||||
authenticatedUser,
|
||||
isSourcegraphDotCom,
|
||||
])
|
||||
|
||||
// Update local query state on sidebar query state updates.
|
||||
useDeepCompareEffectNoCheck(() => {
|
||||
if (context.searchSidebarQueryState.proposedQueryState?.queryState) {
|
||||
setUserQueryState(context.searchSidebarQueryState.proposedQueryState?.queryState)
|
||||
}
|
||||
}, [context.searchSidebarQueryState.proposedQueryState?.queryState])
|
||||
|
||||
const globbing = useMemo(() => globbingEnabledFromSettings(settingsCascade), [settingsCascade])
|
||||
|
||||
const setSelectedSearchContextSpec = useCallback(
|
||||
(spec: string) => {
|
||||
extensionCoreAPI.setSelectedSearchContextSpec(spec).catch(error => {
|
||||
console.error('Error persisting search context spec.', error)
|
||||
})
|
||||
},
|
||||
[extensionCoreAPI]
|
||||
)
|
||||
|
||||
const fetchStreamSuggestions = useCallback(
|
||||
(query): Observable<SearchMatch[]> =>
|
||||
wrapRemoteObservable(extensionCoreAPI.fetchStreamSuggestions(query, instanceURL)),
|
||||
[extensionCoreAPI, instanceURL]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="d-flex flex-column align-items-center">
|
||||
<BrandHeader theme={theme} />
|
||||
|
||||
<div className={styles.homeSearchBoxContainer}>
|
||||
{/* eslint-disable-next-line react/forbid-elements */}
|
||||
<form
|
||||
className="d-flex my-2"
|
||||
onSubmit={event => {
|
||||
event.preventDefault()
|
||||
onSubmit()
|
||||
}}
|
||||
>
|
||||
<SearchBox
|
||||
caseSensitive={caseSensitive}
|
||||
setCaseSensitivity={setCaseSensitivity}
|
||||
patternType={patternType}
|
||||
setPatternType={setPatternType}
|
||||
isSourcegraphDotCom={isSourcegraphDotCom}
|
||||
hasUserAddedExternalServices={false}
|
||||
hasUserAddedRepositories={true} // Used for search context CTA, which we won't show here.
|
||||
structuralSearchDisabled={false}
|
||||
queryState={userQueryState}
|
||||
onChange={setUserQueryState}
|
||||
onSubmit={onSubmit}
|
||||
authenticatedUser={authenticatedUser}
|
||||
searchContextsEnabled={true}
|
||||
showSearchContext={true}
|
||||
showSearchContextManagement={false}
|
||||
defaultSearchContextSpec="global"
|
||||
setSelectedSearchContextSpec={setSelectedSearchContextSpec}
|
||||
selectedSearchContextSpec={context.selectedSearchContextSpec}
|
||||
fetchSearchContexts={fetchSearchContexts}
|
||||
fetchAutoDefinedSearchContexts={fetchAutoDefinedSearchContexts}
|
||||
getUserSearchContextNamespaces={getUserSearchContextNamespaces}
|
||||
fetchStreamSuggestions={fetchStreamSuggestions}
|
||||
settingsCascade={settingsCascade}
|
||||
globbing={globbing}
|
||||
isLightTheme={theme === 'theme-light'}
|
||||
telemetryService={platformContext.telemetryService}
|
||||
platformContext={platformContext}
|
||||
className={classNames('flex-grow-1 flex-shrink-past-contents', styles.searchBox)}
|
||||
containerClassName={styles.searchBoxContainer}
|
||||
autoFocus={true}
|
||||
editorComponent="monaco"
|
||||
/>
|
||||
</form>
|
||||
|
||||
<HomeFooter
|
||||
isLightTheme={theme === 'theme-light'}
|
||||
setQuery={setUserQueryState}
|
||||
telemetryService={platformContext.telemetryService}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
432
client/vscode/src/webview/search-panel/SearchResultsView.tsx
Normal file
432
client/vscode/src/webview/search-panel/SearchResultsView.tsx
Normal file
@ -0,0 +1,432 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import { Observable } from 'rxjs'
|
||||
import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect'
|
||||
|
||||
import {
|
||||
SearchPatternType,
|
||||
fetchAutoDefinedSearchContexts,
|
||||
getUserSearchContextNamespaces,
|
||||
QueryState,
|
||||
} from '@sourcegraph/search'
|
||||
import { IEditor, SearchBox, StreamingProgress, StreamingSearchResultsList } from '@sourcegraph/search-ui'
|
||||
import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
|
||||
import { fetchHighlightedFileLineRanges } from '@sourcegraph/shared/src/backend/file'
|
||||
import { FetchFileParameters } from '@sourcegraph/shared/src/components/CodeExcerpt'
|
||||
import { CtaAlert } from '@sourcegraph/shared/src/components/CtaAlert'
|
||||
import { appendContextFilter, updateFilters } from '@sourcegraph/shared/src/search/query/transformer'
|
||||
import { LATEST_VERSION, RepositoryMatch, SearchMatch } from '@sourcegraph/shared/src/search/stream'
|
||||
import { globbingEnabledFromSettings } from '@sourcegraph/shared/src/util/globbing'
|
||||
import { buildSearchURLQuery } from '@sourcegraph/shared/src/util/url'
|
||||
|
||||
import { DISMISS_SEARCH_CTA_KEY } from '../../settings/LocalStorageService'
|
||||
import { SearchResultsState } from '../../state'
|
||||
import { WebviewPageProps } from '../platform/context'
|
||||
|
||||
import { fetchSearchContexts } from './alias/fetchSearchContext'
|
||||
import { setFocusSearchBox } from './api'
|
||||
import { SearchBetaIcon } from './components/icons'
|
||||
import { SavedSearchCreateForm } from './components/SavedSearchForm'
|
||||
import { SearchResultsInfoBar } from './components/SearchResultsInfoBar'
|
||||
import { MatchHandlersContext, useMatchHandlers } from './MatchHandlersContext'
|
||||
import { RepoView } from './RepoView'
|
||||
|
||||
import styles from './index.module.scss'
|
||||
|
||||
export interface SearchResultsViewProps extends WebviewPageProps {
|
||||
context: SearchResultsState['context']
|
||||
}
|
||||
|
||||
export const SearchResultsView: React.FunctionComponent<SearchResultsViewProps> = ({
|
||||
extensionCoreAPI,
|
||||
authenticatedUser,
|
||||
platformContext,
|
||||
settingsCascade,
|
||||
theme,
|
||||
context,
|
||||
instanceURL,
|
||||
}) => {
|
||||
const [userQueryState, setUserQueryState] = useState<QueryState>(context.submittedSearchQueryState.queryState)
|
||||
const [repoToShow, setRepoToShow] = useState<Pick<
|
||||
RepositoryMatch,
|
||||
'repository' | 'branches' | 'description'
|
||||
> | null>(null)
|
||||
|
||||
// Check VS Code local storage to see if user has clicked dismiss button before
|
||||
const [dismissSearchCta, setDismissSearchCta] = useState(false)
|
||||
// Return empty string if not in vs code local storage or 'search' if it exists
|
||||
const showCtaAlert = useMemo(() => extensionCoreAPI.getLocalStorageItem(DISMISS_SEARCH_CTA_KEY), [extensionCoreAPI])
|
||||
const onDismissCtaAlert = useCallback(async () => {
|
||||
setDismissSearchCta(true)
|
||||
await extensionCoreAPI.setLocalStorageItem(DISMISS_SEARCH_CTA_KEY, 'true')
|
||||
}, [extensionCoreAPI])
|
||||
|
||||
useEffect(() => {
|
||||
showCtaAlert
|
||||
.then(result => {
|
||||
setDismissSearchCta(result.length > 0)
|
||||
})
|
||||
.catch(() => setDismissSearchCta(false))
|
||||
}, [showCtaAlert])
|
||||
|
||||
// Editor focus.
|
||||
const editorReference = useRef<IEditor>()
|
||||
const setEditor = useCallback((editor: IEditor) => {
|
||||
editorReference.current = editor
|
||||
setTimeout(() => editor.focus(), 0)
|
||||
}, [])
|
||||
|
||||
// TODO explain
|
||||
useEffect(() => {
|
||||
setFocusSearchBox(() => editorReference.current?.focus())
|
||||
|
||||
return () => {
|
||||
setFocusSearchBox(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const onChange = useCallback(
|
||||
(newState: QueryState) => {
|
||||
setUserQueryState(newState)
|
||||
|
||||
extensionCoreAPI
|
||||
.setSidebarQueryState({
|
||||
queryState: newState,
|
||||
searchCaseSensitivity: context.submittedSearchQueryState?.searchCaseSensitivity,
|
||||
searchPatternType: context.submittedSearchQueryState?.searchPatternType,
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users
|
||||
console.error('Error updating sidebar query state from panel', error)
|
||||
})
|
||||
},
|
||||
[
|
||||
extensionCoreAPI,
|
||||
context.submittedSearchQueryState.searchCaseSensitivity,
|
||||
context.submittedSearchQueryState.searchPatternType,
|
||||
]
|
||||
)
|
||||
|
||||
const [allExpanded, setAllExpanded] = useState(false)
|
||||
const onExpandAllResultsToggle = useCallback(() => {
|
||||
setAllExpanded(oldValue => !oldValue)
|
||||
platformContext.telemetryService.log(allExpanded ? 'allResultsExpanded' : 'allResultsCollapsed')
|
||||
}, [allExpanded, platformContext])
|
||||
|
||||
const [showSavedSearchForm, setShowSavedSearchForm] = useState(false)
|
||||
|
||||
// Update local query state on sidebar query state updates.
|
||||
useDeepCompareEffectNoCheck(() => {
|
||||
if (context.searchSidebarQueryState.proposedQueryState?.queryState) {
|
||||
setUserQueryState(context.searchSidebarQueryState.proposedQueryState?.queryState)
|
||||
}
|
||||
}, [context.searchSidebarQueryState.proposedQueryState?.queryState])
|
||||
|
||||
// Update local search query state on sidebar search submission.
|
||||
useDeepCompareEffectNoCheck(() => {
|
||||
setUserQueryState(context.submittedSearchQueryState.queryState)
|
||||
// It's a whole new object on each state update, so we need
|
||||
// to compare (alternatively, construct full query TODO)
|
||||
|
||||
// Clear repo view
|
||||
setRepoToShow(null)
|
||||
}, [context.submittedSearchQueryState.queryState])
|
||||
|
||||
// Track sidebar + keyboard shortcut search submissions
|
||||
useEffect(() => {
|
||||
platformContext.telemetryService.log('IDESearchSubmitted')
|
||||
}, [platformContext, context.submittedSearchQueryState.queryState.query])
|
||||
|
||||
const onSubmit = useCallback(
|
||||
(options?: { caseSensitive?: boolean; patternType?: SearchPatternType; newQuery?: string }) => {
|
||||
const previousSearchQueryState = context.submittedSearchQueryState
|
||||
|
||||
const query = options?.newQuery ?? userQueryState.query
|
||||
const caseSensitive = options?.caseSensitive ?? previousSearchQueryState.searchCaseSensitivity
|
||||
const patternType = options?.patternType ?? previousSearchQueryState.searchPatternType
|
||||
|
||||
extensionCoreAPI
|
||||
.streamSearch(query, {
|
||||
caseSensitive,
|
||||
patternType,
|
||||
version: LATEST_VERSION,
|
||||
trace: undefined,
|
||||
})
|
||||
.then(() => {
|
||||
editorReference.current?.focus()
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users? Errors will typically be caught and
|
||||
// surfaced throught streaming search reuls.
|
||||
console.error(error)
|
||||
})
|
||||
|
||||
extensionCoreAPI
|
||||
.setSidebarQueryState({
|
||||
queryState: { query },
|
||||
searchCaseSensitivity: caseSensitive,
|
||||
searchPatternType: patternType,
|
||||
})
|
||||
.catch(error => {
|
||||
// TODO surface error to users
|
||||
console.error('Error updating sidebar query state from panel', error)
|
||||
})
|
||||
|
||||
// Clear repo view
|
||||
setRepoToShow(null)
|
||||
},
|
||||
[userQueryState.query, context.submittedSearchQueryState, extensionCoreAPI]
|
||||
)
|
||||
|
||||
// Submit new search on change
|
||||
const setCaseSensitivity = useCallback(
|
||||
(caseSensitive: boolean) => {
|
||||
onSubmit({ caseSensitive })
|
||||
},
|
||||
[onSubmit]
|
||||
)
|
||||
|
||||
// Submit new search on change
|
||||
const setPatternType = useCallback(
|
||||
(patternType: SearchPatternType) => {
|
||||
console.log({ patternType })
|
||||
onSubmit({ patternType })
|
||||
},
|
||||
[onSubmit]
|
||||
)
|
||||
|
||||
const fetchHighlightedFileLineRangesWithContext = useCallback(
|
||||
(parameters: FetchFileParameters) => fetchHighlightedFileLineRanges({ ...parameters, platformContext }),
|
||||
[platformContext]
|
||||
)
|
||||
|
||||
const fetchStreamSuggestions = useCallback(
|
||||
(query): Observable<SearchMatch[]> =>
|
||||
wrapRemoteObservable(extensionCoreAPI.fetchStreamSuggestions(query, instanceURL)),
|
||||
[extensionCoreAPI, instanceURL]
|
||||
)
|
||||
|
||||
const globbing = useMemo(() => globbingEnabledFromSettings(settingsCascade), [settingsCascade])
|
||||
|
||||
const setSelectedSearchContextSpec = useCallback(
|
||||
(spec: string) => {
|
||||
extensionCoreAPI
|
||||
.setSelectedSearchContextSpec(spec)
|
||||
.catch(error => {
|
||||
console.error('Error persisting search context spec.', error)
|
||||
})
|
||||
.finally(() => {
|
||||
// Execute search with new context state
|
||||
onSubmit()
|
||||
})
|
||||
},
|
||||
[extensionCoreAPI, onSubmit]
|
||||
)
|
||||
|
||||
const onSearchAgain = useCallback(
|
||||
(additionalFilters: string[]) => {
|
||||
platformContext.telemetryService.log('SearchSkippedResultsAgainClicked')
|
||||
onSubmit({
|
||||
newQuery: applyAdditionalFilters(context.submittedSearchQueryState.queryState.query, additionalFilters),
|
||||
})
|
||||
},
|
||||
[context.submittedSearchQueryState.queryState, platformContext, onSubmit]
|
||||
)
|
||||
|
||||
const onShareResultsClick = useCallback((): void => {
|
||||
const queryState = context.submittedSearchQueryState
|
||||
|
||||
const path = `/search?${buildSearchURLQuery(
|
||||
queryState.queryState.query,
|
||||
queryState.searchPatternType,
|
||||
queryState.searchCaseSensitivity,
|
||||
context.selectedSearchContextSpec
|
||||
)}&utm_campaign=vscode-extension&utm_medium=direct_traffic&utm_source=vscode-extension&utm_content=save-search`
|
||||
extensionCoreAPI.copyLink(new URL(path, instanceURL).href).catch(error => {
|
||||
console.error('Error copying search link to clipboard:', error)
|
||||
})
|
||||
platformContext.telemetryService.log('VSCEShareLinkClick')
|
||||
}, [context, instanceURL, extensionCoreAPI, platformContext])
|
||||
|
||||
const fullQuery = useMemo(
|
||||
() =>
|
||||
appendContextFilter(
|
||||
context.submittedSearchQueryState.queryState.query ?? '',
|
||||
context.selectedSearchContextSpec
|
||||
),
|
||||
[context]
|
||||
)
|
||||
|
||||
const isSourcegraphDotCom = useMemo(() => {
|
||||
const hostname = new URL(instanceURL).hostname
|
||||
return hostname === 'sourcegraph.com' || hostname === 'www.sourcegraph.com'
|
||||
}, [instanceURL])
|
||||
|
||||
const onSignUpClick = useCallback(
|
||||
(event?: React.FormEvent): void => {
|
||||
event?.preventDefault()
|
||||
platformContext.telemetryService.log(
|
||||
'VSCECreateAccountBannerClick',
|
||||
{ campaign: 'Sign up link' },
|
||||
{ campaign: 'Sign up link' }
|
||||
)
|
||||
},
|
||||
[platformContext.telemetryService]
|
||||
)
|
||||
|
||||
const matchHandlers = useMatchHandlers({
|
||||
platformContext,
|
||||
extensionCoreAPI,
|
||||
authenticatedUser,
|
||||
onRepoSelected: setRepoToShow,
|
||||
instanceURL,
|
||||
})
|
||||
|
||||
const clearRepositoryToShow = (): void => setRepoToShow(null)
|
||||
|
||||
return (
|
||||
<div className={styles.resultsViewLayout}>
|
||||
{/* eslint-disable-next-line react/forbid-elements */}
|
||||
<form
|
||||
className="d-flex w-100 my-2 pb-2 border-bottom"
|
||||
onSubmit={event => {
|
||||
event.preventDefault()
|
||||
onSubmit()
|
||||
}}
|
||||
>
|
||||
<SearchBox
|
||||
caseSensitive={context.submittedSearchQueryState?.searchCaseSensitivity}
|
||||
setCaseSensitivity={setCaseSensitivity}
|
||||
patternType={context.submittedSearchQueryState?.searchPatternType}
|
||||
setPatternType={setPatternType}
|
||||
isSourcegraphDotCom={isSourcegraphDotCom}
|
||||
hasUserAddedExternalServices={false}
|
||||
hasUserAddedRepositories={true} // Used for search context CTA, which we won't show here.
|
||||
structuralSearchDisabled={false}
|
||||
queryState={userQueryState}
|
||||
onChange={onChange}
|
||||
onSubmit={onSubmit}
|
||||
authenticatedUser={authenticatedUser}
|
||||
searchContextsEnabled={true}
|
||||
showSearchContext={true}
|
||||
showSearchContextManagement={false}
|
||||
defaultSearchContextSpec="global"
|
||||
setSelectedSearchContextSpec={setSelectedSearchContextSpec}
|
||||
selectedSearchContextSpec={context.selectedSearchContextSpec}
|
||||
fetchSearchContexts={fetchSearchContexts}
|
||||
fetchAutoDefinedSearchContexts={fetchAutoDefinedSearchContexts}
|
||||
getUserSearchContextNamespaces={getUserSearchContextNamespaces}
|
||||
fetchStreamSuggestions={fetchStreamSuggestions}
|
||||
settingsCascade={settingsCascade}
|
||||
globbing={globbing}
|
||||
isLightTheme={theme === 'theme-light'}
|
||||
telemetryService={platformContext.telemetryService}
|
||||
platformContext={platformContext}
|
||||
className={classNames('flex-grow-1 flex-shrink-past-contents', styles.searchBox)}
|
||||
containerClassName={styles.searchBoxContainer}
|
||||
autoFocus={true}
|
||||
onEditorCreated={setEditor}
|
||||
editorComponent="monaco"
|
||||
/>
|
||||
</form>
|
||||
|
||||
{!repoToShow ? (
|
||||
<div className={styles.resultsViewScrollContainer}>
|
||||
{isSourcegraphDotCom && !authenticatedUser && !dismissSearchCta && (
|
||||
<CtaAlert
|
||||
title="Sign up to add your public and private repositories and unlock search flow"
|
||||
description="Do all the things editors can’t: search multiple repos & commit history, monitor, save
|
||||
searches and more."
|
||||
cta={{
|
||||
label: 'Get started',
|
||||
href:
|
||||
'https://sourcegraph.com/sign-up?editor=vscode&utm_medium=VSCODE&utm_source=sidebar&utm_campaign=vsce-sign-up&utm_content=sign-up',
|
||||
onClick: onSignUpClick,
|
||||
}}
|
||||
icon={<SearchBetaIcon />}
|
||||
className={classNames('percy-display-none', styles.ctaContainer)}
|
||||
onClose={onDismissCtaAlert}
|
||||
/>
|
||||
)}
|
||||
<SearchResultsInfoBar
|
||||
onShareResultsClick={onShareResultsClick}
|
||||
showSavedSearchForm={showSavedSearchForm}
|
||||
setShowSavedSearchForm={setShowSavedSearchForm}
|
||||
extensionCoreAPI={extensionCoreAPI}
|
||||
patternType={context.submittedSearchQueryState.searchPatternType}
|
||||
authenticatedUser={authenticatedUser}
|
||||
platformContext={platformContext}
|
||||
stats={
|
||||
<StreamingProgress
|
||||
progress={
|
||||
context.searchResults?.progress || { durationMs: 0, matchCount: 0, skipped: [] }
|
||||
}
|
||||
state={context.searchResults?.state || 'loading'}
|
||||
onSearchAgain={onSearchAgain}
|
||||
showTrace={false}
|
||||
/>
|
||||
}
|
||||
allExpanded={allExpanded}
|
||||
onExpandAllResultsToggle={onExpandAllResultsToggle}
|
||||
instanceURL={instanceURL}
|
||||
fullQuery={fullQuery}
|
||||
/>
|
||||
{authenticatedUser && showSavedSearchForm && (
|
||||
<SavedSearchCreateForm
|
||||
authenticatedUser={authenticatedUser}
|
||||
submitLabel="Add saved search"
|
||||
title="Add saved search"
|
||||
fullQuery={`${fullQuery} patternType:${context.submittedSearchQueryState.searchPatternType}`}
|
||||
onComplete={() => setShowSavedSearchForm(false)}
|
||||
platformContext={platformContext}
|
||||
instanceURL={instanceURL}
|
||||
/>
|
||||
)}
|
||||
<MatchHandlersContext.Provider value={{ ...matchHandlers, instanceURL }}>
|
||||
<StreamingSearchResultsList
|
||||
isLightTheme={theme === 'theme-light'}
|
||||
settingsCascade={settingsCascade}
|
||||
telemetryService={platformContext.telemetryService}
|
||||
allExpanded={allExpanded}
|
||||
// Debt: dotcom prop used only for "run search" link
|
||||
// for search examples. Fix on VSCE.
|
||||
isSourcegraphDotCom={false}
|
||||
searchContextsEnabled={true}
|
||||
showSearchContext={true}
|
||||
platformContext={platformContext}
|
||||
results={context.searchResults ?? undefined}
|
||||
authenticatedUser={authenticatedUser}
|
||||
fetchHighlightedFileLineRanges={fetchHighlightedFileLineRangesWithContext}
|
||||
executedQuery={context.submittedSearchQueryState.queryState.query}
|
||||
resultClassName="mr-0"
|
||||
// TODO "no results" video thumbnail assets
|
||||
// In build, copy ui/assets/img folder to dist/
|
||||
assetsRoot="https://raw.githubusercontent.com/sourcegraph/sourcegraph/main/ui/assets"
|
||||
/>
|
||||
</MatchHandlersContext.Provider>
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.resultsViewScrollContainer}>
|
||||
<RepoView
|
||||
extensionCoreAPI={extensionCoreAPI}
|
||||
platformContext={platformContext}
|
||||
onBackToSearchResults={clearRepositoryToShow}
|
||||
repositoryMatch={repoToShow}
|
||||
setQueryState={setUserQueryState}
|
||||
instanceURL={instanceURL}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const applyAdditionalFilters = (query: string, additionalFilters: string[]): string => {
|
||||
let newQuery = query
|
||||
for (const filter of additionalFilters) {
|
||||
const fieldValue = filter.split(':', 2)
|
||||
newQuery = updateFilters(newQuery, fieldValue[0], fieldValue[1])
|
||||
}
|
||||
return newQuery
|
||||
}
|
||||
@ -0,0 +1,355 @@
|
||||
import React, { MouseEvent, KeyboardEvent, useCallback, useMemo } from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import * as H from 'history'
|
||||
import { Observable } from 'rxjs'
|
||||
import { map } from 'rxjs/operators'
|
||||
|
||||
import { HoverMerged } from '@sourcegraph/client-api'
|
||||
import { Hoverifier } from '@sourcegraph/codeintellify'
|
||||
import {
|
||||
appendLineRangeQueryParameter,
|
||||
appendSubtreeQueryParameter,
|
||||
isErrorLike,
|
||||
toPositionOrRangeQueryParameter,
|
||||
} from '@sourcegraph/common'
|
||||
import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem'
|
||||
import { CodeExcerpt, FetchFileParameters } from '@sourcegraph/shared/src/components/CodeExcerpt'
|
||||
import styles from '@sourcegraph/shared/src/components/FileMatchChildren.module.scss'
|
||||
import { LastSyncedIcon } from '@sourcegraph/shared/src/components/LastSyncedIcon'
|
||||
import { MatchGroup } from '@sourcegraph/shared/src/components/ranking/PerFileResultRanking'
|
||||
import { Controller as ExtensionsController } from '@sourcegraph/shared/src/extensions/controller'
|
||||
import { HoverContext } from '@sourcegraph/shared/src/hover/HoverOverlay.types'
|
||||
import { IHighlightLineRange } from '@sourcegraph/shared/src/schema'
|
||||
import { ContentMatch, SymbolMatch, PathMatch, getFileMatchUrl } from '@sourcegraph/shared/src/search/stream'
|
||||
import { SettingsCascadeProps } from '@sourcegraph/shared/src/settings/settings'
|
||||
import { SymbolIcon } from '@sourcegraph/shared/src/symbols/SymbolIcon'
|
||||
import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
|
||||
import { useCodeIntelViewerUpdates } from '@sourcegraph/shared/src/util/useCodeIntelViewerUpdates'
|
||||
|
||||
import { useOpenSearchResultsContext } from '../MatchHandlersContext'
|
||||
|
||||
interface FileMatchProps extends SettingsCascadeProps, TelemetryProps {
|
||||
location?: H.Location
|
||||
result: ContentMatch | SymbolMatch | PathMatch
|
||||
grouped: MatchGroup[]
|
||||
/* Clicking on a match opens the link in a new tab */
|
||||
openInNewTab?: boolean
|
||||
/* Called when the first result has fully loaded. */
|
||||
onFirstResultLoad?: () => void
|
||||
fetchHighlightedFileLineRanges: (parameters: FetchFileParameters, force?: boolean) => Observable<string[][]>
|
||||
extensionsController?: Pick<ExtensionsController, 'extHostAPI'>
|
||||
hoverifier?: Hoverifier<HoverContext, HoverMerged, ActionItemAction>
|
||||
}
|
||||
|
||||
/**
|
||||
* This helper function determines whether a mouse/click event was triggered as
|
||||
* a result of selecting text in search results.
|
||||
* There are at least to ways to do this:
|
||||
*
|
||||
* - Tracking `mouseup`, `mousemove` and `mousedown` events. The occurrence of
|
||||
* a `mousemove` event would indicate a text selection. However, users
|
||||
* might slightly move the mouse while clicking, and solutions that would
|
||||
* take this into account seem fragile.
|
||||
* - (implemented here) Inspect the Selection object returned by
|
||||
* `window.getSelection()`.
|
||||
*
|
||||
* CAVEAT: Chromium and Firefox (and maybe other browsers) behave
|
||||
* differently when a search result is clicked *after* text selection was
|
||||
* made:
|
||||
*
|
||||
* - Firefox will clear the selection before executing the click event
|
||||
* handler, i.e. the search result will be opened.
|
||||
* - Chrome will only clear the selection if the click happens *outside*
|
||||
* of the selected text (in which case the search result will be
|
||||
* opened). If the click happens inside the selected text the selection
|
||||
* will be cleared only *after* executing the click event handler.
|
||||
*/
|
||||
function isTextSelectionEvent(event: MouseEvent<HTMLElement>): boolean {
|
||||
const selection = window.getSelection()
|
||||
|
||||
// Text selections are always ranges. Should the type not be set, verify
|
||||
// that the selection is not empty.
|
||||
if (selection && (selection.type === 'Range' || selection.toString() !== '')) {
|
||||
// Firefox specific: Because our code excerpts are implemented as tables,
|
||||
// CTRL+click would select the table cell. Since users don't know that we
|
||||
// use tables, the most likely wanted to open the search results in a new
|
||||
// tab instead though.
|
||||
if ((event.ctrlKey || event.metaKey) && selection.anchorNode?.nodeName === 'TR') {
|
||||
// Ugly side effect: We don't want the table cell to be highlighted.
|
||||
// The focus style that Firefox uses doesn't seem to be affected by
|
||||
// CSS so instead we clear the selection.
|
||||
selection.empty()
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper function to replicate browser behavior when clicking on links.
|
||||
* A very common interaction is to open links in a new in the _background_ via
|
||||
* CTRL/CMD + click or middle click.
|
||||
* Unfortunately `window.open` doesn't give us much control over how the new
|
||||
* window/tab should be opened, and the behavior is inconcistent between
|
||||
* browsers.
|
||||
* In order to replicate the standard behvior as much as possible this function
|
||||
* dynamically creates an `<a>` element and triggers a click event on it.
|
||||
*/
|
||||
function openLinkInNewTab(
|
||||
url: string,
|
||||
event: Pick<MouseEvent, 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>,
|
||||
button: 'primary' | 'middle'
|
||||
): void {
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.style.display = 'none'
|
||||
link.target = '_blank'
|
||||
link.rel = 'noopener noreferrer'
|
||||
const clickEvent = new window.MouseEvent('click', {
|
||||
bubbles: false,
|
||||
altKey: event.altKey,
|
||||
shiftKey: event.shiftKey,
|
||||
// Regarding middle click: Setting "button: 1:" doesn't seem to suffice:
|
||||
// Firefox doesn't react to the event at all, Chromium opens the tab in
|
||||
// the foreground. So in order to simulate a middle click, we set
|
||||
// ctrlKey and metaKey to `true` instead.
|
||||
ctrlKey: button === 'middle' ? true : event.ctrlKey,
|
||||
metaKey: button === 'middle' ? true : event.metaKey,
|
||||
view: window,
|
||||
})
|
||||
|
||||
// It looks the link has to be part of the document, otherwise Firefox won't
|
||||
// trigger the default behavior (it works without appending in Chromium).
|
||||
document.body.append(link)
|
||||
link.dispatchEvent(clickEvent)
|
||||
link.remove()
|
||||
}
|
||||
|
||||
/**
|
||||
* Since we are not using a real link anymore, we have to simulate opening
|
||||
* the file in a new tab when the search result is clicked on with the
|
||||
* middle mouse button.
|
||||
* This handler is bound to the `mouseup` event because the `auxclick`
|
||||
* (https://w3c.github.io/uievents/#event-type-auxclick) event is not
|
||||
* support by all browsers yet (https://caniuse.com/?search=auxclick)
|
||||
*/
|
||||
function navigateToFileOnMiddleMouseButtonClick(event: MouseEvent<HTMLElement>): void {
|
||||
const href = event.currentTarget.getAttribute('data-href')
|
||||
if (href && event.button === 1) {
|
||||
openLinkInNewTab(href, event, 'middle')
|
||||
}
|
||||
}
|
||||
|
||||
export const FileMatchChildren: React.FunctionComponent<FileMatchProps> = props => {
|
||||
// If optimizeHighlighting is enabled, compile a list of the highlighted file ranges we want to
|
||||
// fetch (instead of the entire file.)
|
||||
const optimizeHighlighting =
|
||||
props.settingsCascade.final &&
|
||||
!isErrorLike(props.settingsCascade.final) &&
|
||||
props.settingsCascade.final.experimentalFeatures &&
|
||||
props.settingsCascade.final.experimentalFeatures.enableFastResultLoading
|
||||
|
||||
const {
|
||||
result,
|
||||
grouped,
|
||||
fetchHighlightedFileLineRanges,
|
||||
telemetryService,
|
||||
onFirstResultLoad,
|
||||
extensionsController,
|
||||
} = props
|
||||
|
||||
const { openFile, openSymbol } = useOpenSearchResultsContext()
|
||||
|
||||
const fetchHighlightedFileRangeLines = React.useCallback(
|
||||
(isFirst, startLine, endLine) => {
|
||||
const startTime = Date.now()
|
||||
return fetchHighlightedFileLineRanges(
|
||||
{
|
||||
repoName: result.repository,
|
||||
commitID: result.commit || '',
|
||||
filePath: result.path,
|
||||
disableTimeout: false,
|
||||
ranges: optimizeHighlighting
|
||||
? grouped.map(
|
||||
(group): IHighlightLineRange => ({
|
||||
startLine: group.startLine,
|
||||
endLine: group.endLine,
|
||||
})
|
||||
)
|
||||
: [{ startLine: 0, endLine: 2147483647 }], // entire file,
|
||||
},
|
||||
false
|
||||
).pipe(
|
||||
map(lines => {
|
||||
if (isFirst && onFirstResultLoad) {
|
||||
onFirstResultLoad()
|
||||
}
|
||||
telemetryService.log(
|
||||
'search.latencies.frontend.code-load',
|
||||
{ durationMs: Date.now() - startTime },
|
||||
{ durationMs: Date.now() - startTime }
|
||||
)
|
||||
return optimizeHighlighting
|
||||
? lines[grouped.findIndex(group => group.startLine === startLine && group.endLine === endLine)]
|
||||
: lines[0].slice(startLine, endLine)
|
||||
})
|
||||
)
|
||||
},
|
||||
[result, fetchHighlightedFileLineRanges, grouped, optimizeHighlighting, telemetryService, onFirstResultLoad]
|
||||
)
|
||||
|
||||
const createCodeExcerptLink = (group: MatchGroup): string => {
|
||||
const positionOrRangeQueryParameter = toPositionOrRangeQueryParameter({ position: group.position })
|
||||
return appendLineRangeQueryParameter(
|
||||
appendSubtreeQueryParameter(getFileMatchUrl(result)),
|
||||
positionOrRangeQueryParameter
|
||||
)
|
||||
}
|
||||
|
||||
const codeIntelViewerUpdatesProps = useMemo(
|
||||
() =>
|
||||
grouped && result.type === 'content' && extensionsController
|
||||
? {
|
||||
extensionsController,
|
||||
repositoryName: result.repository,
|
||||
filePath: result.path,
|
||||
revision: result.commit,
|
||||
}
|
||||
: undefined,
|
||||
[extensionsController, result, grouped]
|
||||
)
|
||||
const viewerUpdates = useCodeIntelViewerUpdates(codeIntelViewerUpdatesProps)
|
||||
|
||||
/**
|
||||
* This handler implements the logic to simulate the click/keyboard
|
||||
* activation behavior of links, while also allowing the selection of text
|
||||
* inside the element.
|
||||
* Because a click event is dispatched in both cases (clicking the search
|
||||
* result to open it as well as selecting text within it), we have to be
|
||||
* able to distinguish between those two actions.
|
||||
* If we detect a text selection action, we don't have to do anything.
|
||||
*
|
||||
* CAVEATS:
|
||||
* - In Firefox, Shift+click will open the URL in a new tab instead of
|
||||
* a window (unlike Chromium which seems to show the same behavior as with
|
||||
* native links).
|
||||
* - Firefox will insert \t\n in between table rows, causing the copied
|
||||
* text to be different from what is in the file/search result.
|
||||
*/
|
||||
const navigateToFile = useCallback(
|
||||
(
|
||||
event: KeyboardEvent<HTMLElement> | MouseEvent<HTMLElement>,
|
||||
{ line, character }: { line: number; character: number }
|
||||
): void => {
|
||||
// Testing for text selection is only necessary for mouse/click
|
||||
// events. Middle-click (event.button === 1) is already handled in the `onMouseUp` callback.
|
||||
if (
|
||||
(event.type === 'click' &&
|
||||
!isTextSelectionEvent(event as MouseEvent<HTMLElement>) &&
|
||||
(event as MouseEvent<HTMLElement>).button !== 1) ||
|
||||
(event as KeyboardEvent<HTMLElement>).key === 'Enter'
|
||||
) {
|
||||
const href = event.currentTarget.getAttribute('data-href')
|
||||
if (!event.defaultPrevented && href) {
|
||||
event.preventDefault()
|
||||
|
||||
openFile(result.repository, {
|
||||
path: result.path,
|
||||
revision: result.commit,
|
||||
position: {
|
||||
line: line - 1,
|
||||
character: character - 1,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
[openFile, result]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className={styles.fileMatchChildren} data-testid="file-match-children">
|
||||
{result.repoLastFetched && <LastSyncedIcon lastSyncedTime={result.repoLastFetched} />}
|
||||
{/* Path */}
|
||||
{result.type === 'path' && (
|
||||
<div className={styles.item} data-testid="file-match-children-item">
|
||||
<small>Path match</small>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Symbols */}
|
||||
{((result.type === 'symbol' && result.symbols) || []).map(symbol => (
|
||||
<button
|
||||
type="button"
|
||||
className={classNames('test-file-match-children-item', styles.item, 'btn btn-text-link')}
|
||||
key={`symbol:${symbol.name}${String(symbol.containerName)}${symbol.url}`}
|
||||
data-testid="file-match-children-item"
|
||||
onClick={() => openSymbol(symbol.url)}
|
||||
>
|
||||
<SymbolIcon kind={symbol.kind} className="mr-1" />
|
||||
<code>
|
||||
{symbol.name}{' '}
|
||||
{symbol.containerName && <span className="text-muted">{symbol.containerName}</span>}
|
||||
</code>
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Line matches */}
|
||||
{grouped && (
|
||||
<div>
|
||||
{grouped.map((group, index) => (
|
||||
<div
|
||||
key={`linematch:${getFileMatchUrl(result)}${group.position.line}:${
|
||||
group.position.character
|
||||
}`}
|
||||
className={classNames('test-file-match-children-item-wrapper', styles.itemCodeWrapper)}
|
||||
>
|
||||
<div
|
||||
data-href={createCodeExcerptLink(group)}
|
||||
className={classNames(
|
||||
'test-file-match-children-item',
|
||||
styles.item,
|
||||
styles.itemClickable
|
||||
)}
|
||||
onClick={event =>
|
||||
navigateToFile(event, {
|
||||
line: group.position.line,
|
||||
character: group.position.character,
|
||||
})
|
||||
}
|
||||
onMouseUp={navigateToFileOnMiddleMouseButtonClick}
|
||||
onKeyDown={event =>
|
||||
navigateToFile(event, {
|
||||
line: group.position.line,
|
||||
character: group.position.character,
|
||||
})
|
||||
}
|
||||
data-testid="file-match-children-item"
|
||||
tabIndex={0}
|
||||
role="link"
|
||||
>
|
||||
<CodeExcerpt
|
||||
repoName={result.repository}
|
||||
commitID={result.commit || ''}
|
||||
filePath={result.path}
|
||||
startLine={group.startLine}
|
||||
endLine={group.endLine}
|
||||
highlightRanges={group.matches}
|
||||
fetchHighlightedFileRangeLines={fetchHighlightedFileRangeLines}
|
||||
isFirst={index === 0}
|
||||
blobLines={group.blobLines}
|
||||
viewerUpdates={viewerUpdates}
|
||||
hoverifier={props.hoverifier}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
137
client/vscode/src/webview/search-panel/alias/Link.tsx
Normal file
137
client/vscode/src/webview/search-panel/alias/Link.tsx
Normal file
@ -0,0 +1,137 @@
|
||||
import React from 'react'
|
||||
import classNames from 'classnames'
|
||||
import * as H from 'history'
|
||||
import isAbsoluteUrl from 'is-absolute-url'
|
||||
|
||||
import styles from '@sourcegraph/wildcard/src/components/Link/AnchorLink/AnchorLink.module.scss'
|
||||
import { useWildcardTheme } from '@sourcegraph/wildcard/src/hooks/useWildcardTheme'
|
||||
|
||||
// This is based off the @sourcegraph/wildcard/Link component
|
||||
// to handle links in VSCE that works differently than in our web app
|
||||
// because in VSCE history does not work as it is in browser
|
||||
|
||||
export interface LinkProps
|
||||
extends Pick<
|
||||
React.AnchorHTMLAttributes<HTMLAnchorElement>,
|
||||
Exclude<keyof React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>
|
||||
> {
|
||||
to: string | H.LocationDescriptor<any>
|
||||
ref?: React.Ref<HTMLAnchorElement>
|
||||
}
|
||||
|
||||
/**
|
||||
* The component used to render a link. All shared code must use this component for links—not <a>, <Link>, etc.
|
||||
*
|
||||
* Different platforms (web app vs. browser extension) require the use of different link components:
|
||||
*
|
||||
* The web app uses <RouterLinkOrAnchor>, which uses react-router-dom's <Link> for relative URLs (for page
|
||||
* navigation using the HTML history API) and <a> for absolute URLs. The react-router-dom <Link> component only
|
||||
* works inside a react-router <BrowserRouter> context, so it wouldn't work in the browser extension.
|
||||
*
|
||||
* The browser extension uses <a> for everything (because code hosts don't generally use react-router). A
|
||||
* react-router-dom <Link> wouldn't work in the browser extension, because there is no <BrowserRouter>.
|
||||
*
|
||||
* This variable must be set at initialization time by calling {@link setLinkComponent}.
|
||||
*
|
||||
* The `to` property holds the destination URL (do not use `href`). If <a> is used, the `to` property value is
|
||||
* given as the `href` property value on the <a> element.
|
||||
*
|
||||
* @see setLinkComponent
|
||||
*/
|
||||
export let Link: React.FunctionComponent<LinkProps> = ({ to, children, ...props }) => (
|
||||
<a
|
||||
href={checkLink(to && typeof to !== 'string' ? H.createPath(to) : to)}
|
||||
id={to && typeof to !== 'string' ? H.createPath(to) : to}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
// Fail with helpful message if setLinkComponent has not been called when the <Link> component is used.
|
||||
Link = () => {
|
||||
throw new Error('No Link component set. You must call setLinkComponent to set the Link component to use.')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets (globally) the component to use for links. This must be set at initialization time.
|
||||
*
|
||||
* @see Link
|
||||
* @see AnchorLink
|
||||
*/
|
||||
export function setLinkComponent(component: typeof Link): void {
|
||||
Link = component
|
||||
}
|
||||
|
||||
export type AnchorLinkProps = LinkProps & {
|
||||
as?: LinkComponent
|
||||
}
|
||||
|
||||
export type LinkComponent = React.FunctionComponent<LinkProps>
|
||||
|
||||
export const AnchorLink: React.FunctionComponent<AnchorLinkProps> = React.forwardRef(
|
||||
({ to, as: Component, children, className, ...rest }: AnchorLinkProps, reference) => {
|
||||
const { isBranded } = useWildcardTheme()
|
||||
|
||||
const commonProps = {
|
||||
ref: reference,
|
||||
className: classNames(isBranded && styles.anchorLink, className),
|
||||
}
|
||||
|
||||
if (!Component) {
|
||||
return (
|
||||
<a href={checkLink(to && typeof to !== 'string' ? H.createPath(to) : to)} {...rest} {...commonProps}>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Component to={to} {...rest} {...commonProps}>
|
||||
{children}
|
||||
</Component>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* Uses react-router-dom's <Link> for relative URLs, <a> for absolute URLs. This is useful because passing an
|
||||
* absolute URL to <Link> will create an (almost certainly invalid) URL where the absolute URL is resolved to the
|
||||
* current URL, such as https://example.com/a/b/https://example.com/c/d.
|
||||
*/
|
||||
export const RouterLink: React.FunctionComponent<AnchorLinkProps> = React.forwardRef(
|
||||
({ to, children, ...rest }: AnchorLinkProps, reference) => (
|
||||
<AnchorLink
|
||||
to={checkLink(to && typeof to !== 'string' ? H.createPath(to) : to)}
|
||||
as={typeof to === 'string' && isAbsoluteUrl(to) ? undefined : Link}
|
||||
{...rest}
|
||||
ref={reference}
|
||||
>
|
||||
{children}
|
||||
</AnchorLink>
|
||||
)
|
||||
)
|
||||
|
||||
/**
|
||||
* Check if link is valid
|
||||
* Set invalid links to '#' because VS Code Web opens invalid links in new tabs
|
||||
* Invalid links includes links that start with 'sourcegraph://'
|
||||
*/
|
||||
function checkLink(uri: string): string {
|
||||
// Private instance user are required to provide access token
|
||||
// This is for users who has not provide an access token and is using dotcom by default
|
||||
if (
|
||||
uri.startsWith('/sign-up') ||
|
||||
uri.startsWith('/contexts') ||
|
||||
uri.startsWith('/code_search/reference/queries') ||
|
||||
uri.startsWith('/help')
|
||||
) {
|
||||
return `https://sourcegraph.com${uri}?editor=vscode&utm_medium=VSCODE&utm_source=sidebar&utm_campaign=vsce-sign-up&utm_content=sign-up`
|
||||
}
|
||||
if (uri.startsWith('https://')) {
|
||||
return uri
|
||||
}
|
||||
return '#'
|
||||
}
|
||||
@ -0,0 +1,73 @@
|
||||
@import 'wildcard/src/global-styles/breakpoints';
|
||||
|
||||
.wrapper {
|
||||
&:hover button {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
figure {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.thumbnail-button {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--border-radius);
|
||||
background-color: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.thumbnail-image {
|
||||
width: 100%;
|
||||
// Note: This is to reduce cumulative layout shift
|
||||
// It should be as close as possible to the source image aspect ratio
|
||||
aspect-ratio: 176/115;
|
||||
}
|
||||
|
||||
.play-icon-wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal {
|
||||
width: 70vw;
|
||||
@media (--lg-breakpoint-down) {
|
||||
width: 90vw;
|
||||
}
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.iframe-video-wrapper {
|
||||
position: relative;
|
||||
// stylelint-disable-next-line declaration-property-unit-allowed-list
|
||||
padding-top: 56.25%;
|
||||
}
|
||||
|
||||
.iframe-video {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
113
client/vscode/src/webview/search-panel/alias/ModalVideo.tsx
Normal file
113
client/vscode/src/webview/search-panel/alias/ModalVideo.tsx
Normal file
@ -0,0 +1,113 @@
|
||||
import React from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
|
||||
import { useWebviewPageContext } from '../../platform/context'
|
||||
|
||||
import styles from './ModalVideo.module.scss'
|
||||
|
||||
// We can't play video in VS Code Desktop: https://stackoverflow.com/a/57512681
|
||||
// Open video in YouTube instead.
|
||||
|
||||
interface ModalVideoProps {
|
||||
id: string
|
||||
title: string
|
||||
src: string
|
||||
thumbnail?: { src: string; alt: string }
|
||||
onToggle?: (isOpen: boolean) => void
|
||||
showCaption?: boolean
|
||||
className?: string
|
||||
assetsRoot?: string
|
||||
}
|
||||
|
||||
export const ModalVideo: React.FunctionComponent<ModalVideoProps> = ({
|
||||
title,
|
||||
src,
|
||||
thumbnail,
|
||||
onToggle,
|
||||
showCaption = false,
|
||||
className,
|
||||
assetsRoot = '',
|
||||
}) => {
|
||||
const { extensionCoreAPI } = useWebviewPageContext()
|
||||
|
||||
const onClick = (): void => {
|
||||
onToggle?.(false)
|
||||
extensionCoreAPI.openLink(src).catch(error => {
|
||||
console.error(`Error opening video at ${src}`, error)
|
||||
})
|
||||
}
|
||||
|
||||
let thumbnailElement = thumbnail ? (
|
||||
<button type="button" className={classNames(styles.thumbnailButton, 'border-0')} onClick={onClick}>
|
||||
<img
|
||||
src={`${assetsRoot}/${thumbnail.src}`}
|
||||
alt={thumbnail.alt}
|
||||
className={classNames(styles.thumbnailImage, 'rounded border opacity-75')}
|
||||
/>
|
||||
<div className={styles.playIconWrapper}>
|
||||
<PlayIcon />
|
||||
</div>
|
||||
</button>
|
||||
) : null
|
||||
|
||||
if (showCaption) {
|
||||
thumbnailElement = (
|
||||
<figure>
|
||||
{thumbnailElement}
|
||||
<figcaption>
|
||||
<button type="button" className="btn btn-link" onClick={onClick}>
|
||||
{title}
|
||||
</button>
|
||||
</figcaption>
|
||||
</figure>
|
||||
)
|
||||
}
|
||||
|
||||
return <div className={classNames(styles.wrapper, className)}>{thumbnailElement}</div>
|
||||
}
|
||||
|
||||
const PlayIcon = React.memo(() => (
|
||||
<svg width="50" height="53" viewBox="0 0 50 53" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g filter="url(#filter0_dd_268:5695)">
|
||||
<path d="M37.5 26.5L12.75 40.7894L12.75 12.2106L37.5 26.5Z" fill="white" />
|
||||
</g>
|
||||
<defs>
|
||||
<filter
|
||||
id="filter0_dd_268:5695"
|
||||
x="0.75"
|
||||
y="0.210449"
|
||||
width="48.75"
|
||||
height="52.5791"
|
||||
filterUnits="userSpaceOnUse"
|
||||
colorInterpolationFilters="sRGB"
|
||||
>
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
type="matrix"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
result="hardAlpha"
|
||||
/>
|
||||
<feOffset />
|
||||
<feGaussianBlur stdDeviation="6" />
|
||||
<feColorMatrix
|
||||
type="matrix"
|
||||
values="0 0 0 0 0.00505209 0 0 0 0 0.0449636 0 0 0 0 0.404167 0 0 0 0.25 0"
|
||||
/>
|
||||
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_268:5695" />
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
type="matrix"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
result="hardAlpha"
|
||||
/>
|
||||
<feOffset dy="4" />
|
||||
<feGaussianBlur stdDeviation="2" />
|
||||
<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0.055 0 0 0 0 0.25 0 0 0 0.25 0" />
|
||||
<feBlend mode="normal" in2="effect1_dropShadow_268:5695" result="effect2_dropShadow_268:5695" />
|
||||
<feBlend mode="normal" in="SourceGraphic" in2="effect2_dropShadow_268:5695" result="shape" />
|
||||
</filter>
|
||||
</defs>
|
||||
</svg>
|
||||
))
|
||||
19
client/vscode/src/webview/search-panel/alias/README.md
Normal file
19
client/vscode/src/webview/search-panel/alias/README.md
Normal file
@ -0,0 +1,19 @@
|
||||
# Aliased files
|
||||
|
||||
Lots of shared client code used in the initial implementation of the VS Code
|
||||
To expedite the implementation and review processes, we decided to "fork"
|
||||
code that would require significant refactoring to work in the VS Code
|
||||
extension context.
|
||||
|
||||
Our plan is remove the need for these aliased/forked files (method TBD).
|
||||
Resolving this divergence will reduce the risk of regressions introduced
|
||||
by changes in the way that base code interacts with forked code.
|
||||
|
||||
- Search result handling
|
||||
- We can't use relative links like in the web app, for most search result types (and eventually all),
|
||||
we need click handlers that call VS Code extension APIs.
|
||||
- Forked components: `FileMatchChildren`, `SearchResult`, `RepoFileLink`
|
||||
- What's changed:
|
||||
- Create a React context to wrap around `StreamingSearchResultsList` (shared) to pass
|
||||
VS Code extension APIs to forked search result components.
|
||||
- Change links to buttons, call VS Code file handlers from context on click.
|
||||
106
client/vscode/src/webview/search-panel/alias/RepoFileLink.tsx
Normal file
106
client/vscode/src/webview/search-panel/alias/RepoFileLink.tsx
Normal file
@ -0,0 +1,106 @@
|
||||
import * as React from 'react'
|
||||
|
||||
import { parseRepoRevision } from '@sourcegraph/shared/src/util/url'
|
||||
import { useIsTruncated } from '@sourcegraph/wildcard'
|
||||
|
||||
import { useOpenSearchResultsContext } from '../MatchHandlersContext'
|
||||
|
||||
/**
|
||||
* Returns the friendly display form of the repository name (e.g., removing "github.com/").
|
||||
*/
|
||||
export function displayRepoName(repoName: string): string {
|
||||
let parts = repoName.split('/')
|
||||
if (parts.length >= 3 && parts[0].includes('.')) {
|
||||
parts = parts.slice(1) // remove hostname from repo name (reduce visual noise)
|
||||
}
|
||||
return parts.join('/')
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits the repository name into the dir and base components.
|
||||
*/
|
||||
export function splitPath(path: string): [string, string] {
|
||||
const components = path.split('/')
|
||||
return [components.slice(0, -1).join('/'), components[components.length - 1]]
|
||||
}
|
||||
|
||||
interface Props {
|
||||
repoName: string
|
||||
repoURL: string
|
||||
filePath: string
|
||||
fileURL: string
|
||||
repoDisplayName?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A link to a repository or a file within a repository, formatted as "repo" or "repo > file". Unless you
|
||||
* absolutely need breadcrumb-like behavior, use this instead of FilePathBreadcrumb.
|
||||
*/
|
||||
export const RepoFileLink: React.FunctionComponent<Props> = ({
|
||||
repoDisplayName,
|
||||
repoName,
|
||||
repoURL,
|
||||
filePath,
|
||||
className,
|
||||
}) => {
|
||||
/**
|
||||
* Use the custom hook useIsTruncated to check if overflow: ellipsis is activated for the element
|
||||
* We want to do it on mouse enter as browser window size might change after the element has been
|
||||
* loaded initially
|
||||
*/
|
||||
const [titleReference, truncated, checkTruncation] = useIsTruncated()
|
||||
|
||||
const [fileBase, fileName] = splitPath(filePath)
|
||||
|
||||
const { openRepo, openFile } = useOpenSearchResultsContext()
|
||||
|
||||
const getRepoAndRevision = (): { repoName: string; revision: string | undefined } => {
|
||||
// Example: `/github.com/sourcegraph/sourcegraph@main`
|
||||
const indexOfSeparator = repoURL.indexOf('/-/')
|
||||
let repoRevision: string
|
||||
if (indexOfSeparator === -1) {
|
||||
repoRevision = repoURL // the whole string
|
||||
} else {
|
||||
repoRevision = repoURL.slice(0, indexOfSeparator) // the whole string leading up to the separator (allows revision to be multiple path parts)
|
||||
}
|
||||
let { repoName, revision } = parseRepoRevision(repoRevision)
|
||||
// Remove leading slash
|
||||
if (repoName.startsWith('/')) {
|
||||
repoName = repoName.slice(1)
|
||||
}
|
||||
return { repoName, revision }
|
||||
}
|
||||
|
||||
const onRepoClick = (): void => {
|
||||
const { repoName, revision } = getRepoAndRevision()
|
||||
|
||||
openRepo({
|
||||
repository: repoName,
|
||||
branches: revision ? [revision] : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
const onFileClick = (): void => {
|
||||
const { repoName, revision } = getRepoAndRevision()
|
||||
openFile(repoName, { path: filePath, revision })
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={titleReference}
|
||||
className={className}
|
||||
onMouseEnter={checkTruncation}
|
||||
data-tooltip={truncated ? (fileBase ? `${fileBase}/${fileName}` : fileName) : null}
|
||||
>
|
||||
<button onClick={onRepoClick} type="button" className="btn btn-text-link">
|
||||
{repoDisplayName || displayRepoName(repoName)}
|
||||
</button>{' '}
|
||||
›{' '}
|
||||
<button onClick={onFileClick} type="button" className="btn btn-text-link">
|
||||
{fileBase ? `${fileBase}/` : null}
|
||||
<strong>{fileName}</strong>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
208
client/vscode/src/webview/search-panel/alias/SearchResult.tsx
Normal file
208
client/vscode/src/webview/search-panel/alias/SearchResult.tsx
Normal file
@ -0,0 +1,208 @@
|
||||
import React from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
import ArchiveIcon from 'mdi-react/ArchiveIcon'
|
||||
import LockIcon from 'mdi-react/LockIcon'
|
||||
import SourceForkIcon from 'mdi-react/SourceForkIcon'
|
||||
|
||||
import { CommitSearchResultMatch } from '@sourcegraph/search-ui/src/components/CommitSearchResultMatch'
|
||||
import styles from '@sourcegraph/search-ui/src/components/SearchResult.module.scss'
|
||||
import { LastSyncedIcon } from '@sourcegraph/shared/src/components/LastSyncedIcon'
|
||||
import { displayRepoName } from '@sourcegraph/shared/src/components/RepoFileLink'
|
||||
import { RepoIcon } from '@sourcegraph/shared/src/components/RepoIcon'
|
||||
import { ResultContainer } from '@sourcegraph/shared/src/components/ResultContainer'
|
||||
import { SearchResultStar } from '@sourcegraph/shared/src/components/SearchResultStar'
|
||||
import { PlatformContextProps } from '@sourcegraph/shared/src/platform/context'
|
||||
import {
|
||||
CommitMatch,
|
||||
getCommitMatchUrl,
|
||||
getRepoMatchLabel,
|
||||
RepositoryMatch,
|
||||
} from '@sourcegraph/shared/src/search/stream'
|
||||
import { formatRepositoryStarCount } from '@sourcegraph/shared/src/util/stars'
|
||||
import { Timestamp } from '@sourcegraph/web/src/components/time/Timestamp'
|
||||
import { Icon } from '@sourcegraph/wildcard'
|
||||
|
||||
import { useOpenSearchResultsContext } from '../MatchHandlersContext'
|
||||
|
||||
interface Props extends PlatformContextProps<'requestGraphQL'> {
|
||||
result: CommitMatch | RepositoryMatch
|
||||
repoName: string
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
onSelect: () => void
|
||||
openInNewTab?: boolean
|
||||
containerClassName?: string
|
||||
}
|
||||
|
||||
export const SearchResult: React.FunctionComponent<Props> = ({
|
||||
result,
|
||||
icon,
|
||||
repoName,
|
||||
platformContext,
|
||||
onSelect,
|
||||
openInNewTab,
|
||||
containerClassName,
|
||||
}) => {
|
||||
const { openRepo, openCommit, instanceURL } = useOpenSearchResultsContext()
|
||||
|
||||
const renderTitle = (): JSX.Element => {
|
||||
const formattedRepositoryStarCount = formatRepositoryStarCount(result.repoStars)
|
||||
return (
|
||||
<div className={styles.title}>
|
||||
<RepoIcon repoName={repoName} className="icon-inline text-muted flex-shrink-0" />
|
||||
<span className="test-search-result-label ml-1 flex-shrink-past-contents text-truncate">
|
||||
{result.type === 'commit' && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-text-link"
|
||||
onClick={() =>
|
||||
openRepo({
|
||||
repository: result.repository,
|
||||
branches: [result.oid],
|
||||
})
|
||||
}
|
||||
>
|
||||
{displayRepoName(result.repository)}
|
||||
</button>
|
||||
{' › '}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-text-link"
|
||||
onClick={() => openCommit(getCommitMatchUrl(result))}
|
||||
>
|
||||
{result.authorName}
|
||||
</button>
|
||||
{': '}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-text-link"
|
||||
onClick={() => openCommit(getCommitMatchUrl(result))}
|
||||
>
|
||||
{result.message.split('\n', 1)[0]}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{result.type === 'repo' && (
|
||||
<button type="button" className="btn btn-text-link" onClick={() => openRepo(result)}>
|
||||
{displayRepoName(getRepoMatchLabel(result))}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
<span className={styles.spacer} />
|
||||
{result.type === 'commit' && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-text-link"
|
||||
onClick={() => openCommit(getCommitMatchUrl(result))}
|
||||
>
|
||||
<code className={styles.commitOid}>{result.oid.slice(0, 7)}</code>{' '}
|
||||
<Timestamp date={result.authorDate} noAbout={true} strict={true} />
|
||||
</button>
|
||||
)}
|
||||
{result.type === 'commit' && formattedRepositoryStarCount && <div className={styles.divider} />}
|
||||
{formattedRepositoryStarCount && (
|
||||
<>
|
||||
<SearchResultStar />
|
||||
{formattedRepositoryStarCount}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderBody = (): JSX.Element => {
|
||||
if (result.type === 'repo') {
|
||||
return (
|
||||
<div data-testid="search-repo-result">
|
||||
<div className={classNames(styles.searchResultMatch, 'p-2 flex-column')}>
|
||||
{result.repoLastFetched && <LastSyncedIcon lastSyncedTime={result.repoLastFetched} />}
|
||||
<div className="d-flex align-items-center flex-row">
|
||||
<div className={styles.matchType}>
|
||||
<small>Repository match</small>
|
||||
</div>
|
||||
{result.fork && (
|
||||
<>
|
||||
<div className={styles.divider} />
|
||||
<div>
|
||||
<Icon
|
||||
className={classNames('flex-shrink-0 text-muted', styles.icon)}
|
||||
as={SourceForkIcon}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<small>Fork</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{result.archived && (
|
||||
<>
|
||||
<div className={styles.divider} />
|
||||
<div>
|
||||
<Icon
|
||||
className={classNames('flex-shrink-0 text-muted', styles.icon)}
|
||||
as={ArchiveIcon}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<small>Archived</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{result.private && (
|
||||
<>
|
||||
<div className={styles.divider} />
|
||||
<div>
|
||||
<Icon
|
||||
className={classNames('flex-shrink-0 text-muted', styles.icon)}
|
||||
as={LockIcon}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<small>Private</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{result.description && (
|
||||
<>
|
||||
<div className={styles.dividerVertical} />
|
||||
<div>
|
||||
<small>
|
||||
<em>{result.description}</em>
|
||||
</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<CommitSearchResultMatch
|
||||
key={result.url}
|
||||
item={{
|
||||
...result,
|
||||
// Make it an absolute URL to open in browser.
|
||||
url: new URL(result.url, instanceURL).href,
|
||||
}}
|
||||
platformContext={platformContext}
|
||||
openInNewTab={openInNewTab}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ResultContainer
|
||||
icon={icon}
|
||||
collapsible={false}
|
||||
defaultExpanded={true}
|
||||
title={renderTitle()}
|
||||
resultType={result.type}
|
||||
onResultClicked={onSelect}
|
||||
expandedChildren={renderBody()}
|
||||
className={containerClassName}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,184 @@
|
||||
import { Observable } from 'rxjs'
|
||||
import { map } from 'rxjs/operators'
|
||||
|
||||
import { gql, dataOrThrowErrors } from '@sourcegraph/http-client'
|
||||
import { PlatformContext } from '@sourcegraph/shared/src/platform/context'
|
||||
import * as GQL from '@sourcegraph/shared/src/schema'
|
||||
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }
|
||||
export type Maybe<T> = T | null
|
||||
|
||||
/** All built-in and custom scalars, mapped to their actual values */
|
||||
export interface Scalars {
|
||||
ID: string
|
||||
String: string
|
||||
Boolean: boolean
|
||||
Int: number
|
||||
Float: number
|
||||
/** A quadruple that represents all possible states of the published value: true, false, 'draft', or null. */
|
||||
PublishedValue: boolean | 'draft'
|
||||
/** A valid JSON value. */
|
||||
JSONValue: unknown
|
||||
/** A string that contains valid JSON, with additional support for //-style comments and trailing commas. */
|
||||
JSONCString: string
|
||||
/** A Git object ID (SHA-1 hash, 40 hexadecimal characters). */
|
||||
GitObjectID: string
|
||||
/** An arbitrarily large integer encoded as a decimal string. */
|
||||
BigInt: string
|
||||
/**
|
||||
* An RFC 3339-encoded UTC date string, such as 1973-11-29T21:33:09Z. This value can be parsed into a
|
||||
* JavaScript Date using Date.parse. To produce this value from a JavaScript Date instance, use
|
||||
* Date#toISOString.
|
||||
*/
|
||||
DateTime: string
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a copy of the fetchSearchContexts function from @sourcegraph/search created for VSCE use
|
||||
* We have removed `query` from SearchContext to support instances below v3.36.0
|
||||
* as query does not exist in Search Context type in older instances
|
||||
* More context in https://github.com/sourcegraph/sourcegraph/issues/31022
|
||||
**/
|
||||
|
||||
const searchContextFragment = gql`
|
||||
fragment SearchContextFields on SearchContext {
|
||||
__typename
|
||||
id
|
||||
name
|
||||
namespace {
|
||||
__typename
|
||||
id
|
||||
namespaceName
|
||||
}
|
||||
spec
|
||||
description
|
||||
public
|
||||
autoDefined
|
||||
updatedAt
|
||||
viewerCanManage
|
||||
repositories {
|
||||
__typename
|
||||
repository {
|
||||
name
|
||||
}
|
||||
revisions
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export function fetchSearchContexts({
|
||||
first,
|
||||
namespaces,
|
||||
query,
|
||||
after,
|
||||
orderBy,
|
||||
descending,
|
||||
platformContext,
|
||||
}: {
|
||||
first: number
|
||||
query?: string
|
||||
namespaces?: Maybe<Scalars['ID']>[]
|
||||
after?: string
|
||||
orderBy?: GQL.SearchContextsOrderBy
|
||||
descending?: boolean
|
||||
platformContext: Pick<PlatformContext, 'requestGraphQL'>
|
||||
}): Observable<ListSearchContextsResult['searchContexts']> {
|
||||
return platformContext
|
||||
.requestGraphQL<ListSearchContextsResult, ListSearchContextsVariables>({
|
||||
request: gql`
|
||||
query ListSearchContexts(
|
||||
$first: Int!
|
||||
$after: String
|
||||
$query: String
|
||||
$namespaces: [ID]
|
||||
$orderBy: SearchContextsOrderBy
|
||||
$descending: Boolean
|
||||
) {
|
||||
searchContexts(
|
||||
first: $first
|
||||
after: $after
|
||||
query: $query
|
||||
namespaces: $namespaces
|
||||
orderBy: $orderBy
|
||||
descending: $descending
|
||||
) {
|
||||
nodes {
|
||||
...SearchContextFields
|
||||
}
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
totalCount
|
||||
}
|
||||
}
|
||||
${searchContextFragment}
|
||||
`,
|
||||
variables: {
|
||||
first,
|
||||
after: after ?? null,
|
||||
query: query ?? null,
|
||||
namespaces: namespaces ?? [],
|
||||
orderBy: orderBy ?? GQL.SearchContextsOrderBy.SEARCH_CONTEXT_SPEC,
|
||||
descending: descending ?? false,
|
||||
},
|
||||
mightContainPrivateInfo: true,
|
||||
})
|
||||
.pipe(
|
||||
map(dataOrThrowErrors),
|
||||
map(data => data.searchContexts)
|
||||
)
|
||||
}
|
||||
|
||||
export interface SearchContextFields {
|
||||
__typename: 'SearchContext'
|
||||
id: string
|
||||
name: string
|
||||
spec: string
|
||||
description: string
|
||||
public: boolean
|
||||
autoDefined: boolean
|
||||
updatedAt: string
|
||||
viewerCanManage: boolean
|
||||
query: string
|
||||
namespace: Maybe<
|
||||
| { __typename: 'User'; id: string; namespaceName: string }
|
||||
| { __typename: 'Org'; id: string; namespaceName: string }
|
||||
>
|
||||
repositories: {
|
||||
__typename: 'SearchContextRepositoryRevisions'
|
||||
revisions: string[]
|
||||
repository: { __typename?: 'Repository'; name: string }
|
||||
}[]
|
||||
}
|
||||
|
||||
export type AutoDefinedSearchContextsVariables = Exact<{ [key: string]: never }>
|
||||
|
||||
export interface AutoDefinedSearchContextsResult {
|
||||
__typename?: 'Query'
|
||||
autoDefinedSearchContexts: ({ __typename?: 'SearchContext' } & SearchContextFields)[]
|
||||
}
|
||||
|
||||
export type ListSearchContextsVariables = Exact<{
|
||||
first: Scalars['Int']
|
||||
after: Maybe<Scalars['String']>
|
||||
query: Maybe<Scalars['String']>
|
||||
namespaces: Maybe<Maybe<Scalars['ID']>[]>
|
||||
orderBy: Maybe<SearchContextsOrderBy>
|
||||
descending: Maybe<Scalars['Boolean']>
|
||||
}>
|
||||
|
||||
export interface ListSearchContextsResult {
|
||||
__typename?: 'Query'
|
||||
searchContexts: {
|
||||
__typename?: 'SearchContextConnection'
|
||||
totalCount: number
|
||||
nodes: ({ __typename?: 'SearchContext' } & SearchContextFields)[]
|
||||
pageInfo: { __typename?: 'PageInfo'; hasNextPage: boolean; endCursor: Maybe<string> }
|
||||
}
|
||||
}
|
||||
|
||||
/** SearchContextsOrderBy enumerates the ways a search contexts list can be ordered. */
|
||||
export enum SearchContextsOrderBy {
|
||||
SEARCH_CONTEXT_SPEC = 'SEARCH_CONTEXT_SPEC',
|
||||
SEARCH_CONTEXT_UPDATED_AT = 'SEARCH_CONTEXT_UPDATED_AT',
|
||||
}
|
||||
24
client/vscode/src/webview/search-panel/api.ts
Normal file
24
client/vscode/src/webview/search-panel/api.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { of } from 'rxjs'
|
||||
|
||||
import { proxySubscribable } from '@sourcegraph/shared/src/api/extension/api/common'
|
||||
|
||||
import { SearchPanelAPI } from '../../contract'
|
||||
|
||||
export const searchPanelAPI: SearchPanelAPI = {
|
||||
ping: () => {
|
||||
console.log('ping called')
|
||||
return proxySubscribable(of('pong'))
|
||||
},
|
||||
focusSearchBox: () => {
|
||||
// Call dynamic `focusSearchBox`.
|
||||
focusSearchBox()
|
||||
},
|
||||
}
|
||||
let focusSearchBox = (): void => {
|
||||
// Initially a noop. Waiting for monaco init
|
||||
}
|
||||
|
||||
// TODO move to api.ts file
|
||||
export const setFocusSearchBox = (replacementFocusSearchBox: (() => void) | null): void => {
|
||||
focusSearchBox = replacementFocusSearchBox || (() => {})
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
import React from 'react'
|
||||
|
||||
import classNames from 'classnames'
|
||||
|
||||
import { WebviewPageProps } from '../../platform/context'
|
||||
|
||||
import styles from '../index.module.scss'
|
||||
|
||||
export const BrandHeader: React.FunctionComponent<Pick<WebviewPageProps, 'theme'>> = ({ theme }) => (
|
||||
<>
|
||||
<img
|
||||
className={classNames(styles.logo)}
|
||||
src={`https://sourcegraph.com/.assets/img/sourcegraph-logo-${
|
||||
theme === 'theme-light' ? 'light' : 'dark'
|
||||
}.svg`}
|
||||
alt="Sourcegraph logo"
|
||||
/>
|
||||
<div data-testid="brand-header" className={classNames(styles.logoText)}>
|
||||
Search your code and 2M+ open source repositories
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
@ -0,0 +1,28 @@
|
||||
.container {
|
||||
width: 31rem;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.toggle {
|
||||
border-radius: var(--border-radius) !important;
|
||||
padding: 0.375rem 0.5rem;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin-bottom: 0.25rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.copy-text {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.icon {
|
||||
// stylelint-disable-next-line declaration-property-unit-whitelist
|
||||
padding: 15px;
|
||||
color: var(--merged-3);
|
||||
|
||||
svg {
|
||||
margin-right: 0 !important;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user