Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add formatMessage color option #110

Merged
merged 3 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions pkg/src/message.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
import c from 'picocolors'
import picocolors from 'picocolors'
import {
formatMessagePath as fp,
getPkgPathValue,
replaceLast
} from './utils.js'

/** @type { import('picocolors/types.js').Colors | undefined } */
let _picocolorsHasColors
/** @type { import('picocolors/types.js').Colors | undefined } */
let _picocolorsNoColors

/**
* @param {import('../index.d.ts').Message} m
* @param {import('./utils.js').Pkg} pkg
* @param {import('../utils.d.ts').FormatMessageOptions} opts
*/
export function formatMessage(m, pkg) {
export function formatMessage(m, pkg, opts = {}) {
/** @type { import('picocolors/types.js').Colors } */
let c = picocolors
if (opts.color === true) {
c = _picocolorsHasColors ??= picocolors.createColors(true)
} else if (opts.color === false) {
c = _picocolorsNoColors ??= picocolors.createColors(false)
}

/** @param {string[]} path */
const pv = (path) => getPkgPathValue(pkg, path)

Expand Down
13 changes: 12 additions & 1 deletion pkg/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,20 @@ import type { Message } from './index.js'

type Pkg = Record<string, any>

export interface FormatMessageOptions {
/**
* Whether the returned string should contain color.
* - `true`: Force has color.
* - `false`: Force no color.
* - `undefined`: Default to whether the environment supports color.
*/
color?: boolean | undefined
}

export declare function formatMessagePath(path: string[]): string
export declare function getPkgPathValue(pkg: Pkg, path: string[]): any
export declare function formatMessage(
msg: Message,
pkg: Pkg
pkg: Pkg,
opts?: FormatMessageOptions
): string | undefined