Browse Source

Renames/reworks logger correlation -> scope

main
Eric Amodio 2 years ago
parent
commit
6f737f1ac8
31 changed files with 650 additions and 655 deletions
  1. +3
    -4
      src/annotations/gutterBlameAnnotationProvider.ts
  2. +3
    -4
      src/annotations/gutterChangesAnnotationProvider.ts
  3. +3
    -4
      src/annotations/gutterHeatmapBlameAnnotationProvider.ts
  4. +18
    -18
      src/annotations/lineAnnotationController.ts
  5. +1
    -1
      src/commands/gitCommands.ts
  6. +5
    -6
      src/commands/switchMode.ts
  7. +94
    -94
      src/env/node/git/localGitProvider.ts
  8. +5
    -4
      src/env/node/git/vslsGitProvider.ts
  9. +6
    -6
      src/git/gitProviderService.ts
  10. +5
    -5
      src/git/models/repository.ts
  11. +13
    -13
      src/git/remotes/provider.ts
  12. +17
    -16
      src/hovers/hovers.ts
  13. +16
    -16
      src/keyboard.ts
  14. +29
    -46
      src/logger.ts
  15. +84
    -88
      src/plus/github/github.ts
  16. +51
    -51
      src/plus/github/githubGitProvider.ts
  17. +37
    -37
      src/plus/gitlab/gitlab.ts
  18. +10
    -10
      src/plus/subscription/authenticationProvider.ts
  19. +3
    -3
      src/plus/subscription/serverConnection.ts
  20. +15
    -11
      src/plus/subscription/subscriptionService.ts
  21. +14
    -7
      src/statusbar/statusBarController.ts
  22. +139
    -131
      src/system/decorators/log.ts
  23. +27
    -27
      src/system/stopwatch.ts
  24. +17
    -18
      src/trackers/gitLineTracker.ts
  25. +3
    -3
      src/trackers/lineTracker.ts
  26. +8
    -8
      src/views/nodes/fileHistoryTrackerNode.ts
  27. +8
    -8
      src/views/nodes/lineHistoryTrackerNode.ts
  28. +5
    -5
      src/views/viewBase.ts
  29. +3
    -3
      src/vsls/guest.ts
  30. +5
    -5
      src/vsls/host.ts
  31. +3
    -3
      src/webviews/webviewViewBase.ts

+ 3
- 4
src/annotations/gutterBlameAnnotationProvider.ts View File

