Skip to content

Commit

Permalink
🗞️ Adding in Default Colors to print outs (#381)
Browse files Browse the repository at this point in the history
  • Loading branch information
sirarthurmoney authored Feb 10, 2024
1 parent cd89a6f commit e766c86
Show file tree
Hide file tree
Showing 7 changed files with 174 additions and 84 deletions.
7 changes: 7 additions & 0 deletions .changeset/empty-lamps-marry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@layerzerolabs/ua-devtools-evm-hardhat-test": patch
"@layerzerolabs/ua-devtools-evm-hardhat": patch
"@layerzerolabs/io-devtools": patch
---

Adding in Default Colors to print outs
1 change: 1 addition & 0 deletions packages/io-devtools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"test": "jest --ci"
},
"dependencies": {
"chalk": "^4.1.2",
"cli-table3": "^0.6.3",
"logform": "^2.6.0",
"prompts": "^2.4.2",
Expand Down
67 changes: 54 additions & 13 deletions packages/io-devtools/src/stdio/printer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import Table, { HorizontalTableRow } from 'cli-table3'
import Table, { HorizontalAlignment, HorizontalTableRow } from 'cli-table3'
import chalk from 'chalk'
import type { ZodError } from 'zod'

type Preprocess = (value: string) => string
export const COLORS = {
TRUE: chalk.rgb(0, 153, 0), // GREEN
FALSE: chalk.rgb(255, 0, 0), // RED
NOT_APPLICABLE: chalk.rgb(255, 128, 0), // ORANGE
DEFAULT_KEY: chalk.rgb(255, 255, 255), // WHITE
DEFAULT_VALUE: chalk.rgb(167, 125, 255), // MAGENTA
}

/**
* Returns a JSON-serialized version of a string, replacing all `BigInt`
* instances with strings
Expand Down Expand Up @@ -29,28 +39,41 @@ export const printJson = (obj: unknown, pretty = true): string =>
* @see {@link printRecord}
*
* @param value
* @param keyColor - color of keys in table (DEFAULT: WHITE)
* @param valueColor - color of values in table (DEFAULT: MAGENTA)
* @returns
*/
const printValue = (value: unknown): string => {
const printValue = (
value: unknown,
keyColor: Preprocess = COLORS.DEFAULT_KEY,
valueColor: Preprocess = COLORS.DEFAULT_VALUE
): string => {
switch (true) {
case value == null:
case value instanceof Date:
case typeof value !== 'object':
return String(value)
return valueColor(String(value))

default:
return printRecord(value)
return printRecord(value, undefined, keyColor, valueColor)
}
}

export const printRecord = <TRecord extends object>(obj: TRecord, title?: string | number): string => {
export const printRecord = <TRecord extends object>(
obj: TRecord,
title?: string | number,
keyColor: Preprocess = COLORS.DEFAULT_KEY,
valueColor: Preprocess = COLORS.DEFAULT_VALUE
): string => {
const table = new Table({
wordWrap: true,
wrapOnWordBoundary: false,
})

const headers: HorizontalTableRow[] = title == null ? [] : [[{ content: title, colSpan: 2 }]]
const rows = Object.entries(obj).map(([key, value]): HorizontalTableRow => [key, printValue(value)])
const rows = Object.entries(obj).map(
([key, value]): HorizontalTableRow => [keyColor(key), printValue(value, keyColor, valueColor)]
)

return table.push(...headers, ...rows), table.toString()
}
Expand All @@ -63,20 +86,30 @@ export const printRecord = <TRecord extends object>(obj: TRecord, title?: string
* the property name.
*
* @param {Record<string | number, unknown>} records
* @param {string[]} [header]
* @param {string[]} [headers] - header row if provided
* @param {boolean} [center] - center text if true
* @param {Preprocess} [keyColor=COLORS.DEFAULT_KEY] keyColor - color of keys in table
* @param {Preprocess} [valueColor=COLORS.DEFAULT_VALUE] valueColor - color of values in table
* @returns {string}
*/
export const printCrossTable = <TRecord extends Record<string | number, unknown>>(
records: TRecord[],
header?: string[]
headers?: string[],
center?: boolean,
keyColor: Preprocess = COLORS.DEFAULT_KEY,
valueColor: Preprocess = COLORS.DEFAULT_VALUE
): string => {
const table = new Table({
head: header ?? [],
wordWrap: true,
wrapOnWordBoundary: false,
style: { head: ['reset'] },
})

// Set the colored headers if provided
const coloredHeaders = headers?.map((header) => keyColor(header)) ?? []
table.push(coloredHeaders)

table.options.colAligns = center ? (['left', ...records.map(() => 'center')] as HorizontalAlignment[]) : []

// We'll gather all the properties of all the records in this array
//
// We do this in case some of the objects were missing any properties -
Expand All @@ -94,10 +127,10 @@ export const printCrossTable = <TRecord extends Record<string | number, unknown>
propertiesLeft.delete(property)

// Get all the values and print them
const values = records.map((record) => record[property]).map(printValue)
const values = records.map((record) => printValue(record[property], keyColor, valueColor))

// Create a row with the property label first
const row = [property, ...values]
const row = [keyColor(property), ...values]

// And add to the table
table.push(row)
Expand All @@ -110,9 +143,17 @@ export const printCrossTable = <TRecord extends Record<string | number, unknown>
* Helper utility for printing out boolean values
*
* @param {boolean | null | undefined} value
* @param {Preprocess} [nullColor=COLORS.NOT_APPLICABLE] nullColor
* @param {Preprocess} [trueColor=COLORS.TRUE] trueColor
* @param {Preprocess} [falseColor=COLORS.FALSE] falseColor
* @returns {string}
*/
export const printBoolean = (value: boolean | null | undefined): string => (value == null ? '∅' : value ? '✓' : '⤫')
export const printBoolean = (
value: boolean | null | undefined,
nullColor: Preprocess = COLORS.NOT_APPLICABLE,
trueColor: Preprocess = COLORS.TRUE,
falseColor: Preprocess = COLORS.FALSE
): string => (value == null ? nullColor('∅') : value ? trueColor('✓') : falseColor('⤫'))

export const printZodErrors = (error: ZodError<unknown>): string => {
// Here we will go through all the errors and prefix them with the name
Expand Down
8 changes: 4 additions & 4 deletions packages/ua-devtools-evm-hardhat/src/tasks/oapp/peers.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ const action: ActionType<TaskArgs> = async ({ oappConfig: oappConfigPath, logLev
})

console.log(
printCrossTable(peerNetworkMatrix, ['from → to', ...points.map(({ networkName }) => networkName)]),
`\n\t${printBoolean(true)} - Connected\n`,
`\t${printBoolean(false)} - Not Connected\n`,
`\t${printBoolean(undefined)} - Ignored`
printCrossTable(peerNetworkMatrix, ['from → to', ...points.map(({ networkName }) => networkName)], true)
)
console.log(` ${printBoolean(true)} - Connected`)
console.log(` ${printBoolean(false)} - Not Connected`)
console.log(` ${printBoolean(undefined)} - Ignored`)

return peers
} catch (error) {
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit e766c86

Please sign in to comment.