浏览代码

Fixes lint issues

main
Eric Amodio 4 年前
父节点
当前提交
7f7c2e2535
共有 167 个文件被更改,包括 735 次插入735 次删除
  1. +39
    -3
      .eslintrc.json
  2. +3
    -3
      generateEmojiShortcodeMap.js
  3. +5
    -6
      src/annotations/annotationProvider.ts
  4. +1
    -3
      src/annotations/autolinks.ts
  5. +5
    -5
      src/annotations/blameAnnotationProvider.ts
  6. +6
    -6
      src/annotations/fileAnnotationController.ts
  7. +6
    -6
      src/annotations/gutterBlameAnnotationProvider.ts
  8. +2
    -2
      src/annotations/heatmapBlameAnnotationProvider.ts
  9. +4
    -4
      src/annotations/lineAnnotationController.ts
  10. +1
    -1
      src/annotations/recentChangesAnnotationProvider.ts
  11. +1
    -1
      src/avatars.ts
  12. +1
    -1
      src/codelens/codeLensController.ts
  13. +10
    -10
      src/codelens/codeLensProvider.ts
  14. +1
    -1
      src/commands/browseRepoAtRevision.ts
  15. +6
    -9
      src/commands/closeUnchangedFiles.ts
  16. +6
    -6
      src/commands/common.ts
  17. +5
    -4
      src/commands/copyMessageToClipboard.ts
  18. +5
    -4
      src/commands/copyShaToClipboard.ts
  19. +1
    -1
      src/commands/diffBranchWith.ts
  20. +4
    -4
      src/commands/diffLineWithPrevious.ts
  21. +3
    -3
      src/commands/diffLineWithWorking.ts
  22. +2
    -2
      src/commands/diffWith.ts
  23. +3
    -3
      src/commands/diffWithNext.ts
  24. +5
    -5
      src/commands/diffWithPrevious.ts
  25. +1
    -1
      src/commands/diffWithRevision.ts
  26. +2
    -2
      src/commands/diffWithRevisionFrom.ts
  27. +4
    -4
      src/commands/diffWithWorking.ts
  28. +2
    -2
      src/commands/externalDiff.ts
  29. +2
    -5
      src/commands/git/branch.ts
  30. +1
    -1
      src/commands/git/cherry-pick.ts
  31. +1
    -1
      src/commands/git/coauthors.ts
  32. +1
    -1
      src/commands/git/fetch.ts
  33. +1
    -1
      src/commands/git/log.ts
  34. +2
    -2
      src/commands/git/merge.ts
  35. +1
    -1
      src/commands/git/pull.ts
  36. +1
    -1
      src/commands/git/push.ts
  37. +2
    -2
      src/commands/git/rebase.ts
  38. +1
    -1
      src/commands/git/reset.ts
  39. +1
    -1
      src/commands/git/revert.ts
  40. +5
    -5
      src/commands/git/show.ts
  41. +13
    -12
      src/commands/git/stash.ts
  42. +1
    -1
      src/commands/git/status.ts
  43. +1
    -1
      src/commands/git/switch.ts
  44. +2
    -5
      src/commands/git/tag.ts
  45. +4
    -4
      src/commands/gitCommands.actions.ts
  46. +8
    -8
      src/commands/gitCommands.ts
  47. +1
    -1
      src/commands/inviteToLiveShare.ts
  48. +3
    -1
      src/commands/openBranchOnRemote.ts
  49. +3
    -1
      src/commands/openBranchesOnRemote.ts
  50. +2
    -2
      src/commands/openChangedFiles.ts
  51. +6
    -2
      src/commands/openCommitOnRemote.ts
  52. +2
    -2
      src/commands/openDirectoryCompare.ts
  53. +1
    -1
      src/commands/openFileAtRevision.ts
  54. +1
    -1
      src/commands/openFileAtRevisionFrom.ts
  55. +2
    -2
      src/commands/openFileOnRemote.ts
  56. +1
    -1
      src/commands/openOnRemote.ts
  57. +1
    -1
      src/commands/openRepoOnRemote.ts
  58. +1
    -1
      src/commands/openRevisionFile.ts
  59. +2
    -2
      src/commands/openWorkingFile.ts
  60. +8
    -8
      src/commands/quickCommand.steps.ts
  61. +9
    -8
      src/commands/quickCommand.ts
  62. +6
    -6
      src/commands/showQuickCommit.ts
  63. +6
    -6
      src/commands/showQuickCommitFile.ts
  64. +0
    -29
      src/commands/showQuickRepoStatus.ts
  65. +1
    -1
      src/commands/stashSave.ts
  66. +1
    -1
      src/commands/switchMode.ts
  67. +4
    -2
      src/commands/toggleFileAnnotations.ts
  68. +4
    -2
      src/commands/toggleLineBlame.ts
  69. +7
    -22
      src/comparers.ts
  70. +1
    -1
      src/config.ts
  71. +1
    -3
      src/configuration.ts
  72. +1
    -1
      src/constants.ts
  73. +3
    -2
      src/credentials.ts
  74. +1
    -1
      src/emojis.ts
  75. +7
    -6
      src/extension.ts
  76. +6
    -6
      src/git/formatters/commitFormatter.ts
  77. +3
    -3
      src/git/formatters/formatter.ts
  78. +1
    -1
      src/git/fsProvider.ts
  79. +13
    -13
      src/git/git.ts
  80. +48
    -44
      src/git/gitService.ts
  81. +1
    -1
      src/git/gitUri.ts
  82. +1
    -1
      src/git/locator.ts
  83. +3
    -3
      src/git/models/blameCommit.ts
  84. +3
    -3
      src/git/models/branch.ts
  85. +1
    -1
      src/git/models/commit.ts
  86. +12
    -12
      src/git/models/logCommit.ts
  87. +3
    -3
      src/git/models/models.ts
  88. +15
    -15
      src/git/models/repository.ts
  89. +6
    -6
      src/git/models/stashCommit.ts
  90. +3
    -3
      src/git/models/status.ts
  91. +2
    -2
      src/git/parsers/blameParser.ts
  92. +6
    -6
      src/git/parsers/logParser.ts
  93. +1
    -1
      src/git/parsers/remoteParser.ts
  94. +2
    -2
      src/git/parsers/stashParser.ts
  95. +3
    -3
      src/git/parsers/statusParser.ts
  96. +2
    -2
      src/git/remotes/custom.ts
  97. +12
    -12
      src/git/remotes/provider.ts
  98. +8
    -6
      src/git/shell.ts
  99. +4
    -4
      src/hovers/hovers.ts
  100. +6
    -6
      src/hovers/lineHoverController.ts

