Skip to content

Commit

Permalink
fix(logger): only print emoji if env supports it
Browse files Browse the repository at this point in the history
  • Loading branch information
eysi09 committed Sep 27, 2018
1 parent 7c83b41 commit 3e541e1
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 13 deletions.
1 change: 1 addition & 0 deletions docs/reference/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ The following option flags can be used with any of the CLI commands:
| `--env` | `-e` | string | The environment (and optionally namespace) to work against
| `--loglevel` | `-l` | `error` `warn` `info` `verbose` `debug` `silly` `0` `1` `2` `3` `4` `5` | Set logger level. Values can be either string or numeric and are prioritized from 0 to 5 (highest to lowest) as follows: error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5
| `--output` | `-o` | `json` `yaml` | Output command result in specified format (note: disables progress logging).
| `--emoji` | | boolean | Enable emoji in output (defaults to true if the environment supports it).

### garden build

Expand Down
10 changes: 8 additions & 2 deletions garden-cli/src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import {
prepareArgConfig,
prepareOptionConfig,
styleConfig,
envSupportsEmoji,
} from "./helpers"
import { GardenConfig } from "../config/base"
import { defaultEnvironments } from "../config/project"
Expand Down Expand Up @@ -125,6 +126,10 @@ export const GLOBAL_OPTIONS = {
choices: Object.keys(OUTPUT_RENDERERS),
help: "Output command result in specified format (note: disables progress logging).",
}),
emoji: new BooleanParameter({
help: "Enable emoji in output (defaults to true if the environment supports it).",
defaultValue: envSupportsEmoji(),
}),
}
const GLOBAL_OPTIONS_GROUP_NAME = "Global options"
const DEFAULT_CLI_LOGGER_TYPE = LoggerType.fancy
Expand Down Expand Up @@ -206,10 +211,11 @@ export class GardenCli {

const action = async (argv, cliContext) => {
// Sywac returns positional args and options in a single object which we separate into args and opts

const parsedArgs = filterByKeys(argv, argKeys)
const parsedOpts = filterByKeys(argv, optKeys.concat(globalKeys))
const root = resolve(process.cwd(), parsedOpts.root)
const { env, loglevel, silent, output } = parsedOpts
const { emoji, env, loglevel, silent, output } = parsedOpts

// Init logger
const level = getLogLevelFromArg(loglevel)
Expand All @@ -223,7 +229,7 @@ export class GardenCli {
}
}

const logger = Logger.initialize({ level, writers })
const logger = Logger.initialize({ level, writers, useEmoji: emoji })
let garden: Garden
let result
do {
Expand Down
9 changes: 8 additions & 1 deletion garden-cli/src/cli/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,20 @@ ${chalk.bold(str.slice(0, 5).toUpperCase())}
export const getKeys = (obj): string[] => Object.keys(obj || {})
export const filterByKeys = (obj: any, keys: string[]): any => {
return keys.reduce((memo, key) => {
if (obj[key]) {
if (obj.hasOwnProperty(key)) {
memo[key] = obj[key]
}
return memo
}, {})
}

// Add platforms/terminals?
export function envSupportsEmoji() {
return process.platform === "darwin"
|| process.env.TERM_PROGRAM === "Hyper"
|| process.env.TERM_PROGRAM === "HyperTerm"
}

export type FalsifiedParams = { [key: string]: false }

/**
Expand Down
2 changes: 2 additions & 0 deletions garden-cli/src/logger/log-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { LogNode, LogLevel } from "./log-node"
import { getChildEntries } from "./util"
import { GardenError } from "../exceptions"
import { Omit } from "../util/util"
import { Logger } from "./logger"

export type EmojiName = keyof typeof nodeEmoji.emoji
export type LogSymbol = keyof typeof logSymbols | "empty"
Expand Down Expand Up @@ -51,6 +52,7 @@ export function resolveParam<T extends UpdateOpts>(param?: string | T): T {

export class LogEntry extends LogNode {
public opts: UpdateOpts
public root: Logger

constructor({ level, opts, parent }: LogEntryConstructor) {
const { id, ...otherOpts } = opts
Expand Down
14 changes: 8 additions & 6 deletions garden-cli/src/logger/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,17 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import * as nodeEmoji from "node-emoji"
import chalk from "chalk"

import { RootLogNode, LogNode } from "./log-node"
import { LogEntry, CreateOpts, resolveParam } from "./log-entry"
import { LogEntry, CreateOpts, resolveParam, EmojiName } from "./log-entry"
import { getChildEntries } from "./util"
import { Writer } from "./writers/base"
import { InternalError, ParameterError } from "../exceptions"
import { LogLevel } from "./log-node"
import { FancyTerminalWriter } from "./writers/fancy-terminal-writer"
import { BasicTerminalWriter } from "./writers/basic-terminal-writer"
import { combine } from "./renderers"
import { combine, printEmoji } from "./renderers"

export enum LoggerType {
quiet = "quiet",
Expand Down Expand Up @@ -45,10 +44,12 @@ export function getCommonConfig(loggerType: LoggerType): LoggerConfig {
export interface LoggerConfig {
level: LogLevel
writers?: Writer[]
useEmoji?: boolean
}

export class Logger extends RootLogNode<LogEntry> {
public writers: Writer[]
public useEmoji: boolean

private static instance: Logger

Expand Down Expand Up @@ -90,6 +91,7 @@ export class Logger extends RootLogNode<LogEntry> {
private constructor(config: LoggerConfig) {
super(config.level)
this.writers = config.writers || []
this.useEmoji = config.useEmoji === false ? false : true
}

createNode(level: LogLevel, _parent: LogNode, opts: CreateOpts) {
Expand All @@ -109,11 +111,11 @@ export class Logger extends RootLogNode<LogEntry> {
}

header(
{ command, emoji, level = LogLevel.info }: { command: string, emoji?: string, level?: LogLevel },
{ command, emoji, level = LogLevel.info }: { command: string, emoji?: EmojiName, level?: LogLevel },
): LogEntry {
const msg = combine([
[chalk.bold.magenta(command)],
[emoji ? " " + nodeEmoji.get(emoji) : ""],
[emoji && this.useEmoji ? " " + printEmoji(emoji) : ""],
["\n"],
])
const lvlStr = LogLevel[level]
Expand All @@ -124,7 +126,7 @@ export class Logger extends RootLogNode<LogEntry> {
{ showDuration = true, level = LogLevel.info }: { showDuration?: boolean, level?: LogLevel } = {},
): LogEntry {
const msg = combine([
[`\n${nodeEmoji.get("sparkles")} Finished`],
[this.useEmoji ? `\n${printEmoji("sparkles")} Finished` : "Finished"],
[showDuration ? ` in ${chalk.bold(this.getDuration() + "s")}` : "!"],
["\n"],
])
Expand Down
13 changes: 10 additions & 3 deletions garden-cli/src/logger/renderers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import cliTruncate = require("cli-truncate")
import stringWidth = require("string-width")
import hasAnsi = require("has-ansi")

import { LogEntry } from "./log-entry"
import { LogEntry, EmojiName } from "./log-entry"

export type ToRender = string | ((...args: any[]) => string)
export type Renderer = [ToRender, any[]] | ToRender[]
Expand Down Expand Up @@ -63,15 +63,22 @@ export function combine(renderers: Renderers): string {
return applyRenderers(renderers)(initOutput).join("")
}

export function printEmoji(emoji: EmojiName) {
if (nodeEmoji.hasEmoji(emoji)) {
return `${nodeEmoji.get(emoji)} `
}
return ""
}

/*** RENDERERS ***/
export function leftPad(entry: LogEntry): string {
return padStart("", (entry.opts.indentationLevel || 0) * 3)
}

export function renderEmoji(entry: LogEntry): string {
const { emoji } = entry.opts
if (emoji && nodeEmoji.hasEmoji(emoji)) {
return `${nodeEmoji.get(emoji)} `
if (emoji && entry.root.useEmoji) {
return printEmoji(emoji)
}
return ""
}
Expand Down
1 change: 0 additions & 1 deletion garden-cli/src/logger/writers/file-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ export class FileWriter extends Writer {
const out = this.render(entry)
if (out) {
if (!this.fileLogger) {

this.fileLogger = this.initFileLogger()
}
this.fileLogger.log(levelToStr(entry.level), out)
Expand Down

0 comments on commit 3e541e1

Please sign in to comment.