Skip to content

Commit

Permalink
Enable no-case-declarations in codebase (#139243)
Browse files Browse the repository at this point in the history
Fixes #139236

This can catch tricky programming mistakes that cause a runtime error. See 7e266b2 as an example of the type of bug this can prevent
  • Loading branch information
mjbvz committed Dec 16, 2021
1 parent f589173 commit e7b3724
Show file tree
Hide file tree
Showing 68 changed files with 233 additions and 158 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"eqeqeq": "warn",
"no-buffer-constructor": "warn",
"no-caller": "warn",
"no-case-declarations": "warn",
"no-debugger": "warn",
"no-duplicate-case": "warn",
"no-duplicate-imports": "warn",
Expand Down
6 changes: 4 additions & 2 deletions extensions/git/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2821,20 +2821,21 @@ export class CommandCenter {
type = 'warning';
options.modal = false;
break;
case GitErrorCodes.AuthenticationFailed:
case GitErrorCodes.AuthenticationFailed: {
const regex = /Authentication failed for '(.*)'/i;
const match = regex.exec(err.stderr || String(err));

message = match
? localize('auth failed specific', "Failed to authenticate to git remote:\n\n{0}", match[1])
: localize('auth failed', "Failed to authenticate to git remote.");
break;
}
case GitErrorCodes.NoUserNameConfigured:
case GitErrorCodes.NoUserEmailConfigured:
message = localize('missing user info', "Make sure you configure your 'user.name' and 'user.email' in git.");
choices.set(localize('learn more', "Learn More"), () => commands.executeCommand('vscode.open', Uri.parse('https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup')));
break;
default:
default: {
const hint = (err.stderr || err.message || String(err))
.replace(/^error: /mi, '')
.replace(/^> husky.*$/mi, '')
Expand All @@ -2847,6 +2848,7 @@ export class CommandCenter {
: localize('git error', "Git error");

break;
}
}

if (!message) {
Expand Down
4 changes: 2 additions & 2 deletions extensions/git/src/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1196,7 +1196,7 @@ export class Repository {
break;

// Rename contains two paths, the second one is what the file is renamed/copied to.
case 'R':
case 'R': {
if (index >= entries.length) {
break;
}
Expand All @@ -1215,7 +1215,7 @@ export class Repository {
});

continue;

}
default:
// Unknown status
break entriesLoop;
Expand Down
4 changes: 2 additions & 2 deletions extensions/git/src/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,7 @@ class ResourceCommandResolver {
case Status.MODIFIED:
case Status.UNTRACKED:
case Status.IGNORED:
case Status.INTENT_TO_ADD:
case Status.INTENT_TO_ADD: {
const uriString = resource.resourceUri.toString();
const [indexStatus] = this.repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString);

Expand All @@ -673,7 +673,7 @@ class ResourceCommandResolver {
}

return resource.resourceUri;

}
case Status.BOTH_ADDED:
case Status.BOTH_MODIFIED:
return resource.resourceUri;
Expand Down
3 changes: 2 additions & 1 deletion extensions/markdown-language-features/preview-src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ window.addEventListener('message', async event => {
}
return;

case 'updateContent':
case 'updateContent': {
const root = document.querySelector('.markdown-body')!;

const parser = new DOMParser();
Expand Down Expand Up @@ -216,6 +216,7 @@ window.addEventListener('message', async event => {

window.dispatchEvent(new CustomEvent('vscode.markdown.updateContent'));
break;
}
}
}, false);

Expand Down
3 changes: 2 additions & 1 deletion extensions/microsoft-authentication/src/authServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export function createServer(nonce: string) {
const server = http.createServer(function (req, res) {
const reqUrl = url.parse(req.url!, /* parseQueryString */ true);
switch (reqUrl.pathname) {
case '/signin':
case '/signin': {
const receivedNonce = ((reqUrl.query.nonce as string) || '').replace(/ /g, '+');
if (receivedNonce === nonce) {
deferredRedirect.resolve({ req, res });
Expand All @@ -129,6 +129,7 @@ export function createServer(nonce: string) {
deferredRedirect.resolve({ err, res });
}
break;
}
case '/':
sendFile(res, path.join(__dirname, '../media/auth.html'), 'text/html; charset=utf-8');
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ export class TypeScriptReferencesCodeLensProvider extends TypeScriptBaseCodeLens
}

switch (item.kind) {
case PConst.Kind.function:
case PConst.Kind.function: {
const showOnAllFunctions = vscode.workspace.getConfiguration(this.modeId).get<boolean>('referencesCodeLens.showOnAllFunctions');
if (showOnAllFunctions) {
return getSymbolRange(document, item);
}
}
// fallthrough

case PConst.Kind.const:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -816,10 +816,10 @@ class TypeScriptCompletionItemProvider implements vscode.CompletionItemProvider<
case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367
return this.client.apiVersion.lt(API.v381) ? undefined : '#';

case ' ':
case ' ': {
const space: Proto.CompletionsTriggerCharacter = ' ';
return this.client.apiVersion.gte(API.v430) ? space : undefined;

}
case '.':
case '"':
case '\'':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,15 @@ class BufferSynchronizer {

private updatePending(resource: vscode.Uri, op: BufferOperation): boolean {
switch (op.type) {
case BufferOperationType.Close:
case BufferOperationType.Close: {
const existing = this._pending.get(resource);
switch (existing?.type) {
case BufferOperationType.Open:
this._pending.delete(resource);
return false; // Open then close. No need to do anything
}
break;
}
}

if (this._pending.has(resource)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ export class ProcessBasedTsServer extends Disposable implements ITypeScriptServe
}
break;

case 'event':
case 'event': {
const event = message as Proto.Event;
if (event.event === 'requestCompleted') {
const seq = (event as Proto.RequestCompletedEvent).body.request_seq;
Expand All @@ -162,7 +162,7 @@ export class ProcessBasedTsServer extends Disposable implements ITypeScriptServe
this._onEvent.fire(event);
}
break;

}
default:
throw new Error(`Unknown message type ${message.type} received`);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -866,7 +866,7 @@ export default class TypeScriptServiceClient extends Disposable implements IType
switch (event.event) {
case EventName.syntaxDiag:
case EventName.semanticDiag:
case EventName.suggestionDiag:
case EventName.suggestionDiag: {
// This event also roughly signals that projects have been loaded successfully (since the TS server is synchronous)
this.loadingIndicator.reset();

Expand All @@ -879,34 +879,32 @@ export default class TypeScriptServiceClient extends Disposable implements IType
});
}
break;

}
case EventName.configFileDiag:
this._onConfigDiagnosticsReceived.fire(event as Proto.ConfigFileDiagnosticEvent);
break;

case EventName.telemetry:
{
const body = (event as Proto.TelemetryEvent).body;
this.dispatchTelemetryEvent(body);
break;
}
case EventName.projectLanguageServiceState:
{
const body = (event as Proto.ProjectLanguageServiceStateEvent).body!;
if (this.serverState.type === ServerState.Type.Running) {
this.serverState.updateLanguageServiceEnabled(body.languageServiceEnabled);
}
this._onProjectLanguageServiceStateChanged.fire(body);
break;
case EventName.telemetry: {
const body = (event as Proto.TelemetryEvent).body;
this.dispatchTelemetryEvent(body);
break;
}
case EventName.projectLanguageServiceState: {
const body = (event as Proto.ProjectLanguageServiceStateEvent).body!;
if (this.serverState.type === ServerState.Type.Running) {
this.serverState.updateLanguageServiceEnabled(body.languageServiceEnabled);
}
case EventName.projectsUpdatedInBackground:
this._onProjectLanguageServiceStateChanged.fire(body);
break;
}
case EventName.projectsUpdatedInBackground: {
this.loadingIndicator.reset();

const body = (event as Proto.ProjectsUpdatedInBackgroundEvent).body;
const resources = body.openFiles.map(file => this.toResource(file));
this.bufferSyncSupport.getErr(resources);
break;

}
case EventName.beginInstallTypes:
this._onDidBeginInstallTypings.fire((event as Proto.BeginInstallTypesEvent).body);
break;
Expand Down Expand Up @@ -936,7 +934,7 @@ export default class TypeScriptServiceClient extends Disposable implements IType
private dispatchTelemetryEvent(telemetryData: Proto.TelemetryEventBody): void {
const properties: { [key: string]: string } = Object.create(null);
switch (telemetryData.telemetryEventName) {
case 'typingsInstalled':
case 'typingsInstalled': {
const typingsInstalledPayload: Proto.TypingsInstalledTelemetryEventPayload = (telemetryData.payload as Proto.TypingsInstalledTelemetryEventPayload);
properties['installedPackages'] = typingsInstalledPayload.installedPackages;

Expand All @@ -947,8 +945,8 @@ export default class TypeScriptServiceClient extends Disposable implements IType
properties['typingsInstallerVersion'] = typingsInstalledPayload.typingsInstallerVersion;
}
break;

default:
}
default: {
const payload = telemetryData.payload;
if (payload) {
Object.keys(payload).forEach((key) => {
Expand All @@ -962,6 +960,7 @@ export default class TypeScriptServiceClient extends Disposable implements IType
});
}
break;
}
}
if (telemetryData.telemetryEventName === 'projectInfo') {
if (this.serverState.type === ServerState.Type.Running) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,16 @@ function getTagBodyText(

const text = convertLinkTags(tag.text, filePathConverter);
switch (tag.name) {
case 'example':
case 'example': {
// check for caption tags, fix for #79704
const captionTagMatches = text.match(/<caption>(.*?)<\/caption>\s*(\r\n|\n)/);
if (captionTagMatches && captionTagMatches.index === 0) {
return captionTagMatches[1] + '\n' + makeCodeblock(text.substr(captionTagMatches[0].length));
} else {
return makeCodeblock(text);
}
case 'author':
}
case 'author': {
// fix obsucated email address, #80898
const emailMatch = text.match(/(.+)\s<([-.\w]+@[-.\w]+)>/);

Expand All @@ -66,6 +67,7 @@ function getTagBodyText(
} else {
return `${emailMatch[1]} ${emailMatch[2]}`;
}
}
case 'default':
return makeCodeblock(text);
}
Expand All @@ -81,7 +83,7 @@ function getTagDocumentation(
case 'augments':
case 'extends':
case 'param':
case 'template':
case 'template': {
const body = (convertLinkTags(tag.text, filePathConverter)).split(/^(\S+)\s*-?\s*/);
if (body?.length === 3) {
const param = body[1];
Expand All @@ -92,6 +94,7 @@ function getTagDocumentation(
}
return label + (doc.match(/\r\n|\n/g) ? ' \n' + processInlineTags(doc) : ` \u2014 ${processInlineTags(doc)}`);
}
}
}

// Generic tag
Expand Down
4 changes: 2 additions & 2 deletions src/vs/base/common/glob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ function parseRegExp(pattern: string): string {
inBrackets = true;
continue;

case '}':
case '}': {
const choices = splitGlobAware(braceVal, ',');

// Converts {foo,bar} => [foo|bar]
Expand All @@ -189,7 +189,7 @@ function parseRegExp(pattern: string): string {
braceVal = '';

break;

}
case ']':
regEx += ('[' + bracketVal + ']');

Expand Down
13 changes: 8 additions & 5 deletions src/vs/base/common/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,14 +332,15 @@ export function createScanner(text: string, ignoreTrivia: boolean = false): JSON
case CharacterCodes.t:
result += '\t';
break;
case CharacterCodes.u:
case CharacterCodes.u: {
const ch3 = scanHexDigits(4);
if (ch3 >= 0) {
result += String.fromCharCode(ch3);
} else {
scanError = ScanError.InvalidUnicode;
}
break;
}
default:
scanError = ScanError.InvalidEscapeCharacter;
}
Expand Down Expand Up @@ -425,7 +426,7 @@ export function createScanner(text: string, ignoreTrivia: boolean = false): JSON
return token = SyntaxKind.StringLiteral;

// comments
case CharacterCodes.slash:
case CharacterCodes.slash: {
const start = pos - 1;
// Single-line comment
if (text.charCodeAt(pos + 1) === CharacterCodes.slash) {
Expand Down Expand Up @@ -471,7 +472,7 @@ export function createScanner(text: string, ignoreTrivia: boolean = false): JSON
value += String.fromCharCode(code);
pos++;
return token = SyntaxKind.Unknown;

}
// numbers
case CharacterCodes.minus:
value += String.fromCharCode(code);
Expand Down Expand Up @@ -1016,7 +1017,7 @@ export function getNodeValue(node: Node): any {
switch (node.type) {
case 'array':
return node.children!.map(getNodeValue);
case 'object':
case 'object': {
const obj = Object.create(null);
for (let prop of node.children!) {
const valueNode = prop.children![1];
Expand All @@ -1025,6 +1026,7 @@ export function getNodeValue(node: Node): any {
}
}
return obj;
}
case 'null':
case 'string':
case 'number':
Expand Down Expand Up @@ -1162,7 +1164,7 @@ export function visit(text: string, visitor: JSONVisitor, options: ParseOptions

function parseLiteral(): boolean {
switch (_scanner.getToken()) {
case SyntaxKind.NumericLiteral:
case SyntaxKind.NumericLiteral: {
let value = 0;
try {
value = JSON.parse(_scanner.getTokenValue());
Expand All @@ -1175,6 +1177,7 @@ export function visit(text: string, visitor: JSONVisitor, options: ParseOptions
}
onLiteralValue(value);
break;
}
case SyntaxKind.NullKeyword:
onLiteralValue(null);
break;
Expand Down

0 comments on commit e7b3724

Please sign in to comment.