From ea21e2c39808383887170b0957706e308ca70618 Mon Sep 17 00:00:00 2001 From: Adi Dahiya Date: Mon, 22 Jun 2015 14:18:40 -0400 Subject: [PATCH] Update to tslint 2.3.0-beta and use new rules Use new rules: - `no-var-keyword` - `sort-object-literal-keys` Also fix some whitespace issues & small cleanup in tests. --- lib/tslint.d.ts | 10 +- src/configuration.ts | 23 ++-- src/enableDisableRules.ts | 27 ++-- src/formatterLoader.ts | 24 ++-- src/formatters/jsonFormatter.ts | 5 +- src/formatters/pmdFormatter.ts | 12 +- src/formatters/proseFormatter.ts | 15 +-- src/formatters/verboseFormatter.ts | 12 +- src/language/formatter/abstractFormatter.ts | 2 - src/language/languageServiceHost.ts | 18 ++- src/language/rule/abstractRule.ts | 9 +- src/language/rule/rule.ts | 47 +++---- src/language/utils.ts | 38 +++--- .../walker/blockScopeAwareRuleWalker.ts | 8 +- src/language/walker/ruleWalker.ts | 40 +----- src/language/walker/scopeAwareRuleWalker.ts | 8 +- src/ruleLoader.ts | 75 ++++++----- src/rules/alignRule.ts | 22 +-- src/rules/banRule.ts | 24 ++-- src/rules/classNameRule.ts | 15 +-- src/rules/commentFormatRule.ts | 28 ++-- src/rules/curlyRule.ts | 34 ++--- src/rules/eoflineRule.ts | 14 +- src/rules/forinRule.ts | 29 ++-- src/rules/indentRule.ts | 36 ++--- src/rules/interfaceNameRule.ts | 10 +- src/rules/jsdocFormatRule.ts | 45 ++++--- src/rules/labelPositionRule.ts | 6 +- src/rules/labelUndefinedRule.ts | 18 +-- src/rules/maxLineLengthRule.ts | 23 ++-- src/rules/memberOrderingRule.ts | 40 +++--- src/rules/noAnyRule.ts | 2 +- src/rules/noArgRule.ts | 14 +- src/rules/noBitwiseRule.ts | 6 +- src/rules/noConsecutiveBlankLinesRule.ts | 11 +- src/rules/noConsoleRule.ts | 10 +- src/rules/noConstructRule.ts | 10 +- src/rules/noConstructorVarsRule.ts | 20 ++- src/rules/noDebuggerRule.ts | 6 +- src/rules/noDuplicateKeyRule.ts | 4 +- src/rules/noEmptyRule.ts | 50 +++---- src/rules/noEvalRule.ts | 8 +- src/rules/noRequireImportsRule.ts | 2 +- src/rules/noShadowedVariableRule.ts | 6 +- src/rules/noStringLiteralRule.ts | 12 +- src/rules/noSwitchCaseFallThroughRule.ts | 46 +++---- src/rules/noTrailingCommaRule.ts | 10 +- src/rules/noTrailingWhitespaceRule.ts | 14 +- src/rules/noUnreachableRule.ts | 22 +-- src/rules/noUnusedExpressionRule.ts | 9 +- src/rules/noUnusedVariableRule.ts | 74 +++++----- src/rules/noUseBeforeDeclareRule.ts | 54 ++++---- src/rules/noVarKeywordRule.ts | 16 +-- src/rules/noVarRequiresRule.ts | 10 +- src/rules/oneLineRule.ts | 126 +++++++++--------- src/rules/quotemarkRule.ts | 20 +-- src/rules/radixRule.ts | 15 +-- src/rules/semicolonRule.ts | 27 +--- src/rules/sortObjectLiteralKeysRule.ts | 9 +- src/rules/switchDefaultRule.ts | 13 +- src/rules/tripleEqualsRule.ts | 12 +- src/rules/typedefRule.ts | 12 +- src/rules/typedefWhitespaceRule.ts | 17 +-- src/rules/useStrictRule.ts | 28 ++-- src/rules/whitespaceRule.ts | 10 +- src/tslint-cli.ts | 32 ++--- src/tslint.ts | 46 +++---- test/files/rules/noAny.test.ts | 6 +- test/files/rules/novarkeyword.test.ts | 12 +- test/formatters/externalFormatterTest.ts | 19 +-- test/formatters/jsonFormatterTests.ts | 22 +-- test/formatters/pmdFormatterTests.ts | 16 +-- test/formatters/proseFormatterTests.ts | 20 +-- test/formatters/verboseFormatterTests.ts | 24 ++-- test/helper.ts | 28 ++-- test/ruleDisableEnableTests.ts | 57 ++++---- test/ruleLoaderTests.ts | 16 +-- test/rules/alignRuleTests.ts | 62 ++++----- test/rules/banRuleTests.ts | 12 +- test/rules/classNameRuleTests.ts | 14 +- test/rules/commentFormatRuleTests.ts | 40 +++--- test/rules/curlyRuleTests.ts | 2 +- test/rules/eofLineRuleTests.ts | 14 +- test/rules/forInRuleTests.ts | 16 ++- test/rules/indentRuleTests.ts | 16 +-- test/rules/interfaceNameRuleTests.ts | 10 +- test/rules/jsdocFormatRuleTests.ts | 28 ++-- test/rules/labelPositionRuleTests.ts | 11 +- test/rules/labelUndefinedRuleTests.ts | 12 +- test/rules/maxLineLengthRuleTests.ts | 9 +- test/rules/memberOrderingRuleTests.ts | 18 +-- test/rules/noAnyRuleTests.ts | 10 +- test/rules/noArgRuleTests.ts | 8 +- test/rules/noBitwiseRuleTests.ts | 10 +- .../rules/noConsecutiveBlankLinesRuleTests.ts | 14 +- test/rules/noConsoleRuleTests.ts | 15 ++- test/rules/noConstructRuleTests.ts | 14 +- test/rules/noConstructorVarsRuleTests.ts | 16 +-- test/rules/noDebuggerRuleTests.ts | 11 +- test/rules/noDuplicateKeyRuleTests.ts | 8 +- test/rules/noDuplicateVariableRuleTests.ts | 7 +- test/rules/noEmptyRuleTests.ts | 18 +-- test/rules/noEvalRuleTests.ts | 11 +- test/rules/noRequireImportsTests.ts | 6 +- test/rules/noShadowedVariableRuleTests.ts | 6 +- test/rules/noStringLiteralRuleTests.ts | 10 +- .../rules/noSwitchCaseFallThroughRuleTests.ts | 16 +-- test/rules/noTrailingCommaRuleTests.ts | 11 +- test/rules/noTrailingWhitespaceRuleTests.ts | 21 ++- test/rules/noUnreachableRuleTests.ts | 11 +- test/rules/noUnusedExpressionRuleTests.ts | 10 +- test/rules/noUnusedVariableRuleTests.ts | 84 ++++++------ test/rules/noUseBeforeDeclareRuleTests.ts | 31 ++--- test/rules/noVarKeywordRuleTests.ts | 24 ++-- test/rules/noVarRequiresRuleTests.ts | 9 +- test/rules/oneLineRuleTests.ts | 44 +++--- test/rules/quotemarkRuleTests.ts | 16 +-- test/rules/radixRuleTests.ts | 11 +- test/rules/semicolonRuleTests.ts | 10 +- test/rules/sortObjectLiteralKeysRuleTests.ts | 8 +- test/rules/switchDefaultRuleTests.ts | 13 +- test/rules/tripleEqualsRuleTests.ts | 14 +- test/rules/typedefWhitespaceRuleTests.ts | 66 ++++----- test/rules/useStrictRuleTests.ts | 13 +- test/tsconfig.json | 7 +- tslint.json | 2 + 126 files changed, 1239 insertions(+), 1330 deletions(-) diff --git a/lib/tslint.d.ts b/lib/tslint.d.ts index 6a524c0bebb..b5633c37a2f 100644 --- a/lib/tslint.d.ts +++ b/lib/tslint.d.ts @@ -83,7 +83,7 @@ declare module Lint { getOptions(): any; hasOption(option: string): boolean; skip(node: ts.Node): void; - createFailure(start: number, width: number, failure: string): Lint.RuleFailure; + createFailure(start: number, width: number, failure: string): RuleFailure; addFailure(failure: RuleFailure): void; private existsFailure(failure); } @@ -149,9 +149,9 @@ declare module Lint { getPosition(): number; getLineAndCharacter(): ts.LineAndCharacter; toJson(): { - position: number; - line: number; character: number; + line: number; + position: number; }; equals(ruleFailurePosition: RuleFailurePosition): boolean; } @@ -165,8 +165,8 @@ declare module Lint { constructor(sourceFile: ts.SourceFile, start: number, end: number, failure: string, ruleName: string); getFileName(): string; getRuleName(): string; - getStartPosition(): Lint.RuleFailurePosition; - getEndPosition(): Lint.RuleFailurePosition; + getStartPosition(): RuleFailurePosition; + getEndPosition(): RuleFailurePosition; getFailure(): string; toJson(): any; equals(ruleFailure: RuleFailure): boolean; diff --git a/src/configuration.ts b/src/configuration.ts index a76dfdcdbc4..083206adeb7 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -12,12 +12,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ module Lint.Configuration { - var fs = require("fs"); - var path = require("path"); - var findup = require("findup-sync"); + const fs = require("fs"); + const path = require("path"); + const findup = require("findup-sync"); const CONFIG_FILENAME = "tslint.json"; const DEFAULT_CONFIG = { @@ -45,7 +45,7 @@ module Lint.Configuration { configFile = findup("package.json", { cwd: inputFileLocation, nocase: true }); if (configFile) { - var content = require(configFile); + const content = require(configFile); if (content.tslintConfig) { return content.tslintConfig; @@ -53,13 +53,13 @@ module Lint.Configuration { } // Next look for tslint.json - var homeDir = getHomeDir(); + const homeDir = getHomeDir(); if (!homeDir) { return undefined; } - var defaultPath = path.join(homeDir, CONFIG_FILENAME); + const defaultPath = path.join(homeDir, CONFIG_FILENAME); configFile = findup(CONFIG_FILENAME, { cwd: inputFileLocation, nocase: true }) || defaultPath; @@ -71,13 +71,12 @@ module Lint.Configuration { } function getHomeDir() { - var environment = global.process.env; - var paths = [environment.USERPROFILE, environment.HOME, environment.HOMEPATH, environment.HOMEDRIVE + environment.HOMEPATH]; + const environment = global.process.env; + const paths = [environment.USERPROFILE, environment.HOME, environment.HOMEPATH, environment.HOMEDRIVE + environment.HOMEPATH]; - for (var homeIndex in paths) { + for (const homeIndex in paths) { if (paths.hasOwnProperty(homeIndex)) { - var homePath = paths[homeIndex]; - + const homePath = paths[homeIndex]; if (homePath && fs.existsSync(homePath)) { return homePath; } diff --git a/src/enableDisableRules.ts b/src/enableDisableRules.ts index 5e067d11693..19541581875 100644 --- a/src/enableDisableRules.ts +++ b/src/enableDisableRules.ts @@ -12,16 +12,16 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ module Lint { export class EnableDisableRulesWalker extends Lint.SkippableTokenAwareRuleWalker { public enableDisableRuleMap: {[rulename: string]: Lint.IEnableDisablePosition[]} = {}; - public visitSourceFile(node: ts.SourceFile): void { + public visitSourceFile(node: ts.SourceFile) { super.visitSourceFile(node); Lint.scanAllTokens(ts.createScanner(ts.ScriptTarget.ES5, false, node.text), (scanner: ts.Scanner) => { - var startPos = scanner.getStartPos(); + const startPos = scanner.getStartPos(); if (this.tokensToSkipStartEndMap[startPos] != null) { // tokens to skip are places where the scanner gets confused about what the token is, without the proper context // (specifically, regex, identifiers, and templates). So skip those tokens. @@ -30,25 +30,25 @@ module Lint { } if (scanner.getToken() === ts.SyntaxKind.MultiLineCommentTrivia) { - var commentText = scanner.getTokenText(); - var startPosition = scanner.getTokenPos(); + const commentText = scanner.getTokenText(); + const startPosition = scanner.getTokenPos(); this.handlePossibleTslintSwitch(commentText, startPosition); } }); } private handlePossibleTslintSwitch(commentText: string, startingPosition: number) { - var currentPosition = startingPosition; + const currentPosition = startingPosition; // regex is: start of string followed by "/*" followed by any amount of whitespace followed by "tslint:" if (commentText.match(/^\/\*\s*tslint:/)) { - var commentTextParts = commentText.split(":"); + const commentTextParts = commentText.split(":"); // regex is: start of string followed by either "enable" or "disable" // followed by either whitespace or end of string - var enableOrDisableMatch = commentTextParts[1].match(/^(enable|disable)(\s|$)/); + const enableOrDisableMatch = commentTextParts[1].match(/^(enable|disable)(\s|$)/); if (enableOrDisableMatch != null) { - var isEnabled = enableOrDisableMatch[1] === "enable"; - var position = currentPosition; - var rulesList = ["all"]; + const isEnabled = enableOrDisableMatch[1] === "enable"; + const position = currentPosition; + let rulesList = ["all"]; if (commentTextParts.length > 2) { rulesList = commentTextParts[2].split(/\s+/); } @@ -56,7 +56,10 @@ module Lint { if (!(ruleToAdd in this.enableDisableRuleMap)) { this.enableDisableRuleMap[ruleToAdd] = []; } - this.enableDisableRuleMap[ruleToAdd].push({position: position, isEnabled: isEnabled}); + this.enableDisableRuleMap[ruleToAdd].push({ + isEnabled: isEnabled, + position: position + }); }); } } diff --git a/src/formatterLoader.ts b/src/formatterLoader.ts index f8528ed957d..e4249875398 100644 --- a/src/formatterLoader.ts +++ b/src/formatterLoader.ts @@ -12,25 +12,25 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ module Lint { - var fs = require("fs"); - var path = require("path"); - var _s = require("underscore.string"); + const fs = require("fs"); + const path = require("path"); + const _s = require("underscore.string"); - var moduleDirectory = path.dirname(module.filename); - var CORE_FORMATTERS_DIRECTORY = path.resolve(moduleDirectory, "..", "build", "formatters"); + const moduleDirectory = path.dirname(module.filename); + const CORE_FORMATTERS_DIRECTORY = path.resolve(moduleDirectory, "..", "build", "formatters"); export function findFormatter(name: string, formattersDirectory?: string) { if (typeof(name) === "function") { return name; } - var camelizedName = _s.camelize(name + "Formatter"); + const camelizedName = _s.camelize(name + "Formatter"); // first check for core formatters - var Formatter = loadFormatter(CORE_FORMATTERS_DIRECTORY, camelizedName); + let Formatter = loadFormatter(CORE_FORMATTERS_DIRECTORY, camelizedName); if (Formatter) { return Formatter; } @@ -48,11 +48,11 @@ module Lint { } function loadFormatter(...paths: string[]) { - var formatterPath = paths.reduce((p, c) => path.join(p, c), ""); - var fullPath = path.resolve(moduleDirectory, formatterPath); + const formatterPath = paths.reduce((p, c) => path.join(p, c), ""); + const fullPath = path.resolve(moduleDirectory, formatterPath); if (fs.existsSync(fullPath + ".js")) { - var formatterModule = require(fullPath); + const formatterModule = require(fullPath); return formatterModule.Formatter; } @@ -60,7 +60,7 @@ module Lint { } function loadFormatterModule(name: string) { - var src: string; + let src: string; try { src = require.resolve(name); } catch (e) { diff --git a/src/formatters/jsonFormatter.ts b/src/formatters/jsonFormatter.ts index 28ef8747f12..c8803d63404 100644 --- a/src/formatters/jsonFormatter.ts +++ b/src/formatters/jsonFormatter.ts @@ -12,12 +12,11 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Formatter extends Lint.Formatters.AbstractFormatter { public format(failures: Lint.RuleFailure[]): string { - var failuresJSON = failures.map((failure) => failure.toJson()); - + const failuresJSON = failures.map((failure) => failure.toJson()); return JSON.stringify(failuresJSON); } } diff --git a/src/formatters/pmdFormatter.ts b/src/formatters/pmdFormatter.ts index 372148c4627..7c67b64bae2 100644 --- a/src/formatters/pmdFormatter.ts +++ b/src/formatters/pmdFormatter.ts @@ -12,28 +12,28 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Formatter extends Lint.Formatters.AbstractFormatter { public format(failures: Lint.RuleFailure[]): string { - var output = ""; + let output = ""; - failures.forEach((failure: Lint.RuleFailure) => { - var failureString = failure.getFailure() + for (let failure of failures) { + const failureString = failure.getFailure() .replace(/&/g, "&") .replace(//g, ">") .replace(/\'/g, "'") .replace(/\"/g, """); - var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); + const lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); output += " "; - }); + } output += ""; return output; diff --git a/src/formatters/proseFormatter.ts b/src/formatters/proseFormatter.ts index 2cfb5e9bd96..b4fb3204b41 100644 --- a/src/formatters/proseFormatter.ts +++ b/src/formatters/proseFormatter.ts @@ -12,19 +12,18 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Formatter extends Lint.Formatters.AbstractFormatter { public format(failures: Lint.RuleFailure[]): string { + const outputLines = failures.map((failure: Lint.RuleFailure) => { + const fileName = failure.getFileName(); + const failureString = failure.getFailure(); - var outputLines = failures.map((failure: Lint.RuleFailure) => { - var fileName = failure.getFileName(); - var failureString = failure.getFailure(); + const lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); + const positionTuple = `[${lineAndCharacter.line + 1}, ${lineAndCharacter.character + 1}]`; - var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); - var positionTuple = "[" + (lineAndCharacter.line + 1) + ", " + (lineAndCharacter.character + 1) + "]"; - - return fileName + positionTuple + ": " + failureString; + return `${fileName}${positionTuple}: ${failureString}`; }); return outputLines.join("\n") + "\n"; diff --git a/src/formatters/verboseFormatter.ts b/src/formatters/verboseFormatter.ts index 56e8a1d9963..049b703f62e 100644 --- a/src/formatters/verboseFormatter.ts +++ b/src/formatters/verboseFormatter.ts @@ -17,13 +17,13 @@ export class Formatter extends Lint.Formatters.AbstractFormatter { public format(failures: Lint.RuleFailure[]): string { - var outputLines = failures.map((failure: Lint.RuleFailure) => { - var fileName = failure.getFileName(); - var failureString = failure.getFailure(); - var ruleName = failure.getRuleName(); + const outputLines = failures.map((failure: Lint.RuleFailure) => { + const fileName = failure.getFileName(); + const failureString = failure.getFailure(); + const ruleName = failure.getRuleName(); - var lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); - var positionTuple = "[" + (lineAndCharacter.line + 1) + ", " + (lineAndCharacter.character + 1) + "]"; + const lineAndCharacter = failure.getStartPosition().getLineAndCharacter(); + const positionTuple = "[" + (lineAndCharacter.line + 1) + ", " + (lineAndCharacter.character + 1) + "]"; return "(" + ruleName + ") " + fileName + positionTuple + ": " + failureString; }); diff --git a/src/language/formatter/abstractFormatter.ts b/src/language/formatter/abstractFormatter.ts index fa021608daa..cc5c65bf4d9 100644 --- a/src/language/formatter/abstractFormatter.ts +++ b/src/language/formatter/abstractFormatter.ts @@ -16,10 +16,8 @@ module Lint.Formatters { export class AbstractFormatter implements Lint.IFormatter { - /* tslint:disable:no-unused-variable */ public format(failures: Lint.RuleFailure[]): string { throw Lint.abstract(); } - /* tslint:enable:no-unused-variable */ } } diff --git a/src/language/languageServiceHost.ts b/src/language/languageServiceHost.ts index 807a7157010..c4deecbc191 100644 --- a/src/language/languageServiceHost.ts +++ b/src/language/languageServiceHost.ts @@ -14,25 +14,23 @@ * limitations under the License. */ -/* tslint:disable:no-unused-variable */ - module Lint { export function createLanguageServiceHost(fileName: string, source: string) { - var host: ts.LanguageServiceHost = { + const host: ts.LanguageServiceHost = { + getCompilationSettings: () => Lint.createCompilerOptions(), + getCurrentDirectory: () => "", + getDefaultLibFileName: () => "lib.d.ts", getScriptFileNames: () => [fileName], - getScriptVersion: () => "1", + getScriptIsOpen: () => true, getScriptSnapshot: () => { return { - getText: (start, end) => source.substring(start, end), + getChangeRange: (oldSnapshot) => undefined, getLength: () => source.length, getLineStartPositions: () => ts.computeLineStarts(source), - getChangeRange: (oldSnapshot) => undefined + getText: (start, end) => source.substring(start, end) }; }, - getCurrentDirectory: () => "", - getScriptIsOpen: () => true, - getCompilationSettings: () => Lint.createCompilerOptions(), - getDefaultLibFileName: () => "lib.d.ts", + getScriptVersion: () => "1", log: (message) => { /* */ } }; diff --git a/src/language/rule/abstractRule.ts b/src/language/rule/abstractRule.ts index 7f9b0a23867..cfb9527679b 100644 --- a/src/language/rule/abstractRule.ts +++ b/src/language/rule/abstractRule.ts @@ -20,7 +20,7 @@ module Lint.Rules { private options: Lint.IOptions; constructor(ruleName: string, value: any, disabledIntervals: Lint.IDisabledInterval[]) { - var ruleArguments: any[] = []; + let ruleArguments: any[] = []; if (Array.isArray(value) && value.length > 1) { ruleArguments = value.slice(1); @@ -28,9 +28,9 @@ module Lint.Rules { this.value = value; this.options = { + disabledIntervals: disabledIntervals, ruleArguments: ruleArguments, - ruleName: ruleName, - disabledIntervals: disabledIntervals + ruleName: ruleName }; } @@ -50,7 +50,7 @@ module Lint.Rules { } public isEnabled(): boolean { - var value = this.value; + const value = this.value; if (typeof value === "boolean") { return value; @@ -63,5 +63,4 @@ module Lint.Rules { return false; } } - } diff --git a/src/language/rule/rule.ts b/src/language/rule/rule.ts index a047f0d6eb2..5d7a1674a71 100644 --- a/src/language/rule/rule.ts +++ b/src/language/rule/rule.ts @@ -28,11 +28,8 @@ module Lint { export interface IRule { getOptions(): IOptions; - isEnabled(): boolean; - apply(sourceFile: ts.SourceFile): RuleFailure[]; - applyWithWalker(walker: Lint.RuleWalker): RuleFailure[]; } @@ -55,19 +52,19 @@ module Lint { public toJson() { return { - position: this.position, + character: this.lineAndCharacter.character, line: this.lineAndCharacter.line, - character: this.lineAndCharacter.character + position: this.position }; } public equals(ruleFailurePosition: RuleFailurePosition) { - var ll = this.lineAndCharacter; - var rr = ruleFailurePosition.lineAndCharacter; + const ll = this.lineAndCharacter; + const rr = ruleFailurePosition.lineAndCharacter; - return (this.position === ruleFailurePosition.position && - ll.line === rr.line && - ll.character === rr.character); + return this.position === ruleFailurePosition.position + && ll.line === rr.line + && ll.character === rr.character; } } @@ -101,11 +98,11 @@ module Lint { return this.ruleName; } - public getStartPosition(): Lint.RuleFailurePosition { + public getStartPosition(): RuleFailurePosition { return this.startPosition; } - public getEndPosition(): Lint.RuleFailurePosition { + public getEndPosition(): RuleFailurePosition { return this.endPosition; } @@ -115,26 +112,24 @@ module Lint { public toJson(): any { return { - name: this.fileName, - failure: this.failure, - startPosition: this.startPosition.toJson(), endPosition: this.endPosition.toJson(), - ruleName: this.ruleName + failure: this.failure, + name: this.fileName, + ruleName: this.ruleName, + startPosition: this.startPosition.toJson() }; } - public equals(ruleFailure: RuleFailure): boolean { - return (this.failure === ruleFailure.getFailure() && - this.fileName === ruleFailure.getFileName() && - this.startPosition.equals(ruleFailure.getStartPosition()) && - this.endPosition.equals(ruleFailure.getEndPosition())); + public equals(ruleFailure: RuleFailure) { + return this.failure === ruleFailure.getFailure() + && this.fileName === ruleFailure.getFileName() + && this.startPosition.equals(ruleFailure.getStartPosition()) + && this.endPosition.equals(ruleFailure.getEndPosition()); } - private createFailurePosition(position: number): RuleFailurePosition { - var lineAndCharacter = this.sourceFile.getLineAndCharacterOfPosition(position); - var failurePosition = new RuleFailurePosition(position, lineAndCharacter); - return failurePosition; + private createFailurePosition(position: number) { + const lineAndCharacter = this.sourceFile.getLineAndCharacterOfPosition(position); + return new RuleFailurePosition(position, lineAndCharacter); } } - } diff --git a/src/language/utils.ts b/src/language/utils.ts index 7b184342f9a..eb667ade311 100644 --- a/src/language/utils.ts +++ b/src/language/utils.ts @@ -15,27 +15,27 @@ */ module Lint { - var path = require("path"); + const path = require("path"); export function getSourceFile(fileName: string, source: string): ts.SourceFile { - var normalizedName = path.normalize(fileName).replace(/\\/g, "/"); - var compilerOptions = createCompilerOptions(); + const normalizedName = path.normalize(fileName).replace(/\\/g, "/"); + const compilerOptions = createCompilerOptions(); - var compilerHost = { + const compilerHost = { + getCanonicalFileName: (filename: string) => filename, + getCurrentDirectory: () => "", + getDefaultLibFileName: () => "lib.d.ts", + getNewLine: () => "\n", getSourceFile: function (filenameToGet: string) { if (filenameToGet === normalizedName) { return ts.createSourceFile(filenameToGet, source, compilerOptions.target, true); } }, - writeFile: () => null, - getDefaultLibFileName: () => "lib.d.ts", useCaseSensitiveFileNames: () => true, - getCanonicalFileName: (filename: string) => filename, - getCurrentDirectory: () => "", - getNewLine: () => "\n" + writeFile: () => null }; - var program = ts.createProgram([normalizedName], compilerOptions, compilerHost); + const program = ts.createProgram([normalizedName], compilerOptions, compilerHost); return program.getSourceFile(normalizedName); } @@ -48,17 +48,11 @@ module Lint { } export function doesIntersect(failure: RuleFailure, disabledIntervals: Lint.IDisabledInterval[]) { - var intersectionExists = false; - - disabledIntervals.forEach((disabledInterval) => { - var maxStart = Math.max(disabledInterval.startPosition, failure.getStartPosition().getPosition()); - var minEnd = Math.min(disabledInterval.endPosition, failure.getEndPosition().getPosition()); - if (maxStart <= minEnd) { - // intervals intersect - intersectionExists = true; - } + return disabledIntervals.some((interval) => { + const maxStart = Math.max(interval.startPosition, failure.getStartPosition().getPosition()); + const minEnd = Math.min(interval.endPosition, failure.getEndPosition().getPosition()); + return maxStart <= minEnd; }); - return intersectionExists; } export function abstract() { @@ -66,9 +60,9 @@ module Lint { } export function scanAllTokens(scanner: ts.Scanner, callback: (scanner: ts.Scanner) => void) { - var lastStartPos = -1; + let lastStartPos = -1; while (scanner.scan() !== ts.SyntaxKind.EndOfFileToken) { - var startPos = scanner.getStartPos(); + const startPos = scanner.getStartPos(); if (startPos === lastStartPos) { break; } diff --git a/src/language/walker/blockScopeAwareRuleWalker.ts b/src/language/walker/blockScopeAwareRuleWalker.ts index b2ee7a12b89..688a7ae2ed1 100644 --- a/src/language/walker/blockScopeAwareRuleWalker.ts +++ b/src/language/walker/blockScopeAwareRuleWalker.ts @@ -38,7 +38,7 @@ module Lint { } // callback notifier when a block scope begins - public onBlockScopeStart(): void { + public onBlockScopeStart() { return; } @@ -47,12 +47,12 @@ module Lint { } // callback notifier when a block scope ends - public onBlockScopeEnd(): void { + public onBlockScopeEnd() { return; } - protected visitNode(node: ts.Node): void { - var isNewBlockScope = this.isBlockScopeBoundary(node); + protected visitNode(node: ts.Node) { + const isNewBlockScope = this.isBlockScopeBoundary(node); if (isNewBlockScope) { this.blockScopeStack.push(this.createBlockScope()); diff --git a/src/language/walker/ruleWalker.ts b/src/language/walker/ruleWalker.ts index 9c6ba53d1bb..45a6cefd601 100644 --- a/src/language/walker/ruleWalker.ts +++ b/src/language/walker/ruleWalker.ts @@ -44,28 +44,10 @@ module Lint { return this.failures; } - /* - public getPosition() { - return this.position; - } - */ - public getLimit() { return this.limit; } - /* - public positionAfter(...nodes: ts.Node[]): number { - var position = this.getPosition(); - nodes.forEach((node) => { - if (node !== null) { - position += node.getFullWidth(); - } - }); - return position; - } - */ - public getOptions(): any { return this.options; } @@ -82,29 +64,21 @@ module Lint { this.position += node.getFullWidth(); } - // create a failure at the given position - public createFailure(start: number, width: number, failure: string): Lint.RuleFailure { - var from = (start > this.limit) ? this.limit : start; - var to = ((start + width) > this.limit) ? this.limit : (start + width); - + public createFailure(start: number, width: number, failure: string): RuleFailure { + const from = (start > this.limit) ? this.limit : start; + const to = ((start + width) > this.limit) ? this.limit : (start + width); return new Lint.RuleFailure(this.sourceFile, from, to, failure, this.ruleName); } public addFailure(failure: RuleFailure) { - if (!this.existsFailure(failure)) { - // don't add failures for a rule if the failure intersects an interval where that rule is disabled - if (!Lint.doesIntersect(failure, this.disabledIntervals)) { - this.failures.push(failure); - } + // don't add failures for a rule if the failure intersects an interval where that rule is disabled + if (!this.existsFailure(failure) && !Lint.doesIntersect(failure, this.disabledIntervals)) { + this.failures.push(failure); } } private existsFailure(failure: RuleFailure) { - var filteredFailures = this.failures.filter(function(f) { - return f.equals(failure); - }); - - return (filteredFailures.length > 0); + return this.failures.some((f) => f.equals(failure)); } } diff --git a/src/language/walker/scopeAwareRuleWalker.ts b/src/language/walker/scopeAwareRuleWalker.ts index b288fd2b459..a544e5bef5f 100644 --- a/src/language/walker/scopeAwareRuleWalker.ts +++ b/src/language/walker/scopeAwareRuleWalker.ts @@ -43,17 +43,17 @@ module Lint { } // callback notifier when a scope begins - public onScopeStart(): void { + public onScopeStart() { return; } // callback notifier when a scope ends - public onScopeEnd(): void { + public onScopeEnd() { return; } - protected visitNode(node: ts.Node): void { - var isNewScope = this.isScopeBoundary(node); + protected visitNode(node: ts.Node) { + const isNewScope = this.isScopeBoundary(node); if (isNewScope) { this.scopeStack.push(this.createScope()); diff --git a/src/ruleLoader.ts b/src/ruleLoader.ts index 1b84dc68387..2772e546e17 100644 --- a/src/ruleLoader.ts +++ b/src/ruleLoader.ts @@ -12,15 +12,15 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ module Lint { - var fs = require("fs"); - var path = require("path"); - var _s = require("underscore.string"); + const fs = require("fs"); + const path = require("path"); + const _s = require("underscore.string"); - var moduleDirectory = path.dirname(module.filename); - var CORE_RULES_DIRECTORY = path.resolve(moduleDirectory, "..", "build", "rules"); + const moduleDirectory = path.dirname(module.filename); + const CORE_RULES_DIRECTORY = path.resolve(moduleDirectory, "..", "build", "rules"); export interface IEnableDisablePosition { isEnabled: boolean; @@ -30,16 +30,16 @@ module Lint { export function loadRules(ruleConfiguration: {[name: string]: any}, enableDisableRuleMap: {[rulename: string]: Lint.IEnableDisablePosition[]}, rulesDirectory?: string): IRule[] { - var rules: IRule[] = []; - for (var ruleName in ruleConfiguration) { + const rules: IRule[] = []; + for (const ruleName in ruleConfiguration) { if (ruleConfiguration.hasOwnProperty(ruleName)) { - var ruleValue = ruleConfiguration[ruleName]; - var Rule = findRule(ruleName, rulesDirectory); + const ruleValue = ruleConfiguration[ruleName]; + const Rule = findRule(ruleName, rulesDirectory); if (Rule !== undefined) { - var all = "all"; // make the linter happy until we can turn it on and off - var allList = (all in enableDisableRuleMap ? enableDisableRuleMap[all] : []); - var ruleSpecificList = (ruleName in enableDisableRuleMap ? enableDisableRuleMap[ruleName] : []); - var disabledIntervals = buildDisabledIntervalsFromSwitches(ruleSpecificList, allList); + const all = "all"; // make the linter happy until we can turn it on and off + const allList = (all in enableDisableRuleMap ? enableDisableRuleMap[all] : []); + const ruleSpecificList = (ruleName in enableDisableRuleMap ? enableDisableRuleMap[ruleName] : []); + const disabledIntervals = buildDisabledIntervalsFromSwitches(ruleSpecificList, allList); rules.push(new Rule(ruleName, ruleValue, disabledIntervals)); } } @@ -49,10 +49,10 @@ module Lint { } export function findRule(name: string, rulesDirectory?: string) { - var camelizedName = transformName(name); + let camelizedName = transformName(name); // first check for core rules - var Rule = loadRule(CORE_RULES_DIRECTORY, camelizedName); + let Rule = loadRule(CORE_RULES_DIRECTORY, camelizedName); if (Rule) { return Rule; } @@ -68,8 +68,8 @@ module Lint { // finally check for rules within the first level of directories, // using dash prefixes as the sub-directory names if (rulesDirectory) { - var subDirectory = _s.strLeft(rulesDirectory, "-"); - var ruleName = _s.strRight(rulesDirectory, "-"); + const subDirectory = _s.strLeft(rulesDirectory, "-"); + const ruleName = _s.strRight(rulesDirectory, "-"); if (subDirectory !== rulesDirectory && ruleName !== rulesDirectory) { camelizedName = transformName(ruleName); Rule = loadRule(rulesDirectory, subDirectory, camelizedName); @@ -85,7 +85,7 @@ module Lint { function transformName(name: string) { // camelize strips out leading and trailing underscores and dashes, so make sure they aren't passed to camelize // the regex matches the groups (leading underscores and dashes)(other characters)(trailing underscores and dashes) - var nameMatch = name.match(/^([-_]*)(.*?)([-_]*)$/); + const nameMatch = name.match(/^([-_]*)(.*?)([-_]*)$/); if (nameMatch == null) { return name + "Rule"; } @@ -93,11 +93,11 @@ module Lint { } function loadRule(...paths: string[]) { - var rulePath = paths.reduce((p, c) => path.join(p, c), ""); - var fullPath = path.resolve(moduleDirectory, rulePath); + const rulePath = paths.reduce((p, c) => path.join(p, c), ""); + const fullPath = path.resolve(moduleDirectory, rulePath); if (fs.existsSync(fullPath + ".js")) { - var ruleModule = require(fullPath); + const ruleModule = require(fullPath); if (ruleModule && ruleModule.Rule) { return ruleModule.Rule; } @@ -107,20 +107,20 @@ module Lint { } /* - * we're assuming both lists are already sorted top-down - * so compare the tops, use the smallest of the two, and build the intervals that way + * We're assuming both lists are already sorted top-down so compare the tops, use the smallest of the two, + * and build the intervals that way. */ function buildDisabledIntervalsFromSwitches(ruleSpecificList: IEnableDisablePosition[], allList: IEnableDisablePosition[]) { + let isCurrentlyDisabled = false; + let disabledStartPosition: number; + const disabledIntervalList: Lint.IDisabledInterval[] = []; + let i = 0; + let j = 0; - var isCurrentlyDisabled = false; - var disabledStartPosition: number; - var disabledIntervalList: Lint.IDisabledInterval[] = []; - var i = 0; - var j = 0; while (i < ruleSpecificList.length || j < allList.length) { - var ruleSpecificTopPositon = (i < ruleSpecificList.length ? ruleSpecificList[i].position : Infinity); - var allTopPositon = (j < allList.length ? allList[j].position : Infinity); - var newPositionToCheck: IEnableDisablePosition; + const ruleSpecificTopPositon = (i < ruleSpecificList.length ? ruleSpecificList[i].position : Infinity); + const allTopPositon = (j < allList.length ? allList[j].position : Infinity); + let newPositionToCheck: IEnableDisablePosition; if (ruleSpecificTopPositon < allTopPositon) { newPositionToCheck = ruleSpecificList[i]; i++; @@ -137,16 +137,21 @@ module Lint { isCurrentlyDisabled = true; } else { // we're currently disabled and about to enable -- end the interval - disabledIntervalList.push({startPosition: disabledStartPosition, endPosition: newPositionToCheck.position}); + disabledIntervalList.push({ + endPosition: newPositionToCheck.position, + startPosition: disabledStartPosition + }); isCurrentlyDisabled = false; } } - } if (isCurrentlyDisabled) { // we started an interval but didn't finish one -- so finish it with an Infinity - disabledIntervalList.push({startPosition: disabledStartPosition, endPosition: Infinity}); + disabledIntervalList.push({ + endPosition: Infinity, + startPosition: disabledStartPosition + }); } return disabledIntervalList; diff --git a/src/rules/alignRule.ts b/src/rules/alignRule.ts index 775f850e56c..d77d6cf0d43 100644 --- a/src/rules/alignRule.ts +++ b/src/rules/alignRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static PARAMETERS_OPTION = "parameters"; @@ -22,7 +22,7 @@ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING_SUFFIX = " are not aligned"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var alignWalker = new AlignWalker(sourceFile, this.getOptions()); + const alignWalker = new AlignWalker(sourceFile, this.getOptions()); return this.applyWithWalker(alignWalker); } } @@ -62,16 +62,16 @@ class AlignWalker extends Lint.RuleWalker { if (nodes.length === 0 || !this.hasOption(kind)) { return; } - var prevPos = this.getPosition(nodes[0]); - var alignToColumn = prevPos.character; - for (var index = 1; index < nodes.length; index++) { - var node = nodes[index]; - var curPos = this.getPosition(node); + + let prevPos = this.getPosition(nodes[0]); + const alignToColumn = prevPos.character; + + // skip first node in list + for (let node of nodes.slice(1)) { + const curPos = this.getPosition(node); if (curPos.line !== prevPos.line && curPos.character !== alignToColumn) { - this.addFailure(this.createFailure(node.getStart(), - node.getWidth(), - kind + Rule.FAILURE_STRING_SUFFIX)); - break; // exit loop. + this.addFailure(this.createFailure(node.getStart(), node.getWidth(), kind + Rule.FAILURE_STRING_SUFFIX)); + break; } prevPos = curPos; } diff --git a/src/rules/banRule.ts b/src/rules/banRule.ts index 851d9fcbaa1..811427b5010 100644 --- a/src/rules/banRule.ts +++ b/src/rules/banRule.ts @@ -12,15 +12,15 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING_PART = "function invocation disallowed: "; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var options = this.getOptions(); - var banFunctionWalker = new BanFunctionWalker(sourceFile, options); - var functionsToBan = options.ruleArguments; + const options = this.getOptions(); + const banFunctionWalker = new BanFunctionWalker(sourceFile, options); + const functionsToBan = options.ruleArguments; functionsToBan.forEach((functionToBan) => { banFunctionWalker.addBannedFunction(functionToBan); }); @@ -35,23 +35,23 @@ export class BanFunctionWalker extends Lint.RuleWalker { this.bannedFunctions.push(bannedFunction); } - public visitCallExpression(node: ts.CallExpression): void { - var expression = node.expression; + public visitCallExpression(node: ts.CallExpression) { + const expression = node.expression; if (expression.kind === ts.SyntaxKind.PropertyAccessExpression && expression.getChildCount() >= 3) { - var firstToken = expression.getFirstToken(); - var secondToken = expression.getChildAt(1); - var thirdToken = expression.getChildAt(2); + const firstToken = expression.getFirstToken(); + const secondToken = expression.getChildAt(1); + const thirdToken = expression.getChildAt(2); - var firstText = firstToken.getText(); - var thirdText = thirdToken.getFullText(); + const firstText = firstToken.getText(); + const thirdText = thirdToken.getFullText(); if (secondToken.kind === ts.SyntaxKind.DotToken) { this.bannedFunctions.forEach((bannedFunction) => { if (firstText === bannedFunction[0] && thirdText === bannedFunction[1]) { - var failure = this.createFailure(expression.getStart(), + const failure = this.createFailure(expression.getStart(), expression.getWidth(), Rule.FAILURE_STRING_PART + firstText + "." + thirdText); this.addFailure(failure); diff --git a/src/rules/classNameRule.ts b/src/rules/classNameRule.ts index c6621a88152..ca2d011495b 100644 --- a/src/rules/classNameRule.ts +++ b/src/rules/classNameRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { static FAILURE_STRING = "name must be in pascal case"; @@ -23,8 +23,8 @@ export class Rule extends Lint.Rules.AbstractRule { } class NameWalker extends Lint.RuleWalker { - public visitClassDeclaration(node: ts.ClassDeclaration): void { - var className = node.name.getText(); + public visitClassDeclaration(node: ts.ClassDeclaration) { + const className = node.name.getText(); if (!this.isPascalCased(className)) { this.addFailureAt(node.name.getStart(), node.name.getWidth()); } @@ -32,8 +32,8 @@ class NameWalker extends Lint.RuleWalker { super.visitClassDeclaration(node); } - public visitInterfaceDeclaration(node: ts.InterfaceDeclaration): void { - var interfaceName = node.name.getText(); + public visitInterfaceDeclaration(node: ts.InterfaceDeclaration) { + const interfaceName = node.name.getText(); if (!this.isPascalCased(interfaceName)) { this.addFailureAt(node.name.getStart(), node.name.getWidth()); } @@ -46,13 +46,12 @@ class NameWalker extends Lint.RuleWalker { return true; } - var firstCharacter = name.charAt(0); + const firstCharacter = name.charAt(0); return ((firstCharacter === firstCharacter.toUpperCase()) && name.indexOf("_") === -1); } private addFailureAt(position: number, width: number) { - var failure = this.createFailure(position, width, Rule.FAILURE_STRING); + const failure = this.createFailure(position, width, Rule.FAILURE_STRING); this.addFailure(failure); } - } diff --git a/src/rules/commentFormatRule.ts b/src/rules/commentFormatRule.ts index 73cfc23eb3a..cf46913e6c8 100644 --- a/src/rules/commentFormatRule.ts +++ b/src/rules/commentFormatRule.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -var OPTION_SPACE = "check-space"; -var OPTION_LOWERCASE = "check-lowercase"; -var OPTION_UPPERCASE = "check-uppercase"; +const OPTION_SPACE = "check-space"; +const OPTION_LOWERCASE = "check-lowercase"; +const OPTION_UPPERCASE = "check-uppercase"; export class Rule extends Lint.Rules.AbstractRule { static LOWERCASE_FAILURE = "comment must start with lowercase letter"; @@ -29,10 +29,10 @@ export class Rule extends Lint.Rules.AbstractRule { } class CommentWalker extends Lint.SkippableTokenAwareRuleWalker { - public visitSourceFile(node: ts.SourceFile): void { + public visitSourceFile(node: ts.SourceFile) { super.visitSourceFile(node); Lint.scanAllTokens(ts.createScanner(ts.ScriptTarget.ES5, false, node.text), (scanner: ts.Scanner) => { - var startPos = scanner.getStartPos(); + const startPos = scanner.getStartPos(); if (this.tokensToSkipStartEndMap[startPos] != null) { // tokens to skip are places where the scanner gets confused about what the token is, without the proper context // (specifically, regex, identifiers, and templates). So skip those tokens. @@ -41,24 +41,24 @@ class CommentWalker extends Lint.SkippableTokenAwareRuleWalker { } if (scanner.getToken() === ts.SyntaxKind.SingleLineCommentTrivia) { - var commentText = scanner.getTokenText(); - var startPosition = scanner.getTokenPos() + 2; - var width = commentText.length - 2; + const commentText = scanner.getTokenText(); + const startPosition = scanner.getTokenPos() + 2; + const width = commentText.length - 2; if (this.hasOption(OPTION_SPACE)) { if (!this.startsWithSpace(commentText)) { - var leadingSpaceFailure = this.createFailure(startPosition, width, Rule.LEADING_SPACE_FAILURE); + const leadingSpaceFailure = this.createFailure(startPosition, width, Rule.LEADING_SPACE_FAILURE); this.addFailure(leadingSpaceFailure); } } if (this.hasOption(OPTION_LOWERCASE)) { if (!this.startsWithLowercase(commentText)) { - var lowercaseFailure = this.createFailure(startPosition, width, Rule.LOWERCASE_FAILURE); + const lowercaseFailure = this.createFailure(startPosition, width, Rule.LOWERCASE_FAILURE); this.addFailure(lowercaseFailure); } } if (this.hasOption(OPTION_UPPERCASE)) { if (!this.startsWithUppercase(commentText)) { - var uppercaseFailure = this.createFailure(startPosition, width, Rule.UPPERCASE_FAILURE); + const uppercaseFailure = this.createFailure(startPosition, width, Rule.UPPERCASE_FAILURE); this.addFailure(uppercaseFailure); } } @@ -76,7 +76,7 @@ class CommentWalker extends Lint.SkippableTokenAwareRuleWalker { return true; } - var firstCharacter = commentText.charAt(2); // first character after the space + const firstCharacter = commentText.charAt(2); // first character after the space // three slashes (///) also works, to allow for /// return firstCharacter === " " || firstCharacter === "/"; } @@ -95,10 +95,10 @@ class CommentWalker extends Lint.SkippableTokenAwareRuleWalker { } // regex is "start of string"//"any amount of whitespace"("word character") - var firstCharacterMatch = commentText.match(/^\/\/\s*(\w)/); + const firstCharacterMatch = commentText.match(/^\/\/\s*(\w)/); if (firstCharacterMatch != null) { // the first group matched, i.e. the thing in the parens, is the first non-space character, if it's alphanumeric - var firstCharacter = firstCharacterMatch[1]; + const firstCharacter = firstCharacterMatch[1]; return firstCharacter === changeCase(firstCharacter); } else { // first character isn't alphanumeric/doesn't exist? Technically not a violation diff --git a/src/rules/curlyRule.ts b/src/rules/curlyRule.ts index 89ae85fc3cd..68d8a156718 100644 --- a/src/rules/curlyRule.ts +++ b/src/rules/curlyRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static DO_FAILURE_STRING = "do statements must be braced"; @@ -27,7 +27,7 @@ export class Rule extends Lint.Rules.AbstractRule { } class CurlyWalker extends Lint.RuleWalker { - public visitForInStatement(node: ts.ForInStatement): void { + public visitForInStatement(node: ts.ForInStatement) { if (!this.isStatementBraced(node.statement)) { this.addFailureForNode(node, Rule.FOR_FAILURE_STRING); } @@ -35,7 +35,7 @@ class CurlyWalker extends Lint.RuleWalker { super.visitForInStatement(node); } - public visitForOfStatement(node: ts.ForInStatement): void { + public visitForOfStatement(node: ts.ForInStatement) { if (!this.isStatementBraced(node.statement)) { this.addFailureForNode(node, Rule.FOR_FAILURE_STRING); } @@ -43,7 +43,7 @@ class CurlyWalker extends Lint.RuleWalker { super.visitForInStatement(node); } - public visitForStatement(node: ts.ForStatement): void { + public visitForStatement(node: ts.ForStatement) { if (!this.isStatementBraced(node.statement)) { this.addFailureForNode(node, Rule.FOR_FAILURE_STRING); } @@ -51,26 +51,29 @@ class CurlyWalker extends Lint.RuleWalker { super.visitForStatement(node); } - public visitIfStatement(node: ts.IfStatement): void { + public visitIfStatement(node: ts.IfStatement) { if (!this.isStatementBraced(node.thenStatement)) { this.addFailure(this.createFailure(node.getStart(), node.thenStatement.getEnd() - node.getStart(), Rule.IF_FAILURE_STRING)); } + if (node.elseStatement != null - && node.elseStatement.kind !== ts.SyntaxKind.IfStatement - && !this.isStatementBraced(node.elseStatement)) { + && node.elseStatement.kind !== ts.SyntaxKind.IfStatement + && !this.isStatementBraced(node.elseStatement)) { // find the else keyword to place the error appropriately - var elseKeywordNode = node.getChildren().filter((child) => child.kind === ts.SyntaxKind.ElseKeyword)[0]; + const elseKeywordNode = node.getChildren().filter((child) => child.kind === ts.SyntaxKind.ElseKeyword)[0]; - this.addFailure(this.createFailure(elseKeywordNode.getStart(), + this.addFailure( + this.createFailure(elseKeywordNode.getStart(), node.elseStatement.getEnd() - elseKeywordNode.getStart(), - Rule.ELSE_FAILURE_STRING)); + Rule.ELSE_FAILURE_STRING) + ); } super.visitIfStatement(node); } - public visitDoStatement(node: ts.DoStatement): void { + public visitDoStatement(node: ts.DoStatement) { if (!this.isStatementBraced(node.statement)) { this.addFailureForNode(node, Rule.DO_FAILURE_STRING); } @@ -78,7 +81,7 @@ class CurlyWalker extends Lint.RuleWalker { super.visitDoStatement(node); } - public visitWhileStatement(node: ts.WhileStatement): void { + public visitWhileStatement(node: ts.WhileStatement) { if (!this.isStatementBraced(node.statement)) { this.addFailureForNode(node, Rule.WHILE_FAILURE_STRING); } @@ -86,11 +89,8 @@ class CurlyWalker extends Lint.RuleWalker { super.visitWhileStatement(node); } - private isStatementBraced(node: ts.Statement): boolean { - if (node.kind === ts.SyntaxKind.Block) { - return true; - } - return false; + private isStatementBraced(node: ts.Statement) { + return node.kind === ts.SyntaxKind.Block; } private addFailureForNode(node: ts.Node, failure: string) { diff --git a/src/rules/eoflineRule.ts b/src/rules/eoflineRule.ts index 732dec9e0f3..1df213e7197 100644 --- a/src/rules/eoflineRule.ts +++ b/src/rules/eoflineRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "file should end with a newline"; @@ -22,12 +22,14 @@ export class Rule extends Lint.Rules.AbstractRule { // if the file is empty, it "ends with a newline", so don't return a failure return []; } - var eofToken = sourceFile.endOfFileToken; - var eofTokenFullText = eofToken.getFullText(); + + const eofToken = sourceFile.endOfFileToken; + const eofTokenFullText = eofToken.getFullText(); if (eofTokenFullText.length === 0 || eofTokenFullText.charAt(eofTokenFullText.length - 1) !== "\n") { - var start = eofToken.getStart(); - var failure = new Lint.RuleFailure(sourceFile, start, start, Rule.FAILURE_STRING, this.getOptions().ruleName); - return [failure]; + const start = eofToken.getStart(); + return [ + new Lint.RuleFailure(sourceFile, start, start, Rule.FAILURE_STRING, this.getOptions().ruleName) + ]; } return []; diff --git a/src/rules/forinRule.ts b/src/rules/forinRule.ts index 46434dadf72..e13518cb8a0 100644 --- a/src/rules/forinRule.ts +++ b/src/rules/forinRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "for (... in ...) statements must be filtered with an if statement"; @@ -23,14 +23,14 @@ export class Rule extends Lint.Rules.AbstractRule { } class ForInWalker extends Lint.RuleWalker { - public visitForInStatement(node: ts.ForInStatement): void { + public visitForInStatement(node: ts.ForInStatement) { this.handleForInStatement(node); super.visitForInStatement(node); } private handleForInStatement(node: ts.ForInStatement) { - var statement = node.statement; - var statementKind = node.statement.kind; + const statement = node.statement; + const statementKind = node.statement.kind; // a direct if statement under a for...in is valid if (statementKind === ts.SyntaxKind.IfStatement) { @@ -39,10 +39,10 @@ class ForInWalker extends Lint.RuleWalker { // if there is a block, verify that it has a single if statement or starts with if (..) continue; if (statementKind === ts.SyntaxKind.Block) { - var blockNode = statement; - var blockStatements = blockNode.statements; + const blockNode = statement; + const blockStatements = blockNode.statements; if (blockStatements.length >= 1) { - var firstBlockStatement = blockStatements[0]; + const firstBlockStatement = blockStatements[0]; if (firstBlockStatement.kind === ts.SyntaxKind.IfStatement) { // if this "if" statement is the only statement within the block if (blockStatements.length === 1) { @@ -50,29 +50,28 @@ class ForInWalker extends Lint.RuleWalker { } // if this "if" statement has a single continue block - var ifStatement = ( firstBlockStatement).thenStatement; - if (this.nodeIsContinue(ifStatement)) { + const ifStatement = ( firstBlockStatement).thenStatement; + if (ForInWalker.nodeIsContinue(ifStatement)) { return; } } } } - var failure = this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING); + const failure = this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING); this.addFailure(failure); } - private nodeIsContinue(node: ts.Node): boolean { - var kind = node.kind; + private static nodeIsContinue(node: ts.Node) { + const kind = node.kind; if (kind === ts.SyntaxKind.ContinueStatement) { return true; } if (kind === ts.SyntaxKind.Block) { - var blockStatements = (node).statements; - if (blockStatements.length === 1 && - blockStatements[0].kind === ts.SyntaxKind.ContinueStatement) { + const blockStatements = ( node).statements; + if (blockStatements.length === 1 && blockStatements[0].kind === ts.SyntaxKind.ContinueStatement) { return true; } } diff --git a/src/rules/indentRule.ts b/src/rules/indentRule.ts index b9773bbc1be..ca58475836d 100644 --- a/src/rules/indentRule.ts +++ b/src/rules/indentRule.ts @@ -12,10 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ -var OPTION_USE_TABS = "tabs"; -var OPTION_USE_SPACES = "spaces"; +const OPTION_USE_TABS = "tabs"; +const OPTION_USE_SPACES = "spaces"; export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING_TABS = "tab indentation expected"; @@ -43,20 +43,22 @@ class IndentWalker extends Lint.RuleWalker { } } - public visitSourceFile(node: ts.SourceFile): void { + public visitSourceFile(node: ts.SourceFile) { if (!this.hasOption(OPTION_USE_TABS) && !this.hasOption(OPTION_USE_SPACES)) { // if we don't have either option, no need to check anything, and no need to call super, so just return return; } - var scanner = ts.createScanner(ts.ScriptTarget.ES5, false, node.text); - var lineStarts = node.getLineStarts(); - lineStarts.forEach((lineStart) => { + + const scanner = ts.createScanner(ts.ScriptTarget.ES5, false, node.text); + for (let lineStart of node.getLineStarts()) { scanner.setTextPos(lineStart); - var currentScannedType = scanner.scan(); - var fullLeadingWhitespace = ""; - var lastStartPos = -1; + + let currentScannedType = scanner.scan(); + let fullLeadingWhitespace = ""; + let lastStartPos = -1; + while (currentScannedType === ts.SyntaxKind.WhitespaceTrivia) { - var startPos = scanner.getStartPos(); + const startPos = scanner.getStartPos(); if (startPos === lastStartPos) { break; } @@ -66,19 +68,17 @@ class IndentWalker extends Lint.RuleWalker { currentScannedType = scanner.scan(); } - if (currentScannedType === ts.SyntaxKind.SingleLineCommentTrivia || - currentScannedType === ts.SyntaxKind.MultiLineCommentTrivia || - currentScannedType === ts.SyntaxKind.NewLineTrivia) { - + if (currentScannedType === ts.SyntaxKind.SingleLineCommentTrivia + || currentScannedType === ts.SyntaxKind.MultiLineCommentTrivia + || currentScannedType === ts.SyntaxKind.NewLineTrivia) { // ignore lines that have comments before the first token - - return; + continue; } if (fullLeadingWhitespace.match(this.regExp)) { this.addFailure(this.createFailure(lineStart, fullLeadingWhitespace.length, this.failureString)); } - }); + } // no need to call super to visit the rest of the nodes, so don't call super here } } diff --git a/src/rules/interfaceNameRule.ts b/src/rules/interfaceNameRule.ts index 171f50bfbc5..4116f53f249 100644 --- a/src/rules/interfaceNameRule.ts +++ b/src/rules/interfaceNameRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { static FAILURE_STRING = "interface name must be a capitalized I"; @@ -23,8 +23,8 @@ export class Rule extends Lint.Rules.AbstractRule { } class NameWalker extends Lint.RuleWalker { - public visitInterfaceDeclaration(node: ts.InterfaceDeclaration): void { - var interfaceName = node.name.text; + public visitInterfaceDeclaration(node: ts.InterfaceDeclaration) { + const interfaceName = node.name.text; if (!this.startsWithI(interfaceName)) { this.addFailureAt(node.name.getStart(), node.name.getWidth()); } @@ -37,12 +37,12 @@ class NameWalker extends Lint.RuleWalker { return true; } - var firstCharacter = name.charAt(0); + const firstCharacter = name.charAt(0); return (firstCharacter === "I"); } private addFailureAt(position: number, width: number) { - var failure = this.createFailure(position, width, Rule.FAILURE_STRING); + const failure = this.createFailure(position, width, Rule.FAILURE_STRING); this.addFailure(failure); } diff --git a/src/rules/jsdocFormatRule.ts b/src/rules/jsdocFormatRule.ts index 78dcf11bb28..46194fe5a41 100644 --- a/src/rules/jsdocFormatRule.ts +++ b/src/rules/jsdocFormatRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static ALIGNMENT_FAILURE_STRING = "asterisks in jsdoc must be aligned"; @@ -24,10 +24,10 @@ export class Rule extends Lint.Rules.AbstractRule { } class JsdocWalker extends Lint.SkippableTokenAwareRuleWalker { - public visitSourceFile(node: ts.SourceFile): void { + public visitSourceFile(node: ts.SourceFile) { super.visitSourceFile(node); Lint.scanAllTokens(ts.createScanner(ts.ScriptTarget.ES5, false, node.text), (scanner: ts.Scanner) => { - var startPos = scanner.getStartPos(); + const startPos = scanner.getStartPos(); if (this.tokensToSkipStartEndMap[startPos] != null) { // tokens to skip are places where the scanner gets confused about what the token is, without the proper context // (specifically, regex, identifiers, and templates). So skip those tokens. @@ -36,58 +36,59 @@ class JsdocWalker extends Lint.SkippableTokenAwareRuleWalker { } if (scanner.getToken() === ts.SyntaxKind.MultiLineCommentTrivia) { - var commentText = scanner.getTokenText(); - var startPosition = scanner.getTokenPos(); + const commentText = scanner.getTokenText(); + const startPosition = scanner.getTokenPos(); this.findFailuresForJsdocComment(commentText, startPosition, node); } }); } private findFailuresForJsdocComment(commentText: string, startingPosition: number, sourceFile: ts.SourceFile) { - var currentPosition = startingPosition; + const currentPosition = startingPosition; // the file may be different depending on the OS it was originally authored on // can't rely on require('os').EOL or process.platform as that is the execution env // regex is: split optionally on \r\n, but alwasy split on \n if no \r exists - var lines = commentText.split(/\r?\n/); - var jsdocPosition = currentPosition; - var firstLine = lines[0]; + const lines = commentText.split(/\r?\n/); + const firstLine = lines[0]; + let jsdocPosition = currentPosition; // regex is: start of string, followed by any amount of whitespace, followed by /** - var isJsdocMatch = firstLine.match(/^\s*\/\*\*/); + const isJsdocMatch = firstLine.match(/^\s*\/\*\*/); if (isJsdocMatch != null) { - if (lines.length === 1) { - var firstLineMatch = firstLine.match(/^\s*\/\*\* (.* )?\*\/$/); + const firstLineMatch = firstLine.match(/^\s*\/\*\* (.* )?\*\/$/); if (firstLineMatch == null) { this.addFailureAt(jsdocPosition, firstLine.length, Rule.FORMAT_FAILURE_STRING); } return; } - var indexToMatch = firstLine.indexOf("**") + sourceFile.getLineAndCharacterOfPosition(currentPosition).character; + + const indexToMatch = firstLine.indexOf("**") + sourceFile.getLineAndCharacterOfPosition(currentPosition).character; // all lines but the first and last - var otherLines = lines.splice(1, lines.length - 2); + const otherLines = lines.splice(1, lines.length - 2); jsdocPosition += firstLine.length + 1; // + 1 for the splitted-out newline - otherLines.forEach((line) => { + for (let line of otherLines) { // regex is: start of string, followed by any amount of whitespace, followed by *, // followed by either a space or the end of the string - var asteriskMatch = line.match(/^\s*\*( |$)/); + const asteriskMatch = line.match(/^\s*\*( |$)/); if (asteriskMatch == null) { this.addFailureAt(jsdocPosition, line.length, Rule.FORMAT_FAILURE_STRING); } - var asteriskIndex = line.indexOf("*"); + const asteriskIndex = line.indexOf("*"); if (asteriskIndex !== indexToMatch) { this.addFailureAt(jsdocPosition, line.length, Rule.ALIGNMENT_FAILURE_STRING); } jsdocPosition += line.length + 1; // + 1 for the splitted-out newline - }); - var lastLine = lines[lines.length - 1]; + } + + const lastLine = lines[lines.length - 1]; // regex is: start of string, followed by any amount of whitespace, followed by */, // followed by the end of the string - var endBlockCommentMatch = lastLine.match(/^\s*\*\/$/); + const endBlockCommentMatch = lastLine.match(/^\s*\*\/$/); if (endBlockCommentMatch == null) { this.addFailureAt(jsdocPosition, lastLine.length, Rule.FORMAT_FAILURE_STRING); } - var lastAsteriskIndex = lastLine.indexOf("*"); + const lastAsteriskIndex = lastLine.indexOf("*"); if (lastAsteriskIndex !== indexToMatch) { this.addFailureAt(jsdocPosition, lastLine.length, Rule.ALIGNMENT_FAILURE_STRING); } @@ -95,7 +96,7 @@ class JsdocWalker extends Lint.SkippableTokenAwareRuleWalker { } private addFailureAt(currentPosition: number, width: number, failureString: string) { - var failure = this.createFailure(currentPosition, width, failureString); + const failure = this.createFailure(currentPosition, width, failureString); this.addFailure(failure); } } diff --git a/src/rules/labelPositionRule.ts b/src/rules/labelPositionRule.ts index d69e23ed9d8..b02e03a6167 100644 --- a/src/rules/labelPositionRule.ts +++ b/src/rules/labelPositionRule.ts @@ -25,15 +25,15 @@ export class Rule extends Lint.Rules.AbstractRule { class LabelPosWalker extends Lint.RuleWalker { private isValidLabel: boolean; - public visitLabeledStatement(node: ts.LabeledStatement): void { - var statement = node.statement; + public visitLabeledStatement(node: ts.LabeledStatement) { + const statement = node.statement; if (statement.kind !== ts.SyntaxKind.DoStatement && statement.kind !== ts.SyntaxKind.ForStatement && statement.kind !== ts.SyntaxKind.ForInStatement && statement.kind !== ts.SyntaxKind.WhileStatement && statement.kind !== ts.SyntaxKind.SwitchStatement) { - var failure = this.createFailure(node.label.getStart(), node.label.getWidth(), Rule.FAILURE_STRING); + const failure = this.createFailure(node.label.getStart(), node.label.getWidth(), Rule.FAILURE_STRING); this.addFailure(failure); } super.visitLabeledStatement(node); diff --git a/src/rules/labelUndefinedRule.ts b/src/rules/labelUndefinedRule.ts index f28d3c74881..bae942bf424 100644 --- a/src/rules/labelUndefinedRule.ts +++ b/src/rules/labelUndefinedRule.ts @@ -27,30 +27,30 @@ class LabelUndefinedWalker extends Lint.ScopeAwareRuleWalker<{[key: string]: any return {}; } - public visitLabeledStatement(node: ts.LabeledStatement): void { - var label = node.label.text; - var currentScope = this.getCurrentScope(); + public visitLabeledStatement(node: ts.LabeledStatement) { + const label = node.label.text; + const currentScope = this.getCurrentScope(); currentScope[label] = true; super.visitLabeledStatement(node); } - public visitBreakStatement(node: ts.BreakOrContinueStatement): void { + public visitBreakStatement(node: ts.BreakOrContinueStatement) { this.validateLabelAt(node.label, node.getStart(), node.getChildAt(0).getWidth()); super.visitBreakStatement(node); } - public visitContinueStatement(node: ts.BreakOrContinueStatement): void { + public visitContinueStatement(node: ts.BreakOrContinueStatement) { this.validateLabelAt(node.label, node.getStart(), node.getChildAt(0).getWidth()); super.visitContinueStatement(node); } - private validateLabelAt(label: ts.Identifier, position: number, width: number): void { - var currentScope = this.getCurrentScope(); + private validateLabelAt(label: ts.Identifier, position: number, width: number) { + const currentScope = this.getCurrentScope(); if (label != null && !currentScope[label.text]) { - var failureString = Rule.FAILURE_STRING + label.text + "'"; - var failure = this.createFailure(position, width, failureString); + const failureString = Rule.FAILURE_STRING + label.text + "'"; + const failure = this.createFailure(position, width, failureString); this.addFailure(failure); } } diff --git a/src/rules/maxLineLengthRule.ts b/src/rules/maxLineLengthRule.ts index ae1dfb5774b..90437710da2 100644 --- a/src/rules/maxLineLengthRule.ts +++ b/src/rules/maxLineLengthRule.ts @@ -12,14 +12,14 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "exceeds maximum line length of "; public isEnabled(): boolean { if (super.isEnabled()) { - var option = this.getOptions().ruleArguments[0]; + const option = this.getOptions().ruleArguments[0]; if (typeof option === "number" && option > 0) { return true; } @@ -29,23 +29,22 @@ export class Rule extends Lint.Rules.AbstractRule { } public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var ruleFailures: Lint.RuleFailure[] = []; - var lineLimit = this.getOptions().ruleArguments[0]; - var lineStarts = sourceFile.getLineStarts(); - var errorString = Rule.FAILURE_STRING + lineLimit; - var disabledIntervals = this.getOptions().disabledIntervals; + const ruleFailures: Lint.RuleFailure[] = []; + const lineLimit = this.getOptions().ruleArguments[0]; + const lineStarts = sourceFile.getLineStarts(); + const errorString = Rule.FAILURE_STRING + lineLimit; + const disabledIntervals = this.getOptions().disabledIntervals; + const source = sourceFile.getFullText(); - var source = sourceFile.getFullText(); - - for (var i = 0; i < lineStarts.length - 1; ++i) { - var from = lineStarts[i], to = lineStarts[i + 1]; + for (let i = 0; i < lineStarts.length - 1; ++i) { + const from = lineStarts[i], to = lineStarts[i + 1]; if ((to - from - 1) > lineLimit && !((to - from - 2) === lineLimit && source[to - 2] === "\r")) { // first condition above is whether the line (minus the newline) is larger than the line limit // second two check for windows line endings, that is, check to make sure it is not the case // that we are only over by the limit by exactly one and that the character we are over the // limit by is a '\r' character which does not count against the limit // (and thus we are not actually over the limit). - var ruleFailure = new Lint.RuleFailure(sourceFile, from, to - 1, errorString, this.getOptions().ruleName); + const ruleFailure = new Lint.RuleFailure(sourceFile, from, to - 1, errorString, this.getOptions().ruleName); if (!Lint.doesIntersect(ruleFailure, disabledIntervals)) { ruleFailures.push(ruleFailure); } diff --git a/src/rules/memberOrderingRule.ts b/src/rules/memberOrderingRule.ts index 6d2967432c5..f42245015ac 100644 --- a/src/rules/memberOrderingRule.ts +++ b/src/rules/memberOrderingRule.ts @@ -12,11 +12,11 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ -var OPTION_VARIABLES_BEFORE_FUNCTIONS = "variables-before-functions"; -var OPTION_STATIC_BEFORE_INSTANCE = "static-before-instance"; -var OPTION_PUBLIC_BEFORE_PRIVATE = "public-before-private"; +const OPTION_VARIABLES_BEFORE_FUNCTIONS = "variables-before-functions"; +const OPTION_STATIC_BEFORE_INSTANCE = "static-before-instance"; +const OPTION_PUBLIC_BEFORE_PRIVATE = "public-before-private"; export class Rule extends Lint.Rules.AbstractRule { public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { @@ -31,7 +31,7 @@ interface IModifiers { } function getModifiers(isMethod: boolean, modifiers?: ts.ModifiersArray): IModifiers { - var modifierStrings: string[] = []; + let modifierStrings: string[] = []; if (modifiers != null) { modifierStrings = modifiers.map((x) => { return x.getText(); @@ -39,9 +39,9 @@ function getModifiers(isMethod: boolean, modifiers?: ts.ModifiersArray): IModifi } return { + isInstance: modifierStrings.indexOf("static") === -1, isMethod: isMethod, - isPrivate: modifierStrings.indexOf("private") !== -1, - isInstance: modifierStrings.indexOf("static") === -1 + isPrivate: modifierStrings.indexOf("private") !== -1 }; } @@ -61,62 +61,62 @@ export class MemberOrderingWalker extends Lint.RuleWalker { super(sourceFile, options); } - public visitClassDeclaration(node: ts.ClassDeclaration): void { + public visitClassDeclaration(node: ts.ClassDeclaration) { this.resetPreviousModifiers(); super.visitClassDeclaration(node); } - public visitInterfaceDeclaration(node: ts.InterfaceDeclaration): void { + public visitInterfaceDeclaration(node: ts.InterfaceDeclaration) { this.resetPreviousModifiers(); super.visitInterfaceDeclaration(node); } - public visitMethodDeclaration(node: ts.MethodDeclaration): void { + public visitMethodDeclaration(node: ts.MethodDeclaration) { this.checkAndSetModifiers(node, getModifiers(true, node.modifiers)); super.visitMethodDeclaration(node); } - public visitMethodSignature(node: ts.SignatureDeclaration): void { + public visitMethodSignature(node: ts.SignatureDeclaration) { this.checkAndSetModifiers(node, getModifiers(true, node.modifiers)); super.visitMethodSignature(node); } - public visitPropertyDeclaration(node: ts.PropertyDeclaration): void { + public visitPropertyDeclaration(node: ts.PropertyDeclaration) { this.checkAndSetModifiers(node, getModifiers(false, node.modifiers)); super.visitPropertyDeclaration(node); } - public visitPropertySignature(node: ts.Node): void { + public visitPropertySignature(node: ts.Node) { this.checkAndSetModifiers(node, getModifiers(false, node.modifiers)); super.visitPropertySignature(node); } - public visitTypeLiteral(node: ts.TypeLiteralNode) { // don't call super from here -- we want to skip the property declarations in type literals } - private resetPreviousModifiers(): void { + private resetPreviousModifiers() { this.previous = { + isInstance: false, isMethod: false, - isPrivate: false, - isInstance: false + isPrivate: false }; } - private checkAndSetModifiers(node: ts.Node, current: IModifiers): void { + private checkAndSetModifiers(node: ts.Node, current: IModifiers) { if (!this.canAppearAfter(this.previous, current)) { - var message = "Declaration of " + toString(current) + + const message = "Declaration of " + toString(current) + " not allowed to appear after declaration of " + toString(this.previous); this.addFailure(this.createFailure(node.getStart(), node.getWidth(), message)); } this.previous = current; } - private canAppearAfter(previous: IModifiers, current: IModifiers): boolean { + private canAppearAfter(previous: IModifiers, current: IModifiers) { if (previous == null || current == null) { return true; } + if (this.hasOption(OPTION_VARIABLES_BEFORE_FUNCTIONS) && previous.isMethod !== current.isMethod) { return Number(previous.isMethod) < Number(current.isMethod); } diff --git a/src/rules/noAnyRule.ts b/src/rules/noAnyRule.ts index 9f1346fa282..9e16ac3beeb 100644 --- a/src/rules/noAnyRule.ts +++ b/src/rules/noAnyRule.ts @@ -23,7 +23,7 @@ export class Rule extends Lint.Rules.AbstractRule { } class NoAnyWalker extends Lint.RuleWalker { - public visitAnyKeyword(node: ts.Node): void { + public visitAnyKeyword(node: ts.Node) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); super.visitAnyKeyword(node); } diff --git a/src/rules/noArgRule.ts b/src/rules/noArgRule.ts index 830fc2ab6cb..a6cb4348c15 100644 --- a/src/rules/noArgRule.ts +++ b/src/rules/noArgRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "access forbidden to arguments property"; @@ -20,19 +20,19 @@ export class Rule extends Lint.Rules.AbstractRule { public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithWalker(new NoArgWalker(sourceFile, this.getOptions())); } - } +} class NoArgWalker extends Lint.RuleWalker { - public visitPropertyAccessExpression(node: ts.PropertyAccessExpression): void { - var expression = node.expression; - var name = node.name; + public visitPropertyAccessExpression(node: ts.PropertyAccessExpression) { + const expression = node.expression; + const name = node.name; if (expression.kind === ts.SyntaxKind.Identifier && name.text === "callee") { - var identifierExpression = expression; + const identifierExpression = expression; if (identifierExpression.text === "arguments") { this.addFailure(this.createFailure(expression.getStart(), expression.getWidth(), Rule.FAILURE_STRING)); } - } + } super.visitPropertyAccessExpression(node); } diff --git a/src/rules/noBitwiseRule.ts b/src/rules/noBitwiseRule.ts index 9dd639ed9a9..dd9a88a1f81 100644 --- a/src/rules/noBitwiseRule.ts +++ b/src/rules/noBitwiseRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "forbidden bitwise operation"; @@ -23,7 +23,7 @@ export class Rule extends Lint.Rules.AbstractRule { } class NoBitwiseWalker extends Lint.RuleWalker { - public visitBinaryExpression(node: ts.BinaryExpression): void { + public visitBinaryExpression(node: ts.BinaryExpression) { switch (node.operatorToken.kind) { case ts.SyntaxKind.AmpersandToken: case ts.SyntaxKind.AmpersandEqualsToken: @@ -43,7 +43,7 @@ class NoBitwiseWalker extends Lint.RuleWalker { super.visitBinaryExpression(node); } - public visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression): void { + public visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression) { if (node.operator === ts.SyntaxKind.TildeToken) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); } diff --git a/src/rules/noConsecutiveBlankLinesRule.ts b/src/rules/noConsecutiveBlankLinesRule.ts index f5196a80fe2..0c5cfed288f 100644 --- a/src/rules/noConsecutiveBlankLinesRule.ts +++ b/src/rules/noConsecutiveBlankLinesRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { static FAILURE_STRING = "consecutive blank lines are disallowed"; @@ -23,12 +23,13 @@ export class Rule extends Lint.Rules.AbstractRule { } class BlankLinesWalker extends Lint.SkippableTokenAwareRuleWalker { - public visitSourceFile(node: ts.SourceFile): void { + public visitSourceFile(node: ts.SourceFile) { super.visitSourceFile(node); + // starting with 1 to cover the case where the file starts with two blank lines - var newLinesInARowSeenSoFar = 1; + let newLinesInARowSeenSoFar = 1; Lint.scanAllTokens(ts.createScanner(ts.ScriptTarget.ES5, false, node.text), (scanner: ts.Scanner) => { - var startPos = scanner.getStartPos(); + const startPos = scanner.getStartPos(); if (this.tokensToSkipStartEndMap[startPos] != null) { // tokens to skip are places where the scanner gets confused about what the token is, without the proper context // (specifically, regex, identifiers, and templates). So skip those tokens. @@ -40,7 +41,7 @@ class BlankLinesWalker extends Lint.SkippableTokenAwareRuleWalker { if (scanner.getToken() === ts.SyntaxKind.NewLineTrivia) { newLinesInARowSeenSoFar += 1; if (newLinesInARowSeenSoFar >= 3) { - var failure = this.createFailure(scanner.getStartPos(), 1, Rule.FAILURE_STRING); + const failure = this.createFailure(scanner.getStartPos(), 1, Rule.FAILURE_STRING); this.addFailure(failure); } } else { diff --git a/src/rules/noConsoleRule.ts b/src/rules/noConsoleRule.ts index 71f005c9a80..cd22d8214fd 100644 --- a/src/rules/noConsoleRule.ts +++ b/src/rules/noConsoleRule.ts @@ -12,17 +12,17 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ import BanRule = require("./banRule"); export class Rule extends BanRule.Rule { public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var options = this.getOptions(); - var consoleBanWalker = new BanRule.BanFunctionWalker(sourceFile, this.getOptions()); - options.ruleArguments.forEach((option) => { + const options = this.getOptions(); + const consoleBanWalker = new BanRule.BanFunctionWalker(sourceFile, this.getOptions()); + for (let option of options.ruleArguments) { consoleBanWalker.addBannedFunction(["console", option]); - }); + } return this.applyWithWalker(consoleBanWalker); } } diff --git a/src/rules/noConstructRule.ts b/src/rules/noConstructRule.ts index c1aad94520b..0d5eb19bd09 100644 --- a/src/rules/noConstructRule.ts +++ b/src/rules/noConstructRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "undesirable constructor use"; @@ -29,12 +29,12 @@ class NoConstructWalker extends Lint.RuleWalker { "String" ]; - public visitNewExpression(node: ts.NewExpression): void { + public visitNewExpression(node: ts.NewExpression) { if (node.expression.kind === ts.SyntaxKind.Identifier) { - var identifier = node.expression; - var constructorName = identifier.text; + const identifier = node.expression; + const constructorName = identifier.text; if (NoConstructWalker.FORBIDDEN_CONSTRUCTORS.indexOf(constructorName) !== -1) { - var failure = this.createFailure(node.getStart(), identifier.getEnd() - node.getStart(), Rule.FAILURE_STRING); + const failure = this.createFailure(node.getStart(), identifier.getEnd() - node.getStart(), Rule.FAILURE_STRING); this.addFailure(failure); } } diff --git a/src/rules/noConstructorVarsRule.ts b/src/rules/noConstructorVarsRule.ts index a59c42c0c7b..47e51c895f9 100644 --- a/src/rules/noConstructorVarsRule.ts +++ b/src/rules/noConstructorVarsRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING_PART = " cannot be declared in the constructor"; @@ -24,19 +24,17 @@ export class Rule extends Lint.Rules.AbstractRule { export class NoConstructorVariableDeclarationsWalker extends Lint.RuleWalker { - public visitConstructorDeclaration(node: ts.ConstructorDeclaration): void { - var parameters = node.parameters; - parameters.forEach((parameter) => { + public visitConstructorDeclaration(node: ts.ConstructorDeclaration) { + const parameters = node.parameters; + for (let parameter of parameters) { if (parameter.modifiers != null && parameter.modifiers.length > 0) { - var name = parameter.name; - var errorMessage = "'" + name.text + "'" + Rule.FAILURE_STRING_PART; - - var lastModifier = parameter.modifiers[parameter.modifiers.length - 1]; - var position = lastModifier.getEnd() - parameter.getStart(); - + const name = parameter.name; + const errorMessage = "'" + name.text + "'" + Rule.FAILURE_STRING_PART; + const lastModifier = parameter.modifiers[parameter.modifiers.length - 1]; + const position = lastModifier.getEnd() - parameter.getStart(); this.addFailure(this.createFailure(parameter.getStart(), position, errorMessage)); } - }); + } super.visitConstructorDeclaration(node); } } diff --git a/src/rules/noDebuggerRule.ts b/src/rules/noDebuggerRule.ts index c7c844005d8..efef88e0dba 100644 --- a/src/rules/noDebuggerRule.ts +++ b/src/rules/noDebuggerRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "use of debugger statements is disallowed"; @@ -23,8 +23,8 @@ export class Rule extends Lint.Rules.AbstractRule { } class NoDebuggerWalker extends Lint.RuleWalker { - public visitDebuggerStatement(node: ts.Statement): void { - var debuggerKeywordNode = node.getChildAt(0); + public visitDebuggerStatement(node: ts.Statement) { + const debuggerKeywordNode = node.getChildAt(0); this.addFailure(this.createFailure(debuggerKeywordNode.getStart(), debuggerKeywordNode.getWidth(), Rule.FAILURE_STRING)); super.visitDebuggerStatement(node); } diff --git a/src/rules/noDuplicateKeyRule.ts b/src/rules/noDuplicateKeyRule.ts index 9e6b795d96d..4502eaee14a 100644 --- a/src/rules/noDuplicateKeyRule.ts +++ b/src/rules/noDuplicateKeyRule.ts @@ -25,13 +25,13 @@ export class Rule extends Lint.Rules.AbstractRule { class NoDuplicateKeyWalker extends Lint.RuleWalker { private objectKeysStack: {[key: string]: boolean}[] = []; - public visitObjectLiteralExpression(node: ts.ObjectLiteralExpression): void { + public visitObjectLiteralExpression(node: ts.ObjectLiteralExpression) { this.objectKeysStack.push(Object.create(null)); super.visitObjectLiteralExpression(node); this.objectKeysStack.pop(); } - public visitPropertyAssignment(node: ts.PropertyAssignment): void { + public visitPropertyAssignment(node: ts.PropertyAssignment) { const objectKeys = this.objectKeysStack[this.objectKeysStack.length - 1]; const keyNode = node.name; diff --git a/src/rules/noEmptyRule.ts b/src/rules/noEmptyRule.ts index 7788018a23a..d5693f2957a 100644 --- a/src/rules/noEmptyRule.ts +++ b/src/rules/noEmptyRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "block is empty"; @@ -25,15 +25,13 @@ export class Rule extends Lint.Rules.AbstractRule { class BlockWalker extends Lint.RuleWalker { private ignoredBlocks: ts.Block[] = []; - public visitBlock(node: ts.Block): void { - var openBrace = node.getChildAt(0); - var closeBrace = node.getChildAt(node.getChildCount() - 1); - - var sourceFileText = node.getSourceFile().text; - - var hasCommentAfter = ts.getTrailingCommentRanges(sourceFileText, openBrace.getEnd()) != null; - var hasCommentBefore = ts.getLeadingCommentRanges(sourceFileText, closeBrace.getFullStart()) != null; - var isSkipped = this.ignoredBlocks.indexOf(node) !== -1; + public visitBlock(node: ts.Block) { + const openBrace = node.getChildAt(0); + const closeBrace = node.getChildAt(node.getChildCount() - 1); + const sourceFileText = node.getSourceFile().text; + const hasCommentAfter = ts.getTrailingCommentRanges(sourceFileText, openBrace.getEnd()) != null; + const hasCommentBefore = ts.getLeadingCommentRanges(sourceFileText, closeBrace.getFullStart()) != null; + const isSkipped = this.ignoredBlocks.indexOf(node) !== -1; if (node.statements.length <= 0 && !hasCommentAfter && !hasCommentBefore && !isSkipped) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); @@ -42,20 +40,22 @@ class BlockWalker extends Lint.RuleWalker { super.visitBlock(node); } - public visitConstructorDeclaration(node: ts.ConstructorDeclaration): void { - var isSkipped = false; - var parameters = node.parameters; - - for (var i = 0; i < parameters.length; i++) { - var param = parameters[i]; + public visitConstructorDeclaration(node: ts.ConstructorDeclaration) { + const parameters = node.parameters; + let isSkipped = false; - for (var j = 0; param.modifiers != null && j < param.modifiers.length; j++) { - if (this.isPropertyAccessModifier(param.modifiers[j].kind)) { - isSkipped = true; - this.ignoredBlocks.push(node.body); + for (let param of parameters) { + const hasPropertyAccessModifier = Lint.hasModifier( + param.modifiers, + ts.SyntaxKind.PrivateKeyword, + ts.SyntaxKind.ProtectedKeyword, + ts.SyntaxKind.PublicKeyword + ); - break; - } + if (hasPropertyAccessModifier) { + isSkipped = true; + this.ignoredBlocks.push(node.body); + break; } if (isSkipped) { @@ -65,10 +65,4 @@ class BlockWalker extends Lint.RuleWalker { super.visitConstructorDeclaration(node); } - - private isPropertyAccessModifier(modifier: ts.SyntaxKind): boolean { - return modifier === ts.SyntaxKind.PrivateKeyword - || modifier === ts.SyntaxKind.ProtectedKeyword - || modifier === ts.SyntaxKind.PublicKeyword; - } } diff --git a/src/rules/noEvalRule.ts b/src/rules/noEvalRule.ts index 14538506e3a..2100683f985 100644 --- a/src/rules/noEvalRule.ts +++ b/src/rules/noEvalRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "forbidden eval"; @@ -23,10 +23,10 @@ export class Rule extends Lint.Rules.AbstractRule { } class NoEvalWalker extends Lint.RuleWalker { - public visitCallExpression(node: ts.CallExpression): void { - var expression = node.expression; + public visitCallExpression(node: ts.CallExpression) { + const expression = node.expression; if (expression.kind === ts.SyntaxKind.Identifier) { - var expressionName = ( expression).text; + const expressionName = ( expression).text; if (expressionName === "eval") { this.addFailure(this.createFailure(expression.getStart(), expression.getWidth(), Rule.FAILURE_STRING)); } diff --git a/src/rules/noRequireImportsRule.ts b/src/rules/noRequireImportsRule.ts index 2f911783aab..617efbe3792 100644 --- a/src/rules/noRequireImportsRule.ts +++ b/src/rules/noRequireImportsRule.ts @@ -36,7 +36,7 @@ class NoRequireImportsWalker extends Lint.RuleWalker { super.visitImportEqualsDeclaration(node); } - private handleDeclaration(decl: ts.VariableDeclaration) : void { + private handleDeclaration(decl: ts.VariableDeclaration) { // make sure the RHS is a call expression. const call = (decl.initializer); if (call && call.arguments && call.expression) { diff --git a/src/rules/noShadowedVariableRule.ts b/src/rules/noShadowedVariableRule.ts index 39f7cee801e..ae4e3e0148c 100644 --- a/src/rules/noShadowedVariableRule.ts +++ b/src/rules/noShadowedVariableRule.ts @@ -66,13 +66,13 @@ class NoShadowedVariableWalker extends Lint.BlockScopeAwareRuleWalker 2) { - var unquotedAccessorText = accessorText.substring(1, accessorText.length - 1); + const unquotedAccessorText = accessorText.substring(1, accessorText.length - 1); // only create a failure if the identifier is valid, in which case there's no need to use string literals if (this.isValidIdentifier(unquotedAccessorText)) { @@ -41,7 +41,7 @@ class NoStringLiteralWalker extends Lint.RuleWalker { } private isValidIdentifier(token: string) { - var scanner = ts.createScanner(ts.ScriptTarget.ES5, true, token); + const scanner = ts.createScanner(ts.ScriptTarget.ES5, true, token); scanner.scan(); // if we scanned to the end of the token, we can check if the scanned item was an identifier return scanner.getTokenText() === token && scanner.isIdentifier(); diff --git a/src/rules/noSwitchCaseFallThroughRule.ts b/src/rules/noSwitchCaseFallThroughRule.ts index ea8d1cc2691..27d1e672b56 100644 --- a/src/rules/noSwitchCaseFallThroughRule.ts +++ b/src/rules/noSwitchCaseFallThroughRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING_PART = "expected a 'break' before "; @@ -23,16 +23,15 @@ export class Rule extends Lint.Rules.AbstractRule { } export class NoSwitchCaseFallThroughWalker extends Lint.RuleWalker { - public visitSwitchStatement(node: ts.SwitchStatement) { - var isFallingThrough = false; - // get the position for the first case statement + let isFallingThrough = false; - var switchClauses = node.caseBlock.clauses; + // get the position for the first case statement + const switchClauses = node.caseBlock.clauses; switchClauses.forEach((child, i) => { - var kind = child.kind; + const kind = child.kind; if (kind === ts.SyntaxKind.CaseClause) { - var switchClause = child; + const switchClause = child; isFallingThrough = this.fallsThrough(switchClause.statements); // no break statements and no statements means the fallthrough is expected. // last item doesn't need a break @@ -45,7 +44,7 @@ export class NoSwitchCaseFallThroughWalker extends Lint.RuleWalker { } else { // case statement falling through a default if (isFallingThrough && !this.fallThroughAllowed(child)) { - var failureString = Rule.FAILURE_STRING_PART + "'default'"; + const failureString = Rule.FAILURE_STRING_PART + "'default'"; this.addFailure(this.createFailure(switchClauses[i - 1].getEnd(), 1, failureString)); } } @@ -53,15 +52,14 @@ export class NoSwitchCaseFallThroughWalker extends Lint.RuleWalker { super.visitSwitchStatement(node); } - private fallThroughAllowed(nextCaseOrDefaultStatement: ts.Node): boolean { - var sourceFileText = nextCaseOrDefaultStatement.getSourceFile().text; - var childCount = nextCaseOrDefaultStatement.getChildCount(); - var firstChild = nextCaseOrDefaultStatement.getChildAt(0); - var commentRanges = ts.getLeadingCommentRanges(sourceFileText, firstChild.getFullStart()); + private fallThroughAllowed(nextCaseOrDefaultStatement: ts.Node) { + const sourceFileText = nextCaseOrDefaultStatement.getSourceFile().text; + const childCount = nextCaseOrDefaultStatement.getChildCount(); + const firstChild = nextCaseOrDefaultStatement.getChildAt(0); + const commentRanges = ts.getLeadingCommentRanges(sourceFileText, firstChild.getFullStart()); if (commentRanges != null) { - for (var i = 0; i < commentRanges.length; i++) { - var commentRange = commentRanges[i]; - var commentText = sourceFileText.substring(commentRange.pos, commentRange.end); + for (let commentRange of commentRanges) { + const commentText = sourceFileText.substring(commentRange.pos, commentRange.end); if (commentText === "/* falls through */") { return true; } @@ -70,15 +68,11 @@ export class NoSwitchCaseFallThroughWalker extends Lint.RuleWalker { return false; } - private fallsThrough(list: ts.NodeArray) { - for (var i = 0; i < list.length; i++) { - var nodeKind = list[i].kind; - if (nodeKind === ts.SyntaxKind.BreakStatement || - nodeKind === ts.SyntaxKind.ThrowStatement || - nodeKind === ts.SyntaxKind.ReturnStatement) { - return false; - } - } - return true; + private fallsThrough(statements: ts.NodeArray) { + return !statements.some((statement) => { + return statement.kind === ts.SyntaxKind.BreakStatement + || statement.kind === ts.SyntaxKind.ThrowStatement + || statement.kind === ts.SyntaxKind.ReturnStatement; + }); } } diff --git a/src/rules/noTrailingCommaRule.ts b/src/rules/noTrailingCommaRule.ts index ce8a3bbc610..d91d2b7b70e 100644 --- a/src/rules/noTrailingCommaRule.ts +++ b/src/rules/noTrailingCommaRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "trailing comma"; @@ -23,12 +23,12 @@ export class Rule extends Lint.Rules.AbstractRule { } class NoTrailingCommaWalker extends Lint.RuleWalker { - public visitObjectLiteralExpression(node: ts.ObjectLiteralExpression): void { - var child = node.getChildAt(1); + public visitObjectLiteralExpression(node: ts.ObjectLiteralExpression) { + const child = node.getChildAt(1); if (child != null && child.kind === ts.SyntaxKind.SyntaxList) { - var grandChildren = child.getChildren(); + const grandChildren = child.getChildren(); if (grandChildren.length > 0) { - var lastGrandChild = grandChildren[grandChildren.length - 1]; + const lastGrandChild = grandChildren[grandChildren.length - 1]; if (lastGrandChild.kind === ts.SyntaxKind.CommaToken) { this.addFailure(this.createFailure(lastGrandChild.getStart(), 1, Rule.FAILURE_STRING)); diff --git a/src/rules/noTrailingWhitespaceRule.ts b/src/rules/noTrailingWhitespaceRule.ts index 6d96097a825..a1a2f74f9d0 100644 --- a/src/rules/noTrailingWhitespaceRule.ts +++ b/src/rules/noTrailingWhitespaceRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "trailing whitespace"; @@ -23,12 +23,12 @@ export class Rule extends Lint.Rules.AbstractRule { } class NoTrailingWhitespaceWalker extends Lint.SkippableTokenAwareRuleWalker { - public visitSourceFile(node: ts.SourceFile): void { + public visitSourceFile(node: ts.SourceFile) { super.visitSourceFile(node); - var lastSeenWasWhitespace = false; - var lastSeenWhitespacePosition = 0; + let lastSeenWasWhitespace = false; + let lastSeenWhitespacePosition = 0; Lint.scanAllTokens(ts.createScanner(ts.ScriptTarget.ES5, false, node.text), (scanner: ts.Scanner) => { - var startPos = scanner.getStartPos(); + const startPos = scanner.getStartPos(); if (this.tokensToSkipStartEndMap[startPos] != null) { // tokens to skip are places where the scanner gets confused about what the token is, without the proper context // (specifically, regex, identifiers, and templates). So skip those tokens. @@ -39,8 +39,8 @@ class NoTrailingWhitespaceWalker extends Lint.SkippableTokenAwareRuleWalker { if (scanner.getToken() === ts.SyntaxKind.NewLineTrivia) { if (lastSeenWasWhitespace) { - var width = scanner.getStartPos() - lastSeenWhitespacePosition; - var failure = this.createFailure(lastSeenWhitespacePosition, width, Rule.FAILURE_STRING); + const width = scanner.getStartPos() - lastSeenWhitespacePosition; + const failure = this.createFailure(lastSeenWhitespacePosition, width, Rule.FAILURE_STRING); this.addFailure(failure); } lastSeenWasWhitespace = false; diff --git a/src/rules/noUnreachableRule.ts b/src/rules/noUnreachableRule.ts index 99deb29d7cc..a3a55e1f18e 100644 --- a/src/rules/noUnreachableRule.ts +++ b/src/rules/noUnreachableRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "unreachable code"; @@ -30,8 +30,8 @@ class UnreachableWalker extends Lint.RuleWalker { this.hasReturned = false; } - public visitNode(node: ts.Node): void { - var previousReturned = this.hasReturned; + public visitNode(node: ts.Node) { + const previousReturned = this.hasReturned; // function declarations can be hoisted -- so set hasReturned to false until we're done with the function if (node.kind === ts.SyntaxKind.FunctionDeclaration) { this.hasReturned = false; @@ -51,22 +51,22 @@ class UnreachableWalker extends Lint.RuleWalker { } } - public visitBlock(node: ts.Block): void { + public visitBlock(node: ts.Block) { super.visitBlock(node); this.hasReturned = false; } - public visitCaseClause(node: ts.CaseClause): void { + public visitCaseClause(node: ts.CaseClause) { super.visitCaseClause(node); this.hasReturned = false; } - public visitDefaultClause(node: ts.DefaultClause): void { + public visitDefaultClause(node: ts.DefaultClause) { super.visitDefaultClause(node); this.hasReturned = false; } - public visitIfStatement(node: ts.IfStatement): void { + public visitIfStatement(node: ts.IfStatement) { this.visitNode(node.expression); this.visitNode(node.thenStatement); this.hasReturned = false; @@ -76,22 +76,22 @@ class UnreachableWalker extends Lint.RuleWalker { } } - public visitBreakStatement(node: ts.BreakOrContinueStatement): void { + public visitBreakStatement(node: ts.BreakOrContinueStatement) { super.visitBreakStatement(node); this.hasReturned = true; } - public visitContinueStatement(node: ts.BreakOrContinueStatement): void { + public visitContinueStatement(node: ts.BreakOrContinueStatement) { super.visitContinueStatement(node); this.hasReturned = true; } - public visitReturnStatement(node: ts.ReturnStatement): void { + public visitReturnStatement(node: ts.ReturnStatement) { super.visitReturnStatement(node); this.hasReturned = true; } - public visitThrowStatement(node: ts.ThrowStatement): void { + public visitThrowStatement(node: ts.ThrowStatement) { super.visitThrowStatement(node); this.hasReturned = true; } diff --git a/src/rules/noUnusedExpressionRule.ts b/src/rules/noUnusedExpressionRule.ts index f40f64ea7e2..f659b3b5e54 100644 --- a/src/rules/noUnusedExpressionRule.ts +++ b/src/rules/noUnusedExpressionRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "expected an assignment or function call"; @@ -36,7 +36,7 @@ class UnusedExpressionWalker extends Lint.RuleWalker { if (this.expressionIsUnused) { // ignore valid unused expressions if (node.expression.kind === ts.SyntaxKind.StringLiteral) { - var expressionText = node.expression.getText(); + const expressionText = node.expression.getText(); if (expressionText === "\"use strict\"" || expressionText === "'use strict'") { return; } @@ -106,13 +106,12 @@ class UnusedExpressionWalker extends Lint.RuleWalker { this.visitNode(node.condition); this.expressionIsUnused = true; this.visitNode(node.whenTrue); - var firstExpressionIsUnused = this.expressionIsUnused; + const firstExpressionIsUnused = this.expressionIsUnused; this.expressionIsUnused = true; this.visitNode(node.whenFalse); - var secondExpressionIsUnused = this.expressionIsUnused; + const secondExpressionIsUnused = this.expressionIsUnused; // if either expression is unused, then that expression's branch is a no-op unless it's // being assigned to something or passed to a function, so consider the entire expression unused this.expressionIsUnused = firstExpressionIsUnused || secondExpressionIsUnused; } - } diff --git a/src/rules/noUnusedVariableRule.ts b/src/rules/noUnusedVariableRule.ts index 5d3e089420b..9fb30942149 100644 --- a/src/rules/noUnusedVariableRule.ts +++ b/src/rules/noUnusedVariableRule.ts @@ -14,15 +14,15 @@ * limitations under the License. */ -var OPTION_CHECK_PARAMETERS = "check-parameters"; +const OPTION_CHECK_PARAMETERS = "check-parameters"; export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "unused variable: "; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var documentRegistry = ts.createDocumentRegistry(); - var languageServiceHost = Lint.createLanguageServiceHost("file.ts", sourceFile.getFullText()); - var languageService = ts.createLanguageService(languageServiceHost, documentRegistry); + const documentRegistry = ts.createDocumentRegistry(); + const languageServiceHost = Lint.createLanguageServiceHost("file.ts", sourceFile.getFullText()); + const languageService = ts.createLanguageService(languageServiceHost, documentRegistry); return this.applyWithWalker(new NoUnusedVariablesWalker(sourceFile, this.getOptions(), languageService)); } @@ -42,23 +42,23 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { } public visitBindingElement(node: ts.BindingElement) { - var isSingleVariable = node.name.kind === ts.SyntaxKind.Identifier; + const isSingleVariable = node.name.kind === ts.SyntaxKind.Identifier; if (isSingleVariable && !this.skipBindingElement) { - var variableIdentifier = node.name; + const variableIdentifier = node.name; this.validateReferencesForVariable(variableIdentifier.text, variableIdentifier.getStart()); } super.visitBindingElement(node); } - public visitImportDeclaration(node: ts.ImportDeclaration): void { + public visitImportDeclaration(node: ts.ImportDeclaration) { if (!Lint.hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword)) { - var importClause = node.importClause; + const importClause = node.importClause; // named imports & namespace imports handled by other walker methods if (importClause.name != null) { - var variableIdentifier = importClause.name; + const variableIdentifier = importClause.name; this.validateReferencesForVariable(variableIdentifier.text, variableIdentifier.getStart()); } } @@ -66,37 +66,37 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { super.visitImportDeclaration(node); } - public visitImportEqualsDeclaration(node: ts.ImportEqualsDeclaration): void { + public visitImportEqualsDeclaration(node: ts.ImportEqualsDeclaration) { if (!Lint.hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword)) { - var name = node.name; + const name = node.name; this.validateReferencesForVariable(name.text, name.getStart()); } super.visitImportEqualsDeclaration(node); } - public visitCatchClause(node: ts.CatchClause): void { + public visitCatchClause(node: ts.CatchClause) { // don't visit the catch clause variable declaration, just visit the block // the catch clause variable declaration needs to be there but doesn't need to be used this.visitBlock(node.block); } - public visitNamedImports(node: ts.NamedImports): void { + public visitNamedImports(node: ts.NamedImports) { node.elements.forEach((namedImport: ts.ImportSpecifier) => { this.validateReferencesForVariable(namedImport.name.text, namedImport.name.getStart()); }); super.visitNamedImports(node); } - public visitNamespaceImport(node: ts.NamespaceImport): void { + public visitNamespaceImport(node: ts.NamespaceImport) { this.validateReferencesForVariable(node.name.text, node.name.getStart()); super.visitNamespaceImport(node); } - public visitVariableDeclaration(node: ts.VariableDeclaration): void { - var isSingleVariable = node.name.kind === ts.SyntaxKind.Identifier; + public visitVariableDeclaration(node: ts.VariableDeclaration) { + const isSingleVariable = node.name.kind === ts.SyntaxKind.Identifier; if (isSingleVariable && !this.skipVariableDeclaration) { - var variableIdentifier = node.name; + const variableIdentifier = node.name; this.validateReferencesForVariable(variableIdentifier.text, variableIdentifier.getStart()); } @@ -104,21 +104,21 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { } // skip parameters in interfaces - public visitInterfaceDeclaration(node: ts.InterfaceDeclaration): void { + public visitInterfaceDeclaration(node: ts.InterfaceDeclaration) { this.skipParameterDeclaration = true; super.visitInterfaceDeclaration(node); this.skipParameterDeclaration = false; } // skip parameters in index signatures (stuff like [key: string]: string) - public visitIndexSignatureDeclaration(node: ts.IndexSignatureDeclaration): void { + public visitIndexSignatureDeclaration(node: ts.IndexSignatureDeclaration) { this.skipParameterDeclaration = true; super.visitIndexSignatureDeclaration(node); this.skipParameterDeclaration = false; } // skip exported and declared variables - public visitVariableStatement(node: ts.VariableStatement): void { + public visitVariableStatement(node: ts.VariableStatement) { if (Lint.hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword, ts.SyntaxKind.DeclareKeyword)) { this.skipBindingElement = true; this.skipVariableDeclaration = true; @@ -129,15 +129,15 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { this.skipVariableDeclaration = false; } - public visitFunctionType(node: ts.Node): void { + public visitFunctionType(node: ts.Node) { this.skipParameterDeclaration = true; super.visitFunctionType(node); this.skipParameterDeclaration = false; } // skip exported and declared functions - public visitFunctionDeclaration(node: ts.FunctionDeclaration): void { - var variableName = node.name.text; + public visitFunctionDeclaration(node: ts.FunctionDeclaration) { + const variableName = node.name.text; if (!Lint.hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword, ts.SyntaxKind.DeclareKeyword)) { this.validateReferencesForVariable(variableName, node.name.getStart()); @@ -146,12 +146,12 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { super.visitFunctionDeclaration(node); } - public visitParameterDeclaration(node: ts.ParameterDeclaration): void { - var isSingleVariable = node.name.kind === ts.SyntaxKind.Identifier; - var isPropertyParameter = Lint.hasModifier(node.modifiers, - ts.SyntaxKind.PublicKeyword, - ts.SyntaxKind.PrivateKeyword, - ts.SyntaxKind.ProtectedKeyword); + public visitParameterDeclaration(node: ts.ParameterDeclaration) { + const isSingleVariable = node.name.kind === ts.SyntaxKind.Identifier; + const isPropertyParameter = Lint.hasModifier(node.modifiers, + ts.SyntaxKind.PublicKeyword, + ts.SyntaxKind.PrivateKeyword, + ts.SyntaxKind.ProtectedKeyword); if (!isSingleVariable && isPropertyParameter) { // tsc error: a parameter property may not be a binding pattern @@ -162,7 +162,7 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { && isSingleVariable && !this.skipParameterDeclaration && !Lint.hasModifier(node.modifiers, ts.SyntaxKind.PublicKeyword)) { - var nameNode = node.name; + const nameNode = node.name; this.validateReferencesForVariable(nameNode.text, node.name.getStart()); } @@ -171,10 +171,10 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { } // check private member variables - public visitPropertyDeclaration(node: ts.PropertyDeclaration): void { + public visitPropertyDeclaration(node: ts.PropertyDeclaration) { if (node.name != null && node.name.kind === ts.SyntaxKind.Identifier) { - var modifiers = node.modifiers; - var variableName = ( node.name).text; + const modifiers = node.modifiers; + const variableName = ( node.name).text; // check only if an explicit 'private' modifier is specified if (Lint.hasModifier(modifiers, ts.SyntaxKind.PrivateKeyword)) { @@ -186,10 +186,10 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { } // check private member functions - public visitMethodDeclaration(node: ts.MethodDeclaration): void { + public visitMethodDeclaration(node: ts.MethodDeclaration) { if (node.name != null && node.name.kind === ts.SyntaxKind.Identifier) { - var modifiers = node.modifiers; - var variableName = ( node.name).text; + const modifiers = node.modifiers; + const variableName = ( node.name).text; if (Lint.hasModifier(modifiers, ts.SyntaxKind.PrivateKeyword)) { this.validateReferencesForVariable(variableName, node.name.getStart()); @@ -200,7 +200,7 @@ class NoUnusedVariablesWalker extends Lint.RuleWalker { } private validateReferencesForVariable(name: string, position: number) { - var highlights = this.languageService.getDocumentHighlights("file.ts", position, ["file.ts"]); + const highlights = this.languageService.getDocumentHighlights("file.ts", position, ["file.ts"]); if (highlights[0].highlightSpans.length <= 1) { this.addFailure(this.createFailure(position, name.length, `${Rule.FAILURE_STRING}'${name}'`)); } diff --git a/src/rules/noUseBeforeDeclareRule.ts b/src/rules/noUseBeforeDeclareRule.ts index 2a3ae082088..6a4001f32bc 100644 --- a/src/rules/noUseBeforeDeclareRule.ts +++ b/src/rules/noUseBeforeDeclareRule.ts @@ -19,9 +19,9 @@ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING_POSTFIX = "' used before declaration"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var documentRegistry = ts.createDocumentRegistry(); - var languageServiceHost = Lint.createLanguageServiceHost("file.ts", sourceFile.getFullText()); - var languageService = ts.createLanguageService(languageServiceHost, documentRegistry); + const documentRegistry = ts.createDocumentRegistry(); + const languageServiceHost = Lint.createLanguageServiceHost("file.ts", sourceFile.getFullText()); + const languageService = ts.createLanguageService(languageServiceHost, documentRegistry); return this.applyWithWalker(new NoUseBeforeDeclareWalker(sourceFile, this.getOptions(), languageService)); } @@ -41,13 +41,13 @@ class NoUseBeforeDeclareWalker extends Lint.ScopeAwareRuleWalker node.name; + public visitImportEqualsDeclaration(node: ts.ImportEqualsDeclaration) { + const name = node.name; this.validateUsageForVariable(name.text, name.getStart()); super.visitImportEqualsDeclaration(node); } - public visitNamedImports(node: ts.NamedImports): void { - node.elements.forEach((namedImport: ts.ImportSpecifier) => { + public visitNamedImports(node: ts.NamedImports) { + for (let namedImport of node.elements) { this.validateUsageForVariable(namedImport.name.text, namedImport.name.getStart()); - }); + } super.visitNamedImports(node); } - public visitNamespaceImport(node: ts.NamespaceImport): void { + public visitNamespaceImport(node: ts.NamespaceImport) { this.validateUsageForVariable(node.name.text, node.name.getStart()); super.visitNamespaceImport(node); } - public visitVariableDeclaration(node: ts.VariableDeclaration): void { - var isSingleVariable = node.name.kind === ts.SyntaxKind.Identifier; - var nameNode = node.name; - var variableName = nameNode.text; - var currentScope = this.getCurrentScope(); + public visitVariableDeclaration(node: ts.VariableDeclaration) { + const isSingleVariable = node.name.kind === ts.SyntaxKind.Identifier; + const nameNode = node.name; + const variableName = nameNode.text; + const currentScope = this.getCurrentScope(); // only validate on the first variable declaration within the current scope if (currentScope[variableName] == null) { @@ -90,17 +90,15 @@ class NoUseBeforeDeclareWalker extends Lint.ScopeAwareRuleWalker { - highlight.highlightSpans.forEach((highlightSpan) => { - var referencePosition = highlightSpan.textSpan.start; - if (referencePosition < position) { - var failureString = Rule.FAILURE_STRING_PREFIX + name + Rule.FAILURE_STRING_POSTFIX; - this.addFailure(this.createFailure(referencePosition, name.length, failureString)); - } - }); - }); + const highlights = this.languageService.getDocumentHighlights("file.ts", position, ["file.ts"]); + for (let highlight of highlights) { + for (let highlightSpan of highlight.highlightSpans) { + const referencePosition = highlightSpan.textSpan.start; + if (referencePosition < position) { + const failureString = Rule.FAILURE_STRING_PREFIX + name + Rule.FAILURE_STRING_POSTFIX; + this.addFailure(this.createFailure(referencePosition, name.length, failureString)); + } + } } } } diff --git a/src/rules/noVarKeywordRule.ts b/src/rules/noVarKeywordRule.ts index 511c9595a01..710b0a99649 100644 --- a/src/rules/noVarKeywordRule.ts +++ b/src/rules/noVarKeywordRule.ts @@ -12,28 +12,28 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ /// -var OPTION_LEADING_UNDERSCORE = "no-var-keyword"; +const OPTION_LEADING_UNDERSCORE = "no-var-keyword"; export class Rule extends Lint.Rules.AbstractRule { - public static FAILURE_STRING = "forbidden var keyword"; + public static FAILURE_STRING = "forbidden const keyword"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var noVarKeywordWalker = new NoVarKeywordWalker(sourceFile, this.getOptions()); + const noVarKeywordWalker = new NoVarKeywordWalker(sourceFile, this.getOptions()); return this.applyWithWalker(noVarKeywordWalker); } } class NoVarKeywordWalker extends Lint.RuleWalker { - public visitVariableStatement(node: ts.VariableStatement): void { + public visitVariableStatement(node: ts.VariableStatement) { if (!Lint.hasModifier(node.modifiers, ts.SyntaxKind.ExportKeyword) && !Lint.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)) { - var flags = node.declarationList.flags; - var declarationIsLet = (Math.floor(flags / ts.NodeFlags.Let) % 2) === 1; - var declarationIsConst = (Math.floor(flags / ts.NodeFlags.Const) % 2) === 1; + const flags = node.declarationList.flags; + const declarationIsLet = (Math.floor(flags / ts.NodeFlags.Let) % 2) === 1; + const declarationIsConst = (Math.floor(flags / ts.NodeFlags.Const) % 2) === 1; if (!declarationIsConst && !declarationIsLet) { this.addFailure(this.createFailure(node.getStart(), "var".length, Rule.FAILURE_STRING)); } diff --git a/src/rules/noVarRequiresRule.ts b/src/rules/noVarRequiresRule.ts index ff985c3a90e..0e8cab9bd67 100644 --- a/src/rules/noVarRequiresRule.ts +++ b/src/rules/noVarRequiresRule.ts @@ -12,19 +12,18 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "require statement not part of an import statement"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var requiresWalker = new RequiresWalker(sourceFile, this.getOptions()); + const requiresWalker = new RequiresWalker(sourceFile, this.getOptions()); return this.applyWithWalker(requiresWalker); } } class RequiresWalker extends Lint.ScopeAwareRuleWalker<{}> { - constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) { super(sourceFile, options); } @@ -34,10 +33,10 @@ class RequiresWalker extends Lint.ScopeAwareRuleWalker<{}> { } public visitCallExpression(node: ts.CallExpression) { - var expression = node.expression; + const expression = node.expression; if (this.getCurrentDepth() <= 1 && expression.kind === ts.SyntaxKind.Identifier) { - var identifierName = ( expression).text; + const identifierName = ( expression).text; if (identifierName === "require") { // if we're calling (invoking) require, then it's not part of an import statement this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); @@ -46,5 +45,4 @@ class RequiresWalker extends Lint.ScopeAwareRuleWalker<{}> { super.visitCallExpression(node); } - } diff --git a/src/rules/oneLineRule.ts b/src/rules/oneLineRule.ts index c65945e235b..3f9874b74f8 100644 --- a/src/rules/oneLineRule.ts +++ b/src/rules/oneLineRule.ts @@ -12,12 +12,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ -var OPTION_BRACE = "check-open-brace"; -var OPTION_CATCH = "check-catch"; -var OPTION_ELSE = "check-else"; -var OPTION_WHITESPACE = "check-whitespace"; +const OPTION_BRACE = "check-open-brace"; +const OPTION_CATCH = "check-catch"; +const OPTION_ELSE = "check-else"; +const OPTION_WHITESPACE = "check-whitespace"; export class Rule extends Lint.Rules.AbstractRule { public static BRACE_FAILURE_STRING = "misplaced opening brace"; @@ -26,34 +26,34 @@ export class Rule extends Lint.Rules.AbstractRule { public static WHITESPACE_FAILURE_STRING = "missing whitespace"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var oneLineWalker = new OneLineWalker(sourceFile, this.getOptions()); + const oneLineWalker = new OneLineWalker(sourceFile, this.getOptions()); return this.applyWithWalker(oneLineWalker); } } class OneLineWalker extends Lint.RuleWalker { public visitIfStatement(node: ts.IfStatement) { - var sourceFile = node.getSourceFile(); - var thenStatement = node.thenStatement; + const sourceFile = node.getSourceFile(); + const thenStatement = node.thenStatement; if (thenStatement.kind === ts.SyntaxKind.Block) { - var expressionCloseParen = node.getChildAt(3); - var thenOpeningBrace = thenStatement.getChildAt(0); + const expressionCloseParen = node.getChildAt(3); + const thenOpeningBrace = thenStatement.getChildAt(0); this.handleOpeningBrace(expressionCloseParen, thenOpeningBrace); } - var elseStatement = node.elseStatement; + const elseStatement = node.elseStatement; if (elseStatement != null) { // find the else keyword - var elseKeyword = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.ElseKeyword); + const elseKeyword = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.ElseKeyword); if (elseStatement.kind === ts.SyntaxKind.Block) { - var elseOpeningBrace = elseStatement.getChildAt(0); + const elseOpeningBrace = elseStatement.getChildAt(0); this.handleOpeningBrace(elseKeyword, elseOpeningBrace); } if (this.hasOption(OPTION_ELSE)) { - var thenStatementEndLine = sourceFile.getLineAndCharacterOfPosition(thenStatement.getEnd()).line; - var elseKeywordLine = sourceFile.getLineAndCharacterOfPosition(elseKeyword.getStart()).line; + const thenStatementEndLine = sourceFile.getLineAndCharacterOfPosition(thenStatement.getEnd()).line; + const elseKeywordLine = sourceFile.getLineAndCharacterOfPosition(elseKeyword.getStart()).line; if (thenStatementEndLine !== elseKeywordLine) { - var failure = this.createFailure(elseKeyword.getStart(), elseKeyword.getWidth(), Rule.ELSE_FAILURE_STRING); + const failure = this.createFailure(elseKeyword.getStart(), elseKeyword.getWidth(), Rule.ELSE_FAILURE_STRING); this.addFailure(failure); } } @@ -63,29 +63,29 @@ class OneLineWalker extends Lint.RuleWalker { } public visitCatchClause(node: ts.CatchClause) { - var catchKeyword = node.getChildAt(0); - var catchOpeningBrace = node.block.getChildAt(0); + const catchKeyword = node.getChildAt(0); + const catchOpeningBrace = node.block.getChildAt(0); this.handleOpeningBrace(catchKeyword, catchOpeningBrace); super.visitCatchClause(node); } public visitTryStatement(node: ts.TryStatement) { - var sourceFile = node.getSourceFile(); - var catchClause = node.catchClause; + const sourceFile = node.getSourceFile(); + const catchClause = node.catchClause; // "visit" try block - var tryKeyword = node.getChildAt(0); - var tryBlock = node.tryBlock; - var tryOpeningBrace = tryBlock.getChildAt(0); + const tryKeyword = node.getChildAt(0); + const tryBlock = node.tryBlock; + const tryOpeningBrace = tryBlock.getChildAt(0); this.handleOpeningBrace(tryKeyword, tryOpeningBrace); if (this.hasOption(OPTION_CATCH) && catchClause != null) { - var tryClosingBrace = node.tryBlock.getChildAt(node.tryBlock.getChildCount() - 1); - var catchKeyword = catchClause.getChildAt(0); - var tryClosingBraceLine = sourceFile.getLineAndCharacterOfPosition(tryClosingBrace.getEnd()).line; - var catchKeywordLine = sourceFile.getLineAndCharacterOfPosition(catchKeyword.getStart()).line; + const tryClosingBrace = node.tryBlock.getChildAt(node.tryBlock.getChildCount() - 1); + const catchKeyword = catchClause.getChildAt(0); + const tryClosingBraceLine = sourceFile.getLineAndCharacterOfPosition(tryClosingBrace.getEnd()).line; + const catchKeywordLine = sourceFile.getLineAndCharacterOfPosition(catchKeyword.getStart()).line; if (tryClosingBraceLine !== catchKeywordLine) { - var failure = this.createFailure(catchKeyword.getStart(), catchKeyword.getWidth(), Rule.CATCH_FAILURE_STRING); + const failure = this.createFailure(catchKeyword.getStart(), catchKeyword.getWidth(), Rule.CATCH_FAILURE_STRING); this.addFailure(failure); } } @@ -108,12 +108,12 @@ class OneLineWalker extends Lint.RuleWalker { } public visitBinaryExpression(node: ts.BinaryExpression) { - var rightkind = node.right.kind; - var opkind = node.operatorToken.kind; + const rightkind = node.right.kind; + const opkind = node.operatorToken.kind; if (opkind === ts.SyntaxKind.EqualsToken && rightkind === ts.SyntaxKind.ObjectLiteralExpression) { - var equalsToken = node.getChildAt(1); - var openBraceToken = node.right.getChildAt(0); + const equalsToken = node.getChildAt(1); + const openBraceToken = node.right.getChildAt(0); this.handleOpeningBrace(equalsToken, openBraceToken); } @@ -121,59 +121,59 @@ class OneLineWalker extends Lint.RuleWalker { } public visitVariableDeclaration(node: ts.VariableDeclaration) { - var initializer = node.initializer; + const initializer = node.initializer; if (initializer != null && initializer.kind === ts.SyntaxKind.ObjectLiteralExpression) { - var equalsToken = node.getChildAt(1); - var openBraceToken = initializer.getChildAt(0); + const equalsToken = node.getChildAt(1); + const openBraceToken = initializer.getChildAt(0); this.handleOpeningBrace(equalsToken, openBraceToken); } super.visitVariableDeclaration(node); } public visitDoStatement(node: ts.DoStatement) { - var doKeyword = node.getChildAt(0); - var statement = node.statement; + const doKeyword = node.getChildAt(0); + const statement = node.statement; if (statement.kind === ts.SyntaxKind.Block) { - var openBraceToken = statement.getChildAt(0); + const openBraceToken = statement.getChildAt(0); this.handleOpeningBrace(doKeyword, openBraceToken); } super.visitDoStatement(node); } public visitModuleDeclaration(node: ts.ModuleDeclaration) { - var nameNode = node.name; - var body = node.body; + const nameNode = node.name; + const body = node.body; if (body.kind === ts.SyntaxKind.ModuleBlock) { - var openBraceToken = body.getChildAt(0); + const openBraceToken = body.getChildAt(0); this.handleOpeningBrace(nameNode, openBraceToken); } super.visitModuleDeclaration(node); } public visitEnumDeclaration(node: ts.EnumDeclaration) { - var nameNode = node.name; - var openBraceToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.OpenBraceToken); + const nameNode = node.name; + const openBraceToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.OpenBraceToken); this.handleOpeningBrace(nameNode, openBraceToken); super.visitEnumDeclaration(node); } public visitSwitchStatement(node: ts.SwitchStatement) { - var closeParenToken = node.getChildAt(3); - var openBraceToken = node.caseBlock.getChildAt(0); + const closeParenToken = node.getChildAt(3); + const openBraceToken = node.caseBlock.getChildAt(0); this.handleOpeningBrace(closeParenToken, openBraceToken); super.visitSwitchStatement(node); } public visitInterfaceDeclaration(node: ts.InterfaceDeclaration) { - var nameNode = node.name; - var openBraceToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.OpenBraceToken); + const nameNode = node.name; + const openBraceToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.OpenBraceToken); this.handleOpeningBrace(nameNode, openBraceToken); super.visitInterfaceDeclaration(node); } public visitClassDeclaration(node: ts.ClassDeclaration) { - var nameNode = node.name; - var openBraceToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.OpenBraceToken); + const nameNode = node.name; + const openBraceToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.OpenBraceToken); this.handleOpeningBrace(nameNode, openBraceToken); super.visitClassDeclaration(node); } @@ -194,23 +194,23 @@ class OneLineWalker extends Lint.RuleWalker { } public visitArrowFunction(node: ts.FunctionLikeDeclaration) { - var body = node.body; + const body = node.body; if (body != null && body.kind === ts.SyntaxKind.Block) { - var arrowToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.EqualsGreaterThanToken); - var openBraceToken = node.body.getChildAt(0); + const arrowToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.EqualsGreaterThanToken); + const openBraceToken = node.body.getChildAt(0); this.handleOpeningBrace(arrowToken, openBraceToken); } super.visitArrowFunction(node); } private handleFunctionLikeDeclaration(node: ts.FunctionLikeDeclaration) { - var body = node.body; + const body = node.body; if (body != null && body.kind === ts.SyntaxKind.Block) { - var openBraceToken = node.body.getChildAt(0); + const openBraceToken = node.body.getChildAt(0); if (node.type != null) { this.handleOpeningBrace(node.type, openBraceToken); } else { - var closeParenToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.CloseParenToken); + const closeParenToken = OneLineWalker.getFirstChildOfKind(node, ts.SyntaxKind.CloseParenToken); this.handleOpeningBrace(closeParenToken, openBraceToken); } } @@ -218,10 +218,10 @@ class OneLineWalker extends Lint.RuleWalker { private handleIterationStatement(node: ts.IterationStatement) { // last child is the statement, second to last child is the close paren - var closeParenToken = node.getChildAt(node.getChildCount() - 2); - var statement = node.statement; + const closeParenToken = node.getChildAt(node.getChildCount() - 2); + const statement = node.statement; if (statement.kind === ts.SyntaxKind.Block) { - var openBraceToken = statement.getChildAt(0); + const openBraceToken = statement.getChildAt(0); this.handleOpeningBrace(closeParenToken, openBraceToken); } } @@ -230,16 +230,18 @@ class OneLineWalker extends Lint.RuleWalker { if (previousNode == null || openBraceToken == null) { return; } - var sourceFile = previousNode.getSourceFile(); - var previousNodeLine = sourceFile.getLineAndCharacterOfPosition(previousNode.getEnd()).line; - var openBraceLine = sourceFile.getLineAndCharacterOfPosition(openBraceToken.getStart()).line; - var failure: Lint.RuleFailure; + + const sourceFile = previousNode.getSourceFile(); + const previousNodeLine = sourceFile.getLineAndCharacterOfPosition(previousNode.getEnd()).line; + const openBraceLine = sourceFile.getLineAndCharacterOfPosition(openBraceToken.getStart()).line; + let failure: Lint.RuleFailure; if (this.hasOption(OPTION_BRACE) && previousNodeLine !== openBraceLine) { failure = this.createFailure(openBraceToken.getStart(), openBraceToken.getWidth(), Rule.BRACE_FAILURE_STRING); } else if (this.hasOption(OPTION_WHITESPACE) && previousNode.getEnd() === openBraceToken.getStart()) { failure = this.createFailure(openBraceToken.getStart(), openBraceToken.getWidth(), Rule.WHITESPACE_FAILURE_STRING); } + if (failure) { this.addFailure(failure); } diff --git a/src/rules/quotemarkRule.ts b/src/rules/quotemarkRule.ts index 7f5a1356985..edf2fae3fca 100644 --- a/src/rules/quotemarkRule.ts +++ b/src/rules/quotemarkRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ enum QuoteMark { SINGLE_QUOTES, @@ -25,7 +25,7 @@ export class Rule extends Lint.Rules.AbstractRule { public isEnabled(): boolean { if (super.isEnabled()) { - var quoteMarkString = this.getOptions().ruleArguments[0]; + const quoteMarkString = this.getOptions().ruleArguments[0]; return (quoteMarkString === "single" || quoteMarkString === "double"); } @@ -43,7 +43,7 @@ class QuoteWalker extends Lint.RuleWalker { constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) { super(sourceFile, options); - var quoteMarkString = this.getOptions()[0]; + const quoteMarkString = this.getOptions()[0]; if (quoteMarkString === "single") { this.quoteMark = QuoteMark.SINGLE_QUOTES; } else { @@ -57,15 +57,15 @@ class QuoteWalker extends Lint.RuleWalker { } private handleNode(node: ts.Node) { - var failure: Lint.RuleFailure = null; + let failure: Lint.RuleFailure; if (node.kind === ts.SyntaxKind.StringLiteral) { - var text = node.getText(); - var width = node.getWidth(); - var position = node.getStart(); + const text = node.getText(); + const width = node.getWidth(); + const position = node.getStart(); - var firstCharacter = text.charAt(0); - var lastCharacter = text.charAt(text.length - 1); + const firstCharacter = text.charAt(0); + const lastCharacter = text.charAt(text.length - 1); if (this.quoteMark === QuoteMark.SINGLE_QUOTES) { if (firstCharacter !== "'" || lastCharacter !== "'") { @@ -78,7 +78,7 @@ class QuoteWalker extends Lint.RuleWalker { } } - if (failure) { + if (failure != null) { this.addFailure(failure); } } diff --git a/src/rules/radixRule.ts b/src/rules/radixRule.ts index d8e70252bad..c11b8328fb3 100644 --- a/src/rules/radixRule.ts +++ b/src/rules/radixRule.ts @@ -12,25 +12,24 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "missing radix parameter"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var radixWalker = new RadixWalker(sourceFile, this.getOptions()); + const radixWalker = new RadixWalker(sourceFile, this.getOptions()); return this.applyWithWalker(radixWalker); } } class RadixWalker extends Lint.RuleWalker { - public visitCallExpression(node: ts.CallExpression): void { - var expression = node.expression; - - if (expression.kind === ts.SyntaxKind.Identifier && - node.getFirstToken().getText() === "parseInt" && - node.arguments.length < 2) { + public visitCallExpression(node: ts.CallExpression) { + const expression = node.expression; + if (expression.kind === ts.SyntaxKind.Identifier + && node.getFirstToken().getText() === "parseInt" + && node.arguments.length < 2) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); } diff --git a/src/rules/semicolonRule.ts b/src/rules/semicolonRule.ts index f51b5141826..b4fc4470152 100644 --- a/src/rules/semicolonRule.ts +++ b/src/rules/semicolonRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "missing semicolon"; @@ -25,90 +25,77 @@ export class Rule extends Lint.Rules.AbstractRule { class SemicolonWalker extends Lint.RuleWalker { public visitVariableStatement(node: ts.VariableStatement) { this.checkSemicolonAt(node); - super.visitVariableStatement(node); } public visitExpressionStatement(node: ts.ExpressionStatement) { this.checkSemicolonAt(node); - super.visitExpressionStatement(node); } public visitReturnStatement(node: ts.ReturnStatement) { this.checkSemicolonAt(node); - super.visitReturnStatement(node); } public visitBreakStatement(node: ts.BreakOrContinueStatement) { this.checkSemicolonAt(node); - super.visitBreakStatement(node); } public visitContinueStatement(node: ts.BreakOrContinueStatement) { this.checkSemicolonAt(node); - super.visitContinueStatement(node); } public visitThrowStatement(node: ts.ThrowStatement) { this.checkSemicolonAt(node); - super.visitThrowStatement(node); } public visitImportDeclaration(node: ts.ImportDeclaration) { this.checkSemicolonAt(node); - super.visitImportDeclaration(node); } public visitImportEqualsDeclaration(node: ts.ImportEqualsDeclaration) { this.checkSemicolonAt(node); - super.visitImportEqualsDeclaration(node); } public visitDoStatement(node: ts.DoStatement) { this.checkSemicolonAt(node); - super.visitDoStatement(node); } public visitDebuggerStatement(node: ts.Statement) { this.checkSemicolonAt(node); - super.visitDebuggerStatement(node); } public visitPropertyDeclaration(node: ts.PropertyDeclaration) { this.checkSemicolonAt(node); - super.visitPropertyDeclaration(node); } public visitInterfaceDeclaration(node: ts.InterfaceDeclaration) { - node.members.forEach((member) => { + for (let member of node.members) { this.checkSemicolonAt(member); - }); - + } super.visitInterfaceDeclaration(node); } private checkSemicolonAt(node: ts.Node) { - var children = node.getChildren(this.getSourceFile()); - for (var i = 0; i < children.length; i++) { - var child = children[i]; + const children = node.getChildren(this.getSourceFile()); + for (let child of children) { if (child.kind === ts.SyntaxKind.SemicolonToken) { return; } } // no semicolon token was found, so add a failure at the given position - var sourceFile = this.getSourceFile(); - var position = node.getStart(sourceFile) + node.getWidth(sourceFile); + const sourceFile = this.getSourceFile(); + const position = node.getStart(sourceFile) + node.getWidth(sourceFile); this.addFailure(this.createFailure(Math.min(position, this.getLimit()), 0, Rule.FAILURE_STRING)); } } diff --git a/src/rules/sortObjectLiteralKeysRule.ts b/src/rules/sortObjectLiteralKeysRule.ts index 2e554da56e7..c3e2ec808e9 100644 --- a/src/rules/sortObjectLiteralKeysRule.ts +++ b/src/rules/sortObjectLiteralKeysRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "unsorted key '"; @@ -23,12 +23,11 @@ export class Rule extends Lint.Rules.AbstractRule { } class SortedKeyWalker extends Lint.RuleWalker { - // Stacks are used to maintain state while - // recursing through nested object literals. + // Stacks are used to maintain state while recursing through nested object literals. private lastSortedKeyStack: string[] = []; private sortedStateStack: boolean[] = []; - public visitObjectLiteralExpression(node: ts.ObjectLiteralExpression): void { + public visitObjectLiteralExpression(node: ts.ObjectLiteralExpression) { this.lastSortedKeyStack.push(""); // Char code 0; every string should be >= to this this.sortedStateStack.push(true); // Sorted state is always initially true super.visitObjectLiteralExpression(node); @@ -36,7 +35,7 @@ class SortedKeyWalker extends Lint.RuleWalker { this.sortedStateStack.pop(); } - public visitPropertyAssignment(node: ts.PropertyAssignment): void { + public visitPropertyAssignment(node: ts.PropertyAssignment) { const sortedState = this.sortedStateStack[this.sortedStateStack.length - 1]; // Skip remainder of object literal scan if a previous key was found // in an unsorted position. This ensures only one error is thrown at diff --git a/src/rules/switchDefaultRule.ts b/src/rules/switchDefaultRule.ts index 8e0188a85ab..01473230a65 100644 --- a/src/rules/switchDefaultRule.ts +++ b/src/rules/switchDefaultRule.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "switch statement doesn't include a 'default' case"; @@ -23,16 +23,13 @@ export class Rule extends Lint.Rules.AbstractRule { } export class SwitchDefaultWalker extends Lint.RuleWalker { - public visitSwitchStatement(node: ts.SwitchStatement) { - var hasDefaultCase = node.caseBlock.clauses.some((clause) => { - return clause.kind === ts.SyntaxKind.DefaultClause; - }); + const hasDefaultCase = node.caseBlock.clauses.some((clause) => clause.kind === ts.SyntaxKind.DefaultClause); + if (!hasDefaultCase) { - this.addFailure(this.createFailure(node.getStart(), - node.getWidth(), - Rule.FAILURE_STRING)); + this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); } + super.visitSwitchStatement(node); } } diff --git a/src/rules/tripleEqualsRule.ts b/src/rules/tripleEqualsRule.ts index ace237063e6..c38f1df8e4d 100644 --- a/src/rules/tripleEqualsRule.ts +++ b/src/rules/tripleEqualsRule.ts @@ -14,14 +14,14 @@ * limitations under the License. */ -var OPTION_ALLOW_NULL_CHECK = "allow-null-check"; +const OPTION_ALLOW_NULL_CHECK = "allow-null-check"; export class Rule extends Lint.Rules.AbstractRule { public static EQ_FAILURE_STRING = "== should be ==="; public static NEQ_FAILURE_STRING = "!= should be !=="; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var comparisonWalker = new ComparisonWalker(sourceFile, this.getOptions()); + const comparisonWalker = new ComparisonWalker(sourceFile, this.getOptions()); return this.applyWithWalker(comparisonWalker); } } @@ -31,7 +31,7 @@ class ComparisonWalker extends Lint.RuleWalker { public visitBinaryExpression(node: ts.BinaryExpression) { if (!this.isExpressionAllowed(node)) { - var position = node.getChildAt(1).getStart(); + const position = node.getChildAt(1).getStart(); this.handleOperatorToken(position, node.operatorToken.kind); } super.visitBinaryExpression(node); @@ -49,9 +49,9 @@ class ComparisonWalker extends Lint.RuleWalker { } private isExpressionAllowed(node: ts.BinaryExpression): boolean { - var nullKeyword = ts.SyntaxKind.NullKeyword; + const nullKeyword = ts.SyntaxKind.NullKeyword; - return this.hasOption(OPTION_ALLOW_NULL_CHECK) && - (node.left.kind === nullKeyword || node.right.kind === nullKeyword); + return this.hasOption(OPTION_ALLOW_NULL_CHECK) + && (node.left.kind === nullKeyword || node.right.kind === nullKeyword); } } diff --git a/src/rules/typedefRule.ts b/src/rules/typedefRule.ts index bc726e5b274..246e5014299 100644 --- a/src/rules/typedefRule.ts +++ b/src/rules/typedefRule.ts @@ -18,7 +18,7 @@ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "missing type declaration"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var typedefWalker = new TypedefWalker(sourceFile, this.getOptions()); + const typedefWalker = new TypedefWalker(sourceFile, this.getOptions()); return this.applyWithWalker(typedefWalker); } } @@ -50,7 +50,7 @@ class TypedefWalker extends Lint.RuleWalker { } public visitObjectLiteralExpression(node: ts.ObjectLiteralExpression) { - node.properties.forEach((property: ts.ObjectLiteralElement) => { + for (let property of node.properties) { switch (property.kind) { case ts.SyntaxKind.PropertyAssignment: this.visitPropertyAssignment( property); @@ -65,7 +65,7 @@ class TypedefWalker extends Lint.RuleWalker { this.visitSetAccessor( property); break; } - }); + } } public visitParameterDeclaration(node: ts.ParameterDeclaration) { @@ -104,9 +104,9 @@ class TypedefWalker extends Lint.RuleWalker { } public visitVariableDeclaration(node: ts.VariableDeclaration) { - // first parent is the VariableDeclarationList, grandparent would be the for-in statement - if (node.parent.parent.kind !== ts.SyntaxKind.ForInStatement && - node.parent.kind !== ts.SyntaxKind.CatchClause) { + // first parent is the variableDeclarationList, grandparent would be the for-in statement + if (node.parent.parent.kind !== ts.SyntaxKind.ForInStatement + && node.parent.kind !== ts.SyntaxKind.CatchClause) { this.checkTypeAnnotation("variable-declaration", node.name.getEnd(), node.type, node.name); } super.visitVariableDeclaration(node); diff --git a/src/rules/typedefWhitespaceRule.ts b/src/rules/typedefWhitespaceRule.ts index 430c876aa3e..5e05a0994ee 100644 --- a/src/rules/typedefWhitespaceRule.ts +++ b/src/rules/typedefWhitespaceRule.ts @@ -39,11 +39,12 @@ class TypedefWhitespaceWalker extends Lint.RuleWalker { } public visitIndexSignatureDeclaration(node: ts.IndexSignatureDeclaration) { - var indexParameter = node.parameters[0]; + const indexParameter = node.parameters[0]; if (indexParameter != null) { this.checkSpace("index-signature", indexParameter, indexParameter.type, indexParameter.name.getEnd()); } + super.visitIndexSignatureDeclaration(node); } @@ -84,36 +85,36 @@ class TypedefWhitespaceWalker extends Lint.RuleWalker { public checkSpace(option: string, node: ts.Node, typeNode: ts.TypeNode | ts.StringLiteral, positionBeforeColon: number) { if (this.hasOption(option) && typeNode != null && positionBeforeColon != null) { - var hasLeadingWhitespace: boolean; - var scanner = ts.createScanner(ts.ScriptTarget.ES5, false, node.getText()); + const scanner = ts.createScanner(ts.ScriptTarget.ES5, false, node.getText()); + let hasLeadingWhitespace: boolean; scanner.setTextPos(positionBeforeColon - node.getStart()); hasLeadingWhitespace = scanner.scan() === ts.SyntaxKind.WhitespaceTrivia; if (hasLeadingWhitespace !== (this.getOption(option) === "space")) { - var message = "expected " + this.getOption(option) + " in " + option; + const message = "expected " + this.getOption(option) + " in " + option; this.addFailure(this.createFailure(positionBeforeColon, 1, message)); } } } public hasOption(option: string) { - var allOptions = this.getOptions(); + const allOptions = this.getOptions(); if (allOptions == null || allOptions.length === 0) { return false; } - var options = allOptions[0]; + const options = allOptions[0]; return options == null || options[option] != null; } private getOption(option: string) { - var allOptions = this.getOptions(); + const allOptions = this.getOptions(); if (allOptions == null || allOptions.length === 0) { return null; } - var options = allOptions[0]; + const options = allOptions[0]; return options[option]; } } diff --git a/src/rules/useStrictRule.ts b/src/rules/useStrictRule.ts index 22a2879f638..ea5e1ffb0ea 100644 --- a/src/rules/useStrictRule.ts +++ b/src/rules/useStrictRule.ts @@ -18,7 +18,7 @@ export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING = "missing 'use strict'"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - var useStrictWalker = new UseStrictWalker(sourceFile, this.getOptions()); + const useStrictWalker = new UseStrictWalker(sourceFile, this.getOptions()); return this.applyWithWalker(useStrictWalker); } } @@ -34,17 +34,13 @@ class UseStrictWalker extends Lint.ScopeAwareRuleWalker<{}> { } public visitModuleDeclaration(node: ts.ModuleDeclaration) { - var modifiers = node.modifiers; - var hasDeclareModifier = (modifiers != null) && (modifiers.length > 0) && (modifiers[0].kind === ts.SyntaxKind.DeclareKeyword); - // current depth is 2: global scope and the scope created by this module - if (this.getCurrentDepth() === 2 && !hasDeclareModifier) { - if (this.hasOption(UseStrictWalker.OPTION_CHECK_MODULE) && - node.body != null && - node.body.kind === ts.SyntaxKind.ModuleBlock && - this.hasOption(UseStrictWalker.OPTION_CHECK_MODULE)) { - this.handleBlock(node, node.body); - } + if (this.getCurrentDepth() === 2 + && !Lint.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword) + && this.hasOption(UseStrictWalker.OPTION_CHECK_MODULE) + && node.body != null + && node.body.kind === ts.SyntaxKind.ModuleBlock) { + this.handleBlock(node, node.body); } super.visitModuleDeclaration(node); @@ -62,16 +58,16 @@ class UseStrictWalker extends Lint.ScopeAwareRuleWalker<{}> { } private handleBlock(node: ts.Declaration, block: ts.Block | ts.ModuleBlock) { - var isFailure = true; + let isFailure = true; if (block.statements != null && block.statements.length > 0) { - var firstStatement = block.statements[0]; + const firstStatement = block.statements[0]; if (firstStatement.kind === ts.SyntaxKind.ExpressionStatement) { - var firstChild = firstStatement.getChildAt(0); + const firstChild = firstStatement.getChildAt(0); - if (firstChild.kind === ts.SyntaxKind.StringLiteral && - ( firstChild).text === UseStrictWalker.USE_STRICT_STRING) { + if (firstChild.kind === ts.SyntaxKind.StringLiteral + && ( firstChild).text === UseStrictWalker.USE_STRICT_STRING) { isFailure = false; } } diff --git a/src/rules/whitespaceRule.ts b/src/rules/whitespaceRule.ts index 64e1e0998a2..7e0c7c2018f 100644 --- a/src/rules/whitespaceRule.ts +++ b/src/rules/whitespaceRule.ts @@ -51,7 +51,7 @@ class WhitespaceWalker extends Lint.SkippableTokenAwareRuleWalker { if (tokenKind === ts.SyntaxKind.WhitespaceTrivia || tokenKind === ts.SyntaxKind.NewLineTrivia) { lastShouldBeFollowedByWhitespace = false; } else if (lastShouldBeFollowedByWhitespace) { - var failure = this.createFailure(startPos, 1, Rule.FAILURE_STRING); + const failure = this.createFailure(startPos, 1, Rule.FAILURE_STRING); this.addFailure(failure); lastShouldBeFollowedByWhitespace = false; } @@ -191,6 +191,7 @@ class WhitespaceWalker extends Lint.SkippableTokenAwareRuleWalker { arrowChildNumber = i; } }); + // condition so we don't crash if the arrow is somehow missing if (arrowChildNumber !== -1) { const equalsGreaterThanToken = node.getChildAt(arrowChildNumber); @@ -208,10 +209,9 @@ class WhitespaceWalker extends Lint.SkippableTokenAwareRuleWalker { this.scanner.setTextPos(position); const nextTokenType = this.scanner.scan(); - if (nextTokenType !== ts.SyntaxKind.WhitespaceTrivia && - nextTokenType !== ts.SyntaxKind.NewLineTrivia && - nextTokenType !== ts.SyntaxKind.EndOfFileToken) { - + if (nextTokenType !== ts.SyntaxKind.WhitespaceTrivia + && nextTokenType !== ts.SyntaxKind.NewLineTrivia + && nextTokenType !== ts.SyntaxKind.EndOfFileToken) { this.addFailure(this.createFailure(position, 1, Rule.FAILURE_STRING)); } } diff --git a/src/tslint-cli.ts b/src/tslint-cli.ts index bd22389aa1d..0b9ad91335e 100644 --- a/src/tslint-cli.ts +++ b/src/tslint-cli.ts @@ -18,8 +18,8 @@ /// /// -var fs = require("fs"); -var optimist = require("optimist") +const fs = require("fs"); +const optimist = require("optimist") .usage("usage: $0") .check((argv: any) => { // at least one of file or help or version must be present @@ -54,17 +54,17 @@ var optimist = require("optimist") }, "t": { alias: "format", - describe: "output format (prose, json, verbose)", - default: "prose" + default: "prose", + describe: "output format (prose, json, verbose)" }, "v": { alias: "version", describe: "current version" } }); -var argv = optimist.argv; +const argv = optimist.argv; -var outputStream: any; +let outputStream: any; if (argv.o !== undefined) { outputStream = fs.createWriteStream(argv.o, { end: false, @@ -82,7 +82,7 @@ if (argv.v !== undefined) { if ("help" in argv) { outputStream.write(optimist.help()); - var outputString = ` + const outputString = ` tslint accepts the following commandline options: -f, --file: @@ -145,28 +145,28 @@ if (argv.c && !fs.existsSync(argv.c)) { process.exit(1); } -var processFile = (file: string) => { +const processFile = (file: string) => { if (!fs.existsSync(file)) { console.error("Unable to open file: " + file); process.exit(1); } - var contents = fs.readFileSync(file, "utf8"); - var configuration = Lint.Configuration.findConfiguration(argv.c, file); + const contents = fs.readFileSync(file, "utf8"); + const configuration = Lint.Configuration.findConfiguration(argv.c, file); if (configuration === undefined) { console.error("unable to find tslint configuration"); process.exit(1); } - var linter = new Lint.Linter(file, contents, { + const linter = new Lint.Linter(file, contents, { configuration: configuration, formatter: argv.t, - rulesDirectory: argv.r, - formattersDirectory: argv.s + formattersDirectory: argv.s, + rulesDirectory: argv.r }); - var lintResult = linter.lint(); + const lintResult = linter.lint(); if (lintResult.failureCount > 0) { outputStream.write(lintResult.output, () => { @@ -175,12 +175,12 @@ var processFile = (file: string) => { } }; -var fileOrFiles = argv.f; +const fileOrFiles = argv.f; if (typeof fileOrFiles === "string") { processFile(fileOrFiles); } else { - for (var ix in fileOrFiles) { + for (const ix in fileOrFiles) { if (fileOrFiles.hasOwnProperty(ix)) { processFile(fileOrFiles[ix]); } diff --git a/src/tslint.ts b/src/tslint.ts index d80712336dc..a2372d40d58 100644 --- a/src/tslint.ts +++ b/src/tslint.ts @@ -15,8 +15,8 @@ */ module Lint { - var path = require("path"); - var moduleDirectory = path.dirname(module.filename); + const path = require("path"); + const moduleDirectory = path.dirname(module.filename); export interface LintResult { failureCount: number; @@ -45,40 +45,42 @@ module Lint { } public lint(): LintResult { - var failures: RuleFailure[] = []; - var sourceFile = Lint.getSourceFile(this.fileName, this.source); + const failures: RuleFailure[] = []; + const sourceFile = Lint.getSourceFile(this.fileName, this.source); // walk the code first to find all the intervals where rules are disabled - var rulesWalker = new EnableDisableRulesWalker(sourceFile, {ruleName: "", disabledIntervals: []}); + const rulesWalker = new EnableDisableRulesWalker(sourceFile, { + disabledIntervals: [], + ruleName: "" + }); rulesWalker.walk(sourceFile); - var enableDisableRuleMap = rulesWalker.enableDisableRuleMap; + const enableDisableRuleMap = rulesWalker.enableDisableRuleMap; - var rulesDirectory = this.getRelativePath(this.options.rulesDirectory); - var configuration = this.options.configuration.rules; - var configuredRules = Lint.loadRules(configuration, enableDisableRuleMap, rulesDirectory); - for (var i = 0; i < configuredRules.length; ++i) { - var rule = configuredRules[i]; + const rulesDirectory = this.getRelativePath(this.options.rulesDirectory); + const configuration = this.options.configuration.rules; + const configuredRules = Lint.loadRules(configuration, enableDisableRuleMap, rulesDirectory); + for (let rule of configuredRules) { if (rule.isEnabled()) { - var ruleFailures = rule.apply(sourceFile); - ruleFailures.forEach((ruleFailure) => { + const ruleFailures = rule.apply(sourceFile); + for (let ruleFailure of ruleFailures) { if (!this.containsRule(failures, ruleFailure)) { failures.push(ruleFailure); } - }); + } } } - var formatter: Lint.IFormatter; - var formattersDirectory = this.getRelativePath(this.options.formattersDirectory); + let formatter: Lint.IFormatter; + const formattersDirectory = this.getRelativePath(this.options.formattersDirectory); - var Formatter = Lint.findFormatter(this.options.formatter, formattersDirectory); + const Formatter = Lint.findFormatter(this.options.formatter, formattersDirectory); if (Formatter) { formatter = new Formatter(); } else { throw new Error("formatter '" + this.options.formatter + "' not found"); } - var output = formatter.format(failures); + const output = formatter.format(failures); return { failureCount: failures.length, format: this.options.formatter, @@ -95,13 +97,7 @@ module Lint { } private containsRule(rules: RuleFailure[], rule: RuleFailure) { - for (var i = 0; i < rules.length; ++i) { - if (rules[i].equals(rule)) { - return true; - } - } - - return false; + return rules.some((r) => r.equals(rule)); } } } diff --git a/test/files/rules/noAny.test.ts b/test/files/rules/noAny.test.ts index 41278fec361..c7c7a796dc3 100644 --- a/test/files/rules/noAny.test.ts +++ b/test/files/rules/noAny.test.ts @@ -1,5 +1 @@ -var x: any; - -/*tslint:disable:no-any */ -var y: any; -/*tslint:enable:no-any */ +var x: any; // failure diff --git a/test/files/rules/novarkeyword.test.ts b/test/files/rules/novarkeyword.test.ts index 62a81e62124..b1348dfeecb 100644 --- a/test/files/rules/novarkeyword.test.ts +++ b/test/files/rules/novarkeyword.test.ts @@ -1,20 +1,16 @@ - -// Error -var foo; +var foo; // failure function tmp(t: any) { - var x = 3; + var x = 3; // failure } -var i, +var i, // failure j; -var [a, b] = [1, 2]; +var [a, b] = [1, 2]; // failure -// Valid declare var tmp2: any; - let bar; const qux; diff --git a/test/formatters/externalFormatterTest.ts b/test/formatters/externalFormatterTest.ts index f7a25aea6a6..b72621470bf 100644 --- a/test/formatters/externalFormatterTest.ts +++ b/test/formatters/externalFormatterTest.ts @@ -15,31 +15,32 @@ */ describe("External Formatter", () => { - var TEST_FILE = "formatters/externalFormatter.test.ts"; - var TEST_MODULE = "../test/files/formatters/simple"; - var sourceFile: ts.SourceFile, formatter: Lint.IFormatter; + const TEST_FILE = "formatters/externalFormatter.test.ts"; + const TEST_MODULE = "../test/files/formatters/simple"; + let sourceFile: ts.SourceFile; + let formatter: Lint.IFormatter; before(function() { - var Formatter = Lint.Test.getFormatter(TEST_MODULE); + const Formatter = Lint.Test.getFormatter(TEST_MODULE); sourceFile = Lint.Test.getSourceFile(TEST_FILE); formatter = new Formatter(); }); it("formats failures", () => { - var maxPosition = sourceFile.getFullWidth(); + const maxPosition = sourceFile.getFullWidth(); - var failures = [ + const failures = [ new Lint.RuleFailure(sourceFile, 0, 1, "first failure", "first-name"), new Lint.RuleFailure(sourceFile, 32, 36, "mid failure", "mid-name"), new Lint.RuleFailure(sourceFile, maxPosition - 1, maxPosition, "last failure", "last-name") ]; - var expectedResult = + const expectedResult = getPositionString(1, 1) + TEST_FILE + "\n" + getPositionString(2, 11) + TEST_FILE + "\n" + getPositionString(9, 2) + TEST_FILE + "\n"; - var actualResult = formatter.format(failures); + const actualResult = formatter.format(failures); assert.equal(actualResult, expectedResult); }); @@ -49,7 +50,7 @@ describe("External Formatter", () => { }); it("handles no failures", () => { - var result = formatter.format([]); + const result = formatter.format([]); assert.equal(result, ""); }); diff --git a/test/formatters/jsonFormatterTests.ts b/test/formatters/jsonFormatterTests.ts index e5f6d7d1e34..27baf87d01f 100644 --- a/test/formatters/jsonFormatterTests.ts +++ b/test/formatters/jsonFormatterTests.ts @@ -12,29 +12,30 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("JSON Formatter", () => { - var TEST_FILE = "formatters/jsonFormatter.test.ts"; - var sourceFile: ts.SourceFile; - var formatter: Lint.IFormatter; + const TEST_FILE = "formatters/jsonFormatter.test.ts"; + let sourceFile: ts.SourceFile; + let formatter: Lint.IFormatter; before(function() { - var Formatter = Lint.Test.getFormatter("json"); + const Formatter = Lint.Test.getFormatter("json"); sourceFile = Lint.Test.getSourceFile(TEST_FILE); formatter = new Formatter(); }); it("formats failures", () => { - var maxPosition = sourceFile.getFullWidth(); + const maxPosition = sourceFile.getFullWidth(); - var failures = [ + const failures = [ new Lint.RuleFailure(sourceFile, 0, 1, "first failure", "first-name"), new Lint.RuleFailure(sourceFile, maxPosition - 1, maxPosition, "last failure", "last-name"), new Lint.RuleFailure(sourceFile, 0, maxPosition, "full failure", "full-name") ]; - var expectedResult = [{ + /* tslint:disable:sort-object-literal-keys */ + const expectedResult = [{ name: TEST_FILE, failure: "first failure", startPosition: { @@ -79,13 +80,14 @@ describe("JSON Formatter", () => { }, ruleName: "full-name" }]; + /* tslint:enable:sort-object-literal-keys */ - var actualResult = JSON.parse(formatter.format(failures)); + const actualResult = JSON.parse(formatter.format(failures)); assert.deepEqual(actualResult, expectedResult); }); it("handles no failures", () => { - var result = JSON.parse(formatter.format([])); + const result = JSON.parse(formatter.format([])); assert.deepEqual(result, []); }); }); diff --git a/test/formatters/pmdFormatterTests.ts b/test/formatters/pmdFormatterTests.ts index 009a5d4fa8e..60623155803 100644 --- a/test/formatters/pmdFormatterTests.ts +++ b/test/formatters/pmdFormatterTests.ts @@ -15,26 +15,26 @@ */ describe("PMD Formatter", () => { - var TEST_FILE = "formatters/pmdFormatter.test.ts"; - var sourceFile: ts.SourceFile; - var formatter: Lint.IFormatter; + const TEST_FILE = "formatters/pmdFormatter.test.ts"; + let sourceFile: ts.SourceFile; + let formatter: Lint.IFormatter; before(function() { - var Formatter = Lint.Test.getFormatter("pmd"); + const Formatter = Lint.Test.getFormatter("pmd"); sourceFile = Lint.Test.getSourceFile(TEST_FILE); formatter = new Formatter(); }); it("formats failures", () => { - var maxPosition = sourceFile.getFullWidth(); + const maxPosition = sourceFile.getFullWidth(); - var failures = [ + const failures = [ new Lint.RuleFailure(sourceFile, 0, 1, "first failure", "first-name"), new Lint.RuleFailure(sourceFile, 2, 3, "&<>'\" should be escaped", "escape"), new Lint.RuleFailure(sourceFile, maxPosition - 1, maxPosition, "last failure", "last-name"), new Lint.RuleFailure(sourceFile, 0, maxPosition, "full failure", "full-name") ]; - var expectedResult = + const expectedResult = "" + "" + " " + @@ -58,7 +58,7 @@ describe("PMD Formatter", () => { }); it("handles no failures", () => { - var result = formatter.format([]); + const result = formatter.format([]); assert.deepEqual(result, ""); }); }); diff --git a/test/formatters/proseFormatterTests.ts b/test/formatters/proseFormatterTests.ts index 7502446b878..a0122be8233 100644 --- a/test/formatters/proseFormatterTests.ts +++ b/test/formatters/proseFormatterTests.ts @@ -15,40 +15,40 @@ */ describe("Prose Formatter", () => { - var TEST_FILE = "formatters/proseFormatter.test.ts"; - var sourceFile: ts.SourceFile; - var formatter: Lint.IFormatter; + const TEST_FILE = "formatters/proseFormatter.test.ts"; + let sourceFile: ts.SourceFile; + let formatter: Lint.IFormatter; before(function() { - var Formatter = Lint.Test.getFormatter("prose"); + const Formatter = Lint.Test.getFormatter("prose"); sourceFile = Lint.Test.getSourceFile(TEST_FILE); formatter = new Formatter(); }); it("formats failures", () => { - var maxPosition = sourceFile.getFullWidth(); + const maxPosition = sourceFile.getFullWidth(); - var failures = [ + const failures = [ new Lint.RuleFailure(sourceFile, 0, 1, "first failure", "first-name"), new Lint.RuleFailure(sourceFile, 32, 36, "mid failure", "mid-name"), new Lint.RuleFailure(sourceFile, maxPosition - 1, maxPosition, "last failure", "last-name") ]; - var expectedResult = + const expectedResult = TEST_FILE + getPositionString(1, 1) + "first failure\n" + TEST_FILE + getPositionString(2, 12) + "mid failure\n" + TEST_FILE + getPositionString(9, 2) + "last failure\n"; - var actualResult = formatter.format(failures); + const actualResult = formatter.format(failures); assert.equal(actualResult, expectedResult); }); it("handles no failures", () => { - var result = formatter.format([]); + const result = formatter.format([]); assert.equal(result, "\n"); }); function getPositionString(line: number, character: number) { - return "[" + line + ", " + character + "]: "; + return `[${line}, ${character}]: `; } }); diff --git a/test/formatters/verboseFormatterTests.ts b/test/formatters/verboseFormatterTests.ts index 94363341a23..951e7d7d583 100644 --- a/test/formatters/verboseFormatterTests.ts +++ b/test/formatters/verboseFormatterTests.ts @@ -12,43 +12,43 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("Verbose Formatter", () => { - var TEST_FILE = "formatters/proseFormatter.test.ts"; - var sourceFile: ts.SourceFile; - var formatter: Lint.IFormatter; + const TEST_FILE = "formatters/proseFormatter.test.ts"; + let sourceFile: ts.SourceFile; + let formatter: Lint.IFormatter; - before(function() { - var Formatter = Lint.Test.getFormatter("verbose"); + before(() => { + const Formatter = Lint.Test.getFormatter("verbose"); sourceFile = Lint.Test.getSourceFile(TEST_FILE); formatter = new Formatter(); }); it("formats failures", () => { - var maxPosition = sourceFile.getFullWidth(); + const maxPosition = sourceFile.getFullWidth(); - var failures = [ + const failures = [ new Lint.RuleFailure(sourceFile, 0, 1, "first failure", "first-name"), new Lint.RuleFailure(sourceFile, 32, 36, "mid failure", "mid-name"), new Lint.RuleFailure(sourceFile, maxPosition - 1, maxPosition, "last failure", "last-name") ]; - var expectedResult = + const expectedResult = "(first-name) " + TEST_FILE + getPositionString(1, 1) + "first failure\n" + "(mid-name) " + TEST_FILE + getPositionString(2, 12) + "mid failure\n" + "(last-name) " + TEST_FILE + getPositionString(9, 2) + "last failure\n"; - var actualResult = formatter.format(failures); + const actualResult = formatter.format(failures); assert.equal(actualResult, expectedResult); }); it("handles no failures", () => { - var result = formatter.format([]); + const result = formatter.format([]); assert.equal(result, "\n"); }); function getPositionString(line: number, character: number) { - return "[" + line + ", " + character + "]: "; + return `[${line}, ${character}]: `; } }); diff --git a/test/helper.ts b/test/helper.ts index 809e22f84a4..da39265cc95 100644 --- a/test/helper.ts +++ b/test/helper.ts @@ -15,38 +15,38 @@ */ module Lint.Test { - var fs = require("fs"); - var path = require("path"); + const fs = require("fs"); + const path = require("path"); export function getSourceFile(fileName: string): ts.SourceFile { - var relativePath = path.join("test", "files", fileName); - var source = fs.readFileSync(relativePath, "utf8"); + const relativePath = path.join("test", "files", fileName); + const source = fs.readFileSync(relativePath, "utf8"); return Lint.getSourceFile(fileName, source); } export function getRule(ruleName: string) { - var rulesDirectory = path.join(global.process.cwd(), "build/rules"); + const rulesDirectory = path.join(global.process.cwd(), "build/rules"); return Lint.findRule(ruleName, rulesDirectory); } export function getFormatter(formatterName: string) { - var formattersDirectory = path.join(global.process.cwd(), "build/formatters"); + const formattersDirectory = path.join(global.process.cwd(), "build/formatters"); return Lint.findFormatter(formatterName, formattersDirectory); } export function applyRuleOnFile(fileName: string, Rule: any, ruleValue: any = true): Lint.RuleFailure[] { - var sourceFile = getSourceFile(fileName); - var rule = new Rule("", ruleValue, []); + const sourceFile = getSourceFile(fileName); + const rule = new Rule("", ruleValue, []); return rule.apply(sourceFile); } // start and end are arrays with the first and second elements // being (one-indexed) line and character positions respectively export function createFailure(fileName: string, start: number[], end: number[], failure: string): Lint.RuleFailure { - var sourceFile = getSourceFile(fileName); - var startPosition = sourceFile.getPositionOfLineAndCharacter(start[0] - 1, start[1] - 1); - var endPosition = sourceFile.getPositionOfLineAndCharacter(end[0] - 1, end[1] - 1); + const sourceFile = getSourceFile(fileName); + const startPosition = sourceFile.getPositionOfLineAndCharacter(start[0] - 1, start[1] - 1); + const endPosition = sourceFile.getPositionOfLineAndCharacter(end[0] - 1, end[1] - 1); return new Lint.RuleFailure(sourceFile, startPosition, endPosition, failure, ""); } @@ -71,11 +71,11 @@ module Lint.Test { // assert whether a failure array contains the given failure export function assertContainsFailure(haystack: Lint.RuleFailure[], needle: Lint.RuleFailure) { - var haystackContainsNeedle = haystack.some((item) => item.equals(needle)); + const haystackContainsNeedle = haystack.some((item) => item.equals(needle)); if (!haystackContainsNeedle) { - var stringifiedNeedle = JSON.stringify(needle.toJson(), null, 2); - var stringifiedHaystack = JSON.stringify(haystack.map((hay) => hay.toJson()), null, 2); + const stringifiedNeedle = JSON.stringify(needle.toJson(), null, 2); + const stringifiedHaystack = JSON.stringify(haystack.map((hay) => hay.toJson()), null, 2); assert(false, "expected " + stringifiedNeedle + " within " + stringifiedHaystack); } diff --git a/test/ruleDisableEnableTests.ts b/test/ruleDisableEnableTests.ts index 0372e9b5b91..f9d7d6b04e4 100644 --- a/test/ruleDisableEnableTests.ts +++ b/test/ruleDisableEnableTests.ts @@ -12,52 +12,51 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ -var fs = require("fs"); +const fs = require("fs"); +const path = require("path"); describe("Enable and Disable Rules", () => { - var path = require("path"); - it("is enabled and disabled in all the right places", () => { - var validConfiguration = {rules: { + const validConfiguration = {rules: { "variable-name": true, "quotemark": [true, "double"] }}; - var relativePath = path.join("test", "files", "rules/enabledisable.test.ts"); - var source = fs.readFileSync(relativePath, "utf8"); + const relativePath = path.join("test", "files", "rules/enabledisable.test.ts"); + const source = fs.readFileSync(relativePath, "utf8"); - var options: Lint.ILinterOptions = { - formatter: "json", + const options: Lint.ILinterOptions = { configuration: validConfiguration, - rulesDirectory: null, - formattersDirectory: null + formatter: "json", + formattersDirectory: null, + rulesDirectory: null }; - var QuotemarkRule = Lint.Test.getRule("quotemark"); - var VariableNameRule = Lint.Test.getRule("variable-name"); + const QuotemarkRule = Lint.Test.getRule("quotemark"); + const variableNameRule = Lint.Test.getRule("variable-name"); - var quotemarkFailure = Lint.Test.createFailuresOnFile("rules/enabledisable.test.ts", QuotemarkRule.DOUBLE_QUOTE_FAILURE); - var variableNameFailure = Lint.Test.createFailuresOnFile("rules/enabledisable.test.ts", VariableNameRule.FAILURE_STRING); + const quotemarkFailure = Lint.Test.createFailuresOnFile("rules/enabledisable.test.ts", QuotemarkRule.DOUBLE_QUOTE_FAILURE); + const variableNameFailure = Lint.Test.createFailuresOnFile("rules/enabledisable.test.ts", variableNameRule.FAILURE_STRING); - var expectedFailure1 = variableNameFailure([2, 5], [2, 10]); - var expectedFailure2 = variableNameFailure([10, 5], [10, 10]); + const expectedFailure1 = variableNameFailure([2, 5], [2, 10]); + const expectedFailure2 = variableNameFailure([10, 5], [10, 10]); - var expectedFailure3 = quotemarkFailure([2, 13], [2, 19]); - var expectedFailure4 = quotemarkFailure([8, 13], [8, 19]); - var expectedFailure5 = quotemarkFailure([10, 13], [10, 19]); - var expectedFailure6 = quotemarkFailure([16, 13], [16, 19]); + const expectedFailure3 = quotemarkFailure([2, 13], [2, 19]); + const expectedFailure4 = quotemarkFailure([8, 13], [8, 19]); + const expectedFailure5 = quotemarkFailure([10, 13], [10, 19]); + const expectedFailure6 = quotemarkFailure([16, 13], [16, 19]); - var ll = new Lint.Linter(relativePath, source, options); - var result = ll.lint(); - var parsedResult = JSON.parse(result.output); - var actualFailures: Lint.RuleFailure[] = []; - parsedResult.forEach((failure: any) => { - var startArray = [failure.startPosition.line + 1, failure.startPosition.character + 1]; - var endArray = [failure.endPosition.line + 1, failure.endPosition.character + 1]; + const ll = new Lint.Linter(relativePath, source, options); + const result = ll.lint(); + const parsedResult = JSON.parse(result.output); + const actualFailures: Lint.RuleFailure[] = []; + for (let failure of parsedResult) { + const startArray = [failure.startPosition.line + 1, failure.startPosition.character + 1]; + const endArray = [failure.endPosition.line + 1, failure.endPosition.character + 1]; actualFailures.push(Lint.Test.createFailure("rules/enabledisable.test.ts", startArray, endArray, failure.failure)); - }); + } Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); diff --git a/test/ruleLoaderTests.ts b/test/ruleLoaderTests.ts index 5a6a4df3297..d540155d127 100644 --- a/test/ruleLoaderTests.ts +++ b/test/ruleLoaderTests.ts @@ -15,11 +15,11 @@ */ describe("Rule Loader", () => { - var path = require("path"); - var rulesDirectory = path.join(global.process.cwd(), "build/rules"); + const path = require("path"); + const rulesDirectory = path.join(global.process.cwd(), "build/rules"); it("loads core rules", () => { - var validConfiguration: {[name: string]: any} = { + const validConfiguration: {[name: string]: any} = { "forin": false, "quotemark": "single", "eofline": true, @@ -27,29 +27,29 @@ describe("Rule Loader", () => { "no-debugger": true }; - var rules = Lint.loadRules(validConfiguration, {}, rulesDirectory); + const rules = Lint.loadRules(validConfiguration, {}, rulesDirectory); assert.equal(rules.length, 5); }); it("skips invalid rules", () => { - var invalidConfiguration: {[name: string]: any} = { + const invalidConfiguration: {[name: string]: any} = { "invalidConfig1": true, "invalidConfig2": false }; - var rules = Lint.loadRules(invalidConfiguration, {}, rulesDirectory); + const rules = Lint.loadRules(invalidConfiguration, {}, rulesDirectory); assert.deepEqual(rules, []); }); it("doesn't ignore leading or trailing underscores or dashes", () => { - var invalidConfiguration: {[name: string]: any} = { + const invalidConfiguration: {[name: string]: any} = { "_indent": 6, "forin_": true, "-quotemark": "single", "eofline-": true }; - var rules = Lint.loadRules(invalidConfiguration, {}, rulesDirectory); + const rules = Lint.loadRules(invalidConfiguration, {}, rulesDirectory); assert.deepEqual(rules, []); }); }); diff --git a/test/rules/alignRuleTests.ts b/test/rules/alignRuleTests.ts index 49234e17468..8a135a036f1 100644 --- a/test/rules/alignRuleTests.ts +++ b/test/rules/alignRuleTests.ts @@ -12,54 +12,50 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("", () => { + const fileName = "rules/align.test.ts"; + const AlignRule = Lint.Test.getRule("align"); it("ensures that parameters in function signatures are aligned", () => { - var fileName = "rules/align.test.ts"; - var AlignRule = Lint.Test.getRule("align"); - var options = [true, AlignRule.PARAMETERS_OPTION]; - var failureString = AlignRule.PARAMETERS_OPTION + AlignRule.FAILURE_STRING_SUFFIX; - var failure = Lint.Test.createFailuresOnFile(fileName, failureString); - var expectedFailures = [ - failure([2, 1], [2, 10]), - failure([7, 1], [7, 10]), - failure([12, 30], [12, 39]), - failure([19, 28], [19, 37]), - failure([26, 34], [26, 45]), - failure([32, 31], [32, 39]) + const options = [true, AlignRule.PARAMETERS_OPTION]; + const failureString = AlignRule.PARAMETERS_OPTION + AlignRule.FAILURE_STRING_SUFFIX; + const createFailure = Lint.Test.createFailuresOnFile(fileName, failureString); + const expectedFailures = [ + createFailure([2, 1], [2, 10]), + createFailure([7, 1], [7, 10]), + createFailure([12, 30], [12, 39]), + createFailure([19, 28], [19, 37]), + createFailure([26, 34], [26, 45]), + createFailure([32, 31], [32, 39]) ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, AlignRule, options); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, AlignRule, options); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); it("ensures that arguments in function calls are aligned", () => { - var fileName = "rules/align.test.ts"; - var AlignRule = Lint.Test.getRule("align"); - var options = [true, AlignRule.ARGUMENTS_OPTION]; - var failureString = AlignRule.ARGUMENTS_OPTION + AlignRule.FAILURE_STRING_SUFFIX; - var failure = Lint.Test.createFailuresOnFile(fileName, failureString); - var expectedFailures = [ - failure([65, 5], [65, 11]), - failure([72, 9], [72, 10]), - failure([83, 14], [83, 20]) + const options = [true, AlignRule.ARGUMENTS_OPTION]; + const failureString = AlignRule.ARGUMENTS_OPTION + AlignRule.FAILURE_STRING_SUFFIX; + const createFailure = Lint.Test.createFailuresOnFile(fileName, failureString); + const expectedFailures = [ + createFailure([65, 5], [65, 11]), + createFailure([72, 9], [72, 10]), + createFailure([83, 14], [83, 20]) ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, AlignRule, options); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, AlignRule, options); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); it("ensures that statements at the same nesting level are aligned", () => { - var fileName = "rules/align.test.ts"; - var AlignRule = Lint.Test.getRule("align"); - var options = [true, AlignRule.STATEMENTS_OPTION]; - var failureString = AlignRule.STATEMENTS_OPTION + AlignRule.FAILURE_STRING_SUFFIX; - var failure = Lint.Test.createFailuresOnFile(fileName, failureString); - var expectedFailures = [ - failure([119, 6], [119, 16]), - failure([127, 8], [127, 18]) + const options = [true, AlignRule.STATEMENTS_OPTION]; + const failureString = AlignRule.STATEMENTS_OPTION + AlignRule.FAILURE_STRING_SUFFIX; + const createFailure = Lint.Test.createFailuresOnFile(fileName, failureString); + const expectedFailures = [ + createFailure([119, 6], [119, 16]), + createFailure([127, 8], [127, 18]) ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, AlignRule, options); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, AlignRule, options); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); }); diff --git a/test/rules/banRuleTests.ts b/test/rules/banRuleTests.ts index e98392d6d79..0ddee529890 100644 --- a/test/rules/banRuleTests.ts +++ b/test/rules/banRuleTests.ts @@ -12,15 +12,15 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("", () => { - it("bans access to specified functions", () => { - var fileName = "rules/ban.test.ts"; - var BanRule = Lint.Test.getRule("ban"); - var dirFailure = Lint.Test.createFailuresOnFile(fileName, BanRule.FAILURE_STRING_PART + "window.toString")([2, 1], [2, 16]); + const fileName = "rules/ban.test.ts"; + const BanRule = Lint.Test.getRule("ban"); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, BanRule, [true, ["window", "toString"]]); + it("bans access to specified functions", () => { + const dirFailure = Lint.Test.createFailuresOnFile(fileName, BanRule.FAILURE_STRING_PART + "window.toString")([2, 1], [2, 16]); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, BanRule, [true, ["window", "toString"]]); Lint.Test.assertContainsFailure(actualFailures, dirFailure); }); }); diff --git a/test/rules/classNameRuleTests.ts b/test/rules/classNameRuleTests.ts index 32e9ba85f6f..51591516bc7 100644 --- a/test/rules/classNameRuleTests.ts +++ b/test/rules/classNameRuleTests.ts @@ -12,17 +12,17 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("", () => { - var ClassNameRule = Lint.Test.getRule("class-name"); + const ClassNameRule = Lint.Test.getRule("class-name"); + const fileName = "rules/classname.test.ts"; it("ensures class names are always pascal-cased", () => { - var fileName = "rules/classname.test.ts"; - var createFailure = Lint.Test.createFailuresOnFile(fileName, ClassNameRule.FAILURE_STRING); - var expectedFailure1 = createFailure([5, 7], [5, 23]); - var expectedFailure2 = createFailure([9, 7], [9, 33]); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, ClassNameRule); + const createFailure = Lint.Test.createFailuresOnFile(fileName, ClassNameRule.FAILURE_STRING); + const expectedFailure1 = createFailure([5, 7], [5, 23]); + const expectedFailure2 = createFailure([9, 7], [9, 33]); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, ClassNameRule); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); diff --git a/test/rules/commentFormatRuleTests.ts b/test/rules/commentFormatRuleTests.ts index f179fbfcfae..bf5e8776a44 100644 --- a/test/rules/commentFormatRuleTests.ts +++ b/test/rules/commentFormatRuleTests.ts @@ -12,25 +12,25 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("", () => { - var CommentFormatRule = Lint.Test.getRule("comment-format"); + const CommentFormatRule = Lint.Test.getRule("comment-format"); it("ensures comments start with a space and a lowercase letter", () => { - var fileName = "rules/comment-lower.test.ts"; - var createLowercaseFailure = Lint.Test.createFailuresOnFile(fileName, CommentFormatRule.LOWERCASE_FAILURE); - var createLeadingSpaceFailure = Lint.Test.createFailuresOnFile(fileName, CommentFormatRule.LEADING_SPACE_FAILURE); - var expectedFailure1 = createLowercaseFailure([5, 27], [5, 73]); - var expectedFailure2 = createLowercaseFailure([6, 11], [6, 84]); - var expectedFailure3 = createLeadingSpaceFailure([6, 11], [6, 84]); - var expectedFailure4 = createLeadingSpaceFailure([7, 32], [7, 57]); + const fileName = "rules/comment-lower.test.ts"; + const createLowercaseFailure = Lint.Test.createFailuresOnFile(fileName, CommentFormatRule.LOWERCASE_FAILURE); + const createLeadingSpaceFailure = Lint.Test.createFailuresOnFile(fileName, CommentFormatRule.LEADING_SPACE_FAILURE); + const expectedFailure1 = createLowercaseFailure([5, 27], [5, 73]); + const expectedFailure2 = createLowercaseFailure([6, 11], [6, 84]); + const expectedFailure3 = createLeadingSpaceFailure([6, 11], [6, 84]); + const expectedFailure4 = createLeadingSpaceFailure([7, 32], [7, 57]); - var options = [true, + const options = [true, "check-space", "check-lowercase" ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, CommentFormatRule, options); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, CommentFormatRule, options); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); @@ -40,19 +40,19 @@ describe("", () => { }); it("ensures comments start with a space and a uppercase letter", () => { - var fileName = "rules/comment-upper.test.ts"; - var createUppercaseFailure = Lint.Test.createFailuresOnFile(fileName, CommentFormatRule.UPPERCASE_FAILURE); - var createLeadingSpaceFailure = Lint.Test.createFailuresOnFile(fileName, CommentFormatRule.LEADING_SPACE_FAILURE); - var expectedFailure1 = createUppercaseFailure([5, 27], [5, 73]); - var expectedFailure2 = createUppercaseFailure([6, 11], [6, 84]); - var expectedFailure3 = createLeadingSpaceFailure([6, 11], [6, 84]); - var expectedFailure4 = createLeadingSpaceFailure([7, 32], [7, 57]); + const fileName = "rules/comment-upper.test.ts"; + const createUppercaseFailure = Lint.Test.createFailuresOnFile(fileName, CommentFormatRule.UPPERCASE_FAILURE); + const createLeadingSpaceFailure = Lint.Test.createFailuresOnFile(fileName, CommentFormatRule.LEADING_SPACE_FAILURE); + const expectedFailure1 = createUppercaseFailure([5, 27], [5, 73]); + const expectedFailure2 = createUppercaseFailure([6, 11], [6, 84]); + const expectedFailure3 = createLeadingSpaceFailure([6, 11], [6, 84]); + const expectedFailure4 = createLeadingSpaceFailure([7, 32], [7, 57]); - var options = [true, + const options = [true, "check-space", "check-uppercase" ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, CommentFormatRule, options); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, CommentFormatRule, options); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); diff --git a/test/rules/curlyRuleTests.ts b/test/rules/curlyRuleTests.ts index b0d569bae00..75403fdcd0e 100644 --- a/test/rules/curlyRuleTests.ts +++ b/test/rules/curlyRuleTests.ts @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("", () => { const fileName = "rules/curly.test.ts"; diff --git a/test/rules/eofLineRuleTests.ts b/test/rules/eofLineRuleTests.ts index 90f27d3cacf..796e50c638a 100644 --- a/test/rules/eofLineRuleTests.ts +++ b/test/rules/eofLineRuleTests.ts @@ -12,16 +12,16 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("", () => { - it("ensures a trailing newline at EOF", () => { - var fileName = "rules/eofline.test.ts"; - var EofLineRule = Lint.Test.getRule("eofline"); - var failureString = EofLineRule.FAILURE_STRING; + const EofLineRule = Lint.Test.getRule("eofline"); + const fileName = "rules/eofline.test.ts"; + const failureString = EofLineRule.FAILURE_STRING; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, EofLineRule); - var expectedFailure = Lint.Test.createFailure(fileName, [4, 38], [4, 38], failureString); + it("ensures a trailing newline at EOF", () => { + const actualFailures = Lint.Test.applyRuleOnFile(fileName, EofLineRule); + const expectedFailure = Lint.Test.createFailure(fileName, [4, 38], [4, 38], failureString); assert.equal(actualFailures.length, 1); assert.isTrue(actualFailures[0].equals(expectedFailure)); diff --git a/test/rules/forInRuleTests.ts b/test/rules/forInRuleTests.ts index e0598ae6d39..d27e9f81176 100644 --- a/test/rules/forInRuleTests.ts +++ b/test/rules/forInRuleTests.ts @@ -15,14 +15,16 @@ */ describe("", () => { + const ForInRule = Lint.Test.getRule("forin"); + const fileName = "rules/forin.test.ts"; + const failureString = ForInRule.FAILURE_STRING; + it("enforces filtering for the body of a for...in statement", () => { - var fileName = "rules/forin.test.ts"; - var ForInRule = Lint.Test.getRule("forin"); - var failureString = ForInRule.FAILURE_STRING; - var firstFailure = Lint.Test.createFailure(fileName, [2, 5], [4, 6], failureString); - var secondFailure = Lint.Test.createFailure(fileName, [6, 5], [11, 6], failureString); - var expectedFailures = [firstFailure, secondFailure]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, ForInRule); + const expectedFailures = [ + Lint.Test.createFailure(fileName, [2, 5], [4, 6], failureString), + Lint.Test.createFailure(fileName, [6, 5], [11, 6], failureString) + ]; + const actualFailures = Lint.Test.applyRuleOnFile(fileName, ForInRule); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); diff --git a/test/rules/indentRuleTests.ts b/test/rules/indentRuleTests.ts index 6f73c9deb5a..fb2087037c4 100644 --- a/test/rules/indentRuleTests.ts +++ b/test/rules/indentRuleTests.ts @@ -15,10 +15,10 @@ */ describe("", () => { - var IndentRule = Lint.Test.getRule("indent"); - var failureStringTabs = IndentRule.FAILURE_STRING_TABS; - var failureStringSpaces = IndentRule.FAILURE_STRING_SPACES; - var actualFailures: Lint.RuleFailure[]; + const IndentRule = Lint.Test.getRule("indent"); + const failureStringTabs = IndentRule.FAILURE_STRING_TABS; + const failureStringSpaces = IndentRule.FAILURE_STRING_SPACES; + let actualFailures: Lint.RuleFailure[]; function expectFailure(failure: Lint.RuleFailure) { Lint.Test.assertContainsFailure(actualFailures, failure); @@ -26,7 +26,7 @@ describe("", () => { // Checks only that the indent character is the specified one, *NOT* the size of the indent describe("on a tab-indented file", () => { - var fileName = "rules/indentwith_tabs.test.ts"; + const fileName = "rules/indentwith_tabs.test.ts"; before(() => { actualFailures = Lint.Test.applyRuleOnFile(fileName, IndentRule, [true, "tabs"]); @@ -73,13 +73,11 @@ describe("", () => { expectFailure(Lint.Test.createFailure(fileName, [119, 1], [119, 9], failureStringTabs)); expectFailure(Lint.Test.createFailure(fileName, [121, 1], [121, 5], failureStringTabs)); }); - }); - // Checks only that the indent character is the specified one, *NOT* the size of the indent describe("on a space-indented file", () => { - var fileName = "rules/indentwith_spaces.test.ts"; + const fileName = "rules/indentwith_spaces.test.ts"; before(() => { actualFailures = Lint.Test.applyRuleOnFile(fileName, IndentRule, [true, "spaces"]); @@ -126,7 +124,5 @@ describe("", () => { expectFailure(Lint.Test.createFailure(fileName, [119, 1], [119, 3], failureStringSpaces)); expectFailure(Lint.Test.createFailure(fileName, [121, 1], [121, 2], failureStringSpaces)); }); - }); - }); diff --git a/test/rules/interfaceNameRuleTests.ts b/test/rules/interfaceNameRuleTests.ts index 86df951ca7e..c3eecbbdd2c 100644 --- a/test/rules/interfaceNameRuleTests.ts +++ b/test/rules/interfaceNameRuleTests.ts @@ -15,13 +15,13 @@ */ describe("", () => { - var InterfaceNameRule = Lint.Test.getRule("interface-name"); + const InterfaceNameRule = Lint.Test.getRule("interface-name"); + const fileName = "rules/interfacename.test.ts"; it("ensures interface names always start with a capital I", () => { - var fileName = "rules/interfacename.test.ts"; - var createFailure = Lint.Test.createFailuresOnFile(fileName, InterfaceNameRule.FAILURE_STRING); - var expectedFailure1 = createFailure([5, 11], [5, 32]); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, InterfaceNameRule); + const createFailure = Lint.Test.createFailuresOnFile(fileName, InterfaceNameRule.FAILURE_STRING); + const expectedFailure1 = createFailure([5, 11], [5, 32]); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, InterfaceNameRule); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); assert.lengthOf(actualFailures, 1); diff --git a/test/rules/jsdocFormatRuleTests.ts b/test/rules/jsdocFormatRuleTests.ts index eb7627116bd..d99e64b8139 100644 --- a/test/rules/jsdocFormatRuleTests.ts +++ b/test/rules/jsdocFormatRuleTests.ts @@ -15,21 +15,21 @@ */ describe("", () => { - var JsdocFormatRule = Lint.Test.getRule("jsdoc-format"); + const JsdocFormatRule = Lint.Test.getRule("jsdoc-format"); it("ensures jsdoc comments have properly lined up asterisks and start with spaces", () => { - var fileName = "rules/jsdoc.test.ts"; - var createFormatFailure = Lint.Test.createFailuresOnFile(fileName, JsdocFormatRule.FORMAT_FAILURE_STRING); - var createAlignmentFailure = Lint.Test.createFailuresOnFile(fileName, JsdocFormatRule.ALIGNMENT_FAILURE_STRING); - var expectedFailure1 = createFormatFailure([28, 1], [28, 40]); - var expectedFailure2 = createAlignmentFailure([34, 1], [34, 6]); - var expectedFailure3 = createFormatFailure([38, 1], [38, 8]); - var expectedFailure4 = createFormatFailure([42, 1], [42, 7]); - var expectedFailure5 = createAlignmentFailure([47, 1], [47, 19]); - var expectedFailure6 = createFormatFailure([50, 5], [50, 26]); - var expectedFailure7 = createFormatFailure([52, 5], [52, 32]); + const fileName = "rules/jsdoc.test.ts"; + const createFormatFailure = Lint.Test.createFailuresOnFile(fileName, JsdocFormatRule.FORMAT_FAILURE_STRING); + const createAlignmentFailure = Lint.Test.createFailuresOnFile(fileName, JsdocFormatRule.ALIGNMENT_FAILURE_STRING); + const expectedFailure1 = createFormatFailure([28, 1], [28, 40]); + const expectedFailure2 = createAlignmentFailure([34, 1], [34, 6]); + const expectedFailure3 = createFormatFailure([38, 1], [38, 8]); + const expectedFailure4 = createFormatFailure([42, 1], [42, 7]); + const expectedFailure5 = createAlignmentFailure([47, 1], [47, 19]); + const expectedFailure6 = createFormatFailure([50, 5], [50, 26]); + const expectedFailure7 = createFormatFailure([52, 5], [52, 32]); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, JsdocFormatRule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, JsdocFormatRule); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); @@ -42,8 +42,8 @@ describe("", () => { }); it("ensures jsdoc commments can have have windows line endings", () => { - var fileName = "rules/jsdoc-windows.test.ts"; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, JsdocFormatRule); + const fileName = "rules/jsdoc-windows.test.ts"; + const actualFailures = Lint.Test.applyRuleOnFile(fileName, JsdocFormatRule); assert.lengthOf(actualFailures, 0); }); }); diff --git a/test/rules/labelPositionRuleTests.ts b/test/rules/labelPositionRuleTests.ts index 45ec1828e83..d04d1c2f0a4 100644 --- a/test/rules/labelPositionRuleTests.ts +++ b/test/rules/labelPositionRuleTests.ts @@ -15,15 +15,16 @@ */ describe("", () => { + const LabelPositionRule = Lint.Test.getRule("label-position"); + const fileName = "rules/labelpos.test.ts"; + it("enforces that labels are correctly positioned", () => { - var fileName = "rules/labelpos.test.ts"; - var LabelPositionRule = Lint.Test.getRule("label-position"); - var createFailure = Lint.Test.createFailuresOnFile(fileName, LabelPositionRule.FAILURE_STRING); - var expectedFailures: Lint.RuleFailure[] = [ + const createFailure = Lint.Test.createFailuresOnFile(fileName, LabelPositionRule.FAILURE_STRING); + const expectedFailures: Lint.RuleFailure[] = [ createFailure([2, 5], [2, 9]), createFailure([5, 5], [5, 9]) ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, LabelPositionRule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, LabelPositionRule); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); diff --git a/test/rules/labelUndefinedRuleTests.ts b/test/rules/labelUndefinedRuleTests.ts index 92d3c45c7c8..8577272b708 100644 --- a/test/rules/labelUndefinedRuleTests.ts +++ b/test/rules/labelUndefinedRuleTests.ts @@ -15,18 +15,18 @@ */ describe("", () => { - it("forbids the use of undefined labels", () => { - var fileName = "rules/label-undefined.test.ts"; - var LabelUndefinedRule = Lint.Test.getRule("label-undefined"); - var failureString = LabelUndefinedRule.FAILURE_STRING; + const LabelUndefinedRule = Lint.Test.getRule("label-undefined"); + const fileName = "rules/label-undefined.test.ts"; + const failureString = LabelUndefinedRule.FAILURE_STRING; - var expectedFailures: Lint.RuleFailure[] = [ + it("forbids the use of undefined labels", () => { + const expectedFailures: Lint.RuleFailure[] = [ Lint.Test.createFailure(fileName, [6, 9], [6, 14], failureString + "lab1'"), Lint.Test.createFailure(fileName, [13, 9], [13, 17], failureString + "lab2'"), Lint.Test.createFailure(fileName, [27, 17], [27, 22], failureString + "lab3'"), Lint.Test.createFailure(fileName, [36, 9], [36, 17], failureString + "lab4'") ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, LabelUndefinedRule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, LabelUndefinedRule); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); diff --git a/test/rules/maxLineLengthRuleTests.ts b/test/rules/maxLineLengthRuleTests.ts index 4cc6de6ed66..ec2c3dd8719 100644 --- a/test/rules/maxLineLengthRuleTests.ts +++ b/test/rules/maxLineLengthRuleTests.ts @@ -15,11 +15,12 @@ */ describe("", () => { + const MaxLineLengthRule = Lint.Test.getRule("max-line-length"); + const fileName = "rules/maxlen.test.ts"; + it("enforces a maximum line length", () => { - var fileName = "rules/maxlen.test.ts"; - var MaxLineLengthRule = Lint.Test.getRule("max-line-length"); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, MaxLineLengthRule, [true, 140]); - var expectedFailures = [ + const actualFailures = Lint.Test.applyRuleOnFile(fileName, MaxLineLengthRule, [true, 140]); + const expectedFailures = [ Lint.Test.createFailure(fileName, [2, 1], [2, 165], MaxLineLengthRule.FAILURE_STRING + "140") ]; diff --git a/test/rules/memberOrderingRuleTests.ts b/test/rules/memberOrderingRuleTests.ts index 7dad517a8f6..435bc6049b2 100644 --- a/test/rules/memberOrderingRuleTests.ts +++ b/test/rules/memberOrderingRuleTests.ts @@ -16,9 +16,9 @@ describe("", () => { it("requires public variables to go before private ones", () => { - var fileName = "rules/memberordering-private.test.ts"; - var MemberOrderingRule = Lint.Test.getRule("member-ordering"); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, MemberOrderingRule, [ + const fileName = "rules/memberordering-private.test.ts"; + const MemberOrderingRule = Lint.Test.getRule("member-ordering"); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, MemberOrderingRule, [ true, "public-before-private" ]); @@ -31,9 +31,9 @@ describe("", () => { }); it("requires variables to go before methods", () => { - var fileName = "rules/memberordering-method.test.ts"; - var MemberOrderingRule = Lint.Test.getRule("member-ordering"); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, MemberOrderingRule, [ + const fileName = "rules/memberordering-method.test.ts"; + const MemberOrderingRule = Lint.Test.getRule("member-ordering"); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, MemberOrderingRule, [ true, "variables-before-functions" ]); @@ -49,9 +49,9 @@ describe("", () => { }); it("requires static variables to go before instance variables", () => { - var fileName = "rules/memberordering-static.test.ts"; - var MemberOrderingRule = Lint.Test.getRule("member-ordering"); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, MemberOrderingRule, [ + const fileName = "rules/memberordering-static.test.ts"; + const MemberOrderingRule = Lint.Test.getRule("member-ordering"); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, MemberOrderingRule, [ true, "static-before-instance" ]); diff --git a/test/rules/noAnyRuleTests.ts b/test/rules/noAnyRuleTests.ts index 03212bd854b..9ef797a2a1a 100644 --- a/test/rules/noAnyRuleTests.ts +++ b/test/rules/noAnyRuleTests.ts @@ -15,12 +15,12 @@ */ describe("", () => { - var fileName = "rules/noAny.test.ts"; - var NoAnyRule = Lint.Test.getRule("no-any"); + const NoAnyRule = Lint.Test.getRule("no-any"); + const fileName = "rules/noAny.test.ts"; - it("var declaration with type of 'any' should not be allowed", () => { - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoAnyRule); - var expectedFailure = Lint.Test.createFailure(fileName, [1, 8], [1, 11], "type decoration of 'any' is forbidden"); + it("const declaration with type of 'any' should not be allowed", () => { + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoAnyRule); + const expectedFailure = Lint.Test.createFailure(fileName, [1, 8], [1, 11], "type decoration of 'any' is forbidden"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); diff --git a/test/rules/noArgRuleTests.ts b/test/rules/noArgRuleTests.ts index 54dba9f085a..7b08561133b 100644 --- a/test/rules/noArgRuleTests.ts +++ b/test/rules/noArgRuleTests.ts @@ -16,11 +16,11 @@ describe("", () => { it("forbids access to arguments properties", () => { - var fileName = "rules/noarg.test.ts"; - var NoArgRule = Lint.Test.getRule("no-arg"); - var expectedFailure = Lint.Test.createFailure(fileName, [4, 8], [4, 17], NoArgRule.FAILURE_STRING); + const fileName = "rules/noarg.test.ts"; + const NoArgRule = Lint.Test.getRule("no-arg"); + const expectedFailure = Lint.Test.createFailure(fileName, [4, 8], [4, 17], NoArgRule.FAILURE_STRING); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoArgRule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoArgRule); assert.equal(actualFailures.length, 1); assert.isTrue(actualFailures[0].equals(expectedFailure)); diff --git a/test/rules/noBitwiseRuleTests.ts b/test/rules/noBitwiseRuleTests.ts index f2571ded480..81c7a393897 100644 --- a/test/rules/noBitwiseRuleTests.ts +++ b/test/rules/noBitwiseRuleTests.ts @@ -15,17 +15,17 @@ */ describe("", () => { - var NoBitwiseRule = Lint.Test.getRule("no-bitwise"); + const NoBitwiseRule = Lint.Test.getRule("no-bitwise"); + const fileName = "rules/bitwise.test.ts"; it("forbids access to bitwise operators", () => { - var fileName = "rules/bitwise.test.ts"; - var createFailure = Lint.Test.createFailuresOnFile(fileName, NoBitwiseRule.FAILURE_STRING); - var expectedFailures: Lint.RuleFailure[] = [ + const createFailure = Lint.Test.createFailuresOnFile(fileName, NoBitwiseRule.FAILURE_STRING); + const expectedFailures: Lint.RuleFailure[] = [ createFailure([2, 10], [2, 15]), createFailure([3, 10], [3, 28]), createFailure([3, 22], [3, 27]), ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoBitwiseRule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoBitwiseRule); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); diff --git a/test/rules/noConsecutiveBlankLinesRuleTests.ts b/test/rules/noConsecutiveBlankLinesRuleTests.ts index 90d57afba8b..ba9f38003c2 100644 --- a/test/rules/noConsecutiveBlankLinesRuleTests.ts +++ b/test/rules/noConsecutiveBlankLinesRuleTests.ts @@ -15,16 +15,16 @@ */ describe("", () => { - var NoConsecutiveBlankLinesRule = Lint.Test.getRule("no-consecutive-blank-lines"); + const NoConsecutiveBlankLinesRule = Lint.Test.getRule("no-consecutive-blank-lines"); + const fileName = "rules/blanklines.test.ts"; it("ensures there is at most one consecutive blank line", () => { - var fileName = "rules/blanklines.test.ts"; - var createFailure = Lint.Test.createFailuresOnFile(fileName, NoConsecutiveBlankLinesRule.FAILURE_STRING); - var expectedFailure1 = createFailure([2, 1], [3, 1]); - var expectedFailure2 = createFailure([9, 1], [10, 1]); - var expectedFailure3 = createFailure([14, 1], [15, 1]); + const createFailure = Lint.Test.createFailuresOnFile(fileName, NoConsecutiveBlankLinesRule.FAILURE_STRING); + const expectedFailure1 = createFailure([2, 1], [3, 1]); + const expectedFailure2 = createFailure([9, 1], [10, 1]); + const expectedFailure3 = createFailure([14, 1], [15, 1]); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoConsecutiveBlankLinesRule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoConsecutiveBlankLinesRule); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); diff --git a/test/rules/noConsoleRuleTests.ts b/test/rules/noConsoleRuleTests.ts index 25361616658..ab030b75d75 100644 --- a/test/rules/noConsoleRuleTests.ts +++ b/test/rules/noConsoleRuleTests.ts @@ -15,15 +15,16 @@ */ describe("", () => { + const NoConsoleRule = Lint.Test.getRule("no-console"); + const fileName = "rules/noconsole.test.ts"; + it("forbids access to specified console properties", () => { - var fileName = "rules/noconsole.test.ts"; - var NoConsoleRule = Lint.Test.getRule("no-console"); - var dirFailure = Lint.Test.createFailuresOnFile(fileName, NoConsoleRule.FAILURE_STRING_PART + "console.dir")([3, 1], [3, 12]); - var errorFailure = Lint.Test.createFailuresOnFile(fileName, NoConsoleRule.FAILURE_STRING_PART + "console.error")([7, 1], [7, 14]); - var logFailure = Lint.Test.createFailuresOnFile(fileName, NoConsoleRule.FAILURE_STRING_PART + "console.log")([2, 1], [2, 12]); - var warnFailure = Lint.Test.createFailuresOnFile(fileName, NoConsoleRule.FAILURE_STRING_PART + "console.warn")([6, 1], [6, 13]); + const dirFailure = Lint.Test.createFailuresOnFile(fileName, NoConsoleRule.FAILURE_STRING_PART + "console.dir")([3, 1], [3, 12]); + const errorFailure = Lint.Test.createFailuresOnFile(fileName, NoConsoleRule.FAILURE_STRING_PART + "console.error")([7, 1], [7, 14]); + const logFailure = Lint.Test.createFailuresOnFile(fileName, NoConsoleRule.FAILURE_STRING_PART + "console.log")([2, 1], [2, 12]); + const warnFailure = Lint.Test.createFailuresOnFile(fileName, NoConsoleRule.FAILURE_STRING_PART + "console.warn")([6, 1], [6, 13]); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoConsoleRule, [true, "dir", "error", "log", "warn"]); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoConsoleRule, [true, "dir", "error", "log", "warn"]); Lint.Test.assertContainsFailure(actualFailures, dirFailure); Lint.Test.assertContainsFailure(actualFailures, errorFailure); Lint.Test.assertContainsFailure(actualFailures, logFailure); diff --git a/test/rules/noConstructRuleTests.ts b/test/rules/noConstructRuleTests.ts index 554f6a8f25a..1d99bc26a83 100644 --- a/test/rules/noConstructRuleTests.ts +++ b/test/rules/noConstructRuleTests.ts @@ -15,27 +15,27 @@ */ describe("", () => { - var actualFailures: Lint.RuleFailure[]; - var fileName = "rules/noconstruct.test.ts"; - var NoConstructRule = Lint.Test.getRule("no-construct"); - var createFailure = Lint.Test.createFailuresOnFile(fileName, NoConstructRule.FAILURE_STRING); + const fileName = "rules/noconstruct.test.ts"; + const NoConstructRule = Lint.Test.getRule("no-construct"); + const createFailure = Lint.Test.createFailuresOnFile(fileName, NoConstructRule.FAILURE_STRING); + let actualFailures: Lint.RuleFailure[]; before(() => { actualFailures = Lint.Test.applyRuleOnFile(fileName, NoConstructRule); }); it("forbids access to String constructor", () => { - var expectedFailure = createFailure([2, 13], [2, 23]); + const expectedFailure = createFailure([2, 13], [2, 23]); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("forbids access to Number constructor", () => { - var expectedFailure = createFailure([5, 10], [5, 23]); + const expectedFailure = createFailure([5, 10], [5, 23]); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("forbids access to Boolean constructor", () => { - var expectedFailure = createFailure([8, 10], [8, 21]); + const expectedFailure = createFailure([8, 10], [8, 21]); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); }); diff --git a/test/rules/noConstructorVarsRuleTests.ts b/test/rules/noConstructorVarsRuleTests.ts index 7b592a1d05e..36d455b8a1e 100644 --- a/test/rules/noConstructorVarsRuleTests.ts +++ b/test/rules/noConstructorVarsRuleTests.ts @@ -15,20 +15,20 @@ */ describe("", () => { - it("No constrctor variable declarations", () => { - var fileName = "rules/noconstructorvars.test.ts"; - var Rule = Lint.Test.getRule("no-constructor-vars"); - var failureString = Rule.FAILURE_STRING_PART; + const Rule = Lint.Test.getRule("no-constructor-vars"); + const fileName = "rules/noconstructorvars.test.ts"; + const failureString = Rule.FAILURE_STRING_PART; - var failureFoo = Lint.Test.createFailuresOnFile(fileName, "'foo'" + failureString); - var failureBar = Lint.Test.createFailuresOnFile(fileName, "'bar'" + failureString); + it("no constructor variable declarations", () => { + const failureFoo = Lint.Test.createFailuresOnFile(fileName, "'foo'" + failureString); + const failureBar = Lint.Test.createFailuresOnFile(fileName, "'bar'" + failureString); - var expectedFailures = [ + const expectedFailures = [ failureFoo([3, 17], [3, 24]), failureFoo([9, 17], [9, 24]), failureBar([9, 38], [9, 44]) ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); assert.lengthOf(actualFailures, 3); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); diff --git a/test/rules/noDebuggerRuleTests.ts b/test/rules/noDebuggerRuleTests.ts index de6689249e8..e1833e56300 100644 --- a/test/rules/noDebuggerRuleTests.ts +++ b/test/rules/noDebuggerRuleTests.ts @@ -15,14 +15,13 @@ */ describe("", () => { - var NoDebuggerRule = Lint.Test.getRule("no-debugger"); + const NoDebuggerRule = Lint.Test.getRule("no-debugger"); + const fileName = "rules/debug.test.ts"; + const failureString = NoDebuggerRule.FAILURE_STRING; it("forbids debugger statements", () => { - var fileName = "rules/debug.test.ts"; - var failureString = NoDebuggerRule.FAILURE_STRING; - - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoDebuggerRule); - var expectedFailure = Lint.Test.createFailure(fileName, [5, 9], [5, 17], failureString); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoDebuggerRule); + const expectedFailure = Lint.Test.createFailure(fileName, [5, 9], [5, 17], failureString); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); diff --git a/test/rules/noDuplicateKeyRuleTests.ts b/test/rules/noDuplicateKeyRuleTests.ts index 7637e0e3a5f..40e23eea31a 100644 --- a/test/rules/noDuplicateKeyRuleTests.ts +++ b/test/rules/noDuplicateKeyRuleTests.ts @@ -15,11 +15,11 @@ */ describe("", () => { - it("forbids duplicate keys in object literals", () => { - const fileName = "rules/dupkey.test.ts"; - const NoDuplicateKeyRule = Lint.Test.getRule("no-duplicate-key"); - const failureString = NoDuplicateKeyRule.FAILURE_STRING; + const NoDuplicateKeyRule = Lint.Test.getRule("no-duplicate-key"); + const fileName = "rules/dupkey.test.ts"; + const failureString = NoDuplicateKeyRule.FAILURE_STRING; + it("forbids duplicate keys in object literals", () => { const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoDuplicateKeyRule); const createFailure1 = Lint.Test.createFailuresOnFile(fileName, failureString + "axa'"); const createFailure2 = Lint.Test.createFailuresOnFile(fileName, failureString + "bd'"); diff --git a/test/rules/noDuplicateVariableRuleTests.ts b/test/rules/noDuplicateVariableRuleTests.ts index 110be45c49d..fe6fb715c0a 100644 --- a/test/rules/noDuplicateVariableRuleTests.ts +++ b/test/rules/noDuplicateVariableRuleTests.ts @@ -15,10 +15,11 @@ */ describe("", () => { + const NoDuplicateVariableRule = Lint.Test.getRule("no-duplicate-variable"); + const fileName = "rules/no-duplicate-variable.test.ts"; + const failureString = NoDuplicateVariableRule.FAILURE_STRING + "duplicated'"; + it("ensures that variable declarations are unique within a scope", () => { - const fileName = "rules/no-duplicate-variable.test.ts"; - const NoDuplicateVariableRule = Lint.Test.getRule("no-duplicate-variable"); - const failureString = NoDuplicateVariableRule.FAILURE_STRING + "duplicated'"; const createFailure = Lint.Test.createFailuresOnFile(fileName, failureString); const expectedFailures = [ createFailure([11, 13], [11, 23]), diff --git a/test/rules/noEmptyRuleTests.ts b/test/rules/noEmptyRuleTests.ts index 2f59abcfba4..fce17dcb73d 100644 --- a/test/rules/noEmptyRuleTests.ts +++ b/test/rules/noEmptyRuleTests.ts @@ -15,35 +15,35 @@ */ describe("", () => { - var actualFailures: Lint.RuleFailure[]; - var fileName = "rules/noempty.test.ts"; - var NoEmptyRule = Lint.Test.getRule("no-empty"); - var createFailure = Lint.Test.createFailuresOnFile(fileName, NoEmptyRule.FAILURE_STRING); + const fileName = "rules/noempty.test.ts"; + const NoEmptyRule = Lint.Test.getRule("no-empty"); + const createFailure = Lint.Test.createFailuresOnFile(fileName, NoEmptyRule.FAILURE_STRING); + let actualFailures: Lint.RuleFailure[]; before(() => { actualFailures = Lint.Test.applyRuleOnFile(fileName, NoEmptyRule); }); it("forbids empty conditional blocks", () => { - var expectedFailure1 = createFailure([1, 14], [1, 16]); - var expectedFailure2 = createFailure([2, 14], [5, 2]); + const expectedFailure1 = createFailure([1, 14], [1, 16]); + const expectedFailure2 = createFailure([2, 14], [5, 2]); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); }); it("forbids empty function blocks", () => { - var expectedFailure = createFailure([7, 25], [9, 2]); + const expectedFailure = createFailure([7, 25], [9, 2]); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("forbids empty loop blocks", () => { - var expectedFailure = createFailure([11, 29], [11, 32]); + const expectedFailure = createFailure([11, 29], [11, 32]); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("forbids empty constructors", () => { - var expectedFailure = createFailure([29, 34], [30, 6]); + const expectedFailure = createFailure([29, 34], [30, 6]); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); diff --git a/test/rules/noEvalRuleTests.ts b/test/rules/noEvalRuleTests.ts index 37304ff21bc..ceb0bd6f07f 100644 --- a/test/rules/noEvalRuleTests.ts +++ b/test/rules/noEvalRuleTests.ts @@ -15,12 +15,13 @@ */ describe("", () => { + const NoEvalRule = Lint.Test.getRule("no-eval"); + const fileName = "rules/evil.test.ts"; + const failureString = NoEvalRule.FAILURE_STRING; + it("forbids eval", () => { - var fileName = "rules/evil.test.ts"; - var NoEvalRule = Lint.Test.getRule("no-eval"); - var failureString = NoEvalRule.FAILURE_STRING; - var expectedFailure = Lint.Test.createFailure(fileName, [6, 13], [6, 17], failureString); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoEvalRule); + const expectedFailure = Lint.Test.createFailure(fileName, [6, 13], [6, 17], failureString); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoEvalRule); assert.equal(actualFailures.length, 1); assert.isTrue(actualFailures[0].equals(expectedFailure)); diff --git a/test/rules/noRequireImportsTests.ts b/test/rules/noRequireImportsTests.ts index a1640b91d4c..5dc6feec3d8 100644 --- a/test/rules/noRequireImportsTests.ts +++ b/test/rules/noRequireImportsTests.ts @@ -15,10 +15,10 @@ */ describe("", () => { - it("forbids CommmonJS style imports", () => { - const fileName = "rules/norequireimports.test.ts"; - const Rule = Lint.Test.getRule("no-require-imports"); + const Rule = Lint.Test.getRule("no-require-imports"); + const fileName = "rules/norequireimports.test.ts"; + it("forbids CommmonJS style imports", () => { const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); assert(actualFailures.length === 6, "Expected 6 failures, got " + actualFailures.length); diff --git a/test/rules/noShadowedVariableRuleTests.ts b/test/rules/noShadowedVariableRuleTests.ts index 1569cb34155..74052828cc0 100644 --- a/test/rules/noShadowedVariableRuleTests.ts +++ b/test/rules/noShadowedVariableRuleTests.ts @@ -15,10 +15,10 @@ */ describe("", () => { - it("ensures that variable declarations are not shadowed", () => { - const fileName = "rules/no-shadowed-variable.test.ts"; - const NoShadowedVariableRule = Lint.Test.getRule("no-shadowed-variable"); + const NoShadowedVariableRule = Lint.Test.getRule("no-shadowed-variable"); + const fileName = "rules/no-shadowed-variable.test.ts"; + it("ensures that variable declarations are not shadowed", () => { const expectedFailures = [ Lint.Test.createFailure(fileName, [6, 13], [6, 14], NoShadowedVariableRule.FAILURE_STRING + "a'"), Lint.Test.createFailure(fileName, [7, 13], [7, 14], NoShadowedVariableRule.FAILURE_STRING + "b'"), diff --git a/test/rules/noStringLiteralRuleTests.ts b/test/rules/noStringLiteralRuleTests.ts index 0a7b82077cf..21c7b0147bf 100644 --- a/test/rules/noStringLiteralRuleTests.ts +++ b/test/rules/noStringLiteralRuleTests.ts @@ -15,12 +15,12 @@ */ describe("", () => { - it("forbids object access via string literals", () => { - var fileName = "rules/sub.test.ts"; - var NoStringLiteralRule = Lint.Test.getRule("no-string-literal"); + const NoStringLiteralRule = Lint.Test.getRule("no-string-literal"); + const fileName = "rules/sub.test.ts"; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoStringLiteralRule); - var expectedFailures = [ + it("forbids object access via string literals", () => { + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoStringLiteralRule); + const expectedFailures = [ Lint.Test.createFailure(fileName, [10, 20], [10, 25], NoStringLiteralRule.FAILURE_STRING), Lint.Test.createFailure(fileName, [11, 21], [11, 24], NoStringLiteralRule.FAILURE_STRING), Lint.Test.createFailure(fileName, [15, 5], [15, 23], NoStringLiteralRule.FAILURE_STRING), diff --git a/test/rules/noSwitchCaseFallThroughRuleTests.ts b/test/rules/noSwitchCaseFallThroughRuleTests.ts index 7f56f05efc7..cd54d89ca4c 100644 --- a/test/rules/noSwitchCaseFallThroughRuleTests.ts +++ b/test/rules/noSwitchCaseFallThroughRuleTests.ts @@ -15,13 +15,14 @@ */ describe("", () => { + const Rule = Lint.Test.getRule("no-switch-case-fall-through"); + const fileName = "rules/noswitchcasefallthrough.test.ts"; + it("Switch fall through", () => { - var fileName = "rules/noswitchcasefallthrough.test.ts"; - var Rule = Lint.Test.getRule("no-switch-case-fall-through"); - var failureString = Rule.FAILURE_STRING_PART; - var failureDefault = Lint.Test.createFailuresOnFile(fileName, failureString + "'default'"); - var failureCase = Lint.Test.createFailuresOnFile(fileName, failureString + "'case'"); - var expectedFailures = [ + const failureString = Rule.FAILURE_STRING_PART; + const failureDefault = Lint.Test.createFailuresOnFile(fileName, failureString + "'default'"); + const failureCase = Lint.Test.createFailuresOnFile(fileName, failureString + "'case'"); + const expectedFailures = [ failureCase([3, 15], [3, 16]), failureCase([6, 15], [6, 16]), failureDefault([8, 12], [8, 13]), @@ -30,10 +31,9 @@ describe("", () => { failureCase([35, 10], [35, 11]), failureDefault([32, 21], [32, 22]) ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); assert.lengthOf(actualFailures, 7); - Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); }); diff --git a/test/rules/noTrailingCommaRuleTests.ts b/test/rules/noTrailingCommaRuleTests.ts index 87f7e7a0d58..e4b630bb2c8 100644 --- a/test/rules/noTrailingCommaRuleTests.ts +++ b/test/rules/noTrailingCommaRuleTests.ts @@ -15,12 +15,13 @@ */ describe("", () => { + const NoTrailingCommaRule = Lint.Test.getRule("no-trailing-comma"); + const fileName = "rules/notrailingcomma.test.ts"; + it("restricts the use of trailing commas in object literals", () => { - var fileName = "rules/notrailingcomma.test.ts"; - var NoTrailingCommaRule = Lint.Test.getRule("no-trailing-comma"); - var expectedFailure1 = Lint.Test.createFailure(fileName, [5, 15], [5, 16], NoTrailingCommaRule.FAILURE_STRING); - var expectedFailure2 = Lint.Test.createFailure(fileName, [15, 9], [15, 10], NoTrailingCommaRule.FAILURE_STRING); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoTrailingCommaRule); + const expectedFailure1 = Lint.Test.createFailure(fileName, [5, 15], [5, 16], NoTrailingCommaRule.FAILURE_STRING); + const expectedFailure2 = Lint.Test.createFailure(fileName, [15, 9], [15, 10], NoTrailingCommaRule.FAILURE_STRING); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoTrailingCommaRule); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); diff --git a/test/rules/noTrailingWhitespaceRuleTests.ts b/test/rules/noTrailingWhitespaceRuleTests.ts index a1bd8504d25..f1ad9810b2a 100644 --- a/test/rules/noTrailingWhitespaceRuleTests.ts +++ b/test/rules/noTrailingWhitespaceRuleTests.ts @@ -15,18 +15,17 @@ */ describe("", () => { - it("forbids trailing whitespace", () => { - var fileName = "rules/trailing.test.ts"; - var NoTrailingWhitespaceRule = Lint.Test.getRule("no-trailing-whitespace"); - var failureString = NoTrailingWhitespaceRule.FAILURE_STRING; - var createFailure = Lint.Test.createFailuresOnFile(fileName, failureString); + const NoTrailingWhitespaceRule = Lint.Test.getRule("no-trailing-whitespace"); + const fileName = "rules/trailing.test.ts"; + const createFailure = Lint.Test.createFailuresOnFile(fileName, NoTrailingWhitespaceRule.FAILURE_STRING); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoTrailingWhitespaceRule); - var expectedFailure1 = createFailure([2, 24], [2, 28]); - var expectedFailure2 = createFailure([3, 32], [3, 36]); - var expectedFailure3 = createFailure([5, 1], [5, 5]); - var expectedFailure4 = createFailure([6, 1], [6, 5]); - var expectedFailure5 = createFailure([9, 2], [9, 6]); + it("forbids trailing whitespace", () => { + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoTrailingWhitespaceRule); + const expectedFailure1 = createFailure([2, 24], [2, 28]); + const expectedFailure2 = createFailure([3, 32], [3, 36]); + const expectedFailure3 = createFailure([5, 1], [5, 5]); + const expectedFailure4 = createFailure([6, 1], [6, 5]); + const expectedFailure5 = createFailure([9, 2], [9, 6]); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); diff --git a/test/rules/noUnreachableRuleTests.ts b/test/rules/noUnreachableRuleTests.ts index c5853c489ff..f25fa8ffba3 100644 --- a/test/rules/noUnreachableRuleTests.ts +++ b/test/rules/noUnreachableRuleTests.ts @@ -15,18 +15,19 @@ */ describe("", () => { + const NoUnreachableRule = Lint.Test.getRule("no-unreachable"); + const fileName = "rules/nounreachable.test.ts"; + it("restricts the use of unreachable code statements", () => { - var fileName = "rules/nounreachable.test.ts"; - var NoUnreachableRule = Lint.Test.getRule("no-unreachable"); - var createFailure = Lint.Test.createFailuresOnFile(fileName, NoUnreachableRule.FAILURE_STRING); - var expectedFailures: Lint.RuleFailure[] = [ + const createFailure = Lint.Test.createFailuresOnFile(fileName, NoUnreachableRule.FAILURE_STRING); + const expectedFailures: Lint.RuleFailure[] = [ createFailure([6, 5], [6, 11]), createFailure([13, 9], [13, 15]), createFailure([25, 9], [25, 27]), createFailure([28, 9], [28, 15]), createFailure([88, 5], [88, 15]) ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoUnreachableRule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoUnreachableRule); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); diff --git a/test/rules/noUnusedExpressionRuleTests.ts b/test/rules/noUnusedExpressionRuleTests.ts index 4edda24ec11..7e081331cd2 100644 --- a/test/rules/noUnusedExpressionRuleTests.ts +++ b/test/rules/noUnusedExpressionRuleTests.ts @@ -15,12 +15,12 @@ */ describe("", () => { - var NoUnusedExpressionRule = Lint.Test.getRule("no-unused-expression"); + const NoUnusedExpressionRule = Lint.Test.getRule("no-unused-expression"); + const fileName = "rules/unused.expression.test.ts"; it("disallows unused expression statements", () => { - var fileName = "rules/unused.expression.test.ts"; - var createFailure = Lint.Test.createFailuresOnFile(fileName, NoUnusedExpressionRule.FAILURE_STRING); - var expectedFailures: Lint.RuleFailure[] = [ + const createFailure = Lint.Test.createFailuresOnFile(fileName, NoUnusedExpressionRule.FAILURE_STRING); + const expectedFailures: Lint.RuleFailure[] = [ createFailure([34, 1], [34, 3]), createFailure([35, 1], [35, 3]), createFailure([36, 1], [36, 7]), @@ -34,7 +34,7 @@ describe("", () => { createFailure([44, 1], [44, 24]), createFailure([45, 1], [45, 13]), ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoUnusedExpressionRule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoUnusedExpressionRule); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); diff --git a/test/rules/noUnusedVariableRuleTests.ts b/test/rules/noUnusedVariableRuleTests.ts index cb9be384534..12bc267560d 100644 --- a/test/rules/noUnusedVariableRuleTests.ts +++ b/test/rules/noUnusedVariableRuleTests.ts @@ -15,15 +15,16 @@ */ describe("", () => { + const Rule = Lint.Test.getRule("no-unused-variable"); + it("restricts unused imports", () => { - var fileName = "rules/nounusedvariable-imports.test.ts"; - var Rule = Lint.Test.getRule("no-unused-variable"); - var failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'xyz'")([3, 9], [3, 12]); - var failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'createReadStream'")([4, 9], [4, 25]); - var failure3 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'template'")([14, 7], [14, 15]); - var failure4 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'foo'")([17, 13], [17, 16]); - var failure5 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'defaultExport'")([20, 8], [20, 21]); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const fileName = "rules/nounusedvariable-imports.test.ts"; + const failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'xyz'")([3, 9], [3, 12]); + const failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'createReadStream'")([4, 9], [4, 25]); + const failure3 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'template'")([14, 7], [14, 15]); + const failure4 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'foo'")([17, 13], [17, 16]); + const failure5 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'defaultExport'")([20, 8], [20, 21]); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); assert.lengthOf(actualFailures, 5); Lint.Test.assertContainsFailure(actualFailures, failure1); @@ -34,19 +35,17 @@ describe("", () => { }); it("restricts unused variables", () => { - var fileName = "rules/nounusedvariable-var.test.ts"; - var Rule = Lint.Test.getRule("no-unused-variable"); - - var failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'y'")([3, 5], [3, 6]); - var failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'a'")([23, 10], [23, 11]); - var failure3 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'b'")([23, 13], [23, 14]); - var failure4 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'d'")([26, 10], [26, 11]); - var failure5 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'e'")([26, 13], [26, 14]); - var failure6 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'a'")([35, 7] , [35, 8 ]); - var failure7 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'e'")([43, 9], [43, 10]); - var failure8 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'b'")([49, 11] , [49, 12]); - - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const fileName = "rules/nounusedvariable-var.test.ts"; + const failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'y'")([3, 5], [3, 6]); + const failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'a'")([23, 10], [23, 11]); + const failure3 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'b'")([23, 13], [23, 14]); + const failure4 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'d'")([26, 10], [26, 11]); + const failure5 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'e'")([26, 13], [26, 14]); + const failure6 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'a'")([35, 7] , [35, 8 ]); + const failure7 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'e'")([43, 9], [43, 10]); + const failure8 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'b'")([49, 11] , [49, 12]); + + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); assert.lengthOf(actualFailures, 8); Lint.Test.assertContainsFailure(actualFailures, failure1); @@ -60,13 +59,11 @@ describe("", () => { }); it("restricts unused functions", () => { - var fileName = "rules/nounusedvariable-function.test.ts"; - var Rule = Lint.Test.getRule("no-unused-variable"); + const fileName = "rules/nounusedvariable-function.test.ts"; + const failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'func2'")([5, 5], [5, 10]); + const failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'func3'")([9, 10], [9, 15]); - var failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'func2'")([5, 5], [5, 10]); - var failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'func3'")([9, 10], [9, 15]); - - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); assert.lengthOf(actualFailures, 2); Lint.Test.assertContainsFailure(actualFailures, failure1); @@ -74,12 +71,11 @@ describe("", () => { }); it("restricts unused class members", () => { - var fileName = "rules/nounusedvariable-class.test.ts"; - var Rule = Lint.Test.getRule("no-unused-variable"); - var failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'z2'")([2, 13], [2, 15]); - var failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'mfunc4'")([18, 13], [18, 19]); + const fileName = "rules/nounusedvariable-class.test.ts"; + const failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'z2'")([2, 13], [2, 15]); + const failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'mfunc4'")([18, 13], [18, 19]); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); assert.lengthOf(actualFailures, 2); Lint.Test.assertContainsFailure(actualFailures, failure1); @@ -87,19 +83,17 @@ describe("", () => { }); it("restricts unused parameters", () => { - var fileName = "rules/nounusedvariable-parameter.test.ts"; - var Rule = Lint.Test.getRule("no-unused-variable"); - - var failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'args'")([1, 48], [1, 52]); - var failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'y'")([5, 34], [5, 35]); - var failure3 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'y'")([9, 35], [9, 36]); - var failure4 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'x'")([18, 25], [18, 26]); - var failure5 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'y'")([38, 27], [38, 28]); - var failure6 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'b'")([46, 22], [46, 23]); - var failure7 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'b'")([50, 23], [50, 24]); - var failure8 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'x'")([55, 20], [55, 21]); - - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule, [true, "check-parameters"]); + const fileName = "rules/nounusedvariable-parameter.test.ts"; + const failure1 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'args'")([1, 48], [1, 52]); + const failure2 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'y'")([5, 34], [5, 35]); + const failure3 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'y'")([9, 35], [9, 36]); + const failure4 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'x'")([18, 25], [18, 26]); + const failure5 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'y'")([38, 27], [38, 28]); + const failure6 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'b'")([46, 22], [46, 23]); + const failure7 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'b'")([50, 23], [50, 24]); + const failure8 = Lint.Test.createFailuresOnFile(fileName, Rule.FAILURE_STRING + "'x'")([55, 20], [55, 21]); + + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule, [true, "check-parameters"]); assert.lengthOf(actualFailures, 8); Lint.Test.assertContainsFailure(actualFailures, failure1); diff --git a/test/rules/noUseBeforeDeclareRuleTests.ts b/test/rules/noUseBeforeDeclareRuleTests.ts index 1fb14ab3c76..5109a047c42 100644 --- a/test/rules/noUseBeforeDeclareRuleTests.ts +++ b/test/rules/noUseBeforeDeclareRuleTests.ts @@ -15,28 +15,22 @@ */ describe("", () => { - var Rule: any; - - before(() => { - Rule = Lint.Test.getRule("no-use-before-declare"); - }); + const Rule = Lint.Test.getRule("no-use-before-declare"); + const fileName = "rules/nousebeforedeclare.test.ts"; it("restricts usage before declaration", () => { - var fileName = "rules/nousebeforedeclare.test.ts"; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); - + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); assert.equal(actualFailures.length, 7); }); it("restricts usage of imports before declaration", () => { - var fileName = "rules/nousebeforedeclare.test.ts"; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); - var failure1 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("$"))([1, 1], [1, 2]); - var failure2 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("foo1"))([35, 17], [35, 21]); - var failure3 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("foo2"))([36, 17], [36, 21]); - var failure4 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("foo3"))([37, 17], [37, 21]); - var failure5 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("map"))([38, 5], [38, 8]); + const failure1 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("$"))([1, 1], [1, 2]); + const failure2 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("foo1"))([35, 17], [35, 21]); + const failure3 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("foo2"))([36, 17], [36, 21]); + const failure4 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("foo3"))([37, 17], [37, 21]); + const failure5 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("map"))([38, 5], [38, 8]); Lint.Test.assertContainsFailure(actualFailures, failure1); Lint.Test.assertContainsFailure(actualFailures, failure2); @@ -46,11 +40,10 @@ describe("", () => { }); it("restricts usage of variables before declaration", () => { - var fileName = "rules/nousebeforedeclare.test.ts"; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); - var failure1 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("varb"))([3, 12], [3, 16]); - var failure2 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("j"))([13, 9], [13, 10]); + const failure1 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("varb"))([3, 12], [3, 16]); + const failure2 = Lint.Test.createFailuresOnFile(fileName, makeFailureString("j"))([13, 9], [13, 10]); Lint.Test.assertContainsFailure(actualFailures, failure1); Lint.Test.assertContainsFailure(actualFailures, failure2); diff --git a/test/rules/noVarKeywordRuleTests.ts b/test/rules/noVarKeywordRuleTests.ts index 30dd456c59d..971f7ab09f2 100644 --- a/test/rules/noVarKeywordRuleTests.ts +++ b/test/rules/noVarKeywordRuleTests.ts @@ -12,20 +12,22 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ describe("", () => { + const NoVarKeywordRule = Lint.Test.getRule("no-var-keyword"); + const fileName = "rules/novarkeyword.test.ts"; + it("disallows use of creating variables with 'var'", () => { - var fileName = "rules/novarkeyword.test.ts"; - var NoVarKeywordRule = Lint.Test.getRule("no-var-keyword"); - var failure = Lint.Test.createFailuresOnFile(fileName, NoVarKeywordRule.FAILURE_STRING); - var expectedFailure = [ - failure([3, 1], [3, 4]), - failure([6, 5], [6, 8]), - failure([9, 1], [9, 4]), - failure([12, 1], [12, 4]), + const failure = Lint.Test.createFailuresOnFile(fileName, NoVarKeywordRule.FAILURE_STRING); + const expectedFailures = [ + failure([1, 1], [1, 4]), + failure([4, 5], [4, 8]), + failure([7, 1], [7, 4]), + failure([10, 1], [10, 4]), ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoVarKeywordRule); - Lint.Test.assertFailuresEqual(actualFailures, expectedFailure); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoVarKeywordRule); + + Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); }); diff --git a/test/rules/noVarRequiresRuleTests.ts b/test/rules/noVarRequiresRuleTests.ts index 8759cfbbd57..f5378d153f2 100644 --- a/test/rules/noVarRequiresRuleTests.ts +++ b/test/rules/noVarRequiresRuleTests.ts @@ -15,11 +15,12 @@ */ describe("", () => { + const NoVarRequiresRule = Lint.Test.getRule("no-var-requires"); + const fileName = "rules/novarrequires.test.ts"; + it("disallows use of require outside import statements", () => { - var fileName = "rules/novarrequires.test.ts"; - var NoVarRequiresRule = Lint.Test.getRule("no-var-requires"); - var expectedFailure = Lint.Test.createFailure(fileName, [2, 9], [2, 21], NoVarRequiresRule.FAILURE_STRING); - var actualFailures = Lint.Test.applyRuleOnFile(fileName, NoVarRequiresRule); + const expectedFailure = Lint.Test.createFailure(fileName, [2, 9], [2, 21], NoVarRequiresRule.FAILURE_STRING); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, NoVarRequiresRule); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); assert.lengthOf(actualFailures, 1); diff --git a/test/rules/oneLineRuleTests.ts b/test/rules/oneLineRuleTests.ts index 45c8dea7c0e..285ea4bf22a 100644 --- a/test/rules/oneLineRuleTests.ts +++ b/test/rules/oneLineRuleTests.ts @@ -15,87 +15,87 @@ */ describe("", () => { - var actualFailures: Lint.RuleFailure[]; - var fileName = "rules/oneline.test.ts"; - var OneLineRule = Lint.Test.getRule("one-line"); - var braceFailure = OneLineRule.BRACE_FAILURE_STRING; - var elseFailure = OneLineRule.ELSE_FAILURE_STRING; - var whitespaceFailure = OneLineRule.WHITESPACE_FAILURE_STRING; - var catchFailure = OneLineRule.CATCH_FAILURE_STRING; + const fileName = "rules/oneline.test.ts"; + const OneLineRule = Lint.Test.getRule("one-line"); + const braceFailure = OneLineRule.BRACE_FAILURE_STRING; + const elseFailure = OneLineRule.ELSE_FAILURE_STRING; + const whitespaceFailure = OneLineRule.WHITESPACE_FAILURE_STRING; + const catchFailure = OneLineRule.CATCH_FAILURE_STRING; + let actualFailures: Lint.RuleFailure[]; before(() => { - var options = [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"]; + const options = [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"]; actualFailures = Lint.Test.applyRuleOnFile(fileName, OneLineRule, options); assert.lengthOf(actualFailures, 13); }); it("enforces rules only when enabled", () => { - var failures = Lint.Test.applyRuleOnFile(fileName, OneLineRule); + const failures = Lint.Test.applyRuleOnFile(fileName, OneLineRule); assert.equal(failures.length, 0); }); it("enforces module brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [2, 1], [2, 2], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [2, 1], [2, 2], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces enumeration brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [4, 5], [4, 6], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [4, 5], [4, 6], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces function brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [12, 5], [12, 6], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [12, 5], [12, 6], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces if brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [14, 9], [14, 10], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [14, 9], [14, 10], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces else position", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [17, 9], [17, 13], elseFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [17, 9], [17, 13], elseFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces class brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [25, 1], [25, 2], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [25, 1], [25, 2], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces object literal brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [30, 1], [30, 2], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [30, 1], [30, 2], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces block brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [36, 1], [36, 2], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [36, 1], [36, 2], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces switch brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [41, 1], [41, 2], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [41, 1], [41, 2], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces try brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [51, 1], [51, 2], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [51, 1], [51, 2], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces catch position", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [54, 1], [54, 6], catchFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [54, 1], [54, 6], catchFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces catch brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [55, 1], [55, 2], braceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [55, 1], [55, 2], braceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces whitespace before a brace", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [59, 14], [59, 15], whitespaceFailure); + const expectedFailure = Lint.Test.createFailure(fileName, [59, 14], [59, 15], whitespaceFailure); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); }); diff --git a/test/rules/quotemarkRuleTests.ts b/test/rules/quotemarkRuleTests.ts index 4fe8471e4f1..4ec00e8d268 100644 --- a/test/rules/quotemarkRuleTests.ts +++ b/test/rules/quotemarkRuleTests.ts @@ -15,22 +15,22 @@ */ describe("", () => { - var fileName = "rules/quotemark.test.ts"; - var QuoteMarkRule = Lint.Test.getRule("quotemark"); - var singleFailure = QuoteMarkRule.SINGLE_QUOTE_FAILURE; - var doubleFailure = QuoteMarkRule.DOUBLE_QUOTE_FAILURE; + const QuoteMarkRule = Lint.Test.getRule("quotemark"); + const fileName = "rules/quotemark.test.ts"; + const singleFailureString = QuoteMarkRule.SINGLE_QUOTE_FAILURE; + const doubleFailureString = QuoteMarkRule.DOUBLE_QUOTE_FAILURE; it("enforces single quotes", () => { - var actualFailures = Lint.Test.applyRuleOnFile(fileName, QuoteMarkRule, [true, "single"]); - var expectedFailure = Lint.Test.createFailure(fileName, [2, 19], [2, 28], singleFailure); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, QuoteMarkRule, [true, "single"]); + const expectedFailure = Lint.Test.createFailure(fileName, [2, 19], [2, 28], singleFailureString); assert.equal(actualFailures.length, 1); assert.isTrue(actualFailures[0].equals(expectedFailure)); }); it("enforces double quotes", () => { - var actualFailures = Lint.Test.applyRuleOnFile(fileName, QuoteMarkRule, [true, "double"]); - var expectedFailure = Lint.Test.createFailure(fileName, [1, 14], [1, 22], doubleFailure); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, QuoteMarkRule, [true, "double"]); + const expectedFailure = Lint.Test.createFailure(fileName, [1, 14], [1, 22], doubleFailureString); assert.equal(actualFailures.length, 1); assert.isTrue(actualFailures[0].equals(expectedFailure)); diff --git a/test/rules/radixRuleTests.ts b/test/rules/radixRuleTests.ts index a9278a201ab..34514f5c773 100644 --- a/test/rules/radixRuleTests.ts +++ b/test/rules/radixRuleTests.ts @@ -15,12 +15,13 @@ */ describe("", () => { + const RadixRule = Lint.Test.getRule("radix"); + const fileName = "rules/radix.test.ts"; + const failureString = RadixRule.FAILURE_STRING; + it("enforces radix parameter of parseInt", () => { - var fileName = "rules/radix.test.ts"; - var RadixRule = Lint.Test.getRule("radix"); - var failureString = RadixRule.FAILURE_STRING; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, RadixRule); - var expectedFailure = Lint.Test.createFailure(fileName, [2, 9], [2, 20], failureString); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, RadixRule); + const expectedFailure = Lint.Test.createFailure(fileName, [2, 9], [2, 20], failureString); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); diff --git a/test/rules/semicolonRuleTests.ts b/test/rules/semicolonRuleTests.ts index 5abcd6dac03..34a52774328 100644 --- a/test/rules/semicolonRuleTests.ts +++ b/test/rules/semicolonRuleTests.ts @@ -15,13 +15,13 @@ */ describe("", () => { - var SemicolonRule = Lint.Test.getRule("semicolon"); - var fileName = "rules/semicolon.test.ts"; - var failureString = SemicolonRule.FAILURE_STRING; - var actualFailures: Lint.RuleFailure[]; - var createFailure = (start: number[], end: number[]) => { + const SemicolonRule = Lint.Test.getRule("semicolon"); + const fileName = "rules/semicolon.test.ts"; + const failureString = SemicolonRule.FAILURE_STRING; + const createFailure = (start: number[], end: number[]) => { return Lint.Test.createFailure(fileName, start, end, failureString); }; + let actualFailures: Lint.RuleFailure[]; before(() => { actualFailures = Lint.Test.applyRuleOnFile(fileName, SemicolonRule); diff --git a/test/rules/sortObjectLiteralKeysRuleTests.ts b/test/rules/sortObjectLiteralKeysRuleTests.ts index 7febffe6ade..ce53051b3e5 100644 --- a/test/rules/sortObjectLiteralKeysRuleTests.ts +++ b/test/rules/sortObjectLiteralKeysRuleTests.ts @@ -15,11 +15,11 @@ */ describe("", () => { - it("forbids unsorted keys in object literals", () => { - const fileName = "rules/sortedkey.test.ts"; - const SortedKeyRule = Lint.Test.getRule("sort-object-literal-keys"); - const failureString = SortedKeyRule.FAILURE_STRING; + const SortedKeyRule = Lint.Test.getRule("sort-object-literal-keys"); + const fileName = "rules/sortedkey.test.ts"; + const failureString = SortedKeyRule.FAILURE_STRING; + it("forbids unsorted keys in object literals", () => { const actualFailures = Lint.Test.applyRuleOnFile(fileName, SortedKeyRule); const createFailure1 = Lint.Test.createFailuresOnFile(fileName, failureString + "a'"); const createFailure2 = Lint.Test.createFailuresOnFile(fileName, failureString + "a'"); diff --git a/test/rules/switchDefaultRuleTests.ts b/test/rules/switchDefaultRuleTests.ts index e160c4406a7..d39b4a3efec 100644 --- a/test/rules/switchDefaultRuleTests.ts +++ b/test/rules/switchDefaultRuleTests.ts @@ -15,16 +15,17 @@ */ describe("", () => { + const SwitchDefaultRule = Lint.Test.getRule("switch-default"); + const fileName = "rules/switchdefault.test.ts"; + const failureString = SwitchDefaultRule.FAILURE_STRING; + it("Switch default", () => { - var fileName = "rules/switchdefault.test.ts"; - var Rule = Lint.Test.getRule("switch-default"); - var failureString = Rule.FAILURE_STRING; - var failure = Lint.Test.createFailuresOnFile(fileName, failureString); - var expectedFailures = [ + const failure = Lint.Test.createFailuresOnFile(fileName, failureString); + const expectedFailures = [ failure([2, 1], [6, 2]), failure([8, 1], [18, 2]) ]; - var actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule); + const actualFailures = Lint.Test.applyRuleOnFile(fileName, SwitchDefaultRule); Lint.Test.assertFailuresEqual(actualFailures, expectedFailures); }); }); diff --git a/test/rules/tripleEqualsRuleTests.ts b/test/rules/tripleEqualsRuleTests.ts index a2174f2c23d..5c80cfeaf31 100644 --- a/test/rules/tripleEqualsRuleTests.ts +++ b/test/rules/tripleEqualsRuleTests.ts @@ -15,9 +15,9 @@ */ describe("", () => { - var actualFailures: Lint.RuleFailure[]; - var fileName = "rules/eqeqeq.test.ts"; - var TripleEqualsRule = Lint.Test.getRule("triple-equals"); + const fileName = "rules/eqeqeq.test.ts"; + const TripleEqualsRule = Lint.Test.getRule("triple-equals"); + let actualFailures: Lint.RuleFailure[]; before(() => { actualFailures = Lint.Test.applyRuleOnFile(fileName, TripleEqualsRule, [true, "allow-null-check"]); @@ -25,15 +25,15 @@ describe("", () => { }); it("ensures ===", () => { - var failureString = TripleEqualsRule.EQ_FAILURE_STRING; - var expectedFailure = Lint.Test.createFailure(fileName, [4, 33], [4, 35], failureString); + const failureString = TripleEqualsRule.EQ_FAILURE_STRING; + const expectedFailure = Lint.Test.createFailure(fileName, [4, 33], [4, 35], failureString); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("ensures !==", () => { - var failureString = TripleEqualsRule.NEQ_FAILURE_STRING; - var expectedFailure = Lint.Test.createFailure(fileName, [8, 21], [8, 23], failureString); + const failureString = TripleEqualsRule.NEQ_FAILURE_STRING; + const expectedFailure = Lint.Test.createFailure(fileName, [8, 21], [8, 23], failureString); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); diff --git a/test/rules/typedefWhitespaceRuleTests.ts b/test/rules/typedefWhitespaceRuleTests.ts index 9611d007258..29fcde85c81 100644 --- a/test/rules/typedefWhitespaceRuleTests.ts +++ b/test/rules/typedefWhitespaceRuleTests.ts @@ -17,28 +17,28 @@ describe("", () => { - var fileName = "rules/typedefWhitespace.test.ts"; - var TypedefWhitespaceRule = Lint.Test.getRule("typedefWhitespace"); + const fileName = "rules/typedefWhitespace.test.ts"; + const TypedefWhitespaceRule = Lint.Test.getRule("typedefWhitespace"); it("enforces rules only when enabled (unspecified)", () => { - var failures = Lint.Test.applyRuleOnFile(fileName, TypedefWhitespaceRule); + const failures = Lint.Test.applyRuleOnFile(fileName, TypedefWhitespaceRule); assert.equal(failures.length, 0); }); it("enforces rules only when enabled (disabled)", () => { - var options = [false]; - var failures = Lint.Test.applyRuleOnFile(fileName, TypedefWhitespaceRule, options); + const options = [false]; + const failures = Lint.Test.applyRuleOnFile(fileName, TypedefWhitespaceRule, options); assert.equal(failures.length, 0); }); }); describe("", () => { - var actualFailures: Lint.RuleFailure[]; - var fileName = "rules/typedefWhitespace.test.ts"; - var TypedefWhitespaceRule = Lint.Test.getRule("typedefWhitespace"); + const fileName = "rules/typedefWhitespace.test.ts"; + const TypedefWhitespaceRule = Lint.Test.getRule("typedefWhitespace"); + let actualFailures: Lint.RuleFailure[]; before(() => { - var options = [true, { + const options = [true, { "call-signature": "space", "index-signature": "space", "parameter": "space", @@ -49,9 +49,9 @@ describe("", () => { }); it("enforces whitespace in call signatures", () => { - var expectedFailure1 = Lint.Test.createFailure(fileName, [4, 15], [4, 16], "expected space in call-signature"); - var expectedFailure2 = Lint.Test.createFailure(fileName, [25, 59], [25, 60], "expected space in call-signature"); - var expectedFailure3 = Lint.Test.createFailure(fileName, [52, 22], [52, 23], "expected space in call-signature"); + const expectedFailure1 = Lint.Test.createFailure(fileName, [4, 15], [4, 16], "expected space in call-signature"); + const expectedFailure2 = Lint.Test.createFailure(fileName, [25, 59], [25, 60], "expected space in call-signature"); + const expectedFailure3 = Lint.Test.createFailure(fileName, [52, 22], [52, 23], "expected space in call-signature"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); @@ -59,15 +59,15 @@ describe("", () => { }); it("enforces whitespace in index signature", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [48, 11], [48, 12], "expected space in index-signature"); + const expectedFailure = Lint.Test.createFailure(fileName, [48, 11], [48, 12], "expected space in index-signature"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces whitespace in parameter", () => { - var expectedFailure1 = Lint.Test.createFailure(fileName, [25, 39], [25, 40], "expected space in parameter"); - var expectedFailure2 = Lint.Test.createFailure(fileName, [25, 50], [25, 51], "expected space in parameter"); - var expectedFailure3 = Lint.Test.createFailure(fileName, [48, 11], [48, 12], "expected space in parameter"); + const expectedFailure1 = Lint.Test.createFailure(fileName, [25, 39], [25, 40], "expected space in parameter"); + const expectedFailure2 = Lint.Test.createFailure(fileName, [25, 50], [25, 51], "expected space in parameter"); + const expectedFailure3 = Lint.Test.createFailure(fileName, [48, 11], [48, 12], "expected space in parameter"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); @@ -75,14 +75,14 @@ describe("", () => { }); it("enforces whitespace in property declaration", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [18, 9], [18, 10], "expected space in property-declaration"); + const expectedFailure = Lint.Test.createFailure(fileName, [18, 9], [18, 10], "expected space in property-declaration"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces whitespace in variable declarator", () => { - var expectedFailure1 = Lint.Test.createFailure(fileName, [26, 10], [26, 11], "expected space in variable-declaration"); - var expectedFailure2 = Lint.Test.createFailure(fileName, [27, 10], [27, 11], "expected space in variable-declaration"); + const expectedFailure1 = Lint.Test.createFailure(fileName, [26, 10], [26, 11], "expected space in variable-declaration"); + const expectedFailure2 = Lint.Test.createFailure(fileName, [27, 10], [27, 11], "expected space in variable-declaration"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); @@ -90,12 +90,12 @@ describe("", () => { }); describe("", () => { - var actualFailures: Lint.RuleFailure[]; - var fileName = "rules/typedefWhitespace.test.ts"; - var TypedefWhitespaceRule = Lint.Test.getRule("typedefWhitespace"); + const fileName = "rules/typedefWhitespace.test.ts"; + const TypedefWhitespaceRule = Lint.Test.getRule("typedefWhitespace"); + let actualFailures: Lint.RuleFailure[]; before(() => { - var options = [true, { + const options = [true, { "call-signature": "nospace", "index-signature": "nospace", "parameter": "nospace", @@ -106,9 +106,9 @@ describe("", () => { }); it("enforces no whitespace in call signatures", () => { - var expectedFailure1 = Lint.Test.createFailure(fileName, [12, 15], [12, 16], "expected nospace in call-signature"); - var expectedFailure2 = Lint.Test.createFailure(fileName, [36, 63], [36, 64], "expected nospace in call-signature"); - var expectedFailure3 = Lint.Test.createFailure(fileName, [62, 22], [62, 23], "expected nospace in call-signature"); + const expectedFailure1 = Lint.Test.createFailure(fileName, [12, 15], [12, 16], "expected nospace in call-signature"); + const expectedFailure2 = Lint.Test.createFailure(fileName, [36, 63], [36, 64], "expected nospace in call-signature"); + const expectedFailure3 = Lint.Test.createFailure(fileName, [62, 22], [62, 23], "expected nospace in call-signature"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); @@ -116,15 +116,15 @@ describe("", () => { }); it("enforces no whitespace in indexSignature", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [58, 11], [58, 12], "expected nospace in index-signature"); + const expectedFailure = Lint.Test.createFailure(fileName, [58, 11], [58, 12], "expected nospace in index-signature"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces no whitespace in parameter", () => { - var expectedFailure1 = Lint.Test.createFailure(fileName, [36, 41], [36, 42], "expected nospace in parameter"); - var expectedFailure2 = Lint.Test.createFailure(fileName, [36, 53], [36, 54], "expected nospace in parameter"); - var expectedFailure3 = Lint.Test.createFailure(fileName, [58, 11], [58, 12], "expected nospace in parameter"); + const expectedFailure1 = Lint.Test.createFailure(fileName, [36, 41], [36, 42], "expected nospace in parameter"); + const expectedFailure2 = Lint.Test.createFailure(fileName, [36, 53], [36, 54], "expected nospace in parameter"); + const expectedFailure3 = Lint.Test.createFailure(fileName, [58, 11], [58, 12], "expected nospace in parameter"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); @@ -132,14 +132,14 @@ describe("", () => { }); it("enforces no whitespace in propertySignature", () => { - var expectedFailure = Lint.Test.createFailure(fileName, [22, 9], [22, 10], "expected nospace in property-declaration"); + const expectedFailure = Lint.Test.createFailure(fileName, [22, 9], [22, 10], "expected nospace in property-declaration"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure); }); it("enforces no whitespace in variable declarator", () => { - var expectedFailure1 = Lint.Test.createFailure(fileName, [37, 10], [37, 11], "expected nospace in variable-declaration"); - var expectedFailure2 = Lint.Test.createFailure(fileName, [38, 10], [38, 11], "expected nospace in variable-declaration"); + const expectedFailure1 = Lint.Test.createFailure(fileName, [37, 10], [37, 11], "expected nospace in variable-declaration"); + const expectedFailure2 = Lint.Test.createFailure(fileName, [38, 10], [38, 11], "expected nospace in variable-declaration"); Lint.Test.assertContainsFailure(actualFailures, expectedFailure1); Lint.Test.assertContainsFailure(actualFailures, expectedFailure2); diff --git a/test/rules/useStrictRuleTests.ts b/test/rules/useStrictRuleTests.ts index 22d28251c73..b7a969355ee 100644 --- a/test/rules/useStrictRuleTests.ts +++ b/test/rules/useStrictRuleTests.ts @@ -15,24 +15,23 @@ */ describe("", () => { - var UseStrictRule = Lint.Test.getRule("use-strict"); - - var actualFailures: any; - var fileName = "rules/usestrict.test.ts"; + const UseStrictRule = Lint.Test.getRule("use-strict"); + const fileName = "rules/usestrict.test.ts"; + let actualFailures: Lint.RuleFailure[]; before(() => { - var options = [true, "check-function", "check-module"]; + const options = [true, "check-function", "check-module"]; actualFailures = Lint.Test.applyRuleOnFile(fileName, UseStrictRule, options); assert.lengthOf(actualFailures, 2); }); it("enforces checks for 'use strict' in functions", () => { - var expectedFailures = Lint.Test.createFailure(fileName, [14, 1], [14, 9], UseStrictRule.FAILURE_STRING); + const expectedFailures = Lint.Test.createFailure(fileName, [14, 1], [14, 9], UseStrictRule.FAILURE_STRING); Lint.Test.assertContainsFailure(actualFailures, expectedFailures); }); it("enforces checks for 'use strict' in modules", () => { - var expectedFailures = Lint.Test.createFailure(fileName, [24, 1], [24, 7], UseStrictRule.FAILURE_STRING); + const expectedFailures = Lint.Test.createFailure(fileName, [24, 1], [24, 7], UseStrictRule.FAILURE_STRING); Lint.Test.assertContainsFailure(actualFailures, expectedFailures); }); }); diff --git a/test/tsconfig.json b/test/tsconfig.json index bbc01dc591e..3ab3dbf3abe 100644 --- a/test/tsconfig.json +++ b/test/tsconfig.json @@ -10,7 +10,7 @@ "filesGlob": [ "../typings/*.d.ts", "../lib/tslint.d.ts", - "./typings/*.ts", + "./typings/**/*.d.ts", "./references.ts", "./helper.ts", "./ruleDisableEnableTests.ts", @@ -23,8 +23,8 @@ "../typings/typescriptServices.d.ts", "../typings/typescriptServicesScanner.d.ts", "../lib/tslint.d.ts", - "./typings/chai.d.ts", - "./typings/mocha.d.ts", + "./typings/chai/chai.d.ts", + "./typings/mocha/mocha.d.ts", "./references.ts", "./helper.ts", "./ruleDisableEnableTests.ts", @@ -60,6 +60,7 @@ "./rules/noDuplicateVariableRuleTests.ts", "./rules/noEmptyRuleTests.ts", "./rules/noEvalRuleTests.ts", + "./rules/noRequireImportsTests.ts", "./rules/noShadowedVariableRuleTests.ts", "./rules/noStringLiteralRuleTests.ts", "./rules/noSwitchCaseFallThroughRuleTests.ts", diff --git a/tslint.json b/tslint.json index 742bed6d73b..08468961638 100644 --- a/tslint.json +++ b/tslint.json @@ -31,6 +31,7 @@ "no-unused-variable": false, "no-unreachable": true, "no-use-before-declare": true, + "no-var-keyword": true, "one-line": [true, "check-open-brace", "check-catch", @@ -40,6 +41,7 @@ "quotemark": [true, "double"], "radix": true, "semicolon": true, + "sort-object-literal-keys": true, "triple-equals": [true, "allow-null-check"], "variable-name": false, "whitespace": [true,