[SG-39797] Enable no-console ESLint rule (#40458)

This commit is contained in:
GitStart-SourceGraph 2022-10-03 14:19:17 +00:00 committed by GitHub
parent dbbb0e0ed0
commit 51befbfa52
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
112 changed files with 355 additions and 213 deletions

View File

@ -35,6 +35,7 @@ const config = {
rules: {
// Rules that are specific to this repo
// All other rules should go into https://github.com/sourcegraph/eslint-config
'no-console': 'error',
'monorepo/no-relative-import': 'error',
'@sourcegraph/sourcegraph/check-help-links': 'error',
'@typescript-eslint/consistent-type-exports': 'warn',
@ -221,6 +222,12 @@ See https://handbook.sourcegraph.com/community/faq#is-all-of-sourcegraph-open-so
'import/no-default-export': 'off',
},
},
{
files: ['**/gulpfile.js', '**/story/**.tsx', '**/story/**.ts', '*.story.tsx'],
rules: {
'no-console': 'off',
},
},
],
}

View File

@ -8,7 +8,7 @@ import { Observable, Subject, Subscription } from 'rxjs'
import { catchError, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators'
import { Badged } from 'sourcegraph'
import { asError, ErrorLike, isErrorLike, isDefined, property } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, isDefined, property, logger } from '@sourcegraph/common'
import { Location } from '@sourcegraph/extension-api-types'
import { FileSearchResult, FetchFileParameters } from '@sourcegraph/search-ui'
import { VirtualList } from '@sourcegraph/shared/src/components/VirtualList'
@ -105,7 +105,7 @@ export class FileLocations extends React.PureComponent<Props, State> {
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)

View File

@ -5,5 +5,8 @@ module.exports = {
...baseConfig.parserOptions,
project: [__dirname + '/tsconfig.json', __dirname + '/src/end-to-end/tsconfig.json'],
},
rules: {
'no-console': 'off',
},
overrides: baseConfig.overrides,
}

View File

@ -8,6 +8,8 @@ module.exports = {
...baseConfig.parserOptions,
project: [__dirname + '/tsconfig.json'],
},
rules: {},
rules: {
'no-console': 'off',
},
overrides: baseConfig.overrides,
}

View File

@ -37,7 +37,7 @@ import {
} from 'rxjs/operators'
import { Key } from 'ts-key-enum'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { Position, Range } from '@sourcegraph/extension-api-types'
import { elementOverlaps, scrollRectangleIntoCenterIfNeeded, toMaybeLoadingProviderResult } from './helpers'
@ -563,7 +563,7 @@ export function createHoverifier<C extends object, D, A>({
if (target) {
part = dom.getDiffCodePart?.(target)
} else {
console.warn('Could not find target for position in file', position)
logger.warn('Could not find target for position in file', position)
}
}
}
@ -904,7 +904,7 @@ export function createHoverifier<C extends object, D, A>({
// Get the document highlights for that position
return from(getDocumentHighlights(position)).pipe(
catchError(error => {
console.error(error)
logger.error(error)
return []
}),
map(documentHighlights => ({

View File

@ -10,3 +10,4 @@ export * from './rxjs'
export * from './strings'
export * from './types'
export * from './url'
export * from './logger'

View File

@ -0,0 +1,38 @@
/* eslint-disable no-console, jsdoc/check-indentation */
export interface Logger {
log: Console['log']
warn: Console['warn']
error: Console['error']
info: Console['info']
debug: Console['debug']
}
type LoggerArgsType = Parameters<Logger['log']>
/**
* The logger utility to be used instead of `console.*` methods in browser environments to:
* 1. Avoid leaving `console.*` added for debugging purposes during development.
* 2. Have more control over logging pipelines. E.g.,
* - Forward errors to the error monitoring services.
* - Dynamically change logging level depending on the environment.
*
* Check out the Unified logger service RFC for more context:
* https://docs.google.com/document/d/1PolGRDS9XfKj-IJEBi7BTbVZeUsQfM-3qpjLsLlB-yw/edit
*/
export const logger: Logger = {
log: (...args: LoggerArgsType) => {
console.log(...args)
},
error: (...args: LoggerArgsType) => {
console.error(...args)
},
warn: (...args: LoggerArgsType) => {
console.warn(...args)
},
info: (...args: LoggerArgsType) => {
console.info(...args)
},
debug: (...args: LoggerArgsType) => {
console.debug(...args)
},
}

View File

@ -6,6 +6,8 @@ import { marked } from 'marked'
import sanitize from 'sanitize-html'
import { Overwrite } from 'utility-types'
import { logger } from '../logger'
/**
* Escapes HTML by replacing characters like `<` with their HTML escape sequences like `&lt;`
*/
@ -37,7 +39,7 @@ export const highlightCodeSafe = (code: string, language?: string): string => {
}
return highlightAuto(code).value
} catch (error) {
console.warn('Error syntax-highlighting hover markdown code block', error)
logger.warn('Error syntax-highlighting hover markdown code block', error)
return escapeHTML(code)
}
}

View File

@ -1,6 +1,8 @@
import { ApolloQueryResult, ObservableQuery, OperationVariables } from '@apollo/client'
import { Observable } from 'rxjs'
import { logger } from '@sourcegraph/common'
/**
* Converts ObservableQuery returned by `client.watchQuery` to `rxjs` Observable.
*
@ -39,7 +41,7 @@ export function fromObservableQueryPromise<T extends object, V extends object>(
return function unsubscribe() {
subscriber.unsubscribe()
subscriptionPromise.then(subscription => subscription?.unsubscribe()).catch(error => console.log(error))
subscriptionPromise.then(subscription => subscription?.unsubscribe()).catch(error => logger.error(error))
}
})
}

View File

@ -8,5 +8,6 @@ module.exports = {
...baseConfig.parserOptions,
project: [__dirname + '/tsconfig.json'],
},
rules: { 'no-console': 'off' },
overrides: baseConfig.overrides,
}

View File

@ -2,6 +2,8 @@ import { Attributes } from '@opentelemetry/api'
import { ExportResultCode, hrTimeToMilliseconds, ExportResult } from '@opentelemetry/core'
import { SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base'
import { logger } from '@sourcegraph/common'
import { parseAttributes } from '../sdk/pareAttributes'
interface FormattedSpan {
@ -73,7 +75,7 @@ export class ConsoleBatchSpanExporter implements SpanExporter {
const formattedSpans = this.groupSpans(spans).map(this.nestSpans)
for (const span of formattedSpans) {
console.debug(span)
logger.debug(span)
}
return resultCallback({ code: ExportResultCode.SUCCESS })

View File

@ -8,6 +8,8 @@ module.exports = {
...baseConfig.parserOptions,
project: [__dirname + '/tsconfig.json'],
},
rules: {},
rules: {
'no-console': 'off',
},
overrides: baseConfig.overrides,
}

View File

@ -6,7 +6,7 @@ import { of } from 'rxjs'
import { catchError } from 'rxjs/operators'
import sanitizeHtml from 'sanitize-html'
import { highlightNode } from '@sourcegraph/common'
import { highlightNode, logger } from '@sourcegraph/common'
import { highlightCode } from '@sourcegraph/search'
import { Markdown } from '@sourcegraph/shared/src/components/Markdown'
import { PlatformContextProps } from '@sourcegraph/shared/src/platform/context'
@ -47,7 +47,7 @@ export const CommitSearchResultMatch: React.FunctionComponent<CommitSearchResult
.pipe(
// Return the rendered markdown if highlighting fails.
catchError(error => {
console.log(error)
logger.log(error)
return of('<pre>' + sanitizeHtml(item.content) + '</pre>')
})
)

View File

@ -6,5 +6,11 @@ module.exports = {
...baseConfig.parserOptions,
project: [__dirname + '/tsconfig.json', __dirname + '/src/testing/tsconfig.json'],
},
overrides: baseConfig.overrides,
overrides: [
...baseConfig.overrides,
{
files: ['dev/**/*.*'],
rules: { 'no-console': 'off' },
},
],
}

View File

@ -7,7 +7,7 @@ import { from, Subject, Subscription } from 'rxjs'
import { catchError, map, mapTo, mergeMap, startWith, tap } from 'rxjs/operators'
import { ActionContribution, Evaluated } from '@sourcegraph/client-api'
import { asError, ErrorLike, isErrorLike, isExternalLink } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, isExternalLink, logger } from '@sourcegraph/common'
import {
LoadingSpinner,
Button,
@ -161,7 +161,7 @@ export class ActionItem extends React.PureComponent<ActionItemProps, State, type
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)
}

View File

