refactor: use ansis instead of chalk (#11263)

This commit is contained in:
Lucian Mocanu 2025-02-27 19:53:59 +01:00 committed by GitHub
parent 17a3c52855
commit 988673c549
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 139 additions and 199 deletions

View File

@ -86,7 +86,7 @@ This code will log all queries which run for more than `1 second`.
TypeORM ships with 4 different types of logger:
- `advanced-console` - this is the default logger which logs all messages into the console using color
and sql syntax highlighting (using [chalk](https://github.com/chalk/chalk)).
and sql syntax highlighting.
- `simple-console` - this is a simple console logger which is exactly the same as the advanced logger, but it does not use any color highlighting.
This logger can be used if you have problems / or don't like colorized logs.
- `file` - this logger writes all logs into `ormlogs.log` in the root folder of your project (near `package.json`).

View File

@ -84,7 +84,7 @@
TypeORM 附带 4 种不同类型的记录器:
- `advanced-console` - 默认记录器,它将使用颜色和 sql 语法高亮显示所有记录到控制台中的消息(使用[chalk](https://github.com/chalk/chalk)
- `advanced-console` - 默认记录器,它将使用颜色和 sql 语法高亮显示所有记录到控制台中的消息。
- `simple-console` - 简单的控制台记录器,与高级记录器完全相同,但它不使用任何颜色突出显示。
如果你不喜欢/或者使用彩色日志有问题,可以使用此记录器。
- `file` - 这个记录器将所有日志写入项目根文件夹中的`ormlogs.log`(靠近`package.json``ormconfig.json`)。

79
package-lock.json generated
View File

@ -10,9 +10,9 @@
"license": "MIT",
"dependencies": {
"@sqltools/formatter": "^1.2.5",
"ansis": "^3.9.0",
"app-root-path": "^3.1.0",
"buffer": "^6.0.3",
"chalk": "^4.1.2",
"dayjs": "^1.11.9",
"debug": "^4.3.4",
"dotenv": "^16.0.3",
@ -20,7 +20,7 @@
"sha.js": "^2.4.11",
"sql-highlight": "^6.0.0",
"tslib": "^2.5.0",
"uuid": "^9.0.0",
"uuid": "^11.0.5",
"yargs": "^17.6.2"
},
"bin": {
@ -1812,20 +1812,6 @@
"node": ">=8"
}
},
"node_modules/@types/gulp/node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/@types/gulp/node_modules/glob-parent": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
@ -2462,6 +2448,15 @@
"node": ">=0.10.0"
}
},
"node_modules/ansis": {
"version": "3.9.0",
"resolved": "https://registry.npmjs.org/ansis/-/ansis-3.9.0.tgz",
"integrity": "sha512-PcDrVe15ldexeZMsVLBAzBwF2KhZgaU0R+CHxH+x5kqn/pO+UWVBZJ+NEXMPpEOLUFeNsnNdoWYc2gwO+MVkDg==",
"license": "ISC",
"engines": {
"node": ">=16"
}
},
"node_modules/anymatch": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz",
@ -3470,6 +3465,7 @@
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dev": true,
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
@ -5578,25 +5574,6 @@
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
"dev": true
},
"node_modules/fsevents": {
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
"deprecated": "The v1 package contains DANGEROUS / INSECURE binaries. Upgrade to safe fsevents v2",
"dev": true,
"hasInstallScript": true,
"optional": true,
"os": [
"darwin"
],
"dependencies": {
"bindings": "^1.5.0",
"nan": "^2.12.1"
},
"engines": {
"node": ">= 4.0"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@ -6936,6 +6913,7 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"engines": {
"node": ">=8"
}
@ -9546,20 +9524,6 @@
"node": ">=8"
}
},
"node_modules/mocha/node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/mocha/node_modules/glob": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz",
@ -9902,13 +9866,6 @@
"node": ">=12"
}
},
"node_modules/nan": {
"version": "2.18.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.18.0.tgz",
"integrity": "sha512-W7tfG7vMOGtD30sHoZSSc/JVYiyDPEyQVso/Zz+/uQd0B0L46gtC+pHha5FFMRpil6fm/AoEcRWyOVi4+E/f8w==",
"dev": true,
"optional": true
},
"node_modules/nanomatch": {
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz",
@ -13437,6 +13394,7 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"dependencies": {
"has-flag": "^4.0.0"
},
@ -14405,15 +14363,16 @@
"dev": true
},
"node_modules/uuid": {
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
"integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
"version": "11.0.5",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.5.tgz",
"integrity": "sha512-508e6IcKLrhxKdBbcA2b4KQZlLVp2+J5UwQ6F7Drckkc5N9ZJwFa4TgWtsww9UG8fGHbm6gbV19TdM5pQ4GaIA==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/v8-compile-cache-lib": {

View File

@ -222,9 +222,9 @@
},
"dependencies": {
"@sqltools/formatter": "^1.2.5",
"ansis": "^3.9.0",
"app-root-path": "^3.1.0",
"buffer": "^6.0.3",
"chalk": "^4.1.2",
"dayjs": "^1.11.9",
"debug": "^4.3.4",
"dotenv": "^16.0.3",
@ -232,7 +232,7 @@
"sha.js": "^2.4.11",
"sql-highlight": "^6.0.0",
"tslib": "^2.5.0",
"uuid": "^9.0.0",
"uuid": "^11.0.5",
"yargs": "^17.6.2"
},
"scripts": {

View File

@ -1,9 +1,9 @@
import { DataSource } from "../data-source/DataSource"
import * as yargs from "yargs"
import chalk from "chalk"
import { PlatformTools } from "../platform/PlatformTools"
import ansi from "ansis"
import path from "path"
import process from "process"
import yargs from "yargs"
import { DataSource } from "../data-source/DataSource"
import { PlatformTools } from "../platform/PlatformTools"
import { CommandUtils } from "./CommandUtils"
/**
@ -45,7 +45,7 @@ export class CacheClearCommand implements yargs.CommandModule {
}
await dataSource.queryResultCache.clear()
console.log(chalk.green("Cache was successfully cleared"))
console.log(ansi.green`Cache was successfully cleared`)
await dataSource.destroy()
} catch (err) {

View File

@ -1,8 +1,8 @@
import { CommandUtils } from "./CommandUtils"
import * as yargs from "yargs"
import chalk from "chalk"
import { PlatformTools } from "../platform/PlatformTools"
import ansi from "ansis"
import path from "path"
import yargs from "yargs"
import { PlatformTools } from "../platform/PlatformTools"
import { CommandUtils } from "./CommandUtils"
/**
* Generates a new entity.
@ -28,18 +28,14 @@ export class EntityCreateCommand implements yargs.CommandModule {
const fileContent = EntityCreateCommand.getTemplate(filename)
const fileExists = await CommandUtils.fileExists(fullPath + ".ts")
if (fileExists) {
throw `File ${chalk.blue(fullPath + ".ts")} already exists`
throw new Error(`File "${fullPath}.ts" already exists`)
}
await CommandUtils.createFile(fullPath + ".ts", fileContent)
console.log(
chalk.green(
`Entity ${chalk.blue(
fullPath + ".ts",
)} has been created successfully.`,
),
ansi.green`Entity ${ansi.blue`${fullPath}.ts`} has been created successfully.`,
)
} catch (err) {
PlatformTools.logCmdErr("Error during entity creation:", err)
} catch (error) {
PlatformTools.logCmdErr("Error during entity creation:", error)
process.exit(1)
}
}

View File

@ -1,10 +1,10 @@
import { CommandUtils } from "./CommandUtils"
import * as path from "path"
import * as yargs from "yargs"
import chalk from "chalk"
import ansi from "ansis"
import { exec } from "child_process"
import path from "path"
import yargs from "yargs"
import { TypeORMError } from "../error"
import { PlatformTools } from "../platform/PlatformTools"
import { CommandUtils } from "./CommandUtils"
/**
* Generates a new project with TypeORM.
@ -125,26 +125,24 @@ export class InitCommand implements yargs.CommandModule {
if (args.name) {
console.log(
chalk.green(
`Project created inside ${chalk.blue(
basePath,
)} directory.`,
),
ansi.green`Project created inside ${ansi.blue(
basePath,
)} directory.`,
)
} else {
console.log(
chalk.green(`Project created inside current directory.`),
ansi.green`Project created inside current directory.`,
)
}
console.log(chalk.green(`Please wait, installing dependencies...`))
console.log(ansi.green`Please wait, installing dependencies...`)
if (args.pm && installNpm) {
await InitCommand.executeCommand("npm install", basePath)
} else {
await InitCommand.executeCommand("yarn install", basePath)
}
console.log(chalk.green(`Done! Start playing with a new project!`))
console.log(ansi.green`Done! Start playing with a new project!`)
} catch (err) {
PlatformTools.logCmdErr("Error during project initialization:", err)
process.exit(1)

View File

@ -1,9 +1,9 @@
import { CommandUtils } from "./CommandUtils"
import { camelCase } from "../util/StringUtils"
import * as yargs from "yargs"
import chalk from "chalk"
import { PlatformTools } from "../platform/PlatformTools"
import ansi from "ansis"
import path from "path"
import yargs from "yargs"
import { PlatformTools } from "../platform/PlatformTools"
import { camelCase } from "../util/StringUtils"
import { CommandUtils } from "./CommandUtils"
/**
* Creates a new migration file.
@ -56,7 +56,7 @@ export class MigrationCreateCommand implements yargs.CommandModule {
fileContent,
)
console.log(
`Migration ${chalk.blue(
`Migration ${ansi.blue(
fullPath + (args.outputJs ? ".js" : ".ts"),
)} has been generated successfully.`,
)

View File

@ -1,12 +1,12 @@
import { CommandUtils } from "./CommandUtils"
import { camelCase } from "../util/StringUtils"
import * as yargs from "yargs"
import chalk from "chalk"
import { format } from "@sqltools/formatter/lib/sqlFormatter"
import { PlatformTools } from "../platform/PlatformTools"
import { DataSource } from "../data-source"
import * as path from "path"
import ansi from "ansis"
import path from "path"
import process from "process"
import yargs from "yargs"
import { DataSource } from "../data-source"
import { PlatformTools } from "../platform/PlatformTools"
import { camelCase } from "../util/StringUtils"
import { CommandUtils } from "./CommandUtils"
/**
* Generates a new migration file with sql needs to be executed to update schema.
@ -140,19 +140,17 @@ export class MigrationGenerateCommand implements yargs.CommandModule {
if (!upSqls.length) {
if (args.check) {
console.log(
chalk.green(`No changes in database schema were found`),
ansi.green`No changes in database schema were found`,
)
process.exit(0)
} else {
console.log(
chalk.yellow(
`No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command`,
),
ansi.yellow`No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command`,
)
process.exit(1)
}
} else if (!args.path) {
console.log(chalk.yellow("Please specify a migration path"))
console.log(ansi.yellow`Please specify a migration path`)
process.exit(1)
}
@ -172,21 +170,19 @@ export class MigrationGenerateCommand implements yargs.CommandModule {
if (args.check) {
console.log(
chalk.yellow(
`Unexpected changes in database schema were found in check mode:\n\n${chalk.white(
fileContent,
)}`,
),
ansi.yellow`Unexpected changes in database schema were found in check mode:\n\n${ansi.white(
fileContent,
)}`,
)
process.exit(1)
}
if (args.dryrun) {
console.log(
chalk.green(
`Migration ${chalk.blue(
ansi.green(
`Migration ${ansi.blue(
fullPath + extension,
)} has content:\n\n${chalk.white(fileContent)}`,
)} has content:\n\n${ansi.white(fileContent)}`,
),
)
} else {
@ -195,11 +191,9 @@ export class MigrationGenerateCommand implements yargs.CommandModule {
await CommandUtils.createFile(migrationFileName, fileContent)
console.log(
chalk.green(
`Migration ${chalk.blue(
migrationFileName,
)} has been generated successfully.`,
),
ansi.green`Migration ${ansi.blue(
migrationFileName,
)} has been generated successfully.`,
)
if (args.exitProcess !== false) {
process.exit(0)

View File

@ -1,10 +1,10 @@
import { QueryRunner } from "../query-runner/QueryRunner"
import { DataSource } from "../data-source/DataSource"
import { PlatformTools } from "../platform/PlatformTools"
import * as yargs from "yargs"
import chalk from "chalk"
import ansi from "ansis"
import path from "path"
import process from "process"
import yargs from "yargs"
import { DataSource } from "../data-source/DataSource"
import { PlatformTools } from "../platform/PlatformTools"
import { QueryRunner } from "../query-runner/QueryRunner"
import { CommandUtils } from "./CommandUtils"
/**
@ -48,19 +48,16 @@ export class QueryCommand implements yargs.CommandModule {
queryRunner = dataSource.createQueryRunner()
const query = args.query as string
console.log(
chalk.green("Running query: ") +
PlatformTools.highlightSql(query),
ansi.green`Running query: ` + PlatformTools.highlightSql(query),
)
const queryResult = await queryRunner.query(query)
if (typeof queryResult === "undefined") {
console.log(
chalk.green(
"Query has been executed. No result was returned.",
),
ansi.green`Query has been executed. No result was returned.`,
)
} else {
console.log(chalk.green("Query has been executed. Result: "))
console.log(ansi.green`Query has been executed. Result: `)
console.dir(queryResult, {
breakLength: Infinity,
compact: false,

View File

@ -1,9 +1,9 @@
import { DataSource } from "../data-source/DataSource"
import * as yargs from "yargs"
import chalk from "chalk"
import { PlatformTools } from "../platform/PlatformTools"
import ansi from "ansis"
import path from "path"
import process from "process"
import yargs from "yargs"
import { DataSource } from "../data-source/DataSource"
import { PlatformTools } from "../platform/PlatformTools"
import { CommandUtils } from "./CommandUtils"
/**
@ -41,7 +41,7 @@ export class SchemaDropCommand implements yargs.CommandModule {
await dataSource.destroy()
console.log(
chalk.green("Database schema has been successfully dropped."),
ansi.green`Database schema has been successfully dropped.`,
)
} catch (err) {
PlatformTools.logCmdErr("Error during schema drop:", err)

View File

@ -1,9 +1,9 @@
import { DataSource } from "../data-source/DataSource"
import * as yargs from "yargs"
import chalk from "chalk"
import { PlatformTools } from "../platform/PlatformTools"
import ansi from "ansis"
import path from "path"
import process from "process"
import yargs from "yargs"
import { DataSource } from "../data-source/DataSource"
import { PlatformTools } from "../platform/PlatformTools"
import { CommandUtils } from "./CommandUtils"
/**
@ -44,42 +44,28 @@ export class SchemaLogCommand implements yargs.CommandModule {
if (sqlInMemory.upQueries.length === 0) {
console.log(
chalk.yellow(
"Your schema is up to date - there are no queries to be executed by schema synchronization.",
),
ansi.yellow`Your schema is up to date - there are no queries to be executed by schema synchronization.`,
)
} else {
const lengthSeparators = String(sqlInMemory.upQueries.length)
.split("")
.map((char) => "-")
.join("")
console.log(
chalk.yellow(
"---------------------------------------------------------------" +
lengthSeparators,
),
const lineSeparator = "".padStart(
63 + String(sqlInMemory.upQueries.length).length,
"-",
)
console.log(ansi.yellow(lineSeparator))
console.log(
chalk.yellow.bold(
`-- Schema synchronization will execute following sql queries (${chalk.white(
sqlInMemory.upQueries.length.toString(),
)}):`,
),
)
console.log(
chalk.yellow(
"---------------------------------------------------------------" +
lengthSeparators,
),
ansi.yellow
.bold`-- Schema synchronization will execute following sql queries (${ansi.white(
sqlInMemory.upQueries.length.toString(),
)}):`,
)
console.log(ansi.yellow(lineSeparator))
sqlInMemory.upQueries.forEach((upQuery) => {
let sqlString = upQuery.query
sqlString = sqlString.trim()
sqlString =
sqlString.substr(-1) === ";"
? sqlString
: sqlString + ";"
sqlString = sqlString.endsWith(";")
? sqlString
: sqlString + ";"
console.log(PlatformTools.highlightSql(sqlString))
})
}

View File

@ -1,9 +1,9 @@
import { DataSource } from "../data-source/DataSource"
import * as yargs from "yargs"
import chalk from "chalk"
import { PlatformTools } from "../platform/PlatformTools"
import ansi from "ansis"
import path from "path"
import process from "process"
import yargs from "yargs"
import { DataSource } from "../data-source/DataSource"
import { PlatformTools } from "../platform/PlatformTools"
import { CommandUtils } from "./CommandUtils"
/**
@ -41,7 +41,7 @@ export class SchemaSyncCommand implements yargs.CommandModule {
await dataSource.destroy()
console.log(
chalk.green("Schema synchronization finished successfully."),
ansi.green`Schema synchronization finished successfully.`,
)
} catch (err) {
PlatformTools.logCmdErr("Error during schema synchronization:", err)

View File

@ -1,6 +1,6 @@
import * as yargs from "yargs"
import chalk from "chalk"
import ansi from "ansis"
import path from "path"
import yargs from "yargs"
import { PlatformTools } from "../platform/PlatformTools"
import { CommandUtils } from "./CommandUtils"
@ -28,18 +28,16 @@ export class SubscriberCreateCommand implements yargs.CommandModule {
const fileContent = SubscriberCreateCommand.getTemplate(filename)
const fileExists = await CommandUtils.fileExists(fullPath + ".ts")
if (fileExists) {
throw `File ${chalk.blue(fullPath + ".ts")} already exists`
throw new Error(`File "${fullPath}.ts" already exists`)
}
await CommandUtils.createFile(fullPath + ".ts", fileContent)
console.log(
chalk.green(
`Subscriber ${chalk.blue(
fullPath,
)} has been created successfully.`,
ansi.green(
`Subscriber ${ansi.blue`${fullPath}.ts`} has been created successfully.`,
),
)
} catch (err) {
PlatformTools.logCmdErr("Error during subscriber creation:")
} catch (error) {
PlatformTools.logCmdErr("Error during subscriber creation:", error)
process.exit(1)
}
}

View File

@ -116,7 +116,7 @@ export class PlatformTools {
}
/**
* Logging functions needed by AdvancedConsoleLogger (but here without chalk)
* Logging functions needed by AdvancedConsoleLogger (but here without ANSI colors)
*/
static logInfo(prefix: string, info: any) {
console.info(prefix + " ", info);

View File

@ -1,11 +1,11 @@
import path from "path"
import fs from "fs"
import ansi from "ansis"
import dotenv from "dotenv"
import chalk from "chalk"
import fs from "fs"
import path from "path"
import { highlight } from "sql-highlight"
export { ReadStream } from "fs"
export { EventEmitter } from "events"
export { ReadStream } from "fs"
export { Readable, Writable } from "stream"
/**
@ -205,42 +205,54 @@ export class PlatformTools {
* Highlights sql string to be printed in the console.
*/
static highlightSql(sql: string) {
return highlight(sql)
return highlight(sql, {
colors: {
keyword: ansi.blueBright.open,
function: ansi.magentaBright.open,
number: ansi.green.open,
string: ansi.white.open,
identifier: ansi.white.open,
special: ansi.white.open,
bracket: ansi.white.open,
comment: ansi.gray.open,
clear: ansi.reset.open,
},
})
}
/**
* Logging functions needed by AdvancedConsoleLogger
*/
static logInfo(prefix: string, info: any) {
console.log(chalk.gray.underline(prefix), info)
console.log(ansi.gray.underline(prefix), info)
}
static logError(prefix: string, error: any) {
console.log(chalk.underline.red(prefix), error)
console.log(ansi.underline.red(prefix), error)
}
static logWarn(prefix: string, warning: any) {
console.log(chalk.underline.yellow(prefix), warning)
console.log(ansi.underline.yellow(prefix), warning)
}
static log(message: string) {
console.log(chalk.underline(message))
console.log(ansi.underline(message))
}
static info(info: any) {
return chalk.gray(info)
return ansi.gray(info)
}
static error(error: any) {
return chalk.red(error)
return ansi.red(error)
}
static warn(message: string) {
return chalk.yellow(message)
return ansi.yellow(message)
}
static logCmdErr(prefix: string, err?: any) {
console.log(chalk.black.bgRed(prefix))
console.log(ansi.black.bgRed(prefix))
if (err) console.error(err)
}
}