+ 39
- 3
.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<string, unknown>` 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<string, unknown>` 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<string, unknown>` 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",

+ 3
- 3
generateEmojiShortcodeMap.js 查看文件

@ -5,7 +5,7 @@ const path = require('path');
async function generate() {
/**
* @type {{ [code: string]: string }}
* @type {Record<string, string>}
*/
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();

+ 5
- 6
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);
}

+ 1
- 3
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}`;

+ 5
- 5
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<Hover | undefined> {
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<Hover | undefined> {
const commit = await this.getCommitForHover(position);
if (commit === undefined) return undefined;

+ 6
- 6
src/annotations/fileAnnotationController.ts 查看文件

@ -68,7 +68,7 @@ export class FileAnnotationController implements Disposable {
}
private _annotationsDisposable: Disposable | undefined;
private _annotationProviders: Map<TextEditorCorrelationKey, AnnotationProviderBase> = new Map();
private _annotationProviders = new Map<TextEditorCorrelationKey, AnnotationProviderBase>();
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<FileAnnotationType, AnnotationsToggleMode>();
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;

+ 6
- 6
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<boolean> {
async onProvideAnnotation(_shaOrLine?: string | number, _type?: FileAnnotationType): Promise<boolean> {
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<string, DecorationOptions | undefined>;
const avatarDecorationsMap = avatars
? (Object.create(null) as Record<string, { decoration: TextEditorDecorationType; ranges: Range[] }>)
: 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<string, { decoration: TextEditorDecorationType; ranges: Range[] }>,
) {
const avatarDecoration = map[commit.email!];
if (avatarDecoration !== undefined) {

+ 2
- 2
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<boolean> {
async onProvideAnnotation(_shaOrLine?: string | number, _type?: FileAnnotationType): Promise<boolean> {
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<string, DecorationOptions | undefined>;
let commit: GitBlameCommit | undefined;
let heatmap: DecorationOptions | undefined;

+ 4
- 4
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);
}
});
}

+ 1
- 1
src/annotations/recentChangesAnnotationProvider.ts 查看文件

@ -132,7 +132,7 @@ export class RecentChangesAnnotationProvider extends AnnotationProviderBase {
return true;
}
selection(shaOrLine?: string | number): Promise<void> {
selection(_shaOrLine?: string | number): Promise<void> {
return Promise.resolve(undefined);
}

+ 1
- 1
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);

+ 1
- 1
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);
}
}