@ -4,7 +4,7 @@ import { from, Observable, observable as symbolObservable, Subscription } from '
import { mergeMap, finalize } from 'rxjs/operators'
import { Subscribable } from 'sourcegraph'
import { asError } from '@sourcegraph/common'
import { asError, logger } from '@sourcegraph/common'
import { ProxySubscribable } from '../../extension/api/common'
import { isPromiseLike, syncRemoteSubscription } from '../../util'
@ -111,7 +111,7 @@ export const wrapRemoteObservable = <T>(
export const finallyReleaseProxy = <T>() => (source: Observable<T> & Partial<ProxySubscribed>): Observable<T> => {
const { proxySubscription } = source
if (!proxySubscription) {
console.warn('finallyReleaseProxy() used on Observable without proxy subscription')
logger.warn('finallyReleaseProxy() used on Observable without proxy subscription')
return source
}
return source.pipe(finalize(() => proxySubscription.unsubscribe()))

View File

@ -3,6 +3,8 @@ import { from, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Unsubscribable } from 'sourcegraph'
import { logger } from '@sourcegraph/common'
import { PlatformContext, ClosableEndpointPair } from '../../platform/context'
import { isSettingsValid } from '../../settings/settings'
import { FlatExtensionHostAPI, MainThreadAPI } from '../contract'
@ -88,7 +90,7 @@ export async function createExtensionHostClientConnection(
comlink.expose(clientAPI, endpoints.expose)
proxy.mainThreadAPIInitialized().catch(() => {
console.error('Error notifying extension host of main thread API init.')
logger.error('Error notifying extension host of main thread API init.')
})
// TODO(tj): return MainThreadAPI and add to Controller interface

View File

@ -3,7 +3,7 @@ import { combineLatest, from, Observable, of, throwError } from 'rxjs'
import { fromFetch } from 'rxjs/fetch'
import { catchError, distinctUntilChanged, map, publishReplay, refCount, shareReplay, switchMap } from 'rxjs/operators'
import { asError, isErrorLike } from '@sourcegraph/common'
import { asError, isErrorLike, logger } from '@sourcegraph/common'
import { checkOk } from '@sourcegraph/http-client'
import {
@ -95,7 +95,7 @@ export const getEnabledExtensions = once(
const sideloadedExtension = from(context.sideloadedExtensionURL).pipe(
switchMap(url => (url ? getConfiguredSideloadedExtension(url) : of(null))),
catchError(error => {
console.error('Error sideloading extension', error)
logger.error('Error sideloading extension', error)
return of(null)
})
)

View File

@ -3,7 +3,7 @@ import { Subscription, from, Observable, Subject, of } from 'rxjs'
import { publishReplay, refCount, switchMap } from 'rxjs/operators'
import * as sourcegraph from 'sourcegraph'
import { asError } from '@sourcegraph/common'
import { asError, logger } from '@sourcegraph/common'
import { registerBuiltinClientCommands } from '../../commands/commands'
import { PlatformContext } from '../../platform/context'
@ -177,7 +177,7 @@ export const initMainThreadAPI = (
return proxySubscribable(getEnabledExtensions(platformContext))
},
logEvent: (eventName, eventProperties) => platformContext.telemetryService?.log(eventName, eventProperties),
logExtensionMessage: (...data) => console.log(...data),
logExtensionMessage: (...data) => logger.log(...data),
}
return { api, exposedToClient, subscription }

View File

@ -1,4 +1,4 @@
import { isDefined } from '@sourcegraph/common'
import { isDefined, logger } from '@sourcegraph/common'
import { ConfiguredExtension, getScriptURLFromExtensionManifest } from '../../extensions/extension'
import { ExecutableExtension, extensionsWithMatchedActivationEvent } from '../extension/activation'
@ -54,6 +54,6 @@ export function preloadExtensions({
loadedScriptURLs.add(activeExtension.scriptURL)
}
} catch (error) {
console.error('Error preloading Sourcegraph extensions:', error)
logger.error('Error preloading Sourcegraph extensions:', error)
}
}

View File

@ -4,6 +4,8 @@ import { Remote } from 'comlink'
import { from, Observable, of, TimeoutError } from 'rxjs'
import { catchError, filter, first, switchMap, timeout } from 'rxjs/operators'
import { logger } from '@sourcegraph/common'
import { FlatExtensionHostAPI } from '../contract'
import { SharedEventLogger } from '../sharedEventLogger'
@ -57,7 +59,7 @@ export function transformSearchQuery({
timeout(TRANSFORM_QUERY_TIMEOUT),
catchError(error => {
if (error instanceof TimeoutError) {
console.error(`Extension query transformers took more than ${TRANSFORM_QUERY_TIMEOUT}ms`)
logger.error(`Extension query transformers took more than ${TRANSFORM_QUERY_TIMEOUT}ms`)
}
return of(query)
})

View File

@ -4,7 +4,7 @@ import { catchError, concatMap, distinctUntilChanged, first, map, switchMap, tap
import sourcegraph from 'sourcegraph'
import { Contributions } from '@sourcegraph/client-api'
import { asError, ErrorLike, isErrorLike, hashCode, memoizeObservable } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, hashCode, memoizeObservable, logger } from '@sourcegraph/common'
import { ConfiguredExtension, getScriptURLFromExtensionManifest, splitExtensionID } from '../../extensions/extension'
import { areExtensionsSame, getEnabledExtensionsForSubject } from '../../extensions/extensions'
@ -192,20 +192,20 @@ export function activateExtensions(
// noop
})
} catch (error) {
console.error(
logger.error(
`Fail to log ExtensionActivation event for extension ${id}:`,
asError(error)
)
}
}
console.log(`Activating Sourcegraph extension: ${id}`)
logger.log(`Activating Sourcegraph extension: ${id}`)
return activate(id, scriptURL, createExtensionAPI).catch(error =>
console.error(`Error activating extension ${id}:`, asError(error))
logger.error(`Error activating extension ${id}:`, asError(error))
)
}),
[...toDeactivate].map(id =>
deactivate(id).catch(error =>
console.error(`Error deactivating extension ${id}:`, asError(error))
logger.error(`Error deactivating extension ${id}:`, asError(error))
)
),
])
@ -213,7 +213,7 @@ export function activateExtensions(
}),
map(() => ({ activated: toActivate, deactivated: toDeactivate })),
catchError(error => {
console.error('Uncaught error during extension activation', error)
logger.error('Uncaught error during extension activation', error)
return []
})
)
@ -343,29 +343,29 @@ export function extensionsWithMatchedActivationEvent<Extension extends Configure
if (!extension.manifest) {
const match = /^sourcegraph\/lang-(.*)$/.exec(extension.id)
if (match) {
console.warn(
logger.warn(
`Extension ${extension.id} has been renamed to sourcegraph/${match[1]}. It's safe to remove ${extension.id} from your settings.`
)
} else {
console.warn(
logger.warn(
`Extension ${extension.id} was not found. Remove it from settings to suppress this warning.`
)
}
return false
}
if (isErrorLike(extension.manifest)) {
console.warn(extension.manifest)
logger.warn(extension.manifest)
return false
}
if (!extension.manifest.activationEvents) {
console.warn(`Extension ${extension.id} has no activation events, so it will never be activated.`)
logger.warn(`Extension ${extension.id} has no activation events, so it will never be activated.`)
return false
}
return extension.manifest.activationEvents.some(
event => event === '*' || languageActivationEvents.has(event)
)
} catch (error) {
console.error(error)
logger.error(error)
}
return false
})

View File

