refactor: replace any in console (#1804)

This commit is contained in:
Yoshiya Hinosawa 2019-02-19 00:31:35 +09:00 committed by Ryan Dahl
parent 96afb62dfb
commit 9e942f30b9

View file

@ -1,13 +1,13 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { isTypedArray } from "./util"; import { isTypedArray } from "./util";
import { TypedArray } from "./types";
import { TextEncoder } from "./text_encoding"; import { TextEncoder } from "./text_encoding";
import { File, stdout } from "./files"; import { File, stdout } from "./files";
import { cliTable } from "./console_table"; import { cliTable } from "./console_table";
import { formatError } from "./format_error"; import { formatError } from "./format_error";
import { libdeno } from "./libdeno"; import { libdeno } from "./libdeno";
// tslint:disable-next-line:no-any type ConsoleContext = Set<unknown>;
type ConsoleContext = Set<any>;
type ConsoleOptions = Partial<{ type ConsoleOptions = Partial<{
showHidden: boolean; showHidden: boolean;
depth: number; depth: number;
@ -43,8 +43,7 @@ function clearScreenDown(stream: File) {
stream.write(uint8); stream.write(uint8);
} }
// tslint:disable-next-line:no-any function getClassInstanceName(instance: unknown): string {
function getClassInstanceName(instance: any): string {
if (typeof instance !== "object") { if (typeof instance !== "object") {
return ""; return "";
} }
@ -67,26 +66,24 @@ function createFunctionString(value: Function, ctx: ConsoleContext): string {
return `[${cstrName}]`; return `[${cstrName}]`;
} }
interface IterablePrintConfig { interface IterablePrintConfig<T> {
typeName: string; typeName: string;
displayName: string; displayName: string;
delims: [string, string]; delims: [string, string];
entryHandler: ( entryHandler: (
// tslint:disable-next-line:no-any entry: T,
entry: any,
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number maxLevel: number
) => string; ) => string;
} }
function createIterableString( function createIterableString<T>(
// tslint:disable-next-line:no-any value: Iterable<T>,
value: any,
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number, maxLevel: number,
config: IterablePrintConfig config: IterablePrintConfig<T>
): string { ): string {
if (level >= maxLevel) { if (level >= maxLevel) {
return `[${config.typeName}]`; return `[${config.typeName}]`;
@ -107,13 +104,12 @@ function createIterableString(
} }
function createArrayString( function createArrayString(
// tslint:disable-next-line:no-any value: Array<unknown>,
value: any[],
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number maxLevel: number
): string { ): string {
const printConfig: IterablePrintConfig = { const printConfig: IterablePrintConfig<unknown> = {
typeName: "Array", typeName: "Array",
displayName: "", displayName: "",
delims: ["[", "]"], delims: ["[", "]"],
@ -125,13 +121,12 @@ function createArrayString(
function createTypedArrayString( function createTypedArrayString(
typedArrayName: string, typedArrayName: string,
// tslint:disable-next-line:no-any value: TypedArray,
value: any,
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number maxLevel: number
): string { ): string {
const printConfig: IterablePrintConfig = { const printConfig: IterablePrintConfig<unknown> = {
typeName: typedArrayName, typeName: typedArrayName,
displayName: typedArrayName, displayName: typedArrayName,
delims: ["[", "]"], delims: ["[", "]"],
@ -142,13 +137,12 @@ function createTypedArrayString(
} }
function createSetString( function createSetString(
// tslint:disable-next-line:no-any value: Set<unknown>,
value: Set<any>,
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number maxLevel: number
): string { ): string {
const printConfig: IterablePrintConfig = { const printConfig: IterablePrintConfig<unknown> = {
typeName: "Set", typeName: "Set",
displayName: "Set", displayName: "Set",
delims: ["{", "}"], delims: ["{", "}"],
@ -159,13 +153,12 @@ function createSetString(
} }
function createMapString( function createMapString(
// tslint:disable-next-line:no-any value: Map<unknown, unknown>,
value: Map<any, any>,
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number maxLevel: number
): string { ): string {
const printConfig: IterablePrintConfig = { const printConfig: IterablePrintConfig<[unknown, unknown]> = {
typeName: "Map", typeName: "Map",
displayName: "Map", displayName: "Map",
delims: ["{", "}"], delims: ["{", "}"],
@ -218,8 +211,7 @@ function createNumberWrapperString(value: Number) {
// TODO: Proxy // TODO: Proxy
function createRawObjectString( function createRawObjectString(
// tslint:disable-next-line:no-any value: { [key: string]: unknown },
value: any,
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number maxLevel: number
@ -260,8 +252,7 @@ function createRawObjectString(
} }
function createObjectString( function createObjectString(
// tslint:disable-next-line:no-any value: {},
value: any,
...args: [ConsoleContext, number, number] ...args: [ConsoleContext, number, number]
): string { ): string {
if (value instanceof Error) { if (value instanceof Error) {
@ -283,11 +274,9 @@ function createObjectString(
} else if (value instanceof Date) { } else if (value instanceof Date) {
return createDateString(value as Date); return createDateString(value as Date);
} else if (value instanceof Set) { } else if (value instanceof Set) {
// tslint:disable-next-line:no-any return createSetString(value as Set<unknown>, ...args);
return createSetString(value as Set<any>, ...args);
} else if (value instanceof Map) { } else if (value instanceof Map) {
// tslint:disable-next-line:no-any return createMapString(value as Map<unknown, unknown>, ...args);
return createMapString(value as Map<any, any>, ...args);
} else if (value instanceof WeakSet) { } else if (value instanceof WeakSet) {
return createWeakSetString(); return createWeakSetString();
} else if (value instanceof WeakMap) { } else if (value instanceof WeakMap) {
@ -305,8 +294,7 @@ function createObjectString(
} }
function stringify( function stringify(
// tslint:disable-next-line:no-any value: unknown,
value: any,
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number maxLevel: number
@ -340,8 +328,7 @@ function stringify(
// Print strings when they are inside of arrays or objects with quotes // Print strings when they are inside of arrays or objects with quotes
function stringifyWithQuotes( function stringifyWithQuotes(
// tslint:disable-next-line:no-any value: unknown,
value: any,
ctx: ConsoleContext, ctx: ConsoleContext,
level: number, level: number,
maxLevel: number maxLevel: number
@ -370,8 +357,7 @@ function isCollapsed(
* @internal * @internal
*/ */
export function stringifyArgs( export function stringifyArgs(
// tslint:disable-next-line:no-any args: Array<unknown>,
args: any[],
options: ConsoleOptions = {} options: ConsoleOptions = {}
): string { ): string {
const first = args[0]; const first = args[0];
@ -401,7 +387,7 @@ export function stringifyArgs(
} else if (typeof tempInteger === "symbol") { } else if (typeof tempInteger === "symbol") {
tempStr = "NaN"; tempStr = "NaN";
} else { } else {
tempStr = `${parseInt(tempInteger, 10)}`; tempStr = `${parseInt(String(tempInteger), 10)}`;
} }
break; break;
case CHAR_LOWERCASE_F: case CHAR_LOWERCASE_F:
@ -410,7 +396,7 @@ export function stringifyArgs(
if (typeof tempFloat === "symbol") { if (typeof tempFloat === "symbol") {
tempStr = "NaN"; tempStr = "NaN";
} else { } else {
tempStr = `${parseFloat(tempFloat)}`; tempStr = `${parseFloat(String(tempFloat))}`;
} }
break; break;
case CHAR_LOWERCASE_O: case CHAR_LOWERCASE_O:
@ -418,8 +404,7 @@ export function stringifyArgs(
// format as an object // format as an object
tempStr = stringify( tempStr = stringify(
args[++a], args[++a],
// tslint:disable-next-line:no-any new Set<unknown>(),
new Set<any>(),
0, 0,
// tslint:disable-next-line:triple-equals // tslint:disable-next-line:triple-equals
options.depth != undefined ? options.depth : DEFAULT_MAX_DEPTH options.depth != undefined ? options.depth : DEFAULT_MAX_DEPTH
@ -468,8 +453,7 @@ export function stringifyArgs(
// use default maximum depth for null or undefined argument // use default maximum depth for null or undefined argument
str += stringify( str += stringify(
value, value,
// tslint:disable-next-line:no-any new Set<unknown>(),
new Set<any>(),
0, 0,
// tslint:disable-next-line:triple-equals // tslint:disable-next-line:triple-equals
options.depth != undefined ? options.depth : DEFAULT_MAX_DEPTH options.depth != undefined ? options.depth : DEFAULT_MAX_DEPTH
@ -510,8 +494,7 @@ export class Console {
} }
/** Writes the arguments to stdout */ /** Writes the arguments to stdout */
// tslint:disable-next-line:no-any log = (...args: Array<unknown>): void => {
log = (...args: any[]): void => {
this.printFunc( this.printFunc(
stringifyArgs(args, { stringifyArgs(args, {
indentLevel: this.indentLevel, indentLevel: this.indentLevel,
@ -528,14 +511,12 @@ export class Console {
info = this.log; info = this.log;
/** Writes the properties of the supplied `obj` to stdout */ /** Writes the properties of the supplied `obj` to stdout */
// tslint:disable-next-line:no-any dir = (obj: unknown, options: ConsoleOptions = {}) => {
dir = (obj: any, options: ConsoleOptions = {}) => {
this.log(stringifyArgs([obj], options)); this.log(stringifyArgs([obj], options));
}; };
/** Writes the arguments to stdout */ /** Writes the arguments to stdout */
// tslint:disable-next-line:no-any warn = (...args: Array<unknown>): void => {
warn = (...args: any[]): void => {
this.printFunc( this.printFunc(
stringifyArgs(args, { stringifyArgs(args, {
indentLevel: this.indentLevel, indentLevel: this.indentLevel,
@ -554,8 +535,7 @@ export class Console {
* *
* ref: https://console.spec.whatwg.org/#assert * ref: https://console.spec.whatwg.org/#assert
*/ */
// tslint:disable-next-line:no-any assert = (condition = false, ...args: Array<unknown>): void => {
assert = (condition = false, ...args: any[]): void => {
if (condition) { if (condition) {
return; return;
} }
@ -598,11 +578,7 @@ export class Console {
} }
}; };
// tslint:disable-next-line:no-any table = (data: unknown, properties?: string[]): void => {
table = (data: any, properties?: string[]): void => {
// tslint:disable-next-line:no-any
type Value = any;
if (properties !== undefined && !Array.isArray(properties)) { if (properties !== undefined && !Array.isArray(properties)) {
throw new Error( throw new Error(
"The 'properties' argument must be of type Array\ "The 'properties' argument must be of type Array\
@ -614,60 +590,56 @@ export class Console {
return this.log(data); return this.log(data);
} }
const objectValues: { [key: string]: Value[] } = {}; const objectValues: { [key: string]: string[] } = {};
const indexKeys: string[] = []; const indexKeys: string[] = [];
const values: Value[] = []; const values: string[] = [];
const stringifyValue = (value: Value) => const stringifyValue = (value: unknown) =>
stringifyWithQuotes( stringifyWithQuotes(value, new Set<unknown>(), 0, 1);
value,
// tslint:disable-next-line:no-any
new Set<any>(),
0,
1
);
const toTable = (header: string[], body: string[][]) => const toTable = (header: string[], body: string[][]) =>
this.log(cliTable(header, body)); this.log(cliTable(header, body));
const createColumn = (value: Value, shift?: number): string[] => [ const createColumn = (value: unknown, shift?: number): string[] => [
...(shift ? [...new Array(shift)].map(() => "") : []), ...(shift ? [...new Array(shift)].map(() => "") : []),
stringifyValue(value) stringifyValue(value)
]; ];
let resultData = data; let resultData: { [key: string]: unknown };
const isSet = data instanceof Set; const isSet = data instanceof Set;
const isMap = data instanceof Map; const isMap = data instanceof Map;
const valuesKey = "Values"; const valuesKey = "Values";
const indexKey = isSet || isMap ? "(iteration index)" : "(index)"; const indexKey = isSet || isMap ? "(iteration index)" : "(index)";
if (isSet) { if (data instanceof Set) {
resultData = [...data]; resultData = [...data];
} else if (isMap) { } else if (data instanceof Map) {
let idx = 0; let idx = 0;
resultData = {}; resultData = {};
data.forEach((k: Value, v: Value) => { data.forEach((k: unknown, v: unknown) => {
resultData[idx] = { Key: k, Values: v }; resultData[idx] = { Key: k, Values: v };
idx++; idx++;
}); });
} else {
resultData = data!;
} }
Object.keys(resultData).forEach((k, idx) => { Object.keys(resultData).forEach((k, idx) => {
const value = resultData[k]; const value: unknown = resultData[k]!;
if (value !== null && typeof value === "object") { if (value !== null && typeof value === "object") {
Object.keys(value).forEach(k => { Object.entries(value as { [key: string]: unknown }).forEach(
const v = value[k]; ([k, v]) => {
if (properties && !properties.includes(k)) {
return;
}
if (properties && !properties.includes(k)) { if (objectValues[k]) {
return; objectValues[k].push(stringifyValue(v));
} else {
objectValues[k] = createColumn(v, idx);
}
} }
);
if (objectValues[k]) {
objectValues[k].push(stringifyValue(v));
} else {
objectValues[k] = createColumn(v, idx);
}
});
values.push(""); values.push("");
} else { } else {
@ -702,8 +674,7 @@ export class Console {
timerMap.set(label, Date.now()); timerMap.set(label, Date.now());
}; };
// tslint:disable-next-line:no-any timeLog = (label = "default", ...args: Array<unknown>): void => {
timeLog = (label = "default", ...args: any[]): void => {
label = String(label); label = String(label);
if (!timerMap.has(label)) { if (!timerMap.has(label)) {
@ -767,18 +738,14 @@ export class Console {
* inspect() converts input into string that has the same format * inspect() converts input into string that has the same format
* as printed by console.log(...); * as printed by console.log(...);
*/ */
export function inspect( export function inspect(value: unknown, options?: ConsoleOptions) {
value: any, // tslint:disable-line:no-any
options?: ConsoleOptions
) {
const opts = options || {}; const opts = options || {};
if (typeof value === "string") { if (typeof value === "string") {
return value; return value;
} else { } else {
return stringify( return stringify(
value, value,
// tslint:disable-next-line:no-any new Set<unknown>(),
new Set<any>(),
0, 0,
// tslint:disable-next-line:triple-equals // tslint:disable-next-line:triple-equals
opts.depth != undefined ? opts.depth : DEFAULT_MAX_DEPTH opts.depth != undefined ? opts.depth : DEFAULT_MAX_DEPTH