+ 10
- 10
src/codelens/codeLensProvider.ts 查看文件

@ -100,7 +100,7 @@ export class GitCodeLensProvider implements CodeLensProvider {
private readonly _tracker: DocumentTracker<GitDocumentState>,
) {}
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<CodeLens>(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;

+ 1
- 1
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');
}
}
}

+ 6
- 9
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<TextEditor | undefined> {
return new Promise<TextEditor>((resolve, reject) => {
return new Promise<TextEditor>(resolve => {
let timer: NodeJS.Timer | undefined;
this._onEditorChangedFn = (editor: TextEditor | undefined) => {

+ 6
- 6
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<any> {
@ -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;
}

+ 5
- 4
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');
}
}
}

+ 5
- 4
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');
}
}
}

+ 1
- 1
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');
}
}
}

+ 4
- 4
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<DiffWithCommandArgs>(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');
}
}
}

+ 3
- 3
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;
}

+ 2
- 2
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');
}
}
}

+ 3
- 3
src/commands/diffWithNext.ts 查看文件

@ -56,11 +56,11 @@ export class DiffWithNextCommand extends ActiveEditorCommand {
void (await executeCommand<DiffWithCommandArgs>(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');
}
}
}

+ 5
- 5
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<DiffWithCommandArgs>(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');
}
}
}

+ 1
- 1
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');
}
}
}

+ 2
- 2
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: '',

+ 4
- 4
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;
}

+ 2
- 2
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');
}
}
}

+ 2
- 5
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<State>,
context: Context,
): StepResultGenerator<State['subcommand']> {
private *pickSubcommandStep(state: PartialStepState<State>): StepResultGenerator<State['subcommand']> {
const step = QuickCommand.createPickStep<QuickPickItemOfT<State['subcommand']>>({
title: this.title,
placeholder: `Choose a ${this.label} command`,

+ 1
- 1
src/commands/git/cherry-pick.ts 查看文件

@ -81,7 +81,7 @@ export class CherryPickGitCommand extends QuickCommand {
protected async *steps(state: PartialStepState<State>): StepGenerator {
const context: Context = {
repos: [...(await Container.git.getOrderedRepositories())],
cache: new Map(),
cache: new Map<string, Promise<GitLog | undefined>>(),
destination: undefined!,
selectedBranchOrTag: undefined,
showTags: true,

+ 1
- 1
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;

+ 1
- 1
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;

+ 1
- 1
src/commands/git/log.ts 查看文件

@ -77,7 +77,7 @@ export class LogGitCommand extends QuickCommand {
protected async *steps(state: PartialStepState<State>): StepGenerator {
const context: Context = {
repos: [...(await Container.git.getOrderedRepositories())],
cache: new Map(),
cache: new Map<string, Promise<GitLog | undefined>>(),
selectedBranchOrTag: undefined,
title: this.title,
};

+ 2
- 2
src/commands/git/merge.ts 查看文件

@ -77,7 +77,7 @@ export class MergeGitCommand extends QuickCommand {
protected async *steps(state: PartialStepState<State>): StepGenerator {
const context: Context = {
repos: [...(await Container.git.getOrderedRepositories())],
cache: new Map(),
cache: new Map<string, Promise<GitLog | undefined>>(),
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<DirectiveQuickPickItem> = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),

+ 1
- 1
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;

+ 1
- 1
src/commands/git/push.ts 查看文件

@ -116,7 +116,7 @@ export class PushGitCommand extends QuickCommand {
}
QuickCommand.endSteps(state);
this.execute(state as State<Repository[]>);
void this.execute(state as State<Repository[]>);
}
return state.counter < 0 ? StepResult.Break : undefined;

+ 2
- 2
src/commands/git/rebase.ts 查看文件

@ -78,7 +78,7 @@ export class RebaseGitCommand extends QuickCommand {
protected async *steps(state: PartialStepState<State>): StepGenerator {
const context: Context = {
repos: [...(await Container.git.getOrderedRepositories())],
cache: new Map(),
cache: new Map<string, Promise<GitLog | undefined>>(),
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<DirectiveQuickPickItem> = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),

+ 1
- 1
src/commands/git/reset.ts 查看文件

@ -69,7 +69,7 @@ export class ResetGitCommand extends QuickCommand {
protected async *steps(state: PartialStepState<State>): StepGenerator {
const context: Context = {
repos: [...(await Container.git.getOrderedRepositories())],
cache: new Map(),
cache: new Map<string, Promise<GitLog | undefined>>(),
destination: undefined!,
title: this.title,
};

+ 1
- 1
src/commands/git/revert.ts 查看文件

@ -71,7 +71,7 @@ export class RevertGitCommand extends QuickCommand {
protected async *steps(state: PartialStepState<State>): StepGenerator {
const context: Context = {
repos: [...(await Container.git.getOrderedRepositories())],
cache: new Map(),
cache: new Map<string, Promise<GitLog | undefined>>(),
destination: undefined!,
title: this.title,
};

+ 5
- 5
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<string, GitAuthor>(),
commits: new Map<string, GitLogCommit>(),
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;
}
}

+ 13
- 12
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<State>,
context: Context,
): StepResultGenerator<State['subcommand']> {
private *pickSubcommandStep(state: PartialStepState<State>): StepResultGenerator<State['subcommand']> {
const step = QuickCommand.createPickStep<QuickPickItemOfT<State['subcommand']>>({
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;
}

+ 1
- 1
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;
}
}

+ 1
- 1
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;

+ 2
- 5
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<State>,
context: Context,
): StepResultGenerator<State['subcommand']> {
private *pickSubcommandStep(state: PartialStepState<State>): StepResultGenerator<State['subcommand']> {
const step = QuickCommand.createPickStep<QuickPickItemOfT<State['subcommand']>>({
title: this.title,
placeholder: `Choose a ${this.label} command`,

+ 4
- 4
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',

+ 8
- 8
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;
}
}

+ 1
- 1
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();

+ 3
- 1
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',
);
}
}
}

+ 3
- 1
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',
);
}
}
}

+ 2
- 2
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');
}
}
}

+ 6
- 2
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',
);
}
}
}