@ -3,7 +3,7 @@ import { catchError, defaultIfEmpty, map, mergeMap, scan, startWith, switchMap }
import sourcegraph from 'sourcegraph'
import { ContributableViewContainer } from '@sourcegraph/client-api'
import { allOf, asError, ErrorLike, isDefined, isExactly, isNot, property } from '@sourcegraph/common'
import { allOf, asError, ErrorLike, isDefined, isExactly, isNot, logger, property } from '@sourcegraph/common'
import { RegisteredViewProvider, ViewContexts, ViewProviderResult } from '../extensionHostApi'
@ -61,7 +61,7 @@ export function callViewProvidersInParallel<W extends ContributableViewContainer
providerResultToObservable(provider.viewProvider.provideView(context)).pipe(
defaultIfEmpty<sourcegraph.View | null | undefined>(null),
catchError((error: unknown): [ErrorLike] => {
console.error('View provider errored:', error)
logger.error('View provider errored:', error)
// Pass only primitive copied values because Error object is not
// cloneable in Firefox and Safari

View File

@ -4,7 +4,7 @@ import { BehaviorSubject, EMPTY, ReplaySubject } from 'rxjs'
import { debounceTime, mapTo } from 'rxjs/operators'
import * as sourcegraph from 'sourcegraph'
import { asError } from '@sourcegraph/common'
import { asError, logger } from '@sourcegraph/common'
import { Location, MarkupKind, Position, Range, Selection } from '@sourcegraph/extension-api-classes'
import { ClientAPI } from '../client/api/api'
@ -286,19 +286,19 @@ export function createExtensionAPIFactory(
// These were removed, but keep them here so that calls from old extensions do not throw
// an exception and completely break.
registerTypeDefinitionProvider: () => {
console.warn(
logger.warn(
'sourcegraph.languages.registerTypeDefinitionProvider was removed. Use sourcegraph.languages.registerLocationProvider instead.'
)
return { unsubscribe: () => undefined }
},
registerImplementationProvider: () => {
console.warn(
logger.warn(
'sourcegraph.languages.registerImplementationProvider was removed. Use sourcegraph.languages.registerLocationProvider instead.'
)
return { unsubscribe: () => undefined }
},
registerCompletionItemProvider: (): sourcegraph.Unsubscribable => {
console.warn('sourcegraph.languages.registerCompletionItemProvider was removed.')
logger.warn('sourcegraph.languages.registerCompletionItemProvider was removed.')
return { unsubscribe: () => undefined }
},
}
@ -337,7 +337,7 @@ export function createExtensionAPIFactory(
clientAPI
.logExtensionMessage(`🧩 %c${extensionID}`, 'background-color: lightgrey;', ...data)
.catch(error => {
console.error('Error sending extension message to main thread:', error)
logger.error('Error sending extension message to main thread:', error)
})
}
},

View File

@ -27,6 +27,7 @@ import {
isDefined,
isExactly,
isNot,
logger,
property,
} from '@sourcegraph/common'
import * as clientType from '@sourcegraph/extension-api-types'
@ -407,7 +408,7 @@ export function createExtensionHostAPI(state: ExtensionHostState): FlatExtension
} catch (error) {
// An error during evaluation causes all of the contributions in the same entry to be
// discarded.
console.log('Discarding contributions: evaluating expressions or templates failed.', {
logger.error('Discarding contributions: evaluating expressions or templates failed.', {
contributions,
error,
})
@ -455,7 +456,7 @@ export function createExtensionHostAPI(state: ExtensionHostState): FlatExtension
return providerResultToObservable(provider.viewProvider.provideView(context))
}),
catchError((error: unknown) => {
console.error('View provider errored:', error)
logger.error('View provider errored:', error)
// Pass only primitive copied values because Error object is not
// cloneable in Firefox and Safari
const { message, name, stack } = asError(error)
@ -575,7 +576,7 @@ export function callProviders<TRegisteredProvider, TProviderResult, TMergedResul
): Observable<MaybeLoadingResult<TMergedResult>> {
const logError = (...args: any): void => {
if (logErrors) {
console.error('Provider errored:', ...args)
logger.error('Provider errored:', ...args)
}
}
const safeInvokeProvider = (provider: TRegisteredProvider): sourcegraph.ProviderResult<TProviderResult> => {
@ -721,7 +722,7 @@ function callViewProviders<W extends ContributableViewContainer>(
providerResultToObservable(viewProvider.provideView(context)).pipe(
defaultIfEmpty<sourcegraph.View | null | undefined>(null),
catchError((error: unknown): [ErrorLike] => {
console.error('View provider errored:', error)
logger.error('View provider errored:', error)
// Pass only primitive copied values because Error object is not
// cloneable in Firefox and Safari
const { message, name, stack } = asError(error)

View File

@ -3,7 +3,7 @@ import '../../polyfills'
import { fromEvent } from 'rxjs'
import { take } from 'rxjs/operators'
import { hasProperty } from '@sourcegraph/common'
import { hasProperty, logger } from '@sourcegraph/common'
import { isEndpointPair } from '../../platform/context'
@ -34,7 +34,7 @@ async function extensionHostMain(): Promise<void> {
const extensionHost = startExtensionHost(endpoints)
self.addEventListener('unload', () => extensionHost.unsubscribe())
} catch (error) {
console.error('Error starting the extension host:', error)
logger.error('Error starting the extension host:', error)
self.close()
}
}

View File

@ -1,6 +1,8 @@
import { BehaviorSubject } from 'rxjs'
import sinon from 'sinon'
import { logger } from '@sourcegraph/common'
import { ClientAPI } from '../../client/api/api'
import { pretendRemote } from '../../util'
import { proxySubscribable } from '../api/common'
@ -10,7 +12,7 @@ import { initializeExtensionHostTest } from './test-helpers'
const noopMain = pretendRemote<ClientAPI>({
getEnabledExtensions: () => proxySubscribable(new BehaviorSubject([])),
getScriptURLForExtension: () => undefined,
logExtensionMessage: (...data) => console.log(...data),
logExtensionMessage: (...data) => logger.log(...data),
})
describe('Extension logging', () => {

View File

@ -11,7 +11,7 @@ import stringScore from 'string-score'
import { Key } from 'ts-key-enum'
import { ContributableMenu, Contributions, Evaluated } from '@sourcegraph/client-api'
import { memoizeObservable } from '@sourcegraph/common'
import { memoizeObservable, logger } from '@sourcegraph/common'
import { Shortcut } from '@sourcegraph/shared/src/react-shortcuts'
import {
ButtonProps,
@ -122,7 +122,7 @@ export class CommandList extends React.PureComponent<CommandListProps, State> {
}
return null
} catch (error) {
console.error('Error reading recent actions:', error)
logger.error('Error reading recent actions:', error)
}
CommandList.writeRecentActions(null)
return null
@ -137,7 +137,7 @@ export class CommandList extends React.PureComponent<CommandListProps, State> {
localStorage.setItem(CommandList.RECENT_ACTIONS_STORAGE_KEY, value)
}
} catch (error) {
console.error('Error writing recent actions:', error)
logger.error('Error writing recent actions:', error)
}
}

View File

@ -18,7 +18,7 @@ import {
import { ContributableMenu, TextDocumentPositionParameters } from '@sourcegraph/client-api'
import { HoveredToken, LOADER_DELAY, MaybeLoadingResult, emitLoading } from '@sourcegraph/codeintellify'
import { asError, ErrorLike, isErrorLike, isExternalLink } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, isExternalLink, logger } from '@sourcegraph/common'
import { Location } from '@sourcegraph/extension-api-types'
import { Context } from '@sourcegraph/template-parser'
@ -534,7 +534,7 @@ export function registerHoverContributions({
// Don't expose remote subscriptions, only sync subscriptions bag
.then(() => undefined)
.catch(() => {
console.error('Failed to register "Go to Definition" and "Find references" actions with extension host')
logger.error('Failed to register "Go to Definition" and "Find references" actions with extension host')
})
// Return promise to provide a way for callers to know when contributions have been successfully registered

View File

@ -5,7 +5,7 @@ import { from, merge, Subscription } from 'rxjs'
import { delay, map, mergeMap, switchMap, takeWhile } from 'rxjs/operators'
import { tabbable } from 'tabbable'
import { asError } from '@sourcegraph/common'
import { asError, logger } from '@sourcegraph/common'
import { wrapRemoteObservable } from '../api/client/api/common'
import { NotificationType } from '../api/extension/extensionHostApi'
@ -180,7 +180,7 @@ export class Notifications extends React.PureComponent<NotificationsProps, Notif
[HAS_NOTIFICATIONS_CONTEXT_KEY]: this.state.notifications.length > 0,
})
)
.catch(error => console.error('Error updating context for notifications', error))
.catch(error => logger.error('Error updating context for notifications', error))
}
public componentWillUnmount(): void {

View File

@ -1,5 +1,7 @@
import React, { createContext, useEffect } from 'react'
import { logger } from '@sourcegraph/common'
import { migrateLocalStorageToTemporarySettings } from './migrateLocalStorageToTemporarySettings'
import { TemporarySettingsStorage } from './TemporarySettingsStorage'
@ -23,7 +25,7 @@ export const TemporarySettingsProvider: React.FunctionComponent<
await migrateLocalStorageToTemporarySettings(temporarySettingsStorage)
}
migrate().catch(console.error)
migrate().catch(logger.error)
}, [temporarySettingsStorage])
// Dispose temporary settings storage on unmount.

View File

@ -3,6 +3,7 @@ import { isEqual } from 'lodash'
import { Observable, of, Subscription, from, ReplaySubject, Subscriber } from 'rxjs'
import { distinctUntilChanged, map } from 'rxjs/operators'
import { logger } from '@sourcegraph/common'
import { fromObservableQuery } from '@sourcegraph/http-client'
import { GetTemporarySettingsResult } from '../../graphql-operations'
@ -93,7 +94,7 @@ class LocalStorageSettingsBackend implements SettingsBackend {
settingsLoaded = true
}
} catch (error: unknown) {
console.error(error)
logger.error(error)
}
if (!settingsLoaded) {
@ -121,7 +122,7 @@ class LocalStorageSettingsBackend implements SettingsBackend {
const currentSettings = JSON.parse(encodedCurrentSettings) as TemporarySettings
localStorage.setItem(this.TemporarySettingsKey, JSON.stringify({ ...currentSettings, ...newSettings }))
} catch (error: unknown) {
console.error(error)
logger.error(error)
}
return of()
@ -167,7 +168,7 @@ class ServersideSettingsBackend implements SettingsBackend {
const settings = data.temporarySettings.contents
parsedSettings = JSON.parse(settings) as TemporarySettings
} catch (error: unknown) {
console.error(error)
logger.error(error)
}
return parsedSettings || {}
@ -205,7 +206,7 @@ class ServersideSettingsBackend implements SettingsBackend {
map(() => {}) // Ignore return value, always empty
)
} catch (error: unknown) {
console.error(error)
logger.error(error)
}
return of()

View File

@ -1,5 +1,7 @@
import { take } from 'rxjs/operators'
import { logger } from '@sourcegraph/common'
import { TemporarySettings, TemporarySettingsSchema } from './TemporarySettings'
import { TemporarySettingsStorage } from './TemporarySettingsStorage'
@ -78,7 +80,7 @@ export async function migrateLocalStorageToTemporarySettings(storage: TemporaryS
localStorage.removeItem(migration.localStorageKey)
}
} catch (error) {
console.error(
logger.error(
`Failed to migrate temporary settings "${migration.temporarySettingsKey}" from localStorage using key "${migration.localStorageKey}"`,
error
)

View File

@ -2,6 +2,8 @@ import { AxePuppeteer } from '@axe-core/puppeteer'
import type { Result, NodeResult, RunOptions } from 'axe-core'
import { Page } from 'puppeteer'
import { logger } from '@sourcegraph/common'
/**
* Takes a list of Axe violation nodes and formats them into a readable string.
*/
@ -74,6 +76,6 @@ export async function accessibilityAudit(page: Page, config: AccessibilityAuditC
throw new Error(errorMessage)
}
console.warn(errorMessage)
logger.warn(errorMessage)
}
}

View File

@ -3,6 +3,8 @@ import pTimeout from 'p-timeout'
import { Browser, WebWorker } from 'puppeteer'
import * as uuid from 'uuid'
import { logger } from '@sourcegraph/common'
import { Driver } from './driver'
declare global {
@ -48,7 +50,7 @@ export async function recordCoverage(browser: Browser): Promise<void> {
2000,
() => {
if (!warnedNoCoverage) {
console.error(
logger.error(
`No coverage found in target ${target.url()}\n` +
'Run the dev Sourcegraph instance with COVERAGE_INSTRUMENT=true to track coverage.'
)

View File

@ -21,7 +21,7 @@ import { from, fromEvent, merge, Subscription } from 'rxjs'
import { filter, map, concatAll, mergeMap, mergeAll, takeUntil } from 'rxjs/operators'
import { Key } from 'ts-key-enum'
import { isDefined } from '@sourcegraph/common'
import { isDefined, logger } from '@sourcegraph/common'
import { dataOrThrowErrors, gql, GraphQLResult } from '@sourcegraph/http-client'
import { ExternalServiceKind } from '../graphql-operations'
@ -199,7 +199,7 @@ export class Driver {
)
)
)
.subscribe(formattedLine => console.log(formattedLine))
.subscribe(formattedLine => logger.log(formattedLine))
)
}
}
@ -295,7 +295,7 @@ export class Driver {
if (!this.keepBrowser) {
await this.browser.close()
}
console.log(
logger.log(
'\n Visited routes:\n' +
[
...new Set(
@ -407,7 +407,7 @@ export class Driver {
}
// Navigate to the add external service page.
console.log('Adding external service of kind', kind)
logger.log('Adding external service of kind', kind)
await this.page.goto(this.sourcegraphBaseUrl + '/site-admin/external-services/new')
await this.page.waitForSelector(`[data-test-external-service-card-link="${kind.toUpperCase()}"]`, {
visible: true,
@ -800,7 +800,7 @@ export async function createDriverForTest(options?: Partial<DriverOptions>): Pro
args.push(`--window-size=${config.windowWidth},${config.windowHeight}`)
if (process.getuid() === 0) {
// TODO don't run as root in CI
console.warn('Running as root, disabling sandbox')
logger.warn('Running as root, disabling sandbox')
args.push('--no-sandbox', '--disable-setuid-sandbox')
}
if (loadExtension) {

View File

@ -14,7 +14,7 @@ import { Subject, Subscription, throwError } from 'rxjs'
import { first, timeoutWith } from 'rxjs/operators'
import { STATIC_ASSETS_PATH } from '@sourcegraph/build-config'
import { asError, keyExistsIn } from '@sourcegraph/common'
import { logger, asError, keyExistsIn } from '@sourcegraph/common'
import { ErrorGraphQLResult, GraphQLResult } from '@sourcegraph/http-client'
// eslint-disable-next-line no-restricted-imports
import { SourcegraphContext } from '@sourcegraph/web/src/jscontext'
@ -208,7 +208,7 @@ export const createSharedIntegrationTestContext = async <
if ((asError(error) as NodeJS.ErrnoException).code === 'ENOENT') {
response.sendStatus(404)
} else {
console.error(error)
logger.error(error)
response.status(500).send(asError(error).message)
}
}
@ -318,11 +318,11 @@ export const createSharedIntegrationTestContext = async <
try {
localStorage.clear()
} catch (error) {
console.error('Failed to clear localStorage!', error)
logger.error('Failed to clear localStorage!', error)
}
}),
DISPOSE_ACTION_TIMEOUT,
() => console.warn('Failed to clear localStorage!')
() => logger.warn('Failed to clear localStorage!')
)
}

View File

@ -6,7 +6,7 @@ import { noop } from 'lodash'
import Puppeteer from 'puppeteer'
import { Observable, Subject } from 'rxjs'
import { isErrorLike } from '@sourcegraph/common'
import { isErrorLike, logger } from '@sourcegraph/common'
function toBase64(input: string): string {
return Buffer.from(input).toString('base64')
@ -183,7 +183,7 @@ export class CdpAdapter extends PollyAdapter {
return new Promise<PollyResponse>((resolve, reject) => {
this.passthroughPromises.set(requestId, { resolve, reject })
this.continuePausedRequest({ requestId }, cdpSession).catch(console.error)
this.continuePausedRequest({ requestId }, cdpSession).catch(logger.error)
})
}
@ -329,7 +329,7 @@ export class CdpAdapter extends PollyAdapter {
// Passthrough missing Chrome extension request because it's expected to fail if the extension is not installed.
if (request.url.includes('chrome-extension://invalid')) {
this.continuePausedRequest({ requestId: event.requestId }, cdpSession).catch(console.error)
this.continuePausedRequest({ requestId: event.requestId }, cdpSession).catch(logger.error)
return
}
@ -376,7 +376,7 @@ export class CdpAdapter extends PollyAdapter {
this.pendingRequests.get(requestId)?.resolve(pollyResponse)
this.pendingRequests.delete(requestId)
})
.catch(console.error)
.catch(logger.error)
}
}

View File

@ -4,6 +4,8 @@ import { afterEach } from 'mocha'
import { mkdir } from 'mz/fs'
import * as puppeteer from 'puppeteer'
import { logger } from '@sourcegraph/common'
/**
* Registers an `afterEach` hook (for use with Mocha) that takes a screenshot of
* the browser when a test fails. It is used by e2e and integration tests.
@ -38,12 +40,12 @@ async function takeScreenshot({
const screenshot = await page.screenshot({ path: filePath })
if (process.env.CI) {
// Print image with ANSI escape code for Buildkite: https://buildkite.com/docs/builds/images-in-log-output.
console.log(`\u001B]1338;url="artifact://${path.relative(repoRootDir, filePath)}";alt="Screenshot"\u0007`)
logger.log(`\u001B]1338;url="artifact://${path.relative(repoRootDir, filePath)}";alt="Screenshot"\u0007`)
} else if (process.env.TERM_PROGRAM === 'iTerm.app') {
// Print image inline for iTerm2
const nameBase64 = Buffer.from(fileName).toString('base64')
console.log(`\u001B]1337;File=name=${nameBase64};inline=1;width=500px:${screenshot.toString('base64')}\u0007`)
logger.log(`\u001B]1337;File=name=${nameBase64};inline=1;width=500px:${screenshot.toString('base64')}\u0007`)
} else {
console.log(`📸 Saved screenshot of failure to ${path.relative(process.cwd(), filePath)}`)
logger.log(`📸 Saved screenshot of failure to ${path.relative(process.cwd(), filePath)}`)
}
}

View File

@ -2,6 +2,8 @@ import { useMemo, useEffect } from 'react'
import { ReplaySubject } from 'rxjs'
import { logger } from '@sourcegraph/common'
import { ViewerId } from '../api/viewerTypes'
import { ExtensionsControllerProps } from '../extensions/controller'
import { HoverContext } from '../hover/HoverOverlay'
@ -64,14 +66,14 @@ export function useCodeIntelViewerUpdates(props?: UseCodeIntelViewerUpdatesProps
})
})
.catch(error => {
console.error('Extension host API error', error)
logger.error('Extension host API error', error)
})
return () => {
// Remove from extension host
extensionsController.extHostAPI
.then(extensionHostAPI => previousViewerId && extensionHostAPI.removeViewer(previousViewerId))
.catch(error => console.error('Error removing viewer from extension host', error))
.catch(error => logger.error('Error removing viewer from extension host', error))
}
}, [props, viewerUpdates])

View File

@ -4,6 +4,7 @@ import { ApolloLink } from '@apollo/client'
import { MockedProvider, MockedProviderProps, MockedResponse, MockLink } from '@apollo/client/testing'
import { getOperationName } from '@apollo/client/utilities'
import { logger } from '@sourcegraph/common'
import { cache } from '@sourcegraph/http-client'
/**
@ -16,7 +17,7 @@ const forceMockVariablesLink = (mocks: readonly MockedResponse[]): ApolloLink =>
if (mock) {
operation.variables = mock.request.variables || {}
} else {
console.warn(`Unable to find a mock for query: ${operation.operationName}. Did you mean to mock this?`)
logger.warn(`Unable to find a mock for query: ${operation.operationName}. Did you mean to mock this?`)
}
return forward(operation)
})

View File

@ -8,5 +8,8 @@ module.exports = {
...baseConfig.parserOptions,
project: [__dirname + '/tsconfig.json'],
},
rules: {
'no-console': 'off',
},
overrides: baseConfig.overrides,
}

View File

@ -11,5 +11,11 @@ module.exports = {
files: ['src/stores/**.ts', 'src/__mocks__/zustand.ts'],
rules: { 'no-restricted-imports': 'off' },
},
{
files: 'dev/**/*.ts',
rules: {
'no-console': 'off',
},
},
],
}

View File

@ -11,6 +11,7 @@ import { combineLatest, from, Subscription, fromEvent, of, Subject, Observable }
import { distinctUntilChanged, first, map, startWith, switchMap } from 'rxjs/operators'
import * as uuid from 'uuid'
import { logger } from '@sourcegraph/common'
import { GraphQLClient, HTTPStatusError } from '@sourcegraph/http-client'
import {
fetchAutoDefinedSearchContexts,
@ -238,7 +239,7 @@ export class SourcegraphWebApp extends React.Component<
})
})
.catch(error => {
console.error('Error initializing GraphQL client', error)
logger.error('Error initializing GraphQL client', error)
})
this.subscriptions.add(
@ -295,7 +296,7 @@ export class SourcegraphWebApp extends React.Component<
}
this.setWorkspaceSearchContext(this.state.selectedSearchContextSpec).catch(error => {
console.error('Error sending search context to extensions!', error)
logger.error('Error sending search context to extensions!', error)
})
// Update search query state whenever the URL changes
@ -484,7 +485,7 @@ export class SourcegraphWebApp extends React.Component<
localStorage.setItem(LAST_SEARCH_CONTEXT_KEY, availableSearchContextSpecOrDefault)
this.setWorkspaceSearchContext(availableSearchContextSpecOrDefault).catch(error => {
console.error('Error sending search context to extensions', error)
logger.error('Error sending search context to extensions', error)
})
})
)

