Skip to content

Commit

Permalink
Update dependencies and lint for no-unsafe-any (palantir#2544)
Browse files Browse the repository at this point in the history
  • Loading branch information
andy-hanson authored and nchen63 committed Apr 17, 2017
1 parent bf89425 commit a3d8d6f
Show file tree
Hide file tree
Showing 46 changed files with 371 additions and 258 deletions.
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
"compile:scripts": "tsc -p scripts",
"compile:test": "tsc -p test",
"lint": "npm-run-all -p lint:global lint:from-bin",
"lint:global": "tslint --project test/tsconfig.json --format stylish # test includes 'src' too",
"lint:from-bin": "node bin/tslint --project test/tsconfig.json --format stylish",
"lint:global": "tslint --project test/tsconfig.json --format stylish --type-check # test includes 'src' too",
"lint:from-bin": "node bin/tslint --project test/tsconfig.json --format stylish --type-check",
"test": "npm-run-all test:pre -p test:mocha test:rules",
"test:pre": "cd ./test/config && npm install",
"test:mocha": "mocha --reporter spec --colors \"build/test/**/*Tests.js\"",
Expand All @@ -51,7 +51,7 @@
},
"devDependencies": {
"@types/babel-code-frame": "^6.20.0",
"@types/chai": "~3.4.34",
"@types/chai": "^3.5.0",
"@types/colors": "^0.6.33",
"@types/diff": "0.0.31",
"@types/findup-sync": "^0.3.29",
Expand All @@ -73,7 +73,7 @@
"rimraf": "^2.5.4",
"tslint": "latest",
"tslint-test-config-non-relative": "file:test/external/tslint-test-config-non-relative",
"typescript": "^2.2.2"
"typescript": "^2.3.0"
},
"license": "Apache-2.0",
"engines": {
Expand Down
8 changes: 6 additions & 2 deletions src/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import { join as joinPaths } from "path";

import { findRule } from "../ruleLoader";
import { hasOwnProperty } from "../utils";

// tslint:disable object-literal-sort-keys
// tslint:disable object-literal-key-quotes
Expand Down Expand Up @@ -234,11 +235,14 @@ export const RULES_EXCLUDED_FROM_ALL_CONFIG =
// Exclude typescript-only rules from jsRules, otherwise it's identical.
export const jsRules: { [key: string]: any } = {};
for (const key in rules) {
if (!Object.prototype.hasOwnProperty.call(rules, key)) {
if (!hasOwnProperty(rules, key)) {
continue;
}

const Rule = findRule(key, joinPaths(__dirname, "..", "rules"))!;
const Rule = findRule(key, joinPaths(__dirname, "..", "rules"));
if (Rule === "not-found") {
throw new Error(`Couldn't find rule '${key}'.`);
}
if (!Rule.metadata.typescriptOnly) {
jsRules[key] = (rules as any)[key];
}
Expand Down
164 changes: 92 additions & 72 deletions src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import * as resolve from "resolve";
import { FatalError } from "./error";

import { IOptions, RuleSeverity } from "./language/rule/rule";
import { arrayify, objectify, stripComments } from "./utils";
import { arrayify, hasOwnProperty, stripComments } from "./utils";

export interface IConfigurationFile {
/**
Expand Down Expand Up @@ -99,7 +99,7 @@ export function findConfiguration(configFile: string | null, inputFilePath: stri
loadResult.results = loadConfigurationFromPath(path);
return loadResult;
} catch (error) {
throw new FatalError(`Failed to load ${path}: ${error.message}`, error);
throw new FatalError(`Failed to load ${path}: ${(error as Error).message}`, error as Error);
}
}

Expand Down Expand Up @@ -154,15 +154,15 @@ export function loadConfigurationFromPath(configFilePath?: string): IConfigurati
return DEFAULT_CONFIG;
} else {
const resolvedConfigFilePath = resolveConfigurationPath(configFilePath);
let rawConfigFile: any;
let rawConfigFile: RawConfigFile;
if (path.extname(resolvedConfigFilePath) === ".json") {
const fileContent = stripComments(fs.readFileSync(resolvedConfigFilePath)
.toString()
.replace(/^\uFEFF/, ""));
rawConfigFile = JSON.parse(fileContent);
.toString()
.replace(/^\uFEFF/, ""));
rawConfigFile = JSON.parse(fileContent) as RawConfigFile;
} else {
rawConfigFile = require(resolvedConfigFilePath);
delete require.cache[resolvedConfigFilePath];
rawConfigFile = require(resolvedConfigFilePath) as RawConfigFile;
delete (require.cache as { [key: string]: any })[resolvedConfigFilePath]; // tslint:disable-line no-unsafe-any (Fixed in 5.2)
}

const configFileDir = path.dirname(resolvedConfigFilePath);
Expand Down Expand Up @@ -212,16 +212,23 @@ function resolveConfigurationPath(filePath: string, relativeTo?: string) {
export function extendConfigurationFile(targetConfig: IConfigurationFile,
nextConfigSource: IConfigurationFile): IConfigurationFile {

const combineProperties = (targetProperty: any, nextProperty: any) => {
const combinedProperty: any = {};
for (const name of Object.keys(objectify(targetProperty))) {
combinedProperty[name] = targetProperty[name];
}
const combineProperties = <T>(targetProperty: T | undefined, nextProperty: T | undefined): T => {
const combinedProperty: { [key: string]: any } = {};
add(targetProperty);
// next config source overwrites the target config object
for (const name of Object.keys(objectify(nextProperty))) {
combinedProperty[name] = nextProperty[name];
add(nextProperty);
return combinedProperty as T;

function add(property: T | undefined): void {
if (property) {
for (const name in property) {
if (hasOwnProperty(property, name)) {
combinedProperty[name] = property[name];
}
}
}

}
return combinedProperty;
};

const combineMaps = (target: Map<string, Partial<IOptions>>, next: Map<string, Partial<IOptions>>) => {
Expand Down Expand Up @@ -252,9 +259,9 @@ export function extendConfigurationFile(targetConfig: IConfigurationFile,
};
}

function getHomeDir() {
const environment = global.process.env;
const paths = [
function getHomeDir(): string | undefined {
const environment = global.process.env as { [key: string]: string };
const paths: string[] = [
environment.USERPROFILE,
environment.HOME,
environment.HOMEPATH,
Expand All @@ -266,6 +273,8 @@ function getHomeDir() {
return homePath;
}
}

return undefined;
}

// returns the absolute path (contrary to what the name implies)
Expand Down Expand Up @@ -317,9 +326,8 @@ export function getRulesDirectories(directories?: string | string[], relativeTo?
*
* @param ruleConfigValue The raw option setting of a rule
*/
function parseRuleOptions(ruleConfigValue: any, rawDefaultRuleSeverity: string): Partial<IOptions> {
function parseRuleOptions(ruleConfigValue: RawRuleConfig, rawDefaultRuleSeverity: string | undefined): Partial<IOptions> {
let ruleArguments: any[] | undefined;
let ruleSeverity: RuleSeverity;
let defaultRuleSeverity: RuleSeverity = "error";

if (rawDefaultRuleSeverity) {
Expand All @@ -337,43 +345,46 @@ function parseRuleOptions(ruleConfigValue: any, rawDefaultRuleSeverity: string):
}
}

let ruleSeverity = defaultRuleSeverity;

if (ruleConfigValue == null) {
ruleArguments = [];
ruleSeverity = "off";
} else if (Array.isArray(ruleConfigValue) && ruleConfigValue.length > 0) {
// old style: array
ruleArguments = ruleConfigValue.slice(1);
ruleSeverity = ruleConfigValue[0] === true ? defaultRuleSeverity : "off";
} else if (Array.isArray(ruleConfigValue)) {
if (ruleConfigValue.length > 0) {
// old style: array
ruleArguments = ruleConfigValue.slice(1);
ruleSeverity = ruleConfigValue[0] === true ? defaultRuleSeverity : "off";
}
} else if (typeof ruleConfigValue === "boolean") {
// old style: boolean
ruleArguments = [];
ruleSeverity = ruleConfigValue === true ? defaultRuleSeverity : "off";
} else if (ruleConfigValue.severity) {
switch (ruleConfigValue.severity.toLowerCase()) {
case "default":
ruleSeverity = defaultRuleSeverity;
break;
case "error":
ruleSeverity = "error";
break;
case "warn":
case "warning":
ruleSeverity = "warning";
break;
case "off":
case "none":
ruleSeverity = "off";
break;
default:
console.warn(`Invalid severity level: ${ruleConfigValue.severity}`);
ruleSeverity = defaultRuleSeverity;
} else if (typeof ruleConfigValue === "object") {
if (ruleConfigValue.severity) {
switch (ruleConfigValue.severity.toLowerCase()) {
case "default":
ruleSeverity = defaultRuleSeverity;
break;
case "error":
ruleSeverity = "error";
break;
case "warn":
case "warning":
ruleSeverity = "warning";
break;
case "off":
case "none":
ruleSeverity = "off";
break;
default:
console.warn(`Invalid severity level: ${ruleConfigValue.severity}`);
ruleSeverity = defaultRuleSeverity;
}
}
if (ruleConfigValue.options != null) {
ruleArguments = arrayify(ruleConfigValue.options);
}
} else {
ruleSeverity = defaultRuleSeverity;
}

if (ruleConfigValue && ruleConfigValue.options) {
ruleArguments = arrayify(ruleConfigValue.options);
}

return {
Expand All @@ -382,39 +393,48 @@ function parseRuleOptions(ruleConfigValue: any, rawDefaultRuleSeverity: string):
};
}

export interface RawConfigFile {
extends?: string | string[];
linterOptions?: IConfigurationFile["linterOptions"];
rulesDirectory?: string | string[];
defaultSeverity?: string;
rules?: RawRulesConfig;
jsRules?: RawRulesConfig;
}
export interface RawRulesConfig {
[key: string]: RawRuleConfig;
}
export type RawRuleConfig = null | undefined | boolean | any[] | {
severity?: RuleSeverity | "warn" | "none" | "default",
options?: any,
};

/**
* Parses a config file and normalizes legacy config settings
*
* @param configFile The raw object read from the JSON of a config file
* @param configFileDir The directory of the config file
*/
export function parseConfigFile(configFile: any, configFileDir?: string): IConfigurationFile {
const rules = new Map<string, Partial<IOptions>>();
const jsRules = new Map<string, Partial<IOptions>>();

if (configFile.rules) {
for (const ruleName in configFile.rules) {
if (configFile.rules.hasOwnProperty(ruleName)) {
rules.set(ruleName, parseRuleOptions(configFile.rules[ruleName], configFile.defaultSeverity));
}
}
}

if (configFile.jsRules) {
for (const ruleName in configFile.jsRules) {
if (configFile.jsRules.hasOwnProperty(ruleName)) {
jsRules.set(ruleName, parseRuleOptions(configFile.jsRules[ruleName], configFile.defaultSeverity));
}
}
}

export function parseConfigFile(configFile: RawConfigFile, configFileDir?: string): IConfigurationFile {
return {
extends: arrayify(configFile.extends),
jsRules,
jsRules: parseRules(configFile.jsRules),
linterOptions: configFile.linterOptions || {},
rules: parseRules(configFile.rules),
rulesDirectory: getRulesDirectories(configFile.rulesDirectory, configFileDir),
rules,
};

function parseRules(config: RawRulesConfig | undefined): Map<string, Partial<IOptions>> {
const map = new Map<string, Partial<IOptions>>();
if (config) {
for (const ruleName in config) {
if (hasOwnProperty(config, ruleName)) {
map.set(ruleName, parseRuleOptions(config[ruleName], configFile.defaultSeverity));
}
}
}
return map;
}
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class FatalError extends Error {
}

export function isError(possibleError: any): possibleError is Error {
return possibleError != null && possibleError.message !== undefined;
return possibleError != null && (possibleError as Error).message !== undefined;
}

export function showWarningOnce(message: string) {
Expand Down
12 changes: 6 additions & 6 deletions src/formatterLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@

import * as fs from "fs";
import * as path from "path";
import {FormatterFunction} from "./index";
import {FormatterConstructor} from "./index";
import {camelize} from "./utils";

const moduleDirectory = path.dirname(module.filename);
const CORE_FORMATTERS_DIRECTORY = path.resolve(moduleDirectory, ".", "formatters");

export function findFormatter(name: string | FormatterFunction, formattersDirectory?: string) {
export function findFormatter(name: string | FormatterConstructor, formattersDirectory?: string): FormatterConstructor | undefined {
if (typeof name === "function") {
return name;
} else if (typeof name === "string") {
Expand Down Expand Up @@ -52,24 +52,24 @@ export function findFormatter(name: string | FormatterFunction, formattersDirect
}
}

function loadFormatter(...paths: string[]) {
function loadFormatter(...paths: string[]): FormatterConstructor | undefined {
const formatterPath = paths.reduce((p, c) => path.join(p, c), "");
const fullPath = path.resolve(moduleDirectory, formatterPath);

if (fs.existsSync(`${fullPath}.js`)) {
const formatterModule = require(fullPath);
const formatterModule = require(fullPath) as { Formatter: FormatterConstructor };
return formatterModule.Formatter;
}

return undefined;
}

function loadFormatterModule(name: string) {
function loadFormatterModule(name: string): FormatterConstructor | undefined {
let src: string;
try {
src = require.resolve(name);
} catch (e) {
return undefined;
}
return require(src).Formatter;
return (require(src) as { Formatter: FormatterConstructor }).Formatter;
}
7 changes: 3 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import * as Configuration from "./configuration";
import * as Formatters from "./formatters";
import {FormatterConstructor} from "./language/formatter/formatter";
import {RuleFailure} from "./language/rule/rule";
import * as Linter from "./linter";
import * as Rules from "./rules";
Expand All @@ -38,15 +39,13 @@ export interface LintResult {
warningCount: number;
failures: RuleFailure[];
fixes?: RuleFailure[];
format: string | FormatterFunction;
format: string | FormatterConstructor;
output: string;
}

export type FormatterFunction = (failures: RuleFailure[]) => string;

export interface ILinterOptions {
fix: boolean;
formatter?: string | FormatterFunction;
formatter?: string | FormatterConstructor;
formattersDirectory?: string;
rulesDirectory?: string | string[];
}
4 changes: 4 additions & 0 deletions src/language/formatter/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ export interface IFormatterMetadata {

export type ConsumerType = "human" | "machine";

export interface FormatterConstructor {
new(): IFormatter;
}

export interface IFormatter {
/**
* Formats linter results
Expand Down
Loading

0 comments on commit a3d8d6f

Please sign in to comment.