+ 2
- 2
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');
}
}
}

+ 1
- 1
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');
}
}
}

+ 1
- 1
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;
}

+ 2
- 2
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');
}
}
}

+ 1
- 1
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');
}
}
}

+ 1
- 1
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',
);
}

+ 1
- 1
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');
}
}
}

+ 2
- 2
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');
}
}
}

+ 8
- 8
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, {

+ 9
- 8
src/commands/quickCommand.ts 查看文件

@ -27,7 +27,7 @@ export function isQuickInputStep(
return typeof step === 'object' && (step as QuickPickStep).items == null;
}
export interface QuickPickStep<T extends QuickPickItem = any> {
export interface QuickPickStep<T extends QuickPickItem = QuickPickItem> {
additionalButtons?: QuickInputButton[];
allowEmpty?: boolean;
buttons?: QuickInputButton[];
@ -73,7 +73,7 @@ export type StepSelection = T extends QuickPickStep
? string | Directive
: never;
export type PartialStepState<T = unknown> = Partial<T> & { counter: number; confirm?: boolean; startingStep?: number };
export type StepState<T = {}> = T & { counter: number; confirm?: boolean; startingStep?: number };
export type StepState<T = Record<string, unknown>> = T & { counter: number; confirm?: boolean; startingStep?: number };
export abstract class QuickCommand<State = any> implements QuickPickItem {
readonly description?: string;
@ -194,8 +194,8 @@ export abstract class QuickCommand implements QuickPickItem {
return QuickCommand.createPickStep<T>({
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<T> {
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<T>({
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,
});
}

+ 6
- 6
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');
}
}
}

+ 6
- 6
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');
}
}
}

+ 0
- 29
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');
// }
}
}

+ 1
- 1
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 };

+ 1
- 1
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;