View File

@ -6,7 +6,7 @@ import { from as fromPromise, Subject, Subscription } from 'rxjs'
import { catchError, debounceTime } from 'rxjs/operators'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { LoadingSpinner, Button, Alert, Link } from '@sourcegraph/wildcard'
import { PageTitle } from '../components/PageTitle'
@ -104,7 +104,7 @@ export class ApiConsole extends React.PureComponent<Props, State> {
fromPromise(import('graphiql'))
.pipe(
catchError(error => {
console.error(error)
logger.error(error)
return [asError(error)]
})
)

View File

@ -1,6 +1,7 @@
import { Observable, ReplaySubject } from 'rxjs'
import { catchError, map, mergeMap, tap } from 'rxjs/operators'
import { logger } from '@sourcegraph/common'
import { dataOrThrowErrors } from '@sourcegraph/http-client'
import { AuthenticatedUser as SharedAuthenticatedUser, currentAuthStateQuery } from '@sourcegraph/shared/src/auth'
import { CurrentAuthStateResult } from '@sourcegraph/shared/src/graphql-operations'
@ -48,7 +49,7 @@ if (window.context?.isAuthenticatedUser) {
refreshAuthenticatedUser()
.toPromise()
.then(() => undefined)
.catch(error => console.error(error))
.catch(error => logger.error(error))
} else {
authenticatedUser.next(null)
}

View File

@ -5,7 +5,7 @@ import { useLocation } from 'react-router-dom-v5-compat'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { Button, Link, LoadingSpinner, Alert, Text, Input } from '@sourcegraph/wildcard'
import { AuthenticatedUser } from '../auth'
@ -137,7 +137,7 @@ class ResetPasswordInitForm extends React.PureComponent<{}, ResetPasswordInitFor
.text()
.catch(() => null)
.then(text => this.setState({ submitOrError: new Error(text || 'Unknown error') }))
.catch(error => console.error(error))
.catch(error => logger.error(error))
}
})
.catch(error => this.setState({ submitOrError: asError(error) }))

View File

@ -2,6 +2,7 @@ import React, { useCallback, useState } from 'react'
import { gql, useMutation } from '@apollo/client'
import { logger } from '@sourcegraph/common'
import { Link, Alert, AnchorLink, Checkbox, H1, Text } from '@sourcegraph/wildcard'
import { LoaderButton } from '../components/LoaderButton'
@ -37,7 +38,7 @@ export const TosConsentModal: React.FunctionComponent<React.PropsWithChildren<{
await setTosAccepted()
afterTosAccepted()
} catch (error) {
console.error(error)
logger.error(error)
}
},
[afterTosAccepted, setTosAccepted]

View File

@ -4,7 +4,7 @@ import classNames from 'classnames'
import { useLocation } from 'react-router-dom-v5-compat'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { asError } from '@sourcegraph/common'
import { asError, logger } from '@sourcegraph/common'
import { Label, Button, LoadingSpinner, Link, Text, Input } from '@sourcegraph/wildcard'
import { SourcegraphContext } from '../jscontext'
@ -81,7 +81,7 @@ export const UsernamePasswordSignInForm: React.FunctionComponent<React.PropsWith
}
})
.catch(error => {
console.error('Auth error:', error)
logger.error('Auth error:', error)
setLoading(false)
onAuthError(asError(error))
})

