diff --git a/.eslintrc.json b/.eslintrc.json index cb7352f..1fc5152 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -111,7 +111,43 @@ "newlines-between": "never" } ], - "@typescript-eslint/ban-types": "off", // TODO@eamodio revisit + "@typescript-eslint/ban-types": [ + "error", + { + "extendDefaults": false, + "types": { + "String": { + "message": "Use string instead", + "fixWith": "string" + }, + "Boolean": { + "message": "Use boolean instead", + "fixWith": "boolean" + }, + "Number": { + "message": "Use number instead", + "fixWith": "number" + }, + "Symbol": { + "message": "Use symbol instead", + "fixWith": "symbol" + }, + "Function": { + "message": "The `Function` type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with `new`.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape." + }, + "Object": { + "message": "The `Object` type actually means \"any non-nullish value\", so it is marginally better than `unknown`.\n- If you want a type meaning \"any object\", you probably want `Record` instead.\n- If you want a type meaning \"any value\", you probably want `unknown` instead." + }, + "{}": { + "message": "`{}` actually means \"any non-nullish value\".\n- If you want a type meaning \"any object\", you probably want `object` or `Record` instead.\n- If you want a type meaning \"any value\", you probably want `unknown` instead.", + "fixWith": "object" + } + // "object": { + // "message": "The `object` type is currently hard to use ([see this issue](https://github.com/microsoft/TypeScript/issues/21732)).\nConsider using `Record` instead, as it allows you to more easily inspect and use the keys." + // } + } + } + ], "@typescript-eslint/consistent-type-assertions": [ "error", { @@ -169,9 +205,9 @@ } ], "@typescript-eslint/no-empty-function": ["warn", { "allow": ["constructors"] }], - "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-empty-interface": "error", "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-floating-promises": "off", // TODO@eamodio revisit + "@typescript-eslint/no-floating-promises": "error", "@typescript-eslint/no-inferrable-types": ["warn", { "ignoreParameters": true, "ignoreProperties": true }], "@typescript-eslint/no-misused-promises": ["error", { "checksVoidReturn": false }], "@typescript-eslint/no-namespace": "off", diff --git a/generateEmojiShortcodeMap.js b/generateEmojiShortcodeMap.js index b5976df..a212d1b 100644 --- a/generateEmojiShortcodeMap.js +++ b/generateEmojiShortcodeMap.js @@ -5,7 +5,7 @@ const path = require('path'); async function generate() { /** - * @type {{ [code: string]: string }} + * @type {Record} */ let map = Object.create(null); @@ -77,7 +77,7 @@ async function generate() { } function download(url, destination) { - return new Promise((resolve, reject) => { + return new Promise(resolve => { const stream = fs.createWriteStream(destination); https.get(url, rsp => { rsp.pipe(stream); @@ -89,4 +89,4 @@ function download(url, destination) { }); } -generate(); +void generate(); diff --git a/src/annotations/annotationProvider.ts b/src/annotations/annotationProvider.ts index 1a6cab3..184baf0 100644 --- a/src/annotations/annotationProvider.ts +++ b/src/annotations/annotationProvider.ts @@ -10,7 +10,6 @@ import { Uri, window, } from 'vscode'; -import { TextDocumentComparer } from '../comparers'; import { FileAnnotationType } from '../configuration'; import { CommandContext, setCommandContext } from '../constants'; import { Functions } from '../system'; @@ -53,13 +52,13 @@ export abstract class AnnotationProviderBase implements Disposable { dispose() { this.clear(); - this.disposable && this.disposable.dispose(); + this.disposable.dispose(); } private onTextEditorSelectionChanged(e: TextEditorSelectionChangeEvent) { - if (!TextDocumentComparer.equals(this.document, e.textEditor && e.textEditor.document)) return; + if (this.document !== e.textEditor.document) return; - this.selection(e.selections[0].active.line); + void this.selection(e.selections[0].active.line); } get editorId(): string { @@ -147,10 +146,10 @@ export abstract class AnnotationProviderBase implements Disposable { this.correlationKey = AnnotationProviderBase.getCorrelationKey(editor); this.document = editor.document; - if (this.decorations !== undefined && this.decorations.length) { + if (this.decorations?.length) { this.editor.setDecorations(this.decoration, this.decorations); - if (this.additionalDecorations !== undefined && this.additionalDecorations.length) { + if (this.additionalDecorations?.length) { for (const d of this.additionalDecorations) { this.editor.setDecorations(d.decoration, d.ranges); } diff --git a/src/annotations/autolinks.ts b/src/annotations/autolinks.ts index 7a31154..a799637 100644 --- a/src/annotations/autolinks.ts +++ b/src/annotations/autolinks.ts @@ -204,11 +204,9 @@ export class Autolinks implements Disposable { `${superscript} ${ issue instanceof Promises.CancellationError ? 'Details timed out' - : issue - ? `${issue.title} ${GlyphChars.Dot} ${ + : `${issue.title} ${GlyphChars.Dot} ${ issue.closed ? 'Closed' : 'Opened' }, ${Dates.getFormatter(issue.closedDate ?? issue.date).fromNow()}` - : '' }`, ); return `${linkText}${superscript}`; diff --git a/src/annotations/blameAnnotationProvider.ts b/src/annotations/blameAnnotationProvider.ts index 923f47e..edfd32d 100644 --- a/src/annotations/blameAnnotationProvider.ts +++ b/src/annotations/blameAnnotationProvider.ts @@ -78,7 +78,7 @@ export abstract class BlameAnnotationProviderBase extends AnnotationProviderBase } else if (typeof shaOrLine === 'number') { if (shaOrLine >= 0) { const commitLine = blame.lines[shaOrLine]; - sha = commitLine && commitLine.sha; + sha = commitLine?.sha; } } else { sha = Iterables.first(blame.commits.values()).sha; @@ -211,7 +211,7 @@ export abstract class BlameAnnotationProviderBase extends AnnotationProviderBase async provideDetailsHover( document: TextDocument, position: Position, - token: CancellationToken, + _token: CancellationToken, ): Promise { const commit = await this.getCommitForHover(position); if (commit === undefined) return undefined; @@ -231,11 +231,11 @@ export abstract class BlameAnnotationProviderBase extends AnnotationProviderBase let editorLine = this.editor.selection.active.line; const line = editorLine + 1; - const commitLine = commit.lines.find(l => l.line === line) || commit.lines[0]; + const commitLine = commit.lines.find(l => l.line === line) ?? commit.lines[0]; editorLine = commitLine.originalLine - 1; const message = await Hovers.detailsMessage( - logCommit || commit, + logCommit ?? commit, await GitUri.fromUri(document.uri), editorLine, Container.config.defaultDateFormat, @@ -250,7 +250,7 @@ export abstract class BlameAnnotationProviderBase extends AnnotationProviderBase async provideChangesHover( document: TextDocument, position: Position, - token: CancellationToken, + _token: CancellationToken, ): Promise { const commit = await this.getCommitForHover(position); if (commit === undefined) return undefined; diff --git a/src/annotations/fileAnnotationController.ts b/src/annotations/fileAnnotationController.ts index fcb84e2..d73b811 100644 --- a/src/annotations/fileAnnotationController.ts +++ b/src/annotations/fileAnnotationController.ts @@ -68,7 +68,7 @@ export class FileAnnotationController implements Disposable { } private _annotationsDisposable: Disposable | undefined; - private _annotationProviders: Map = new Map(); + private _annotationProviders = new Map(); private _disposable: Disposable; private _editor: TextEditor | undefined; private _keyboardScope: KeyboardScope | undefined = undefined; @@ -78,7 +78,7 @@ export class FileAnnotationController implements Disposable { constructor() { this._disposable = Disposable.from(configuration.onDidChange(this.onConfigurationChanged, this)); - this._toggleModes = new Map(); + this._toggleModes = new Map(); this.onConfigurationChanged(configuration.initializingChangeEvent); } @@ -222,10 +222,10 @@ export class FileAnnotationController implements Disposable { const provider = this.getProvider(editor); if (provider === undefined) { - setCommandContext(CommandContext.AnnotationStatus, undefined); + void setCommandContext(CommandContext.AnnotationStatus, undefined); void this.detachKeyboardHook(); } else { - setCommandContext(CommandContext.AnnotationStatus, provider.status); + void setCommandContext(CommandContext.AnnotationStatus, provider.status); void this.attachKeyboardHook(); } } @@ -294,7 +294,7 @@ export class FileAnnotationController implements Disposable { private getToggleMode(annotationType: FileAnnotationType | undefined): AnnotationsToggleMode { if (annotationType === undefined) return AnnotationsToggleMode.File; - return this._toggleModes.get(annotationType) || AnnotationsToggleMode.File; + return this._toggleModes.get(annotationType) ?? AnnotationsToggleMode.File; } clear(editor: TextEditor, reason: AnnotationClearReason = AnnotationClearReason.User) { @@ -381,7 +381,7 @@ export class FileAnnotationController implements Disposable { const provider = await computingAnnotations; if (editor === this._editor) { - await setCommandContext(CommandContext.AnnotationStatus, provider && provider.status); + await setCommandContext(CommandContext.AnnotationStatus, provider?.status); } return computingAnnotations; diff --git a/src/annotations/gutterBlameAnnotationProvider.ts b/src/annotations/gutterBlameAnnotationProvider.ts index 7eeeaf0..e60ff2e 100644 --- a/src/annotations/gutterBlameAnnotationProvider.ts +++ b/src/annotations/gutterBlameAnnotationProvider.ts @@ -11,7 +11,7 @@ import { BlameAnnotationProviderBase } from './blameAnnotationProvider'; export class GutterBlameAnnotationProvider extends BlameAnnotationProviderBase { @log() - async onProvideAnnotation(shaOrLine?: string | number, type?: FileAnnotationType): Promise { + async onProvideAnnotation(_shaOrLine?: string | number, _type?: FileAnnotationType): Promise { const cc = Logger.getCorrelationContext(); this.annotationType = FileAnnotationType.Blame; @@ -48,10 +48,10 @@ export class GutterBlameAnnotationProvider extends BlameAnnotationProviderBase { const renderOptions = Annotations.gutterRenderOptions(separateLines, cfg.heatmap, cfg.format, options); this.decorations = []; - const decorationsMap: { [sha: string]: DecorationOptions | undefined } = Object.create(null); - const avatarDecorationsMap: - | { [email: string]: { decoration: TextEditorDecorationType; ranges: Range[] } } - | undefined = avatars ? Object.create(null) : undefined; + const decorationsMap = Object.create(null) as Record; + const avatarDecorationsMap = avatars + ? (Object.create(null) as Record) + : undefined; let commit: GitBlameCommit | undefined; let compacted = false; @@ -167,7 +167,7 @@ export class GutterBlameAnnotationProvider extends BlameAnnotationProviderBase { commit: GitBlameCommit, range: Range, gravatarDefault: GravatarDefaultStyle, - map: { [email: string]: { decoration: TextEditorDecorationType; ranges: Range[] } }, + map: Record, ) { const avatarDecoration = map[commit.email!]; if (avatarDecoration !== undefined) { diff --git a/src/annotations/heatmapBlameAnnotationProvider.ts b/src/annotations/heatmapBlameAnnotationProvider.ts index 138b9b6..62b87b8 100644 --- a/src/annotations/heatmapBlameAnnotationProvider.ts +++ b/src/annotations/heatmapBlameAnnotationProvider.ts @@ -10,7 +10,7 @@ import { BlameAnnotationProviderBase } from './blameAnnotationProvider'; export class HeatmapBlameAnnotationProvider extends BlameAnnotationProviderBase { @log() - async onProvideAnnotation(shaOrLine?: string | number, type?: FileAnnotationType): Promise { + async onProvideAnnotation(_shaOrLine?: string | number, _type?: FileAnnotationType): Promise { const cc = Logger.getCorrelationContext(); this.annotationType = FileAnnotationType.Heatmap; @@ -23,7 +23,7 @@ export class HeatmapBlameAnnotationProvider extends BlameAnnotationProviderBase const renderOptions = Annotations.heatmapRenderOptions(); this.decorations = []; - const decorationsMap: { [sha: string]: DecorationOptions | undefined } = Object.create(null); + const decorationsMap = Object.create(null) as Record; let commit: GitBlameCommit | undefined; let heatmap: DecorationOptions | undefined; diff --git a/src/annotations/lineAnnotationController.ts b/src/annotations/lineAnnotationController.ts index 7fac720..cab0a66 100644 --- a/src/annotations/lineAnnotationController.ts +++ b/src/annotations/lineAnnotationController.ts @@ -27,7 +27,7 @@ const annotationDecoration: TextEditorDecorationType = window.createTextEditorDe }); export class LineAnnotationController implements Disposable { - private _disposable: Disposable; + private readonly _disposable: Disposable; private _editor: TextEditor | undefined; private _enabled: boolean = false; @@ -43,7 +43,7 @@ export class LineAnnotationController implements Disposable { this.clearAnnotations(this._editor); Container.lineTracker.stop(this); - this._disposable && this._disposable.dispose(); + this._disposable.dispose(); } private onConfigurationChanged(e: ConfigurationChangeEvent) { @@ -284,14 +284,14 @@ export class LineAnnotationController implements Disposable { cc, `${GlyphChars.Dot} pull request queries (${timeouts.length}) took too long (over ${timeout} ms)`, ); - Promise.all(timeouts).then(() => { + void Promise.all(timeouts).then(() => { if (editor === this._editor) { Logger.debug( cc, `${GlyphChars.Dot} pull request queries (${timeouts.length}) completed; refreshing...`, ); - this.refresh(editor); + void this.refresh(editor); } }); } diff --git a/src/annotations/recentChangesAnnotationProvider.ts b/src/annotations/recentChangesAnnotationProvider.ts index b797af6..8241772 100644 --- a/src/annotations/recentChangesAnnotationProvider.ts +++ b/src/annotations/recentChangesAnnotationProvider.ts @@ -132,7 +132,7 @@ export class RecentChangesAnnotationProvider extends AnnotationProviderBase { return true; } - selection(shaOrLine?: string | number): Promise { + selection(_shaOrLine?: string | number): Promise { return Promise.resolve(undefined); } diff --git a/src/avatars.ts b/src/avatars.ts index efea093..90b183e 100644 --- a/src/avatars.ts +++ b/src/avatars.ts @@ -36,7 +36,7 @@ export function getAvatarUri(email: string | undefined, fallback: GravatarDefaul if (avatar !== undefined) return avatar; avatar = - getAvatarUriFromGitHubNoReplyAddress(email, size) || + getAvatarUriFromGitHubNoReplyAddress(email, size) ?? Uri.parse(`https://www.gravatar.com/avatar/${hash}.jpg?s=${size}&d=${fallback}`); avatarCache.set(key, avatar); diff --git a/src/codelens/codeLensController.ts b/src/codelens/codeLensController.ts index 8a79800..3b1aa14 100644 --- a/src/codelens/codeLensController.ts +++ b/src/codelens/codeLensController.ts @@ -47,7 +47,7 @@ export class GitCodeLensController implements Disposable { } this._canToggle = cfg.recentChange.enabled || cfg.authors.enabled; - setCommandContext(CommandContext.CanToggleCodeLens, this._canToggle); + void setCommandContext(CommandContext.CanToggleCodeLens, this._canToggle); } } diff --git a/src/codelens/codeLensProvider.ts b/src/codelens/codeLensProvider.ts index eb65ef9..683a5ce 100644 --- a/src/codelens/codeLensProvider.ts +++ b/src/codelens/codeLensProvider.ts @@ -100,7 +100,7 @@ export class GitCodeLensProvider implements CodeLensProvider { private readonly _tracker: DocumentTracker, ) {} - reset(reason?: 'idle' | 'saved') { + reset(_reason?: 'idle' | 'saved') { this._onDidChangeCodeLenses.fire(); } @@ -352,7 +352,7 @@ export class GitCodeLensProvider implements CodeLensProvider { break; } - return valid ? range || getRangeFromSymbol(symbol) : undefined; + return valid ? range ?? getRangeFromSymbol(symbol) : undefined; } private provideCodeLens( @@ -471,7 +471,7 @@ export class GitCodeLensProvider implements CodeLensProvider { return Promise.reject(undefined); } - private resolveGitRecentChangeCodeLens(lens: GitRecentChangeCodeLens, token: CancellationToken): CodeLens { + private resolveGitRecentChangeCodeLens(lens: GitRecentChangeCodeLens, _token: CancellationToken): CodeLens { const blame = lens.getBlame(); if (blame === undefined) return lens; @@ -490,7 +490,7 @@ export class GitCodeLensProvider implements CodeLensProvider { })]`; } - if (!lens.desiredCommand) { + if (lens.desiredCommand === false) { return this.applyCommandWithNoClickAction(title, lens); } @@ -516,7 +516,7 @@ export class GitCodeLensProvider implements CodeLensProvider { } } - private resolveGitAuthorsCodeLens(lens: GitAuthorsCodeLens, token: CancellationToken): CodeLens { + private resolveGitAuthorsCodeLens(lens: GitAuthorsCodeLens, _token: CancellationToken): CodeLens { const blame = lens.getBlame(); if (blame === undefined) return lens; @@ -538,12 +538,12 @@ export class GitCodeLensProvider implements CodeLensProvider { )})]`; } - if (!lens.desiredCommand) { + if (lens.desiredCommand === false) { return this.applyCommandWithNoClickAction(title, lens); } const commit = - Iterables.find(blame.commits.values(), c => c.author === author) || Iterables.first(blame.commits.values()); + Iterables.find(blame.commits.values(), c => c.author === author) ?? Iterables.first(blame.commits.values()); switch (lens.desiredCommand) { case CodeLensCommand.DiffWithPrevious: @@ -594,7 +594,7 @@ export class GitCodeLensProvider implements CodeLensProvider { }; lens.command = { title: title, - command: commit !== undefined && commit.isUncommitted ? '' : CodeLensCommand.RevealCommitInView, + command: commit?.isUncommitted ? '' : CodeLensCommand.RevealCommitInView, arguments: [lens.uri!.toFileUri(), commandArgs], }; return lens; @@ -636,7 +636,7 @@ export class GitCodeLensProvider implements CodeLensProvider { }; lens.command = { title: title, - command: commit !== undefined && commit.isUncommitted ? '' : CodeLensCommand.ShowQuickCommitDetails, + command: commit?.isUncommitted ? '' : CodeLensCommand.ShowQuickCommitDetails, arguments: [lens.uri!.toFileUri(), commandArgs], }; return lens; @@ -653,7 +653,7 @@ export class GitCodeLensProvider implements CodeLensProvider { }; lens.command = { title: title, - command: commit !== undefined && commit.isUncommitted ? '' : CodeLensCommand.ShowQuickCommitFileDetails, + command: commit?.isUncommitted ? '' : CodeLensCommand.ShowQuickCommitFileDetails, arguments: [lens.uri!.toFileUri(), commandArgs], }; return lens; diff --git a/src/commands/browseRepoAtRevision.ts b/src/commands/browseRepoAtRevision.ts index 16e1772..1304f3a 100644 --- a/src/commands/browseRepoAtRevision.ts +++ b/src/commands/browseRepoAtRevision.ts @@ -54,7 +54,7 @@ export class BrowseRepoAtRevisionCommand extends ActiveEditorCommand { } } catch (ex) { Logger.error(ex, 'BrowseRepoAtRevisionCommand'); - Messages.showGenericErrorMessage('Unable to open the repository at the specified revision'); + void Messages.showGenericErrorMessage('Unable to open the repository at the specified revision'); } } } diff --git a/src/commands/closeUnchangedFiles.ts b/src/commands/closeUnchangedFiles.ts index 0aae8ea..4b93db9 100644 --- a/src/commands/closeUnchangedFiles.ts +++ b/src/commands/closeUnchangedFiles.ts @@ -30,7 +30,7 @@ export class CloseUnchangedFilesCommand extends Command { const status = await Container.git.getStatusForRepo(repoPath); if (status == null) { - window.showWarningMessage('Unable to close unchanged files'); + void window.showWarningMessage('Unable to close unchanged files'); return; } @@ -86,12 +86,9 @@ export class CloseUnchangedFilesCommand extends Command { for (let i = 0; i <= count; i++) { if ( editor == null || - (editor.document !== undefined && - (editor.document.isDirty || - // eslint-disable-next-line no-loop-func - args.uris.some(uri => - UriComparer.equals(uri, editor!.document && editor!.document.uri), - ))) + editor.document.isDirty || + // eslint-disable-next-line no-loop-func + args.uris.some(uri => UriComparer.equals(uri, editor?.document.uri)) ) { editor = await this.nextEditor(); } else { @@ -103,7 +100,7 @@ export class CloseUnchangedFilesCommand extends Command { disposable.dispose(); } catch (ex) { Logger.error(ex, 'CloseUnchangedFilesCommand'); - Messages.showGenericErrorMessage('Unable to close all unchanged files'); + void Messages.showGenericErrorMessage('Unable to close all unchanged files'); } } @@ -132,7 +129,7 @@ export class CloseUnchangedFilesCommand extends Command { } private waitForEditorChange(timeout: number = 500): Promise { - return new Promise((resolve, reject) => { + return new Promise(resolve => { let timer: NodeJS.Timer | undefined; this._onEditorChangedFn = (editor: TextEditor | undefined) => { diff --git a/src/commands/common.ts b/src/commands/common.ts index 16182a8..9cb4e91 100644 --- a/src/commands/common.ts +++ b/src/commands/common.ts @@ -338,7 +338,7 @@ export abstract class Command implements Disposable { protected readonly contextParsingOptions: CommandContextParsingOptions = { editor: false, uri: false }; - private _disposable: Disposable; + private readonly _disposable: Disposable; constructor(command: Commands | Commands[]) { if (typeof command === 'string') { @@ -358,7 +358,7 @@ export abstract class Command implements Disposable { } dispose() { - this._disposable && this._disposable.dispose(); + this._disposable.dispose(); } protected preExecute(context: CommandContext, ...args: any[]): Promise { @@ -483,7 +483,7 @@ export abstract class ActiveEditorCachedCommand extends ActiveEditorCommand { } export abstract class EditorCommand implements Disposable { - private _disposable: Disposable; + private readonly _disposable: Disposable; constructor(command: Commands | Commands[]) { if (!Array.isArray(command)) { @@ -505,7 +505,7 @@ export abstract class EditorCommand implements Disposable { } dispose() { - this._disposable && this._disposable.dispose(); + this._disposable.dispose(); } private executeCore(command: string, editor: TextEditor, edit: TextEditorEdit, ...args: any[]): any { @@ -570,7 +570,7 @@ export async function openEditor( ...opts, }); } catch (ex) { - const msg = ex.toString(); + const msg: string = ex?.toString() ?? ''; if (msg.includes('File seems to be binary and cannot be opened as text')) { await commands.executeCommand(BuiltInCommands.Open, uri); @@ -586,7 +586,7 @@ export async function openEditor( export function openWorkspace(uri: Uri, name: string, options: { openInNewWindow?: boolean } = {}) { if (options.openInNewWindow) { - commands.executeCommand(BuiltInCommands.OpenFolder, uri, true); + void commands.executeCommand(BuiltInCommands.OpenFolder, uri, true); return true; } diff --git a/src/commands/copyMessageToClipboard.ts b/src/commands/copyMessageToClipboard.ts index e031d45..3842c28 100644 --- a/src/commands/copyMessageToClipboard.ts +++ b/src/commands/copyMessageToClipboard.ts @@ -72,7 +72,7 @@ export class CopyMessageToClipboardCommand extends ActiveEditorCommand { } } catch (ex) { Logger.error(ex, 'CopyMessageToClipboardCommand', `getBlameForLine(${blameline})`); - Messages.showGenericErrorMessage('Unable to copy message'); + void Messages.showGenericErrorMessage('Unable to copy message'); return; } @@ -87,8 +87,9 @@ export class CopyMessageToClipboardCommand extends ActiveEditorCommand { void (await env.clipboard.writeText(args.message)); } catch (ex) { - if (ex.message.includes("Couldn't find the required `xsel` binary")) { - window.showErrorMessage( + const msg: string = ex?.message ?? ''; + if (msg.includes("Couldn't find the required `xsel` binary")) { + void window.showErrorMessage( 'Unable to copy message, xsel is not installed. Please install it via your package manager, e.g. `sudo apt install xsel`', ); @@ -96,7 +97,7 @@ export class CopyMessageToClipboardCommand extends ActiveEditorCommand { } Logger.error(ex, 'CopyMessageToClipboardCommand'); - Messages.showGenericErrorMessage('Unable to copy message'); + void Messages.showGenericErrorMessage('Unable to copy message'); } } } diff --git a/src/commands/copyShaToClipboard.ts b/src/commands/copyShaToClipboard.ts index e864512..163d30f 100644 --- a/src/commands/copyShaToClipboard.ts +++ b/src/commands/copyShaToClipboard.ts @@ -62,7 +62,7 @@ export class CopyShaToClipboardCommand extends ActiveEditorCommand { args.sha = blame.commit.sha; } catch (ex) { Logger.error(ex, 'CopyShaToClipboardCommand', `getBlameForLine(${blameline})`); - Messages.showGenericErrorMessage('Unable to copy commit id'); + void Messages.showGenericErrorMessage('Unable to copy commit id'); return; } @@ -70,8 +70,9 @@ export class CopyShaToClipboardCommand extends ActiveEditorCommand { void (await env.clipboard.writeText(args.sha)); } catch (ex) { - if (ex.message.includes("Couldn't find the required `xsel` binary")) { - window.showErrorMessage( + const msg: string = ex?.message ?? ''; + if (msg.includes("Couldn't find the required `xsel` binary")) { + void window.showErrorMessage( 'Unable to copy commit id, xsel is not installed. Please install it via your package manager, e.g. `sudo apt install xsel`', ); @@ -79,7 +80,7 @@ export class CopyShaToClipboardCommand extends ActiveEditorCommand { } Logger.error(ex, 'CopyShaToClipboardCommand'); - Messages.showGenericErrorMessage('Unable to copy commit id'); + void Messages.showGenericErrorMessage('Unable to copy commit id'); } } } diff --git a/src/commands/diffBranchWith.ts b/src/commands/diffBranchWith.ts index 1c6c0a1..0fdf53d 100644 --- a/src/commands/diffBranchWith.ts +++ b/src/commands/diffBranchWith.ts @@ -86,7 +86,7 @@ export class DiffBranchWithCommand extends ActiveEditorCommand { void (await Container.compareView.compare(repoPath, args.ref1, args.ref2)); } catch (ex) { Logger.error(ex, 'DiffBranchWithCommand'); - Messages.showGenericErrorMessage('Unable to open branch compare'); + void Messages.showGenericErrorMessage('Unable to open branch compare'); } } } diff --git a/src/commands/diffLineWithPrevious.ts b/src/commands/diffLineWithPrevious.ts index 3f2eb0d..d0e3f92 100644 --- a/src/commands/diffLineWithPrevious.ts +++ b/src/commands/diffLineWithPrevious.ts @@ -41,7 +41,7 @@ export class DiffLineWithPreviousCommand extends ActiveEditorCommand { ); if (diffUris == null || diffUris.previous == null) { - Messages.showCommitHasNoPreviousCommitWarningMessage(); + void Messages.showCommitHasNoPreviousCommitWarningMessage(); return; } @@ -49,11 +49,11 @@ export class DiffLineWithPreviousCommand extends ActiveEditorCommand { void (await executeCommand(Commands.DiffWith, { repoPath: diffUris.current.repoPath, lhs: { - sha: diffUris.previous.sha || '', + sha: diffUris.previous.sha ?? '', uri: diffUris.previous.documentUri(), }, rhs: { - sha: diffUris.current.sha || '', + sha: diffUris.current.sha ?? '', uri: diffUris.current.documentUri(), }, line: diffUris.line, @@ -65,7 +65,7 @@ export class DiffLineWithPreviousCommand extends ActiveEditorCommand { 'DiffLineWithPreviousCommand', `getPreviousLineDiffUris(${gitUri.repoPath}, ${gitUri.fsPath}, ${gitUri.sha})`, ); - Messages.showGenericErrorMessage('Unable to open compare'); + void Messages.showGenericErrorMessage('Unable to open compare'); } } } diff --git a/src/commands/diffLineWithWorking.ts b/src/commands/diffLineWithWorking.ts index d0884cb..de7b1a9 100644 --- a/src/commands/diffLineWithWorking.ts +++ b/src/commands/diffLineWithWorking.ts @@ -41,7 +41,7 @@ export class DiffLineWithWorkingCommand extends ActiveEditorCommand { ? await Container.git.getBlameForLineContents(gitUri, blameline, editor.document.getText()) : await Container.git.getBlameForLine(gitUri, blameline); if (blame == null) { - Messages.showFileNotUnderSourceControlWarningMessage('Unable to open compare'); + void Messages.showFileNotUnderSourceControlWarningMessage('Unable to open compare'); return; } @@ -63,7 +63,7 @@ export class DiffLineWithWorkingCommand extends ActiveEditorCommand { } } catch (ex) { Logger.error(ex, 'DiffLineWithWorkingCommand', `getBlameForLine(${blameline})`); - Messages.showGenericErrorMessage('Unable to open compare'); + void Messages.showGenericErrorMessage('Unable to open compare'); return; } @@ -71,7 +71,7 @@ export class DiffLineWithWorkingCommand extends ActiveEditorCommand { const workingUri = await args.commit.getWorkingUri(); if (workingUri == null) { - window.showWarningMessage('Unable to open compare. File has been deleted from the working tree'); + void window.showWarningMessage('Unable to open compare. File has been deleted from the working tree'); return; } diff --git a/src/commands/diffWith.ts b/src/commands/diffWith.ts index 9b745d4..710302e 100644 --- a/src/commands/diffWith.ts +++ b/src/commands/diffWith.ts @@ -148,7 +148,7 @@ export class DiffWithCommand extends Command { const title = args.lhs.title != null && args.rhs.title != null ? `${args.lhs.title} ${GlyphChars.ArrowLeftRightLong} ${args.rhs.title}` - : args.lhs.title || args.rhs.title; + : args.lhs.title ?? args.rhs.title; if (args.showOptions == null) { args.showOptions = {}; @@ -171,7 +171,7 @@ export class DiffWithCommand extends Command { )); } catch (ex) { Logger.error(ex, 'DiffWithCommand', 'getVersionedFile'); - Messages.showGenericErrorMessage('Unable to open compare'); + void Messages.showGenericErrorMessage('Unable to open compare'); } } } diff --git a/src/commands/diffWithNext.ts b/src/commands/diffWithNext.ts index e94f5d3..979252a 100644 --- a/src/commands/diffWithNext.ts +++ b/src/commands/diffWithNext.ts @@ -56,11 +56,11 @@ export class DiffWithNextCommand extends ActiveEditorCommand { void (await executeCommand(Commands.DiffWith, { repoPath: diffUris.current.repoPath, lhs: { - sha: diffUris.current.sha || '', + sha: diffUris.current.sha ?? '', uri: diffUris.current.documentUri(), }, rhs: { - sha: diffUris.next.sha || '', + sha: diffUris.next.sha ?? '', uri: diffUris.next.documentUri(), }, line: args.line, @@ -72,7 +72,7 @@ export class DiffWithNextCommand extends ActiveEditorCommand { 'DiffWithNextCommand', `getNextDiffUris(${gitUri.repoPath}, ${gitUri.fsPath}, ${gitUri.sha})`, ); - Messages.showGenericErrorMessage('Unable to open compare'); + void Messages.showGenericErrorMessage('Unable to open compare'); } } } diff --git a/src/commands/diffWithPrevious.ts b/src/commands/diffWithPrevious.ts index 0142280..5f26381 100644 --- a/src/commands/diffWithPrevious.ts +++ b/src/commands/diffWithPrevious.ts @@ -93,7 +93,7 @@ export class DiffWithPreviousCommand extends ActiveEditorCommand { if (diffUris == null || diffUris.previous == null) { if (diffUris == null) { - Messages.showCommitHasNoPreviousCommitWarningMessage(); + void Messages.showCommitHasNoPreviousCommitWarningMessage(); return; } @@ -106,7 +106,7 @@ export class DiffWithPreviousCommand extends ActiveEditorCommand { } if (!diffUris.current.isUncommittedStaged) { - Messages.showCommitHasNoPreviousCommitWarningMessage(); + void Messages.showCommitHasNoPreviousCommitWarningMessage(); return; } @@ -122,11 +122,11 @@ export class DiffWithPreviousCommand extends ActiveEditorCommand { void (await executeCommand(Commands.DiffWith, { repoPath: diffUris.current.repoPath, lhs: { - sha: diffUris.previous.sha || '', + sha: diffUris.previous.sha ?? '', uri: diffUris.previous.documentUri(), }, rhs: { - sha: diffUris.current.sha || '', + sha: diffUris.current.sha ?? '', uri: diffUris.current.documentUri(), }, line: args.line, @@ -138,7 +138,7 @@ export class DiffWithPreviousCommand extends ActiveEditorCommand { 'DiffWithPreviousCommand', `getPreviousDiffUris(${gitUri.repoPath}, ${gitUri.fsPath}, ${gitUri.sha})`, ); - Messages.showGenericErrorMessage('Unable to open compare'); + void Messages.showGenericErrorMessage('Unable to open compare'); } } } diff --git a/src/commands/diffWithRevision.ts b/src/commands/diffWithRevision.ts index 7d0cf16..3936285 100644 --- a/src/commands/diffWithRevision.ts +++ b/src/commands/diffWithRevision.ts @@ -90,7 +90,7 @@ export class DiffWithRevisionCommand extends ActiveEditorCommand { })); } catch (ex) { Logger.error(ex, 'DiffWithRevisionCommand'); - Messages.showGenericErrorMessage('Unable to open compare'); + void Messages.showGenericErrorMessage('Unable to open compare'); } } } diff --git a/src/commands/diffWithRevisionFrom.ts b/src/commands/diffWithRevisionFrom.ts index aa4bdb3..166f9c8 100644 --- a/src/commands/diffWithRevisionFrom.ts +++ b/src/commands/diffWithRevisionFrom.ts @@ -28,7 +28,7 @@ export class DiffWithRevisionFromCommand extends ActiveEditorCommand { const gitUri = await GitUri.fromUri(uri); if (!gitUri.repoPath) { - Messages.showNoRepositoryWarningMessage('Unable to open file compare'); + void Messages.showNoRepositoryWarningMessage('Unable to open file compare'); return; } @@ -71,7 +71,7 @@ export class DiffWithRevisionFromCommand extends ActiveEditorCommand { lhs: { sha: GitReference.isBranch(pick) && pick.remote ? `remotes/${ref}` : ref, uri: renamedUri ?? gitUri, - title: renamedTitle || `${paths.basename(gitUri.fsPath)} (${GitRevision.shorten(ref)})`, + title: renamedTitle ?? `${paths.basename(gitUri.fsPath)} (${GitRevision.shorten(ref)})`, }, rhs: { sha: '', diff --git a/src/commands/diffWithWorking.ts b/src/commands/diffWithWorking.ts index c1b3ecd..5183ca1 100644 --- a/src/commands/diffWithWorking.ts +++ b/src/commands/diffWithWorking.ts @@ -54,7 +54,7 @@ export class DiffWithWorkingCommand extends ActiveEditorCommand { 'DiffWithWorkingCommand', `getPreviousDiffUris(${gitUri.repoPath}, ${gitUri.fsPath}, ${gitUri.sha})`, ); - Messages.showGenericErrorMessage('Unable to open compare'); + void Messages.showGenericErrorMessage('Unable to open compare'); return; } @@ -63,12 +63,12 @@ export class DiffWithWorkingCommand extends ActiveEditorCommand { // if (args.commit == null || args.commit.isUncommitted) { // If the sha is missing, just let the user know the file matches if (gitUri.sha == null) { - window.showInformationMessage('File matches the working tree'); + void window.showInformationMessage('File matches the working tree'); return; } if (gitUri.sha === GitRevision.deletedOrMissing) { - window.showWarningMessage('Unable to open compare. File has been deleted from the working tree'); + void window.showWarningMessage('Unable to open compare. File has been deleted from the working tree'); return; } @@ -99,7 +99,7 @@ export class DiffWithWorkingCommand extends ActiveEditorCommand { const workingUri = await Container.git.getWorkingUri(gitUri.repoPath!, uri); if (workingUri == null) { - window.showWarningMessage('Unable to open compare. File has been deleted from the working tree'); + void window.showWarningMessage('Unable to open compare. File has been deleted from the working tree'); return; } diff --git a/src/commands/externalDiff.ts b/src/commands/externalDiff.ts index dceee7a..9ab5807 100644 --- a/src/commands/externalDiff.ts +++ b/src/commands/externalDiff.ts @@ -164,7 +164,7 @@ export class ExternalDiffCommand extends Command { const uri = editor.document.uri; const status = await Container.git.getStatusForFile(repoPath, uri.fsPath); if (status == null) { - window.showInformationMessage("The current file doesn't have any changes"); + void window.showInformationMessage("The current file doesn't have any changes"); return; } @@ -207,7 +207,7 @@ export class ExternalDiffCommand extends Command { } } catch (ex) { Logger.error(ex, 'ExternalDiffCommand'); - Messages.showGenericErrorMessage('Unable to open changes in diff tool'); + void Messages.showGenericErrorMessage('Unable to open changes in diff tool'); } } } diff --git a/src/commands/git/branch.ts b/src/commands/git/branch.ts index 562c536..09cfcb0 100644 --- a/src/commands/git/branch.ts +++ b/src/commands/git/branch.ts @@ -158,7 +158,7 @@ export class BranchGitCommand extends QuickCommand { if (state.counter < 1 || state.subcommand == null) { this.subcommand = undefined; - const result = yield* this.pickSubcommandStep(state, context); + const result = yield* this.pickSubcommandStep(state); // Always break on the first step (so we will go back) if (result === StepResult.Break) break; @@ -211,10 +211,7 @@ export class BranchGitCommand extends QuickCommand { return state.counter < 0 ? StepResult.Break : undefined; } - private *pickSubcommandStep( - state: PartialStepState, - context: Context, - ): StepResultGenerator { + private *pickSubcommandStep(state: PartialStepState): StepResultGenerator { const step = QuickCommand.createPickStep>({ title: this.title, placeholder: `Choose a ${this.label} command`, diff --git a/src/commands/git/cherry-pick.ts b/src/commands/git/cherry-pick.ts index 1e2606e..3f37eb9 100644 --- a/src/commands/git/cherry-pick.ts +++ b/src/commands/git/cherry-pick.ts @@ -81,7 +81,7 @@ export class CherryPickGitCommand extends QuickCommand { protected async *steps(state: PartialStepState): StepGenerator { const context: Context = { repos: [...(await Container.git.getOrderedRepositories())], - cache: new Map(), + cache: new Map>(), destination: undefined!, selectedBranchOrTag: undefined, showTags: true, diff --git a/src/commands/git/coauthors.ts b/src/commands/git/coauthors.ts index cd0940f..615c044 100644 --- a/src/commands/git/coauthors.ts +++ b/src/commands/git/coauthors.ts @@ -159,7 +159,7 @@ export class CoAuthorsGitCommand extends QuickCommand { } QuickCommand.endSteps(state); - this.execute(state as CoAuthorStepState); + void this.execute(state as CoAuthorStepState); } return state.counter < 0 ? StepResult.Break : undefined; diff --git a/src/commands/git/fetch.ts b/src/commands/git/fetch.ts index 8d74452..e2457e1 100644 --- a/src/commands/git/fetch.ts +++ b/src/commands/git/fetch.ts @@ -115,7 +115,7 @@ export class FetchGitCommand extends QuickCommand { } QuickCommand.endSteps(state); - this.execute(state as FetchStepState); + void this.execute(state as FetchStepState); } return state.counter < 0 ? StepResult.Break : undefined; diff --git a/src/commands/git/log.ts b/src/commands/git/log.ts index bf7920f..fcbf7b0 100644 --- a/src/commands/git/log.ts +++ b/src/commands/git/log.ts @@ -77,7 +77,7 @@ export class LogGitCommand extends QuickCommand { protected async *steps(state: PartialStepState): StepGenerator { const context: Context = { repos: [...(await Container.git.getOrderedRepositories())], - cache: new Map(), + cache: new Map>(), selectedBranchOrTag: undefined, title: this.title, }; diff --git a/src/commands/git/merge.ts b/src/commands/git/merge.ts index 4544580..d4de3c8 100644 --- a/src/commands/git/merge.ts +++ b/src/commands/git/merge.ts @@ -77,7 +77,7 @@ export class MergeGitCommand extends QuickCommand { protected async *steps(state: PartialStepState): StepGenerator { const context: Context = { repos: [...(await Container.git.getOrderedRepositories())], - cache: new Map(), + cache: new Map>(), destination: undefined!, pickCommit: false, selectedBranchOrTag: undefined, @@ -192,7 +192,7 @@ export class MergeGitCommand extends QuickCommand { const count = (await Container.git.getCommitCount(state.repo.path, [ GitRevision.createRange(context.destination.name, state.reference.name), - ])) || 0; + ])) ?? 0; if (count === 0) { const step: QuickPickStep = this.createConfirmStep( appendReposToTitle(`Confirm ${context.title}`, state, context), diff --git a/src/commands/git/pull.ts b/src/commands/git/pull.ts index 5433b8c..7cd52f7 100644 --- a/src/commands/git/pull.ts +++ b/src/commands/git/pull.ts @@ -115,7 +115,7 @@ export class PullGitCommand extends QuickCommand { } QuickCommand.endSteps(state); - this.execute(state as PullStepState); + void this.execute(state as PullStepState); } return state.counter < 0 ? StepResult.Break : undefined; diff --git a/src/commands/git/push.ts b/src/commands/git/push.ts index 4daa4a5..5445dad 100644 --- a/src/commands/git/push.ts +++ b/src/commands/git/push.ts @@ -116,7 +116,7 @@ export class PushGitCommand extends QuickCommand { } QuickCommand.endSteps(state); - this.execute(state as State); + void this.execute(state as State); } return state.counter < 0 ? StepResult.Break : undefined; diff --git a/src/commands/git/rebase.ts b/src/commands/git/rebase.ts index 0238860..ab3549f 100644 --- a/src/commands/git/rebase.ts +++ b/src/commands/git/rebase.ts @@ -78,7 +78,7 @@ export class RebaseGitCommand extends QuickCommand { protected async *steps(state: PartialStepState): StepGenerator { const context: Context = { repos: [...(await Container.git.getOrderedRepositories())], - cache: new Map(), + cache: new Map>(), destination: undefined!, pickCommit: false, selectedBranchOrTag: undefined, @@ -193,7 +193,7 @@ export class RebaseGitCommand extends QuickCommand { const count = (await Container.git.getCommitCount(state.repo.path, [ GitRevision.createRange(state.reference.ref, context.destination.ref), - ])) || 0; + ])) ?? 0; if (count === 0) { const step: QuickPickStep = this.createConfirmStep( appendReposToTitle(`Confirm ${context.title}`, state, context), diff --git a/src/commands/git/reset.ts b/src/commands/git/reset.ts index 78bbf7f..46242d5 100644 --- a/src/commands/git/reset.ts +++ b/src/commands/git/reset.ts @@ -69,7 +69,7 @@ export class ResetGitCommand extends QuickCommand { protected async *steps(state: PartialStepState): StepGenerator { const context: Context = { repos: [...(await Container.git.getOrderedRepositories())], - cache: new Map(), + cache: new Map>(), destination: undefined!, title: this.title, }; diff --git a/src/commands/git/revert.ts b/src/commands/git/revert.ts index 22dea82..f9a48e2 100644 --- a/src/commands/git/revert.ts +++ b/src/commands/git/revert.ts @@ -71,7 +71,7 @@ export class RevertGitCommand extends QuickCommand { protected async *steps(state: PartialStepState): StepGenerator { const context: Context = { repos: [...(await Container.git.getOrderedRepositories())], - cache: new Map(), + cache: new Map>(), destination: undefined!, title: this.title, }; diff --git a/src/commands/git/show.ts b/src/commands/git/show.ts index 83b2a82..f7b4a27 100644 --- a/src/commands/git/show.ts +++ b/src/commands/git/show.ts @@ -1,6 +1,6 @@ 'use strict'; import { Container } from '../../container'; -import { GitLogCommit, GitRevisionReference, GitStashCommit, Repository } from '../../git/git'; +import { GitAuthor, GitLogCommit, GitRevisionReference, GitStashCommit, Repository } from '../../git/git'; import { PartialStepState, pickCommitStep, @@ -112,8 +112,8 @@ export class ShowGitCommand extends QuickCommand { const result = yield* pickCommitStep(state as ShowStepState, context, { log: { repoPath: state.repo.path, - authors: new Map(), - commits: new Map(), + authors: new Map(), + commits: new Map(), sha: undefined, range: undefined, count: 0, @@ -153,7 +153,7 @@ export class ShowGitCommand extends QuickCommand { if (result instanceof CommandQuickPickItem && !(result instanceof CommitFilesQuickPickItem)) { QuickCommand.endSteps(state); - result.execute(); + void result.execute(); break; } } @@ -201,7 +201,7 @@ export class ShowGitCommand extends QuickCommand { if (result instanceof CommandQuickPickItem) { QuickCommand.endSteps(state); - result.execute(); + void result.execute(); break; } } diff --git a/src/commands/git/stash.ts b/src/commands/git/stash.ts index 1c4e1c6..c06c433 100644 --- a/src/commands/git/stash.ts +++ b/src/commands/git/stash.ts @@ -151,7 +151,7 @@ export class StashGitCommand extends QuickCommand { if (state.counter < 1 || state.subcommand == null) { this.subcommand = undefined; - const result = yield* this.pickSubcommandStep(state, context); + const result = yield* this.pickSubcommandStep(state); // Always break on the first step (so we will go back) if (result === StepResult.Break) break; @@ -204,10 +204,7 @@ export class StashGitCommand extends QuickCommand { return state.counter < 0 ? StepResult.Break : undefined; } - private *pickSubcommandStep( - state: PartialStepState, - context: Context, - ): StepResultGenerator { + private *pickSubcommandStep(state: PartialStepState): StepResultGenerator { const step = QuickCommand.createPickStep>({ title: this.title, placeholder: `Choose a ${this.label} command`, @@ -285,7 +282,8 @@ export class StashGitCommand extends QuickCommand { } catch (ex) { Logger.error(ex, context.title); - if (ex.message.includes('Your local changes to the following files would be overwritten by merge')) { + const msg: string = ex?.message ?? ''; + if (msg.includes('Your local changes to the following files would be overwritten by merge')) { void window.showWarningMessage( 'Unable to apply stash. Your working tree changes would be overwritten. Please commit or stash your changes before trying again', ); @@ -294,9 +292,11 @@ export class StashGitCommand extends QuickCommand { } if ( - (ex.message.includes('Auto-merging') && ex.message.includes('CONFLICT')) || - (ex.stdout?.includes('Auto-merging') && ex.stdout?.includes('CONFLICT')) || - ex.stdout?.includes('needs merge') + (msg.includes('Auto-merging') && msg.includes('CONFLICT')) || + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions + (ex?.stdout?.includes('Auto-merging') && ex?.stdout?.includes('CONFLICT')) || + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions + ex?.stdout?.includes('needs merge') ) { void window.showInformationMessage('Stash applied with conflicts'); @@ -304,7 +304,7 @@ export class StashGitCommand extends QuickCommand { } void Messages.showGenericErrorMessage( - `Unable to apply stash \u2014 ${ex.message.trim().replace(/\n+?/g, '; ')}`, + `Unable to apply stash \u2014 ${msg.trim().replace(/\n+?/g, '; ')}`, ); return; @@ -489,8 +489,9 @@ export class StashGitCommand extends QuickCommand { } catch (ex) { Logger.error(ex, context.title); - if (ex.message.includes('newer version of Git')) { - void window.showErrorMessage(`Unable to stash changes. ${ex.message}`); + const msg: string = ex?.toString() ?? ''; + if (msg.includes('newer version of Git')) { + void window.showErrorMessage(`Unable to stash changes. ${msg}`); return; } diff --git a/src/commands/git/status.ts b/src/commands/git/status.ts index 0d125a9..06f6e1b 100644 --- a/src/commands/git/status.ts +++ b/src/commands/git/status.ts @@ -115,7 +115,7 @@ export class StatusGitCommand extends QuickCommand { if (result instanceof CommandQuickPickItem) { QuickCommand.endSteps(state); - result.execute(); + void result.execute(); break; } } diff --git a/src/commands/git/switch.ts b/src/commands/git/switch.ts index e2854a1..414064f 100644 --- a/src/commands/git/switch.ts +++ b/src/commands/git/switch.ts @@ -165,7 +165,7 @@ export class SwitchGitCommand extends QuickCommand { } QuickCommand.endSteps(state); - this.execute(state as SwitchStepState); + void this.execute(state as SwitchStepState); } return state.counter < 0 ? StepResult.Break : undefined; diff --git a/src/commands/git/tag.ts b/src/commands/git/tag.ts index 47ba24d..ad7be60 100644 --- a/src/commands/git/tag.ts +++ b/src/commands/git/tag.ts @@ -137,7 +137,7 @@ export class TagGitCommand extends QuickCommand { if (state.counter < 1 || state.subcommand == null) { this.subcommand = undefined; - const result = yield* this.pickSubcommandStep(state, context); + const result = yield* this.pickSubcommandStep(state); // Always break on the first step (so we will go back) if (result === StepResult.Break) break; @@ -186,10 +186,7 @@ export class TagGitCommand extends QuickCommand { return state.counter < 0 ? StepResult.Break : undefined; } - private *pickSubcommandStep( - state: PartialStepState, - context: Context, - ): StepResultGenerator { + private *pickSubcommandStep(state: PartialStepState): StepResultGenerator { const step = QuickCommand.createPickStep>({ title: this.title, placeholder: `Choose a ${this.label} command`, diff --git a/src/commands/gitCommands.actions.ts b/src/commands/gitCommands.actions.ts index 5fe2d45..95f7cdb 100644 --- a/src/commands/gitCommands.actions.ts +++ b/src/commands/gitCommands.actions.ts @@ -786,7 +786,7 @@ export namespace GitActions { } for (const file of files) { - openChangesWithDiffTool(file, ref!); + void openChangesWithDiffTool(file, ref!); } } @@ -927,7 +927,7 @@ export namespace GitActions { } } - Container.git.openDiffTool( + void Container.git.openDiffTool( commitOrRef.repoPath, GitUri.fromFile(file, file.repoPath ?? commitOrRef.repoPath), { @@ -990,7 +990,7 @@ export namespace GitActions { try { void (await Container.git.openDirectoryCompare(ref.repoPath, ref.ref, `${ref.ref}^`)); } catch (ex) { - const msg = ex && ex.toString(); + const msg: string = ex?.toString() ?? ''; if (msg === 'No diff tool found') { const result = await window.showWarningMessage( 'Unable to open directory compare because there is no Git diff tool configured', @@ -1011,7 +1011,7 @@ export namespace GitActions { try { void (await Container.git.openDirectoryCompare(ref.repoPath, ref.ref, undefined)); } catch (ex) { - const msg = ex && ex.toString(); + const msg: string = ex?.toString() ?? ''; if (msg === 'No diff tool found') { const result = await window.showWarningMessage( 'Unable to open directory compare because there is no Git diff tool configured', diff --git a/src/commands/gitCommands.ts b/src/commands/gitCommands.ts index a85309f..4e14463 100644 --- a/src/commands/gitCommands.ts +++ b/src/commands/gitCommands.ts @@ -127,7 +127,7 @@ export class GitCommandsCommand extends Command { if (command?.canConfirm) { if (command.canSkipConfirm) { - const willConfirmToggle = new QuickCommandButtons.WillConfirmToggle(command.confirm(), async input => { + const willConfirmToggle = new QuickCommandButtons.WillConfirmToggle(command.confirm(), async () => { if (command?.skipConfirmKey == null) return; const skipConfirmations = configuration.get('gitCommands', 'skipConfirmations') ?? []; @@ -204,14 +204,14 @@ export class GitCommandsCommand extends Command { } const scope = Container.keyboard.createScope(mapping); - scope.start(); + void scope.start(); disposables.push( scope, input.onDidHide(() => resolve()), input.onDidTriggerButton(async e => { if (e === QuickInputButtons.Back) { - goBack(); + void goBack(); return; } @@ -348,7 +348,7 @@ export class GitCommandsCommand extends Command { } const scope = Container.keyboard.createScope(mapping); - scope.start(); + void scope.start(); let overrideItems = false; @@ -358,14 +358,14 @@ export class GitCommandsCommand extends Command { quickpick.onDidTriggerButton(async e => { if (e === QuickInputButtons.Back) { - goBack(); + void goBack(); return; } if (e === QuickCommandButtons.WillConfirmForced) return; if (e === QuickCommandButtons.LoadMore) { - loadMore(); + void loadMore(); return; } @@ -522,11 +522,11 @@ export class GitCommandsCommand extends Command { return; case Directive.Back: - goBack(); + void goBack(); return; case Directive.LoadMore: - loadMore(); + void loadMore(); return; } } diff --git a/src/commands/inviteToLiveShare.ts b/src/commands/inviteToLiveShare.ts index 67fb09e..bca91bb 100644 --- a/src/commands/inviteToLiveShare.ts +++ b/src/commands/inviteToLiveShare.ts @@ -31,7 +31,7 @@ export class InviteToLiveShareCommand extends Command { } async execute(args?: InviteToLiveShareCommandArgs) { - if (args != null && args.email) { + if (args?.email) { const contact = await Container.vsls.getContact(args.email); if (contact != null) { return contact.invite(); diff --git a/src/commands/openBranchOnRemote.ts b/src/commands/openBranchOnRemote.ts index 5b0121d..d92e8df 100644 --- a/src/commands/openBranchOnRemote.ts +++ b/src/commands/openBranchOnRemote.ts @@ -70,7 +70,9 @@ export class OpenBranchOnRemoteCommand extends ActiveEditorCommand { })); } catch (ex) { Logger.error(ex, 'OpenBranchOnRemoteCommand'); - window.showErrorMessage('Unable to open branch on remote provider. See output channel for more details'); + void window.showErrorMessage( + 'Unable to open branch on remote provider. See output channel for more details', + ); } } } diff --git a/src/commands/openBranchesOnRemote.ts b/src/commands/openBranchesOnRemote.ts index 492e874..3cae92c 100644 --- a/src/commands/openBranchesOnRemote.ts +++ b/src/commands/openBranchesOnRemote.ts @@ -52,7 +52,9 @@ export class OpenBranchesOnRemoteCommand extends ActiveEditorCommand { })); } catch (ex) { Logger.error(ex, 'OpenBranchesOnRemoteCommand'); - window.showErrorMessage('Unable to open branches on remote provider. See output channel for more details'); + void window.showErrorMessage( + 'Unable to open branches on remote provider. See output channel for more details', + ); } } } diff --git a/src/commands/openChangedFiles.ts b/src/commands/openChangedFiles.ts index c73173d..a4f3a10 100644 --- a/src/commands/openChangedFiles.ts +++ b/src/commands/openChangedFiles.ts @@ -26,7 +26,7 @@ export class OpenChangedFilesCommand extends Command { const status = await Container.git.getStatusForRepo(repoPath); if (status == null) { - window.showWarningMessage('Unable to open changed files'); + void window.showWarningMessage('Unable to open changed files'); return; } @@ -39,7 +39,7 @@ export class OpenChangedFilesCommand extends Command { } } catch (ex) { Logger.error(ex, 'OpenChangedFilesCommand'); - Messages.showGenericErrorMessage('Unable to open all changed files'); + void Messages.showGenericErrorMessage('Unable to open all changed files'); } } } diff --git a/src/commands/openCommitOnRemote.ts b/src/commands/openCommitOnRemote.ts index 82682f7..3e81913 100644 --- a/src/commands/openCommitOnRemote.ts +++ b/src/commands/openCommitOnRemote.ts @@ -62,7 +62,9 @@ export class OpenCommitOnRemoteCommand extends ActiveEditorCommand { ? await Container.git.getBlameForLineContents(gitUri, blameline, editor.document.getText()) : await Container.git.getBlameForLine(gitUri, blameline); if (blame == null) { - Messages.showFileNotUnderSourceControlWarningMessage('Unable to open commit on remote provider'); + void Messages.showFileNotUnderSourceControlWarningMessage( + 'Unable to open commit on remote provider', + ); return; } @@ -91,7 +93,9 @@ export class OpenCommitOnRemoteCommand extends ActiveEditorCommand { })); } catch (ex) { Logger.error(ex, 'OpenCommitOnRemoteCommand'); - window.showErrorMessage('Unable to open commit on remote provider. See output channel for more details'); + void window.showErrorMessage( + 'Unable to open commit on remote provider. See output channel for more details', + ); } } } diff --git a/src/commands/openDirectoryCompare.ts b/src/commands/openDirectoryCompare.ts index e075b77..d7fbde7 100644 --- a/src/commands/openDirectoryCompare.ts +++ b/src/commands/openDirectoryCompare.ts @@ -84,7 +84,7 @@ export class OpenDirectoryCompareCommand extends ActiveEditorCommand { void Container.git.openDirectoryCompare(repoPath, args.ref1, args.ref2); } catch (ex) { - const msg = ex && ex.toString(); + const msg: string = ex?.toString() ?? ''; if (msg === 'No diff tool found') { const result = await window.showWarningMessage( 'Unable to open directory compare because there is no Git diff tool configured', @@ -100,7 +100,7 @@ export class OpenDirectoryCompareCommand extends ActiveEditorCommand { } Logger.error(ex, 'DiffDirectoryCommand'); - Messages.showGenericErrorMessage('Unable to open directory compare'); + void Messages.showGenericErrorMessage('Unable to open directory compare'); } } } diff --git a/src/commands/openFileAtRevision.ts b/src/commands/openFileAtRevision.ts index 6bc304c..1fe41c4 100644 --- a/src/commands/openFileAtRevision.ts +++ b/src/commands/openFileAtRevision.ts @@ -112,7 +112,7 @@ export class OpenFileAtRevisionCommand extends ActiveEditorCommand { })); } catch (ex) { Logger.error(ex, 'OpenFileAtRevisionCommand'); - Messages.showGenericErrorMessage('Unable to open file at revision'); + void Messages.showGenericErrorMessage('Unable to open file at revision'); } } } diff --git a/src/commands/openFileAtRevisionFrom.ts b/src/commands/openFileAtRevisionFrom.ts index 164366f..0d0b485 100644 --- a/src/commands/openFileAtRevisionFrom.ts +++ b/src/commands/openFileAtRevisionFrom.ts @@ -30,7 +30,7 @@ export class OpenFileAtRevisionFromCommand extends ActiveEditorCommand { const gitUri = await GitUri.fromUri(uri); if (!gitUri.repoPath) { - Messages.showNoRepositoryWarningMessage('Unable to open file revision'); + void Messages.showNoRepositoryWarningMessage('Unable to open file revision'); return; } diff --git a/src/commands/openFileOnRemote.ts b/src/commands/openFileOnRemote.ts index ff0a7b0..a85ee9b 100644 --- a/src/commands/openFileOnRemote.ts +++ b/src/commands/openFileOnRemote.ts @@ -68,7 +68,7 @@ export class OpenFileOnRemoteCommand extends ActiveEditorCommand { editor.selection.end.with({ line: editor.selection.end.line + 1 }), ) : undefined; - let sha = args.sha || gitUri.sha; + let sha = args.sha ?? gitUri.sha; if (args.branch == null && sha != null && !GitRevision.isSha(sha) && remotes.length !== 0) { const [remoteName, branchName] = Strings.splitSingle(sha, '/'); @@ -116,7 +116,7 @@ export class OpenFileOnRemoteCommand extends ActiveEditorCommand { })); } catch (ex) { Logger.error(ex, 'OpenFileOnRemoteCommand'); - window.showErrorMessage('Unable to open file on remote provider. See output channel for more details'); + void window.showErrorMessage('Unable to open file on remote provider. See output channel for more details'); } } } diff --git a/src/commands/openOnRemote.ts b/src/commands/openOnRemote.ts index 41bc75a..664820e 100644 --- a/src/commands/openOnRemote.ts +++ b/src/commands/openOnRemote.ts @@ -130,7 +130,7 @@ export class OpenOnRemoteCommand extends Command { void (await pick?.execute()); } catch (ex) { Logger.error(ex, 'OpenOnRemoteCommand'); - Messages.showGenericErrorMessage('Unable to open in remote provider'); + void Messages.showGenericErrorMessage('Unable to open in remote provider'); } } } diff --git a/src/commands/openRepoOnRemote.ts b/src/commands/openRepoOnRemote.ts index c5b3159..21134be 100644 --- a/src/commands/openRepoOnRemote.ts +++ b/src/commands/openRepoOnRemote.ts @@ -52,7 +52,7 @@ export class OpenRepoOnRemoteCommand extends ActiveEditorCommand { })); } catch (ex) { Logger.error(ex, 'OpenRepoOnRemoteCommand'); - window.showErrorMessage( + void window.showErrorMessage( 'Unable to open repository on remote provider. See output channel for more details', ); } diff --git a/src/commands/openRevisionFile.ts b/src/commands/openRevisionFile.ts index 5093cd7..8ad4634 100644 --- a/src/commands/openRevisionFile.ts +++ b/src/commands/openRevisionFile.ts @@ -54,7 +54,7 @@ export class OpenRevisionFileCommand extends ActiveEditorCommand { })); } catch (ex) { Logger.error(ex, 'OpenRevisionFileCommand'); - Messages.showGenericErrorMessage('Unable to open file revision'); + void Messages.showGenericErrorMessage('Unable to open file revision'); } } } diff --git a/src/commands/openWorkingFile.ts b/src/commands/openWorkingFile.ts index 6334fb0..63a2743 100644 --- a/src/commands/openWorkingFile.ts +++ b/src/commands/openWorkingFile.ts @@ -38,7 +38,7 @@ export class OpenWorkingFileCommand extends ActiveEditorCommand { if (GitUri.is(args.uri) && args.uri.sha) { const workingUri = await Container.git.getWorkingUri(args.uri.repoPath!, args.uri); if (workingUri === undefined) { - window.showWarningMessage( + void window.showWarningMessage( 'Unable to open working file. File could not be found in the working tree', ); @@ -61,7 +61,7 @@ export class OpenWorkingFileCommand extends ActiveEditorCommand { void (await Container.fileAnnotations.show(e, args.annotationType, args.line)); } catch (ex) { Logger.error(ex, 'OpenWorkingFileCommand'); - Messages.showGenericErrorMessage('Unable to open working file'); + void Messages.showGenericErrorMessage('Unable to open working file'); } } } diff --git a/src/commands/quickCommand.steps.ts b/src/commands/quickCommand.steps.ts index f0d7337..4f26ba3 100644 --- a/src/commands/quickCommand.steps.ts +++ b/src/commands/quickCommand.steps.ts @@ -380,7 +380,7 @@ export async function* pickBranchStep< } }, keys: ['right', 'alt+right', 'ctrl+right'], - onDidPressKey: async (quickpick, key) => { + onDidPressKey: async quickpick => { if (quickpick.activeItems.length === 0) return; await Container.repositoriesView.revealBranch(quickpick.activeItems[0].item, { @@ -445,7 +445,7 @@ export async function* pickBranchesStep< } }, keys: ['right', 'alt+right', 'ctrl+right'], - onDidPressKey: async (quickpick, key) => { + onDidPressKey: async quickpick => { if (quickpick.activeItems.length === 0) return; await Container.repositoriesView.revealBranch(quickpick.activeItems[0].item, { @@ -558,7 +558,7 @@ export async function* pickBranchOrTagStep< } }, keys: ['right', 'alt+right', 'ctrl+right'], - onDidPressKey: (quickpick, key) => { + onDidPressKey: quickpick => { if (quickpick.activeItems.length === 0) return; const item = quickpick.activeItems[0].item; @@ -674,7 +674,7 @@ export async function* pickBranchOrTagStepMultiRepo< } }, keys: ['right', 'alt+right', 'ctrl+right'], - onDidPressKey: (quickpick, key) => { + onDidPressKey: quickpick => { if (quickpick.activeItems.length === 0) return; const item = quickpick.activeItems[0].item; @@ -1001,7 +1001,7 @@ export async function* pickRepositoryStep< } }, keys: ['right', 'alt+right', 'ctrl+right'], - onDidPressKey: (quickpick, key) => { + onDidPressKey: quickpick => { if (quickpick.activeItems.length === 0) return; void Container.repositoriesView.revealRepository(quickpick.activeItems[0].item.path, { @@ -1064,7 +1064,7 @@ export async function* pickRepositoriesStep< } }, keys: ['right', 'alt+right', 'ctrl+right'], - onDidPressKey: (quickpick, key) => { + onDidPressKey: quickpick => { if (quickpick.activeItems.length === 0) return; void Container.repositoriesView.revealRepository(quickpick.activeItems[0].item.path, { @@ -1153,7 +1153,7 @@ export function* pickStashStep< } }, keys: ['right', 'alt+right', 'ctrl+right'], - onDidPressKey: async (quickpick, key) => { + onDidPressKey: async quickpick => { if (quickpick.activeItems.length === 0) return; await Container.repositoriesView.revealStash(quickpick.activeItems[0].item, { @@ -1218,7 +1218,7 @@ export async function* pickTagsStep< } }, keys: ['right', 'alt+right', 'ctrl+right'], - onDidPressKey: async (quickpick, key) => { + onDidPressKey: async quickpick => { if (quickpick.activeItems.length === 0) return; await Container.repositoriesView.revealTag(quickpick.activeItems[0].item, { diff --git a/src/commands/quickCommand.ts b/src/commands/quickCommand.ts index bee529d..b55b39c 100644 --- a/src/commands/quickCommand.ts +++ b/src/commands/quickCommand.ts @@ -27,7 +27,7 @@ export function isQuickInputStep( return typeof step === 'object' && (step as QuickPickStep).items == null; } -export interface QuickPickStep { +export interface QuickPickStep { additionalButtons?: QuickInputButton[]; allowEmpty?: boolean; buttons?: QuickInputButton[]; @@ -73,7 +73,7 @@ export type StepSelection = T extends QuickPickStep ? string | Directive : never; export type PartialStepState = Partial & { counter: number; confirm?: boolean; startingStep?: number }; -export type StepState = T & { counter: number; confirm?: boolean; startingStep?: number }; +export type StepState> = T & { counter: number; confirm?: boolean; startingStep?: number }; export abstract class QuickCommand implements QuickPickItem { readonly description?: string; @@ -194,8 +194,8 @@ export abstract class QuickCommand implements QuickPickItem { return QuickCommand.createPickStep({ placeholder: `Confirm ${this.title}`, title: title, - items: [...confirmations, cancel || DirectiveQuickPickItem.create(Directive.Cancel)], - selectedItems: [confirmations.find(c => c.picked) || confirmations[0]], + items: [...confirmations, cancel ?? DirectiveQuickPickItem.create(Directive.Cancel)], + selectedItems: [confirmations.find(c => c.picked) ?? confirmations[0]], ...options, }); } @@ -223,7 +223,8 @@ export namespace QuickCommand { ) { if (!canStepContinue(step, state, value)) return false; - if (step.validate == null || (await step.validate(value))) { + const [valid] = (await step.validate?.(value)) ?? [true]; + if (valid) { state.counter++; return true; } @@ -238,7 +239,7 @@ export namespace QuickCommand { ): selection is StepItemType { if (!canStepContinue(step, state, selection)) return false; - if (step.validate == null || step.validate(selection)) { + if (step.validate?.(selection) ?? true) { state.counter++; return true; } @@ -282,8 +283,8 @@ export namespace QuickCommand { return createPickStep({ placeholder: `Confirm ${context.title}`, title: title, - items: [...confirmations, cancel || DirectiveQuickPickItem.create(Directive.Cancel)], - selectedItems: [confirmations.find(c => c.picked) || confirmations[0]], + items: [...confirmations, cancel ?? DirectiveQuickPickItem.create(Directive.Cancel)], + selectedItems: [confirmations.find(c => c.picked) ?? confirmations[0]], ...options, }); } diff --git a/src/commands/showQuickCommit.ts b/src/commands/showQuickCommit.ts index 19d46fc..1597756 100644 --- a/src/commands/showQuickCommit.ts +++ b/src/commands/showQuickCommit.ts @@ -71,14 +71,14 @@ export class ShowQuickCommitCommand extends ActiveEditorCachedCommand { try { const blame = await Container.git.getBlameForLine(gitUri, blameline); if (blame == null) { - Messages.showFileNotUnderSourceControlWarningMessage('Unable to show commit details'); + void Messages.showFileNotUnderSourceControlWarningMessage('Unable to show commit details'); return; } // Because the previous sha of an uncommitted file isn't trust worthy we just have to kick out if (blame.commit.isUncommitted) { - Messages.showLineUncommittedWarningMessage('Unable to show commit details'); + void Messages.showLineUncommittedWarningMessage('Unable to show commit details'); return; } @@ -89,7 +89,7 @@ export class ShowQuickCommitCommand extends ActiveEditorCachedCommand { args.commit = blame.commit; } catch (ex) { Logger.error(ex, 'ShowQuickCommitDetailsCommand', `getBlameForLine(${blameline})`); - Messages.showGenericErrorMessage('Unable to show commit details'); + void Messages.showGenericErrorMessage('Unable to show commit details'); return; } @@ -108,7 +108,7 @@ export class ShowQuickCommitCommand extends ActiveEditorCachedCommand { if (args.repoLog === undefined) { const log = await Container.git.getLog(repoPath!, { limit: 2, ref: args.sha }); if (log === undefined) { - Messages.showCommitNotFoundWarningMessage('Unable to show commit details'); + void Messages.showCommitNotFoundWarningMessage('Unable to show commit details'); return; } @@ -118,7 +118,7 @@ export class ShowQuickCommitCommand extends ActiveEditorCachedCommand { } if (args.commit === undefined) { - Messages.showCommitNotFoundWarningMessage('Unable to show commit details'); + void Messages.showCommitNotFoundWarningMessage('Unable to show commit details'); return; } @@ -142,7 +142,7 @@ export class ShowQuickCommitCommand extends ActiveEditorCachedCommand { })); } catch (ex) { Logger.error(ex, 'ShowQuickCommitDetailsCommand'); - Messages.showGenericErrorMessage('Unable to show commit details'); + void Messages.showGenericErrorMessage('Unable to show commit details'); } } } diff --git a/src/commands/showQuickCommitFile.ts b/src/commands/showQuickCommitFile.ts index 1497c8c..5da6ce6 100644 --- a/src/commands/showQuickCommitFile.ts +++ b/src/commands/showQuickCommitFile.ts @@ -75,14 +75,14 @@ export class ShowQuickCommitFileCommand extends ActiveEditorCachedCommand { try { const blame = await Container.git.getBlameForLine(gitUri, blameline); if (blame == null) { - Messages.showFileNotUnderSourceControlWarningMessage('Unable to show commit file details'); + void Messages.showFileNotUnderSourceControlWarningMessage('Unable to show commit file details'); return; } // Because the previous sha of an uncommitted file isn't trust worthy we just have to kick out if (blame.commit.isUncommitted) { - Messages.showLineUncommittedWarningMessage('Unable to show commit file details'); + void Messages.showLineUncommittedWarningMessage('Unable to show commit file details'); return; } @@ -92,7 +92,7 @@ export class ShowQuickCommitFileCommand extends ActiveEditorCachedCommand { args.commit = blame.commit; } catch (ex) { Logger.error(ex, 'ShowQuickCommitFileDetailsCommand', `getBlameForLine(${blameline})`); - window.showErrorMessage('Unable to show commit file details. See output channel for more details'); + void window.showErrorMessage('Unable to show commit file details. See output channel for more details'); return; } @@ -112,7 +112,7 @@ export class ShowQuickCommitFileCommand extends ActiveEditorCachedCommand { const repoPath = args.commit === undefined ? gitUri.repoPath : args.commit.repoPath; args.commit = await Container.git.getCommitForFile(repoPath, gitUri.fsPath, { ref: args.sha }); if (args.commit === undefined) { - Messages.showCommitNotFoundWarningMessage('Unable to show commit file details'); + void Messages.showCommitNotFoundWarningMessage('Unable to show commit file details'); return; } @@ -120,7 +120,7 @@ export class ShowQuickCommitFileCommand extends ActiveEditorCachedCommand { } if (args.commit === undefined) { - Messages.showCommitNotFoundWarningMessage('Unable to show commit file details'); + void Messages.showCommitNotFoundWarningMessage('Unable to show commit file details'); return; } @@ -182,7 +182,7 @@ export class ShowQuickCommitFileCommand extends ActiveEditorCachedCommand { // return undefined; } catch (ex) { Logger.error(ex, 'ShowQuickCommitFileDetailsCommand'); - Messages.showGenericErrorMessage('Unable to show commit file details'); + void Messages.showGenericErrorMessage('Unable to show commit file details'); } } } diff --git a/src/commands/showQuickRepoStatus.ts b/src/commands/showQuickRepoStatus.ts index 5cb0eb9..5fdf685 100644 --- a/src/commands/showQuickRepoStatus.ts +++ b/src/commands/showQuickRepoStatus.ts @@ -1,11 +1,6 @@ 'use strict'; import { executeGitCommand } from '../commands'; import { Command, command, Commands } from './common'; -import { CommandQuickPickItem } from '../quickpicks'; - -export interface ShowQuickRepoStatusCommandArgs { - goBackCommand?: CommandQuickPickItem; -} export interface ShowQuickRepoStatusCommandArgs { repoPath?: string; @@ -24,29 +19,5 @@ export class ShowQuickRepoStatusCommand extends Command { repo: args?.repoPath, }, }); - - // uri = getCommandUri(uri, editor); - - // try { - // const repoPath = await getRepoPathOrActiveOrPrompt( - // uri, - // editor, - // `Show status for which repository${GlyphChars.Ellipsis}`, - // ); - // if (!repoPath) return undefined; - - // const status = await Container.git.getStatusForRepo(repoPath); - // if (status === undefined) return window.showWarningMessage('Unable to show repository status'); - - // const pick = await RepoStatusQuickPick.show(status, args && args.goBackCommand); - // if (pick === undefined) return undefined; - - // if (pick instanceof CommandQuickPickItem) return pick.execute(); - - // return undefined; - // } catch (ex) { - // Logger.error(ex, 'ShowQuickRepoStatusCommand'); - // return Messages.showGenericErrorMessage('Unable to show repository status'); - // } } } diff --git a/src/commands/stashSave.ts b/src/commands/stashSave.ts index 47a6311..96847b3 100644 --- a/src/commands/stashSave.ts +++ b/src/commands/stashSave.ts @@ -34,7 +34,7 @@ export class StashSaveCommand extends Command { protected preExecute(context: CommandContext, args?: StashSaveCommandArgs) { if (isCommandViewContextWithFile(context)) { args = { ...args }; - args.repoPath = context.node.file.repoPath || context.node.repoPath; + args.repoPath = context.node.file.repoPath ?? context.node.repoPath; args.uris = [GitUri.fromFile(context.node.file, args.repoPath)]; } else if (isCommandViewContextWithRepo(context)) { args = { ...args }; diff --git a/src/commands/switchMode.ts b/src/commands/switchMode.ts index 8cc1682..7b15eff 100644 --- a/src/commands/switchMode.ts +++ b/src/commands/switchMode.ts @@ -21,7 +21,7 @@ export class SwitchModeCommand extends Command { if (pick === undefined) return; if (cc) { - cc.exitDetails = ` \u2014 mode=${pick.key || ''}`; + cc.exitDetails = ` \u2014 mode=${pick.key ?? ''}`; } const active = Container.config.mode.active; diff --git a/src/commands/toggleFileAnnotations.ts b/src/commands/toggleFileAnnotations.ts index 0552eb3..0459517 100644 --- a/src/commands/toggleFileAnnotations.ts +++ b/src/commands/toggleFileAnnotations.ts @@ -29,7 +29,7 @@ export class ClearFileAnnotationsCommand extends EditorCommand { void (await Container.fileAnnotations.clear(editor)); } catch (ex) { Logger.error(ex, 'ClearFileAnnotationsCommand'); - Messages.showGenericErrorMessage('Unable to clear file annotations'); + void Messages.showGenericErrorMessage('Unable to clear file annotations'); } } } @@ -110,6 +110,8 @@ async function toggleFileAnnotations( )); } catch (ex) { Logger.error(ex, 'ToggleFileAnnotationsCommand'); - window.showErrorMessage(`Unable to toggle file ${args.type} annotations. See output channel for more details`); + void window.showErrorMessage( + `Unable to toggle file ${args.type} annotations. See output channel for more details`, + ); } } diff --git a/src/commands/toggleLineBlame.ts b/src/commands/toggleLineBlame.ts index da407c2..f038268 100644 --- a/src/commands/toggleLineBlame.ts +++ b/src/commands/toggleLineBlame.ts @@ -9,12 +9,14 @@ export class ToggleLineBlameCommand extends ActiveEditorCommand { super(Commands.ToggleLineBlame); } - async execute(editor: TextEditor, uri?: Uri): Promise { + async execute(editor: TextEditor, _uri?: Uri): Promise { try { void (await Container.lineAnnotations.toggle(editor)); } catch (ex) { Logger.error(ex, 'ToggleLineBlameCommand'); - window.showErrorMessage('Unable to toggle line blame annotations. See output channel for more details'); + void window.showErrorMessage( + 'Unable to toggle line blame annotations. See output channel for more details', + ); } } } diff --git a/src/comparers.ts b/src/comparers.ts index a90ac4d..417f432 100644 --- a/src/comparers.ts +++ b/src/comparers.ts @@ -1,5 +1,5 @@ 'use strict'; -import { TextDocument, TextEditor, Uri } from 'vscode'; +import { TextEditor, Uri } from 'vscode'; abstract class Comparer { abstract equals(lhs: T, rhs: T): boolean; @@ -8,25 +8,15 @@ abstract class Comparer { class UriComparer extends Comparer { equals(lhs: Uri | undefined, rhs: Uri | undefined, options: { exact?: boolean } = { exact: false }) { if (lhs === rhs) return true; - if (lhs === undefined || rhs === undefined) return false; + if (lhs == null || rhs == null) return false; if (options.exact) { - return lhs.toString(true) === rhs.toString(true); + return lhs.toString() === rhs.toString(); } return lhs.scheme === rhs.scheme && lhs.fsPath === rhs.fsPath; } } -class TextDocumentComparer extends Comparer { - equals(lhs: TextDocument | undefined, rhs: TextDocument | undefined) { - return lhs === rhs; - // if (lhs === rhs) return true; - // if (lhs === undefined || rhs === undefined) return false; - - // return uriComparer.equals(lhs.uri, rhs.uri); - } -} - class TextEditorComparer extends Comparer { equals( lhs: TextEditor | undefined, @@ -34,25 +24,20 @@ class TextEditorComparer extends Comparer { options: { useId: boolean; usePosition: boolean } = { useId: false, usePosition: false }, ) { if (lhs === rhs) return true; - if (lhs === undefined || rhs === undefined) return false; + if (lhs == null || rhs == null) return false; if (options.usePosition && lhs.viewColumn !== rhs.viewColumn) return false; - if (options.useId && (!lhs.document || !rhs.document)) { + if (options.useId && (lhs.document != null || rhs.document != null)) { if ((lhs as any).id !== (rhs as any).id) return false; return true; } - return textDocumentComparer.equals(lhs.document, rhs.document); + return lhs.document === rhs.document; } } -const textDocumentComparer = new TextDocumentComparer(); const textEditorComparer = new TextEditorComparer(); const uriComparer = new UriComparer(); -export { - textDocumentComparer as TextDocumentComparer, - textEditorComparer as TextEditorComparer, - uriComparer as UriComparer, -}; +export { textEditorComparer as TextEditorComparer, uriComparer as UriComparer }; diff --git a/src/config.ts b/src/config.ts index 9aed67b..5ff58c7 100644 --- a/src/config.ts +++ b/src/config.ts @@ -90,7 +90,7 @@ export interface Config { alignment: 'left' | 'right'; }; }; - modes: { [key: string]: ModeConfig }; + modes: Record; outputLevel: TraceLevel; recentChanges: { highlight: { diff --git a/src/configuration.ts b/src/configuration.ts index 7f3c308..0ea633d 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -70,9 +70,7 @@ export class Configuration { this._onDidChange.fire(e); } - readonly initializingChangeEvent: ConfigurationChangeEvent = { - affectsConfiguration: (section: string, scope?: ConfigurationScope) => true, - }; + readonly initializingChangeEvent: ConfigurationChangeEvent = { affectsConfiguration: () => true }; get(): Config; get(s1: S1, scope?: ConfigurationScope | null, defaultValue?: Config[S1]): Config[S1]; diff --git a/src/constants.ts b/src/constants.ts index 93415d0..ca9c6ee 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -130,7 +130,7 @@ export enum GlobalState { GitLensVersion = 'gitlensVersion', } -export const ImageMimetypes: { [key: string]: string } = { +export const ImageMimetypes: Record = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', diff --git a/src/credentials.ts b/src/credentials.ts index df2a53a..6f58037 100644 --- a/src/credentials.ts +++ b/src/credentials.ts @@ -36,7 +36,8 @@ export namespace CredentialManager { const _onDidChange = new EventEmitter(); export const onDidChange: Event = _onDidChange.event; - export async function addOrUpdate(key: string, value: string | {}) { + export async function addOrUpdate(key: string, value: string | object) { + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!key || !value) return; if (keychain == null) { Logger.log('CredentialManager.addOrUpdate: No credential store found'); @@ -83,7 +84,7 @@ export namespace CredentialManager { } } - export async function getAs(key: string): Promise { + export async function getAs(key: string): Promise { const value = await get(key); if (value == null) return undefined; diff --git a/src/emojis.ts b/src/emojis.ts index c74541a..ae77bd1 100644 --- a/src/emojis.ts +++ b/src/emojis.ts @@ -1,7 +1,7 @@ 'use strict'; import * as emojis from './emojis.json'; -const emojiMap: { [key: string]: string } = (emojis as any).default; +const emojiMap = (emojis as any).default as Record; const emojiRegex = /:([-+_a-z0-9]+):/g; export function emojify(message: string) { diff --git a/src/extension.ts b/src/extension.ts index 525fe36..646cf96 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -17,7 +17,7 @@ export async function activate(context: ExtensionContext) { const start = process.hrtime(); // Pretend we are enabled (until we know otherwise) and set the view contexts to reduce flashing on load - setCommandContext(CommandContext.Enabled, true); + void setCommandContext(CommandContext.Enabled, true); Logger.configure(context, configuration.get('outputLevel'), o => { if (GitUri.is(o)) { @@ -39,7 +39,7 @@ export async function activate(context: ExtensionContext) { const enabled = workspace.getConfiguration('git', null).get('enabled', true); if (!enabled) { Logger.log(`GitLens (v${gitlensVersion}) was NOT activated -- "git.enabled": false`); - setCommandContext(CommandContext.Enabled, false); + void setCommandContext(CommandContext.Enabled, false); void Messages.showGitDisabledErrorMessage(); @@ -57,9 +57,10 @@ export async function activate(context: ExtensionContext) { await GitService.initialize(); } catch (ex) { Logger.error(ex, `GitLens (v${gitlensVersion}) activate`); - setCommandContext(CommandContext.Enabled, false); + void setCommandContext(CommandContext.Enabled, false); - if (ex.message.includes('Unable to find git')) { + const msg: string = ex?.message ?? ''; + if (msg.includes('Unable to find git')) { await window.showErrorMessage( "GitLens was unable to find Git. Please make sure Git is installed. Also ensure that Git is either in the PATH, or that 'git.path' is pointed to its installed location.", ); @@ -76,7 +77,7 @@ export async function activate(context: ExtensionContext) { // Telemetry.configure(ApplicationInsightsKey); - // const telemetryContext: { [id: string]: any } = Object.create(null); + // const telemetryContext: Record = Object.create(null); // telemetryContext.version = gitlensVersion; // telemetryContext['git.version'] = gitVersion; // Telemetry.setContext(telemetryContext); @@ -84,7 +85,7 @@ export async function activate(context: ExtensionContext) { notifyOnUnsupportedGitVersion(gitVersion); void showWelcomeOrWhatsNew(gitlensVersion, previousVersion); - context.globalState.update(GlobalState.GitLensVersion, gitlensVersion); + void context.globalState.update(GlobalState.GitLensVersion, gitlensVersion); // Constantly over my data cap so stop collecting initialized event // Telemetry.trackEvent('initialized', Objects.flatten(cfg, 'config', true)); diff --git a/src/git/formatters/commitFormatter.ts b/src/git/formatters/commitFormatter.ts index 3a1d281..c60644d 100644 --- a/src/git/formatters/commitFormatter.ts +++ b/src/git/formatters/commitFormatter.ts @@ -206,7 +206,7 @@ export class CommitFormatter extends Formatter { let commands; if (this._item.isUncommitted) { const { previousLineDiffUris: diffUris } = this._options; - if (diffUris != null && diffUris.previous != null) { + if (diffUris?.previous != null) { commands = `\`${this._padOrTruncate( GitRevision.shorten( GitRevision.isUncommittedStaged(diffUris.current.sha) @@ -218,11 +218,11 @@ export class CommitFormatter extends Formatter { commands += `  **[\`${GlyphChars.MuchLessThan}\`](${DiffWithCommand.getMarkdownCommandArgs({ lhs: { - sha: diffUris.previous.sha || emptyStr, + sha: diffUris.previous.sha ?? emptyStr, uri: diffUris.previous.documentUri(), }, rhs: { - sha: diffUris.current.sha || emptyStr, + sha: diffUris.current.sha ?? emptyStr, uri: diffUris.current.documentUri(), }, repoPath: this._item.repoPath, @@ -281,7 +281,7 @@ export class CommitFormatter extends Formatter { ); commands += `[$(history)](${OpenFileAtRevisionCommand.getMarkdownCommandArgs( uri, - annotationType || FileAnnotationType.Blame, + annotationType ?? FileAnnotationType.Blame, this._options.line, )} "Blame Previous Revision")${separator}`; } @@ -327,11 +327,11 @@ export class CommitFormatter extends Formatter { } get email() { - return this._padOrTruncate(this._item.email || emptyStr, this._options.tokenOptions.email); + return this._padOrTruncate(this._item.email ?? emptyStr, this._options.tokenOptions.email); } get id() { - return this._padOrTruncate(this._item.shortSha || emptyStr, this._options.tokenOptions.id); + return this._padOrTruncate(this._item.shortSha ?? emptyStr, this._options.tokenOptions.id); } get message() { diff --git a/src/git/formatters/formatter.ts b/src/git/formatters/formatter.ts index 4700913..21d2319 100644 --- a/src/git/formatters/formatter.ts +++ b/src/git/formatters/formatter.ts @@ -5,10 +5,10 @@ const emptyStr = ''; export interface FormatOptions { dateFormat?: string | null; - tokenOptions?: { [id: string]: Strings.TokenOptions | undefined }; + tokenOptions?: Record; } -type Constructor = new (...args: any[]) => T; +type Constructor> = new (...args: any[]) => T; const spaceReplacementRegex = / /g; @@ -87,7 +87,7 @@ export abstract class Formatter(); diff --git a/src/git/git.ts b/src/git/git.ts index db78283..27f2355 100644 --- a/src/git/git.ts +++ b/src/git/git.ts @@ -64,7 +64,7 @@ export interface GitCommandOptions extends RunOptions { } // A map of running git commands -- avoids running duplicate overlaping commands -const pendingCommands: Map> = new Map(); +const pendingCommands = new Map>(); export async function git(options: GitCommandOptions, ...args: any[]): Promise { if (Container.vsls.isMaybeGuest) { @@ -83,7 +83,7 @@ export async function git(options: GitCommandOptio const { configs, correlationKey, errors: errorHandling, ...opts } = options; - const encoding = options.encoding || 'utf8'; + const encoding = options.encoding ?? 'utf8'; const runOpts: RunOptions = { ...opts, encoding: encoding === 'utf8' ? 'utf8' : encoding === 'buffer' ? 'buffer' : 'binary', @@ -91,7 +91,7 @@ export async function git(options: GitCommandOptio // Shouldn't *really* be needed but better safe than sorry env: { ...process.env, - ...(options.env || emptyObj), + ...(options.env ?? emptyObj), GCM_INTERACTIVE: 'NEVER', GCM_PRESERVE_CREDS: 'TRUE', LC_ALL: 'C', @@ -188,11 +188,11 @@ function defaultExceptionHandler(ex: Error, cwd: string | undefined, start?: [nu } const match = GitErrors.badRevision.exec(msg); - if (match != null && match) { + if (match != null) { const [, ref] = match; // Since looking up a ref with ^3 (e.g. looking for untracked files in a stash) can error on some versions of git just ignore it - if (ref != null && ref.endsWith('^3')) return emptyStr; + if (ref?.endsWith('^3')) return emptyStr; } } @@ -361,7 +361,7 @@ export namespace Git { if (supported) { let ignoreRevsFile = params[index + 1]; if (!paths.isAbsolute(ignoreRevsFile)) { - ignoreRevsFile = paths.join(repoPath || '', ignoreRevsFile); + ignoreRevsFile = paths.join(repoPath ?? emptyStr, ignoreRevsFile); } const exists = ignoreRevsFileMap.get(ignoreRevsFile); @@ -460,7 +460,7 @@ export namespace Git { )); return ref; } catch (ex) { - const msg = ex && ex.toString(); + const msg: string = ex?.toString(); if (GitErrors.notAValidObjectName.test(msg)) { return GitRevision.deletedOrMissing; } @@ -507,7 +507,7 @@ export namespace Git { try { const data = await git( - { cwd: repoPath || emptyStr, errors: GitErrorHandling.Throw, local: true }, + { cwd: repoPath ?? emptyStr, errors: GitErrorHandling.Throw, local: true }, ...params, ref, ); @@ -540,7 +540,7 @@ export namespace Git { export async function config__get(key: string, repoPath?: string, options: { local?: boolean } = {}) { const data = await git( - { cwd: repoPath || emptyStr, errors: GitErrorHandling.Ignore, local: options.local }, + { cwd: repoPath ?? emptyStr, errors: GitErrorHandling.Ignore, local: options.local }, 'config', '--get', key, @@ -550,7 +550,7 @@ export namespace Git { export async function config__get_regex(pattern: string, repoPath?: string, options: { local?: boolean } = {}) { const data = await git( - { cwd: repoPath || emptyStr, errors: GitErrorHandling.Ignore, local: options.local }, + { cwd: repoPath ?? emptyStr, errors: GitErrorHandling.Ignore, local: options.local }, 'config', '--get-regex', pattern, @@ -1026,7 +1026,7 @@ export namespace Git { ); return [data, undefined]; } catch (ex) { - const msg = ex && ex.toString(); + const msg: string = ex?.toString() ?? ''; if (GitErrors.badRevision.test(msg) || GitWarnings.noUpstream.test(msg)) { return [ex.stdout, undefined]; } @@ -1095,7 +1095,7 @@ export namespace Git { const opts: GitCommandOptions = { configs: ['-c', 'log.showSignature=false'], cwd: root, - encoding: options.encoding || 'utf8', + encoding: options.encoding ?? 'utf8', errors: GitErrorHandling.Throw, }; const args = ref.endsWith(':') ? `${ref}./${file}` : `${ref}:./${file}`; @@ -1104,7 +1104,7 @@ export namespace Git { const data = await git(opts, 'show', args, '--'); return data; } catch (ex) { - const msg = ex && ex.toString(); + const msg: string = ex?.toString() ?? ''; if (ref === ':' && GitErrors.badRevision.test(msg)) { return Git.show(repoPath, fileName, 'HEAD:', options); } diff --git a/src/git/gitService.ts b/src/git/gitService.ts index d9a130a..3a66115 100644 --- a/src/git/gitService.ts +++ b/src/git/gitService.ts @@ -139,7 +139,7 @@ export class GitService implements Disposable { this._trackedCache.clear(); this._userMapCache.clear(); - this._disposable && this._disposable.dispose(); + this._disposable.dispose(); } @log() @@ -151,7 +151,7 @@ export class GitService implements Disposable { gitPath = gitApi.git.path; } - await Git.setOrFindGitPath(gitPath || configuration.getAny('git.path')); + await Git.setOrFindGitPath(gitPath ?? configuration.getAny('git.path')); } get readonly() { @@ -210,7 +210,7 @@ export class GitService implements Disposable { if (e == null) { initializing = true; e = { - added: workspace.workspaceFolders || [], + added: workspace.workspaceFolders ?? [], removed: [], }; @@ -314,8 +314,8 @@ export class GitService implements Disposable { // Get any specified excludes -- this is a total hack, but works for some simple cases and something is better than nothing :) let excludes = { - ...configuration.getAny<{ [key: string]: boolean }>('files.exclude', uri, {}), - ...configuration.getAny<{ [key: string]: boolean }>('search.exclude', uri, {}), + ...configuration.getAny>('files.exclude', uri, {}), + ...configuration.getAny>('search.exclude', uri, {}), }; const excludedPaths = [ @@ -329,14 +329,15 @@ export class GitService implements Disposable { excludes = excludedPaths.reduce((accumulator, current) => { accumulator[current] = true; return accumulator; - }, Object.create(null)); + }, Object.create(null) as Record); let repoPaths; try { repoPaths = await this.repositorySearchCore(uri.fsPath, depth, excludes); } catch (ex) { - if (RepoSearchWarnings.doesNotExist.test(ex.message || emptyStr)) { - Logger.log(cc, `FAILED${ex.message ? ` Error: ${ex.message}` : emptyStr}`); + const msg: string = ex?.toString() ?? emptyStr; + if (RepoSearchWarnings.doesNotExist.test(msg)) { + Logger.log(cc, `FAILED${msg ? ` Error: ${msg}` : emptyStr}`); } else { Logger.error(ex, cc, 'FAILED'); } @@ -372,7 +373,7 @@ export class GitService implements Disposable { private repositorySearchCore( root: string, depth: number, - excludes: { [key: string]: boolean }, + excludes: Record, repositories: string[] = [], ): Promise { const cc = Logger.getCorrelationContext(); @@ -471,7 +472,7 @@ export class GitService implements Disposable { async applyChangesToWorkingFile(uri: GitUri, ref1?: string, ref2?: string) { const cc = Logger.getCorrelationContext(); - ref1 = ref1 || uri.sha; + ref1 = ref1 ?? uri.sha; if (ref1 == null || uri.repoPath == null) return; if (ref2 == null) { @@ -486,7 +487,8 @@ export class GitService implements Disposable { }); void (await Git.apply(uri.repoPath, patch)); } catch (ex) { - if (patch && /patch does not apply/i.test(ex.message)) { + const msg: string = ex?.toString() ?? emptyStr; + if (patch && /patch does not apply/i.test(msg)) { const result = await window.showWarningMessage( 'Unable to apply changes cleanly. Retry and allow conflicts?', { title: 'Yes' }, @@ -518,7 +520,8 @@ export class GitService implements Disposable { try { return await Git.checkout(repoPath, ref, options); } catch (ex) { - if (/overwritten by checkout/i.test(ex.message)) { + const msg: string = ex?.toString() ?? emptyStr; + if (/overwritten by checkout/i.test(msg)) { void Messages.showGenericErrorMessage( `Unable to checkout '${ref}'. Please commit or stash your changes before switching branches`, ); @@ -569,7 +572,7 @@ export class GitService implements Disposable { if (repositories.length === 0) return; if (repositories.length === 1) { - repositories[0].fetch(options); + await repositories[0].fetch(options); return; } @@ -598,7 +601,7 @@ export class GitService implements Disposable { if (repositories.length === 0) return; if (repositories.length === 1) { - repositories[0].pull(options); + await repositories[0].pull(options); return; } @@ -625,7 +628,7 @@ export class GitService implements Disposable { if (repositories.length === 0) return; if (repositories.length === 1) { - repositories[0].push(options); + await repositories[0].push(options); return; } @@ -659,7 +662,7 @@ export class GitService implements Disposable { }, }) async getActiveRepoPath(editor?: TextEditor): Promise { - editor = editor || window.activeTextEditor; + editor = editor ?? window.activeTextEditor; let repoPath; if (editor != null) { @@ -746,7 +749,7 @@ export class GitService implements Disposable { } catch (ex) { // Trap and cache expected blame errors if (document.state != null) { - const msg = ex && ex.toString(); + const msg = ex?.toString() ?? ''; Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); const value: CachedBlame = { @@ -766,7 +769,7 @@ export class GitService implements Disposable { @log({ args: { - 1: contents => '', + 1: _contents => '', }, }) async getBlameForFileContents(uri: GitUri, contents: string): Promise { @@ -830,7 +833,7 @@ export class GitService implements Disposable { } catch (ex) { // Trap and cache expected blame errors if (document.state != null) { - const msg = ex && ex.toString(); + const msg = ex?.toString() ?? ''; Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); const value: CachedBlame = { @@ -899,7 +902,7 @@ export class GitService implements Disposable { @log({ args: { - 2: contents => '', + 2: _contents => '', }, }) async getBlameForLineContents( @@ -963,7 +966,7 @@ export class GitService implements Disposable { @log({ args: { - 2: contents => '', + 2: _contents => '', }, }) async getBlameForRangeContents(uri: GitUri, range: Range, contents: string): Promise { @@ -975,7 +978,7 @@ export class GitService implements Disposable { @log({ args: { - 0: blame => '', + 0: _blame => '', }, }) getBlameForRangeSync(blame: GitBlame, uri: GitUri, range: Range): GitBlameLines | undefined { @@ -992,8 +995,8 @@ export class GitService implements Disposable { const startLine = range.start.line + 1; const endLine = range.end.line + 1; - const authors: Map = new Map(); - const commits: Map = new Map(); + const authors = new Map(); + const commits = new Map(); for (const c of blame.commits.values()) { if (!shas.has(c.sha)) continue; @@ -1148,7 +1151,7 @@ export class GitService implements Disposable { const log = await this.getLog(repoPath, { limit: 2, ref: ref }); if (log == null) return undefined; - return log.commits.get(ref) || Iterables.first(log.commits.values()); + return log.commits.get(ref) ?? Iterables.first(log.commits.values()); } @log() @@ -1350,7 +1353,7 @@ export class GitService implements Disposable { } catch (ex) { // Trap and cache expected diff errors if (document.state != null) { - const msg = ex && ex.toString(); + const msg = ex?.toString() ?? ''; Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); const value: CachedDiff = { @@ -1889,7 +1892,7 @@ export class GitService implements Disposable { } catch (ex) { // Trap and cache expected log errors if (document.state != null && range == null && !options.reverse) { - const msg = ex && ex.toString(); + const msg: string = ex?.toString() ?? ''; Logger.debug(cc, `Cache replace (with empty promise): '${key}'`); const value: CachedLog = { @@ -2083,18 +2086,18 @@ export class GitService implements Disposable { simple: true, }); if (data == null || data.length === 0) { - return GitUri.fromFile(file || fileName, repoPath, nextRef); + return GitUri.fromFile(file ?? fileName, repoPath, nextRef); } - const [nextRenamedRef, renamedFile] = GitLogParser.parseSimpleRenamed(data, file || fileName); + const [nextRenamedRef, renamedFile] = GitLogParser.parseSimpleRenamed(data, file ?? fileName); return GitUri.fromFile( - renamedFile || file || fileName, + renamedFile ?? file ?? fileName, repoPath, - nextRenamedRef || nextRef || GitRevision.deletedOrMissing, + nextRenamedRef ?? nextRef ?? GitRevision.deletedOrMissing, ); } - return GitUri.fromFile(file || fileName, repoPath, nextRef); + return GitUri.fromFile(file ?? fileName, repoPath, nextRef); } @log() @@ -2242,7 +2245,7 @@ export class GitService implements Disposable { // If line is committed, diff with line ref with previous else { ref = blameLine.commit.sha; - fileName = blameLine.commit.fileName || blameLine.commit.originalFileName || fileName; + fileName = blameLine.commit.fileName || (blameLine.commit.originalFileName ?? fileName); uri = GitUri.resolveToUri(fileName, repoPath); editorLine = blameLine.line.originalLine - 1; @@ -2271,7 +2274,7 @@ export class GitService implements Disposable { // Diff with line ref with previous ref = blameLine.commit.sha; - fileName = blameLine.commit.fileName || blameLine.commit.originalFileName || fileName; + fileName = blameLine.commit.fileName || (blameLine.commit.originalFileName ?? fileName); uri = GitUri.resolveToUri(fileName, repoPath); editorLine = blameLine.line.originalLine - 1; @@ -2321,17 +2324,18 @@ export class GitService implements Disposable { startLine: editorLine != null ? editorLine + 1 : undefined, }); } catch (ex) { + const msg: string = ex?.toString() ?? emptyStr; // If the line count is invalid just fallback to the most recent commit - if ((ref == null || GitRevision.isUncommittedStaged(ref)) && GitErrors.invalidLineCount.test(ex.message)) { + if ((ref == null || GitRevision.isUncommittedStaged(ref)) && GitErrors.invalidLineCount.test(msg)) { if (ref == null) { const status = await this.getStatusForFile(repoPath, fileName); - if (status != null && status.indexStatus != null) { + if (status?.indexStatus != null) { return GitUri.fromFile(fileName, repoPath, GitRevision.uncommittedStaged); } } ref = await Git.log__file_recent(repoPath, fileName); - return GitUri.fromFile(fileName, repoPath, ref || GitRevision.deletedOrMissing); + return GitUri.fromFile(fileName, repoPath, ref ?? GitRevision.deletedOrMissing); } Logger.error(ex, cc); @@ -2343,7 +2347,7 @@ export class GitService implements Disposable { // If the previous ref matches the ref we asked for assume we are at the end of the history if (ref != null && ref === previousRef) return undefined; - return GitUri.fromFile(file || fileName, repoPath, previousRef || GitRevision.deletedOrMissing); + return GitUri.fromFile(file ?? fileName, repoPath, previousRef ?? GitRevision.deletedOrMissing); } async getPullRequestForCommit( @@ -2471,7 +2475,7 @@ export class GitService implements Disposable { ): Promise { if (repoPath == null) return []; - providers = providers || RemoteProviderFactory.loadProviders(configuration.get('remotes', null)); + providers = providers ?? RemoteProviderFactory.loadProviders(configuration.get('remotes', null)); try { const data = await Git.remote(repoPath); @@ -2783,7 +2787,7 @@ export class GitService implements Disposable { let tags = this.useCaching ? this._tagsCache.get(repoPath) : undefined; if (tags == null) { const data = await Git.tag(repoPath); - tags = GitTagParser.parse(data, repoPath) || []; + tags = GitTagParser.parse(data, repoPath) ?? []; const repo = await this.getRepository(repoPath); if (repo?.supportsChangeEvents) { @@ -2808,7 +2812,7 @@ export class GitService implements Disposable { const data = await Git.ls_tree(repoPath, ref, { fileName: fileName }); const trees = GitTreeParser.parse(data); - return trees == null || trees.length === 0 ? undefined : trees[0]; + return trees?.length ? trees[0] : undefined; } @log() @@ -2816,7 +2820,7 @@ export class GitService implements Disposable { if (repoPath == null) return []; const data = await Git.ls_tree(repoPath, ref); - return GitTreeParser.parse(data) || []; + return GitTreeParser.parse(data) ?? []; } @log() @@ -2991,7 +2995,7 @@ export class GitService implements Disposable { @log() async getDiffTool(repoPath?: string) { return ( - (await Git.config__get('diff.guitool', repoPath, { local: true })) || + (await Git.config__get('diff.guitool', repoPath, { local: true })) ?? Git.config__get('diff.tool', repoPath, { local: true }) ); } @@ -3038,7 +3042,7 @@ export class GitService implements Disposable { if (fileNameOrUri == null) { if (GitRevision.isSha(ref) || !GitRevision.isShaLike(ref) || ref.endsWith('^3')) return ref; - return (await Git.rev_parse(repoPath, ref)) || ref; + return (await Git.rev_parse(repoPath, ref)) ?? ref; } const fileName = diff --git a/src/git/gitUri.ts b/src/git/gitUri.ts index 70c94b2..9c1c2bc 100644 --- a/src/git/gitUri.ts +++ b/src/git/gitUri.ts @@ -95,7 +95,7 @@ export class GitUri extends ((Uri as any) as UriEx) { const [authority, fsPath] = GitUri.ensureValidUNCPath( uri.authority, - GitUri.resolve(commitOrRepoPath.fileName || uri.fsPath, commitOrRepoPath.repoPath), + GitUri.resolve(commitOrRepoPath.fileName ?? uri.fsPath, commitOrRepoPath.repoPath), ); let path; diff --git a/src/git/locator.ts b/src/git/locator.ts index fb72bf5..dddcf0a 100644 --- a/src/git/locator.ts +++ b/src/git/locator.ts @@ -65,7 +65,7 @@ function findGitWin32(): Promise { export async function findGitPath(path?: string): Promise { try { - return await findSpecificGit(path || 'git'); + return await findSpecificGit(path ?? 'git'); } catch (ex) { try { switch (process.platform) { diff --git a/src/git/models/blameCommit.ts b/src/git/models/blameCommit.ts index 630363e..c41eb3a 100644 --- a/src/git/models/blameCommit.ts +++ b/src/git/models/blameCommit.ts @@ -49,17 +49,17 @@ export class GitBlameCommit extends GitCommit { }): GitBlameCommit { return new GitBlameCommit( this.repoPath, - changes.sha || this.sha, + changes.sha ?? this.sha, this.author, this.email, this.authorDate, this.committerDate, this.message, - changes.fileName || this.fileName, + changes.fileName ?? this.fileName, this.getChangedValue(changes.originalFileName, this.originalFileName), this.getChangedValue(changes.previousSha, this.previousSha), this.getChangedValue(changes.previousFileName, this.previousFileName), - this.getChangedValue(changes.lines, changes.sha || changes.fileName ? [] : this.lines) || [], + this.getChangedValue(changes.lines, changes.sha ?? changes.fileName ? [] : this.lines) ?? [], ); } } diff --git a/src/git/models/branch.ts b/src/git/models/branch.ts index d416e5d..c4dfae4 100644 --- a/src/git/models/branch.ts +++ b/src/git/models/branch.ts @@ -193,13 +193,13 @@ export class GitBranch implements GitBranchReference { private async updateStarred(star: boolean) { let starred = Container.context.workspaceState.get(WorkspaceState.StarredBranches); if (starred === undefined) { - starred = Object.create(null); + starred = Object.create(null) as StarredBranches; } if (star) { - starred![this.id] = true; + starred[this.id] = true; } else { - const { [this.id]: _, ...rest } = starred!; + const { [this.id]: _, ...rest } = starred; starred = rest; } await Container.context.workspaceState.update(WorkspaceState.StarredBranches, starred); diff --git a/src/git/models/commit.ts b/src/git/models/commit.ts index 1104cc3..55d6e15 100644 --- a/src/git/models/commit.ts +++ b/src/git/models/commit.ts @@ -143,7 +143,7 @@ export abstract class GitCommit implements GitRevisionReference { } @memoize( - (uri, editorLine, ref) => `${uri.toString(true)}|${editorLine || ''}|${ref || ''}`, + (uri, editorLine, ref) => `${uri.toString(true)}|${editorLine ?? ''}|${ref ?? ''}`, ) getPreviousLineDiffUris(uri: Uri, editorLine: number, ref: string | undefined) { if (!this.isFile) return Promise.resolve(undefined); diff --git a/src/git/models/logCommit.ts b/src/git/models/logCommit.ts index 4b1dcb8..35ed79b 100644 --- a/src/git/models/logCommit.ts +++ b/src/git/models/logCommit.ts @@ -70,7 +70,7 @@ export class GitLogCommit extends GitCommit { message, fileName, originalFileName, - previousSha || `${sha}^`, + previousSha ?? `${sha}^`, previousFileName, ); } @@ -143,7 +143,7 @@ export class GitLogCommit extends GitCommit { suffix?: string; } = {}): string { const { added, changed, deleted } = this.getDiffStatus(); - if (added === 0 && changed === 0 && deleted === 0) return empty || ''; + if (added === 0 && changed === 0 && deleted === 0) return empty ?? ''; if (expand) { const type = this.isFile ? 'line' : 'file'; @@ -187,7 +187,7 @@ export class GitLogCommit extends GitCommit { fileName: foundFile.fileName, originalFileName: foundFile.originalFileName, previousSha: previousSha, - previousFileName: foundFile.originalFileName || foundFile.fileName, + previousFileName: foundFile.originalFileName ?? foundFile.fileName, status: foundFile.status, files: [foundFile], }); @@ -209,17 +209,17 @@ export class GitLogCommit extends GitCommit { files?: GitFile[] | null; }): GitLogCommit { return new GitLogCommit( - changes.type || this.type, + changes.type ?? this.type, this.repoPath, this.getChangedValue(changes.sha, this.sha)!, - changes.author || this.author, - changes.email || this.email, - changes.authorDate || this.authorDate, - changes.committedDate || this.committerDate, - changes.message || this.message, - changes.fileName || this.fileName, - this.getChangedValue(changes.files, this.files) || [], - changes.status || this.status, + changes.author ?? this.author, + changes.email ?? this.email, + changes.authorDate ?? this.authorDate, + changes.committedDate ?? this.committerDate, + changes.message ?? this.message, + changes.fileName ?? this.fileName, + this.getChangedValue(changes.files, this.files) ?? [], + changes.status ?? this.status, this.getChangedValue(changes.originalFileName, this.originalFileName), this.getChangedValue(changes.previousSha, this.previousSha), this.getChangedValue(changes.previousFileName, this.previousFileName), diff --git a/src/git/models/models.ts b/src/git/models/models.ts index 13d33af..809f206 100644 --- a/src/git/models/models.ts +++ b/src/git/models/models.ts @@ -28,7 +28,7 @@ export namespace GitRevision { ref2: string | undefined, notation: '..' | '...' = '..', ): string { - return `${ref1 || ''}${notation}${ref2 || ''}`; + return `${ref1 ?? ''}${notation}${ref2 ?? ''}`; } export function isRange(ref: string | undefined) { @@ -70,8 +70,8 @@ export namespace GitRevision { if (ref == null || ref.length === 0) return strings.working ?? emptyStr; if (isUncommitted(ref)) { return isUncommittedStaged(ref) - ? strings.uncommittedStaged || 'Index' - : strings.uncommitted || 'Working Tree'; + ? strings.uncommittedStaged ?? 'Index' + : strings.uncommitted ?? 'Working Tree'; } if (GitRevision.isRange(ref)) return ref; diff --git a/src/git/models/repository.ts b/src/git/models/repository.ts index 043b687..7e1a0e4 100644 --- a/src/git/models/repository.ts +++ b/src/git/models/repository.ts @@ -187,7 +187,7 @@ export class Repository implements Disposable { } private onRepositoryChanged(uri: Uri | undefined) { - if (uri !== undefined && uri.path.endsWith('refs/stash')) { + if (uri?.path.endsWith('refs/stash')) { this.fireChange(RepositoryChange.Stashes); return; @@ -195,20 +195,20 @@ export class Repository implements Disposable { this._branch = undefined; - if (uri !== undefined && uri.path.endsWith('refs/remotes')) { + if (uri?.path.endsWith('refs/remotes')) { this.resetRemotesCache(); this.fireChange(RepositoryChange.Remotes); return; } - if (uri !== undefined && uri.path.endsWith('refs/tags')) { + if (uri?.path.endsWith('refs/tags')) { this.fireChange(RepositoryChange.Tags); return; } - if (uri !== undefined && uri.path.endsWith('config')) { + if (uri?.path.endsWith('config')) { this.resetRemotesCache(); this.fireChange(RepositoryChange.Config, RepositoryChange.Remotes); @@ -299,7 +299,7 @@ export class Repository implements Disposable { this.fireChange(RepositoryChange.Repository); } catch (ex) { Logger.error(ex); - Messages.showGenericErrorMessage('Unable to fetch repository'); + void Messages.showGenericErrorMessage('Unable to fetch repository'); } } @@ -345,7 +345,7 @@ export class Repository implements Disposable { } } - getRemotes(options: { sort?: boolean } = {}): Promise { + getRemotes(_options: { sort?: boolean } = {}): Promise { if (this._remotes === undefined || !this.supportsChangeEvents) { if (this._providers === undefined) { const remotesCfg = configuration.get('remotes', this.folder.uri); @@ -354,7 +354,7 @@ export class Repository implements Disposable { // Since we are caching the results, always sort this._remotes = Container.git.getRemotesCore(this.path, this._providers, { sort: true }); - this.subscribeToRemotes(this._remotes); + void this.subscribeToRemotes(this._remotes); } return this._remotes; @@ -397,12 +397,12 @@ export class Repository implements Disposable { async hasRemotes(): Promise { const remotes = await this.getRemotes(); - return remotes !== undefined && remotes.length > 0; + return remotes?.length > 0; } async hasTrackingBranch(): Promise { const branch = await this.getBranch(); - return branch !== undefined && branch.tracking !== undefined; + return branch?.tracking != null; } @gate(() => '') @@ -438,7 +438,7 @@ export class Repository implements Disposable { this.fireChange(RepositoryChange.Repository); } catch (ex) { Logger.error(ex); - Messages.showGenericErrorMessage('Unable to pull repository'); + void Messages.showGenericErrorMessage('Unable to pull repository'); } } @@ -464,7 +464,7 @@ export class Repository implements Disposable { this.fireChange(RepositoryChange.Repository); } catch (ex) { Logger.error(ex); - Messages.showGenericErrorMessage('Unable to push repository'); + void Messages.showGenericErrorMessage('Unable to push repository'); } } @@ -561,7 +561,7 @@ export class Repository implements Disposable { this.fireChange(RepositoryChange.Repository); } catch (ex) { Logger.error(ex); - Messages.showGenericErrorMessage('Unable to switch to reference'); + void Messages.showGenericErrorMessage('Unable to switch to reference'); } } @@ -572,13 +572,13 @@ export class Repository implements Disposable { private async updateStarred(star: boolean) { let starred = Container.context.workspaceState.get(WorkspaceState.StarredRepositories); if (starred === undefined) { - starred = Object.create(null); + starred = Object.create(null) as StarredRepositories; } if (star) { - starred![this.id] = true; + starred[this.id] = true; } else { - const { [this.id]: _, ...rest } = starred!; + const { [this.id]: _, ...rest } = starred; starred = rest; } await Container.context.workspaceState.update(WorkspaceState.StarredRepositories, starred); diff --git a/src/git/models/stashCommit.ts b/src/git/models/stashCommit.ts index e1c7360..e27c1c5 100644 --- a/src/git/models/stashCommit.ts +++ b/src/git/models/stashCommit.ts @@ -52,15 +52,15 @@ export class GitStashCommit extends GitLogCommit { files?: GitFile[] | null; }): GitLogCommit { return new GitStashCommit( - changes.type || this.type, + changes.type ?? this.type, this.stashName, this.repoPath, this.getChangedValue(changes.sha, this.sha)!, - changes.authorDate || this.authorDate, - changes.committedDate || this.committerDate, - changes.message || this.message, - changes.fileName || this.fileName, - this.getChangedValue(changes.files, this.files) || [], + changes.authorDate ?? this.authorDate, + changes.committedDate ?? this.committerDate, + changes.message ?? this.message, + changes.fileName ?? this.fileName, + this.getChangedValue(changes.files, this.files) ?? [], ); } } diff --git a/src/git/models/status.ts b/src/git/models/status.ts index 0eb87e2..044550d 100644 --- a/src/git/models/status.ts +++ b/src/git/models/status.ts @@ -148,7 +148,7 @@ export class GitStatus { suffix?: string; } = {}): string { const { added, changed, deleted } = this.getDiffStatus(); - if (added === 0 && changed === 0 && deleted === 0) return empty || ''; + if (added === 0 && changed === 0 && deleted === 0) return empty ?? ''; if (expand) { let status = ''; @@ -197,7 +197,7 @@ export class GitStatus { state: { ahead: number; behind: number }, options: { empty?: string; expand?: boolean; prefix?: string; separator?: string; suffix?: string } = {}, ): string { - if (upstream == null || (state.behind === 0 && state.ahead === 0)) return options.empty || ''; + if (upstream == null || (state.behind === 0 && state.ahead === 0)) return options.empty ?? ''; const { expand, prefix = '', separator = ' ', suffix = '' } = options; if (expand) { @@ -263,7 +263,7 @@ export class GitStatusFile implements GitFile { this.repoPath, this.getChangedValue(changes.indexStatus, this.indexStatus) as GitFileStatus, this.getChangedValue(changes.workTreeStatus, this.workingTreeStatus) as GitFileStatus, - changes.fileName || this.fileName, + changes.fileName ?? this.fileName, this.getChangedValue(changes.originalFileName, this.originalFileName), ); } diff --git a/src/git/parsers/blameParser.ts b/src/git/parsers/blameParser.ts index 2fe5d6d..d2c876f 100644 --- a/src/git/parsers/blameParser.ts +++ b/src/git/parsers/blameParser.ts @@ -39,8 +39,8 @@ export class GitBlameParser { ): GitBlame | undefined { if (!data) return undefined; - const authors: Map = new Map(); - const commits: Map = new Map(); + const authors = new Map(); + const commits = new Map(); const lines: GitCommitLine[] = []; let relativeFileName; diff --git a/src/git/parsers/logParser.ts b/src/git/parsers/logParser.ts index 126d4ec..43c38d2 100644 --- a/src/git/parsers/logParser.ts +++ b/src/git/parsers/logParser.ts @@ -110,8 +110,8 @@ export class GitLogParser { repoPath = Strings.normalizePath(repoPath); } - const authors: Map = new Map(); - const commits: Map = new Map(); + const authors = new Map(); + const commits = new Map(); let truncationCount = limit; let match; @@ -416,7 +416,7 @@ export class GitLogParser { } const originalFileName = - entry.originalFileName || (relativeFileName !== entry.fileName ? entry.fileName : undefined); + entry.originalFileName ?? (relativeFileName !== entry.fileName ? entry.fileName : undefined); if (type === GitCommitType.LogFile) { entry.files = [ @@ -438,7 +438,7 @@ export class GitLogParser { new Date((entry.committedDate! as any) * 1000), entry.summary === undefined ? emptyStr : entry.summary, relativeFileName, - entry.files || [], + entry.files ?? [], entry.status, originalFileName, type === GitCommitType.Log ? entry.parentShas![0] : undefined, @@ -460,8 +460,8 @@ export class GitLogParser { // Only add a filename if this is a file log if (type === GitCommitType.LogFile) { - recentCommit.previousFileName = commit.originalFileName || commit.fileName; - commit.nextFileName = recentCommit.originalFileName || recentCommit.fileName; + recentCommit.previousFileName = commit.originalFileName ?? commit.fileName; + commit.nextFileName = recentCommit.originalFileName ?? recentCommit.fileName; } } return commit; diff --git a/src/git/parsers/remoteParser.ts b/src/git/parsers/remoteParser.ts index 27c3ed1..472ed30 100644 --- a/src/git/parsers/remoteParser.ts +++ b/src/git/parsers/remoteParser.ts @@ -57,7 +57,7 @@ export class GitRemoteParser { if (!data) return undefined; const remotes: GitRemote[] = []; - const groups = Object.create(null); + const groups = Object.create(null) as Record; let name; let url; diff --git a/src/git/parsers/stashParser.ts b/src/git/parsers/stashParser.ts index 75684fb..02fe6c2 100644 --- a/src/git/parsers/stashParser.ts +++ b/src/git/parsers/stashParser.ts @@ -48,7 +48,7 @@ export class GitStashParser { repoPath = Strings.normalizePath(repoPath); } - const commits: Map = new Map(); + const commits = new Map(); let entry: StashEntry = emptyEntry; let line: string | undefined = undefined; @@ -172,7 +172,7 @@ export class GitStashParser { new Date((entry.committedDate! as any) * 1000), entry.summary === undefined ? emptyStr : entry.summary, entry.fileNames!, - entry.files || [], + entry.files ?? [], ); } diff --git a/src/git/parsers/statusParser.ts b/src/git/parsers/statusParser.ts index 6971d6f..3bd36e4 100644 --- a/src/git/parsers/statusParser.ts +++ b/src/git/parsers/statusParser.ts @@ -58,7 +58,7 @@ export class GitStatusParser { } } - return new GitStatus(Strings.normalizePath(repoPath), branch || emptyStr, emptyStr, files, state, upstream); + return new GitStatus(Strings.normalizePath(repoPath), branch ?? emptyStr, emptyStr, files, state, upstream); } @debug({ args: false, singleLine: true }) @@ -117,8 +117,8 @@ export class GitStatusParser { return new GitStatus( Strings.normalizePath(repoPath), - branch || emptyStr, - sha || emptyStr, + branch ?? emptyStr, + sha ?? emptyStr, files, state, upstream, diff --git a/src/git/remotes/custom.ts b/src/git/remotes/custom.ts index b991140..a644900 100644 --- a/src/git/remotes/custom.ts +++ b/src/git/remotes/custom.ts @@ -59,13 +59,13 @@ export class CustomRemote extends RemoteProvider { return Strings.interpolate(this.urls.file, this.getContext({ file: fileName, line: line })); } - private getContext(context?: {}) { + private getContext(context?: Record) { const [repoBase, repoPath] = this.splitPath(); return { repo: this.path, repoBase: repoBase, repoPath: repoPath, - ...(context || {}), + ...(context ?? {}), }; } } diff --git a/src/git/remotes/provider.ts b/src/git/remotes/provider.ts index b8129f4..7b8221b 100644 --- a/src/git/remotes/provider.ts +++ b/src/git/remotes/provider.ts @@ -96,24 +96,24 @@ export abstract class RemoteProvider { abstract get name(): string; - async copy(resource: RemoteResource): Promise<{} | undefined> { + async copy(resource: RemoteResource): Promise { const url = this.url(resource); - if (url === undefined) return undefined; + if (url === undefined) return; try { void (await env.clipboard.writeText(url)); - - return undefined; } catch (ex) { - if (ex.message.includes("Couldn't find the required `xsel` binary")) { - window.showErrorMessage( + const msg: string = ex?.toString() ?? ''; + if (msg.includes("Couldn't find the required `xsel` binary")) { + void window.showErrorMessage( 'Unable to copy remote url, xsel is not installed. Please install it via your package manager, e.g. `sudo apt install xsel`', ); - return undefined; + + return; } Logger.error(ex, 'CopyRemoteUrlToClipboardCommand'); - return Messages.showGenericErrorMessage('Unable to copy remote url'); + void Messages.showGenericErrorMessage('Unable to copy remote url'); } } @@ -121,7 +121,7 @@ export abstract class RemoteProvider { return RemoteProviderWithApi.is(this); } - open(resource: RemoteResource): Thenable<{} | undefined> { + open(resource: RemoteResource): Promise { return this.openUrl(this.url(resource)); } @@ -180,14 +180,14 @@ export abstract class RemoteProvider { return this.baseUrl; } - private openUrl(url?: string): Thenable<{} | undefined> { - if (url === undefined) return Promise.resolve(undefined); + private async openUrl(url?: string): Promise { + if (url == null) return undefined; return env.openExternal(Uri.parse(url)); } } -export abstract class RemoteProviderWithApi extends RemoteProvider { +export abstract class RemoteProviderWithApi extends RemoteProvider { static is(provider: RemoteProvider | undefined): provider is RemoteProviderWithApi { return provider instanceof RemoteProviderWithApi; } diff --git a/src/git/shell.ts b/src/git/shell.ts index f97c58b..9a20276 100644 --- a/src/git/shell.ts +++ b/src/git/shell.ts @@ -31,7 +31,7 @@ function runDownPath(exe: string): string { const target = paths.join('.', exe); try { const stats = fs.statSync(target); - if (stats && stats.isFile() && isExecutable(stats)) return target; + if (stats?.isFile() && isExecutable(stats)) return target; } catch {} const path = process.env.PATH; @@ -42,7 +42,7 @@ function runDownPath(exe: string): string { const needle = paths.join(p, exe); try { stats = fs.statSync(needle); - if (stats && stats.isFile() && isExecutable(stats)) return needle; + if (stats?.isFile() && isExecutable(stats)) return needle; } catch {} } } @@ -53,7 +53,9 @@ function runDownPath(exe: string): string { function isExecutable(stats: fs.Stats) { if (isWindows) return true; + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions const isGroup = stats.gid ? process.getgid && stats.gid === process.getgid() : true; + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions const isUser = stats.uid ? process.getuid && stats.uid === process.getuid() : true; return Boolean(stats.mode & 0o0001 || (stats.mode & 0o0010 && isGroup) || (stats.mode & 0o0100 && isUser)); @@ -86,7 +88,7 @@ export function findExecutable(exe: string, args: string[]): { cmd: string; args if (ps1Regex.test(exe)) { const cmd = paths.join( - process.env.SYSTEMROOT || 'C:\\WINDOWS', + process.env.SYSTEMROOT ?? 'C:\\WINDOWS', 'System32', 'WindowsPowerShell', 'v1.0', @@ -98,7 +100,7 @@ export function findExecutable(exe: string, args: string[]): { cmd: string; args } if (batOrCmdRegex.test(exe)) { - const cmd = paths.join(process.env.SYSTEMROOT || 'C:\\WINDOWS', 'System32', 'cmd.exe'); + const cmd = paths.join(process.env.SYSTEMROOT ?? 'C:\\WINDOWS', 'System32', 'cmd.exe'); const cmdArgs = ['/C', exe, ...args]; return { cmd: cmd, args: cmdArgs }; @@ -181,8 +183,8 @@ export function run( }, ); - if (stdin) { - proc.stdin?.end(stdin, stdinEncoding || 'utf8'); + if (stdin != null) { + proc.stdin?.end(stdin, stdinEncoding ?? 'utf8'); } }); } diff --git a/src/hovers/hovers.ts b/src/hovers/hovers.ts index b8a49bf..0bc1d73 100644 --- a/src/hovers/hovers.ts +++ b/src/hovers/hovers.ts @@ -48,7 +48,7 @@ export namespace Hovers { } const line = editorLine + 1; - const commitLine = commit.lines.find(l => l.line === line) || commit.lines[0]; + const commitLine = commit.lines.find(l => l.line === line) ?? commit.lines[0]; let originalFileName = commit.originalFileName; if (originalFileName === undefined) { @@ -87,11 +87,11 @@ export namespace Hovers { message = `[$(compare-changes) Changes](${DiffWithCommand.getMarkdownCommandArgs({ lhs: { - sha: diffUris.previous.sha || '', + sha: diffUris.previous.sha ?? '', uri: diffUris.previous.documentUri(), }, rhs: { - sha: diffUris.current.sha || '', + sha: diffUris.current.sha ?? '', uri: diffUris.current.documentUri(), }, repoPath: commit.repoPath, @@ -162,7 +162,7 @@ export namespace Hovers { commit.isUncommitted ? commit.getPreviousLineDiffUris(uri, editorLine, uri.sha) : undefined, getAutoLinkedIssuesOrPullRequests(commit.message, remotes), getPullRequestForCommit(commit.ref, remotes), - Container.vsls.maybeGetPresence(commit.email).catch(reason => undefined), + Container.vsls.maybeGetPresence(commit.email).catch(() => undefined), ]); const details = CommitFormatter.fromTemplate(Container.config.hovers.detailsMarkdownFormat, commit, { diff --git a/src/hovers/lineHoverController.ts b/src/hovers/lineHoverController.ts index 086adcd..3c5505d 100644 --- a/src/hovers/lineHoverController.ts +++ b/src/hovers/lineHoverController.ts @@ -20,7 +20,7 @@ import { debug } from '../system'; import { UriComparer } from '../comparers'; export class LineHoverController implements Disposable { - private _disposable: Disposable; + private readonly _disposable: Disposable; private _hoverProviderDisposable: Disposable | undefined; private _uri: Uri | undefined; @@ -33,7 +33,7 @@ export class LineHoverController implements Disposable { this.unregister(); Container.lineTracker.stop(this); - this._disposable && this._disposable.dispose(); + this._disposable.dispose(); } private onConfigurationChanged(e: ConfigurationChangeEvent) { @@ -89,7 +89,7 @@ export class LineHoverController implements Disposable { async provideDetailsHover( document: TextDocument, position: Position, - token: CancellationToken, + _token: CancellationToken, ): Promise { if (!Container.lineTracker.includes(position.line)) return undefined; @@ -129,14 +129,14 @@ export class LineHoverController implements Disposable { let editorLine = position.line; const line = editorLine + 1; - const commitLine = commit.lines.find(l => l.line === line) || commit.lines[0]; + const commitLine = commit.lines.find(l => l.line === line) ?? commit.lines[0]; editorLine = commitLine.originalLine - 1; const trackedDocument = await Container.tracker.get(document); if (trackedDocument === undefined) return undefined; const message = await Hovers.detailsMessage( - logCommit || commit, + logCommit ?? commit, trackedDocument.uri, editorLine, Container.config.defaultDateFormat, @@ -155,7 +155,7 @@ export class LineHoverController implements Disposable { async provideChangesHover( document: TextDocument, position: Position, - token: CancellationToken, + _token: CancellationToken, ): Promise { if (!Container.lineTracker.includes(position.line)) return undefined; diff --git a/src/keyboard.ts b/src/keyboard.ts index 8d1bdd6..55a0ac1 100644 --- a/src/keyboard.ts +++ b/src/keyboard.ts @@ -36,7 +36,7 @@ export class KeyboardScope implements Disposable { constructor(mapping: KeyMapping) { this._mapping = mapping; for (const key in this._mapping) { - this._mapping[key] = this._mapping[key] || keyNoopCommand; + this._mapping[key] = this._mapping[key] ?? keyNoopCommand; } mappings.push(this._mapping); @@ -96,9 +96,9 @@ export class KeyboardScope implements Disposable { this._paused = true; const mapping = (Object.keys(this._mapping) as Keys[]).reduce((accumulator, key) => { - accumulator[key] = keys === undefined ? false : keys.includes(key) ? false : this._mapping[key]; + accumulator[key] = keys == null || keys.includes(key) ? undefined : this._mapping[key]; return accumulator; - }, {} as any); + }, Object.create(null) as KeyMapping); await this.updateKeyCommandsContext(mapping); } @@ -143,14 +143,12 @@ export class KeyboardScope implements Disposable { } private async updateKeyCommandsContext(mapping: KeyMapping) { - await Promise.all( - keys.map(key => setCommandContext(`${CommandContext.Key}:${key}`, Boolean(mapping && mapping[key]))), - ); + await Promise.all(keys.map(key => setCommandContext(`${CommandContext.Key}:${key}`, Boolean(mapping?.[key])))); } } export class Keyboard implements Disposable { - private _disposable: Disposable; + private readonly _disposable: Disposable; constructor() { const subscriptions = keys.map(key => @@ -160,7 +158,7 @@ export class Keyboard implements Disposable { } dispose() { - this._disposable && this._disposable.dispose(); + this._disposable.dispose(); } @log({ @@ -184,7 +182,7 @@ export class Keyboard implements Disposable { } @log() - async execute(key: Keys): Promise<{} | undefined> { + async execute(key: Keys): Promise { const cc = Logger.getCorrelationContext(); if (!mappings.length) { @@ -192,7 +190,7 @@ export class Keyboard implements Disposable { cc.exitDetails = ' \u2022 skipped, no mappings'; } - return undefined; + return; } try { @@ -207,15 +205,12 @@ export class Keyboard implements Disposable { cc.exitDetails = ' \u2022 skipped, no callback'; } - return undefined; + return; } - await command.onDidPressKey(key); - - return undefined; + void (await command.onDidPressKey(key)); } catch (ex) { Logger.error(ex, cc); - return undefined; } } } diff --git a/src/logger.ts b/src/logger.ts index 3b7a1bb..86a66a4 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -40,12 +40,12 @@ export class Logger { static set level(value: TraceLevel) { this._level = value; if (value === TraceLevel.Silent) { - if (this.output !== undefined) { + if (this.output != null) { this.output.dispose(); this.output = undefined; } } else { - this.output = this.output || window.createOutputChannel(extensionOutputChannelName); + this.output = this.output ?? window.createOutputChannel(extensionOutputChannelName); } } @@ -60,17 +60,17 @@ export class Logger { } else { message = params.shift(); - if (contextOrMessage !== undefined) { - message = `${contextOrMessage.prefix} ${message || emptyStr}`; + if (contextOrMessage != null) { + message = `${contextOrMessage.prefix} ${message ?? emptyStr}`; } } if (Logger.isDebugging) { - console.log(this.timestamp, ConsolePrefix, message || emptyStr, ...params); + console.log(this.timestamp, ConsolePrefix, message ?? emptyStr, ...params); } - if (this.output !== undefined && this.level === TraceLevel.Debug) { - this.output.appendLine(`${this.timestamp} ${message || emptyStr}${this.toLoggableParams(true, params)}`); + if (this.output != null && this.level === TraceLevel.Debug) { + this.output.appendLine(`${this.timestamp} ${message ?? emptyStr}${this.toLoggableParams(true, params)}`); } } @@ -80,13 +80,13 @@ export class Logger { if (this.level === TraceLevel.Silent && !Logger.isDebugging) return; let message; - if (contextOrMessage === undefined || typeof contextOrMessage === 'string') { + if (contextOrMessage == null || typeof contextOrMessage === 'string') { message = contextOrMessage; } else { - message = `${contextOrMessage.prefix} ${params.shift() || emptyStr}`; + message = `${contextOrMessage.prefix} ${params.shift() ?? emptyStr}`; } - if (message === undefined) { + if (message == null) { const stack = ex.stack; if (stack) { const match = /.*\s*?at\s(.+?)\s/.exec(stack); @@ -97,12 +97,12 @@ export class Logger { } if (Logger.isDebugging) { - console.error(this.timestamp, ConsolePrefix, message || emptyStr, ...params, ex); + console.error(this.timestamp, ConsolePrefix, message ?? emptyStr, ...params, ex); } - if (this.output !== undefined && this.level !== TraceLevel.Silent) { + if (this.output != null && this.level !== TraceLevel.Silent) { this.output.appendLine( - `${this.timestamp} ${message || emptyStr}${this.toLoggableParams(false, params)}\n${ex?.toString()}`, + `${this.timestamp} ${message ?? emptyStr}${this.toLoggableParams(false, params)}\n${ex?.toString()}`, ); } @@ -134,17 +134,17 @@ export class Logger { } else { message = params.shift(); - if (contextOrMessage !== undefined) { - message = `${contextOrMessage.prefix} ${message || emptyStr}`; + if (contextOrMessage != null) { + message = `${contextOrMessage.prefix} ${message ?? emptyStr}`; } } if (Logger.isDebugging) { - console.log(this.timestamp, ConsolePrefix, message || emptyStr, ...params); + console.log(this.timestamp, ConsolePrefix, message ?? emptyStr, ...params); } - if (this.output !== undefined && (this.level === TraceLevel.Verbose || this.level === TraceLevel.Debug)) { - this.output.appendLine(`${this.timestamp} ${message || emptyStr}${this.toLoggableParams(false, params)}`); + if (this.output != null && (this.level === TraceLevel.Verbose || this.level === TraceLevel.Debug)) { + this.output.appendLine(`${this.timestamp} ${message ?? emptyStr}${this.toLoggableParams(false, params)}`); } } @@ -161,17 +161,17 @@ export class Logger { } else { message = params.shift(); - if (contextOrMessage !== undefined) { - message = `${contextOrMessage.prefix} ${message || emptyStr}`; + if (contextOrMessage != null) { + message = `${contextOrMessage.prefix} ${message ?? emptyStr}`; } } if (Logger.isDebugging) { - console.log(this.timestamp, ConsolePrefix, message || emptyStr, ...params); + console.log(this.timestamp, ConsolePrefix, message ?? emptyStr, ...params); } - if (this.output !== undefined && (this.level === TraceLevel.Verbose || this.level === TraceLevel.Debug)) { - this.output.appendLine(`${this.timestamp} ${message || emptyStr}${this.toLoggableParams(true, params)}`); + if (this.output != null && (this.level === TraceLevel.Verbose || this.level === TraceLevel.Debug)) { + this.output.appendLine(`${this.timestamp} ${message ?? emptyStr}${this.toLoggableParams(true, params)}`); } } @@ -186,29 +186,29 @@ export class Logger { } else { message = params.shift(); - if (contextOrMessage !== undefined) { - message = `${contextOrMessage.prefix} ${message || emptyStr}`; + if (contextOrMessage != null) { + message = `${contextOrMessage.prefix} ${message ?? emptyStr}`; } } if (Logger.isDebugging) { - console.warn(this.timestamp, ConsolePrefix, message || emptyStr, ...params); + console.warn(this.timestamp, ConsolePrefix, message ?? emptyStr, ...params); } - if (this.output !== undefined && this.level !== TraceLevel.Silent) { - this.output.appendLine(`${this.timestamp} ${message || emptyStr}${this.toLoggableParams(false, params)}`); + if (this.output != null && this.level !== TraceLevel.Silent) { + this.output.appendLine(`${this.timestamp} ${message ?? emptyStr}${this.toLoggableParams(false, params)}`); } } static showOutputChannel() { - if (this.output === undefined) return; + if (this.output == null) return; this.output.show(); } static toLoggable(p: any, sanitize?: ((key: string, value: any) => any) | undefined) { if (typeof p !== 'object') return String(p); - if (this.customLoggableFn !== undefined) { + if (this.customLoggableFn != null) { const loggable = this.customLoggableFn(p); if (loggable != null) return loggable; } @@ -221,6 +221,7 @@ export class Logger { } } + // eslint-disable-next-line @typescript-eslint/ban-types static toLoggableName(instance: Function | object) { let name: string; if (typeof instance === 'function') { @@ -257,10 +258,11 @@ export class Logger { private static _isDebugging: boolean | undefined; static get isDebugging() { - if (this._isDebugging === undefined) { + if (this._isDebugging == null) { const env = process.env; - this._isDebugging = - env && env.VSCODE_DEBUGGING_EXTENSION ? isDebuggingRegex.test(env.VSCODE_DEBUGGING_EXTENSION) : false; + this._isDebugging = env?.VSCODE_DEBUGGING_EXTENSION + ? isDebuggingRegex.test(env.VSCODE_DEBUGGING_EXTENSION) + : false; } return this._isDebugging; @@ -271,7 +273,7 @@ export class Logger { static logGitCommand(command: string, ex?: Error): void { if (this.level !== TraceLevel.Debug) return; - if (this.gitOutput === undefined) { + if (this.gitOutput == null) { this.gitOutput = window.createOutputChannel(`${extensionOutputChannelName} (Git)`); } this.gitOutput.appendLine(`${this.timestamp} ${command}${ex != null ? `\n\n${ex.toString()}` : emptyStr}`); diff --git a/src/messages.ts b/src/messages.ts index 54e5443..712c7ee 100644 --- a/src/messages.ts +++ b/src/messages.ts @@ -198,7 +198,7 @@ export class Messages { } private static suppressedMessage(suppressionKey: SuppressedMessages) { - const messages: { [key: string]: boolean | undefined } = configuration.get('advanced', 'messages'); + const messages: Record = configuration.get('advanced', 'messages'); messages[suppressionKey] = true; diff --git a/src/quickpicks/commitPicker.ts b/src/quickpicks/commitPicker.ts index 216780a..3f671e9 100644 --- a/src/quickpicks/commitPicker.ts +++ b/src/quickpicks/commitPicker.ts @@ -103,14 +103,14 @@ export namespace CommitPicker { { onDidPressKey: key => { if (quickpick.activeItems.length !== 0) { - options.onDidPressKey!(key, quickpick); + void options.onDidPressKey!(key, quickpick); } }, } as KeyCommand, ]), ), ); - scope.start(); + void scope.start(); disposables.push(scope); } @@ -124,7 +124,7 @@ export namespace CommitPicker { if (DirectiveQuickPickItem.is(item)) { switch (item.directive) { case Directive.LoadMore: - loadMore(); + void loadMore(); return; default: diff --git a/src/quickpicks/commitQuickPickItems.ts b/src/quickpicks/commitQuickPickItems.ts index dcf46ec..e7ed591 100644 --- a/src/quickpicks/commitQuickPickItems.ts +++ b/src/quickpicks/commitQuickPickItems.ts @@ -67,7 +67,7 @@ export class CommitFileQuickPickItem extends CommandQuickPickItem { export class CommitCopyIdQuickPickItem extends CommandQuickPickItem { constructor(private readonly commit: GitLogCommit, item?: QuickPickItem) { - super(item || '$(clippy) Copy Commit ID'); + super(item ?? '$(clippy) Copy Commit ID'); } execute(): Promise { @@ -76,13 +76,13 @@ export class CommitCopyIdQuickPickItem extends CommandQuickPickItem { async onDidPressKey(key: Keys): Promise { await super.onDidPressKey(key); - window.showInformationMessage('Commit ID copied to the clipboard'); + void window.showInformationMessage('Commit ID copied to the clipboard'); } } export class CommitCopyMessageQuickPickItem extends CommandQuickPickItem { constructor(private readonly commit: GitLogCommit, item?: QuickPickItem) { - super(item || '$(clippy) Copy Message'); + super(item ?? '$(clippy) Copy Message'); } execute(): Promise { @@ -91,7 +91,9 @@ export class CommitCopyMessageQuickPickItem extends CommandQuickPickItem { async onDidPressKey(key: Keys): Promise { await super.onDidPressKey(key); - window.showInformationMessage(`${this.commit.isStash ? 'Stash' : 'Commit'} Message copied to the clipboard`); + void window.showInformationMessage( + `${this.commit.isStash ? 'Stash' : 'Commit'} Message copied to the clipboard`, + ); } } @@ -157,7 +159,7 @@ export class CommitOpenChangesWithWorkingCommandQuickPickItem extends CommandQui export class CommitOpenDirectoryCompareCommandQuickPickItem extends CommandQuickPickItem { constructor(private readonly commit: GitLogCommit, item?: QuickPickItem) { - super(item || '$(git-compare) Open Directory Compare'); + super(item ?? '$(git-compare) Open Directory Compare'); } execute(): Promise { @@ -167,7 +169,7 @@ export class CommitOpenDirectoryCompareCommandQuickPickItem extends CommandQuick export class CommitOpenDirectoryCompareWithWorkingCommandQuickPickItem extends CommandQuickPickItem { constructor(private readonly commit: GitLogCommit, item?: QuickPickItem) { - super(item || '$(git-compare) Open Directory Compare with Working Tree'); + super(item ?? '$(git-compare) Open Directory Compare with Working Tree'); } execute(): Promise { @@ -187,7 +189,7 @@ export class CommitOpenFilesCommandQuickPickItem extends CommandQuickPickItem { export class CommitOpenFileCommandQuickPickItem extends CommandQuickPickItem { constructor(private readonly commit: GitLogCommit, private readonly file: string | GitFile, item?: QuickPickItem) { - super(item || '$(file) Open File'); + super(item ?? '$(file) Open File'); } execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise { @@ -207,7 +209,7 @@ export class CommitOpenRevisionsCommandQuickPickItem extends CommandQuickPickIte export class CommitOpenRevisionCommandQuickPickItem extends CommandQuickPickItem { constructor(private readonly commit: GitLogCommit, private readonly file: string | GitFile, item?: QuickPickItem) { - super(item || '$(file) Open File at Revision'); + super(item ?? '$(file) Open File at Revision'); } execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise { @@ -217,7 +219,7 @@ export class CommitOpenRevisionCommandQuickPickItem extends CommandQuickPickItem export class CommitApplyFileChangesCommandQuickPickItem extends CommandQuickPickItem { constructor(private readonly commit: GitLogCommit, private readonly file: string | GitFile, item?: QuickPickItem) { - super(item || 'Apply Changes'); + super(item ?? 'Apply Changes'); } async execute(): Promise { @@ -228,7 +230,7 @@ export class CommitApplyFileChangesCommandQuickPickItem extends CommandQuickPick export class CommitRestoreFileChangesCommandQuickPickItem extends CommandQuickPickItem { constructor(private readonly commit: GitLogCommit, private readonly file: string | GitFile, item?: QuickPickItem) { super( - item || { + item ?? { label: 'Restore', description: 'aka checkout', }, diff --git a/src/quickpicks/gitQuickPickItems.ts b/src/quickpicks/gitQuickPickItems.ts index aa69512..dc98274 100644 --- a/src/quickpicks/gitQuickPickItems.ts +++ b/src/quickpicks/gitQuickPickItems.ts @@ -139,7 +139,7 @@ export class CommitLoadMoreQuickPickItem implements QuickPickItem { readonly alwaysShow = true; } -export interface CommitQuickPickItem extends QuickPickItemOfT {} +export type CommitQuickPickItem = QuickPickItemOfT export namespace CommitQuickPickItem { export function create( @@ -213,7 +213,7 @@ export namespace CommitQuickPickItem { } } -export interface ContributorQuickPickItem extends QuickPickItemOfT {} +export type ContributorQuickPickItem = QuickPickItemOfT export namespace ContributorQuickPickItem { export function create( diff --git a/src/quickpicks/quickPicksItems.ts b/src/quickpicks/quickPicksItems.ts index c13dc75..73e6d1b 100644 --- a/src/quickpicks/quickPicksItems.ts +++ b/src/quickpicks/quickPicksItems.ts @@ -140,10 +140,10 @@ export class CommandQuickPickItem implements Qu } } - execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise { + execute(_options?: { preserveFocus?: boolean; preview?: boolean }): Promise { if (this.command === undefined) return Promise.resolve(undefined); - const result = commands.executeCommand(this.command, ...(this.args || [])) as Promise; + const result = commands.executeCommand(this.command, ...(this.args ?? [])) as Promise; // this.options?.onDidExecute?.(options, result); return result; } @@ -157,7 +157,7 @@ export class CommandQuickPickItem implements Qu } } -export interface FlagsQuickPickItem extends QuickPickItemOfT {} +export type FlagsQuickPickItem = QuickPickItemOfT; export namespace FlagsQuickPickItem { export function create(flags: T[], item: T[], options: QuickPickItem) { return { ...options, item: item, picked: hasFlags(flags, item) }; @@ -182,7 +182,7 @@ export class OpenInSearchCommitsViewQuickPickItem extends CommandQuickPickItem { super(item, undefined, undefined); } - async execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise<{} | undefined> { + async execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise { void (await Container.searchView.search( this.reference.repoPath, { @@ -199,8 +199,6 @@ export class OpenInSearchCommitsViewQuickPickItem extends CommandQuickPickItem { }, }, )); - - return undefined; } } @@ -217,7 +215,7 @@ export class RevealInRepositoriesViewQuickPickItem extends CommandQuickPickItem super(item, undefined, undefined); } - async execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise<{} | undefined> { + async execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise { if (GitStashCommit.is(this.reference)) { void (await Container.repositoriesView.revealStash(this.reference, { select: true, @@ -231,7 +229,5 @@ export class RevealInRepositoriesViewQuickPickItem extends CommandQuickPickItem expand: true, })); } - - return undefined; } } diff --git a/src/quickpicks/referencePicker.ts b/src/quickpicks/referencePicker.ts index fcad205..3ab0daa 100644 --- a/src/quickpicks/referencePicker.ts +++ b/src/quickpicks/referencePicker.ts @@ -57,14 +57,14 @@ export namespace ReferencePicker { { onDidPressKey: key => { if (quickpick.activeItems.length !== 0) { - options.onDidPressKey!(key, quickpick); + void options.onDidPressKey!(key, quickpick); } }, } as KeyCommand, ]), ), ); - scope.start(); + void scope.start(); disposables.push(scope); } diff --git a/src/quickpicks/remoteProviderPicker.ts b/src/quickpicks/remoteProviderPicker.ts index 98d19f0..8634af9 100644 --- a/src/quickpicks/remoteProviderPicker.ts +++ b/src/quickpicks/remoteProviderPicker.ts @@ -44,12 +44,12 @@ export class CopyRemoteResourceCommandQuickPickItem extends CommandQuickPickItem async onDidPressKey(key: Keys): Promise { await super.onDidPressKey(key); - window.showInformationMessage('Url copied to the clipboard'); + void window.showInformationMessage('Url copied to the clipboard'); } } export class OpenRemoteResourceCommandQuickPickItem extends CommandQuickPickItem { - constructor(remotes: GitRemote[], resource: RemoteResource, goBackCommand?: CommandQuickPickItem) { + constructor(remotes: GitRemote[], resource: RemoteResource) { const providers = GitRemote.getHighlanderProviders(remotes); const commandArgs: OpenOnRemoteCommandArgs = { resource: resource, diff --git a/src/statusbar/statusBarController.ts b/src/statusbar/statusBarController.ts index 44dbd8c..ddfabe9 100644 --- a/src/statusbar/statusBarController.ts +++ b/src/statusbar/statusBarController.ts @@ -10,7 +10,7 @@ import { debug } from '../system'; export class StatusBarController implements Disposable { private _blameStatusBarItem: StatusBarItem | undefined; - private _disposable: Disposable; + private readonly _disposable: Disposable; private _modeStatusBarItem: StatusBarItem | undefined; constructor() { @@ -21,11 +21,11 @@ export class StatusBarController implements Disposable { dispose() { this.clearBlame(); - this._blameStatusBarItem && this._blameStatusBarItem.dispose(); - this._modeStatusBarItem && this._modeStatusBarItem.dispose(); + this._blameStatusBarItem?.dispose(); + this._modeStatusBarItem?.dispose(); Container.lineTracker.stop(this); - this._disposable && this._disposable.dispose(); + this._disposable.dispose(); } private onConfigurationChanged(e: ConfigurationChangeEvent) { @@ -34,21 +34,21 @@ export class StatusBarController implements Disposable { Container.config.mode.active && Container.config.mode.statusBar.enabled ? Container.config.modes[Container.config.mode.active] : undefined; - if (mode && mode.statusBarItemName) { + if (mode?.statusBarItemName) { const alignment = Container.config.mode.statusBar.alignment !== 'left' ? StatusBarAlignment.Right : StatusBarAlignment.Left; if (configuration.changed(e, 'mode', 'statusBar', 'alignment')) { - if (this._modeStatusBarItem !== undefined && this._modeStatusBarItem.alignment !== alignment) { - this._modeStatusBarItem.dispose(); + if (this._modeStatusBarItem?.alignment !== alignment) { + this._modeStatusBarItem?.dispose(); this._modeStatusBarItem = undefined; } } this._modeStatusBarItem = - this._modeStatusBarItem || + this._modeStatusBarItem ?? window.createStatusBarItem(alignment, alignment === StatusBarAlignment.Right ? 999 : 1); this._modeStatusBarItem.command = Commands.SwitchMode; this._modeStatusBarItem.text = mode.statusBarItemName; @@ -74,7 +74,7 @@ export class StatusBarController implements Disposable { } this._blameStatusBarItem = - this._blameStatusBarItem || + this._blameStatusBarItem ?? window.createStatusBarItem(alignment, alignment === StatusBarAlignment.Right ? 1000 : 0); this._blameStatusBarItem.command = Container.config.statusBar.command; @@ -111,7 +111,7 @@ export class StatusBarController implements Disposable { ); if (!e.pending && e.lines !== undefined) { const state = Container.lineTracker.getState(e.lines[0]); - if (state !== undefined && state.commit !== undefined) { + if (state?.commit !== undefined) { this.updateBlame(state.commit, e.editor!); return; diff --git a/src/system.ts b/src/system.ts index 38ce6c8..4628d64 100644 --- a/src/system.ts +++ b/src/system.ts @@ -1,7 +1,7 @@ 'use strict'; declare global { - export type PartialDeep = T extends object ? { [K in keyof T]?: PartialDeep } : T; + export type PartialDeep = T extends Record ? { [K in keyof T]?: PartialDeep } : T; export type PickPartialDeep = Omit, K> & { [P in K]?: Partial }; export type Mutable = { -readonly [P in keyof T]: T[P] }; diff --git a/src/system/array.ts b/src/system/array.ts index 81ef50c..d1e70c3 100644 --- a/src/system/array.ts +++ b/src/system/array.ts @@ -7,8 +7,8 @@ import { } from 'lodash-es'; export namespace Arrays { - export function countUniques(source: T[], accessor: (item: T) => string): { [key: string]: number } { - const uniqueCounts: Record = Object.create(null); + export function countUniques(source: T[], accessor: (item: T) => string): Record { + const uniqueCounts = Object.create(null) as Record; for (const item of source) { const value = accessor(item); uniqueCounts[value] = (uniqueCounts[value] ?? 0) + 1; @@ -46,19 +46,19 @@ export namespace Arrays { export const findLastIndex = _findLastIndex; - export function groupBy(source: T[], accessor: (item: T) => string): { [key: string]: T[] } { + export function groupBy(source: T[], accessor: (item: T) => string): Record { return source.reduce((groupings, current) => { const value = accessor(current); - groupings[value] = groupings[value] || []; + groupings[value] = groupings[value] ?? []; groupings[value].push(current); return groupings; - }, Object.create(null)); + }, Object.create(null) as Record); } export function groupByMap(source: TValue[], accessor: (item: TValue) => TKey): Map { return source.reduce((groupings, current) => { const value = accessor(current); - const group = groupings.get(value) || []; + const group = groupings.get(value) ?? []; groupings.set(value, group); group.push(current); return groupings; @@ -74,7 +74,7 @@ export namespace Arrays { const mapped = predicateMapper(current); if (mapped != null) { const value = accessor(current); - const group = groupings.get(value) || []; + const group = groupings.get(value) ?? []; groupings.set(value, group); group.push(mapped); } @@ -190,9 +190,10 @@ export namespace Arrays { } export function uniqueBy(source: T[], accessor: (item: T) => any, predicate?: (item: T) => boolean): T[] { - const uniqueValues = Object.create(null); + const uniqueValues = Object.create(null) as Record; return source.filter(item => { const value = accessor(item); + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (uniqueValues[value]) return false; uniqueValues[value] = accessor; diff --git a/src/system/decorators/gate.ts b/src/system/decorators/gate.ts index 449709e..596606d 100644 --- a/src/system/decorators/gate.ts +++ b/src/system/decorators/gate.ts @@ -20,6 +20,7 @@ function defaultResolver(...args: any[]): string { export function gate any>(resolver?: (...args: Parameters) => string) { return (target: any, key: string, descriptor: PropertyDescriptor) => { + // eslint-disable-next-line @typescript-eslint/ban-types let fn: Function | undefined; if (typeof descriptor.value === 'function') { fn = descriptor.value; @@ -32,7 +33,7 @@ export function gate any>(resolver?: (...args: Parame descriptor.value = function (this: any, ...args: any[]) { const prop = - args.length === 0 ? gateKey : `${gateKey}$${(resolver || defaultResolver)(...(args as Parameters))}`; + args.length === 0 ? gateKey : `${gateKey}$${(resolver ?? defaultResolver)(...(args as Parameters))}`; if (!Object.prototype.hasOwnProperty.call(this, prop)) { Object.defineProperty(this, prop, { diff --git a/src/system/decorators/log.ts b/src/system/decorators/log.ts index 43378a0..4e04f0a 100644 --- a/src/system/decorators/log.ts +++ b/src/system/decorators/log.ts @@ -44,6 +44,7 @@ export interface LogContext { export const LogInstanceNameFn = Symbol('logInstanceNameFn'); export function logName(fn: (c: T, name: string) => string) { + // eslint-disable-next-line @typescript-eslint/ban-types return (target: Function) => { (target as any)[LogInstanceNameFn] = fn; }; @@ -51,7 +52,7 @@ export function logName(fn: (c: T, name: string) => string) { export function debug any>( options: { - args?: false | { [arg: string]: (arg: any) => string | false }; + args?: false | Record string | false>; condition?(...args: Parameters): boolean; correlate?: boolean; enter?(...args: Parameters): string; @@ -69,7 +70,7 @@ type PromiseType = T extends Promise ? U : T; export function log any>( options: { - args?: false | { [arg: number]: (arg: any) => string | false }; + args?: false | Record string | false>; condition?(...args: Parameters): boolean; correlate?: boolean; debug?: boolean; @@ -87,7 +88,8 @@ export function log any>( | typeof Logger.debug | typeof Logger.log; - return (target: any, key: string, descriptor: PropertyDescriptor & { [key: string]: any }) => { + return (target: any, key: string, descriptor: PropertyDescriptor & Record) => { + // eslint-disable-next-line @typescript-eslint/ban-types let fn: Function | undefined; let fnKey: string | undefined; if (typeof descriptor.value === 'function') { @@ -116,7 +118,8 @@ export function log any>( let instanceName: string; if (this != null) { instanceName = Logger.toLoggableName(this); - if (this.constructor != null && this.constructor[LogInstanceNameFn]) { + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions + if (this.constructor?.[LogInstanceNameFn]) { instanceName = target.constructor[LogInstanceNameFn](this, instanceName); } } else { @@ -198,9 +201,7 @@ export function log any>( ex, `${prefix}${enter}`, `failed${ - correlationContext !== undefined && correlationContext.exitDetails - ? correlationContext.exitDetails - : emptyStr + correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr }${timing}`, loggableParams, ); @@ -209,9 +210,7 @@ export function log any>( ex, prefix, `failed${ - correlationContext !== undefined && correlationContext.exitDetails - ? correlationContext.exitDetails - : emptyStr + correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr }${timing}`, ); } @@ -247,18 +246,14 @@ export function log any>( if (!options.debug) { Logger.logWithDebugParams( `${prefix}${enter} ${exit}${ - correlationContext !== undefined && correlationContext.exitDetails - ? correlationContext.exitDetails - : emptyStr + correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr }${timing}`, loggableParams, ); } else { logFn( `${prefix}${enter} ${exit}${ - correlationContext !== undefined && correlationContext.exitDetails - ? correlationContext.exitDetails - : emptyStr + correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr }${timing}`, loggableParams, ); @@ -266,9 +261,7 @@ export function log any>( } else { logFn( `${prefix} ${exit}${ - correlationContext !== undefined && correlationContext.exitDetails - ? correlationContext.exitDetails - : emptyStr + correlationContext?.exitDetails ? correlationContext.exitDetails : emptyStr }${timing}`, ); } diff --git a/src/system/decorators/memoize.ts b/src/system/decorators/memoize.ts index cf7bea8..ed9777b 100644 --- a/src/system/decorators/memoize.ts +++ b/src/system/decorators/memoize.ts @@ -18,7 +18,8 @@ function defaultResolver(...args: any[]): string { } export function memoize any>(resolver?: (...args: Parameters) => string) { - return (target: any, key: string, descriptor: PropertyDescriptor & { [key: string]: any }) => { + return (target: any, key: string, descriptor: PropertyDescriptor & Record) => { + // eslint-disable-next-line @typescript-eslint/ban-types let fn: Function | undefined; let fnKey: string | undefined; @@ -41,7 +42,7 @@ export function memoize any>(resolver?: (...args: Par const prop = fnKey === 'get' || args.length === 0 ? memoizeKey - : `${memoizeKey}$${(resolver || defaultResolver)(...(args as Parameters))}`; + : `${memoizeKey}$${(resolver ?? defaultResolver)(...(args as Parameters))}`; if (Object.prototype.hasOwnProperty.call(this, prop)) { result = this[prop]; diff --git a/src/system/decorators/timeout.ts b/src/system/decorators/timeout.ts index d634031..38bc0e0 100644 --- a/src/system/decorators/timeout.ts +++ b/src/system/decorators/timeout.ts @@ -19,6 +19,7 @@ export function timeout any>( } return (target: any, key: string, descriptor: PropertyDescriptor) => { + // eslint-disable-next-line @typescript-eslint/ban-types let fn: Function | undefined; if (typeof descriptor.value === 'function') { fn = descriptor.value; diff --git a/src/system/function.ts b/src/system/function.ts index 1f61931..3d2a317 100644 --- a/src/system/function.ts +++ b/src/system/function.ts @@ -41,7 +41,7 @@ export namespace Functions { ): T & Deferrable { const { track, ...opts }: DebounceOptions = { track: false, - ...(options || {}), + ...(options ?? {}), }; if (track !== true) return _debounce(fn, wait, opts); @@ -103,6 +103,7 @@ export namespace Functions { const fnBodyStripCommentsRegex = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm; const fnBodyStripParamDefaultValueRegex = /\s?=.*$/; + // eslint-disable-next-line @typescript-eslint/ban-types export function getParameters(fn: Function): string[] { if (typeof fn !== 'function') throw new Error('Not supported'); diff --git a/src/system/object.ts b/src/system/object.ts index fbaeb7b..fac1210 100644 --- a/src/system/object.ts +++ b/src/system/object.ts @@ -3,21 +3,21 @@ import { isEqual as _isEqual } from 'lodash-es'; import { Arrays } from './array'; export namespace Objects { - export function entries(o: { [key: string]: T }): IterableIterator<[string, T]>; - export function entries(o: { [key: number]: T }): IterableIterator<[string, T]>; + export function entries(o: Record): IterableIterator<[string, T]>; + export function entries(o: Record): IterableIterator<[string, T]>; export function* entries(o: any): IterableIterator<[string, T]> { for (const key in o) { yield [key, o[key]]; } } - export function flatten(o: any, prefix: string = '', stringify: boolean = false): { [key: string]: any } { - const flattened = Object.create(null); + export function flatten(o: any, prefix: string = '', stringify: boolean = false): Record { + const flattened = Object.create(null) as Record; _flatten(flattened, prefix, o, stringify); return flattened; } - function _flatten(flattened: { [key: string]: any }, key: string, value: any, stringify: boolean = false) { + function _flatten(flattened: Record, key: string, value: any, stringify: boolean = false) { if (Object(value) !== value) { if (stringify) { if (value == null) { @@ -61,7 +61,7 @@ export namespace Objects { return isEqual(value, other); } - export function paths(o: { [key: string]: any }, path?: string): string[] { + export function paths(o: Record, path?: string): string[] { const results = []; for (const key in o) { @@ -76,8 +76,8 @@ export namespace Objects { return results; } - export function values(o: { [key: string]: T }): IterableIterator; - export function values(o: { [key: number]: T }): IterableIterator; + export function values(o: Record): IterableIterator; + export function values(o: Record): IterableIterator; export function* values(o: any): IterableIterator { for (const key in o) { yield o[key]; diff --git a/src/system/promise.ts b/src/system/promise.ts index 349becd..93fad2b 100644 --- a/src/system/promise.ts +++ b/src/system/promise.ts @@ -34,7 +34,7 @@ export namespace Promises { if (typeof options.onDidCancel === 'function') { options.onDidCancel(resolve, reject); } else { - reject(new CancellationError(promise, options.cancelMessage || 'TIMED OUT')); + reject(new CancellationError(promise, options.cancelMessage ?? 'TIMED OUT')); } }, timeoutOrToken); } else { @@ -44,7 +44,7 @@ export namespace Promises { if (typeof options.onDidCancel === 'function') { options.onDidCancel(resolve, reject); } else { - reject(new CancellationError(promise, options.cancelMessage || 'CANCELLED')); + reject(new CancellationError(promise, options.cancelMessage ?? 'CANCELLED')); } }); } diff --git a/src/system/searchTree.ts b/src/system/searchTree.ts index 8e9a72f..9a5715e 100644 --- a/src/system/searchTree.ts +++ b/src/system/searchTree.ts @@ -1,3 +1,5 @@ +/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */ +/* eslint-disable @typescript-eslint/strict-boolean-expressions */ 'use strict'; import { Iterables } from './iterable'; import { Strings } from './string'; @@ -278,7 +280,7 @@ export class TernarySearchTree { break; } } - return (node && node.value) || candidate; + return node?.value || candidate; } findSuperstr(key: string, limit: boolean = false): Iterable | undefined { diff --git a/src/system/string.ts b/src/system/string.ts index ed318f2..8d86b33 100644 --- a/src/system/string.ts +++ b/src/system/string.ts @@ -102,14 +102,15 @@ export namespace Strings { return tokens; } + // eslint-disable-next-line @typescript-eslint/ban-types const interpolationMap = new Map(); export function interpolate(template: string, context: object | undefined): string { if (template == null || template.length === 0) return template; - if (context === undefined) return template.replace(tokenSanitizeRegex, emptyStr); + if (context == null) return template.replace(tokenSanitizeRegex, emptyStr); let fn = interpolationMap.get(template); - if (fn === undefined) { + if (fn == null) { // eslint-disable-next-line @typescript-eslint/no-implied-eval fn = new Function(`return \`${template.replace(tokenSanitizeRegex, tokenSanitizeReplacement)}\`;`); interpolationMap.set(template, fn); @@ -170,19 +171,19 @@ export namespace Strings { } export function padLeft(s: string, padTo: number, padding: string = '\u00a0', width?: number) { - const diff = padTo - (width || getWidth(s)); + const diff = padTo - (width ?? getWidth(s)); return diff <= 0 ? s : padding.repeat(diff) + s; } export function padLeftOrTruncate(s: string, max: number, padding?: string, width?: number) { - width = width || getWidth(s); + width = width ?? getWidth(s); if (width < max) return padLeft(s, max, padding, width); if (width > max) return truncate(s, max, undefined, width); return s; } export function padRight(s: string, padTo: number, padding: string = '\u00a0', width?: number) { - const diff = padTo - (width || getWidth(s)); + const diff = padTo - (width ?? getWidth(s)); return diff <= 0 ? s : s + padding.repeat(diff); } @@ -190,14 +191,14 @@ export namespace Strings { const left = max < 0; max = Math.abs(max); - width = width || getWidth(s); + width = width ?? getWidth(s); if (width < max) return left ? padLeft(s, max, padding, width) : padRight(s, max, padding, width); if (width > max) return truncate(s, max, undefined, width); return s; } export function padRightOrTruncate(s: string, max: number, padding?: string, width?: number) { - width = width || getWidth(s); + width = width ?? getWidth(s); if (width < max) return padRight(s, max, padding, width); if (width > max) return truncate(s, max); return s; @@ -218,7 +219,7 @@ export namespace Strings { : options.number != null ? options.number : count - } ${count === 1 ? s : options.plural || `${s}${options.suffix || 's'}`}`; + } ${count === 1 ? s : options.plural ?? `${s}${options.suffix ?? 's'}`}`; } // Removes \ / : * ? " < > | and C0 and C1 control codes diff --git a/src/telemetry.ts b/src/telemetry.ts index db9c25a..64f7022 100644 --- a/src/telemetry.ts +++ b/src/telemetry.ts @@ -22,13 +22,13 @@ // Logger.log(`Telemetry.configure ${GlyphChars.Dot} ${Strings.getDurationMilliseconds(start)} ms`); // } -// static setContext(context?: { [key: string]: string }) { +// static setContext(context?: Record) { // if (_reporter === undefined) return; // _reporter.setContext(context); // } -// static trackEvent(name: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number; }) { +// static trackEvent(name: string, properties?: Record, measurements?: Record) { // if (_reporter === undefined) return; // _reporter.trackEvent(name, properties, measurements); @@ -45,7 +45,7 @@ // private appInsights: ApplicationInsights; // private _client: Client; -// private _context: { [key: string]: string }; +// private _context: Record; // constructor(key: string) { // const diagChannelState = process.env['APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL']; @@ -75,7 +75,7 @@ // this.stripPII(this._client); // } -// setContext(context?: { [key: string]: string }) { +// setContext(context?: Record) { // if (!this._context) { // this._context = Object.create(null); @@ -96,7 +96,7 @@ // Object.assign(this._client.commonProperties, this._context); // } -// trackEvent(name: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number; }) { +// trackEvent(name: string, properties?: Record, measurements?: Record) { // this._client.trackEvent(name, properties, measurements); // } diff --git a/src/trackers/documentTracker.ts b/src/trackers/documentTracker.ts index c3016ee..d00b3ba 100644 --- a/src/trackers/documentTracker.ts +++ b/src/trackers/documentTracker.ts @@ -64,7 +64,7 @@ export class DocumentTracker implements Disposable { private _dirtyIdleTriggerDelay!: number; private readonly _disposable: Disposable | undefined; - private readonly _documentMap: Map> = new Map(); + private readonly _documentMap = new Map>(); constructor() { this._disposable = Disposable.from( @@ -120,7 +120,7 @@ export class DocumentTracker implements Disposable { this._timer = setTimeout(() => { this._timer = undefined; - setCommandContext(CommandContext.ActiveFileStatus, undefined); + void setCommandContext(CommandContext.ActiveFileStatus, undefined); }, 250); return; @@ -257,7 +257,7 @@ export class DocumentTracker implements Disposable { try { document = await workspace.openTextDocument(documentOrId.documentUri({ useVersionedPath: true })); } catch (ex) { - const msg = ex.toString(); + const msg: string = ex?.toString() ?? ''; if (msg.includes('File seems to be binary and cannot be opened as text')) { document = new BinaryTextDocument(documentOrId); } else if ( @@ -394,25 +394,25 @@ class EmptyTextDocument implements TextDocument { this.version = 0; } - getText(range?: Range | undefined): string { + getText(_range?: Range | undefined): string { throw new Error('Method not supported.'); } - getWordRangeAtPosition(position: Position, regex?: RegExp | undefined): Range | undefined { + getWordRangeAtPosition(_position: Position, _regex?: RegExp | undefined): Range | undefined { throw new Error('Method not supported.'); } lineAt(line: number): TextLine; lineAt(position: Position): TextLine; - lineAt(position: any): TextLine { + lineAt(_position: any): TextLine { throw new Error('Method not supported.'); } - offsetAt(position: Position): number { + offsetAt(_position: Position): number { throw new Error('Method not supported.'); } - positionAt(offset: number): Position { + positionAt(_offset: number): Position { throw new Error('Method not supported.'); } @@ -420,11 +420,11 @@ class EmptyTextDocument implements TextDocument { throw new Error('Method not supported.'); } - validatePosition(position: Position): Position { + validatePosition(_position: Position): Position { throw new Error('Method not supported.'); } - validateRange(range: Range): Range { + validateRange(_range: Range): Range { throw new Error('Method not supported.'); } } diff --git a/src/trackers/gitDocumentTracker.ts b/src/trackers/gitDocumentTracker.ts index 0466fb1..beeb20c 100644 --- a/src/trackers/gitDocumentTracker.ts +++ b/src/trackers/gitDocumentTracker.ts @@ -14,7 +14,7 @@ export type CachedDiff = CachedItem; export type CachedLog = CachedItem; export class GitDocumentState { - private cache: Map = new Map(); + private cache = new Map(); constructor(public readonly key: string) {} diff --git a/src/trackers/gitLineTracker.ts b/src/trackers/gitLineTracker.ts index ab926f1..17af2c3 100644 --- a/src/trackers/gitLineTracker.ts +++ b/src/trackers/gitLineTracker.ts @@ -66,7 +66,7 @@ export class GitLineTracker extends LineTracker { }`, }, }) - private onBlameStateChanged(e: DocumentBlameStateChangeEvent) { + private onBlameStateChanged(_e: DocumentBlameStateChangeEvent) { this.trigger('editor'); } diff --git a/src/trackers/lineTracker.ts b/src/trackers/lineTracker.ts index b7b8c3c..a9c99c3 100644 --- a/src/trackers/lineTracker.ts +++ b/src/trackers/lineTracker.ts @@ -20,7 +20,7 @@ export class LineTracker implements Disposable { protected _disposable: Disposable | undefined; private _editor: TextEditor | undefined; - private readonly _state: Map = new Map(); + private readonly _state = new Map(); dispose() { for (const subscriber of this._subscriptions.keys()) { @@ -67,7 +67,7 @@ export class LineTracker implements Disposable { } includes(line: number): boolean { - return this._lines !== undefined && this._lines.includes(line); + return this._lines?.includes(line) ?? false; } includesAll(lines: number[] | undefined): boolean { @@ -82,7 +82,7 @@ export class LineTracker implements Disposable { this._state.clear(); } - private _subscriptions: Map = new Map(); + private _subscriptions = new Map(); isSubscribed(subscriber: any) { return this._subscriptions.has(subscriber); diff --git a/src/trackers/trackedDocument.ts b/src/trackers/trackedDocument.ts index 7c17147..df1274c 100644 --- a/src/trackers/trackedDocument.ts +++ b/src/trackers/trackedDocument.ts @@ -120,7 +120,7 @@ export class TrackedDocument implements Disposable { } activate() { - setCommandContext(CommandContext.ActiveFileStatus, this.getStatus()); + void setCommandContext(CommandContext.ActiveFileStatus, this.getStatus()); } async ensureInitialized() { @@ -197,7 +197,7 @@ export class TrackedDocument implements Disposable { if (active !== undefined) { const blameable = this.isBlameable; - setCommandContext(CommandContext.ActiveFileStatus, this.getStatus()); + void setCommandContext(CommandContext.ActiveFileStatus, this.getStatus()); if (!options.initializing && wasBlameable !== blameable) { const e: DocumentBlameStateChangeEvent = { editor: active, document: this, blameable: blameable }; diff --git a/src/views/compareView.ts b/src/views/compareView.ts index 1bc8d42..ffa12c0 100644 --- a/src/views/compareView.ts +++ b/src/views/compareView.ts @@ -17,7 +17,7 @@ export class CompareView extends ViewBase { constructor() { super('gitlens.views.compare', 'Compare'); - setCommandContext(CommandContext.ViewsCompareKeepResults, this.keepResults); + void setCommandContext(CommandContext.ViewsCompareKeepResults, this.keepResults); } getRoot() { @@ -149,13 +149,13 @@ export class CompareView extends ViewBase { async updatePinnedComparison(id: string, pin?: PinnedComparison) { let pinned = Container.context.workspaceState.get(WorkspaceState.PinnedComparisons); if (pinned == null) { - pinned = Object.create(null); + pinned = Object.create(null) as PinnedComparisons; } if (pin !== undefined) { - pinned![id] = { ...pin }; + pinned[id] = { ...pin }; } else { - const { [id]: _, ...rest } = pinned!; + const { [id]: _, ...rest } = pinned; pinned = rest; } @@ -178,8 +178,8 @@ export class CompareView extends ViewBase { } private setKeepResults(enabled: boolean) { - Container.context.workspaceState.update(WorkspaceState.ViewsCompareKeepResults, enabled); - setCommandContext(CommandContext.ViewsCompareKeepResults, enabled); + void Container.context.workspaceState.update(WorkspaceState.ViewsCompareKeepResults, enabled); + void setCommandContext(CommandContext.ViewsCompareKeepResults, enabled); } private setShowAvatars(enabled: boolean) { diff --git a/src/views/fileHistoryView.ts b/src/views/fileHistoryView.ts index 65693c6..0cb7b47 100644 --- a/src/views/fileHistoryView.ts +++ b/src/views/fileHistoryView.ts @@ -87,7 +87,7 @@ export class FileHistoryView extends ViewBase { } if (configuration.changed(e, 'views', 'fileHistory', 'enabled')) { - setCommandContext(CommandContext.ViewsFileHistoryEditorFollowing, true); + void setCommandContext(CommandContext.ViewsFileHistoryEditorFollowing, true); } if (configuration.changed(e, 'views', 'fileHistory', 'location')) { @@ -118,7 +118,7 @@ export class FileHistoryView extends ViewBase { } private setEditorFollowing(enabled: boolean) { - setCommandContext(CommandContext.ViewsFileHistoryEditorFollowing, enabled); + void setCommandContext(CommandContext.ViewsFileHistoryEditorFollowing, enabled); if (this._root !== undefined) { this._root.setEditorFollowing(enabled); } diff --git a/src/views/lineHistoryView.ts b/src/views/lineHistoryView.ts index e127c6b..ddc466c 100644 --- a/src/views/lineHistoryView.ts +++ b/src/views/lineHistoryView.ts @@ -75,7 +75,7 @@ export class LineHistoryView extends ViewBase { } if (configuration.changed(e, 'views', 'lineHistory', 'enabled')) { - setCommandContext(CommandContext.ViewsLineHistoryEditorFollowing, true); + void setCommandContext(CommandContext.ViewsLineHistoryEditorFollowing, true); } if (configuration.changed(e, 'views', 'lineHistory', 'location')) { @@ -98,7 +98,7 @@ export class LineHistoryView extends ViewBase { } private setEditorFollowing(enabled: boolean) { - setCommandContext(CommandContext.ViewsLineHistoryEditorFollowing, enabled); + void setCommandContext(CommandContext.ViewsLineHistoryEditorFollowing, enabled); if (this._root !== undefined) { this._root.setEditorFollowing(enabled); } diff --git a/src/views/nodes/branchNode.ts b/src/views/nodes/branchNode.ts index f7e4ec2..5effe1c 100644 --- a/src/views/nodes/branchNode.ts +++ b/src/views/nodes/branchNode.ts @@ -257,6 +257,6 @@ export class BranchNode extends ViewRefNode implements Pageabl this._log = log; this.limit = log?.count; - this.triggerChange(false); + void this.triggerChange(false); } } diff --git a/src/views/nodes/branchOrTagFolderNode.ts b/src/views/nodes/branchOrTagFolderNode.ts index 6b44ee7..2519a78 100644 --- a/src/views/nodes/branchOrTagFolderNode.ts +++ b/src/views/nodes/branchOrTagFolderNode.ts @@ -45,9 +45,7 @@ export class BranchOrTagFolderNode extends ViewNode { for (const folder of this.root.children.values()) { if (folder.value === undefined) { // If the folder contains the current branch, expand it by default - const expanded = - folder.descendants !== undefined && - folder.descendants.some(n => n instanceof BranchNode && n.current); + const expanded = folder.descendants?.some(n => n instanceof BranchNode && n.current); children.push( new BranchOrTagFolderNode( this.view, diff --git a/src/views/nodes/branchTrackingStatusNode.ts b/src/views/nodes/branchTrackingStatusNode.ts index 08fff71..2a2fd7d 100644 --- a/src/views/nodes/branchTrackingStatusNode.ts +++ b/src/views/nodes/branchTrackingStatusNode.ts @@ -155,6 +155,6 @@ export class BranchTrackingStatusNode extends ViewNode implements this._log = log; this.limit = log?.count; - this.triggerChange(false); + void this.triggerChange(false); } } diff --git a/src/views/nodes/commitFileNode.ts b/src/views/nodes/commitFileNode.ts index 2525d98..7dd8975 100644 --- a/src/views/nodes/commitFileNode.ts +++ b/src/views/nodes/commitFileNode.ts @@ -50,7 +50,7 @@ export class CommitFileNode extends ViewRefFileNode { ref: this.commit.sha, }); if (log !== undefined) { - this.commit = log.commits.get(this.commit.sha) || this.commit; + this.commit = log.commits.get(this.commit.sha) ?? this.commit; } } else { this.commit = commit; diff --git a/src/views/nodes/commitNode.ts b/src/views/nodes/commitNode.ts index 0643abf..03a6848 100644 --- a/src/views/nodes/commitNode.ts +++ b/src/views/nodes/commitNode.ts @@ -68,7 +68,7 @@ export class CommitNode extends ViewRefNode { this._options.expand ? TreeItemCollapsibleState.Expanded : TreeItemCollapsibleState.Collapsed, ); item.contextValue = ResourceType.Commit; - if (this.branch !== undefined && this.branch.current) { + if (this.branch?.current) { item.contextValue += '+current'; } item.description = CommitFormatter.fromTemplate(this.view.config.commitDescriptionFormat, this.commit, { diff --git a/src/views/nodes/compareBranchNode.ts b/src/views/nodes/compareBranchNode.ts index 8ba9fa2..755fb8b 100644 --- a/src/views/nodes/compareBranchNode.ts +++ b/src/views/nodes/compareBranchNode.ts @@ -31,6 +31,7 @@ export class CompareBranchNode extends ViewNode { this._compareWith = { ref: compareWith, notation: Container.config.advanced.useSymmetricDifferenceNotation ? '...' : '..', + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions type: this.view.config.showBranchComparison || ViewShowBranchComparison.Working, }; } else { @@ -48,7 +49,7 @@ export class CompareBranchNode extends ViewNode { if (this._children === undefined) { let ref1 = this._compareWith.ref || 'HEAD'; if (this.comparisonNotation === '..') { - ref1 = (await Container.git.getMergeBase(this.branch.repoPath, ref1, this.branch.ref)) || ref1; + ref1 = (await Container.git.getMergeBase(this.branch.repoPath, ref1, this.branch.ref)) ?? ref1; } this._children = [ @@ -158,6 +159,7 @@ export class CompareBranchNode extends ViewNode { } private get comparisonType() { + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions return this._compareWith?.type ?? (this.view.config.showBranchComparison || ViewShowBranchComparison.Working); } @@ -174,7 +176,7 @@ export class CompareBranchNode extends ViewNode { ); if (pick === undefined || pick instanceof CommandQuickPickItem) return; - this.updateCompareWith({ + await this.updateCompareWith({ ref: pick.ref, notation: this.comparisonNotation, type: this.comparisonType, @@ -188,7 +190,7 @@ export class CompareBranchNode extends ViewNode { const log = await Container.git.getLog(this.uri.repoPath!, { limit: limit, ref: GitRevision.createRange( - this._compareWith?.ref || 'HEAD', + this._compareWith?.ref ?? 'HEAD', this.compareWithWorkingTree ? '' : this.branch.ref, this.comparisonNotation, ), @@ -229,7 +231,7 @@ export class CompareBranchNode extends ViewNode { const diff = await Container.git.getDiffStatus( this.uri.repoPath!, GitRevision.createRange( - this._compareWith?.ref || 'HEAD', + this._compareWith?.ref ?? 'HEAD', this.compareWithWorkingTree ? '' : this.branch.ref, this.diffComparisonNotation, ), @@ -246,13 +248,13 @@ export class CompareBranchNode extends ViewNode { let comparisons = Container.context.workspaceState.get(WorkspaceState.BranchComparisons); if (comparisons === undefined) { - comparisons = Object.create(null); + comparisons = Object.create(null) as BranchComparisons; } if (compareWith) { - comparisons![this.branch.id] = { ...compareWith }; + comparisons[this.branch.id] = { ...compareWith }; } else { - const { [this.branch.id]: _, ...rest } = comparisons!; + const { [this.branch.id]: _, ...rest } = comparisons; comparisons = rest; } await Container.context.workspaceState.update(WorkspaceState.BranchComparisons, comparisons); diff --git a/src/views/nodes/compareNode.ts b/src/views/nodes/compareNode.ts index e52edc6..7dc596a 100644 --- a/src/views/nodes/compareNode.ts +++ b/src/views/nodes/compareNode.ts @@ -88,7 +88,7 @@ export class CompareNode extends ViewNode { @log() clear() { this._selectedRef = undefined; - setCommandContext(CommandContext.ViewsCanCompare, false); + void setCommandContext(CommandContext.ViewsCanCompare, false); this._children.length = 0; this.view.triggerNodeChange(); @@ -99,7 +99,7 @@ export class CompareNode extends ViewNode { }) dismiss(node: ViewNode) { this._selectedRef = undefined; - setCommandContext(CommandContext.ViewsCanCompare, false); + void setCommandContext(CommandContext.ViewsCanCompare, false); if (this._children.length !== 0) { const index = this._children.indexOf(node); @@ -165,7 +165,7 @@ export class CompareNode extends ViewNode { const ref1 = this._selectedRef; this._selectedRef = undefined; - setCommandContext(CommandContext.ViewsCanCompare, false); + void setCommandContext(CommandContext.ViewsCanCompare, false); void (await this.view.compare(repoPath, ref1.ref, ref)); } @@ -204,7 +204,7 @@ export class CompareNode extends ViewNode { } this._selectedRef = { label: this.getRefName(ref), repoPath: repoPath, ref: ref }; - setCommandContext(CommandContext.ViewsCanCompare, true); + void setCommandContext(CommandContext.ViewsCanCompare, true); void (await this.triggerChange()); await this.view.reveal(this._comparePickerNode!, { focus: true, select: true }); @@ -215,6 +215,6 @@ export class CompareNode extends ViewNode { } private getRefName(ref: string | NamedRef) { - return typeof ref === 'string' ? GitRevision.shorten(ref)! : ref.label || GitRevision.shorten(ref.ref)!; + return typeof ref === 'string' ? GitRevision.shorten(ref)! : ref.label ?? GitRevision.shorten(ref.ref)!; } } diff --git a/src/views/nodes/comparePickerNode.ts b/src/views/nodes/comparePickerNode.ts index d3adf64..f27a6e8 100644 --- a/src/views/nodes/comparePickerNode.ts +++ b/src/views/nodes/comparePickerNode.ts @@ -23,7 +23,7 @@ export class ComparePickerNode extends ViewNode { if (repoPath !== undefined) { if ((await Container.git.getRepositoryCount()) > 1) { const repo = await Container.git.getRepository(repoPath); - description = (repo && repo.formattedName) || repoPath; + description = repo?.formattedName ?? repoPath; } } diff --git a/src/views/nodes/compareResultsNode.ts b/src/views/nodes/compareResultsNode.ts index 91bfdbe..a505055 100644 --- a/src/views/nodes/compareResultsNode.ts +++ b/src/views/nodes/compareResultsNode.ts @@ -68,17 +68,17 @@ export class CompareResultsNode extends SubscribeableViewNode { let description; if ((await Container.git.getRepositoryCount()) > 1) { const repo = await Container.git.getRepository(this.uri.repoPath!); - description = (repo && repo.formattedName) || this.uri.repoPath; + description = repo?.formattedName ?? this.uri.repoPath; } const item = new TreeItem( `Comparing ${ - this._ref.label || GitRevision.shorten(this._ref.ref, { strings: { working: 'Working Tree' } }) + this._ref.label ?? GitRevision.shorten(this._ref.ref, { strings: { working: 'Working Tree' } }) } to ${ - this._compareWith.label || + this._compareWith.label ?? GitRevision.shorten(this._compareWith.ref, { strings: { working: 'Working Tree' } }) }`, - this._state || TreeItemCollapsibleState.Collapsed, + this._state ?? TreeItemCollapsibleState.Collapsed, ); item.contextValue = `${ResourceType.CompareResults}+${ this.comparisonNotation === '..' ? 'twodot' : 'threedot' @@ -107,7 +107,7 @@ export class CompareResultsNode extends SubscribeableViewNode { async getDiffRefs(): Promise<[string, string]> { if (this.comparisonNotation === '..') { return [ - (await Container.git.getMergeBase(this.repoPath, this._compareWith.ref, this._ref.ref)) || + (await Container.git.getMergeBase(this.repoPath, this._compareWith.ref, this._ref.ref)) ?? this._compareWith.ref, this._ref.ref, ]; @@ -195,7 +195,7 @@ export class CompareResultsNode extends SubscribeableViewNode { } private get comparisonNotation() { - return this._comparisonNotation || (Container.config.advanced.useSymmetricDifferenceNotation ? '...' : '..'); + return this._comparisonNotation ?? (Container.config.advanced.useSymmetricDifferenceNotation ? '...' : '..'); } private get diffComparisonNotation() { diff --git a/src/views/nodes/contributorNode.ts b/src/views/nodes/contributorNode.ts index e55b89f..c6a69ee 100644 --- a/src/views/nodes/contributorNode.ts +++ b/src/views/nodes/contributorNode.ts @@ -117,6 +117,6 @@ export class ContributorNode extends ViewNode implements Pagea this._log = log; this.limit = log?.count; - this.triggerChange(false); + void this.triggerChange(false); } } diff --git a/src/views/nodes/contributorsNode.ts b/src/views/nodes/contributorsNode.ts index 88bc30f..a7af5a0 100644 --- a/src/views/nodes/contributorsNode.ts +++ b/src/views/nodes/contributorsNode.ts @@ -29,7 +29,7 @@ export class ContributorsNode extends ViewNode { if (contributors.length === 0) return [new MessageNode(this.view, this, 'No contributors could be found.')]; GitContributor.sort(contributors); - const presenceMap = await this.maybeGetPresenceMap(contributors).catch(reason => undefined); + const presenceMap = await this.maybeGetPresenceMap(contributors).catch(() => undefined); const children = contributors.map(c => new ContributorNode(this.uri, this.view, this, c, presenceMap)); return children; diff --git a/src/views/nodes/fileHistoryNode.ts b/src/views/nodes/fileHistoryNode.ts index 0b1bb79..167a312 100644 --- a/src/views/nodes/fileHistoryNode.ts +++ b/src/views/nodes/fileHistoryNode.ts @@ -60,7 +60,7 @@ export class FileHistoryNode extends SubscribeableViewNode implements PageableVi status.status, status.originalFileName, GitRevision.uncommittedStaged, - status.originalFileName || status.fileName, + status.originalFileName ?? status.fileName, ); children.push( @@ -84,7 +84,7 @@ export class FileHistoryNode extends SubscribeableViewNode implements PageableVi status.status, status.originalFileName, 'HEAD', - status.originalFileName || status.fileName, + status.originalFileName ?? status.fileName, ); children.push( @@ -110,7 +110,7 @@ export class FileHistoryNode extends SubscribeableViewNode implements PageableVi status.status, status.originalFileName, 'HEAD', - status.originalFileName || status.fileName, + status.originalFileName ?? status.fileName, ); children.push( new CommitFileNode(this.view, this, status, commit, { @@ -236,6 +236,6 @@ export class FileHistoryNode extends SubscribeableViewNode implements PageableVi this._log = log; this.limit = log?.count; - this.triggerChange(false); + void this.triggerChange(false); } } diff --git a/src/views/nodes/fileHistoryTrackerNode.ts b/src/views/nodes/fileHistoryTrackerNode.ts index e55dc2e..870d908 100644 --- a/src/views/nodes/fileHistoryTrackerNode.ts +++ b/src/views/nodes/fileHistoryTrackerNode.ts @@ -47,8 +47,8 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode e.document && e.document.uri.path === this.uri.path)) + window.visibleTextEditors.some(e => e.document?.uri.path === this.uri.path)) ) { return true; } @@ -141,7 +141,7 @@ export class FileHistoryTrackerNode extends SubscribeableViewNode e.document && e.document.uri.path === this.uri.path)) + window.visibleTextEditors.some(e => e.document?.uri.path === this.uri.path)) ) { return true; } @@ -194,7 +194,7 @@ export class LineHistoryTrackerNode extends SubscribeableViewNode implements PageableVi this._reflog = reflog; this.limit = reflog?.count; - this.triggerChange(false); + void this.triggerChange(false); } } diff --git a/src/views/nodes/reflogRecordNode.ts b/src/views/nodes/reflogRecordNode.ts index e66bb4a..9c0face 100644 --- a/src/views/nodes/reflogRecordNode.ts +++ b/src/views/nodes/reflogRecordNode.ts @@ -22,7 +22,7 @@ export class ReflogRecordNode extends ViewNode implements Pageabl date: Date, ): string { return `${RepositoryNode.getId(repoPath)}${this.key}(${sha}|${selector}|${command}|${ - commandArgs || '' + commandArgs ?? '' }|${date.getTime()})`; } @@ -113,6 +113,6 @@ export class ReflogRecordNode extends ViewNode implements Pageabl this._log = log; this.limit = log?.count; - this.triggerChange(false); + void this.triggerChange(false); } } diff --git a/src/views/nodes/repositoryNode.ts b/src/views/nodes/repositoryNode.ts index 27d14b5..40952c4 100644 --- a/src/views/nodes/repositoryNode.ts +++ b/src/views/nodes/repositoryNode.ts @@ -113,13 +113,13 @@ export class RepositoryNode extends SubscribeableViewNode { } async getTreeItem(): Promise { - const label = this.repo.formattedName || this.uri.repoPath || ''; + const label = this.repo.formattedName ?? this.uri.repoPath ?? ''; this._lastFetched = await this.repo.getLastFetched(); const lastFetchedTooltip = this.formatLastFetched({ prefix: `${Strings.pad(GlyphChars.Dash, 2, 2)}Last fetched on `, - format: Container.config.defaultDateFormat || 'dddd MMMM Do, YYYY', + format: Container.config.defaultDateFormat ?? 'dddd MMMM Do, YYYY', includeTime: true, }); @@ -187,7 +187,7 @@ export class RepositoryNode extends SubscribeableViewNode { const item = new TreeItem(label, TreeItemCollapsibleState.Expanded); item.contextValue = contextValue; - item.description = `${description || ''}${this.formatLastFetched({ + item.description = `${description ?? ''}${this.formatLastFetched({ prefix: `${Strings.pad(GlyphChars.Dot, 2, 2)}Last fetched `, })}`; item.iconPath = { @@ -273,7 +273,7 @@ export class RepositoryNode extends SubscribeableViewNode { .join(', ')}${e.uris.length > 1 ? ', ...' : ''}] }`, }, }) - private async onFileSystemChanged(e: RepositoryFileSystemChangeEvent) { + private async onFileSystemChanged(_e: RepositoryFileSystemChangeEvent) { this._status = this.repo.getStatus(); if (this._children !== undefined) { @@ -356,7 +356,7 @@ export class RepositoryNode extends SubscribeableViewNode { // } // } - let format = options.format || Container.config.defaultDateShortFormat || 'MMM D, YYYY'; + let format = options.format ?? Container.config.defaultDateShortFormat ?? 'MMM D, YYYY'; if ( (options.includeTime || // If less than a day has passed show the time too @@ -367,7 +367,7 @@ export class RepositoryNode extends SubscribeableViewNode { format = `h:mma, ${format}`; } - return `${options.prefix || ''}${Dates.getFormatter(new Date(this._lastFetched)).format(format)}`; + return `${options.prefix ?? ''}${Dates.getFormatter(new Date(this._lastFetched)).format(format)}`; } // @debug() diff --git a/src/views/nodes/resultsCommitsNode.ts b/src/views/nodes/resultsCommitsNode.ts index d0e768c..a24be7e 100644 --- a/src/views/nodes/resultsCommitsNode.ts +++ b/src/views/nodes/resultsCommitsNode.ts @@ -91,10 +91,10 @@ export class ResultsCommitsNode extends ViewNode implements Pagea let description; if (this._options.includeDescription && (await Container.git.getRepositoryCount()) > 1) { const repo = await Container.git.getRepository(this.repoPath); - description = (repo && repo.formattedName) || this.repoPath; + description = repo?.formattedName ?? this.repoPath; } - const item = new TreeItem(label || this._label, state); + const item = new TreeItem(label ?? this._label, state); item.contextValue = this.type; item.description = description; item.id = this.id; @@ -135,6 +135,6 @@ export class ResultsCommitsNode extends ViewNode implements Pagea await results.more?.(limit ?? this.view.config.pageItemLimit); this.limit = results.log?.count; - this.triggerChange(false); + void this.triggerChange(false); } } diff --git a/src/views/nodes/resultsFilesNode.ts b/src/views/nodes/resultsFilesNode.ts index 11d005c..66ed8a8 100644 --- a/src/views/nodes/resultsFilesNode.ts +++ b/src/views/nodes/resultsFilesNode.ts @@ -79,7 +79,7 @@ export class ResultsFilesNode extends ViewNode { state = TreeItemCollapsibleState.Collapsed; } - const item = new TreeItem(label || 'files changed', state); + const item = new TreeItem(label ?? 'files changed', state); item.contextValue = ResourceType.ResultsFiles; item.id = this.id; diff --git a/src/views/nodes/statusFilesNode.ts b/src/views/nodes/statusFilesNode.ts index 5047716..2fb17dc 100644 --- a/src/views/nodes/statusFilesNode.ts +++ b/src/views/nodes/statusFilesNode.ts @@ -180,8 +180,8 @@ export class StatusFilesNode extends ViewNode { ref, 'You', undefined, - date || new Date(), - date || new Date(), + date ?? new Date(), + date ?? new Date(), '', file.fileName, [file], diff --git a/src/views/nodes/tagNode.ts b/src/views/nodes/tagNode.ts index dab435b..6e54fde 100644 --- a/src/views/nodes/tagNode.ts +++ b/src/views/nodes/tagNode.ts @@ -117,6 +117,6 @@ export class TagNode extends ViewRefNode implements PageableVi this._log = log; this.limit = log?.count; - this.triggerChange(false); + void this.triggerChange(false); } } diff --git a/src/views/repositoriesView.ts b/src/views/repositoriesView.ts index 40e2068..a6df5bd 100644 --- a/src/views/repositoriesView.ts +++ b/src/views/repositoriesView.ts @@ -595,7 +595,7 @@ export class RepositoriesView extends ViewBase { } } - setCommandContext(CommandContext.ViewsRepositoriesAutoRefresh, enabled && workspaceEnabled); + void setCommandContext(CommandContext.ViewsRepositoriesAutoRefresh, enabled && workspaceEnabled); this._onDidChangeAutoRefresh.fire(); } diff --git a/src/views/searchView.ts b/src/views/searchView.ts index d81c190..f2a3241 100644 --- a/src/views/searchView.ts +++ b/src/views/searchView.ts @@ -19,7 +19,7 @@ export class SearchView extends ViewBase { constructor() { super('gitlens.views.search', 'Search Commits'); - setCommandContext(CommandContext.ViewsSearchKeepResults, this.keepResults); + void setCommandContext(CommandContext.ViewsSearchKeepResults, this.keepResults); } getRoot() { @@ -143,7 +143,7 @@ export class SearchView extends ViewBase { } const searchQueryFn = this.getSearchQueryFn( - results || Container.git.getLogForSearch(repoPath, search, options), + results ?? Container.git.getLogForSearch(repoPath, search, options), { label: label }, ); @@ -291,8 +291,8 @@ export class SearchView extends ViewBase { } private setKeepResults(enabled: boolean) { - Container.context.workspaceState.update(WorkspaceState.ViewsSearchKeepResults, enabled); - setCommandContext(CommandContext.ViewsSearchKeepResults, enabled); + void Container.context.workspaceState.update(WorkspaceState.ViewsSearchKeepResults, enabled); + void setCommandContext(CommandContext.ViewsSearchKeepResults, enabled); } private setShowAvatars(enabled: boolean) { diff --git a/src/views/viewBase.ts b/src/views/viewBase.ts index 08df036..436e79e 100644 --- a/src/views/viewBase.ts +++ b/src/views/viewBase.ts @@ -64,10 +64,10 @@ export abstract class ViewBase> implements TreeData const parent = node.getParent(); if (parent !== undefined) { item.tooltip = `${ - item.tooltip || item.label + item.tooltip ?? item.label }\n\nDBG:\nnode: ${node.toString()}\nparent: ${parent.toString()}\ncontext: ${item.contextValue}`; } else { - item.tooltip = `${item.tooltip || item.label}\n\nDBG:\nnode: ${node.toString()}\ncontext: ${ + item.tooltip = `${item.tooltip ?? item.label}\n\nDBG:\nnode: ${node.toString()}\ncontext: ${ item.contextValue }`; } @@ -243,7 +243,7 @@ export abstract class ViewBase> implements TreeData let children: ViewNode[]; let pagedChildren: ViewNode[]; while (queue.length > 1) { - if (token !== undefined && token.isCancellationRequested) return undefined; + if (token?.isCancellationRequested) return undefined; node = queue.shift(); if (node === undefined) { @@ -274,13 +274,13 @@ export abstract class ViewBase> implements TreeData if (allowPaging && node.hasMore) { while (true) { - if (token !== undefined && token.isCancellationRequested) return undefined; + if (token?.isCancellationRequested) return undefined; await this.showMoreNodeChildren(node, defaultPageSize); pagedChildren = await Promises.cancellable( Promise.resolve(node.getChildren()), - token || 60000, + token ?? 60000, { onDidCancel: resolve => resolve([]), }, @@ -305,7 +305,7 @@ export abstract class ViewBase> implements TreeData @debug() async refresh(reset: boolean = false) { - if (this._root !== undefined && this._root.refresh !== undefined) { + if (this._root?.refresh != null) { await this._root.refresh(reset); } @@ -354,6 +354,7 @@ export abstract class ViewBase> implements TreeData Logger.error(ex); const section = Strings.splitSingle(this.id, '.')[1]; + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions if (!configuration.get(section as any, 'enabled')) { const actions: MessageItem[] = [{ title: 'Enable' }, { title: 'Cancel', isCloseAffordance: true }]; diff --git a/src/views/viewCommands.ts b/src/views/viewCommands.ts index 6f06dc0..178b57b 100644 --- a/src/views/viewCommands.ts +++ b/src/views/viewCommands.ts @@ -569,7 +569,7 @@ export class ViewCommands { const selected = this._selectedFile; this._selectedFile = undefined; - setCommandContext(CommandContext.ViewsCanCompareFile, false); + void setCommandContext(CommandContext.ViewsCanCompareFile, false); const diffArgs: DiffWithCommandArgs = { repoPath: selected.repoPath, @@ -596,7 +596,7 @@ export class ViewCommands { repoPath: node.repoPath, uri: node.uri, }; - setCommandContext(CommandContext.ViewsCanCompareFile, true); + void setCommandContext(CommandContext.ViewsCanCompareFile, true); } @debug() @@ -821,7 +821,7 @@ export class ViewCommands { } } - return findOrOpenEditor(uri, options.showOptions || { preserveFocus: true, preview: false }); + return findOrOpenEditor(uri, options.showOptions ?? { preserveFocus: true, preview: false }); } @debug() @@ -885,7 +885,7 @@ export class ViewCommands { async terminalPushCommit(node: CommitNode) { if (!(node instanceof CommitNode)) return; - const branch = node.branch || (await Container.git.getBranch(node.repoPath)); + const branch = node.branch ?? (await Container.git.getBranch(node.repoPath)); if (branch === undefined) return; runGitCommandInTerminal( diff --git a/src/vsls/guest.ts b/src/vsls/guest.ts index b086b71..1e7364a 100644 --- a/src/vsls/guest.ts +++ b/src/vsls/guest.ts @@ -76,7 +76,7 @@ export class VslsGuestService implements Disposable { private sendRequest( requestType: RequestType, request: TRequest, - cancellation?: CancellationToken, + _cancellation?: CancellationToken, ): Promise { return this._service.request(requestType.name, [request]); } diff --git a/src/vsls/host.ts b/src/vsls/host.ts index 66e36c5..5cdd32b 100644 --- a/src/vsls/host.ts +++ b/src/vsls/host.ts @@ -91,12 +91,12 @@ export class VslsHostService implements Disposable { } @log() - private onAvailabilityChanged(available: boolean) { + private onAvailabilityChanged(_available: boolean) { // TODO } @debug() - private onWorkspaceFoldersChanged(e?: WorkspaceFoldersChangeEvent) { + private onWorkspaceFoldersChanged(_e?: WorkspaceFoldersChangeEvent) { if (workspace.workspaceFolders === undefined || workspace.workspaceFolders.length === 0) return; const cc = Logger.getCorrelationContext(); @@ -127,7 +127,7 @@ export class VslsHostService implements Disposable { @log() private async onGitCommandRequest( request: GitCommandRequest, - cancellation: CancellationToken, + _cancellation: CancellationToken, ): Promise { const { options, args } = request; @@ -137,7 +137,7 @@ export class VslsHostService implements Disposable { let isRootWorkspace = false; if (options.cwd !== undefined && options.cwd.length > 0 && this._sharedToLocalPaths !== undefined) { // This is all so ugly, but basically we are converting shared paths to local paths - if (this._sharedPathsRegex !== undefined && this._sharedPathsRegex.test(options.cwd)) { + if (this._sharedPathsRegex?.test(options.cwd)) { options.cwd = Strings.normalizePath(options.cwd).replace(this._sharedPathsRegex, (match, shared) => { if (!isRootWorkspace) { isRootWorkspace = shared === '/~0'; @@ -172,7 +172,7 @@ export class VslsHostService implements Disposable { args.splice(i, 1, arg.substr(1)); } - if (this._sharedPathsRegex !== undefined && this._sharedPathsRegex.test(arg)) { + if (this._sharedPathsRegex?.test(arg)) { args.splice( i, 1, @@ -204,7 +204,7 @@ export class VslsHostService implements Disposable { @log() private async onRepositoriesInFolderRequest( request: RepositoriesInFolderRequest, - cancellation: CancellationToken, + _cancellation: CancellationToken, ): Promise { const uri = this.convertSharedUriToLocal(Uri.parse(request.folderUri)); const normalized = Strings.normalizePath(uri.fsPath, { stripTrailingSlash: true }).toLowerCase(); diff --git a/src/vsls/vsls.ts b/src/vsls/vsls.ts index 907ec3d..38560af 100644 --- a/src/vsls/vsls.ts +++ b/src/vsls/vsls.ts @@ -60,10 +60,7 @@ export class VslsController implements Disposable { private async initialize() { try { // If we have a vsls: workspace open, we might be a guest, so wait until live share transitions into a mode - if ( - workspace.workspaceFolders !== undefined && - workspace.workspaceFolders.some(f => f.uri.scheme === DocumentSchemes.Vsls) - ) { + if (workspace.workspaceFolders?.some(f => f.uri.scheme === DocumentSchemes.Vsls)) { this.setReadonly(true); this._waitForReady = new Promise(resolve => (this._onReady = resolve)); } @@ -71,7 +68,7 @@ export class VslsController implements Disposable { this._api = getApi(); const api = await this._api; if (api == null) { - setCommandContext(CommandContext.Vsls, false); + void setCommandContext(CommandContext.Vsls, false); // Tear it down if we can't talk to live share if (this._onReady !== undefined) { this._onReady(); @@ -81,7 +78,7 @@ export class VslsController implements Disposable { return; } - setCommandContext(CommandContext.Vsls, true); + void setCommandContext(CommandContext.Vsls, true); this._disposable = Disposable.from( api.onDidChangeSession(e => this.onLiveShareSessionChanged(api, e), this), @@ -101,7 +98,7 @@ export class VslsController implements Disposable { } private setReadonly(value: boolean) { this._readonly = value; - setCommandContext(CommandContext.Readonly, value ? true : undefined); + void setCommandContext(CommandContext.Readonly, value ? true : undefined); } @debug() @@ -197,20 +194,20 @@ export class VslsController implements Disposable { switch (e.session.role) { case Role.Host: this.setReadonly(false); - setCommandContext(CommandContext.Vsls, 'host'); + void setCommandContext(CommandContext.Vsls, 'host'); if (Container.config.liveshare.allowGuestAccess) { this._host = await VslsHostService.share(api); } break; case Role.Guest: this.setReadonly(true); - setCommandContext(CommandContext.Vsls, 'guest'); + void setCommandContext(CommandContext.Vsls, 'guest'); this._guest = await VslsGuestService.connect(api); break; default: this.setReadonly(false); - setCommandContext(CommandContext.Vsls, true); + void setCommandContext(CommandContext.Vsls, true); break; } diff --git a/src/webviews/apps/settings/index.ts b/src/webviews/apps/settings/index.ts index d73c619..3f62ad5 100644 --- a/src/webviews/apps/settings/index.ts +++ b/src/webviews/apps/settings/index.ts @@ -19,7 +19,7 @@ export class SettingsApp extends AppWithConfig { protected onInitialize() { // Add scopes if available const scopes = DOM.getElementById('scopes'); - if (scopes && this.state.scopes.length > 1) { + if (scopes != null && this.state.scopes.length > 1) { for (const [scope, text] of this.state.scopes) { const option = document.createElement('option'); option.value = scope; @@ -93,7 +93,7 @@ export class SettingsApp extends AppWithConfig { } } - private onObserver(entries: IntersectionObserverEntry[], observer: IntersectionObserver) { + private onObserver(entries: IntersectionObserverEntry[], _observer: IntersectionObserver) { for (const entry of entries) { this._sections.set(entry.target.parentElement!.id, entry.isIntersecting); } @@ -189,7 +189,7 @@ export class SettingsApp extends AppWithConfig { element.parentElement!.classList.toggle('collapsed'); } - private onSettingExpanderCicked(element: HTMLElement, e: MouseEvent) { + private onSettingExpanderCicked(element: HTMLElement, _e: MouseEvent) { element.parentElement!.parentElement!.classList.toggle('expanded'); } diff --git a/src/webviews/apps/shared/appBase.ts b/src/webviews/apps/shared/appBase.ts index 24cb43e..fc19cfc 100644 --- a/src/webviews/apps/shared/appBase.ts +++ b/src/webviews/apps/shared/appBase.ts @@ -4,9 +4,9 @@ import { IpcCommandParamsOf, IpcCommandType, IpcMessage, ReadyCommandType } from import { initializeAndWatchThemeColors } from './theme'; interface VsCodeApi { - postMessage(msg: {}): void; - setState(state: {}): void; - getState(): {}; + postMessage(msg: object): void; + setState(state: object): void; + getState(): object; } declare function acquireVsCodeApi(): VsCodeApi; diff --git a/src/webviews/apps/shared/appWithConfigBase.ts b/src/webviews/apps/shared/appWithConfigBase.ts index e70851e..2a91386 100644 --- a/src/webviews/apps/shared/appWithConfigBase.ts +++ b/src/webviews/apps/shared/appWithConfigBase.ts @@ -14,7 +14,7 @@ import { Dates } from '../../../system/date'; const dateFormatter = Dates.getFormatter(new Date('Wed Jul 25 2018 19:18:00 GMT-0400')); export abstract class AppWithConfig extends App { - private _changes: { [key: string]: any } = Object.create(null); + private _changes = Object.create(null) as Record; private _updating: boolean = false; constructor(appName: string, state: TState) { @@ -78,7 +78,7 @@ export abstract class AppWithConfig extends A scope: this.getSettingsScope(), }); - this._changes = Object.create(null); + this._changes = Object.create(null) as Record; } protected getSettingsScope(): 'user' | 'workspace' { @@ -126,7 +126,7 @@ export abstract class AppWithConfig extends A case 'object': { const props = element.name.split('.'); const settingName = props.splice(0, 1)[0]; - const setting = this.getSettingValue(settingName) || Object.create(null); + const setting = this.getSettingValue(settingName) ?? Object.create(null); if (element.checked) { set(setting, props.join('.'), fromCheckboxValue(element.value)); @@ -139,7 +139,7 @@ export abstract class AppWithConfig extends A break; } case 'array': { - const setting = this.getSettingValue(element.name) || []; + const setting = this.getSettingValue(element.name) ?? []; if (Array.isArray(setting)) { if (element.checked) { if (!setting.includes(element.value)) { @@ -203,7 +203,7 @@ export abstract class AppWithConfig extends A e.preventDefault(); const el = e.target as HTMLElement; - if (el && el.matches('[data-token]')) { + if (el?.matches('[data-token]')) { this.onTokenMouseDown(el, e); } } @@ -226,7 +226,7 @@ export abstract class AppWithConfig extends A e.preventDefault(); } - private evaluateStateExpression(expression: string, changes: { [key: string]: string | boolean }): boolean { + private evaluateStateExpression(expression: string, changes: Record): boolean { let state = false; for (const expr of expression.trim().split('&')) { const [lhs, op, rhs] = parseStateExpression(expr); @@ -236,7 +236,7 @@ export abstract class AppWithConfig extends A // Equals let value = changes[lhs]; if (value === undefined) { - value = this.getSettingValue(lhs) || false; + value = this.getSettingValue(lhs) ?? false; } state = rhs !== undefined ? rhs === String(value) : Boolean(value); break; @@ -245,8 +245,9 @@ export abstract class AppWithConfig extends A // Not equals let value = changes[lhs]; if (value === undefined) { - value = this.getSettingValue(lhs) || false; + value = this.getSettingValue(lhs) ?? false; } + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions state = rhs !== undefined ? rhs !== String(value) : !value; break; } @@ -275,19 +276,19 @@ export abstract class AppWithConfig extends A try { for (const el of document.querySelectorAll('input[type=checkbox][data-setting]')) { if (el.dataset.settingType === 'array') { - el.checked = (this.getSettingValue(el.name) || []).includes(el.value); + el.checked = (this.getSettingValue(el.name) ?? []).includes(el.value); } else if (el.dataset.valueOff != null) { const value = this.getSettingValue(el.name); el.checked = el.dataset.valueOff !== value; } else { - el.checked = this.getSettingValue(el.name) || false; + el.checked = this.getSettingValue(el.name) ?? false; } } for (const el of document.querySelectorAll( 'input[type=text][data-setting], input:not([type])[data-setting]', )) { - el.value = this.getSettingValue(el.name) || ''; + el.value = this.getSettingValue(el.name) ?? ''; } for (const el of document.querySelectorAll('select[data-setting]')) { @@ -319,7 +320,7 @@ export abstract class AppWithConfig extends A } } - private setEnablement(state: { [key: string]: string | boolean }) { + private setEnablement(state: Record) { for (const el of document.querySelectorAll('[data-enablement]')) { const disabled = !this.evaluateStateExpression(el.dataset.enablement!, state); if (disabled) { @@ -339,7 +340,7 @@ export abstract class AppWithConfig extends A } } - private setVisibility(state: { [key: string]: string | boolean }) { + private setVisibility(state: Record) { for (const el of document.querySelectorAll('[data-visibility]')) { el.classList.toggle('hidden', !this.evaluateStateExpression(el.dataset.visibility!, state)); } @@ -371,11 +372,11 @@ function ensureIfBoolean(value: string | boolean): string | boolean { return value; } -function get(o: { [key: string]: any }, path: string): T | undefined { +function get(o: Record, path: string): T | undefined { return path.split('.').reduce((o = {}, key) => (o == null ? undefined : o[key]), o) as T; } -function set(o: { [key: string]: any }, path: string, value: any): { [key: string]: any } { +function set(o: Record, path: string, value: any): Record { const props = path.split('.'); const length = props.length; const lastIndex = length - 1; @@ -412,8 +413,8 @@ function parseStateExpression(expression: string): [string, string, string | boo return [lhs.trim(), op !== undefined ? op.trim() : '=', rhs !== undefined ? rhs.trim() : rhs]; } -function flatten(o: { [key: string]: any }, path?: string): { [key: string]: any } { - const results: { [key: string]: any } = {}; +function flatten(o: Record, path?: string): Record { + const results: Record = {}; for (const key in o) { const value = o[key]; diff --git a/src/webviews/apps/shared/events.ts b/src/webviews/apps/shared/events.ts index 04ae193..8f724f7 100644 --- a/src/webviews/apps/shared/events.ts +++ b/src/webviews/apps/shared/events.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/ban-types */ 'use strict'; // Taken from github.com/microsoft/vscode/src/vs/base/common/event.ts @@ -51,7 +52,7 @@ export class Emitter { this._options.onFirstListenerAdd(this); } - const remove = this._listeners.push(!thisArgs ? listener : [listener, thisArgs]); + const remove = this._listeners.push(thisArgs != null ? listener : [listener, thisArgs]); if (firstListener && this._options && this._options.onFirstListenerDidAdd) { this._options.onFirstListenerDidAdd(this); @@ -269,7 +270,7 @@ class LinkedList { return FIN; } - if (!element) { + if (element == null) { element = { done: false, value: node.element }; } else { element.value = node.element; diff --git a/src/webviews/protocol.ts b/src/webviews/protocol.ts index 904b56f..d6174bf 100644 --- a/src/webviews/protocol.ts +++ b/src/webviews/protocol.ts @@ -40,7 +40,7 @@ export const DidChangeConfigurationNotificationType = new IpcNotificationType('webview/ready'); +export const ReadyCommandType = new IpcCommandType('webview/ready'); export interface UpdateConfigurationCommandParams { changes: { @@ -70,4 +70,4 @@ export interface SettingsState extends AppStateWithConfig { scopes: ['user' | 'workspace', string][]; } -export interface WelcomeState extends AppStateWithConfig {} +export type WelcomeState = AppStateWithConfig; diff --git a/src/webviews/settingsWebview.ts b/src/webviews/settingsWebview.ts index ae94fc2..538f2f0 100644 --- a/src/webviews/settingsWebview.ts +++ b/src/webviews/settingsWebview.ts @@ -19,8 +19,8 @@ export class SettingsWebview extends WebviewBase { constructor() { super(Commands.ShowSettingsPage); - this._disposable = Disposable.from( - this._disposable, + this.disposable = Disposable.from( + this.disposable, ...[ Commands.ShowSettingsPageAndJumpToCompareView, Commands.ShowSettingsPageAndJumpToFileHistoryView, @@ -50,9 +50,11 @@ export class SettingsWebview extends WebviewBase { protected onMessageReceived(e: IpcMessage) { switch (e.method) { case ReadyCommandType.method: - onIpcCommand(ReadyCommandType, e, params => { + onIpcCommand(ReadyCommandType, e, _params => { if (this._pendingJumpToAnchor !== undefined) { - this.notify(SettingsDidRequestJumpToNotificationType, { anchor: this._pendingJumpToAnchor }); + void this.notify(SettingsDidRequestJumpToNotificationType, { + anchor: this._pendingJumpToAnchor, + }); this._pendingJumpToAnchor = undefined; } }); @@ -80,7 +82,7 @@ export class SettingsWebview extends WebviewBase { renderEndOfBody() { const scopes: ['user' | 'workspace', string][] = [['user', 'User']]; - if (workspace.workspaceFolders !== undefined && workspace.workspaceFolders.length) { + if (workspace.workspaceFolders?.length) { scopes.push(['workspace', 'Workspace']); } diff --git a/src/webviews/webviewBase.ts b/src/webviews/webviewBase.ts index 6c4ae6b..16ee9d1 100644 --- a/src/webviews/webviewBase.ts +++ b/src/webviews/webviewBase.ts @@ -37,12 +37,12 @@ const emptyCommands: Disposable[] = [ ]; export abstract class WebviewBase implements Disposable { - protected _disposable: Disposable; + protected disposable: Disposable; private _disposablePanel: Disposable | undefined; private _panel: WebviewPanel | undefined; constructor(showCommand: Commands, private readonly _column?: ViewColumn) { - this._disposable = Disposable.from( + this.disposable = Disposable.from( configuration.onDidChange(this.onConfigurationChanged, this), commands.registerCommand(showCommand, this.onShowCommand, this), ); @@ -61,16 +61,16 @@ export abstract class WebviewBase implements Disposable { renderEndOfBody?(): string | Promise; dispose() { - this._disposable && this._disposable.dispose(); + this.disposable.dispose(); this._disposablePanel && this._disposablePanel.dispose(); } protected onShowCommand() { - this.show(this._column); + void this.show(this._column); } - private onConfigurationChanged(e: ConfigurationChangeEvent) { - this.notifyDidChangeConfiguration(); + private onConfigurationChanged(_e: ConfigurationChangeEvent) { + void this.notifyDidChangeConfiguration(); } private onPanelDisposed() { @@ -86,7 +86,7 @@ export abstract class WebviewBase implements Disposable { // Anytime the webview becomes active, make sure it has the most up-to-date config if (e.webviewPanel.active) { - this.notifyDidChangeConfiguration(); + void this.notifyDidChangeConfiguration(); } } @@ -181,7 +181,7 @@ export abstract class WebviewBase implements Disposable { // Reset the html to get the webview to reload this._panel.webview.html = ''; this._panel.webview.html = html; - this._panel.reveal(this._panel.viewColumn || ViewColumn.Active, false); + this._panel.reveal(this._panel.viewColumn ?? ViewColumn.Active, false); } }