@ -5,9 +5,8 @@ import type { Container } from '../container';
import { CommitFormatOptions, CommitFormatter } from '../git/formatters/commitFormatter'; import { CommitFormatOptions, CommitFormatter } from '../git/formatters/commitFormatter';
import type { GitBlame } from '../git/models/blame'; import type { GitBlame } from '../git/models/blame';
import type { GitCommit } from '../git/models/commit'; import type { GitCommit } from '../git/models/commit';
import { Logger } from '../logger';
import { filterMap } from '../system/array'; import { filterMap } from '../system/array';
import { log } from '../system/decorators/log';
import { getLogScope, log } from '../system/decorators/log';
import { first } from '../system/iterable'; import { first } from '../system/iterable';
import { Stopwatch } from '../system/stopwatch'; import { Stopwatch } from '../system/stopwatch';
import { getTokensFromTemplate, getWidth, TokenOptions } from '../system/string'; import { getTokensFromTemplate, getWidth, TokenOptions } from '../system/string';
@ -37,14 +36,14 @@ export class GutterBlameAnnotationProvider extends BlameAnnotationProviderBase {
@log() @log()
async onProvideAnnotation(context?: AnnotationContext, _type?: FileAnnotationType): Promise<boolean> { async onProvideAnnotation(context?: AnnotationContext, _type?: FileAnnotationType): Promise<boolean> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
this.annotationContext = context; this.annotationContext = context;
const blame = await this.getBlame(); const blame = await this.getBlame();
if (blame == null) return false; if (blame == null) return false;
const sw = new Stopwatch(cc!);
const sw = new Stopwatch(scope);
const cfg = configuration.get('blame'); const cfg = configuration.get('blame');

+ 3
- 4
src/annotations/gutterChangesAnnotationProvider.ts View File

@ -17,8 +17,7 @@ import type { Container } from '../container';
import type { GitCommit } from '../git/models/commit'; import type { GitCommit } from '../git/models/commit';
import type { GitDiff } from '../git/models/diff'; import type { GitDiff } from '../git/models/diff';
import { Hovers } from '../hovers/hovers'; import { Hovers } from '../hovers/hovers';
import { Logger } from '../logger';
import { log } from '../system/decorators/log';
import { getLogScope, log } from '../system/decorators/log';
import { Stopwatch } from '../system/stopwatch'; import { Stopwatch } from '../system/stopwatch';
import type { GitDocumentState, TrackedDocument } from '../trackers/gitDocumentTracker'; import type { GitDocumentState, TrackedDocument } from '../trackers/gitDocumentTracker';
import { AnnotationContext, AnnotationProviderBase } from './annotationProvider'; import { AnnotationContext, AnnotationProviderBase } from './annotationProvider';
@ -66,7 +65,7 @@ export class GutterChangesAnnotationProvider extends AnnotationProviderBase
@log() @log()
async onProvideAnnotation(context?: ChangesAnnotationContext): Promise<boolean> { async onProvideAnnotation(context?: ChangesAnnotationContext): Promise<boolean> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (this.mustReopen(context)) { if (this.mustReopen(context)) {
this.clear(); this.clear();
@ -159,7 +158,7 @@ export class GutterChangesAnnotationProvider extends AnnotationProviderBase
).filter(<T>(d?: T): d is T => Boolean(d)); ).filter(<T>(d?: T): d is T => Boolean(d));
if (!diffs?.length) return false; if (!diffs?.length) return false;
const sw = new Stopwatch(cc!);
const sw = new Stopwatch(scope);
const decorationsMap = new Map< const decorationsMap = new Map<
string, string,

+ 3
- 4
src/annotations/gutterHeatmapBlameAnnotationProvider.ts View File

@ -2,8 +2,7 @@ import { Range, TextEditor, TextEditorDecorationType } from 'vscode';
import { FileAnnotationType } from '../configuration'; import { FileAnnotationType } from '../configuration';
import type { Container } from '../container'; import type { Container } from '../container';
import type { GitCommit } from '../git/models/commit'; import type { GitCommit } from '../git/models/commit';
import { Logger } from '../logger';
import { log } from '../system/decorators/log';
import { getLogScope, log } from '../system/decorators/log';
import { Stopwatch } from '../system/stopwatch'; import { Stopwatch } from '../system/stopwatch';
import type { GitDocumentState } from '../trackers/gitDocumentTracker'; import type { GitDocumentState } from '../trackers/gitDocumentTracker';
import type { TrackedDocument } from '../trackers/trackedDocument'; import type { TrackedDocument } from '../trackers/trackedDocument';
@ -18,14 +17,14 @@ export class GutterHeatmapBlameAnnotationProvider extends BlameAnnotationProvide
@log() @log()
async onProvideAnnotation(context?: AnnotationContext, _type?: FileAnnotationType): Promise<boolean> { async onProvideAnnotation(context?: AnnotationContext, _type?: FileAnnotationType): Promise<boolean> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
this.annotationContext = context; this.annotationContext = context;
const blame = await this.getBlame(); const blame = await this.getBlame();
if (blame == null) return false; if (blame == null) return false;
const sw = new Stopwatch(cc!);
const sw = new Stopwatch(scope);
const decorationsMap = new Map< const decorationsMap = new Map<
string, string,

+ 18
- 18
src/annotations/lineAnnotationController.ts View File

@ -17,8 +17,8 @@ import { CommitFormatter } from '../git/formatters/commitFormatter';
import type { GitCommit } from '../git/models/commit'; import type { GitCommit } from '../git/models/commit';
import type { PullRequest } from '../git/models/pullRequest'; import type { PullRequest } from '../git/models/pullRequest';
import { Authentication } from '../git/remotes/provider'; import { Authentication } from '../git/remotes/provider';
import { LogCorrelationContext, Logger } from '../logger';
import { debug, log } from '../system/decorators/log';
import { Logger, LogScope } from '../logger';
import { debug, getLogScope, log } from '../system/decorators/log';
import { once } from '../system/event'; import { once } from '../system/event';
import { count, every, filterMap } from '../system/iterable'; import { count, every, filterMap } from '../system/iterable';
import { PromiseCancelledError, PromiseCancelledErrorWithId, raceAll } from '../system/promise'; import { PromiseCancelledError, PromiseCancelledErrorWithId, raceAll } from '../system/promise';
@ -189,12 +189,12 @@ export class LineAnnotationController implements Disposable {
private async refresh(editor: TextEditor | undefined, options?: { prs?: Map<string, PullRequest | undefined> }) { private async refresh(editor: TextEditor | undefined, options?: { prs?: Map<string, PullRequest | undefined> }) {
if (editor == null && this._editor == null) return; if (editor == null && this._editor == null) return;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const selections = this.container.lineTracker.selections; const selections = this.container.lineTracker.selections;
if (editor == null || selections == null || !isTextEditor(editor)) { if (editor == null || selections == null || !isTextEditor(editor)) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} Skipped because there is no valid editor or no valid selections`;
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} Skipped because there is no valid editor or no valid selections`;
} }
this.clear(this._editor); this.clear(this._editor);
@ -210,8 +210,8 @@ export class LineAnnotationController implements Disposable {
const cfg = configuration.get('currentLine'); const cfg = configuration.get('currentLine');
if (this.suspended) { if (this.suspended) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} Skipped because the controller is suspended`;
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} Skipped because the controller is suspended`;
} }
this.clear(editor); this.clear(editor);
@ -220,8 +220,8 @@ export class LineAnnotationController implements Disposable {
const trackedDocument = await this.container.tracker.getOrAdd(editor.document); const trackedDocument = await this.container.tracker.getOrAdd(editor.document);
if (!trackedDocument.isBlameable && this.suspended) { if (!trackedDocument.isBlameable && this.suspended) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} Skipped because the ${
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} Skipped because the ${
this.suspended this.suspended
? 'controller is suspended' ? 'controller is suspended'
: `document(${trackedDocument.uri.toString(true)}) is not blameable` : `document(${trackedDocument.uri.toString(true)}) is not blameable`
@ -234,8 +234,8 @@ export class LineAnnotationController implements Disposable {
// Make sure the editor hasn't died since the await above and that we are still on the same line(s) // Make sure the editor hasn't died since the await above and that we are still on the same line(s)
if (editor.document == null || !this.container.lineTracker.includes(selections)) { if (editor.document == null || !this.container.lineTracker.includes(selections)) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} Skipped because the ${
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} Skipped because the ${
editor.document == null editor.document == null
? 'editor is gone' ? 'editor is gone'
: `selection(s)=${selections : `selection(s)=${selections
@ -246,8 +246,8 @@ export class LineAnnotationController implements Disposable {
return; return;
} }
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} selection(s)=${selections
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} selection(s)=${selections
.map(s => `[${s.anchor}-${s.active}]`) .map(s => `[${s.anchor}-${s.active}]`)
.join()}`; .join()}`;
} }
@ -256,7 +256,7 @@ export class LineAnnotationController implements Disposable {
...filterMap<LineSelection, [number, GitCommit]>(selections, selection => { ...filterMap<LineSelection, [number, GitCommit]>(selections, selection => {
const state = this.container.lineTracker.getState(selection.active); const state = this.container.lineTracker.getState(selection.active);
if (state?.commit == null) { if (state?.commit == null) {
Logger.debug(cc, `Line ${selection.active} returned no commit`);
Logger.debug(scope, `Line ${selection.active} returned no commit`);
return undefined; return undefined;
} }
@ -292,7 +292,7 @@ export class LineAnnotationController implements Disposable {
if (prs != null) { if (prs != null) {
this._cancellation?.cancel(); this._cancellation?.cancel();
this._cancellation = new CancellationTokenSource(); this._cancellation = new CancellationTokenSource();
void this.waitForAnyPendingPullRequests(editor, prs, this._cancellation.token, timeout, cc);
void this.waitForAnyPendingPullRequests(editor, prs, this._cancellation.token, timeout, scope);
} }
const decorations = []; const decorations = [];
@ -344,13 +344,13 @@ export class LineAnnotationController implements Disposable {
>, >,
cancellationToken: CancellationToken, cancellationToken: CancellationToken,
timeout: number, timeout: number,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
) { ) {
// If there are any PRs that timed out, refresh the annotation(s) once they complete // If there are any PRs that timed out, refresh the annotation(s) once they complete
const prCount = count(prs.values(), pr => pr instanceof PromiseCancelledError); const prCount = count(prs.values(), pr => pr instanceof PromiseCancelledError);
if (cancellationToken.isCancellationRequested || prCount === 0) return; if (cancellationToken.isCancellationRequested || prCount === 0) return;
Logger.debug(cc, `${GlyphChars.Dot} ${prCount} pull request queries took too long (over ${timeout} ms)`);
Logger.debug(scope, `${GlyphChars.Dot} ${prCount} pull request queries took too long (over ${timeout} ms)`);
const resolved = new Map<string, PullRequest | undefined>(); const resolved = new Map<string, PullRequest | undefined>();
for (const [key, value] of prs) { for (const [key, value] of prs) {
@ -359,7 +359,7 @@ export class LineAnnotationController implements Disposable {
if (cancellationToken.isCancellationRequested || editor !== this._editor) return; if (cancellationToken.isCancellationRequested || editor !== this._editor) return;
Logger.debug(cc, `${GlyphChars.Dot} ${prCount} pull request queries completed; refreshing...`);
Logger.debug(scope, `${GlyphChars.Dot} ${prCount} pull request queries completed; refreshing...`);
void this.refresh(editor, { prs: resolved }); void this.refresh(editor, { prs: resolved });
} }

+ 1
- 1
src/commands/gitCommands.ts View File

@ -116,7 +116,7 @@ export class GitCommandsCommand extends Command {
return this.execute(args); return this.execute(args);
} }
@log({ args: false, correlate: true, singleLine: true, timed: false })
@log({ args: false, scoped: true, singleLine: true, timed: false })
async execute(args?: GitCommandsCommandArgs) { async execute(args?: GitCommandsCommandArgs) {
const commandsStep = new PickCommandStep(this.container, args); const commandsStep = new PickCommandStep(this.container, args);

+ 5
- 6
src/commands/switchMode.ts View File

@ -2,10 +2,9 @@ import { ConfigurationTarget } from 'vscode';
import { configuration } from '../configuration'; import { configuration } from '../configuration';
import { Commands } from '../constants'; import { Commands } from '../constants';
import type { Container } from '../container'; import type { Container } from '../container';
import { Logger } from '../logger';
import { ModePicker } from '../quickpicks/modePicker'; import { ModePicker } from '../quickpicks/modePicker';
import { command } from '../system/command'; import { command } from '../system/command';
import { log } from '../system/decorators/log';
import { getLogScope, log } from '../system/decorators/log';
import { Command } from './base'; import { Command } from './base';
@command() @command()
@ -14,15 +13,15 @@ export class SwitchModeCommand extends Command {
super(Commands.SwitchMode); super(Commands.SwitchMode);
} }
@log({ args: false, correlate: true, singleLine: true, timed: false })
@log({ args: false, scoped: true, singleLine: true, timed: false })
async execute() { async execute() {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const pick = await ModePicker.show(); const pick = await ModePicker.show();
if (pick === undefined) return; if (pick === undefined) return;
if (cc != null) {
cc.exitDetails = ` \u2014 mode=${pick.key ?? ''}`;
if (scope != null) {
scope.exitDetails = ` \u2014 mode=${pick.key ?? ''}`;
} }
const active = configuration.get('mode.active'); const active = configuration.get('mode.active');

+ 94
- 94
src/env/node/git/localGitProvider.ts View File

@ -90,13 +90,13 @@ import { GitWorktreeParser } from '../../../git/parsers/worktreeParser';
import { RemoteProviderFactory, RemoteProviders } from '../../../git/remotes/factory'; import { RemoteProviderFactory, RemoteProviders } from '../../../git/remotes/factory';
import { RemoteProvider, RemoteResourceType, RichRemoteProvider } from '../../../git/remotes/provider'; import { RemoteProvider, RemoteResourceType, RichRemoteProvider } from '../../../git/remotes/provider';
import { SearchPattern } from '../../../git/search'; import { SearchPattern } from '../../../git/search';
import { LogCorrelationContext, Logger } from '../../../logger';
import { Logger, LogScope } from '../../../logger';
import { Messages } from '../../../messages'; import { Messages } from '../../../messages';
import { WorkspaceStorageKeys } from '../../../storage'; import { WorkspaceStorageKeys } from '../../../storage';
import { countStringLength, filterMap } from '../../../system/array'; import { countStringLength, filterMap } from '../../../system/array';
import { TimedCancellationSource } from '../../../system/cancellation'; import { TimedCancellationSource } from '../../../system/cancellation';
import { gate } from '../../../system/decorators/gate'; import { gate } from '../../../system/decorators/gate';
import { debug, log } from '../../../system/decorators/log';
import { debug, getLogScope, log } from '../../../system/decorators/log';
import { filterMap as filterMapIterable, find, first, last, some } from '../../../system/iterable'; import { filterMap as filterMapIterable, find, first, last, some } from '../../../system/iterable';
import { import {
commonBaseIndex, commonBaseIndex,
@ -240,10 +240,10 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log() @log()
private async findGit(): Promise<GitLocation> { private async findGit(): Promise<GitLocation> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (!configuration.getAny<boolean>('git.enabled', null, true)) { if (!configuration.getAny<boolean>('git.enabled', null, true)) {
Logger.log(cc, 'Built-in Git is disabled ("git.enabled": false)');
Logger.log(scope, 'Built-in Git is disabled ("git.enabled": false)');
void Messages.showGitDisabledErrorMessage(); void Messages.showGitDisabledErrorMessage();
throw new UnableToFindGitError(); throw new UnableToFindGitError();
@ -295,13 +295,13 @@ export class LocalGitProvider implements GitProvider, Disposable {
void this.container.storage.storeWorkspace(WorkspaceStorageKeys.GitPath, location.path); void this.container.storage.storeWorkspace(WorkspaceStorageKeys.GitPath, location.path);
}, 1000); }, 1000);
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} Git (${location.version}) found in ${
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} Git (${location.version}) found in ${
location.path === 'git' ? 'PATH' : location.path location.path === 'git' ? 'PATH' : location.path
}`; }`;
} else { } else {
Logger.log( Logger.log(
cc,
scope,
`Git (${location.version}) found in ${location.path === 'git' ? 'PATH' : location.path} ${ `Git (${location.version}) found in ${location.path === 'git' ? 'PATH' : location.path} ${
GlyphChars.Dot GlyphChars.Dot
} ${getDurationMilliseconds(start)} ms`, } ${getDurationMilliseconds(start)} ms`,
@ -310,7 +310,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
// Warn if git is less than v2.7.2 // Warn if git is less than v2.7.2
if (compare(fromString(location.version), fromString('2.7.2')) === -1) { if (compare(fromString(location.version), fromString('2.7.2')) === -1) {
Logger.log(cc, `Git version (${location.version}) is outdated`);
Logger.log(scope, `Git version (${location.version}) is outdated`);
void Messages.showGitVersionUnsupportedErrorMessage(location.version, '2.7.2'); void Messages.showGitVersionUnsupportedErrorMessage(location.version, '2.7.2');
} }
@ -501,13 +501,13 @@ export class LocalGitProvider implements GitProvider, Disposable {
}`, }`,
}) })
private async repositorySearch(folder: WorkspaceFolder, depth?: number): Promise<Repository[]> { private async repositorySearch(folder: WorkspaceFolder, depth?: number): Promise<Repository[]> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
depth = depth =
depth ?? depth ??
configuration.get('advanced.repositorySearchDepth', folder.uri) ?? configuration.get('advanced.repositorySearchDepth', folder.uri) ??
configuration.getAny<number>(CoreGitConfiguration.RepositoryScanMaxDepth, folder.uri, 1); configuration.getAny<number>(CoreGitConfiguration.RepositoryScanMaxDepth, folder.uri, 1);
Logger.log(cc, `searching (depth=${depth})...`);
Logger.log(scope, `searching (depth=${depth})...`);
const repositories: Repository[] = []; const repositories: Repository[] = [];
@ -523,7 +523,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
canonicalRootPath = normalizePath(canonicalUri.fsPath); canonicalRootPath = normalizePath(canonicalUri.fsPath);
} }
Logger.log(cc, `found root repository in '${uri.fsPath}'`);
Logger.log(scope, `found root repository in '${uri.fsPath}'`);
repositories.push(...this.openRepository(folder, uri, true)); repositories.push(...this.openRepository(folder, uri, true));
} }
@ -554,9 +554,9 @@ export class LocalGitProvider implements GitProvider, Disposable {
} catch (ex) { } catch (ex) {
const msg: string = ex?.toString() ?? ''; const msg: string = ex?.toString() ?? '';
if (RepoSearchWarnings.doesNotExist.test(msg)) { if (RepoSearchWarnings.doesNotExist.test(msg)) {
Logger.log(cc, `FAILED${msg ? ` Error: ${msg}` : ''}`);
Logger.log(scope, `FAILED${msg ? ` Error: ${msg}` : ''}`);
} else { } else {
Logger.error(ex, cc, 'FAILED');
Logger.error(ex, scope, 'FAILED');
} }
return repositories; return repositories;
@ -576,16 +576,16 @@ export class LocalGitProvider implements GitProvider, Disposable {
continue; continue;
} }
Logger.log(cc, `searching in '${p}'...`);
Logger.log(scope, `searching in '${p}'...`);
Logger.debug( Logger.debug(
cc,
scope,
`normalizedRepoPath=${normalized}, rootPath=${rootPath}, canonicalRootPath=${canonicalRootPath}`, `normalizedRepoPath=${normalized}, rootPath=${rootPath}, canonicalRootPath=${canonicalRootPath}`,
); );
const rp = await this.findRepositoryUri(Uri.file(p), true); const rp = await this.findRepositoryUri(Uri.file(p), true);
if (rp == null) continue; if (rp == null) continue;
Logger.log(cc, `found repository in '${rp.fsPath}'`);
Logger.log(scope, `found repository in '${rp.fsPath}'`);
repositories.push(...this.openRepository(folder, rp, false)); repositories.push(...this.openRepository(folder, rp, false));
} }
@ -599,7 +599,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
excludes: Set<string>, excludes: Set<string>,
repositories: string[] = [], repositories: string[] = [],
): Promise<string[]> { ): Promise<string[]> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
return new Promise<string[]>((resolve, reject) => { return new Promise<string[]>((resolve, reject) => {
readdir(root, { withFileTypes: true }, async (err, files) => { readdir(root, { withFileTypes: true }, async (err, files) => {
@ -623,7 +623,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
try { try {
await this.repositorySearchCore(resolvePath(root, f.name), depth, excludes, repositories); await this.repositorySearchCore(resolvePath(root, f.name), depth, excludes, repositories);
} catch (ex) { } catch (ex) {
Logger.error(ex, cc, 'FAILED');
Logger.error(ex, scope, 'FAILED');
} }
} }
} }
@ -809,7 +809,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log() @log()
async applyChangesToWorkingFile(uri: GitUri, ref1?: string, ref2?: string) { async applyChangesToWorkingFile(uri: GitUri, ref1?: string, ref2?: string) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
ref1 = ref1 ?? uri.sha; ref1 = ref1 ?? uri.sha;
if (ref1 == null || uri.repoPath == null) return; if (ref1 == null || uri.repoPath == null) return;
@ -848,7 +848,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
} }
} }
Logger.error(ex, cc);
Logger.error(ex, scope);
void Messages.showGenericErrorMessage('Unable to apply changes'); void Messages.showGenericErrorMessage('Unable to apply changes');
} }
} }
@ -859,7 +859,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
ref: string, ref: string,
options?: { createBranch?: string } | { path?: string }, options?: { createBranch?: string } | { path?: string },
): Promise<void> { ): Promise<void> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
await this.git.checkout(repoPath, ref, options); await this.git.checkout(repoPath, ref, options);
@ -872,7 +872,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return; return;
} }
Logger.error(ex, cc);
Logger.error(ex, scope);
void void Messages.showGenericErrorMessage(`Unable to checkout '${ref}'`); void void Messages.showGenericErrorMessage(`Unable to checkout '${ref}'`);
} }
} }
@ -952,7 +952,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@gate() @gate()
@debug() @debug()
async findRepositoryUri(uri: Uri, isDirectory?: boolean): Promise<Uri | undefined> { async findRepositoryUri(uri: Uri, isDirectory?: boolean): Promise<Uri | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
let repoPath: string | undefined; let repoPath: string | undefined;
try { try {
@ -1007,13 +1007,13 @@ export class LocalGitProvider implements GitProvider, Disposable {
[repoPath, symlink] = await new Promise<[string, string | undefined]>(resolve => { [repoPath, symlink] = await new Promise<[string, string | undefined]>(resolve => {
realpath(uri.fsPath, { encoding: 'utf8' }, (err, resolvedPath) => { realpath(uri.fsPath, { encoding: 'utf8' }, (err, resolvedPath) => {
if (err != null) { if (err != null) {
Logger.debug(cc, `fs.realpath failed; repoPath=${repoPath}`);
Logger.debug(scope, `fs.realpath failed; repoPath=${repoPath}`);
resolve([repoPath!, undefined]); resolve([repoPath!, undefined]);
return; return;
} }
if (equalsIgnoreCase(uri.fsPath, resolvedPath)) { if (equalsIgnoreCase(uri.fsPath, resolvedPath)) {
Logger.debug(cc, `No symlink detected; repoPath=${repoPath}`);
Logger.debug(scope, `No symlink detected; repoPath=${repoPath}`);
resolve([repoPath!, undefined]); resolve([repoPath!, undefined]);
return; return;
} }
@ -1028,7 +1028,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
} }
Logger.debug( Logger.debug(
cc,
scope,
`Symlink detected; repoPath=${repoPath}, path=${uri.fsPath}, resolvedPath=${resolvedPath}`, `Symlink detected; repoPath=${repoPath}, path=${uri.fsPath}, resolvedPath=${resolvedPath}`,
); );
resolve([repoPath!, linkPath]); resolve([repoPath!, linkPath]);
@ -1044,7 +1044,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return repoPath ? Uri.file(repoPath) : undefined; return repoPath ? Uri.file(repoPath) : undefined;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }
@ -1060,7 +1060,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@gate<LocalGitProvider['getBlame']>((u, d) => `${u.toString()}|${d?.isDirty}`) @gate<LocalGitProvider['getBlame']>((u, d) => `${u.toString()}|${d?.isDirty}`)
@log<LocalGitProvider['getBlame']>({ args: { 1: d => d?.isDirty } }) @log<LocalGitProvider['getBlame']>({ args: { 1: d => d?.isDirty } })
async getBlame(uri: GitUri, document?: TextDocument | undefined): Promise<GitBlame | undefined> { async getBlame(uri: GitUri, document?: TextDocument | undefined): Promise<GitBlame | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (document?.isDirty) return this.getBlameContents(uri, document.getText()); if (document?.isDirty) return this.getBlameContents(uri, document.getText());
@ -1074,22 +1074,22 @@ export class LocalGitProvider implements GitProvider, Disposable {
if (doc.state != null) { if (doc.state != null) {
const cachedBlame = doc.state.getBlame(key); const cachedBlame = doc.state.getBlame(key);
if (cachedBlame != null) { if (cachedBlame != null) {
Logger.debug(cc, `Cache hit: '${key}'`);
Logger.debug(scope, `Cache hit: '${key}'`);
return cachedBlame.item; return cachedBlame.item;
} }
} }
Logger.debug(cc, `Cache miss: '${key}'`);
Logger.debug(scope, `Cache miss: '${key}'`);
if (doc.state == null) { if (doc.state == null) {
doc.state = new GitDocumentState(); doc.state = new GitDocumentState();
} }
} }
const promise = this.getBlameCore(uri, doc, key, cc);
const promise = this.getBlameCore(uri, doc, key, scope);
if (doc.state != null) { if (doc.state != null) {
Logger.debug(cc, `Cache add: '${key}'`);
Logger.debug(scope, `Cache add: '${key}'`);
const value: CachedBlame = { const value: CachedBlame = {
item: promise as Promise<GitBlame>, item: promise as Promise<GitBlame>,
@ -1104,11 +1104,11 @@ export class LocalGitProvider implements GitProvider, Disposable {
uri: GitUri, uri: GitUri,
document: TrackedDocument<GitDocumentState>, document: TrackedDocument<GitDocumentState>,
key: string, key: string,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<GitBlame | undefined> { ): Promise<GitBlame | undefined> {
const paths = await this.isTrackedPrivate(uri); const paths = await this.isTrackedPrivate(uri);
if (paths == null) { if (paths == null) {
Logger.log(cc, `Skipping blame; '${uri.fsPath}' is not tracked`);
Logger.log(scope, `Skipping blame; '${uri.fsPath}' is not tracked`);
return emptyPromise as Promise<GitBlame>; return emptyPromise as Promise<GitBlame>;
} }
@ -1125,7 +1125,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
// Trap and cache expected blame errors // Trap and cache expected blame errors
if (document.state != null) { if (document.state != null) {
const msg = ex?.toString() ?? ''; const msg = ex?.toString() ?? '';
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
Logger.debug(scope, `Cache replace (with empty promise): '${key}'`);
const value: CachedBlame = { const value: CachedBlame = {
item: emptyPromise as Promise<GitBlame>, item: emptyPromise as Promise<GitBlame>,
@ -1144,7 +1144,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log<LocalGitProvider['getBlameContents']>({ args: { 1: '<contents>' } }) @log<LocalGitProvider['getBlameContents']>({ args: { 1: '<contents>' } })
async getBlameContents(uri: GitUri, contents: string): Promise<GitBlame | undefined> { async getBlameContents(uri: GitUri, contents: string): Promise<GitBlame | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const key = `blame:${md5(contents)}`; const key = `blame:${md5(contents)}`;
@ -1153,22 +1153,22 @@ export class LocalGitProvider implements GitProvider, Disposable {
if (doc.state != null) { if (doc.state != null) {
const cachedBlame = doc.state.getBlame(key); const cachedBlame = doc.state.getBlame(key);
if (cachedBlame != null) { if (cachedBlame != null) {
Logger.debug(cc, `Cache hit: ${key}`);
Logger.debug(scope, `Cache hit: ${key}`);
return cachedBlame.item; return cachedBlame.item;
} }
} }
Logger.debug(cc, `Cache miss: ${key}`);
Logger.debug(scope, `Cache miss: ${key}`);
if (doc.state == null) { if (doc.state == null) {
doc.state = new GitDocumentState(); doc.state = new GitDocumentState();
} }
} }
const promise = this.getBlameContentsCore(uri, contents, doc, key, cc);
const promise = this.getBlameContentsCore(uri, contents, doc, key, scope);
if (doc.state != null) { if (doc.state != null) {
Logger.debug(cc, `Cache add: '${key}'`);
Logger.debug(scope, `Cache add: '${key}'`);
const value: CachedBlame = { const value: CachedBlame = {
item: promise as Promise<GitBlame>, item: promise as Promise<GitBlame>,
@ -1184,11 +1184,11 @@ export class LocalGitProvider implements GitProvider, Disposable {
contents: string, contents: string,
document: TrackedDocument<GitDocumentState>, document: TrackedDocument<GitDocumentState>,
key: string, key: string,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<GitBlame | undefined> { ): Promise<GitBlame | undefined> {
const paths = await this.isTrackedPrivate(uri); const paths = await this.isTrackedPrivate(uri);
if (paths == null) { if (paths == null) {
Logger.log(cc, `Skipping blame; '${uri.fsPath}' is not tracked`);
Logger.log(scope, `Skipping blame; '${uri.fsPath}' is not tracked`);
return emptyPromise as Promise<GitBlame>; return emptyPromise as Promise<GitBlame>;
} }
@ -1206,7 +1206,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
// Trap and cache expected blame errors // Trap and cache expected blame errors
if (document.state != null) { if (document.state != null) {
const msg = ex?.toString() ?? ''; const msg = ex?.toString() ?? '';
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
Logger.debug(scope, `Cache replace (with empty promise): '${key}'`);
const value: CachedBlame = { const value: CachedBlame = {
item: emptyPromise as Promise<GitBlame>, item: emptyPromise as Promise<GitBlame>,
@ -1561,7 +1561,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
uri: Uri, uri: Uri,
options?: { ref?: string; firstIfNotFound?: boolean; range?: Range }, options?: { ref?: string; firstIfNotFound?: boolean; range?: Range },
): Promise<GitCommit | undefined> { ): Promise<GitCommit | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const [relativePath, root] = splitPath(uri, repoPath); const [relativePath, root] = splitPath(uri, repoPath);
@ -1584,7 +1584,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return commit ?? first(log.commits.values()); return commit ?? first(log.commits.values());
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }
@ -1712,7 +1712,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
async getCurrentUser(repoPath: string): Promise<GitUser | undefined> { async getCurrentUser(repoPath: string): Promise<GitUser | undefined> {
if (!repoPath) return undefined; if (!repoPath) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const repo = this._repoInfoCache.get(repoPath); const repo = this._repoInfoCache.get(repoPath);
@ -1767,7 +1767,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
this._repoInfoCache.set(repoPath, { ...repo, user: user }); this._repoInfoCache.set(repoPath, { ...repo, user: user });
return user; return user;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
// Mark it so we won't bother trying again // Mark it so we won't bother trying again
@ -1804,7 +1804,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log() @log()
async getDiffForFile(uri: GitUri, ref1: string | undefined, ref2?: string): Promise<GitDiff | undefined> { async getDiffForFile(uri: GitUri, ref1: string | undefined, ref2?: string): Promise<GitDiff | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
let key = 'diff'; let key = 'diff';
if (ref1 != null) { if (ref1 != null) {
@ -1819,12 +1819,12 @@ export class LocalGitProvider implements GitProvider, Disposable {
if (doc.state != null) { if (doc.state != null) {
const cachedDiff = doc.state.getDiff(key); const cachedDiff = doc.state.getDiff(key);
if (cachedDiff != null) { if (cachedDiff != null) {
Logger.debug(cc, `Cache hit: '${key}'`);
Logger.debug(scope, `Cache hit: '${key}'`);
return cachedDiff.item; return cachedDiff.item;
} }
} }
Logger.debug(cc, `Cache miss: '${key}'`);
Logger.debug(scope, `Cache miss: '${key}'`);
if (doc.state == null) { if (doc.state == null) {
doc.state = new GitDocumentState(); doc.state = new GitDocumentState();
@ -1839,11 +1839,11 @@ export class LocalGitProvider implements GitProvider, Disposable {
{ encoding: GitProviderService.getEncoding(uri) }, { encoding: GitProviderService.getEncoding(uri) },
doc, doc,
key, key,
cc,
scope,
); );
if (doc.state != null) { if (doc.state != null) {
Logger.debug(cc, `Cache add: '${key}'`);
Logger.debug(scope, `Cache add: '${key}'`);
const value: CachedDiff = { const value: CachedDiff = {
item: promise as Promise<GitDiff>, item: promise as Promise<GitDiff>,
@ -1862,7 +1862,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
options: { encoding?: string }, options: { encoding?: string },
document: TrackedDocument<GitDocumentState>, document: TrackedDocument<GitDocumentState>,
key: string, key: string,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<GitDiff | undefined> { ): Promise<GitDiff | undefined> {
const [relativePath, root] = splitPath(path, repoPath); const [relativePath, root] = splitPath(path, repoPath);
@ -1881,7 +1881,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
// Trap and cache expected diff errors // Trap and cache expected diff errors
if (document.state != null) { if (document.state != null) {
const msg = ex?.toString() ?? ''; const msg = ex?.toString() ?? '';
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
Logger.debug(scope, `Cache replace (with empty promise): '${key}'`);
const value: CachedDiff = { const value: CachedDiff = {
item: emptyPromise as Promise<GitDiff>, item: emptyPromise as Promise<GitDiff>,
@ -1898,7 +1898,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log<LocalGitProvider['getDiffForFileContents']>({ args: { 1: '<contents>' } }) @log<LocalGitProvider['getDiffForFileContents']>({ args: { 1: '<contents>' } })
async getDiffForFileContents(uri: GitUri, ref: string, contents: string): Promise<GitDiff | undefined> { async getDiffForFileContents(uri: GitUri, ref: string, contents: string): Promise<GitDiff | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const key = `diff:${md5(contents)}`; const key = `diff:${md5(contents)}`;
@ -1907,12 +1907,12 @@ export class LocalGitProvider implements GitProvider, Disposable {
if (doc.state != null) { if (doc.state != null) {
const cachedDiff = doc.state.getDiff(key); const cachedDiff = doc.state.getDiff(key);
if (cachedDiff != null) { if (cachedDiff != null) {
Logger.debug(cc, `Cache hit: ${key}`);
Logger.debug(scope, `Cache hit: ${key}`);
return cachedDiff.item; return cachedDiff.item;
} }
} }
Logger.debug(cc, `Cache miss: ${key}`);
Logger.debug(scope, `Cache miss: ${key}`);
if (doc.state == null) { if (doc.state == null) {
doc.state = new GitDocumentState(); doc.state = new GitDocumentState();
@ -1927,11 +1927,11 @@ export class LocalGitProvider implements GitProvider, Disposable {
{ encoding: GitProviderService.getEncoding(uri) }, { encoding: GitProviderService.getEncoding(uri) },
doc, doc,
key, key,
cc,
scope,
); );
if (doc.state != null) { if (doc.state != null) {
Logger.debug(cc, `Cache add: '${key}'`);
Logger.debug(scope, `Cache add: '${key}'`);
const value: CachedDiff = { const value: CachedDiff = {
item: promise as Promise<GitDiff>, item: promise as Promise<GitDiff>,
@ -1950,7 +1950,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
options: { encoding?: string }, options: { encoding?: string },
document: TrackedDocument<GitDocumentState>, document: TrackedDocument<GitDocumentState>,
key: string, key: string,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<GitDiff | undefined> { ): Promise<GitDiff | undefined> {
const [relativePath, root] = splitPath(path, repoPath); const [relativePath, root] = splitPath(path, repoPath);
@ -1967,7 +1967,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
// Trap and cache expected diff errors // Trap and cache expected diff errors
if (document.state != null) { if (document.state != null) {
const msg = ex?.toString() ?? ''; const msg = ex?.toString() ?? '';
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
Logger.debug(scope, `Cache replace (with empty promise): '${key}'`);
const value: CachedDiff = { const value: CachedDiff = {
item: emptyPromise as Promise<GitDiff>, item: emptyPromise as Promise<GitDiff>,
@ -2075,7 +2075,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
since?: string; since?: string;
}, },
): Promise<GitLog | undefined> { ): Promise<GitLog | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0; const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0;
@ -2139,7 +2139,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return log; return log;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return undefined; return undefined;
} }
@ -2158,7 +2158,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
since?: string; since?: string;
}, },
): Promise<Set<string> | undefined> { ): Promise<Set<string> | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0; const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0;
@ -2178,7 +2178,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
const commits = new Set(parser.parse(data)); const commits = new Set(parser.parse(data));
return commits; return commits;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return undefined; return undefined;
} }
@ -2419,7 +2419,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
): Promise<GitLog | undefined> { ): Promise<GitLog | undefined> {
if (repoPath == null) return undefined; if (repoPath == null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const relativePath = this.getRelativePath(pathOrUri, repoPath); const relativePath = this.getRelativePath(pathOrUri, repoPath);
@ -2471,7 +2471,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
if (doc.state != null) { if (doc.state != null) {
const cachedLog = doc.state.getLog(key); const cachedLog = doc.state.getLog(key);
if (cachedLog != null) { if (cachedLog != null) {
Logger.debug(cc, `Cache hit: '${key}'`);
Logger.debug(scope, `Cache hit: '${key}'`);
return cachedLog.item; return cachedLog.item;
} }
@ -2482,14 +2482,14 @@ export class LocalGitProvider implements GitProvider, Disposable {
); );
if (cachedLog != null) { if (cachedLog != null) {
if (options.ref == null) { if (options.ref == null) {
Logger.debug(cc, `Cache hit: ~'${key}'`);
Logger.debug(scope, `Cache hit: ~'${key}'`);
return cachedLog.item; return cachedLog.item;
} }
Logger.debug(cc, `Cache ?: '${key}'`);
Logger.debug(scope, `Cache ?: '${key}'`);
let log = await cachedLog.item; let log = await cachedLog.item;
if (log != null && !log.hasMore && log.commits.has(options.ref)) { if (log != null && !log.hasMore && log.commits.has(options.ref)) {
Logger.debug(cc, `Cache hit: '${key}'`);
Logger.debug(scope, `Cache hit: '${key}'`);
// Create a copy of the log starting at the requested commit // Create a copy of the log starting at the requested commit
let skip = true; let skip = true;
@ -2529,17 +2529,17 @@ export class LocalGitProvider implements GitProvider, Disposable {
} }
} }
Logger.debug(cc, `Cache miss: '${key}'`);
Logger.debug(scope, `Cache miss: '${key}'`);
if (doc.state == null) { if (doc.state == null) {
doc.state = new GitDocumentState(); doc.state = new GitDocumentState();
} }
} }
const promise = this.getLogForFileCore(repoPath, relativePath, options, doc, key, cc);
const promise = this.getLogForFileCore(repoPath, relativePath, options, doc, key, scope);
if (doc.state != null && options.range == null) { if (doc.state != null && options.range == null) {
Logger.debug(cc, `Cache add: '${key}'`);
Logger.debug(scope, `Cache add: '${key}'`);
const value: CachedLog = { const value: CachedLog = {
item: promise as Promise<GitLog>, item: promise as Promise<GitLog>,
@ -2571,11 +2571,11 @@ export class LocalGitProvider implements GitProvider, Disposable {
}, },
document: TrackedDocument<GitDocumentState>, document: TrackedDocument<GitDocumentState>,
key: string, key: string,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<GitLog | undefined> { ): Promise<GitLog | undefined> {
const paths = await this.isTrackedPrivate(path, repoPath, ref); const paths = await this.isTrackedPrivate(path, repoPath, ref);
if (paths == null) { if (paths == null) {
Logger.log(cc, `Skipping blame; '${path}' is not tracked`);
Logger.log(scope, `Skipping blame; '${path}' is not tracked`);
return emptyPromise as Promise<GitLog>; return emptyPromise as Promise<GitLog>;
} }
@ -2621,7 +2621,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
// Trap and cache expected log errors // Trap and cache expected log errors
if (document.state != null && range == null && !options.reverse) { if (document.state != null && range == null && !options.reverse) {
const msg: string = ex?.toString() ?? ''; const msg: string = ex?.toString() ?? '';
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
Logger.debug(scope, `Cache replace (with empty promise): '${key}'`);
const value: CachedLog = { const value: CachedLog = {
item: emptyPromise as Promise<GitLog>, item: emptyPromise as Promise<GitLog>,
@ -2699,7 +2699,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log() @log()
async getMergeBase(repoPath: string, ref1: string, ref2: string, options?: { forkPoint?: boolean }) { async getMergeBase(repoPath: string, ref1: string, ref2: string, options?: { forkPoint?: boolean }) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const data = await this.git.merge_base(repoPath, ref1, ref2, options); const data = await this.git.merge_base(repoPath, ref1, ref2, options);
@ -2707,7 +2707,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return data.split('\n')[0].trim() || undefined; return data.split('\n')[0].trim() || undefined;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }
@ -3135,7 +3135,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
): Promise<GitUri | undefined> { ): Promise<GitUri | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined; if (ref === GitRevision.deletedOrMissing) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (ref === GitRevision.uncommitted) { if (ref === GitRevision.uncommitted) {
ref = undefined; ref = undefined;
@ -3171,7 +3171,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return GitUri.fromFile(relativePath, repoPath, ref ?? GitRevision.deletedOrMissing); return GitUri.fromFile(relativePath, repoPath, ref ?? GitRevision.deletedOrMissing);
} }
Logger.error(ex, cc);
Logger.error(ex, scope);
throw ex; throw ex;
} }
if (data == null || data.length === 0) return undefined; if (data == null || data.length === 0) return undefined;
@ -3188,7 +3188,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
repoPath: string, repoPath: string,
options?: { all?: boolean; branch?: string; limit?: number; ordering?: string | null; skip?: number }, options?: { all?: boolean; branch?: string; limit?: number; ordering?: string | null; skip?: number },
): Promise<GitReflog | undefined> { ): Promise<GitReflog | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0; const limit = options?.limit ?? configuration.get('advanced.maxListItems') ?? 0;
try { try {
@ -3207,7 +3207,7 @@ export class LocalGitProvider implements GitProvider, Disposable {
return reflog; return reflog;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }
@ -3656,12 +3656,12 @@ export class LocalGitProvider implements GitProvider, Disposable {
try { try {
let tool = options?.tool; let tool = options?.tool;
if (!tool) { if (!tool) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
tool = configuration.get('advanced.externalDiffTool') || (await this.getDiffTool(root)); tool = configuration.get('advanced.externalDiffTool') || (await this.getDiffTool(root));
if (tool == null) throw new Error('No diff tool found'); if (tool == null) throw new Error('No diff tool found');
Logger.log(cc, `Using tool=${tool}`);
Logger.log(scope, `Using tool=${tool}`);
} }
await this.git.difftool(root, relativePath, tool, options); await this.git.difftool(root, relativePath, tool, options);
@ -3691,12 +3691,12 @@ export class LocalGitProvider implements GitProvider, Disposable {
async openDirectoryCompare(repoPath: string, ref1: string, ref2?: string, tool?: string): Promise<void> { async openDirectoryCompare(repoPath: string, ref1: string, ref2?: string, tool?: string): Promise<void> {
try { try {
if (!tool) { if (!tool) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
tool = configuration.get('advanced.externalDirectoryDiffTool') || (await this.getDiffTool(repoPath)); tool = configuration.get('advanced.externalDirectoryDiffTool') || (await this.getDiffTool(repoPath));
if (tool == null) throw new Error('No diff tool found'); if (tool == null) throw new Error('No diff tool found');
Logger.log(cc, `Using tool=${tool}`);
Logger.log(scope, `Using tool=${tool}`);
} }
await this.git.difftool__dir_diff(repoPath, tool, ref1, ref2); await this.git.difftool__dir_diff(repoPath, tool, ref1, ref2);
@ -3988,31 +3988,31 @@ export class LocalGitProvider implements GitProvider, Disposable {
@log() @log()
async getOpenScmRepositories(): Promise<ScmRepository[]> { async getOpenScmRepositories(): Promise<ScmRepository[]> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const gitApi = await this.getScmGitApi(); const gitApi = await this.getScmGitApi();
return gitApi?.repositories ?? []; return gitApi?.repositories ?? [];
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return []; return [];
} }
} }
@log() @log()
async getScmRepository(repoPath: string): Promise<ScmRepository | undefined> { async getScmRepository(repoPath: string): Promise<ScmRepository | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const gitApi = await this.getScmGitApi(); const gitApi = await this.getScmGitApi();
return gitApi?.getRepository(Uri.file(repoPath)) ?? undefined; return gitApi?.getRepository(Uri.file(repoPath)) ?? undefined;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }
@log() @log()
async getOrOpenScmRepository(repoPath: string): Promise<ScmRepository | undefined> { async getOrOpenScmRepository(repoPath: string): Promise<ScmRepository | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const gitApi = await this.getScmGitApi(); const gitApi = await this.getScmGitApi();
if (gitApi?.openRepository != null) { if (gitApi?.openRepository != null) {
@ -4021,19 +4021,19 @@ export class LocalGitProvider implements GitProvider, Disposable {
return gitApi?.getRepository(Uri.file(repoPath)) ?? undefined; return gitApi?.getRepository(Uri.file(repoPath)) ?? undefined;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }
@log() @log()
private async openScmRepository(uri: Uri): Promise<BuiltInGitRepository | undefined> { private async openScmRepository(uri: Uri): Promise<BuiltInGitRepository | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const gitApi = await this.getScmGitApi(); const gitApi = await this.getScmGitApi();
return (await gitApi?.openRepository?.(uri)) ?? undefined; return (await gitApi?.openRepository?.(uri)) ?? undefined;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }

+ 5
- 4
src/env/node/git/vslsGitProvider.ts View File

@ -5,6 +5,7 @@ import { GitCommandOptions } from '../../../git/commandOptions';
import { GitProviderDescriptor, GitProviderId } from '../../../git/gitProvider'; import { GitProviderDescriptor, GitProviderId } from '../../../git/gitProvider';
import { Repository } from '../../../git/models/repository'; import { Repository } from '../../../git/models/repository';
import { Logger } from '../../../logger'; import { Logger } from '../../../logger';
import { getLogScope } from '../../../system/decorators/log';
import { addVslsPrefixIfNeeded } from '../../../system/path'; import { addVslsPrefixIfNeeded } from '../../../system/path';
import { Git } from './git'; import { Git } from './git';
import { LocalGitProvider } from './localGitProvider'; import { LocalGitProvider } from './localGitProvider';
@ -38,7 +39,7 @@ export class VslsGitProvider extends LocalGitProvider {
override async discoverRepositories(uri: Uri): Promise<Repository[]> { override async discoverRepositories(uri: Uri): Promise<Repository[]> {
if (!this.supportedSchemes.has(uri.scheme)) return []; if (!this.supportedSchemes.has(uri.scheme)) return [];
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const guest = await this.container.vsls.guest(); const guest = await this.container.vsls.guest();
@ -49,7 +50,7 @@ export class VslsGitProvider extends LocalGitProvider {
this.openRepository(undefined, Uri.parse(r.folderUri, true), r.root, undefined, r.closed), this.openRepository(undefined, Uri.parse(r.folderUri, true), r.root, undefined, r.closed),
); );
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return []; return [];
@ -73,7 +74,7 @@ export class VslsGitProvider extends LocalGitProvider {
} }
override async findRepositoryUri(uri: Uri, isDirectory?: boolean): Promise<Uri | undefined> { override async findRepositoryUri(uri: Uri, isDirectory?: boolean): Promise<Uri | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
let repoPath: string | undefined; let repoPath: string | undefined;
try { try {
@ -92,7 +93,7 @@ export class VslsGitProvider extends LocalGitProvider {
return repoPath ? Uri.parse(repoPath, true) : undefined; return repoPath ? Uri.parse(repoPath, true) : undefined;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }

+ 6
- 6
src/git/gitProviderService.ts View File

@ -37,7 +37,7 @@ import {
} from '../subscription'; } from '../subscription';
import { groupByFilterMap, groupByMap } from '../system/array'; import { groupByFilterMap, groupByMap } from '../system/array';
import { gate } from '../system/decorators/gate'; import { gate } from '../system/decorators/gate';
import { debug, log } from '../system/decorators/log';
import { debug, getLogScope, log } from '../system/decorators/log';
import { count, filter, first, flatMap, map, some } from '../system/iterable'; import { count, filter, first, flatMap, map, some } from '../system/iterable';
import { getBestPath, getScheme, isAbsolute, maybeUri, normalizePath } from '../system/path'; import { getBestPath, getScheme, isAbsolute, maybeUri, normalizePath } from '../system/path';
import { cancellable, fastestSettled, isPromise, PromiseCancelledError } from '../system/promise'; import { cancellable, fastestSettled, isPromise, PromiseCancelledError } from '../system/promise';
@ -418,7 +418,7 @@ export class GitProviderService implements Disposable {
@log({ singleLine: true }) @log({ singleLine: true })
registrationComplete() { registrationComplete() {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
this._initializing = false; this._initializing = false;
@ -429,8 +429,8 @@ export class GitProviderService implements Disposable {
this.updateContext(); this.updateContext();
} }
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} workspaceFolders=${
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} workspaceFolders=${
workspaceFolders?.length workspaceFolders?.length
}, git.autoRepositoryDetection=${configuration.getAny<boolean | 'subFolders' | 'openEditors'>( }, git.autoRepositoryDetection=${configuration.getAny<boolean | 'subFolders' | 'openEditors'>(
CoreGitConfiguration.AutoRepositoryDetection, CoreGitConfiguration.AutoRepositoryDetection,
@ -1874,7 +1874,7 @@ export class GitProviderService implements Disposable {
@log<GitProviderService['getOrOpenRepository']>({ exit: r => `returned ${r?.path}` }) @log<GitProviderService['getOrOpenRepository']>({ exit: r => `returned ${r?.path}` })
async getOrOpenRepository(uri: Uri, detectNested?: boolean): Promise<Repository | undefined> { async getOrOpenRepository(uri: Uri, detectNested?: boolean): Promise<Repository | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const path = getBestPath(uri); const path = getBestPath(uri);
let repository: Repository | undefined; let repository: Repository | undefined;
@ -1925,7 +1925,7 @@ export class GitProviderService implements Disposable {
const closed = autoRepositoryDetection !== true && autoRepositoryDetection !== 'openEditors'; const closed = autoRepositoryDetection !== true && autoRepositoryDetection !== 'openEditors';
Logger.log(cc, `Repository found in '${repoUri.toString(false)}'`);
Logger.log(scope, `Repository found in '${repoUri.toString(false)}'`);
const repositories = provider.openRepository(root?.folder, repoUri, false, undefined, closed); const repositories = provider.openRepository(root?.folder, repoUri, false, undefined, closed);
for (const repository of repositories) { for (const repository of repositories) {
this._repositories.add(repository); this._repositories.add(repository);

+ 5
- 5
src/git/models/repository.ts View File

@ -24,7 +24,7 @@ import { filterMap, groupByMap } from '../../system/array';
import { executeActionCommand, executeCoreGitCommand } from '../../system/command'; import { executeActionCommand, executeCoreGitCommand } from '../../system/command';
import { formatDate, fromNow } from '../../system/date'; import { formatDate, fromNow } from '../../system/date';
import { gate } from '../../system/decorators/gate'; import { gate } from '../../system/decorators/gate';
import { debug, log, logName } from '../../system/decorators/log';
import { debug, getLogScope, log, logName } from '../../system/decorators/log';
import { debounce } from '../../system/function'; import { debounce } from '../../system/function';
import { filter, join, some } from '../../system/iterable'; import { filter, join, some } from '../../system/iterable';
import { basename, normalizePath } from '../../system/path'; import { basename, normalizePath } from '../../system/path';
@ -1008,7 +1008,7 @@ export class Repository implements Disposable {
@debug() @debug()
private fireChange(...changes: RepositoryChange[]) { private fireChange(...changes: RepositoryChange[]) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
this._updatedAt = Date.now(); this._updatedAt = Date.now();
@ -1021,7 +1021,7 @@ export class Repository implements Disposable {
this.onDidRepositoryChange(this, new RepositoryChangeEvent(this, changes)); this.onDidRepositoryChange(this, new RepositoryChangeEvent(this, changes));
if (this._suspended) { if (this._suspended) {
Logger.debug(cc, `queueing suspended ${this._pendingRepoChange.toString(true)}`);
Logger.debug(scope, `queueing suspended ${this._pendingRepoChange.toString(true)}`);
return; return;
} }
@ -1041,7 +1041,7 @@ export class Repository implements Disposable {
@debug() @debug()
private fireFileSystemChange(uri: Uri) { private fireFileSystemChange(uri: Uri) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
this._updatedAt = Date.now(); this._updatedAt = Date.now();
@ -1057,7 +1057,7 @@ export class Repository implements Disposable {
e.uris.push(uri); e.uris.push(uri);
if (this._suspended) { if (this._suspended) {
Logger.debug(cc, `queueing suspended fs changes=${e.uris.map(u => u.fsPath).join(', ')}`);
Logger.debug(scope, `queueing suspended fs changes=${e.uris.map(u => u.fsPath).join(', ')}`);
return; return;
} }

+ 13
- 13
src/git/remotes/provider.ts View File

@ -22,7 +22,7 @@ import { Messages } from '../../messages';
import type { IntegrationAuthenticationSessionDescriptor } from '../../plus/integrationAuthentication'; import type { IntegrationAuthenticationSessionDescriptor } from '../../plus/integrationAuthentication';
import { WorkspaceStorageKeys } from '../../storage'; import { WorkspaceStorageKeys } from '../../storage';
import { gate } from '../../system/decorators/gate'; import { gate } from '../../system/decorators/gate';
import { debug, log } from '../../system/decorators/log';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { encodeUrl } from '../../system/encoding'; import { encodeUrl } from '../../system/encoding';
import { isPromise } from '../../system/promise'; import { isPromise } from '../../system/promise';
import type { Account } from '../models/author'; import type { Account } from '../models/author';
@ -451,7 +451,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<Account | undefined> { ): Promise<Account | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected()); const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined; if (!connected) return undefined;
@ -461,7 +461,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
this.resetRequestExceptionCount(); this.resetRequestExceptionCount();
return author; return author;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException(); this.trackRequestException();
@ -486,7 +486,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<Account | undefined> { ): Promise<Account | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected()); const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined; if (!connected) return undefined;
@ -496,7 +496,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
this.resetRequestExceptionCount(); this.resetRequestExceptionCount();
return author; return author;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException(); this.trackRequestException();
@ -516,7 +516,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
@gate() @gate()
@debug() @debug()
async getDefaultBranch(): Promise<DefaultBranch | undefined> { async getDefaultBranch(): Promise<DefaultBranch | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected()); const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined; if (!connected) return undefined;
@ -526,7 +526,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
this.resetRequestExceptionCount(); this.resetRequestExceptionCount();
return defaultBranch; return defaultBranch;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException(); this.trackRequestException();
@ -542,7 +542,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
@gate() @gate()
@debug() @debug()
async getIssueOrPullRequest(id: string): Promise<IssueOrPullRequest | undefined> { async getIssueOrPullRequest(id: string): Promise<IssueOrPullRequest | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected()); const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined; if (!connected) return undefined;
@ -552,7 +552,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
this.resetRequestExceptionCount(); this.resetRequestExceptionCount();
return issueOrPullRequest; return issueOrPullRequest;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException(); this.trackRequestException();
@ -591,7 +591,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
include?: PullRequestState[]; include?: PullRequestState[];
}, },
): Promise<PullRequest | undefined> { ): Promise<PullRequest | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected()); const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return undefined; if (!connected) return undefined;
@ -601,7 +601,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
this.resetRequestExceptionCount(); this.resetRequestExceptionCount();
return pr; return pr;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) { if (ex instanceof AuthenticationError || ex instanceof ProviderRequestClientError) {
this.trackRequestException(); this.trackRequestException();
@ -634,7 +634,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
@debug() @debug()
private async getPullRequestForCommitCore(ref: string) { private async getPullRequestForCommitCore(ref: string) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const connected = this.maybeConnected ?? (await this.isConnected()); const connected = this.maybeConnected ?? (await this.isConnected());
if (!connected) return null; if (!connected) return null;
@ -645,7 +645,7 @@ export abstract class RichRemoteProvider extends RemoteProvider {
this.resetRequestExceptionCount(); this.resetRequestExceptionCount();
return pr; return pr;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
this._prsByCommit.delete(ref); this._prsByCommit.delete(ref);

+ 17
- 16
src/hovers/hovers.ts View File

@ -12,6 +12,7 @@ import type { PullRequest } from '../git/models/pullRequest';
import { GitRevision } from '../git/models/reference'; import { GitRevision } from '../git/models/reference';
import type { GitRemote } from '../git/models/remote'; import type { GitRemote } from '../git/models/remote';
import { Logger, LogLevel } from '../logger'; import { Logger, LogLevel } from '../logger';
import { getNewLogScope } from '../system/decorators/log';
import { count } from '../system/iterable'; import { count } from '../system/iterable';
import { PromiseCancelledError } from '../system/promise'; import { PromiseCancelledError } from '../system/promise';
import { getDurationMilliseconds } from '../system/string'; import { getDurationMilliseconds } from '../system/string';
@ -287,8 +288,8 @@ export namespace Hovers {
} }
async function getAutoLinkedIssuesOrPullRequests(message: string, remotes: GitRemote[]) { async function getAutoLinkedIssuesOrPullRequests(message: string, remotes: GitRemote[]) {
const cc = Logger.getNewCorrelationContext('Hovers.getAutoLinkedIssuesOrPullRequests');
Logger.debug(cc, `${GlyphChars.Dash} message=<message>`);
const scope = getNewLogScope('Hovers.getAutoLinkedIssuesOrPullRequests');
Logger.debug(scope, `${GlyphChars.Dash} message=<message>`);
const start = hrtime(); const start = hrtime();
@ -298,14 +299,14 @@ export namespace Hovers {
!cfg.autolinks.enhanced || !cfg.autolinks.enhanced ||
!CommitFormatter.has(cfg.detailsMarkdownFormat, 'message') !CommitFormatter.has(cfg.detailsMarkdownFormat, 'message')
) { ) {
Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return undefined; return undefined;
} }
const remote = await Container.instance.git.getBestRemoteWithRichProvider(remotes); const remote = await Container.instance.git.getBestRemoteWithRichProvider(remotes);
if (remote?.provider == null) { if (remote?.provider == null) {
Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return undefined; return undefined;
} }
@ -323,7 +324,7 @@ export namespace Hovers {
const prCount = count(autolinks.values(), pr => pr instanceof PromiseCancelledError); const prCount = count(autolinks.values(), pr => pr instanceof PromiseCancelledError);
if (prCount !== 0) { if (prCount !== 0) {
Logger.debug( Logger.debug(
cc,
scope,
`timed out ${ `timed out ${
GlyphChars.Dash GlyphChars.Dash
} ${prCount} issue/pull request queries took too long (over ${timeout} ms) ${ } ${prCount} issue/pull request queries took too long (over ${timeout} ms) ${
@ -340,7 +341,7 @@ export namespace Hovers {
// ]; // ];
// void Promise.all(pending).then(() => { // void Promise.all(pending).then(() => {
// Logger.debug( // Logger.debug(
// cc,
// scope,
// `${GlyphChars.Dot} ${count} issue/pull request queries completed; refreshing...`, // `${GlyphChars.Dot} ${count} issue/pull request queries completed; refreshing...`,
// ); // );
// void executeCoreCommand(CoreCommands.EditorShowHover); // void executeCoreCommand(CoreCommands.EditorShowHover);
@ -350,11 +351,11 @@ export namespace Hovers {
} }
} }
Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return autolinks; return autolinks;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc, `failed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.error(ex, scope, `failed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return undefined; return undefined;
} }
@ -367,13 +368,13 @@ export namespace Hovers {
pullRequests?: boolean; pullRequests?: boolean;
}, },
) { ) {
const cc = Logger.getNewCorrelationContext('Hovers.getPullRequestForCommit');
Logger.debug(cc, `${GlyphChars.Dash} ref=${ref}`);
const scope = getNewLogScope('Hovers.getPullRequestForCommit');
Logger.debug(scope, `${GlyphChars.Dash} ref=${ref}`);
const start = hrtime(); const start = hrtime();
if (!options?.pullRequests) { if (!options?.pullRequests) {
Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return undefined; return undefined;
} }
@ -382,7 +383,7 @@ export namespace Hovers {
includeDisconnected: true, includeDisconnected: true,
}); });
if (remote?.provider == null) { if (remote?.provider == null) {
Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return undefined; return undefined;
} }
@ -390,7 +391,7 @@ export namespace Hovers {
const { provider } = remote; const { provider } = remote;
const connected = provider.maybeConnected ?? (await provider.isConnected()); const connected = provider.maybeConnected ?? (await provider.isConnected());
if (!connected) { if (!connected) {
Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return remote; return remote;
} }
@ -398,17 +399,17 @@ export namespace Hovers {
try { try {
const pr = await Container.instance.git.getPullRequestForCommit(ref, provider, { timeout: 250 }); const pr = await Container.instance.git.getPullRequestForCommit(ref, provider, { timeout: 250 });
Logger.debug(cc, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.debug(scope, `completed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return pr; return pr;
} catch (ex) { } catch (ex) {
if (ex instanceof PromiseCancelledError) { if (ex instanceof PromiseCancelledError) {
Logger.debug(cc, `timed out ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.debug(scope, `timed out ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return ex; return ex;
} }
Logger.error(ex, cc, `failed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
Logger.error(ex, scope, `failed ${GlyphChars.Dot} ${getDurationMilliseconds(start)} ms`);
return undefined; return undefined;
} }

+ 16
- 16
src/keyboard.ts View File

@ -2,7 +2,7 @@ import { commands, Disposable } from 'vscode';
import { ContextKeys } from './constants'; import { ContextKeys } from './constants';
import { setContext } from './context'; import { setContext } from './context';
import { Logger } from './logger'; import { Logger } from './logger';
import { log } from './system/decorators/log';
import { getLogScope, log } from './system/decorators/log';
export declare interface KeyCommand { export declare interface KeyCommand {
onDidPressKey?(key: Keys): void | Promise<void>; onDidPressKey?(key: Keys): void | Promise<void>;
@ -49,9 +49,9 @@ export class KeyboardScope implements Disposable {
async dispose() { async dispose() {
const index = mappings.indexOf(this._mapping); const index = mappings.indexOf(this._mapping);
const cc = Logger.getCorrelationContext();
if (cc != null) {
cc.exitDetails = ` \u2022 index=${index}`;
const scope = getLogScope();
if (scope != null) {
scope.exitDetails = ` \u2022 index=${index}`;
} }
if (index === mappings.length - 1) { if (index === mappings.length - 1) {
@ -72,12 +72,12 @@ export class KeyboardScope implements Disposable {
prefix: (context, key) => `${context.prefix}[${mappings.length}](${key})`, prefix: (context, key) => `${context.prefix}[${mappings.length}](${key})`,
}) })
async clearKeyCommand(key: Keys) { async clearKeyCommand(key: Keys) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const mapping = mappings[mappings.length - 1]; const mapping = mappings[mappings.length - 1];
if (mapping !== this._mapping || mapping[key] == null) { if (mapping !== this._mapping || mapping[key] == null) {
if (cc != null) {
cc.exitDetails = ' \u2022 skipped';
if (scope != null) {
scope.exitDetails = ' \u2022 skipped';
} }
return; return;
@ -123,12 +123,12 @@ export class KeyboardScope implements Disposable {
prefix: (context, key) => `${context.prefix}[${mappings.length}](${key})`, prefix: (context, key) => `${context.prefix}[${mappings.length}](${key})`,
}) })
async setKeyCommand(key: Keys, command: KeyCommand | (() => Promise<KeyCommand>)) { async setKeyCommand(key: Keys, command: KeyCommand | (() => Promise<KeyCommand>)) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const mapping = mappings[mappings.length - 1]; const mapping = mappings[mappings.length - 1];
if (mapping !== this._mapping) { if (mapping !== this._mapping) {
if (cc != null) {
cc.exitDetails = ' \u2022 skipped';
if (scope != null) {
scope.exitDetails = ' \u2022 skipped';
} }
return; return;
@ -183,11 +183,11 @@ export class Keyboard implements Disposable {
@log() @log()
async execute(key: Keys): Promise<void> { async execute(key: Keys): Promise<void> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (!mappings.length) { if (!mappings.length) {
if (cc != null) {
cc.exitDetails = ' \u2022 skipped, no mappings';
if (scope != null) {
scope.exitDetails = ' \u2022 skipped, no mappings';
} }
return; return;
@ -201,8 +201,8 @@ export class Keyboard implements Disposable {
command = await command(); command = await command();
} }
if (typeof command?.onDidPressKey !== 'function') { if (typeof command?.onDidPressKey !== 'function') {
if (cc != null) {
cc.exitDetails = ' \u2022 skipped, no callback';
if (scope != null) {
scope.exitDetails = ' \u2022 skipped, no callback';
} }
return; return;
@ -210,7 +210,7 @@ export class Keyboard implements Disposable {
void (await command.onDidPressKey(key)); void (await command.onDidPressKey(key));
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
} }
} }
} }

+ 29
- 46
src/logger.ts View File

@ -1,6 +1,5 @@
import { ExtensionContext, ExtensionMode, OutputChannel, Uri, window } from 'vscode'; import { ExtensionContext, ExtensionMode, OutputChannel, Uri, window } from 'vscode';
import { OutputLevel } from './configuration'; import { OutputLevel } from './configuration';
import { getCorrelationContext, getNextCorrelationId } from './system/decorators/log';
const emptyStr = ''; const emptyStr = '';
const outputChannelName = 'GitLens'; const outputChannelName = 'GitLens';
@ -17,6 +16,12 @@ export const enum LogLevel {
Debug = 'debug', Debug = 'debug',
} }
export interface LogScope {
readonly scopeId?: number;
readonly prefix: string;
exitDetails?: string;
}
const enum OrderedLevel { const enum OrderedLevel {
Off = 0, Off = 0,
Error = 1, Error = 1,
@ -25,12 +30,6 @@ const enum OrderedLevel {
Debug = 4, Debug = 4,
} }
export interface LogCorrelationContext {
readonly correlationId?: number;
readonly prefix: string;
exitDetails?: string;
}
export class Logger { export class Logger {
static readonly slowCallWarningThreshold = 500; static readonly slowCallWarningThreshold = 500;
@ -70,18 +69,18 @@ export class Logger {
} }
static debug(message: string, ...params: any[]): void; static debug(message: string, ...params: any[]): void;
static debug(context: LogCorrelationContext | undefined, message: string, ...params: any[]): void;
static debug(contextOrMessage: LogCorrelationContext | string | undefined, ...params: any[]): void {
static debug(scope: LogScope | undefined, message: string, ...params: any[]): void;
static debug(scopeOrMessage: LogScope | string | undefined, ...params: any[]): void {
if (this.level < OrderedLevel.Debug && !this.isDebugging) return; if (this.level < OrderedLevel.Debug && !this.isDebugging) return;
let message; let message;
if (typeof contextOrMessage === 'string') {
message = contextOrMessage;
if (typeof scopeOrMessage === 'string') {
message = scopeOrMessage;
} else { } else {
message = params.shift(); message = params.shift();
if (contextOrMessage != null) {
message = `${contextOrMessage.prefix} ${message ?? emptyStr}`;
if (scopeOrMessage != null) {
message = `${scopeOrMessage.prefix} ${message ?? emptyStr}`;
} }
} }
@ -94,19 +93,15 @@ export class Logger {
} }
static error(ex: Error | unknown, message?: string, ...params: any[]): void; static error(ex: Error | unknown, message?: string, ...params: any[]): void;
static error(ex: Error | unknown, context?: LogCorrelationContext, message?: string, ...params: any[]): void;
static error(
ex: Error | unknown,
contextOrMessage: LogCorrelationContext | string | undefined,
...params: any[]
): void {
static error(ex: Error | unknown, scope?: LogScope, message?: string, ...params: any[]): void;
static error(ex: Error | unknown, scopeOrMessage: LogScope | string | undefined, ...params: any[]): void {
if (this.level < OrderedLevel.Error && !this.isDebugging) return; if (this.level < OrderedLevel.Error && !this.isDebugging) return;
let message; let message;
if (contextOrMessage == null || typeof contextOrMessage === 'string') {
message = contextOrMessage;
if (scopeOrMessage == null || typeof scopeOrMessage === 'string') {
message = scopeOrMessage;
} else { } else {
message = `${contextOrMessage.prefix} ${params.shift() ?? emptyStr}`;
message = `${scopeOrMessage.prefix} ${params.shift() ?? emptyStr}`;
} }
if (message == null) { if (message == null) {
@ -130,18 +125,18 @@ export class Logger {
} }
static log(message: string, ...params: any[]): void; static log(message: string, ...params: any[]): void;
static log(context: LogCorrelationContext | undefined, message: string, ...params: any[]): void;
static log(contextOrMessage: LogCorrelationContext | string | undefined, ...params: any[]): void {
static log(scope: LogScope | undefined, message: string, ...params: any[]): void;
static log(scopeOrMessage: LogScope | string | undefined, ...params: any[]): void {
if (this.level < OrderedLevel.Info && !this.isDebugging) return; if (this.level < OrderedLevel.Info && !this.isDebugging) return;
let message; let message;
if (typeof contextOrMessage === 'string') {
message = contextOrMessage;
if (typeof scopeOrMessage === 'string') {
message = scopeOrMessage;
} else { } else {
message = params.shift(); message = params.shift();
if (contextOrMessage != null) {
message = `${contextOrMessage.prefix} ${message ?? emptyStr}`;
if (scopeOrMessage != null) {
message = `${scopeOrMessage.prefix} ${message ?? emptyStr}`;
} }
} }
@ -154,18 +149,18 @@ export class Logger {
} }
static warn(message: string, ...params: any[]): void; static warn(message: string, ...params: any[]): void;
static warn(context: LogCorrelationContext | undefined, message: string, ...params: any[]): void;
static warn(contextOrMessage: LogCorrelationContext | string | undefined, ...params: any[]): void {
static warn(scope: LogScope | undefined, message: string, ...params: any[]): void;
static warn(scopeOrMessage: LogScope | string | undefined, ...params: any[]): void {
if (this.level < OrderedLevel.Warn && !this.isDebugging) return; if (this.level < OrderedLevel.Warn && !this.isDebugging) return;
let message; let message;
if (typeof contextOrMessage === 'string') {
message = contextOrMessage;
if (typeof scopeOrMessage === 'string') {
message = scopeOrMessage;
} else { } else {
message = params.shift(); message = params.shift();
if (contextOrMessage != null) {
message = `${contextOrMessage.prefix} ${message ?? emptyStr}`;
if (scopeOrMessage != null) {
message = `${scopeOrMessage.prefix} ${message ?? emptyStr}`;
} }
} }
@ -177,18 +172,6 @@ export class Logger {
this.output.appendLine(`${this.timestamp} ${message ?? emptyStr}${this.toLoggableParams(false, params)}`); this.output.appendLine(`${this.timestamp} ${message ?? emptyStr}${this.toLoggableParams(false, params)}`);
} }
static getCorrelationContext() {
return getCorrelationContext();
}
static getNewCorrelationContext(prefix: string): LogCorrelationContext {
const correlationId = getNextCorrelationId();
return {
correlationId: correlationId,
prefix: `[${String(correlationId).padStart(5)}] ${prefix}`,
};
}
static showOutputChannel(): void { static showOutputChannel(): void {
this.output?.show(); this.output?.show();
} }

+ 84
- 88
src/plus/github/github.ts View File

@ -24,9 +24,9 @@ import { GitRevision } from '../../git/models/reference';
import type { GitUser } from '../../git/models/user'; import type { GitUser } from '../../git/models/user';
import { getGitHubNoReplyAddressParts } from '../../git/remotes/github'; import { getGitHubNoReplyAddressParts } from '../../git/remotes/github';
import type { RichRemoteProvider } from '../../git/remotes/provider'; import type { RichRemoteProvider } from '../../git/remotes/provider';
import { LogCorrelationContext, Logger, LogLevel } from '../../logger';
import { Logger, LogLevel, LogScope } from '../../logger';
import { Messages } from '../../messages'; import { Messages } from '../../messages';
import { debug } from '../../system/decorators/log';
import { debug, getLogScope } from '../../system/decorators/log';
import { Stopwatch } from '../../system/stopwatch'; import { Stopwatch } from '../../system/stopwatch';
import { base64 } from '../../system/string'; import { base64 } from '../../system/string';
import { fromString, satisfies, Version } from '../../system/version'; import { fromString, satisfies, Version } from '../../system/version';
@ -103,7 +103,7 @@ export class GitHubApi implements Disposable {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<Account | undefined> { ): Promise<Account | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -153,7 +153,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
ref: ref, ref: ref,
}, },
cc,
scope,
); );
const author = rsp?.repository?.object?.author; const author = rsp?.repository?.object?.author;
@ -180,7 +180,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -196,7 +196,7 @@ export class GitHubApi implements Disposable {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<Account | undefined> { ): Promise<Account | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
search: search:
@ -240,7 +240,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
emailQuery: `in:email ${email}`, emailQuery: `in:email ${email}`,
}, },
cc,
scope,
); );
const author = rsp?.search?.nodes?.[0]; const author = rsp?.search?.nodes?.[0];
@ -267,7 +267,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -281,7 +281,7 @@ export class GitHubApi implements Disposable {
baseUrl?: string; baseUrl?: string;
}, },
): Promise<DefaultBranch | undefined> { ): Promise<DefaultBranch | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -313,7 +313,7 @@ export class GitHubApi implements Disposable {
owner: owner, owner: owner,
repo: repo, repo: repo,
}, },
cc,
scope,
); );
const defaultBranch = rsp?.repository?.defaultBranchRef?.name ?? undefined; const defaultBranch = rsp?.repository?.defaultBranchRef?.name ?? undefined;
@ -326,7 +326,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -341,7 +341,7 @@ export class GitHubApi implements Disposable {
baseUrl?: string; baseUrl?: string;
}, },
): Promise<IssueOrPullRequest | undefined> { ): Promise<IssueOrPullRequest | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository?: { issueOrPullRequest?: GitHubIssueOrPullRequest }; repository?: { issueOrPullRequest?: GitHubIssueOrPullRequest };
@ -384,7 +384,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
number: number, number: number,
}, },
cc,
scope,
); );
const issue = rsp?.repository?.issueOrPullRequest; const issue = rsp?.repository?.issueOrPullRequest;
@ -403,7 +403,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -420,7 +420,7 @@ export class GitHubApi implements Disposable {
include?: GitHubPullRequestState[]; include?: GitHubPullRequestState[];
}, },
): Promise<PullRequest | undefined> { ): Promise<PullRequest | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -488,7 +488,7 @@ export class GitHubApi implements Disposable {
// Since GitHub sort doesn't seem to really work, look for a max of 10 PRs and then sort them ourselves // Since GitHub sort doesn't seem to really work, look for a max of 10 PRs and then sort them ourselves
limit: 10, limit: 10,
}, },
cc,
scope,
); );
// If the pr is not from a fork, keep it e.g. show root pr's on forks, otherwise, ensure the repo owners match // If the pr is not from a fork, keep it e.g. show root pr's on forks, otherwise, ensure the repo owners match
@ -510,7 +510,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -526,7 +526,7 @@ export class GitHubApi implements Disposable {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<PullRequest | undefined> { ): Promise<PullRequest | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -588,7 +588,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
ref: ref, ref: ref,
}, },
cc,
scope,
); );
// If the pr is not from a fork, keep it e.g. show root pr's on forks, otherwise, ensure the repo owners match // If the pr is not from a fork, keep it e.g. show root pr's on forks, otherwise, ensure the repo owners match
@ -610,13 +610,13 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@debug<GitHubApi['getBlame']>({ args: { 0: '<token>' } }) @debug<GitHubApi['getBlame']>({ args: { 0: '<token>' } })
async getBlame(token: string, owner: string, repo: string, ref: string, path: string): Promise<GitHubBlame> { async getBlame(token: string, owner: string, repo: string, ref: string, path: string): Promise<GitHubBlame> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
viewer: { name: string }; viewer: { name: string };
@ -682,7 +682,7 @@ export class GitHubApi implements Disposable {
ref: ref, ref: ref,
path: path, path: path,
}, },
cc,
scope,
); );
if (rsp == null) return emptyBlameResult; if (rsp == null) return emptyBlameResult;
@ -693,7 +693,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return emptyBlameResult; if (ex instanceof ProviderRequestNotFoundError) return emptyBlameResult;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -704,7 +704,7 @@ export class GitHubApi implements Disposable {
repo: string, repo: string,
options?: { query?: string; cursor?: string; limit?: number }, options?: { query?: string; cursor?: string; limit?: number },
): Promise<PagedResult<GitHubBranch>> { ): Promise<PagedResult<GitHubBranch>> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -761,7 +761,7 @@ export class GitHubApi implements Disposable {
cursor: options?.cursor, cursor: options?.cursor,
limit: Math.min(100, options?.limit ?? 100), limit: Math.min(100, options?.limit ?? 100),
}, },
cc,
scope,
); );
if (rsp == null) return emptyPagedResult; if (rsp == null) return emptyPagedResult;
@ -778,7 +778,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult; if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -789,7 +789,7 @@ export class GitHubApi implements Disposable {
repo: string, repo: string,
ref: string, ref: string,
): Promise<(GitHubCommit & { viewer?: string }) | undefined> { ): Promise<(GitHubCommit & { viewer?: string }) | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const rsp = await this.request( const rsp = await this.request(
@ -801,7 +801,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
ref: ref, ref: ref,
}, },
cc,
scope,
); );
const result = rsp?.data; const result = rsp?.data;
@ -831,7 +831,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
// const results = await this.getCommits(token, owner, repo, ref, { limit: 1 }); // const results = await this.getCommits(token, owner, repo, ref, { limit: 1 });
@ -860,7 +860,7 @@ export class GitHubApi implements Disposable {
@debug<GitHubApi['getCommitBranches']>({ args: { 0: '<token>' } }) @debug<GitHubApi['getCommitBranches']>({ args: { 0: '<token>' } })
async getCommitBranches(token: string, owner: string, repo: string, ref: string, date: Date): Promise<string[]> { async getCommitBranches(token: string, owner: string, repo: string, ref: string, date: Date): Promise<string[]> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: { repository: {
@ -909,7 +909,7 @@ export class GitHubApi implements Disposable {
since: date.toISOString(), since: date.toISOString(),
until: date.toISOString(), until: date.toISOString(),
}, },
cc,
scope,
); );
const nodes = rsp?.repository?.refs?.nodes; const nodes = rsp?.repository?.refs?.nodes;
@ -930,13 +930,13 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return []; if (ex instanceof ProviderRequestNotFoundError) return [];
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@debug<GitHubApi['getCommitCount']>({ args: { 0: '<token>' } }) @debug<GitHubApi['getCommitCount']>({ args: { 0: '<token>' } })
async getCommitCount(token: string, owner: string, repo: string, ref: string): Promise<number | undefined> { async getCommitCount(token: string, owner: string, repo: string, ref: string): Promise<number | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: { repository: {
@ -976,7 +976,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
ref: ref, ref: ref,
}, },
cc,
scope,
); );
const count = rsp?.repository?.ref?.target.history.totalCount; const count = rsp?.repository?.ref?.target.history.totalCount;
@ -984,7 +984,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -997,7 +997,7 @@ export class GitHubApi implements Disposable {
ref: string, ref: string,
date: Date, date: Date,
): Promise<string[]> { ): Promise<string[]> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: { repository: {
@ -1041,7 +1041,7 @@ export class GitHubApi implements Disposable {
since: date.toISOString(), since: date.toISOString(),
until: date.toISOString(), until: date.toISOString(),
}, },
cc,
scope,
); );
const nodes = rsp?.repository?.ref.target.history.nodes; const nodes = rsp?.repository?.ref.target.history.nodes;
@ -1060,7 +1060,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return []; if (ex instanceof ProviderRequestNotFoundError) return [];
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1081,7 +1081,7 @@ export class GitHubApi implements Disposable {
until?: string | Date; until?: string | Date;
}, },
): Promise<PagedResult<GitHubCommit> & { viewer?: string }> { ): Promise<PagedResult<GitHubCommit> & { viewer?: string }> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (options?.limit === 1 && options?.path == null) { if (options?.limit === 1 && options?.path == null) {
return this.getCommitsCoreSingle(token, owner, repo, ref); return this.getCommitsCoreSingle(token, owner, repo, ref);
@ -1186,7 +1186,7 @@ export class GitHubApi implements Disposable {
since: typeof options?.since === 'string' ? options?.since : options?.since?.toISOString(), since: typeof options?.since === 'string' ? options?.since : options?.since?.toISOString(),
until: typeof options?.until === 'string' ? options?.until : options?.until?.toISOString(), until: typeof options?.until === 'string' ? options?.until : options?.until?.toISOString(),
}, },
cc,
scope,
); );
const history = rsp?.repository?.object?.history; const history = rsp?.repository?.object?.history;
if (history == null) return emptyPagedResult; if (history == null) return emptyPagedResult;
@ -1205,7 +1205,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult; if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1215,7 +1215,7 @@ export class GitHubApi implements Disposable {
repo: string, repo: string,
ref: string, ref: string,
): Promise<PagedResult<GitHubCommit> & { viewer?: string }> { ): Promise<PagedResult<GitHubCommit> & { viewer?: string }> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
viewer: { name: string }; viewer: { name: string };
@ -1263,7 +1263,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
ref: ref, ref: ref,
}, },
cc,
scope,
); );
if (rsp == null) return emptyPagedResult; if (rsp == null) return emptyPagedResult;
@ -1272,7 +1272,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult; if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1292,7 +1292,7 @@ export class GitHubApi implements Disposable {
until?: string; until?: string;
}, },
): Promise<GitHubPagedResult<GitHubCommitRef> | undefined> { ): Promise<GitHubPagedResult<GitHubCommitRef> | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -1354,7 +1354,7 @@ export class GitHubApi implements Disposable {
since: options?.since, since: options?.since,
until: options?.until, until: options?.until,
}, },
cc,
scope,
); );
const history = rsp?.repository?.object?.history; const history = rsp?.repository?.object?.history;
if (history == null) return undefined; if (history == null) return undefined;
@ -1367,7 +1367,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1412,7 +1412,7 @@ export class GitHubApi implements Disposable {
} }
private async getCommitDate(token: string, owner: string, repo: string, sha: string): Promise<string | undefined> { private async getCommitDate(token: string, owner: string, repo: string, sha: string): Promise<string | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -1445,20 +1445,20 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
sha: sha, sha: sha,
}, },
cc,
scope,
); );
const date = rsp?.repository?.object?.committer.date; const date = rsp?.repository?.object?.committer.date;
return date; return date;
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@debug<GitHubApi['getContributors']>({ args: { 0: '<token>' } }) @debug<GitHubApi['getContributors']>({ args: { 0: '<token>' } })
async getContributors(token: string, owner: string, repo: string): Promise<GitHubContributor[]> { async getContributors(token: string, owner: string, repo: string): Promise<GitHubContributor[]> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
// TODO@eamodio implement pagination // TODO@eamodio implement pagination
@ -1472,7 +1472,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
per_page: 100, per_page: 100,
}, },
cc,
scope,
); );
const result = rsp?.data; const result = rsp?.data;
@ -1482,13 +1482,13 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return []; if (ex instanceof ProviderRequestNotFoundError) return [];
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@debug<GitHubApi['getDefaultBranchName']>({ args: { 0: '<token>' } }) @debug<GitHubApi['getDefaultBranchName']>({ args: { 0: '<token>' } })
async getDefaultBranchName(token: string, owner: string, repo: string): Promise<string | undefined> { async getDefaultBranchName(token: string, owner: string, repo: string): Promise<string | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -1519,7 +1519,7 @@ export class GitHubApi implements Disposable {
owner: owner, owner: owner,
repo: repo, repo: repo,
}, },
cc,
scope,
); );
if (rsp == null) return undefined; if (rsp == null) return undefined;
@ -1527,13 +1527,13 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@debug<GitHubApi['getCurrentUser']>({ args: { 0: '<token>' } }) @debug<GitHubApi['getCurrentUser']>({ args: { 0: '<token>' } })
async getCurrentUser(token: string, owner: string, repo: string): Promise<GitUser | undefined> { async getCurrentUser(token: string, owner: string, repo: string): Promise<GitUser | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
viewer: { viewer: {
@ -1562,7 +1562,7 @@ export class GitHubApi implements Disposable {
owner: owner, owner: owner,
repo: repo, repo: repo,
}, },
cc,
scope,
); );
if (rsp == null) return undefined; if (rsp == null) return undefined;
@ -1575,7 +1575,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1585,7 +1585,7 @@ export class GitHubApi implements Disposable {
owner: string, owner: string,
repo: string, repo: string,
): Promise<RepositoryVisibility | undefined> { ): Promise<RepositoryVisibility | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -1614,7 +1614,7 @@ export class GitHubApi implements Disposable {
owner: owner, owner: owner,
repo: repo, repo: repo,
}, },
cc,
scope,
); );
if (rsp?.repository?.visibility == null) return undefined; if (rsp?.repository?.visibility == null) return undefined;
@ -1622,7 +1622,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1633,7 +1633,7 @@ export class GitHubApi implements Disposable {
repo: string, repo: string,
options?: { query?: string; cursor?: string; limit?: number }, options?: { query?: string; cursor?: string; limit?: number },
): Promise<PagedResult<GitHubTag>> { ): Promise<PagedResult<GitHubTag>> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
repository: repository:
@ -1695,7 +1695,7 @@ export class GitHubApi implements Disposable {
cursor: options?.cursor, cursor: options?.cursor,
limit: Math.min(100, options?.limit ?? 100), limit: Math.min(100, options?.limit ?? 100),
}, },
cc,
scope,
); );
if (rsp == null) return emptyPagedResult; if (rsp == null) return emptyPagedResult;
@ -1712,7 +1712,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult; if (ex instanceof ProviderRequestNotFoundError) return emptyPagedResult;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1724,7 +1724,7 @@ export class GitHubApi implements Disposable {
ref: string, ref: string,
path?: string, path?: string,
): Promise<string | undefined> { ): Promise<string | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
if (!path) { if (!path) {
@ -1753,7 +1753,7 @@ export class GitHubApi implements Disposable {
repo: repo, repo: repo,
ref: ref, ref: ref,
}, },
cc,
scope,
); );
return rsp?.repository?.object?.oid ?? undefined; return rsp?.repository?.object?.oid ?? undefined;
} }
@ -1798,13 +1798,13 @@ export class GitHubApi implements Disposable {
ref: ref, ref: ref,
path: path, path: path,
}, },
cc,
scope,
); );
return rsp?.repository?.object?.history.nodes?.[0]?.oid ?? undefined; return rsp?.repository?.object?.history.nodes?.[0]?.oid ?? undefined;
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1819,7 +1819,7 @@ export class GitHubApi implements Disposable {
sort?: 'author-date' | 'committer-date' | undefined; sort?: 'author-date' | 'committer-date' | undefined;
}, },
): Promise<GitHubPagedResult<GitHubCommit> | undefined> { ): Promise<GitHubPagedResult<GitHubCommit> | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const limit = Math.min(100, options?.limit ?? 100); const limit = Math.min(100, options?.limit ?? 100);
@ -1850,7 +1850,7 @@ export class GitHubApi implements Disposable {
per_page: pageSize, per_page: pageSize,
page: page, page: page,
}, },
cc,
scope,
); );
const data = rsp?.data; const data = rsp?.data;
@ -1889,7 +1889,7 @@ export class GitHubApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, undefined, cc);
throw this.handleException(ex, undefined, scope);
} }
} }
@ -1905,10 +1905,10 @@ export class GitHubApi implements Disposable {
if (version != null) return version; if (version != null) return version;
if (version === null) return undefined; if (version === null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const rsp = await this.request(provider, token, 'GET /meta', options, cc);
const rsp = await this.request(provider, token, 'GET /meta', options, scope);
const v = (rsp?.data as any)?.installed_version as string | null | undefined; const v = (rsp?.data as any)?.installed_version as string | null | undefined;
version = v ? fromString(v) : null; version = v ? fromString(v) : null;
} catch (ex) { } catch (ex) {
@ -1975,7 +1975,7 @@ export class GitHubApi implements Disposable {
token: string, token: string,
query: string, query: string,
variables: { [key: string]: any }, variables: { [key: string]: any },
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<T | undefined> { ): Promise<T | undefined> {
try { try {
return await wrapForForcedInsecureSSL(provider?.getIgnoreSSLErrors() ?? false, () => return await wrapForForcedInsecureSSL(provider?.getIgnoreSSLErrors() ?? false, () =>
@ -2007,7 +2007,7 @@ export class GitHubApi implements Disposable {
void window.showErrorMessage(`GitHub request failed: ${ex.errors?.[0]?.message ?? ex.message}`); void window.showErrorMessage(`GitHub request failed: ${ex.errors?.[0]?.message ?? ex.message}`);
} }
} else if (ex instanceof RequestError) { } else if (ex instanceof RequestError) {
this.handleRequestError(provider, token, ex, cc);
this.handleRequestError(provider, token, ex, scope);
} else if (Logger.isDebugging) { } else if (Logger.isDebugging) {
void window.showErrorMessage(`GitHub request failed: ${ex.message}`); void window.showErrorMessage(`GitHub request failed: ${ex.message}`);
} }
@ -2023,7 +2023,7 @@ export class GitHubApi implements Disposable {
options: options:
| (R extends keyof Endpoints ? Endpoints[R]['parameters'] & RequestParameters : RequestParameters) | (R extends keyof Endpoints ? Endpoints[R]['parameters'] & RequestParameters : RequestParameters)
| undefined, | undefined,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<R extends keyof Endpoints ? Endpoints[R]['response'] : OctokitResponse<unknown>> { ): Promise<R extends keyof Endpoints ? Endpoints[R]['response'] : OctokitResponse<unknown>> {
try { try {
return (await wrapForForcedInsecureSSL(provider?.getIgnoreSSLErrors() ?? false, () => return (await wrapForForcedInsecureSSL(provider?.getIgnoreSSLErrors() ?? false, () =>
@ -2031,7 +2031,7 @@ export class GitHubApi implements Disposable {
)) as any; )) as any;
} catch (ex) { } catch (ex) {
if (ex instanceof RequestError) { if (ex instanceof RequestError) {
this.handleRequestError(provider, token, ex, cc);
this.handleRequestError(provider, token, ex, scope);
} else if (Logger.isDebugging) { } else if (Logger.isDebugging) {
void window.showErrorMessage(`GitHub request failed: ${ex.message}`); void window.showErrorMessage(`GitHub request failed: ${ex.message}`);
} }
@ -2044,7 +2044,7 @@ export class GitHubApi implements Disposable {
provider: RichRemoteProvider | undefined, provider: RichRemoteProvider | undefined,
token: string, token: string,
ex: RequestError, ex: RequestError,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): void { ): void {
switch (ex.status) { switch (ex.status) {
case 404: // Not found case 404: // Not found
@ -2070,7 +2070,7 @@ export class GitHubApi implements Disposable {
} }
throw new AuthenticationError('github', AuthenticationErrorReason.Forbidden, ex); throw new AuthenticationError('github', AuthenticationErrorReason.Forbidden, ex);
case 500: // Internal Server Error case 500: // Internal Server Error
Logger.error(ex, cc);
Logger.error(ex, scope);
if (ex.response != null) { if (ex.response != null) {
provider?.trackRequestException(); provider?.trackRequestException();
void Messages.showIntegrationRequestFailed500WarningMessage( void Messages.showIntegrationRequestFailed500WarningMessage(
@ -2083,7 +2083,7 @@ export class GitHubApi implements Disposable {
} }
return; return;
case 502: // Bad Gateway case 502: // Bad Gateway
Logger.error(ex, cc);
Logger.error(ex, scope);
// GitHub seems to return this status code for timeouts // GitHub seems to return this status code for timeouts
if (ex.message.includes('timeout')) { if (ex.message.includes('timeout')) {
provider?.trackRequestException(); provider?.trackRequestException();
@ -2096,7 +2096,7 @@ export class GitHubApi implements Disposable {
break; break;
} }
Logger.error(ex, cc);
Logger.error(ex, scope);
if (Logger.isDebugging) { if (Logger.isDebugging) {
void window.showErrorMessage( void window.showErrorMessage(
`GitHub request failed: ${(ex.response as any)?.errors?.[0]?.message ?? ex.message}`, `GitHub request failed: ${(ex.response as any)?.errors?.[0]?.message ?? ex.message}`,
@ -2104,12 +2104,8 @@ export class GitHubApi implements Disposable {
} }
} }
private handleException(
ex: Error,
provider: RichRemoteProvider | undefined,
cc: LogCorrelationContext | undefined,
): Error {
Logger.error(ex, cc);
private handleException(ex: Error, provider: RichRemoteProvider | undefined, scope: LogScope | undefined): Error {
Logger.error(ex, scope);
// debugger; // debugger;
if (ex instanceof AuthenticationError) { if (ex instanceof AuthenticationError) {

+ 51
- 51
src/plus/github/githubGitProvider.ts View File

@ -60,9 +60,9 @@ import { GitUser, isUserMatch } from '../../git/models/user';
import { RemoteProviderFactory, RemoteProviders } from '../../git/remotes/factory'; import { RemoteProviderFactory, RemoteProviders } from '../../git/remotes/factory';
import type { RemoteProvider, RichRemoteProvider } from '../../git/remotes/provider'; import type { RemoteProvider, RichRemoteProvider } from '../../git/remotes/provider';
import { SearchPattern } from '../../git/search'; import { SearchPattern } from '../../git/search';
import { LogCorrelationContext, Logger } from '../../logger';
import { Logger, LogScope } from '../../logger';
import { gate } from '../../system/decorators/gate'; import { gate } from '../../system/decorators/gate';
import { debug, log } from '../../system/decorators/log';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { filterMap, some } from '../../system/iterable'; import { filterMap, some } from '../../system/iterable';
import { isAbsolute, isFolderGlob, maybeUri, normalizePath, relative } from '../../system/path'; import { isAbsolute, isFolderGlob, maybeUri, normalizePath, relative } from '../../system/path';
import { getSettledValue } from '../../system/promise'; import { getSettledValue } from '../../system/promise';
@ -364,7 +364,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
@gate() @gate()
@debug() @debug()
async findRepositoryUri(uri: Uri, _isDirectory?: boolean): Promise<Uri | undefined> { async findRepositoryUri(uri: Uri, _isDirectory?: boolean): Promise<Uri | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const remotehub = await this.ensureRemoteHubApi(); const remotehub = await this.ensureRemoteHubApi();
@ -374,7 +374,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
if (!(ex instanceof ExtensionNotFoundError)) { if (!(ex instanceof ExtensionNotFoundError)) {
debugger; debugger;
} }
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
@ -391,7 +391,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
@gate<GitHubGitProvider['getBlame']>((u, d) => `${u.toString()}|${d?.isDirty}`) @gate<GitHubGitProvider['getBlame']>((u, d) => `${u.toString()}|${d?.isDirty}`)
@log<GitHubGitProvider['getBlame']>({ args: { 1: d => d?.isDirty } }) @log<GitHubGitProvider['getBlame']>({ args: { 1: d => d?.isDirty } })
async getBlame(uri: GitUri, document?: TextDocument | undefined): Promise<GitBlame | undefined> { async getBlame(uri: GitUri, document?: TextDocument | undefined): Promise<GitBlame | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
// TODO@eamodio we need to figure out when to do this, since dirty isn't enough, we need to know if there are any uncommitted changes // TODO@eamodio we need to figure out when to do this, since dirty isn't enough, we need to know if there are any uncommitted changes
if (document?.isDirty) return undefined; //this.getBlameContents(uri, document.getText()); if (document?.isDirty) return undefined; //this.getBlameContents(uri, document.getText());
@ -405,21 +405,21 @@ export class GitHubGitProvider implements GitProvider, Disposable {
if (doc.state != null) { if (doc.state != null) {
const cachedBlame = doc.state.getBlame(key); const cachedBlame = doc.state.getBlame(key);
if (cachedBlame != null) { if (cachedBlame != null) {
Logger.debug(cc, `Cache hit: '${key}'`);
Logger.debug(scope, `Cache hit: '${key}'`);
return cachedBlame.item; return cachedBlame.item;
} }
} }
Logger.debug(cc, `Cache miss: '${key}'`);
Logger.debug(scope, `Cache miss: '${key}'`);
if (doc.state == null) { if (doc.state == null) {
doc.state = new GitDocumentState(); doc.state = new GitDocumentState();
} }
const promise = this.getBlameCore(uri, doc, key, cc);
const promise = this.getBlameCore(uri, doc, key, scope);
if (doc.state != null) { if (doc.state != null) {
Logger.debug(cc, `Cache add: '${key}'`);
Logger.debug(scope, `Cache add: '${key}'`);
const value: CachedBlame = { const value: CachedBlame = {
item: promise as Promise<GitBlame>, item: promise as Promise<GitBlame>,
@ -434,7 +434,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
uri: GitUri, uri: GitUri,
document: TrackedDocument<GitDocumentState>, document: TrackedDocument<GitDocumentState>,
key: string, key: string,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<GitBlame | undefined> { ): Promise<GitBlame | undefined> {
try { try {
const context = await this.ensureRepositoryContext(uri.repoPath!); const context = await this.ensureRepositoryContext(uri.repoPath!);
@ -530,7 +530,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
// Trap and cache expected blame errors // Trap and cache expected blame errors
if (document.state != null && !/No provider registered with/.test(String(ex))) { if (document.state != null && !/No provider registered with/.test(String(ex))) {
const msg = ex?.toString() ?? ''; const msg = ex?.toString() ?? '';
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
Logger.debug(scope, `Cache replace (with empty promise): '${key}'`);
const value: CachedBlame = { const value: CachedBlame = {
item: emptyPromise as Promise<GitBlame>, item: emptyPromise as Promise<GitBlame>,
@ -563,7 +563,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
document?: TextDocument | undefined, document?: TextDocument | undefined,
options?: { forceSingleLine?: boolean }, options?: { forceSingleLine?: boolean },
): Promise<GitBlameLine | undefined> { ): Promise<GitBlameLine | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
// TODO@eamodio we need to figure out when to do this, since dirty isn't enough, we need to know if there are any uncommitted changes // TODO@eamodio we need to figure out when to do this, since dirty isn't enough, we need to know if there are any uncommitted changes
if (document?.isDirty) return undefined; //this.getBlameForLineContents(uri, editorLine, document.getText(), options); if (document?.isDirty) return undefined; //this.getBlameForLineContents(uri, editorLine, document.getText(), options);
@ -648,7 +648,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
}; };
} catch (ex) { } catch (ex) {
debugger; debugger;
Logger.error(cc, ex);
Logger.error(scope, ex);
return undefined; return undefined;
} }
} }
@ -747,7 +747,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<PagedResult<GitBranch>> { ): Promise<PagedResult<GitBranch>> {
if (repoPath == null) return emptyPagedResult; if (repoPath == null) return emptyPagedResult;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
let branchesPromise = options?.cursor ? undefined : this._branchesCache.get(repoPath); let branchesPromise = options?.cursor ? undefined : this._branchesCache.get(repoPath);
if (branchesPromise == null) { if (branchesPromise == null) {
@ -793,7 +793,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
cursor = result.paging.cursor; cursor = result.paging.cursor;
} }
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
this._branchesCache.delete(repoPath!); this._branchesCache.delete(repoPath!);
@ -843,7 +843,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
async getCommit(repoPath: string, ref: string): Promise<GitCommit | undefined> { async getCommit(repoPath: string, ref: string): Promise<GitCommit | undefined> {
if (repoPath == null) return undefined; if (repoPath == null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); const { metadata, github, session } = await this.ensureRepositoryContext(repoPath);
@ -888,7 +888,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
[], [],
); );
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return undefined; return undefined;
} }
@ -902,7 +902,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<string[]> { ): Promise<string[]> {
if (repoPath == null || options?.commitDate == null) return []; if (repoPath == null || options?.commitDate == null) return [];
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); const { metadata, github, session } = await this.ensureRepositoryContext(repoPath);
@ -930,7 +930,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
return branches; return branches;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return []; return [];
} }
@ -940,7 +940,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
async getCommitCount(repoPath: string, ref: string): Promise<number | undefined> { async getCommitCount(repoPath: string, ref: string): Promise<number | undefined> {
if (repoPath == null) return undefined; if (repoPath == null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); const { metadata, github, session } = await this.ensureRepositoryContext(repoPath);
@ -954,7 +954,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
return count; return count;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return undefined; return undefined;
} }
@ -968,7 +968,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<GitCommit | undefined> { ): Promise<GitCommit | undefined> {
if (repoPath == null) return undefined; if (repoPath == null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const { metadata, github, remotehub, session } = await this.ensureRepositoryContext(repoPath); const { metadata, github, remotehub, session } = await this.ensureRepositoryContext(repoPath);
@ -1025,7 +1025,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
[], [],
); );
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return undefined; return undefined;
} }
@ -1044,7 +1044,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<GitContributor[]> { ): Promise<GitContributor[]> {
if (repoPath == null) return []; if (repoPath == null) return [];
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); const { metadata, github, session } = await this.ensureRepositoryContext(repoPath);
@ -1074,7 +1074,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
return contributors; return contributors;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return []; return [];
} }
@ -1085,7 +1085,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
async getCurrentUser(repoPath: string): Promise<GitUser | undefined> { async getCurrentUser(repoPath: string): Promise<GitUser | undefined> {
if (!repoPath) return undefined; if (!repoPath) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const repo = this._repoInfoCache.get(repoPath); const repo = this._repoInfoCache.get(repoPath);
@ -1101,7 +1101,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
this._repoInfoCache.set(repoPath, { ...repo, user: user ?? null }); this._repoInfoCache.set(repoPath, { ...repo, user: user ?? null });
return user; return user;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
// Mark it so we won't bother trying again // Mark it so we won't bother trying again
@ -1114,13 +1114,13 @@ export class GitHubGitProvider implements GitProvider, Disposable {
async getDefaultBranchName(repoPath: string | undefined, _remote?: string): Promise<string | undefined> { async getDefaultBranchName(repoPath: string | undefined, _remote?: string): Promise<string | undefined> {
if (repoPath == null) return undefined; if (repoPath == null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const { metadata, github, session } = await this.ensureRepositoryContext(repoPath); const { metadata, github, session } = await this.ensureRepositoryContext(repoPath);
return await github.getDefaultBranchName(session.accessToken, metadata.repo.owner, metadata.repo.name); return await github.getDefaultBranchName(session.accessToken, metadata.repo.owner, metadata.repo.name);
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return undefined; return undefined;
} }
@ -1190,7 +1190,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<GitLog | undefined> { ): Promise<GitLog | undefined> {
if (repoPath == null) return undefined; if (repoPath == null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const limit = this.getPagingLimit(options?.limit); const limit = this.getPagingLimit(options?.limit);
@ -1274,7 +1274,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
return log; return log;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return undefined; return undefined;
} }
@ -1376,7 +1376,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<GitLog | undefined> { ): Promise<GitLog | undefined> {
if (repoPath == null) return undefined; if (repoPath == null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const operations = SearchPattern.parseSearchOperations(search.pattern); const operations = SearchPattern.parseSearchOperations(search.pattern);
@ -1514,7 +1514,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
return log; return log;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
return undefined; return undefined;
} }
@ -1577,7 +1577,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<GitLog | undefined> { ): Promise<GitLog | undefined> {
if (repoPath == null) return undefined; if (repoPath == null) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const relativePath = this.getRelativePath(pathOrUri, repoPath); const relativePath = this.getRelativePath(pathOrUri, repoPath);
@ -1637,7 +1637,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
if (doc.state != null) { if (doc.state != null) {
const cachedLog = doc.state.getLog(key); const cachedLog = doc.state.getLog(key);
if (cachedLog != null) { if (cachedLog != null) {
Logger.debug(cc, `Cache hit: '${key}'`);
Logger.debug(scope, `Cache hit: '${key}'`);
return cachedLog.item; return cachedLog.item;
} }
@ -1648,14 +1648,14 @@ export class GitHubGitProvider implements GitProvider, Disposable {
); );
if (cachedLog != null) { if (cachedLog != null) {
if (options.ref == null) { if (options.ref == null) {
Logger.debug(cc, `Cache hit: ~'${key}'`);
Logger.debug(scope, `Cache hit: ~'${key}'`);
return cachedLog.item; return cachedLog.item;
} }
Logger.debug(cc, `Cache ?: '${key}'`);
Logger.debug(scope, `Cache ?: '${key}'`);
let log = await cachedLog.item; let log = await cachedLog.item;
if (log != null && !log.hasMore && log.commits.has(options.ref)) { if (log != null && !log.hasMore && log.commits.has(options.ref)) {
Logger.debug(cc, `Cache hit: '${key}'`);
Logger.debug(scope, `Cache hit: '${key}'`);
// Create a copy of the log starting at the requested commit // Create a copy of the log starting at the requested commit
let skip = true; let skip = true;
@ -1695,17 +1695,17 @@ export class GitHubGitProvider implements GitProvider, Disposable {
} }
} }
Logger.debug(cc, `Cache miss: '${key}'`);
Logger.debug(scope, `Cache miss: '${key}'`);
if (doc.state == null) { if (doc.state == null) {
doc.state = new GitDocumentState(); doc.state = new GitDocumentState();
} }
} }
const promise = this.getLogForFileCore(repoPath, relativePath, doc, key, cc, options);
const promise = this.getLogForFileCore(repoPath, relativePath, doc, key, scope, options);
if (doc.state != null && options.range == null) { if (doc.state != null && options.range == null) {
Logger.debug(cc, `Cache add: '${key}'`);
Logger.debug(scope, `Cache add: '${key}'`);
const value: CachedLog = { const value: CachedLog = {
item: promise as Promise<GitLog>, item: promise as Promise<GitLog>,
@ -1721,7 +1721,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
path: string, path: string,
document: TrackedDocument<GitDocumentState>, document: TrackedDocument<GitDocumentState>,
key: string, key: string,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
options?: { options?: {
all?: boolean; all?: boolean;
cursor?: string; cursor?: string;
@ -1843,7 +1843,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
// Trap and cache expected log errors // Trap and cache expected log errors
if (document.state != null && options?.range == null && !options?.reverse) { if (document.state != null && options?.range == null && !options?.reverse) {
const msg: string = ex?.toString() ?? ''; const msg: string = ex?.toString() ?? '';
Logger.debug(cc, `Cache replace (with empty promise): '${key}'`);
Logger.debug(scope, `Cache replace (with empty promise): '${key}'`);
const value: CachedLog = { const value: CachedLog = {
item: emptyPromise as Promise<GitLog>, item: emptyPromise as Promise<GitLog>,
@ -1952,7 +1952,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
// If we have no ref there is no next commit // If we have no ref there is no next commit
if (!ref) return undefined; if (!ref) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const context = await this.ensureRepositoryContext(repoPath); const context = await this.ensureRepositoryContext(repoPath);
@ -1983,7 +1983,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
next: new GitUri(await this.getBestRevisionUri(repoPath, relativePath, refs[skip])), next: new GitUri(await this.getBestRevisionUri(repoPath, relativePath, refs[skip])),
}; };
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
throw ex; throw ex;
@ -2000,7 +2000,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<PreviousComparisonUrisResult | undefined> { ): Promise<PreviousComparisonUrisResult | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined; if (ref === GitRevision.deletedOrMissing) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (ref === GitRevision.uncommitted) { if (ref === GitRevision.uncommitted) {
ref = undefined; ref = undefined;
@ -2051,7 +2051,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
), ),
}; };
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
throw ex; throw ex;
@ -2068,7 +2068,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<PreviousLineComparisonUrisResult | undefined> { ): Promise<PreviousLineComparisonUrisResult | undefined> {
if (ref === GitRevision.deletedOrMissing) return undefined; if (ref === GitRevision.deletedOrMissing) return undefined;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const context = await this.ensureRepositoryContext(repoPath); const context = await this.ensureRepositoryContext(repoPath);
@ -2117,7 +2117,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
line: (currentLine ?? editorLine) + 1, // 1-based line: (currentLine ?? editorLine) + 1, // 1-based
}; };
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
throw ex; throw ex;
@ -2199,7 +2199,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
): Promise<PagedResult<GitTag>> { ): Promise<PagedResult<GitTag>> {
if (repoPath == null) return emptyPagedResult; if (repoPath == null) return emptyPagedResult;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
let tagsPromise = options?.cursor ? undefined : this._tagsCache.get(repoPath); let tagsPromise = options?.cursor ? undefined : this._tagsCache.get(repoPath);
if (tagsPromise == null) { if (tagsPromise == null) {
@ -2238,7 +2238,7 @@ export class GitHubGitProvider implements GitProvider, Disposable {
cursor = result.paging.cursor; cursor = result.paging.cursor;
} }
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
this._tagsCache.delete(repoPath!); this._tagsCache.delete(repoPath!);

+ 37
- 37
src/plus/gitlab/gitlab.ts View File

@ -18,9 +18,9 @@ import type { DefaultBranch } from '../../git/models/defaultBranch';
import { IssueOrPullRequest, IssueOrPullRequestType } from '../../git/models/issue'; import { IssueOrPullRequest, IssueOrPullRequestType } from '../../git/models/issue';
import { PullRequest } from '../../git/models/pullRequest'; import { PullRequest } from '../../git/models/pullRequest';
import type { RichRemoteProvider } from '../../git/remotes/provider'; import type { RichRemoteProvider } from '../../git/remotes/provider';
import { LogCorrelationContext, Logger, LogLevel } from '../../logger';
import { Logger, LogLevel, LogScope } from '../../logger';
import { Messages } from '../../messages'; import { Messages } from '../../messages';
import { debug } from '../../system/decorators/log';
import { debug, getLogScope } from '../../system/decorators/log';
import { Stopwatch } from '../../system/stopwatch'; import { Stopwatch } from '../../system/stopwatch';
import { equalsIgnoreCase } from '../../system/string'; import { equalsIgnoreCase } from '../../system/string';
import { import {
@ -83,7 +83,7 @@ export class GitLabApi implements Disposable {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<Account | undefined> { ): Promise<Account | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const projectId = await this.getProjectId(provider, token, owner, repo, options?.baseUrl); const projectId = await this.getProjectId(provider, token, owner, repo, options?.baseUrl);
if (!projectId) return undefined; if (!projectId) return undefined;
@ -98,7 +98,7 @@ export class GitLabApi implements Disposable {
method: 'GET', method: 'GET',
// ...options, // ...options,
}, },
cc,
scope,
); );
let user: GitLabUser | undefined; let user: GitLabUser | undefined;
@ -132,7 +132,7 @@ export class GitLabApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -148,7 +148,7 @@ export class GitLabApi implements Disposable {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<Account | undefined> { ): Promise<Account | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const [user] = await this.findUser(provider, token, email, options); const [user] = await this.findUser(provider, token, email, options);
@ -163,7 +163,7 @@ export class GitLabApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -177,7 +177,7 @@ export class GitLabApi implements Disposable {
baseUrl?: string; baseUrl?: string;
}, },
): Promise<DefaultBranch | undefined> { ): Promise<DefaultBranch | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
data: { data: {
@ -208,7 +208,7 @@ export class GitLabApi implements Disposable {
{ {
fullPath: `${owner}/${repo}`, fullPath: `${owner}/${repo}`,
}, },
cc,
scope,
); );
const defaultBranch = rsp?.data?.project?.repository?.rootRef ?? undefined; const defaultBranch = rsp?.data?.project?.repository?.rootRef ?? undefined;
@ -221,7 +221,7 @@ export class GitLabApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -236,7 +236,7 @@ export class GitLabApi implements Disposable {
baseUrl?: string; baseUrl?: string;
}, },
): Promise<IssueOrPullRequest | undefined> { ): Promise<IssueOrPullRequest | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
data: { data: {
@ -295,7 +295,7 @@ export class GitLabApi implements Disposable {
fullPath: `${owner}/${repo}`, fullPath: `${owner}/${repo}`,
iid: String(number), iid: String(number),
}, },
cc,
scope,
); );
if (rsp?.data?.project?.issue != null) { if (rsp?.data?.project?.issue != null) {
@ -331,7 +331,7 @@ export class GitLabApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -348,7 +348,7 @@ export class GitLabApi implements Disposable {
include?: GitLabMergeRequestState[]; include?: GitLabMergeRequestState[];
}, },
): Promise<PullRequest | undefined> { ): Promise<PullRequest | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
data: { data: {
@ -433,7 +433,7 @@ export class GitLabApi implements Disposable {
branches: [branch], branches: [branch],
state: options?.include, state: options?.include,
}, },
cc,
scope,
); );
let pr: GitLabMergeRequest | undefined; let pr: GitLabMergeRequest | undefined;
@ -478,7 +478,7 @@ export class GitLabApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -494,7 +494,7 @@ export class GitLabApi implements Disposable {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<PullRequest | undefined> { ): Promise<PullRequest | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const projectId = await this.getProjectId(provider, token, owner, repo, options?.baseUrl); const projectId = await this.getProjectId(provider, token, owner, repo, options?.baseUrl);
if (!projectId) return undefined; if (!projectId) return undefined;
@ -510,7 +510,7 @@ export class GitLabApi implements Disposable {
method: 'GET', method: 'GET',
// ...options, // ...options,
}, },
cc,
scope,
); );
if (mrs == null || mrs.length === 0) return undefined; if (mrs == null || mrs.length === 0) return undefined;
@ -527,7 +527,7 @@ export class GitLabApi implements Disposable {
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
throw this.handleException(ex, provider, cc);
throw this.handleException(ex, provider, scope);
} }
} }
@ -540,7 +540,7 @@ export class GitLabApi implements Disposable {
avatarSize?: number; avatarSize?: number;
}, },
): Promise<GitLabUser[]> { ): Promise<GitLabUser[]> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
data: { data: {
@ -582,7 +582,7 @@ $search: String!
{ {
search: search, search: search,
}, },
cc,
scope,
); );
const matches = rsp?.data?.users?.nodes; const matches = rsp?.data?.users?.nodes;
@ -609,7 +609,7 @@ $search: String!
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return []; if (ex instanceof ProviderRequestNotFoundError) return [];
this.handleException(ex, provider, cc);
this.handleException(ex, provider, scope);
return []; return [];
} }
} }
@ -639,7 +639,7 @@ $search: String!
repo: string, repo: string,
baseUrl?: string, baseUrl?: string,
): Promise<string | undefined> { ): Promise<string | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
interface QueryResult { interface QueryResult {
data: { project: { id: string } }; data: { project: { id: string } };
@ -661,7 +661,7 @@ $search: String!
{ {
fullPath: `${group}/${repo}`, fullPath: `${group}/${repo}`,
}, },
cc,
scope,
); );
const gid = rsp?.data?.project?.id; const gid = rsp?.data?.project?.id;
@ -672,14 +672,14 @@ $search: String!
const projectId = match[1]; const projectId = match[1];
if (cc != null) {
cc.exitDetails = `\u2022 projectId=${projectId}`;
if (scope != null) {
scope.exitDetails = `\u2022 projectId=${projectId}`;
} }
return projectId; return projectId;
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderRequestNotFoundError) return undefined; if (ex instanceof ProviderRequestNotFoundError) return undefined;
this.handleException(ex, provider, cc);
this.handleException(ex, provider, scope);
return undefined; return undefined;
} }
} }
@ -690,7 +690,7 @@ $search: String!
baseUrl: string | undefined, baseUrl: string | undefined,
query: string, query: string,
variables: { [key: string]: any }, variables: { [key: string]: any },
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<T | undefined> { ): Promise<T | undefined> {
let rsp: Response; let rsp: Response;
try { try {
@ -727,7 +727,7 @@ $search: String!
} }
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderFetchError) { if (ex instanceof ProviderFetchError) {
this.handleRequestError(provider, token, ex, cc);
this.handleRequestError(provider, token, ex, scope);
} else if (Logger.isDebugging) { } else if (Logger.isDebugging) {
void window.showErrorMessage(`GitLab request failed: ${ex.message}`); void window.showErrorMessage(`GitLab request failed: ${ex.message}`);
} }
@ -742,7 +742,7 @@ $search: String!
baseUrl: string | undefined, baseUrl: string | undefined,
route: string, route: string,
options: { method: RequestInit['method'] } & Record<string, unknown>, options: { method: RequestInit['method'] } & Record<string, unknown>,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): Promise<T> { ): Promise<T> {
const url = `${baseUrl ?? 'https://gitlab.com/api'}/${route}`; const url = `${baseUrl ?? 'https://gitlab.com/api'}/${route}`;
@ -775,7 +775,7 @@ $search: String!
} }
} catch (ex) { } catch (ex) {
if (ex instanceof ProviderFetchError) { if (ex instanceof ProviderFetchError) {
this.handleRequestError(provider, token, ex, cc);
this.handleRequestError(provider, token, ex, scope);
} else if (Logger.isDebugging) { } else if (Logger.isDebugging) {
void window.showErrorMessage(`GitLab request failed: ${ex.message}`); void window.showErrorMessage(`GitLab request failed: ${ex.message}`);
} }
@ -788,7 +788,7 @@ $search: String!
provider: RichRemoteProvider | undefined, provider: RichRemoteProvider | undefined,
token: string, token: string,
ex: ProviderFetchError, ex: ProviderFetchError,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
): void { ): void {
switch (ex.status) { switch (ex.status) {
case 404: // Not found case 404: // Not found
@ -814,7 +814,7 @@ $search: String!
} }
throw new AuthenticationError('gitlab', AuthenticationErrorReason.Forbidden, ex); throw new AuthenticationError('gitlab', AuthenticationErrorReason.Forbidden, ex);
case 500: // Internal Server Error case 500: // Internal Server Error
Logger.error(ex, cc);
Logger.error(ex, scope);
if (ex.response != null) { if (ex.response != null) {
provider?.trackRequestException(); provider?.trackRequestException();
void Messages.showIntegrationRequestFailed500WarningMessage( void Messages.showIntegrationRequestFailed500WarningMessage(
@ -827,7 +827,7 @@ $search: String!
} }
return; return;
case 502: // Bad Gateway case 502: // Bad Gateway
Logger.error(ex, cc);
Logger.error(ex, scope);
// GitHub seems to return this status code for timeouts // GitHub seems to return this status code for timeouts
if (ex.message.includes('timeout')) { if (ex.message.includes('timeout')) {
provider?.trackRequestException(); provider?.trackRequestException();
@ -840,7 +840,7 @@ $search: String!
break; break;
} }
Logger.error(ex, cc);
Logger.error(ex, scope);
if (Logger.isDebugging) { if (Logger.isDebugging) {
void window.showErrorMessage( void window.showErrorMessage(
`GitLab request failed: ${(ex.response as any)?.errors?.[0]?.message ?? ex.message}`, `GitLab request failed: ${(ex.response as any)?.errors?.[0]?.message ?? ex.message}`,
@ -848,8 +848,8 @@ $search: String!
} }
} }
private handleException(ex: Error, provider: RichRemoteProvider, cc: LogCorrelationContext | undefined): Error {
Logger.error(ex, cc);
private handleException(ex: Error, provider: RichRemoteProvider, scope: LogScope | undefined): Error {
Logger.error(ex, scope);
// debugger; // debugger;
if (ex instanceof AuthenticationError) { if (ex instanceof AuthenticationError) {

+ 10
- 10
src/plus/subscription/authenticationProvider.ts View File

@ -12,7 +12,7 @@ import { uuid } from '@env/crypto';
import type { Container } from '../../container'; import type { Container } from '../../container';
import { Logger } from '../../logger'; import { Logger } from '../../logger';
import { StorageKeys } from '../../storage'; import { StorageKeys } from '../../storage';
import { debug } from '../../system/decorators/log';
import { debug, getLogScope } from '../../system/decorators/log';
import { ServerConnection } from './serverConnection'; import { ServerConnection } from './serverConnection';
interface StoredSession { interface StoredSession {
@ -64,7 +64,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide
@debug() @debug()
public async createSession(scopes: string[]): Promise<AuthenticationSession> { public async createSession(scopes: string[]): Promise<AuthenticationSession> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
// Ensure that the scopes are sorted consistently (since we use them for matching and order doesn't matter) // Ensure that the scopes are sorted consistently (since we use them for matching and order doesn't matter)
scopes = scopes.sort(); scopes = scopes.sort();
@ -90,7 +90,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide
// If login was cancelled, do not notify user. // If login was cancelled, do not notify user.
if (ex === 'Cancelled') throw ex; if (ex === 'Cancelled') throw ex;
Logger.error(ex, cc);
Logger.error(ex, scope);
void window.showErrorMessage(`Unable to sign in to GitLens+: ${ex}`); void window.showErrorMessage(`Unable to sign in to GitLens+: ${ex}`);
throw ex; throw ex;
} }
@ -98,7 +98,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide
@debug() @debug()
async getSessions(scopes?: string[]): Promise<AuthenticationSession[]> { async getSessions(scopes?: string[]): Promise<AuthenticationSession[]> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
scopes = scopes?.sort(); scopes = scopes?.sort();
const scopesKey = getScopesKey(scopes); const scopesKey = getScopesKey(scopes);
@ -106,8 +106,8 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide
const sessions = await this._sessionsPromise; const sessions = await this._sessionsPromise;
const filtered = scopes != null ? sessions.filter(s => getScopesKey(s.scopes) === scopesKey) : sessions; const filtered = scopes != null ? sessions.filter(s => getScopesKey(s.scopes) === scopesKey) : sessions;
if (cc != null) {
cc.exitDetails = ` \u2022 Found ${filtered.length} sessions`;
if (scope != null) {
scope.exitDetails = ` \u2022 Found ${filtered.length} sessions`;
} }
return filtered; return filtered;
@ -115,7 +115,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide
@debug() @debug()
public async removeSession(id: string) { public async removeSession(id: string) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const sessions = await this._sessionsPromise; const sessions = await this._sessionsPromise;
@ -132,7 +132,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide
this._onDidChangeSessions.fire({ added: [], removed: [session], changed: [] }); this._onDidChangeSessions.fire({ added: [], removed: [session], changed: [] });
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
void window.showErrorMessage(`Unable to sign out of GitLens+: ${ex}`); void window.showErrorMessage(`Unable to sign out of GitLens+: ${ex}`);
throw ex; throw ex;
} }
@ -140,7 +140,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide
@debug() @debug()
public async removeSessionsByScopes(scopes?: string[]) { public async removeSessionsByScopes(scopes?: string[]) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
scopes = scopes?.sort(); scopes = scopes?.sort();
@ -168,7 +168,7 @@ export class SubscriptionAuthenticationProvider implements AuthenticationProvide
this._onDidChangeSessions.fire({ added: [], removed: removed, changed: [] }); this._onDidChangeSessions.fire({ added: [], removed: removed, changed: [] });
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
void window.showErrorMessage(`Unable to sign out of GitLens+: ${ex}`); void window.showErrorMessage(`Unable to sign out of GitLens+: ${ex}`);
throw ex; throw ex;
} }

+ 3
- 3
src/plus/subscription/serverConnection.ts View File

@ -14,7 +14,7 @@ import { uuid } from '@env/crypto';
import { fetch, getProxyAgent, Response } from '@env/fetch'; import { fetch, getProxyAgent, Response } from '@env/fetch';
import { Container } from '../../container'; import { Container } from '../../container';
import { Logger } from '../../logger'; import { Logger } from '../../logger';
import { debug, log } from '../../system/decorators/log';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { memoize } from '../../system/decorators/memoize'; import { memoize } from '../../system/decorators/memoize';
import { DeferredEvent, DeferredEventExecutor, promisifyDeferred } from '../../system/event'; import { DeferredEvent, DeferredEventExecutor, promisifyDeferred } from '../../system/event';
@ -75,7 +75,7 @@ export class ServerConnection implements Disposable {
@debug({ args: false }) @debug({ args: false })
async getAccountInfo(token: string): Promise<AccountInfo> { async getAccountInfo(token: string): Promise<AccountInfo> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
let rsp: Response; let rsp: Response;
try { try {
@ -88,7 +88,7 @@ export class ServerConnection implements Disposable {
}, },
}); });
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
throw ex; throw ex;
} }

+ 15
- 11
src/plus/subscription/subscriptionService.ts View File

@ -44,7 +44,7 @@ import {
import { executeCommand } from '../../system/command'; import { executeCommand } from '../../system/command';
import { createFromDateDelta } from '../../system/date'; import { createFromDateDelta } from '../../system/date';
import { gate } from '../../system/decorators/gate'; import { gate } from '../../system/decorators/gate';
import { debug, log } from '../../system/decorators/log';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { memoize } from '../../system/decorators/memoize'; import { memoize } from '../../system/decorators/memoize';
import { once } from '../../system/function'; import { once } from '../../system/function';
import { pluralize } from '../../system/string'; import { pluralize } from '../../system/string';
@ -327,7 +327,7 @@ export class SubscriptionService implements Disposable {
async resendVerification(): Promise<boolean> { async resendVerification(): Promise<boolean> {
if (this._subscription.account?.verified) return true; if (this._subscription.account?.verified) return true;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
void this.showHomeView(true); void this.showHomeView(true);
@ -348,7 +348,11 @@ export class SubscriptionService implements Disposable {
if (!rsp.ok) { if (!rsp.ok) {
debugger; debugger;
Logger.error('', cc, `Unable to resend verification email; status=(${rsp.status}): ${rsp.statusText}`);
Logger.error(
'',
scope,
`Unable to resend verification email; status=(${rsp.status}): ${rsp.statusText}`,
);
void window.showErrorMessage(`Unable to resend verification email; Status: ${rsp.statusText}`, 'OK'); void window.showErrorMessage(`Unable to resend verification email; Status: ${rsp.statusText}`, 'OK');
@ -368,7 +372,7 @@ export class SubscriptionService implements Disposable {
return true; return true;
} }
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
void window.showErrorMessage('Unable to resend verification email', 'OK'); void window.showErrorMessage('Unable to resend verification email', 'OK');
@ -461,7 +465,7 @@ export class SubscriptionService implements Disposable {
@gate() @gate()
@log() @log()
async validate(): Promise<void> { async validate(): Promise<void> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const session = await this.ensureSession(false); const session = await this.ensureSession(false);
if (session == null) { if (session == null) {
@ -472,7 +476,7 @@ export class SubscriptionService implements Disposable {
try { try {
await this.checkInAndValidate(session); await this.checkInAndValidate(session);
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
} }
} }
@ -500,7 +504,7 @@ export class SubscriptionService implements Disposable {
@debug<SubscriptionService['checkInAndValidate']>({ args: { 0: s => s?.account.label } }) @debug<SubscriptionService['checkInAndValidate']>({ args: { 0: s => s?.account.label } })
private async checkInAndValidateCore(session: AuthenticationSession): Promise<void> { private async checkInAndValidateCore(session: AuthenticationSession): Promise<void> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const checkInData = { const checkInData = {
@ -533,7 +537,7 @@ export class SubscriptionService implements Disposable {
this.validateSubscription(data); this.validateSubscription(data);
this._lastCheckInDate = new Date(); this._lastCheckInDate = new Date();
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
if (ex instanceof AccountValidationError) throw ex; if (ex instanceof AccountValidationError) throw ex;
@ -657,7 +661,7 @@ export class SubscriptionService implements Disposable {
@debug() @debug()
private async getOrCreateSession(createIfNeeded: boolean): Promise<AuthenticationSession | null> { private async getOrCreateSession(createIfNeeded: boolean): Promise<AuthenticationSession | null> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
let session: AuthenticationSession | null | undefined; let session: AuthenticationSession | null | undefined;
@ -678,7 +682,7 @@ export class SubscriptionService implements Disposable {
return null; return null;
} }
Logger.error(ex, cc);
Logger.error(ex, scope);
} }
// If we didn't find a session, check if we could migrate one from the GK auth provider // If we didn't find a session, check if we could migrate one from the GK auth provider
@ -694,7 +698,7 @@ export class SubscriptionService implements Disposable {
try { try {
await this.checkInAndValidate(session, createIfNeeded); await this.checkInAndValidate(session, createIfNeeded);
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
debugger; debugger;
const name = session.account.label; const name = session.account.label;

+ 14
- 7
src/statusbar/statusBarController.ts View File

@ -18,9 +18,9 @@ import { CommitFormatter } from '../git/formatters/commitFormatter';
import type { GitCommit } from '../git/models/commit'; import type { GitCommit } from '../git/models/commit';
import type { PullRequest } from '../git/models/pullRequest'; import type { PullRequest } from '../git/models/pullRequest';
import { Hovers } from '../hovers/hovers'; import { Hovers } from '../hovers/hovers';
import { LogCorrelationContext, Logger } from '../logger';
import { Logger, LogScope } from '../logger';
import { asCommand } from '../system/command'; import { asCommand } from '../system/command';
import { debug } from '../system/decorators/log';
import { debug, getLogScope } from '../system/decorators/log';
import { once } from '../system/event'; import { once } from '../system/event';
import { PromiseCancelledError } from '../system/promise'; import { PromiseCancelledError } from '../system/promise';
import { isTextEditor } from '../system/utils'; import { isTextEditor } from '../system/utils';
@ -179,7 +179,7 @@ export class StatusBarController implements Disposable {
const cfg = configuration.get('statusBar'); const cfg = configuration.get('statusBar');
if (!cfg.enabled || this._statusBarBlame == null || !isTextEditor(editor)) return; if (!cfg.enabled || this._statusBarBlame == null || !isTextEditor(editor)) return;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const showPullRequests = const showPullRequests =
cfg.pullRequests.enabled && cfg.pullRequests.enabled &&
@ -214,7 +214,14 @@ export class StatusBarController implements Disposable {
if (pr != null) { if (pr != null) {
this._pullRequestCancellation?.cancel(); this._pullRequestCancellation?.cancel();
this._pullRequestCancellation = new CancellationTokenSource(); this._pullRequestCancellation = new CancellationTokenSource();
void this.waitForPendingPullRequest(editor, commit, pr, this._pullRequestCancellation.token, timeout, cc);
void this.waitForPendingPullRequest(
editor,
commit,
pr,
this._pullRequestCancellation.token,
timeout,
scope,
);
} }
this._statusBarBlame.text = `$(git-commit) ${CommitFormatter.fromTemplate(cfg.format, commit, { this._statusBarBlame.text = `$(git-commit) ${CommitFormatter.fromTemplate(cfg.format, commit, {
@ -403,18 +410,18 @@ export class StatusBarController implements Disposable {
pr: PullRequest | PromiseCancelledError<Promise<PullRequest | undefined>> | undefined, pr: PullRequest | PromiseCancelledError<Promise<PullRequest | undefined>> | undefined,
cancellationToken: CancellationToken, cancellationToken: CancellationToken,
timeout: number, timeout: number,
cc: LogCorrelationContext | undefined,
scope: LogScope | undefined,
) { ) {
if (cancellationToken.isCancellationRequested || !(pr instanceof PromiseCancelledError)) return; if (cancellationToken.isCancellationRequested || !(pr instanceof PromiseCancelledError)) return;
// If the PR timed out, refresh the status bar once it completes // If the PR timed out, refresh the status bar once it completes
Logger.debug(cc, `${GlyphChars.Dot} pull request query took too long (over ${timeout} ms)`);
Logger.debug(scope, `${GlyphChars.Dot} pull request query took too long (over ${timeout} ms)`);
pr = await pr.promise; pr = await pr.promise;
if (cancellationToken.isCancellationRequested) return; if (cancellationToken.isCancellationRequested) return;
Logger.debug(cc, `${GlyphChars.Dot} pull request query completed; refreshing...`);
Logger.debug(scope, `${GlyphChars.Dot} pull request query completed; refreshing...`);
void this.updateBlame(editor, commit, { pr: pr ?? null }); void this.updateBlame(editor, commit, { pr: pr ?? null });
} }

+ 139
- 131
src/system/decorators/log.ts View File

@ -1,6 +1,6 @@
import { hrtime } from '@env/hrtime'; import { hrtime } from '@env/hrtime';
import { LogCorrelationContext, Logger, LogLevel } from '../../logger';
import { filterMap } from '../array';
import type { LogScope } from '../../logger';
import { Logger, LogLevel } from '../../logger';
import { getParameters } from '../function'; import { getParameters } from '../function';
import { isPromise } from '../promise'; import { isPromise } from '../promise';
import { getDurationMilliseconds } from '../string'; import { getDurationMilliseconds } from '../string';
@ -8,30 +8,38 @@ import { getDurationMilliseconds } from '../string';
const emptyStr = ''; const emptyStr = '';
const maxSmallIntegerV8 = 2 ** 30; // Max number that can be stored in V8's smis (small integers) const maxSmallIntegerV8 = 2 ** 30; // Max number that can be stored in V8's smis (small integers)
const correlationContext = new Map<number, LogCorrelationContext>();
let correlationCounter = 0;
const scopes = new Map<number, LogScope>();
let scopeCounter = 0;
export function getCorrelationContext() {
return correlationContext.get(correlationCounter);
export function getLogScope(): LogScope | undefined {
return scopes.get(scopeCounter);
} }
export function getCorrelationId() {
return correlationCounter;
export function getNewLogScope(prefix: string): LogScope {
const scopeId = getNextLogScopeId();
return {
scopeId: scopeId,
prefix: `[${String(scopeId).padStart(5)}] ${prefix}`,
};
}
export function getLogScopeId(): number {
return scopeCounter;
} }
export function getNextCorrelationId() {
if (correlationCounter === maxSmallIntegerV8) {
correlationCounter = 0;
export function getNextLogScopeId(): number {
if (scopeCounter === maxSmallIntegerV8) {
scopeCounter = 0;
} }
return ++correlationCounter;
return ++scopeCounter;
} }
function clearCorrelationContext(correlationId: number) {
correlationContext.delete(correlationId);
function clearLogScope(scopeId: number) {
scopes.delete(scopeId);
} }
function setCorrelationContext(correlationId: number, context: LogCorrelationContext) {
correlationContext.set(correlationId, context);
function setLogScope(scopeId: number, scope: LogScope) {
scopes.set(scopeId, scope);
} }
export interface LogContext { export interface LogContext {
@ -42,6 +50,27 @@ export interface LogContext {
prefix: string; prefix: string;
} }
interface LogOptions<T extends (...arg: any) => any> {
args?:
| false
| {
0?: ((arg: Parameters<T>[0]) => unknown) | string | false;
1?: ((arg: Parameters<T>[1]) => unknown) | string | false;
2?: ((arg: Parameters<T>[2]) => unknown) | string | false;
3?: ((arg: Parameters<T>[3]) => unknown) | string | false;
4?: ((arg: Parameters<T>[4]) => unknown) | string | false;
[key: number]: (((arg: any) => unknown) | string | false) | undefined;
};
condition?(...args: Parameters<T>): boolean;
enter?(...args: Parameters<T>): string;
exit?(result: PromiseType<ReturnType<T>>): string;
prefix?(context: LogContext, ...args: Parameters<T>): string;
sanitize?(key: string, value: any): any;
scoped?: boolean;
singleLine?: boolean;
timed?: boolean;
}
export const LogInstanceNameFn = Symbol('logInstanceNameFn'); export const LogInstanceNameFn = Symbol('logInstanceNameFn');
export function logName<T>(fn: (c: T, name: string) => string) { export function logName<T>(fn: (c: T, name: string) => string) {
@ -50,59 +79,41 @@ export function logName(fn: (c: T, name: string) => string) {
}; };
} }
export function debug<T extends (...arg: any) => any>(
options: {
args?:
| false
| {
0?: ((arg: Parameters<T>[0]) => unknown) | string | false;
1?: ((arg: Parameters<T>[1]) => unknown) | string | false;
2?: ((arg: Parameters<T>[2]) => unknown) | string | false;
3?: ((arg: Parameters<T>[3]) => unknown) | string | false;
4?: ((arg: Parameters<T>[4]) => unknown) | string | false;
[key: number]: (((arg: any) => unknown) | string | false) | undefined;
};
condition?(...args: Parameters<T>): boolean;
correlate?: boolean;
enter?(...args: Parameters<T>): string;
exit?(result: PromiseType<ReturnType<T>>): string;
prefix?(context: LogContext, ...args: Parameters<T>): string;
sanitize?(key: string, value: any): any;
singleLine?: boolean;
timed?: boolean;
} = { timed: true },
) {
return log<T>({ debug: true, ...options });
export function debug<T extends (...arg: any) => any>(options?: LogOptions<T>) {
return log<T>(options, true);
} }
type PromiseType<T> = T extends Promise<infer U> ? U : T; type PromiseType<T> = T extends Promise<infer U> ? U : T;
export function log<T extends (...arg: any) => any>(
options: {
args?:
| false
| {
0?: ((arg: Parameters<T>[0]) => unknown) | string | false;
1?: ((arg: Parameters<T>[1]) => unknown) | string | false;
2?: ((arg: Parameters<T>[2]) => unknown) | string | false;
3?: ((arg: Parameters<T>[3]) => unknown) | string | false;
4?: ((arg: Parameters<T>[4]) => unknown) | string | false;
[key: number]: (((arg: any) => unknown) | string | false) | undefined;
};
condition?(...args: Parameters<T>): boolean;
correlate?: boolean;
debug?: boolean;
enter?(...args: Parameters<T>): string;
exit?(result: PromiseType<ReturnType<T>>): string;
prefix?(context: LogContext, ...args: Parameters<T>): string;
sanitize?(key: string, value: any): any;
singleLine?: boolean;
timed?: boolean;
} = { timed: true },
) {
options = { timed: true, ...options };
const logFn = (options.debug ? Logger.debug.bind(Logger) : Logger.log.bind(Logger)) as
export function log<T extends (...arg: any) => any>(options?: LogOptions<T>, debug = false) {
let overrides: LogOptions<T>['args'] | undefined;
let conditionFn: LogOptions<T>['condition'] | undefined;
let enterFn: LogOptions<T>['enter'] | undefined;
let exitFn: LogOptions<T>['exit'] | undefined;
let prefixFn: LogOptions<T>['prefix'] | undefined;
let sanitizeFn: LogOptions<T>['sanitize'] | undefined;
let scoped = false;
let singleLine = false;
let timed = true;
if (options != null) {
({
args: overrides,
condition: conditionFn,
enter: enterFn,
exit: exitFn,
prefix: prefixFn,
sanitize: sanitizeFn,
scoped = true,
singleLine = false,
timed = true,
} = options);
}
if (timed) {
scoped = true;
}
const logFn = (debug ? Logger.debug.bind(Logger) : Logger.log.bind(Logger)) as
| typeof Logger.debug | typeof Logger.debug
| typeof Logger.log; | typeof Logger.log;
const warnFn = Logger.warn.bind(Logger); const warnFn = Logger.warn.bind(Logger);
@ -122,13 +133,13 @@ export function log any>(
const parameters = getParameters(fn); const parameters = getParameters(fn);
descriptor[fnKey] = function (this: any, ...args: Parameters<T>) { descriptor[fnKey] = function (this: any, ...args: Parameters<T>) {
const correlationId = getNextCorrelationId();
const scopeId = getNextLogScopeId();
if ( if (
(!Logger.isDebugging && (!Logger.isDebugging &&
!Logger.enabled(LogLevel.Debug) && !Logger.enabled(LogLevel.Debug) &&
!(Logger.enabled(LogLevel.Info) && !options.debug)) ||
(typeof options.condition === 'function' && !options.condition(...args))
!(Logger.enabled(LogLevel.Info) && !debug)) ||
(conditionFn != null && !conditionFn(...args))
) { ) {
return fn!.apply(this, args); return fn!.apply(this, args);
} }
@ -144,19 +155,14 @@ export function log any>(
instanceName = emptyStr; instanceName = emptyStr;
} }
let { correlate } = options;
if (!correlate && options.timed) {
correlate = true;
}
let prefix = `${correlate ? `[${correlationId.toString(16).padStart(5)}] ` : emptyStr}${
let prefix = `${scoped ? `[${scopeId.toString(16).padStart(5)}] ` : emptyStr}${
instanceName ? `${instanceName}.` : emptyStr instanceName ? `${instanceName}.` : emptyStr
}${key}`; }${key}`;
if (options.prefix != null) {
prefix = options.prefix(
if (prefixFn != null) {
prefix = prefixFn(
{ {
id: correlationId,
id: scopeId,
instance: this, instance: this,
instanceName: instanceName, instanceName: instanceName,
name: key, name: key,
@ -166,76 +172,84 @@ export function log any>(
); );
} }
let correlationContext: LogCorrelationContext | undefined;
if (correlate) {
correlationContext = { correlationId: correlationId, prefix: prefix };
setCorrelationContext(correlationId, correlationContext);
let scope: LogScope | undefined;
if (scoped) {
scope = { scopeId: scopeId, prefix: prefix };
setLogScope(scopeId, scope);
} }
const enter = options.enter != null ? options.enter(...args) : emptyStr;
const enter = enterFn != null ? enterFn(...args) : emptyStr;
let loggableParams: string; let loggableParams: string;
if (options.args === false || args.length === 0) {
if (overrides === false || args.length === 0) {
loggableParams = emptyStr; loggableParams = emptyStr;
if (!options.singleLine) {
if (!singleLine) {
logFn(`${prefix}${enter}`); logFn(`${prefix}${enter}`);
} }
} else { } else {
const argControllers = typeof options.args === 'object' ? options.args : undefined;
let argController;
let loggable;
loggableParams = filterMap(args, (v: any, index: number) => {
const p = parameters[index];
argController = argControllers != null ? argControllers[index] : undefined;
if (argController != null) {
if (typeof argController === 'boolean') return undefined;
if (typeof argController === 'string') return argController;
loggable = String(argController(v));
let loggableParams = '';
let paramOverride;
let paramIndex = -1;
let paramName;
let paramLogValue;
let paramValue;
for (paramValue of args as unknown[]) {
paramName = parameters[++paramIndex];
paramOverride = overrides?.[paramIndex];
if (paramOverride != null) {
if (typeof paramOverride === 'boolean') continue;
if (loggableParams.length > 0) {
loggableParams += ', ';
}
if (typeof paramOverride === 'string') {
loggableParams += paramOverride;
continue;
}
paramLogValue = String(paramOverride(paramValue));
} else { } else {
loggable = Logger.toLoggable(v, options.sanitize);
if (loggableParams.length > 0) {
loggableParams += ', ';
}
paramLogValue = Logger.toLoggable(paramValue, sanitizeFn);
} }
return p ? `${p}=${loggable}` : loggable;
}).join(', ');
loggableParams += paramName ? `${paramName}=${paramLogValue}` : paramLogValue;
}
if (!options.singleLine) {
if (!singleLine) {
logFn( logFn(
`${prefix}${enter}`, `${prefix}${enter}`,
!options.debug && !Logger.enabled(LogLevel.Debug) && !Logger.isDebugging
? emptyStr
: loggableParams,
!debug && !Logger.enabled(LogLevel.Debug) && !Logger.isDebugging ? emptyStr : loggableParams,
); );
} }
} }
if (options.singleLine || options.timed || options.exit != null) {
const start = options.timed ? hrtime() : undefined;
if (singleLine || timed || exitFn != null) {
const start = timed ? hrtime() : undefined;
const logError = (ex: Error) => { const logError = (ex: Error) => {
const timing = start !== undefined ? ` \u2022 ${getDurationMilliseconds(start)} ms` : emptyStr; const timing = start !== undefined ? ` \u2022 ${getDurationMilliseconds(start)} ms` : emptyStr;
if (options.singleLine) {
if (singleLine) {
Logger.error( Logger.error(
ex, ex,
`${prefix}${enter}`, `${prefix}${enter}`,
`failed${
correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr
}${timing}`,
`failed${scope?.exitDetails ? scope.exitDetails : emptyStr}${timing}`,
loggableParams, loggableParams,
); );
} else { } else {
Logger.error(
ex,
prefix,
`failed${
correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr
}${timing}`,
);
Logger.error(ex, prefix, `failed${scope?.exitDetails ? scope.exitDetails : emptyStr}${timing}`);
} }
if (correlate) {
clearCorrelationContext(correlationId);
if (scoped) {
clearLogScope(scopeId);
} }
}; };
@ -265,9 +279,9 @@ export function log any>(
} }
let exit; let exit;
if (options.exit != null) {
if (exitFn != null) {
try { try {
exit = options.exit(r);
exit = exitFn(r);
} catch (ex) { } catch (ex) {
exit = `@log.exit error: ${ex}`; exit = `@log.exit error: ${ex}`;
} }
@ -275,25 +289,19 @@ export function log any>(
exit = 'completed'; exit = 'completed';
} }
if (options.singleLine) {
if (singleLine) {
exitLogFn( exitLogFn(
`${prefix}${enter} ${exit}${
correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr
}${timing}`,
!options.debug && !Logger.enabled(LogLevel.Debug) && !Logger.isDebugging
`${prefix}${enter} ${exit}${scope?.exitDetails ? scope.exitDetails : emptyStr}${timing}`,
!debug && !Logger.enabled(LogLevel.Debug) && !Logger.isDebugging
? emptyStr ? emptyStr
: loggableParams, : loggableParams,
); );
} else { } else {
exitLogFn(
`${prefix} ${exit}${
correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr
}${timing}`,
);
exitLogFn(`${prefix} ${exit}${scope?.exitDetails ? scope.exitDetails : emptyStr}${timing}`);
} }
if (correlate) {
clearCorrelationContext(correlationId);
if (scoped) {
clearLogScope(scopeId);
} }
}; };

+ 27
- 27
src/system/stopwatch.ts View File

@ -1,7 +1,7 @@
import { hrtime } from '@env/hrtime'; import { hrtime } from '@env/hrtime';
import { GlyphChars } from '../constants'; import { GlyphChars } from '../constants';
import { LogCorrelationContext, Logger, LogLevel } from '../logger';
import { getNextCorrelationId } from '../system/decorators/log';
import { Logger, LogLevel, LogScope } from '../logger';
import { getNextLogScopeId } from '../system/decorators/log';
type StopwatchLogOptions = { message?: string; suffix?: string }; type StopwatchLogOptions = { message?: string; suffix?: string };
type StopwatchOptions = { type StopwatchOptions = {
@ -11,15 +11,15 @@ type StopwatchOptions = {
type StopwatchLogLevel = Exclude<LogLevel, LogLevel.Off>; type StopwatchLogLevel = Exclude<LogLevel, LogLevel.Off>;
export class Stopwatch { export class Stopwatch {
private readonly instance = `[${String(getNextCorrelationId()).padStart(5)}] `;
private readonly instance = `[${String(getNextLogScopeId()).padStart(5)}] `;
private readonly logLevel: StopwatchLogLevel; private readonly logLevel: StopwatchLogLevel;
private time: [number, number]; private time: [number, number];
constructor(public readonly context: string | LogCorrelationContext, options?: StopwatchOptions, ...params: any[]) {
let cc;
if (typeof context !== 'string') {
cc = context;
context = '';
constructor(public readonly scope: string | LogScope | undefined, options?: StopwatchOptions, ...params: any[]) {
let logScope;
if (typeof scope !== 'string') {
logScope = scope;
scope = '';
this.instance = ''; this.instance = '';
} }
@ -39,26 +39,26 @@ export class Stopwatch {
if (params.length) { if (params.length) {
log( log(
this.logLevel, this.logLevel,
cc,
`${this.instance}${context}${logOptions.message ?? ''}${logOptions.suffix ?? ''}`,
logScope,
`${this.instance}${scope}${logOptions.message ?? ''}${logOptions.suffix ?? ''}`,
...params, ...params,
); );
} else { } else {
log( log(
this.logLevel, this.logLevel,
cc,
`${this.instance}${context}${logOptions.message ?? ''}${logOptions.suffix ?? ''}`,
logScope,
`${this.instance}${scope}${logOptions.message ?? ''}${logOptions.suffix ?? ''}`,
); );
} }
} }
} }
log(options?: StopwatchLogOptions): void { log(options?: StopwatchLogOptions): void {
this.logCore(this.context, options, false);
this.logCore(this.scope, options, false);
} }
restart(options?: StopwatchLogOptions): void { restart(options?: StopwatchLogOptions): void {
this.logCore(this.context, options, true);
this.logCore(this.scope, options, true);
this.time = hrtime(); this.time = hrtime();
} }
@ -67,20 +67,20 @@ export class Stopwatch {
} }
private logCore( private logCore(
context: string | LogCorrelationContext,
scope: string | LogScope | undefined,
options: StopwatchLogOptions | undefined, options: StopwatchLogOptions | undefined,
logTotalElapsed: boolean, logTotalElapsed: boolean,
): void { ): void {
if (!Logger.enabled(this.logLevel)) return; if (!Logger.enabled(this.logLevel)) return;
let cc;
if (typeof context !== 'string') {
cc = context;
context = '';
let logScope;
if (typeof scope !== 'string') {
logScope = scope;
scope = '';
} }
if (!logTotalElapsed) { if (!logTotalElapsed) {
log(this.logLevel, cc, `${this.instance}${context}${options?.message ?? ''}${options?.suffix ?? ''}`);
log(this.logLevel, logScope, `${this.instance}${scope}${options?.message ?? ''}${options?.suffix ?? ''}`);
return; return;
} }
@ -88,10 +88,10 @@ export class Stopwatch {
const [secs, nanosecs] = hrtime(this.time); const [secs, nanosecs] = hrtime(this.time);
const ms = secs * 1000 + Math.floor(nanosecs / 1000000); const ms = secs * 1000 + Math.floor(nanosecs / 1000000);
const prefix = `${this.instance}${context}${options?.message ?? ''}`;
const prefix = `${this.instance}${scope}${options?.message ?? ''}`;
log( log(
ms > 250 ? LogLevel.Warn : this.logLevel, ms > 250 ? LogLevel.Warn : this.logLevel,
cc,
logScope,
`${prefix ? `${prefix} ${GlyphChars.Dot} ` : ''}${ms} ms${options?.suffix ?? ''}`, `${prefix ? `${prefix} ${GlyphChars.Dot} ` : ''}${ms} ms${options?.suffix ?? ''}`,
); );
} }
@ -113,19 +113,19 @@ export class Stopwatch {
} }
} }
function log(logLevel: StopwatchLogLevel, cc: LogCorrelationContext | undefined, message: string, ...params: any[]) {
function log(logLevel: StopwatchLogLevel, scope: LogScope | undefined, message: string, ...params: any[]) {
switch (logLevel) { switch (logLevel) {
case LogLevel.Error: case LogLevel.Error:
Logger.error('', cc, message, ...params);
Logger.error('', scope, message, ...params);
break; break;
case LogLevel.Warn: case LogLevel.Warn:
Logger.warn(cc, message, ...params);
Logger.warn(scope, message, ...params);
break; break;
case LogLevel.Info: case LogLevel.Info:
Logger.log(cc, message, ...params);
Logger.log(scope, message, ...params);
break; break;
default: default:
Logger.debug(cc, message, ...params);
Logger.debug(scope, message, ...params);
break; break;
} }
} }

+ 17
- 18
src/trackers/gitLineTracker.ts View File

@ -3,8 +3,7 @@ import { configuration } from '../configuration';
import { GlyphChars } from '../constants'; import { GlyphChars } from '../constants';
import type { Container } from '../container'; import type { Container } from '../container';
import type { GitCommit } from '../git/models/commit'; import type { GitCommit } from '../git/models/commit';
import { Logger } from '../logger';
import { debug } from '../system/decorators/log';
import { debug, getLogScope } from '../system/decorators/log';
import type { import type {
DocumentBlameStateChangeEvent, DocumentBlameStateChangeEvent,
DocumentContentChangeEvent, DocumentContentChangeEvent,
@ -83,11 +82,11 @@ export class GitLineTracker extends LineTracker {
}) })
private onContentChanged(e: DocumentContentChangeEvent<GitDocumentState>) { private onContentChanged(e: DocumentContentChangeEvent<GitDocumentState>) {
if ( if (
e.contentChanges.some(cc =>
e.contentChanges.some(scope =>
this.selections?.some( this.selections?.some(
selection => selection =>
(cc.range.end.line >= selection.active && selection.active >= cc.range.start.line) ||
(cc.range.start.line >= selection.active && selection.active >= cc.range.end.line),
(scope.range.end.line >= selection.active && selection.active >= scope.range.start.line) ||
(scope.range.start.line >= selection.active && selection.active >= scope.range.end.line),
), ),
) )
) { ) {
@ -128,11 +127,11 @@ export class GitLineTracker extends LineTracker {
exit: updated => `returned ${updated}`, exit: updated => `returned ${updated}`,
}) })
private async updateState(selections: LineSelection[], editor: TextEditor): Promise<boolean> { private async updateState(selections: LineSelection[], editor: TextEditor): Promise<boolean> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (!this.includes(selections)) { if (!this.includes(selections)) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} lines no longer match`;
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} lines no longer match`;
} }
return false; return false;
@ -140,8 +139,8 @@ export class GitLineTracker extends LineTracker {
const trackedDocument = await this.container.tracker.getOrAdd(editor.document); const trackedDocument = await this.container.tracker.getOrAdd(editor.document);
if (!trackedDocument.isBlameable) { if (!trackedDocument.isBlameable) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} document is not blameable`;
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} document is not blameable`;
} }
return false; return false;
@ -154,8 +153,8 @@ export class GitLineTracker extends LineTracker {
editor?.document, editor?.document,
); );
if (blameLine == null) { if (blameLine == null) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} blame failed`;
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} blame failed`;
} }
return false; return false;
@ -165,8 +164,8 @@ export class GitLineTracker extends LineTracker {
} else { } else {
const blame = await this.container.git.getBlame(trackedDocument.uri, editor.document); const blame = await this.container.git.getBlame(trackedDocument.uri, editor.document);
if (blame == null) { if (blame == null) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} blame failed`;
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} blame failed`;
} }
return false; return false;
@ -181,16 +180,16 @@ export class GitLineTracker extends LineTracker {
// Check again because of the awaits above // Check again because of the awaits above
if (!this.includes(selections)) { if (!this.includes(selections)) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} lines no longer match`;
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} lines no longer match`;
} }
return false; return false;
} }
if (!trackedDocument.isBlameable) { if (!trackedDocument.isBlameable) {
if (cc != null) {
cc.exitDetails = ` ${GlyphChars.Dot} document is not blameable`;
if (scope != null) {
scope.exitDetails = ` ${GlyphChars.Dot} document is not blameable`;
} }
return false; return false;

+ 3
- 3
src/trackers/lineTracker.ts View File

@ -1,6 +1,6 @@
import { Disposable, Event, EventEmitter, Selection, TextEditor, TextEditorSelectionChangeEvent, window } from 'vscode'; import { Disposable, Event, EventEmitter, Selection, TextEditor, TextEditorSelectionChangeEvent, window } from 'vscode';
import { Logger } from '../logger'; import { Logger } from '../logger';
import { debug } from '../system/decorators/log';
import { debug, getLogScope } from '../system/decorators/log';
import { debounce, Deferrable } from '../system/function'; import { debounce, Deferrable } from '../system/function';
import { isTextEditor } from '../system/utils'; import { isTextEditor } from '../system/utils';
@ -115,7 +115,7 @@ export class LineTracker implements Disposable {
@debug({ args: false }) @debug({ args: false })
subscribe(subscriber: unknown, subscription: Disposable): Disposable { subscribe(subscriber: unknown, subscription: Disposable): Disposable {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
const disposable = { const disposable = {
dispose: () => this.unsubscribe(subscriber), dispose: () => this.unsubscribe(subscriber),
@ -132,7 +132,7 @@ export class LineTracker implements Disposable {
} }
if (first) { if (first) {
Logger.debug(cc, 'Starting line tracker...');
Logger.debug(scope, 'Starting line tracker...');
this._disposable = Disposable.from( this._disposable = Disposable.from(
window.onDidChangeActiveTextEditor(debounce(this.onActiveTextEditorChanged, 0), this), window.onDidChangeActiveTextEditor(debounce(this.onActiveTextEditorChanged, 0), this),

+ 8
- 8
src/views/nodes/fileHistoryTrackerNode.ts View File

@ -7,7 +7,7 @@ import { GitReference, GitRevision } from '../../git/models/reference';
import { Logger } from '../../logger'; import { Logger } from '../../logger';
import { ReferencePicker } from '../../quickpicks/referencePicker'; import { ReferencePicker } from '../../quickpicks/referencePicker';
import { gate } from '../../system/decorators/gate'; import { gate } from '../../system/decorators/gate';
import { debug, log } from '../../system/decorators/log';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { debounce, Deferrable } from '../../system/function'; import { debounce, Deferrable } from '../../system/function';
import { isVirtualUri } from '../../system/utils'; import { isVirtualUri } from '../../system/utils';
import type { FileHistoryView } from '../fileHistoryView'; import type { FileHistoryView } from '../fileHistoryView';
@ -131,7 +131,7 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode
exit: r => `returned ${r}`, exit: r => `returned ${r}`,
}) })
override async refresh(reset: boolean = false) { override async refresh(reset: boolean = false) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (!this.canSubscribe) return false; if (!this.canSubscribe) return false;
@ -155,15 +155,15 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode
this.reset(); this.reset();
if (cc != null) {
cc.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
if (scope != null) {
scope.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
} }
return false; return false;
} }
if (editor.document.uri.path === this.uri.path) { if (editor.document.uri.path === this.uri.path) {
if (cc != null) {
cc.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
if (scope != null) {
scope.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
} }
return true; return true;
} }
@ -195,8 +195,8 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode
this.resetChild(); this.resetChild();
} }
if (cc != null) {
cc.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
if (scope != null) {
scope.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
} }
return false; return false;
} }

+ 8
- 8
src/views/nodes/lineHistoryTrackerNode.ts View File

@ -7,7 +7,7 @@ import { GitReference, GitRevision } from '../../git/models/reference';
import { Logger } from '../../logger'; import { Logger } from '../../logger';
import { ReferencePicker } from '../../quickpicks/referencePicker'; import { ReferencePicker } from '../../quickpicks/referencePicker';
import { gate } from '../../system/decorators/gate'; import { gate } from '../../system/decorators/gate';
import { debug, log } from '../../system/decorators/log';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { debounce } from '../../system/function'; import { debounce } from '../../system/function';
import type { LinesChangeEvent } from '../../trackers/gitLineTracker'; import type { LinesChangeEvent } from '../../trackers/gitLineTracker';
import type { FileHistoryView } from '../fileHistoryView'; import type { FileHistoryView } from '../fileHistoryView';
@ -142,7 +142,7 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode
exit: r => `returned ${r}`, exit: r => `returned ${r}`,
}) })
override async refresh(reset: boolean = false) { override async refresh(reset: boolean = false) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
if (!this.canSubscribe) return false; if (!this.canSubscribe) return false;
@ -166,8 +166,8 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode
this.reset(); this.reset();
if (cc != null) {
cc.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
if (scope != null) {
scope.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
} }
return false; return false;
} }
@ -177,8 +177,8 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode
this._selection != null && this._selection != null &&
editor.selection.isEqual(this._selection) editor.selection.isEqual(this._selection)
) { ) {
if (cc != null) {
cc.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
if (scope != null) {
scope.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
} }
return true; return true;
} }
@ -204,8 +204,8 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode
this.resetChild(); this.resetChild();
} }
if (cc != null) {
cc.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
if (scope != null) {
scope.exitDetails = `, uri=${Logger.toLoggable(this._uri)}`;
} }
return false; return false;
} }

+ 5
- 5
src/views/viewBase.ts View File

@ -34,7 +34,7 @@ import {
import { Container } from '../container'; import { Container } from '../container';
import { Logger } from '../logger'; import { Logger } from '../logger';
import { executeCommand } from '../system/command'; import { executeCommand } from '../system/command';
import { debug, log } from '../system/decorators/log';
import { debug, getLogScope, log } from '../system/decorators/log';
import { once } from '../system/event'; import { once } from '../system/event';
import { debounce } from '../system/function'; import { debounce } from '../system/function';
import { cancellable, isPromise } from '../system/promise'; import { cancellable, isPromise } from '../system/promise';
@ -369,7 +369,7 @@ export abstract class ViewBase<
token?: CancellationToken; token?: CancellationToken;
} = {}, } = {},
): Promise<ViewNode | undefined> { ): Promise<ViewNode | undefined> {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
async function find(this: ViewBase<RootNode, ViewConfig>) { async function find(this: ViewBase<RootNode, ViewConfig>) {
try { try {
@ -384,7 +384,7 @@ export abstract class ViewBase<
return node; return node;
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }
@ -537,12 +537,12 @@ export abstract class ViewBase<
@log() @log()
async show(options?: { preserveFocus?: boolean }) { async show(options?: { preserveFocus?: boolean }) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
void (await executeCommand(`${this.id}.focus`, options)); void (await executeCommand(`${this.id}.focus`, options));
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
} }
} }

+ 3
- 3
src/vsls/guest.ts View File

@ -3,14 +3,14 @@ import type { LiveShare, SharedServiceProxy } from '../@types/vsls';
import { Container } from '../container'; import { Container } from '../container';
import { GitCommandOptions } from '../git/commandOptions'; import { GitCommandOptions } from '../git/commandOptions';
import { Logger } from '../logger'; import { Logger } from '../logger';
import { debug, log } from '../system/decorators/log';
import { debug, getLogScope, log } from '../system/decorators/log';
import { VslsHostService } from './host'; import { VslsHostService } from './host';
import { GetRepositoriesForUriRequestType, GitCommandRequestType, RepositoryProxy, RequestType } from './protocol'; import { GetRepositoriesForUriRequestType, GitCommandRequestType, RepositoryProxy, RequestType } from './protocol';
export class VslsGuestService implements Disposable { export class VslsGuestService implements Disposable {
@log() @log()
static async connect(api: LiveShare, container: Container) { static async connect(api: LiveShare, container: Container) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
const service = await api.getSharedService(VslsHostService.ServiceId); const service = await api.getSharedService(VslsHostService.ServiceId);
@ -20,7 +20,7 @@ export class VslsGuestService implements Disposable {
return new VslsGuestService(api, service, container); return new VslsGuestService(api, service, container);
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
return undefined; return undefined;
} }
} }

+ 5
- 5
src/vsls/host.ts View File

@ -3,7 +3,7 @@ import { git } from '@env/providers';
import type { LiveShare, SharedService } from '../@types/vsls'; import type { LiveShare, SharedService } from '../@types/vsls';
import { Container } from '../container'; import { Container } from '../container';
import { Logger } from '../logger'; import { Logger } from '../logger';
import { debug, log } from '../system/decorators/log';
import { debug, getLogScope, log } from '../system/decorators/log';
import { join } from '../system/iterable'; import { join } from '../system/iterable';
import { isVslsRoot, normalizePath } from '../system/path'; import { isVslsRoot, normalizePath } from '../system/path';
import { import {
@ -103,7 +103,7 @@ export class VslsHostService implements Disposable {
private onWorkspaceFoldersChanged(_e?: WorkspaceFoldersChangeEvent) { private onWorkspaceFoldersChanged(_e?: WorkspaceFoldersChangeEvent) {
if (workspace.workspaceFolders == null || workspace.workspaceFolders.length === 0) return; if (workspace.workspaceFolders == null || workspace.workspaceFolders.length === 0) return;
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
this._localToSharedPaths.clear(); this._localToSharedPaths.clear();
this._sharedToLocalPaths.clear(); this._sharedToLocalPaths.clear();
@ -114,7 +114,7 @@ export class VslsHostService implements Disposable {
localPath = normalizePath(f.uri.fsPath); localPath = normalizePath(f.uri.fsPath);
sharedPath = normalizePath(this.convertLocalUriToShared(f.uri).toString()); sharedPath = normalizePath(this.convertLocalUriToShared(f.uri).toString());
Logger.debug(cc, `shared='${sharedPath}' \u2194 local='${localPath}'`);
Logger.debug(scope, `shared='${sharedPath}' \u2194 local='${localPath}'`);
this._localToSharedPaths.set(localPath, sharedPath); this._localToSharedPaths.set(localPath, sharedPath);
this._sharedToLocalPaths.set(sharedPath, localPath); this._sharedToLocalPaths.set(sharedPath, localPath);
} }
@ -233,11 +233,11 @@ export class VslsHostService implements Disposable {
exit: result => `returned ${result.toString(true)}`, exit: result => `returned ${result.toString(true)}`,
}) })
private convertLocalUriToShared(localUri: Uri) { private convertLocalUriToShared(localUri: Uri) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
let sharedUri = this._api.convertLocalUriToShared(localUri); let sharedUri = this._api.convertLocalUriToShared(localUri);
Logger.debug( Logger.debug(
cc,
scope,
`LiveShare.convertLocalUriToShared(${localUri.toString(true)}) returned ${sharedUri.toString(true)}`, `LiveShare.convertLocalUriToShared(${localUri.toString(true)}) returned ${sharedUri.toString(true)}`,
); );

+ 3
- 3
src/webviews/webviewViewBase.ts View File

@ -15,7 +15,7 @@ import { Commands } from '../constants';
import type { Container } from '../container'; import type { Container } from '../container';
import { Logger } from '../logger'; import { Logger } from '../logger';
import { executeCommand } from '../system/command'; import { executeCommand } from '../system/command';
import { log } from '../system/decorators/log';
import { getLogScope, log } from '../system/decorators/log';
import { import {
ExecuteCommandType, ExecuteCommandType,
IpcMessage, IpcMessage,
@ -85,12 +85,12 @@ export abstract class WebviewViewBase implements WebviewViewProvider, Dis
@log() @log()
async show(options?: { preserveFocus?: boolean }) { async show(options?: { preserveFocus?: boolean }) {
const cc = Logger.getCorrelationContext();
const scope = getLogScope();
try { try {
void (await executeCommand(`${this.id}.focus`, options)); void (await executeCommand(`${this.id}.focus`, options));
} catch (ex) { } catch (ex) {
Logger.error(ex, cc);
Logger.error(ex, scope);
} }
} }

Loading…
Cancel
Save