View File

@ -2,6 +2,7 @@ import { render, RenderResult, within, fireEvent } from '@testing-library/react'
import * as H from 'history'
import { EMPTY, NEVER, noop, of, Subscription } from 'rxjs'
import { logger } from '@sourcegraph/common'
import { FlatExtensionHostAPI } from '@sourcegraph/shared/src/api/contract'
import { pretendProxySubscribable, pretendRemote } from '@sourcegraph/shared/src/api/util'
import { ViewerId } from '@sourcegraph/shared/src/api/viewerTypes'
@ -59,7 +60,7 @@ const defaultProps: Omit<ReferencesPanelProps, 'externalHistory' | 'externalLoca
if (args.filePath === 'diff/diff.go') {
return of(highlightedLinesDiffGo)
}
console.error('attempt to fetch highlighted lines for file without mocks', args.filePath)
logger.error('attempt to fetch highlighted lines for file without mocks', args.filePath)
return of([])
},
}

View File

@ -13,6 +13,7 @@ import {
addLineRangeQueryParameter,
ErrorLike,
formatSearchParameters,
logger,
lprToRange,
pluralize,
toPositionOrRangeQueryParameter,
@ -642,7 +643,7 @@ function parseSideBlobProps(
: undefined
return { activeURL, repository: url.repoName, commitID: url.commitID || '', file: url.filePath, position }
} catch (error) {
console.error(`failed to parse activeURL ${activeURL}`, error)
logger.error(`failed to parse activeURL ${activeURL}`, error)
return undefined
}
}

View File

@ -19,7 +19,7 @@ import {
share,
} from 'rxjs/operators'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { ConnectionNodes, ConnectionNodesState, ConnectionNodesDisplayProps, ConnectionProps } from './ConnectionNodes'
import { Connection, ConnectionQueryArguments } from './ConnectionType'
@ -363,7 +363,7 @@ export class FilteredConnection<
}
this.setState({ connectionOrError, ...rest })
},
error => console.error(error)
error => logger.error(error)
)
)

View File

@ -1,5 +1,6 @@
import React, { useEffect } from 'react'
import { logger } from '@sourcegraph/common'
import { screenReaderAnnounce } from '@sourcegraph/wildcard'
interface PageTitleProps {
@ -19,7 +20,7 @@ let titleSet = false
export const PageTitle: React.FunctionComponent<React.PropsWithChildren<PageTitleProps>> = ({ title }) => {
useEffect(() => {
if (titleSet) {
console.error('more than one PageTitle used at the same time')
logger.error('more than one PageTitle used at the same time')
}
titleSet = true
document.title = title ? `${title} - ${getBrandName()}` : getBrandName()

View File

@ -7,7 +7,7 @@ import { Omit } from 'utility-types'
import { HoverMerged } from '@sourcegraph/client-api'
import { Hoverifier } from '@sourcegraph/codeintellify'
import { ErrorLike, isDefined, isErrorLike, property } from '@sourcegraph/common'
import { ErrorLike, isDefined, isErrorLike, logger, property } from '@sourcegraph/common'
import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem'
import { TextDocumentData, ViewerData, ViewerId } from '@sourcegraph/shared/src/api/viewerTypes'
import { Controller as ExtensionsController } from '@sourcegraph/shared/src/extensions/controller'
@ -103,7 +103,7 @@ export const FileDiffConnection: React.FunctionComponent<React.PropsWithChildren
)
)
.catch(error => {
console.error('Error removing viewers from extension host', error)
logger.error('Error removing viewers from extension host', error)
})
},
[getCurrentViewerIdByUri, extensionInfo?.extensionsController]
@ -234,7 +234,7 @@ export const FileDiffConnection: React.FunctionComponent<React.PropsWithChildren
return new Map([...currentViewerIdByUri])
} catch (error) {
console.error('Error syncing documents/viewers with extension host', error)
logger.error('Error syncing documents/viewers with extension host', error)
return new Map([...currentViewerIdByUri])
}
})

View File

@ -2,7 +2,7 @@ import React, { useEffect, useCallback, useState } from 'react'
import * as H from 'history'
import { asError, isErrorLike, renderMarkdown } from '@sourcegraph/common'
import { asError, isErrorLike, logger, renderMarkdown } from '@sourcegraph/common'
import { Markdown } from '@sourcegraph/shared/src/components/Markdown'
import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
import { ThemeProps } from '@sourcegraph/shared/src/theme'
@ -92,7 +92,7 @@ export const AddExternalServicePage: React.FunctionComponent<React.PropsWithChil
// Refresh site flags so that global site alerts
// reflect the latest configuration.
// eslint-disable-next-line rxjs/no-ignored-subscription
refreshSiteFlags().subscribe({ error: error => console.error(error) })
refreshSiteFlags().subscribe({ error: error => logger.error(error) })
history.push(afterCreateRoute)
}
}, [afterCreateRoute, createdExternalService, history])

View File

@ -4,6 +4,7 @@ import classNames from 'classnames'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { logger } from '@sourcegraph/common'
import { Button, Modal, Link, Code, Label, Text, Input } from '@sourcegraph/wildcard'
import { LoaderButton } from '../../../components/LoaderButton'
@ -119,7 +120,7 @@ export const AddCredentialModal: React.FunctionComponent<React.PropsWithChildren
afterCreate()
}
} catch (error) {
console.error(error)
logger.error(error)
}
},
[

View File

@ -3,6 +3,7 @@ import React, { useCallback, useRef, useState } from 'react'
import { mdiCheckCircleOutline, mdiCheckboxBlankCircleOutline } from '@mdi/js'
import classNames from 'classnames'
import { logger } from '@sourcegraph/common'
import { useLazyQuery } from '@sourcegraph/http-client'
import { Badge, Button, Icon, H3, Tooltip } from '@sourcegraph/wildcard'
@ -81,7 +82,7 @@ export const CodeHostConnectionNode: React.FunctionComponent<React.PropsWithChil
// At the moment, log the error since it is not being displayed on the page.
if (checkCredError) {
console.log(checkCredError.message)
logger.error(checkCredError.message)
}
return (

View File

@ -1,6 +1,7 @@
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { logger } from '@sourcegraph/common'
import { createInvalidGraphQLMutationResponseError, dataOrThrowErrors, gql } from '@sourcegraph/http-client'
import { requestGraphQL } from '../../backend/graphql'
@ -291,7 +292,7 @@ export const sendTestEmail = (id: Scalars['ID']): Observable<void> => {
map(dataOrThrowErrors),
map(data => {
if (!data.resetTriggerQueryTimestamps) {
console.log('DATA', data)
logger.log('DATA', data)
throw createInvalidGraphQLMutationResponseError('ResetTriggerQueryTimestamps')
}
})

View File

@ -5,7 +5,7 @@ import { upperFirst } from 'lodash'
import { Subject, Subscription } from 'rxjs'
import { catchError, map, mapTo, startWith, switchMap, tap } from 'rxjs/operators'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import * as GQL from '@sourcegraph/shared/src/schema'
import { Button, ButtonGroup, Icon } from '@sourcegraph/wildcard'
@ -62,7 +62,7 @@ export class RegistryExtensionDeleteButton extends React.PureComponent<
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)
}

View File

@ -10,7 +10,7 @@ import { catchError, concatMap, map, tap } from 'rxjs/operators'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { asError, createAggregateError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, createAggregateError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import * as GQL from '@sourcegraph/shared/src/schema'
import { Button, LoadingSpinner, Link, CardHeader, CardBody, Card, Alert, Icon, Code, H2 } from '@sourcegraph/wildcard'
@ -113,7 +113,7 @@ export const RegistryExtensionManagePage = withAuthenticatedUser(
)
.subscribe(
stateUpdate => this.setState(stateUpdate as State),
error => console.error(error)
error => logger.error(error)
)
)

View File

@ -10,7 +10,7 @@ import { catchError, concatMap, map, tap } from 'rxjs/operators'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { Scalars } from '@sourcegraph/shared/src/graphql-operations'
import * as GQL from '@sourcegraph/shared/src/schema'
import { Button, Code, Container, Icon, Label, Link, LoadingSpinner, PageHeader } from '@sourcegraph/wildcard'
@ -68,7 +68,7 @@ export const RegistryNewExtensionPage = withAuthenticatedUser(
)
).subscribe(
stateUpdate => this.setState(stateUpdate as State),
error => console.error(error)
error => logger.error(error)
)
)
@ -92,7 +92,7 @@ export const RegistryNewExtensionPage = withAuthenticatedUser(
)
.subscribe(
stateUpdate => this.setState(stateUpdate as State),
error => console.error(error)
error => logger.error(error)
)
)

View File

@ -3,6 +3,8 @@ import escapeRegExp from 'lodash/escapeRegExp'
import { defer } from 'rxjs'
import { retry } from 'rxjs/operators'
import { logger } from '@sourcegraph/common'
import { InsightContentType } from '../../../../types/insight/common'
import { GetSearchInsightContentInput, InsightSeriesContent } from '../../../code-insights-backend-types'
@ -142,7 +144,7 @@ async function determineCommitsToSearch(dates: Date[], repo: string): Promise<Se
const firstCommit = search.results.results[0]
if (search.results.results.length === 0 || firstCommit?.__typename !== 'CommitSearchResult') {
console.warn(`No result for ${commitQueries[index_]}`)
logger.warn(`No result for ${commitQueries[index_]}`)
return { commit: null, date }
}

View File

@ -1,6 +1,6 @@
import { useCallback, useContext, useState } from 'react'
import { ErrorLike } from '@sourcegraph/common'
import { ErrorLike, logger } from '@sourcegraph/common'
import { eventLogger } from '../../../tracking/eventLogger'
import { CodeInsightsBackendContext, Insight } from '../core'
@ -41,7 +41,7 @@ export function useDeleteInsight(): UseDeleteInsightAPI {
eventLogger.log('InsightRemoval', { insightType }, { insightType })
} catch (error) {
// TODO [VK] Improve error UI for deleting
console.error(error)
logger.error(error)
setError(error)
}
},

