delightful

package module
v0.2.15 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2022 License: Apache-2.0 Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

🚧 🚧 🚧 Work-in-Progress

This is still under heavy construction. Do NOT use just yet!






Got

go-delightful
command-line messaging with colors and emojis


Go library designed for command-line applications interacting with humans, providing delightful end-user experience for informational messaging via colourful, lightly structured messages with emojis.


✅  This tool is for Informational messaging for the end-user while the command is running:

Messages are written into standard error stream (stderr) to avoid polluting the actual program output in standard output stream (stdout); Hence the messages are intended for end-user communication during the program runtime, not for the actual parseable result output:

Not everything on stderr is an error though. For example, you can use curl to download a file but the progress output is on stderr. This allows you to redirect the stdout while still seeing the progress.

In short: stdout is for output, stderr is for messaging.

– 12 Factor CLI Apps


❌  This tool is NOT for:

  • Log Events for tracing/debugging the program execution
    → Use logging frameworks such as zap, zerolog or logrus for more advanced application logging. You still should ensure they write to stderr (or to a rotated log file or something).

  • Command Output (i.e. the result) written into stdout (which could be redirected to a file for example)
    → Use fmt.Print for that which defaults to writing into standard output.


Features

  • Coloured output with emoji prefixes by default

  • Prints to Standard Error stream (stderr)

  • Subprocess friendly: Tries to access the tty and print to its stderr (can be disabled)

  • Respectful of environment, end-user can set environment variables to:

    • disable color
    • disable emoji
    • enable silent mode
    • verbose mode


Install

go get github.com/aripalo/go-delightful

Usage

For example usage, see vegas-credentials which utilizes this library. (Not yet implemented!)


Getting started

Here are some of the basic methods:

package main

import (
	"github.com/aripalo/go-delightful"
)

func main() {

	// Initialize
	message := delightful.New("demo")

	// Purple message line
	message.Titleln("👷", "Just showing things around here")

	// Gray message line
	message.Infoln("ℹ️", "Good to know")

	// Cyan message (without newline)
	message.Prompt("📝", "Provide input")

	// Green message line
	message.Successln("✅", "Great Success")

	// Red message line
	message.Failureln("❌", "Error")
}

Real world'ish example

An example command-line application using aripalo/go-delightful:

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/aripalo/go-delightful"
	"github.com/enescakir/emoji"
	flag "github.com/spf13/pflag"
)

func main() {

	// Initialize
	message := delightful.New("greet")

	// Some setup with spf13/pflag, not really important for this example
	var silentMode bool
	var verboseMode bool
	var noEmoji bool
	var noColor bool
	flag.BoolVarP(&silentMode, "silent", "s", false, "silent mode (hides everything except prompt/failure messages)")
	flag.BoolVar(&verboseMode, "verbose", false, "verbose output (show everything, overrides silent mode)")
	flag.BoolVar(&noEmoji, "no-emoji", false, "disable emojis")
	flag.BoolVar(&noColor, "no-color", false, "disable colors and emojis")
	flag.Parse()

	// Configure how messaging works based on above CLI flags
	message.SetSilentMode(silentMode)
	message.SetVerboseMode(verboseMode)
	message.SetEmojiMode(!noEmoji)
	message.SetColorMode(!noColor)

	// Print a "banner" showing your app name and other (optional) info.
	// Banner optional info only printed if in verbose mode.
	message.Banner(delightful.BannerOptions{
		Version: "v0.0.1",
		Website: "http://example.com",
		Command: "hello",
		Extra:   "Some extra info, let's keep it short!",
	})

	// Print "title" message line in purple.
	message.Titleln("🔥", "This is going to be lit!")

	// Print "debug" message line in dark gray.
	// Only printed if in verbose mode.
	message.Debugln("", "This is only visible if in verbose mode") // passing empty string for emoji disables it

	// Print "info" message line in gray.
	message.Infoln("ℹ️", "Just something for your information.")

	// Print "prompt" message in cyan.
	// Does not actually read input, only shows the "question".
	message.Prompt("🙋", "Tell us Your name: ")

	// Actually query the name via stdin
	reader := bufio.NewReader(os.Stdin)
	value, err := reader.ReadString('\n')
	if err != nil {
		// Print "failure" message line in red.
		message.Failure("❌", "galaxies exploded")
		log.Fatal(err)
	}
	name := strings.TrimSpace(value)

	if strings.ContainsRune(name, '💩') {

		// Unfortunately many environments print gendered/toned emojis incorrectly
		// so you might want to use github.com/enescakir/emoji to assign "neutral" emoji
		facepalm := emoji.Emoji(emoji.PersonFacepalming.Tone(emoji.Default))

		// Print "warning" message line in yellow.
		message.Warningln(facepalm, "Really? Your name has a poop emoji? You're being silly...")
	} else {
		// Print "success" message line in green.
		message.Successln("✅", "Name received!")
	}

	// Print horizontal ruler.
	// Useful for visually separating the informational messages above from
	// actual command output.
	// Visible only on verbose mode.
	message.HorizontalRuler()

	// Finally you often should print some actual command output into standard
	// output stream.
	fmt.Printf("Hello %s!\n", name)
}

Example Output

Results of running above code with go run main.go and various flags:

No flags

default

--no-emoji

emoji disabled

... or with NO_EMOJI or <APP_NAME>_NO_EMOJI environment variables set (to something other than false or 0).

--no-color

color disabled

... or with NO_COLOR or <APP_NAME>_NO_COLOR environment variables set (to something other than false or 0).

--silent

silent mode

--verbose

verbose mode

... or with VERBOSE or <APP_NAME>_VERBOSE environment variables set (to something other than false or 0).


Emojis

