Skip to content

Commit

Permalink
refactor: centralize styles for consistency and profit (#5375)
Browse files Browse the repository at this point in the history
* chore(logger): centralize styles for consistency and profit

* chore(logger): remove unneeded calls to styles map

* chore(logger): better types for styles map + tweaks
  • Loading branch information
eysi09 authored Nov 13, 2023
1 parent 3d168dc commit b7121b2
Show file tree
Hide file tree
Showing 135 changed files with 768 additions and 704 deletions.
6 changes: 3 additions & 3 deletions core/src/actions/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import chalk from "chalk"
import titleize from "titleize"
import type { ConfigGraph, GetActionOpts, ResolvedConfigGraph } from "../graph/config-graph.js"
import type { ActionReference, DeepPrimitiveMap } from "../config/common.js"
Expand Down Expand Up @@ -65,6 +64,7 @@ import { createActionLog } from "../logger/log-entry.js"
import { joinWithPosix } from "../util/fs.js"
import type { LinkedSource } from "../config-store/local.js"
import type { BaseActionTaskParams, ExecuteTask } from "../tasks/base.js"
import { styles } from "../logger/styles.js"

// TODO: split this file

Expand Down Expand Up @@ -398,10 +398,10 @@ export abstract class BaseAction<
* Verbose string description of the action. Useful for logging and error messages.
*/
longDescription(): string {
let d = `${chalk.white(this.kind)} type=${chalk.bold.white(this.type)} name=${chalk.bold.white(this.name)}`
let d = `${styles.accent(this.kind)} type=${styles.accent.bold(this.type)} name=${styles.accent.bold(this.name)}`

if (this._moduleName) {
d += ` (from module ${chalk.bold.white(this._moduleName)})`
d += ` (from module ${styles.accent.bold(this._moduleName)})`
}

return d
Expand Down
6 changes: 3 additions & 3 deletions core/src/actions/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import chalk from "chalk"
import { fromPairs, memoize } from "lodash-es"
import { joi } from "../config/common.js"
import type { Garden } from "../garden.js"
Expand Down Expand Up @@ -34,6 +33,7 @@ import type { ActionStatusPayload } from "../events/action-status-events.js"
import type { BuildStatusForEventPayload } from "../plugin/handlers/Build/get-status.js"
import type { DeployStatusForEventPayload } from "../types/service.js"
import type { RunStatusForEventPayload } from "../plugin/plugin.js"
import { styles } from "../logger/styles.js"

/**
* Creates a corresponding Resolved version of the given Action, given the additional parameters needed.
Expand Down Expand Up @@ -91,12 +91,12 @@ export async function warnOnLinkedActions(garden: Garden, log: Log, actions: Act

const linkedActionsMsg = actions
.filter((a) => a.isLinked(linkedSources))
.map((a) => `${a.longDescription()} linked to path ${chalk.white(a.sourcePath())}`)
.map((a) => `${a.longDescription()} linked to path ${styles.accent(a.sourcePath())}`)
.map((msg) => " " + msg) // indent list

if (linkedActionsMsg.length > 0) {
log.info(renderDivider())
log.info(chalk.gray(`The following actions are linked to a local path:\n${linkedActionsMsg.join("\n")}`))
log.info(styles.primary(`The following actions are linked to a local path:\n${linkedActionsMsg.join("\n")}`))
log.info(renderDivider())
}
}
Expand Down
3 changes: 1 addition & 2 deletions core/src/build-staging/build-staging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { normalizeRelativePath, joinWithPosix } from "../util/fs.js"
import type { Log } from "../logger/log-entry.js"
import { Profile } from "../util/profiling.js"
import async from "async"
import chalk from "chalk"
import { hasMagic } from "glob"
import type { MappedPaths } from "./helpers.js"
import { FileStatsHelper, syncFileAsync, cloneFile, scanDirectoryForClone } from "./helpers.js"
Expand Down Expand Up @@ -223,7 +222,7 @@ export class BuildStaging {
}

if (!sourceStat) {
log.warn(chalk.yellow(`Build staging: Could not find source file or directory at path ${sourceRoot}`))
log.warn(`Build staging: Could not find source file or directory at path ${sourceRoot}`)
return
}
}
Expand Down
23 changes: 14 additions & 9 deletions core/src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import { intersection, mapValues, sortBy } from "lodash-es"
import { resolve, join } from "path"
import chalk from "chalk"
import fsExtra from "fs-extra"
const { pathExists } = fsExtra
import { getBuiltinCommands } from "../commands/commands.js"
Expand Down Expand Up @@ -60,6 +59,7 @@ import { withSessionContext } from "../util/open-telemetry/context.js"
import { wrapActiveSpan } from "../util/open-telemetry/spans.js"
import { JsonFileWriter } from "../logger/writers/json-file-writer.js"
import type minimist from "minimist"
import { styles } from "../logger/styles.js"

export interface RunOutput {
argv: any
Expand Down Expand Up @@ -109,7 +109,7 @@ export class GardenCli {
// Thus we have to dedent like this.
let msg = `
${cliStyles.heading("USAGE")}
garden ${cliStyles.commandPlaceholder()} ${cliStyles.optionsPlaceholder()}
garden ${cliStyles.commandPlaceholder()} ${cliStyles.argumentsPlaceholder()} ${cliStyles.optionsPlaceholder()}
${cliStyles.heading("COMMANDS")}
${renderCommands(commands)}
Expand Down Expand Up @@ -251,7 +251,7 @@ ${renderCommands(commands)}
} catch (err) {
if (err instanceof CloudApiTokenRefreshError) {
log.warn(dedent`
${chalk.yellow(`Unable to authenticate against ${distroName} with the current session token.`)}
Unable to authenticate against ${distroName} with the current session token.
Command results for this command run will not be available in ${distroName}. If this not a
${distroName} project you can ignore this warning. Otherwise, please try logging out with
\`garden logout\` and back in again with \`garden login\`.
Expand Down Expand Up @@ -314,18 +314,23 @@ ${renderCommands(commands)}
await garden.emitWarning({
key: "0.13-bonsai",
log,
message: chalk.yellow(dedent`
message: dedent`
Garden v0.13 (Bonsai) is a major release with significant changes. Please help us improve it by reporting any issues/bugs here:
https://go.garden.io/report-bonsai
`),
`,
})
}

nsLog.info(`Running in Garden environment ${chalk.cyan(`${garden.environmentName}.${garden.namespace}`)}`)
nsLog.info(
`Running in Garden environment ${styles.highlight(`${garden.environmentName}.${garden.namespace}`)}`
)

if (!cloudApi && garden.projectId) {
log.info("")
log.warn(
`You are not logged in into Garden Cloud. Please log in via the ${chalk.green("garden login")} command.`
`Warning: You are not logged in into Garden Cloud. Please log in via the ${styles.command(
"garden login"
)} command.`
)
log.info("")
}
Expand Down Expand Up @@ -376,7 +381,7 @@ ${renderCommands(commands)}

if (garden.monitors.anyMonitorsActive()) {
// Wait for monitors to exit
log.debug(chalk.gray("One or more monitors active, waiting until all exit."))
log.debug(styles.primary("One or more monitors active, waiting until all exit."))
await garden.monitors.waitUntilStopped()
}

Expand Down Expand Up @@ -438,7 +443,7 @@ ${renderCommands(commands)}
const workingDir = resolve(cwd || process.cwd(), argv.root || "")

if (!(await pathExists(workingDir))) {
return done(1, chalk.red(`Could not find specified root path (${argv.root})`))
return done(1, styles.error(`Could not find specified root path (${argv.root})`))
}

let projectConfig: ProjectConfig | undefined
Expand Down
49 changes: 25 additions & 24 deletions core/src/cli/command-line.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import chalk from "chalk"
import type { Key } from "ink"
import { max } from "lodash-es"
import { resolve } from "path"
Expand Down Expand Up @@ -40,14 +39,15 @@ import type { GlobalOptions, ParameterObject, ParameterValues } from "./params.j
import { bindActiveContext, withSessionContext } from "../util/open-telemetry/context.js"
import { wrapActiveSpan } from "../util/open-telemetry/spans.js"
import { DEFAULT_BROWSER_DIVIDER_WIDTH } from "../constants.js"
import { styles } from "../logger/styles.js"

const defaultMessageDuration = 3000
const commandLinePrefix = chalk.yellow("🌼 > ")
const emptyCommandLinePlaceholder = chalk.gray("<enter command> (enter help for more info)")
const commandLinePrefix = styles.warning("🌼 > ")
const emptyCommandLinePlaceholder = styles.primary("<enter command> (enter help for more info)")
const inputHistoryLength = 100

const styles = {
command: chalk.white.bold,
const commandLineStyles = {
command: styles.accent.bold,
}

export type SetStringCallback = (data: string) => void
Expand Down Expand Up @@ -76,15 +76,16 @@ interface CommandLineEvents {
function getCmdsRunningMsg(commandNames: string[]) {
let msg = ""
if (commandNames.length === 1) {
msg = chalk.cyan(`Running ${styles.command(commandNames[0])} command...`)
msg = styles.highlight(`Running ${commandLineStyles.command(commandNames[0])} command...`)
} else if (commandNames.length > 1) {
msg = chalk.cyan(`Running ${commandNames.length} commands: `) + styles.command(commandNames.join(", "))
msg =
styles.highlight(`Running ${commandNames.length} commands: `) + commandLineStyles.command(commandNames.join(", "))
}
return msg
}

function getCmdSuccessMsg(commandName: string) {
return `${chalk.cyan(commandName)} command completed successfully!`
return `${styles.highlight(commandName)} command completed successfully!`
}

function getCmdFailMsg(commandName: string) {
Expand All @@ -99,7 +100,7 @@ function getCmdFailMsg(commandName: string) {
* by the web UI.
*/
function logCommand({ msg, log, width, error }: { msg: string; log: Log; width: number; error: boolean }) {
const dividerColor = error ? chalk.red : chalk.blueBright
const dividerColor = error ? styles.error : styles.highlight
const dividerOptsBase = { width, title: msg, color: dividerColor, char: "┈" }
const terminalMsg = renderDivider(dividerOptsBase)
const rawMsg = renderDivider({ ...dividerOptsBase, width: DEFAULT_BROWSER_DIVIDER_WIDTH })
Expand Down Expand Up @@ -428,18 +429,18 @@ export class CommandLine extends TypedEventEmitter<CommandLineEvents> {
const suggestions = this.getSuggestions(this.currentCommand.length)

if (this.isSuggestedCommand(suggestions)) {
renderedCommand = chalk.cyan(renderedCommand)
renderedCommand = styles.highlight(renderedCommand)
}

if (suggestions.length > 0) {
// Show autocomplete suggestion after string
renderedCommand = renderedCommand + chalk.gray(suggestions[0].line.substring(renderedCommand.length))
renderedCommand = renderedCommand + styles.primary(suggestions[0].line.substring(renderedCommand.length))
}

if (renderedCommand.length === 0) {
if (this.showCursor) {
renderedCommand =
chalk.underline(sliceAnsi(emptyCommandLinePlaceholder, 0, 1)) + sliceAnsi(emptyCommandLinePlaceholder, 1)
styles.underline(sliceAnsi(emptyCommandLinePlaceholder, 0, 1)) + sliceAnsi(emptyCommandLinePlaceholder, 1)
} else {
renderedCommand = emptyCommandLinePlaceholder
}
Expand All @@ -450,7 +451,7 @@ export class CommandLine extends TypedEventEmitter<CommandLineEvents> {

renderedCommand =
sliceAnsi(renderedCommand, 0, this.cursorPosition) +
(this.showCursor ? chalk.underline(cursorChar) : cursorChar) +
(this.showCursor ? styles.underline(cursorChar) : cursorChar) +
sliceAnsi(renderedCommand, this.cursorPosition + 1)
}

Expand Down Expand Up @@ -489,13 +490,13 @@ export class CommandLine extends TypedEventEmitter<CommandLineEvents> {
}

const char = "┈"
const color = chalk.bold
const color = styles.bold

// `dedent` has a bug where it doesn't indent correctly
// when there's ANSI codes in the beginning of a line.
// Thus we have to dedent like this.
const wrapped = `
${renderDivider({ title: chalk.bold(title), width, char, color })}
${renderDivider({ title: styles.bold(title), width, char, color })}
${text}
${renderDivider({ width, char, color })}
`
Expand All @@ -509,17 +510,17 @@ ${renderDivider({ width, char, color })}
})

const helpText = `
${chalk.white.underline("Popular commands:")}
${styles.accent.underline("Popular commands:")}
${renderCommands(getPopularCommands(commandsToRender))}
${chalk.white.underline("Other commands:")}
${styles.accent.underline("Other commands:")}
${renderCommands(getOtherCommands(commandsToRender))}
${chalk.white.underline("Keys:")}
${styles.accent.underline("Keys:")}
${chalk.gray(`[tab]: auto-complete [up/down]: command history [ctrl-u]: clear line [ctrl-d]: quit`)}
${styles.primary(`[tab]: auto-complete [up/down]: command history [ctrl-u]: clear line [ctrl-d]: quit`)}
`
this.printWithDividers(helpText, "help")
}
Expand All @@ -543,15 +544,15 @@ ${chalk.white.underline("Keys:")}
}

flashSuccess(message: string, opts: FlashOpts = {}) {
this.flashMessage(chalk.green(message), { prefix: chalk.green("✔︎ "), ...opts })
this.flashMessage(styles.success(message), { prefix: styles.success("✔︎ "), ...opts })
}

flashError(message: string, opts: FlashOpts = {}) {
this.flashMessage(chalk.red(message), { prefix: "❗️ ", ...opts })
this.flashMessage(styles.error(message), { prefix: "❗️ ", ...opts })
}

flashWarning(message: string, opts: FlashOpts = {}) {
this.flashMessage(chalk.yellowBright(message), { prefix: chalk.yellow("⚠️ "), ...opts })
this.flashMessage(styles.warning(message), { prefix: styles.warning("⚠️ "), ...opts })
}

setKeyHandler(stringKey: string, handler: KeyHandler) {
Expand Down Expand Up @@ -608,7 +609,7 @@ ${chalk.white.underline("Keys:")}
const { command, rest, matchedPath } = pickCommand(this.getCommands(), rawArgs)

if (!command) {
this.flashError(`Could not find command. Try typing ${chalk.white("help")} to see the available commands.`)
this.flashError(`Could not find command. Try typing ${styles.accent("help")} to see the available commands.`)
return
}

Expand Down Expand Up @@ -775,7 +776,7 @@ ${chalk.white.underline("Keys:")}
// Update persisted history
// Note: We're currently not resolving history across concurrent dev commands, but that's anyway not well supported
garden.localConfigStore.set("devCommandHistory", this.commandHistory).catch((error) => {
this.log.warn(chalk.yellow(`Could not persist command history: ${error}`))
this.log.warn(`Could not persist command history: ${error}`)
})

command
Expand Down
Loading

0 comments on commit b7121b2

Please sign in to comment.