View File

@ -1,6 +1,6 @@
import { useCallback, useContext, useState } from 'react'
import { ErrorLike } from '@sourcegraph/common'
import { ErrorLike, logger } from '@sourcegraph/common'
import { eventLogger } from '../../../tracking/eventLogger'
import { CodeInsightsBackendContext, Insight, InsightDashboard } from '../core'
@ -46,7 +46,7 @@ export function useRemoveInsightFromDashboard(): useRemoveInsightFromDashboardAP
eventLogger.log('InsightRemovalFromDashboard', { insightType }, { insightType })
} catch (error) {
// TODO [VK] Improve error UI for removing
console.error(error)
logger.error(error)
setError(error)
}
},

View File

@ -3,6 +3,7 @@ import { FunctionComponent, useCallback, useState } from 'react'
import { RouteComponentProps } from 'react-router'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { logger } from '@sourcegraph/common'
import { gql, useLazyQuery, useMutation } from '@sourcegraph/http-client'
import { IFeatureFlagOverride } from '@sourcegraph/shared/src/schema'
import { Input, Alert, H2, Text } from '@sourcegraph/wildcard'
@ -63,7 +64,7 @@ export const EarlyAccessOrgsCodeForm: FunctionComponent<EarlyAccessOrgsCodeFormP
FeatureFlagOverrideResult,
FeatureFlagOverrideVariables
>(CREATE_FEATURE_FLAG_OVERRIDE, {
onError: apolloError => console.error('Error when creating feature flag override', apolloError),
onError: apolloError => logger.error('Error when creating feature flag override', apolloError),
})
const [getOrgID, { loading: orgLoading, error: orgError }] = useLazyQuery<OrgResult, OrganizationVariables>(

View File

@ -7,7 +7,7 @@ import { Observable, Subject, Subscription } from 'rxjs'
import { catchError, map, mapTo, startWith, switchMap, tap } from 'rxjs/operators'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { asError, createAggregateError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, createAggregateError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import * as GQL from '@sourcegraph/shared/src/schema'
import { Button, ButtonLink, Link, Icon, H2, Text } from '@sourcegraph/wildcard'
@ -66,7 +66,7 @@ class RegistryExtensionNodeSiteAdminRow extends React.PureComponent<
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)
}

View File

@ -4,7 +4,7 @@ import { Observable, Subject, Subscription } from 'rxjs'
import { catchError, filter, map, mapTo, startWith, switchMap, tap } from 'rxjs/operators'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { dataOrThrowErrors, gql } from '@sourcegraph/http-client'
import { Badge, Button, Link, AnchorLink } from '@sourcegraph/wildcard'
@ -108,7 +108,7 @@ export class ExternalAccountNode extends React.PureComponent<ExternalAccountNode
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)
}

View File

@ -8,7 +8,7 @@ import { filter, first, mapTo, switchMap } from 'rxjs/operators'
import { tabbable } from 'tabbable'
import { useMergeRefs } from 'use-callback-ref'
import { isDefined } from '@sourcegraph/common'
import { isDefined, logger } from '@sourcegraph/common'
import { urlForClientCommandOpen } from '@sourcegraph/shared/src/actions/ActionItem'
import { StatusBarItemWithKey } from '@sourcegraph/shared/src/api/extension/api/codeEditor'
import { haveInitialExtensionsLoaded } from '@sourcegraph/shared/src/api/features'
@ -123,7 +123,7 @@ export const StatusBar: React.FunctionComponent<React.PropsWithChildren<StatusBa
})
)
})
.catch(error => console.error('Error registering "Focus status bar" command', error))
.catch(error => logger.error('Error registering "Focus status bar" command', error))
}
return () => subscription.unsubscribe()

View File

@ -7,7 +7,7 @@ import { combineLatest, merge, Observable, of, Subject, Subscription } from 'rxj
import { catchError, distinctUntilChanged, map, mapTo, startWith, switchMap } from 'rxjs/operators'
import { ErrorMessage } from '@sourcegraph/branded/src/components/alerts'
import { createAggregateError, ErrorLike, isErrorLike, asError } from '@sourcegraph/common'
import { createAggregateError, ErrorLike, isErrorLike, asError, logger } from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import {
ConfiguredRegistryExtension,
@ -176,7 +176,7 @@ export class ExtensionArea extends React.Component<ExtensionAreaProps> {
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)

View File

@ -2,6 +2,8 @@ import React, { createContext, useEffect, useMemo } from 'react'
import { Observable, of, throwError } from 'rxjs'
import { logger } from '@sourcegraph/common'
import { requestGraphQL } from '../backend/graphql'
import { FeatureFlagName } from './featureFlags'
@ -36,13 +38,13 @@ const FeatureFlagsLocalOverrideAgent = React.memo(() => {
} else if ([0, 'false'].includes(value)) {
setFeatureFlagOverride(flagName, false)
} else {
console.warn(
logger.warn(
`[FeatureFlagsLocalOverrideAgent]: can not override feature flag "${flagName}" with value "${value}". Only boolean values are supported.`
)
}
}
} catch (error) {
console.error(error)
logger.error(error)
}
}, [])
return null

View File

@ -1,5 +1,7 @@
import { useContext, useEffect, useState } from 'react'
import { logger } from '@sourcegraph/common'
import { FeatureFlagName } from './featureFlags'
import { FeatureFlagsContext } from './FeatureFlagsProvider'
@ -24,7 +26,7 @@ export function useFeatureFlag(flagName: FeatureFlagName, defaultValue = false):
if (!client) {
const errorMessage =
'[useFeatureFlag]: No FeatureFlagClient is configured. All feature flags will default to "false" value.'
console.warn(errorMessage)
logger.warn(errorMessage)
setResult(({ value }) => ({ value, status: 'error', error: new Error(errorMessage) }))
return
}

View File

@ -3,6 +3,8 @@ import { useEffect } from 'react'
import { debounce } from 'lodash'
import { useHistory } from 'react-router'
import { logger } from '@sourcegraph/common'
import {
MutationObserverError,
MutationObserverPromise,
@ -94,7 +96,7 @@ export function useScrollManager(containerKey: string, containerRef: React.RefOb
)
.catch((error: MutationObserverError) => {
if (!error.cancelled) {
console.error(
logger.error(
`Failed to scroll to position '${scrollPosition}' for pathname '${pathname}' in container '${containerKey}'.`
)
}

View File

@ -3,6 +3,7 @@ import React from 'react'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import ElmComponent from 'react-elm-components'
import { logger } from '@sourcegraph/common'
import { PlatformContext } from '@sourcegraph/shared/src/platform/context'
import { ThemeProps } from '@sourcegraph/shared/src/theme'
@ -55,7 +56,7 @@ const setupPorts = (sourcegraphURL: string, updateBlockInputWithID: (blockInput:
}
ports.openStream.subscribe((args: string[]) => {
console.log(`stream: ${args[0]}`)
logger.log(`stream: ${args[0]}`)
const address = args[0]
// Close any open streams if we receive a request to open a new stream before seeing 'done'.
@ -73,7 +74,7 @@ const setupPorts = (sourcegraphURL: string, updateBlockInputWithID: (blockInput:
},
signal: ctrl.signal,
onerror(error) {
console.log(`Compute EventSource error: ${JSON.stringify(error)}`)
logger.error(`Compute EventSource error: ${JSON.stringify(error)}`)
},
onclose() {
// Note: 'done:true' is sent in progress too. But we want a 'done' for the entire stream in case we don't see it.
@ -87,7 +88,7 @@ const setupPorts = (sourcegraphURL: string, updateBlockInputWithID: (blockInput:
}
fetch().catch(error => {
console.log(`Compute fetch error: ${JSON.stringify(error)}`)
logger.error(`Compute fetch error: ${JSON.stringify(error)}`)
})
})

View File

@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'
import { from } from 'rxjs'
import { logger } from '@sourcegraph/common'
import { SimpleActionItem } from '@sourcegraph/shared/src/actions/SimpleActionItem'
import { PlatformContext } from '@sourcegraph/shared/src/platform/context'
import { isSettingsValid, Settings } from '@sourcegraph/shared/src/settings/settings'
@ -138,10 +139,10 @@ function upgradeSettings(platformContext: PlatformContext, settings: Settings, u
value: openInEditor,
})
.then(() => {
console.log('Migrated items successfully.')
logger.log('Migrated items successfully.')
})
.catch(error => {
console.error('Setting migration failed.', error)
logger.error('Setting migration failed.', error)
})
}
}

View File

@ -7,7 +7,7 @@ import { combineLatest, merge, Observable, of, Subject, Subscription } from 'rxj
import { catchError, distinctUntilChanged, map, mapTo, startWith, switchMap } from 'rxjs/operators'
import { ErrorMessage } from '@sourcegraph/branded/src/components/alerts'
import { ErrorLike, isErrorLike, asError } from '@sourcegraph/common'
import { ErrorLike, isErrorLike, asError, logger } from '@sourcegraph/common'
import { gql, dataOrThrowErrors } from '@sourcegraph/http-client'
import { ExtensionsControllerProps } from '@sourcegraph/shared/src/extensions/controller'
import { PlatformContextProps } from '@sourcegraph/shared/src/platform/context'
@ -241,7 +241,7 @@ export class OrgArea extends React.Component<Props> {
this.setState(stateUpdate)
}
},
error => console.error(error)
error => logger.error(error)
)
)

View File

@ -6,7 +6,7 @@ import { catchError, concatMap, distinctUntilKeyChanged, map, mapTo, tap, withLa
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { dataOrThrowErrors, gql } from '@sourcegraph/http-client'
import { OrganizationInvitationResponseType } from '@sourcegraph/shared/src/graphql-operations'
import { LoadingSpinner, Button, Link, Alert, H3, Text } from '@sourcegraph/wildcard'
@ -90,7 +90,7 @@ export const OrgInvitationPageLegacy = withAuthenticatedUser(
)
.subscribe(
stateUpdate => this.setState(stateUpdate as State),
error => console.error(error)
error => logger.error(error)
)
)

View File

@ -4,6 +4,7 @@ import classNames from 'classnames'
import { RouteComponentProps } from 'react-router-dom'
import { Form } from '@sourcegraph/branded/src/components/Form'
import { logger } from '@sourcegraph/common'
import { gql, useMutation, useQuery } from '@sourcegraph/http-client'
import { OrganizationInvitationResponseType } from '@sourcegraph/shared/src/graphql-operations'
import { Alert, AnchorLink, Button, LoadingSpinner, Link, H2, H3 } from '@sourcegraph/wildcard'
@ -100,7 +101,7 @@ export const OrgInvitationPage: React.FunctionComponent<React.PropsWithChildren<
RespondToOrgInvitationVariables
>(RESPOND_TO_ORG_INVITATION, {
onError: apolloError => {
console.error('Error when responding to invitation', apolloError)
logger.error('Error when responding to invitation', apolloError)
},
})

View File

@ -7,7 +7,7 @@ import { Observable, Subject, Subscription } from 'rxjs'
import { catchError, distinctUntilChanged, filter, map, startWith, switchMap, tap } from 'rxjs/operators'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { asError, createAggregateError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, createAggregateError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import { Container, PageHeader, Button, Link, Alert } from '@sourcegraph/wildcard'
@ -99,7 +99,7 @@ class UserNode extends React.PureComponent<UserNodeProps, UserNodeState> {
stateUpdate => {
this.setState(stateUpdate)
},
error => console.error(error)
error => logger.error(error)
)
)
}

View File

@ -1,7 +1,13 @@
import { ApolloQueryResult, ObservableQuery } from '@apollo/client'
import { map, publishReplay, refCount, shareReplay } from 'rxjs/operators'
import { createAggregateError, asError, LocalStorageSubject, appendSubtreeQueryParameter } from '@sourcegraph/common'
import {
createAggregateError,
asError,
LocalStorageSubject,
appendSubtreeQueryParameter,
logger,
} from '@sourcegraph/common'
import { fromObservableQueryPromise, getDocumentNode } from '@sourcegraph/http-client'
import { viewerSettingsQuery } from '@sourcegraph/shared/src/backend/settings'
import { ViewerSettingsResult, ViewerSettingsVariables } from '@sourcegraph/shared/src/graphql-operations'
@ -67,7 +73,7 @@ export function createPlatformContext(): PlatformContext {
}
// The error will be emitted to consumers from the `context.settings` observable.
await settingsQueryWatcher.refetch().catch(error => console.error(error))
await settingsQueryWatcher.refetch().catch(error => logger.error(error))
},
getGraphQLClient: getWebGraphQLClient,
requestGraphQL: ({ request, variables }) => requestGraphQL(request, variables),