Unfortunately not all command-line environments are capable of rendering all emojis as they should be rendered. To ensure best possible compatibility with different systems and fonts:

  • Use non-gendered emojis
  • Use default skintone emojis
  • Avoid complex group emojis such as 👨‍👩‍👧‍👧

Sometimes using enescakir/emoji can make getting the exactly right emoji easier:

emoji.Emoji(emoji.PersonFacepalming.Tone(emoji.Default))

Of course you may use any emoji you wish but note that they may not render as expected in different systems and environments.


Configuration

TODO!

  • VERBOSE
  • SILENT
  • Set* methods

Design

  1. Environment Variables should win

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BannerOptions

type BannerOptions struct {
	Command string
	Version string
	Website string
	Extra   string
}

BannerOptions enables passing optional/additional information into the banner output. Values given here are only printed if Verbose Mode is active.

type Message

type Message struct {
	// contains filtered or unexported fields
}

Message struct holds the configurationg for messaging and you can call various methods on it that print messages.

func New

func New(appName string) Message

New returns a new Output instance with default configuration

func (*Message) Banner

func (m *Message) Banner(b BannerOptions)

Banner prints information about the current application/command. Application name shown in magenta color, other info in gray/white. No-op if Silent Mode active. BannerOptions printed only if Verbose Mode active.

func (*Message) Debug added in v0.0.5

func (m *Message) Debug(prefix emoji.Emoji, rendered string)

Debug prints a message in gray for debugging/testing purposes. No-op, unless Verbose Mode active.

func (*Message) Debugln added in v0.2.0

func (m *Message) Debugln(prefix emoji.Emoji, rendered string)

Debugln prints a message line in gray for debugging/testing purposes. No-op, unless Verbose Mode active.

func (*Message) Failure added in v0.0.5

func (m *Message) Failure(prefix emoji.Emoji, rendered string)

Failure prints a message in red. Usefule for notifying user about errors. Printed always, even if Silent Mode active.

func (*Message) Failureln added in v0.2.0

func (m *Message) Failureln(prefix emoji.Emoji, rendered string)

Failureln prints a message line in red. Usefule for notifying user about errors. Printed always, even if Silent Mode active.

func (*Message) HorizontalRuler added in v0.0.5

func (m *Message) HorizontalRuler()

HorizontalRuler prints equals (=) characters as wide as the terminal.

func (*Message) Info added in v0.0.5

func (m *Message) Info(prefix emoji.Emoji, rendered string)

Info prints an informational message in white color. No-op if Silent Mode active.

func (*Message) Infoln added in v0.2.0

func (m *Message) Infoln(prefix emoji.Emoji, rendered string)

Infoln prints an informational message line in white color. No-op if Silent Mode active.

func (*Message) Prompt added in v0.0.5

func (m *Message) Prompt(prefix emoji.Emoji, rendered string)

Prompt prints a "prompt query/question" in cyan. Meant to be used for asking user input, just before reading stdin. Printed always, even if Silent Mode active.

NOTE: This method only prints the "prompt query/question" and does not actually read the stdin: You need to implement that yourself!

func (*Message) Promptln added in v0.2.0

func (m *Message) Promptln(prefix emoji.Emoji, rendered string)

Promptln prints a "prompt query/question" line in cyan. Meant to be used for asking user input, just before reading stdin. Printed always, even if Silent Mode active.

NOTE: This method only prints the "prompt query/question" and does not actually read the stdin: You need to implement that yourself!

func (*Message) SetColorMode

func (m *Message) SetColorMode(colorMode bool)

SetColorMode controls if the messages are printed with emojis and colors. ColorMode is enabled (true) by default. May not have any effect if user has disabled color & emojis via environment variable. Or if user's terminal environment does not support colors.

func (*Message) SetEmojiMode added in v0.0.3

func (m *Message) SetEmojiMode(emojiMode bool)

SetEmojiMode controls if emojis are printed with the messages: Can be disabled even when colors are enabled, but not enabled when colors are disabled.

func (*Message) SetMessageTarget

func (m *Message) SetMessageTarget(target io.Writer)

SetMessageTarget overrides the default output target (tty/stderr). Mainly used for testing.

func (*Message) SetSilentMode added in v0.0.11

func (m *Message) SetSilentMode(silentMode bool)

SetSilentMode controls if info/warning/success messages are shown or not (i.e. silent mode). Silent mode can not be enabled if verbose mode is active.

func (*Message) SetVerboseMode

func (m *Message) SetVerboseMode(verboseMode bool)

SetVerboseMode controls additional debug messages. Verbose output is disabled by default unless user has set VERBOSE or <APP_NAME>_VERBOSE environment variables. Enabling verbose mode also disables silent mode.

func (*Message) Success added in v0.0.5

func (m *Message) Success(prefix emoji.Emoji, rendered string)

Success prints a message in green. No-op if Silent Mode active.

func (*Message) Successln added in v0.2.0

func (m *Message) Successln(prefix emoji.Emoji, rendered string)

Successln prints a message line in green. No-op if Silent Mode active.

func (*Message) Title added in v0.0.5

func (m *Message) Title(prefix emoji.Emoji, rendered string)

Title prints a heading message in blue color. No-op if Silent Mode active.

func (*Message) Titleln added in v0.2.0

func (m *Message) Titleln(prefix emoji.Emoji, rendered string)

Titleln prints a heading message line in blue color. No-op if Silent Mode active.

func (*Message) Warning added in v0.0.5

func (m *Message) Warning(prefix emoji.Emoji, rendered string)

Warning prints a message in yellow. No-op if Silent Mode active.

func (*Message) Warningln added in v0.2.0

func (m *Message) Warningln(prefix emoji.Emoji, rendered string)

Warningln prints a message line in yellow. No-op if Silent Mode active.

Directories

Path Synopsis
internal
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址