+ 4
- 2
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`,
);
}
}

+ 4
- 2
src/commands/toggleLineBlame.ts 查看文件

@ -9,12 +9,14 @@ export class ToggleLineBlameCommand extends ActiveEditorCommand {
super(Commands.ToggleLineBlame);
}
async execute(editor: TextEditor, uri?: Uri): Promise<void> {
async execute(editor: TextEditor, _uri?: Uri): Promise<void> {
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',
);
}
}
}

+ 7
- 22
src/comparers.ts 查看文件

@ -1,5 +1,5 @@
'use strict';
import { TextDocument, TextEditor, Uri } from 'vscode';
import { TextEditor, Uri } from 'vscode';
abstract class Comparer<T> {
abstract equals(lhs: T, rhs: T): boolean;
@ -8,25 +8,15 @@ abstract class Comparer {
class UriComparer extends Comparer<Uri> {
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<TextDocument> {
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<TextEditor> {
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 };

+ 1
- 1
src/config.ts 查看文件

@ -90,7 +90,7 @@ export interface Config {
alignment: 'left' | 'right';
};
};
modes: { [key: string]: ModeConfig };
modes: Record<string, ModeConfig>;
outputLevel: TraceLevel;
recentChanges: {
highlight: {

+ 1
- 3
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 extends keyof Config>(s1: S1, scope?: ConfigurationScope | null, defaultValue?: Config[S1]): Config[S1];

+ 1
- 1
src/constants.ts 查看文件

@ -130,7 +130,7 @@ export enum GlobalState {
GitLensVersion = 'gitlensVersion',
}
export const ImageMimetypes: { [key: string]: string } = {
export const ImageMimetypes: Record<string, string> = {
'.png': 'image/png',
'.gif': 'image/gif',
'.jpg': 'image/jpeg',

+ 3
- 2
src/credentials.ts 查看文件

@ -36,7 +36,8 @@ export namespace CredentialManager {
const _onDidChange = new EventEmitter<CredentialChangeEvent>();
export const onDidChange: Event<CredentialChangeEvent> = _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<T extends {}>(key: string): Promise<T | undefined> {
export async function getAs<T extends object>(key: string): Promise<T | undefined> {
const value = await get(key);
if (value == null) return undefined;

+ 1
- 1
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<string, string>;
const emojiRegex = /:([-+_a-z0-9]+):/g;
export function emojify(message: string) {

+ 7
- 6
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<boolean>('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<string, any> = 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));

+ 6
- 6
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 += `&nbsp; **[\`${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() {

+ 3
- 3
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<string, Strings.TokenOptions | undefined>;
}
type Constructor<T = {}> = new (...args: any[]) => T;
type Constructor<T = Record<string, unknown>> = new (...args: any[]) => T;
const spaceReplacementRegex = / /g;
@ -87,7 +87,7 @@ export abstract class Formatter
}
if (options.prefix || options.suffix) {
s = `${options.prefix || emptyStr}${s}${options.suffix || emptyStr}`;
s = `${options.prefix ?? emptyStr}${s}${options.suffix ?? emptyStr}`;
}
return s;

+ 1
- 1
src/git/fsProvider.ts 查看文件

@ -43,7 +43,7 @@ export class GitFileSystemProvider implements FileSystemProvider, Disposable {
}
dispose() {
this._disposable && this._disposable.dispose();
this._disposable.dispose();
}
private _onDidChangeFile = new EventEmitter<FileChangeEvent[]>();

+ 13
- 13
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<string, Promise<string | Buffer>> = new Map();
const pendingCommands = new Map<string, Promise<string | Buffer>>();
export async function git<TOut extends string | Buffer>(options: GitCommandOptions, ...args: any[]): Promise<TOut> {
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<string>(
{ 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<string>(
{ 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<string>(
{ 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<TOut>(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<TOut>(repoPath, fileName, 'HEAD:', options);
}

+ 48
- 44
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<string>('git.path'));
await Git.setOrFindGitPath(gitPath ?? configuration.getAny<string>('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<Record<string, boolean>>('files.exclude', uri, {}),
...configuration.getAny<Record<string, boolean>>('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<string, boolean>);
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<string, boolean>,
repositories: string[] = [],
): Promise<string[]> {
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<string | undefined> {
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 => '<contents>',
1: _contents => '<contents>',
},
})
async getBlameForFileContents(uri: GitUri, contents: string): Promise<GitBlame | undefined> {
@ -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 => '<contents>',
2: _contents => '<contents>',
},
})
async getBlameForLineContents(
@ -963,7 +966,7 @@ export class GitService implements Disposable {
@log({
args: {
2: contents => '<contents>',
2: _contents => '<contents>',
},
})
async getBlameForRangeContents(uri: GitUri, range: Range, contents: string): Promise<GitBlameLines | undefined> {
@ -975,7 +978,7 @@ export class GitService implements Disposable {
@log({
args: {
0: blame => '<blame>',
0: _blame => '<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<string, GitAuthor> = new Map();
const commits: Map<string, GitBlameCommit> = new Map();
const authors = new Map<string, GitAuthor>();
const commits = new Map<string, GitBlameCommit>();
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<GitRemote[]> {
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 =

+ 1
- 1
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;

+ 1
- 1
src/git/locator.ts 查看文件

@ -65,7 +65,7 @@ function findGitWin32(): Promise {
export async function findGitPath(path?: string): Promise<GitLocation> {
try {
return await findSpecificGit(path || 'git');
return await findSpecificGit(path ?? 'git');
} catch (ex) {
try {
switch (process.platform) {

+ 3
- 3
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) ?? [],
);
}
}

+ 3
- 3
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<StarredBranches>(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);

+ 1
- 1
src/git/models/commit.ts 查看文件

@ -143,7 +143,7 @@ export abstract class GitCommit implements GitRevisionReference {
}
@memoize<GitCommit['getPreviousLineDiffUris']>(
(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);

+ 12
- 12
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),

+ 3
- 3
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;

+ 15
- 15
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<GitRemote[]> {
getRemotes(_options: { sort?: boolean } = {}): Promise<GitRemote[]> {
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<boolean> {
const remotes = await this.getRemotes();
return remotes !== undefined && remotes.length > 0;
return remotes?.length > 0;
}
async hasTrackingBranch(): Promise<boolean> {
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<StarredRepositories>(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);

+ 6
- 6
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) ?? [],
);
}
}

+ 3
- 3
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),
);
}

+ 2
- 2
src/git/parsers/blameParser.ts 查看文件

@ -39,8 +39,8 @@ export class GitBlameParser {
): GitBlame | undefined {
if (!data) return undefined;
const authors: Map<string, GitAuthor> = new Map();
const commits: Map<string, GitBlameCommit> = new Map();
const authors = new Map<string, GitAuthor>();
const commits = new Map<string, GitBlameCommit>();
const lines: GitCommitLine[] = [];
let relativeFileName;

+ 6
- 6
src/git/parsers/logParser.ts 查看文件

@ -110,8 +110,8 @@ export class GitLogParser {
repoPath = Strings.normalizePath(repoPath);
}
const authors: Map<string, GitAuthor> = new Map();
const commits: Map<string, GitLogCommit> = new Map();
const authors = new Map<string, GitAuthor>();
const commits = new Map<string, GitLogCommit>();
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;

+ 1
- 1
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<string, GitRemote | undefined>;
let name;
let url;

+ 2
- 2
src/git/parsers/stashParser.ts 查看文件

@ -48,7 +48,7 @@ export class GitStashParser {
repoPath = Strings.normalizePath(repoPath);
}
const commits: Map<string, GitStashCommit> = new Map();
const commits = new Map<string, GitStashCommit>();
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 ?? [],
);
}

+ 3
- 3
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,

+ 2
- 2
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<string, unknown>) {
const [repoBase, repoPath] = this.splitPath();
return {
repo: this.path,
repoBase: repoBase,
repoPath: repoPath,
...(context || {}),
...(context ?? {}),
};
}
}

+ 12
- 12
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<void> {
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<boolean | undefined> {
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<boolean | undefined> {
if (url == null) return undefined;
return env.openExternal(Uri.parse(url));
}
}
export abstract class RemoteProviderWithApi<T extends string | {} = any> extends RemoteProvider {
export abstract class RemoteProviderWithApi<T extends object = any> extends RemoteProvider {
static is(provider: RemoteProvider | undefined): provider is RemoteProviderWithApi {
return provider instanceof RemoteProviderWithApi;
}

+ 8
- 6
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');
}
});
}

+ 4
- 4
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, {

+ 6
- 6
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<Hover | undefined> {
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<Hover | undefined> {
if (!Container.lineTracker.includes(position.line)) return undefined;

部分文件因为文件数量过多而无法显示

正在加载...
取消
保存