View File

@ -3,6 +3,7 @@ import expect from 'expect'
import { describe, before, beforeEach, after, afterEach, test } from 'mocha'
import { map } from 'rxjs/operators'
import { logger } from '@sourcegraph/common'
import { gql, dataOrThrowErrors } from '@sourcegraph/http-client'
// import { overwriteSettings } from '@sourcegraph/shared/src/settings/edit'
import { getConfig } from '@sourcegraph/shared/src/testing/config'
@ -67,7 +68,7 @@ describe('Core functionality regression test suite', () => {
await driver.close()
}
if (screenshots.screenshots.length > 0) {
console.log(screenshots.verificationInstructions())
logger.log(screenshots.verificationInstructions())
}
})

View File

@ -1,4 +1,4 @@
import { asError } from '@sourcegraph/common'
import { asError, logger } from '@sourcegraph/common'
export type ResourceDestructor = () => Promise<void>
@ -63,14 +63,14 @@ export class TestResourceManager {
try {
await resource.destroy()
} catch (error) {
console.error(
logger.error(
`Error when destroying resource ${resource.type} ${JSON.stringify(resource.name)}: ${
asError(error).message
}`
)
continue
}
console.log(`Test resource destroyed: ${resource.type} ${JSON.stringify(resource.name)}`)
logger.log(`Test resource destroyed: ${resource.type} ${JSON.stringify(resource.name)}`)
}
}
}

View File

@ -5,7 +5,7 @@
import { zip, timer, concat, throwError, defer, Observable } from 'rxjs'
import { map, tap, retryWhen, delayWhen, take, mergeMap } from 'rxjs/operators'
import { isErrorLike, createAggregateError } from '@sourcegraph/common'
import { isErrorLike, createAggregateError, logger } from '@sourcegraph/common'
import {
gql,
dataOrThrowErrors,
@ -109,7 +109,7 @@ export function waitForRepo(
if (isErrorLike(error) && error.message === 'Repo exists') {
// Delay retry by 2s.
if (logStatusMessages) {
console.log(
logger.log(
`Waiting for ${repoName} to be removed (attempt ${
retryCount + 1
} of ${numberRetries})`
@ -147,7 +147,7 @@ export function waitForRepo(
if (isCloneInProgressErrorLike(error)) {
// Delay retry by 2s.
if (logStatusMessages) {
console.log(
logger.log(
`Waiting for ${repoName} to finish cloning (attempt ${
retryCount + 1
} of ${numberRetries})`
@ -267,7 +267,7 @@ export async function updateExternalService(
map(dataOrThrowErrors),
tap(({ updateExternalService: { warning } }) => {
if (warning) {
console.warn('updateExternalService warning:', warning)
logger.warn('updateExternalService warning:', warning)
}
})
)

View File

@ -4,7 +4,7 @@ import { throwError } from 'rxjs'
import { catchError, map } from 'rxjs/operators'
import { Key } from 'ts-key-enum'
import { asError } from '@sourcegraph/common'
import { asError, logger } from '@sourcegraph/common'
import { gql, dataOrThrowErrors } from '@sourcegraph/http-client'
import { PlatformContext } from '@sourcegraph/shared/src/platform/context'
import * as GQL from '@sourcegraph/shared/src/schema'
@ -63,7 +63,7 @@ export async function ensureLoggedInOrCreateTestUser(
await driver.ensureLoggedIn({ username, password: testUserPassword })
return userDestructor
} catch (error) {
console.log(
logger.error(
`Login failed (error: ${asError(error).message}), will attempt to create user ${JSON.stringify(
username
)}`

View File

@ -9,7 +9,7 @@ import { matchPath, Route, RouteComponentProps, Switch } from 'react-router'
import { NEVER, of } from 'rxjs'
import { catchError, switchMap } from 'rxjs/operators'
import { asError, ErrorLike, isErrorLike, encodeURIPathComponent, repeatUntil } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, encodeURIPathComponent, repeatUntil, logger } from '@sourcegraph/common'
import { SearchContextProps } from '@sourcegraph/search'
import { StreamingSearchResultsListProps } from '@sourcegraph/search-ui'
import { isCloneInProgressErrorLike, isRepoSeeOtherErrorLike } from '@sourcegraph/shared/src/backend/errors'
@ -247,7 +247,7 @@ export const RepoContainer: React.FunctionComponent<React.PropsWithChildren<Repo
})
)
.catch(error => {
console.error('Error adding workspace root', error)
logger.error('Error adding workspace root', error)
})
}
@ -257,7 +257,7 @@ export const RepoContainer: React.FunctionComponent<React.PropsWithChildren<Repo
extensionsController.extHostAPI
.then(extensionHostAPI => extensionHostAPI.removeWorkspaceRoot(workspaceRootUri))
.catch(error => {
console.error('Error removing workspace root', error)
logger.error('Error removing workspace root', error)
})
}
}

View File

@ -5,7 +5,7 @@ import MapSearchIcon from 'mdi-react/MapSearchIcon'
import { merge, of, Subject, Subscription } from 'rxjs'
import { catchError, distinctUntilChanged, map, switchMap } from 'rxjs/operators'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { Link, Text } from '@sourcegraph/wildcard'
import { HeroPage } from '../components/HeroPage'
@ -73,7 +73,7 @@ export class RepositoryNotFoundPage extends React.PureComponent<Props, State> {
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)

View File

@ -53,6 +53,7 @@ import {
toPositionOrRangeQueryParameter,
addLineRangeQueryParameter,
formatSearchParameters,
logger,
} from '@sourcegraph/common'
import { TextDocumentDecoration } from '@sourcegraph/extension-api-types'
import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem'
@ -550,7 +551,7 @@ export const Blob: React.FunctionComponent<React.PropsWithChildren<BlobProps>> =
subscriptions.add(() => {
extensionHostAPI
.removeViewer(viewerId)
.catch(error => console.error('Error removing viewer from extension host', error))
.catch(error => logger.error('Error removing viewer from extension host', error))
})
viewerUpdates.next({ viewerId, blobInfo, extensionHostAPI, subscriptions })
@ -626,7 +627,7 @@ export const Blob: React.FunctionComponent<React.PropsWithChildren<BlobProps>> =
viewerData.extensionHostAPI
.setEditorSelections(viewerData.viewerId, lprToSelectionsZeroIndexed(position))
.catch(error =>
console.error('Error updating editor selections on extension host', error)
logger.error('Error updating editor selections on extension host', error)
)
})
)

View File

@ -1,6 +1,7 @@
import { Facet, RangeSetBuilder } from '@codemirror/state'
import { Decoration, DecorationSet, EditorView, PluginValue, ViewPlugin, ViewUpdate } from '@codemirror/view'
import { logger } from '@sourcegraph/common'
import { Occurrence, SyntaxKind } from '@sourcegraph/shared/src/codeintel/scip'
import { BlobInfo } from '../Blob'
@ -51,7 +52,7 @@ function createHighlightTable(info: BlobInfo): HighlightIndex {
return { occurrences, lineIndex }
} catch (error) {
console.error(`Unable to process SCIP highlight data: ${info.lsif}`, error)
logger.error(`Unable to process SCIP highlight data: ${info.lsif}`, error)
return { occurrences: [], lineIndex }
}
}
@ -136,7 +137,7 @@ class SyntaxHighlightManager implements PluginValue {
}
}
} catch (error) {
console.error('Failed to compute decorations from SCIP occurrences', error)
logger.error('Failed to compute decorations from SCIP occurrences', error)
}
return builder.finish()
}

View File

