cli

package module
v0.0.0-...-ecd919d Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2019 License: BSD-3-Clause Imports: 14 Imported by: 6

README

github.com/fraugster/cli

Build Status GoDoc License

Package cli implements utility functions for running command line applications.

The following simple features are currently implemented:

  • creating a context.Context which is closed when SIGINT, SIGQUIT or SIGTERM is received.
  • context aware reading lines from stdin into a channel
  • printing values using user a defined format (e.g. json, yml or table)

Motivation

CLI applications often perform similar tasks such as handling stop signals, reading from stdin and printing results to stdout. This package provides these functions in a single and coherent repository. Applications built with github.com/fraugster/cli treat context.Context as first class citizen to remain responsive and implement graceful shutdown. Naturally this is visible when consuming (multi-line) input from stdin. The cli.Print function is especially useful since it encourages developers to support multiple machine readable output formats which makes it easy to pipe the results of one application into another (e.g. my-app -o=json | jq …).

Installation

$ go get github.com/fraugster/cli

Usage

package main

import (
	"context"
	"flag"
	"fmt"
	"time"

	"github.com/fraugster/cli"
)

func main() {
	// Create a context that is done when SIGINT, SIGQUIT or SIGTERM is received
	ctx := cli.Context()

	// Let the user decide what output format she prefers.
	format := flag.String("output", "json", "Output format. One of json|yaml|table|raw")
	flag.Parse()

	// Reading a single line from stdin (returns "" if context is canceled).
	fmt.Print("Please insert your name: ")
	name := cli.ReadLine(ctx)
	fmt.Println("Hello", name)

	// Continuously read lines from stdin and return them in a channel.
	fmt.Println("You have 10 seconds to talk to me")
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	var inputs []string
	for line := range cli.ReadLines(ctx) {
		inputs = append(inputs, line)
		fmt.Println("OK, go on")
	}
	fmt.Println("Time is up")
    
	// Print something to stdout in a format specified by the user.
	fmt.Println("Your inputs were:")
	cli.Print(*format, inputs)
}

Dependencies

  • gopkg.in/yaml.v2 for YAML output
  • github.com/stretchr/testify to run unit tests

License

This package is licensed under the the BSD 3-Clause License. Please see the LICENSE file for details.

Contributing

Contributions are welcome but must be discussed first in a new github issue before Pull Requests will be accepted.

Documentation

Overview

Package cli implements utility functions for running command line applications.

Index

Constants

This section is empty.

Variables

View Source
var (
	// JSONHTMLEscape controls the SetEscapeHTML option in the "json" output
	// format. If this is true then problematic HTML characters will be escaped
	// inside JSON quoted strings.
	//
	// By default this is disabled to not interfere with readability of the
	// output. If you are rendering output in an HTML context you should enable
	// this feature.
	JSONHTMLEscape = false
)

Functions

func Context

func Context() context.Context

Context returns a context that is cancelled automatically when a SIGINT, SIGQUIT or SIGTERM signal is received.

func MustPrint

func MustPrint(encoding string, i interface{})

MustPrint is exactly like Print but panics if an error occurs.

func Print

func Print(encoding string, value interface{}) error

Print encodes the value using the given encoding and then prints it to the standard output. Accepted encodings are "json", "yml", "yaml", "table" and "raw". If encoding is the empty string this function defaults to "table" encoding.

Usually the encoding is controlled via command line flags of your application so the user can select in what format the output should be returned.

Accepted encodings

"table": value is printed via a tab writer (see below) "json": value is printed as indented JSON "yaml": value is printed as YAML "raw": value is printed via fmt.Println

Table encoding

If the "table" encoding is used, the reflection API is used to print all exported fields of the value via a tab writer. The columns will be the UPPERCASE field names or whatever you set in the "table" tag of the corresponding field. Field names with a "table" tag set to "-" are omitted. When the "table" encoding is used the value must either be a struct, pointer to a struct, a slice or an array.

func PrintWriter

func PrintWriter(encoding string, value interface{}, w io.Writer) error

PrintWriter is like Print but lets the caller inject an io.Writer.

func ReadLine

func ReadLine(ctx context.Context) string

ReadLine reads a single line from stdin and returns it without the trailing newline. This function blocks until the first newline is read or the context is canceled. In the later case the empty string is returned.

func ReadLines

func ReadLines(ctx context.Context) <-chan string

ReadLines reads lines from stdin and returns them in a channel. All strings in the returned channel will not include the trailing newline. The channel is closed automatically if there are no more lines or if the context is closed.

This function panics if there was any error other than io.EOF when reading from os.Stdin.

func ReceiveSignal

func ReceiveSignal(s os.Signal)

ReceiveSignal propagates the given signal to all contexts that may have been created via cli.Context(). This function is only useful when the terminal is hijacked and you want to emulate signals manually.

Types

This section is empty.

Jump to

Keyboard shortcuts

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