@ -15,7 +15,7 @@ import { combineLatest, EMPTY, from, Observable, of, Subject, Subscription } fro
import { filter, map, catchError, switchMap, distinctUntilChanged, startWith, shareReplay } from 'rxjs/operators'
import { DocumentHighlight, LOADER_DELAY, MaybeLoadingResult, emitLoading } from '@sourcegraph/codeintellify'
import { asError, ErrorLike, LineOrPositionOrRange, lprToSelectionsZeroIndexed } from '@sourcegraph/common'
import { asError, ErrorLike, LineOrPositionOrRange, lprToSelectionsZeroIndexed, logger } from '@sourcegraph/common'
import { Position, TextDocumentDecoration } from '@sourcegraph/extension-api-types'
import { wrapRemoteObservable } from '@sourcegraph/shared/src/api/client/api/common'
import { FlatExtensionHostAPI } from '@sourcegraph/shared/src/api/contract'
@ -103,14 +103,14 @@ export function sourcegraphExtensions({
})
).pipe(
catchError(() => {
console.error('Unable to initialize extensions context')
logger.error('Unable to initialize extensions context')
return EMPTY
}),
map(([viewerId, extensionHostAPI]) => {
subscriptions.add(() => {
extensionHostAPI
.removeViewer(viewerId)
.catch(error => console.error('Error removing viewer from extension host', error))
.catch(error => logger.error('Error removing viewer from extension host', error))
})
return {
@ -232,7 +232,7 @@ class SelectionManager implements PluginValue {
this.subscription = combineLatest([context, this.nextSelection]).subscribe(([context, selection]) => {
context.extensionHostAPI
.setEditorSelections(context.viewerId, lprToSelectionsZeroIndexed(selection ?? {}))
.catch(error => console.error('Error updating editor selections on extension host', error))
.catch(error => logger.error('Error updating editor selections on extension host', error))
})
}

View File

@ -6,7 +6,7 @@ import { Observable, Subject, Subscription } from 'rxjs'
import { catchError, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { asError, createAggregateError, ErrorLike, isErrorLike, memoizeObservable } from '@sourcegraph/common'
import { asError, createAggregateError, ErrorLike, isErrorLike, logger, memoizeObservable } from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import { Scalars } from '@sourcegraph/shared/src/graphql-operations'
import * as GQL from '@sourcegraph/shared/src/schema'
@ -105,7 +105,7 @@ export class RepositoryBranchesOverviewPage extends React.PureComponent<Props, S
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)
this.componentUpdates.next(this.props)

View File

@ -17,6 +17,7 @@ import {
isDefined,
memoizeObservable,
property,
logger,
} from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem'
@ -238,7 +239,7 @@ export class RepositoryCommitPage extends React.Component<RepositoryCommitPagePr
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)
this.componentUpdates.next(this.props)

View File

@ -7,7 +7,7 @@ import { catchError, distinctUntilChanged, map, switchMap } from 'rxjs/operators
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { HoverMerged } from '@sourcegraph/client-api'
import { Hoverifier } from '@sourcegraph/codeintellify'
import { asError, createAggregateError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, createAggregateError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import { ActionItemAction } from '@sourcegraph/shared/src/actions/ActionItem'
import { ExtensionsControllerProps } from '@sourcegraph/shared/src/extensions/controller'
@ -140,7 +140,7 @@ export class RepositoryCompareOverviewPage extends React.PureComponent<Props, St
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)
this.componentUpdates.next(this.props)

View File

@ -7,7 +7,7 @@ import { Redirect, Route, Switch, useRouteMatch } from 'react-router-dom'
import { catchError } from 'rxjs/operators'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { asError, encodeURIPathComponent, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, encodeURIPathComponent, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import { SearchContextProps } from '@sourcegraph/search'
import { fetchTreeEntries } from '@sourcegraph/shared/src/backend/repo'
@ -176,7 +176,7 @@ export const TreePage: React.FunctionComponent<React.PropsWithChildren<Props>> =
})
)
.catch(error => {
console.error('Error adding viewer to extension host:', error)
logger.error('Error adding viewer to extension host:', error)
return null
})
@ -188,7 +188,7 @@ export const TreePage: React.FunctionComponent<React.PropsWithChildren<Props>> =
}
return
})
.catch(error => console.error('Error removing viewer from extension host:', error))
.catch(error => logger.error('Error removing viewer from extension host:', error))
}
}, [uri, showCodeInsights, extensionsController])

View File

@ -9,7 +9,7 @@ import { catchError, map, mapTo, startWith, switchMap } from 'rxjs/operators'
import { useCallbackRef } from 'use-callback-ref'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/common'
import { asError, ErrorLike, isErrorLike, logger } from '@sourcegraph/common'
import { SearchPatternTypeProps } from '@sourcegraph/search'
import * as GQL from '@sourcegraph/shared/src/schema'
import { buildSearchURLQuery } from '@sourcegraph/shared/src/util/url'
@ -50,7 +50,7 @@ class SavedSearchNode extends React.PureComponent<NodeProps, NodeState> {
deleteSavedSearch(search.id).pipe(
mapTo(undefined),
catchError(error => {
console.error(error)
logger.error(error)
return []
})
)

View File

@ -1,5 +1,7 @@
import { useEffect, useState } from 'react'
import { logger } from '@sourcegraph/common'
/**
* Add `document.fonts` to Typescript type definitions based on the issue:
* https://github.com/Microsoft/TypeScript/issues/30984#issuecomment-631991019
@ -56,7 +58,7 @@ export function useDynamicWebFonts(fonts: DynamicWebFont[]): boolean {
// If fonts are available, skip redundant network request and proceed to UI rendering.
if (!areFontsLoaded) {
loadFonts().catch(error => {
console.error(error)
logger.error(error)
setHasNetworkError(true)
})
}

View File

@ -1,6 +1,8 @@
/* eslint-disable unicorn/no-abusive-eslint-disable */
/* eslint-disable */
const { logger } = require('@sourcegraph/common')
function initElmPorts(app) {
// Compute streaming
var sources = {}
@ -31,18 +33,18 @@ function initElmPorts(app) {
app.ports.openStream.subscribe(function (args) {
deleteAllEventSources() // Pre-emptively close any open streams if we receive a request to open a new stream before seeing 'done'.
console.log(`stream: ${args[0]}`)
logger.log(`stream: ${args[0]}`)
var address = args[0]
var eventSource = newEventSource(address)
eventSource.onerror = function (err) {
console.log(`EventSource failed: ${JSON.stringify(err)}`)
logger.log(`EventSource failed: ${JSON.stringify(err)}`)
}
eventSource.addEventListener('results', sendEventToElm)
eventSource.addEventListener('alert', sendEventToElm)
eventSource.addEventListener('error', sendEventToElm)
eventSource.addEventListener('done', function (event) {
console.log('Done')
logger.log('Done')
deleteEventSource(address)
// Note: 'done:true' is sent in progress too. But we want a 'done' for the entire stream in case we don't see it.
sendEventToElm({ type: 'done', data: '' })

View File

@ -4,6 +4,7 @@ import * as H from 'history'
import * as _monaco from 'monaco-editor' // type only
import { Subscription } from 'rxjs'
import { logger } from '@sourcegraph/common'
import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
import { ThemeProps } from '@sourcegraph/shared/src/theme'
import { LoadingSpinner } from '@sourcegraph/wildcard'
@ -225,7 +226,7 @@ export class DynamicallyImportedMonacoSettingsEditor<T extends object = {}> exte
const action = this.configEditor.getAction(id)
action.run().then(
() => undefined,
error => console.error(error)
error => logger.error(error)
)
} else {
alert('Wait for editor to load before running action.')

View File

@ -8,7 +8,7 @@ import { combineLatest, from, Observable, of, Subject, Subscription } from 'rxjs
import { catchError, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators'
import { ErrorMessage } from '@sourcegraph/branded/src/components/alerts'
import { asError, createAggregateError, ErrorLike, isErrorLike, isDefined } from '@sourcegraph/common'
import { asError, createAggregateError, ErrorLike, isErrorLike, isDefined, logger } from '@sourcegraph/common'
import { gql } from '@sourcegraph/http-client'
import { getConfiguredSideloadedExtension } from '@sourcegraph/shared/src/api/client/enabledExtensions'
import { extensionIDsFromSettings } from '@sourcegraph/shared/src/extensions/extension'
@ -108,7 +108,7 @@ export class SettingsArea extends React.Component<Props, State> {
)
.subscribe(
stateUpdate => this.setState(stateUpdate),
error => console.error(error)
error => logger.error(error)
)
)
@ -193,14 +193,14 @@ export class SettingsArea extends React.Component<Props, State> {
extensionIDsFromSettings(gqlToCascade(cascade))
).pipe(
catchError(error => {
console.warn('Unable to get extension settings JSON Schemas for settings editor.', { error })
logger.warn('Unable to get extension settings JSON Schemas for settings editor.', { error })
return of([])
})
),
from(this.props.platformContext.sideloadedExtensionURL).pipe(
switchMap(url => (url ? getConfiguredSideloadedExtension(url) : of(null))),
catchError(error => {
console.error('Error sideloading extension', error)
logger.error('Error sideloading extension', error)
return of(null)
})
),

View File

@ -2,6 +2,7 @@ import * as React from 'react'
import { RouteComponentProps } from 'react-router'
import { logger } from '@sourcegraph/common'
import { overwriteSettings } from '@sourcegraph/shared/src/settings/edit'
import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
import { ThemeProps } from '@sourcegraph/shared/src/theme'
@ -70,7 +71,7 @@ export class SettingsPage extends React.PureComponent<Props, State> {
this.props.onUpdate()
} catch (commitError) {
this.setState({ commitError })
console.error(commitError)
logger.error(commitError)
}
}

View File

@ -14,6 +14,7 @@ import classNames from 'classnames'
import { formatDistanceToNowStrict, startOfDay, endOfDay } from 'date-fns'
import { ErrorAlert } from '@sourcegraph/branded/src/components/alerts'
import { logger } from '@sourcegraph/common'
import { useQuery } from '@sourcegraph/http-client'
import {
H2,
@ -153,7 +154,7 @@ export const UsersList: React.FunctionComponent<UsersListProps> = ({ onActionEnd
(error?: any) => {
if (!error) {
// reload data
refetch(variables).catch(console.error)
refetch(variables).catch(logger.error)
onActionEnd?.()
}
},

View File

@ -1,5 +1,6 @@
import React, { useState, useCallback } from 'react'
import { logger } from '@sourcegraph/common'
import { useMutation } from '@sourcegraph/http-client'
import { Text } from '@sourcegraph/wildcard'
@ -31,7 +32,7 @@ export function useUserListActions(onEnd: (error?: any) => void): UseUserListAct
),
isError: true,
})
console.error(error)
logger.error(error)
onEnd(error)
},
[onEnd]

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