cli

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2019 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package cli contains the command-line interface implementation of selene.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultEventFormat = "{{ .IDShort }}:[{{ .Timestamp }}]({{ .Source }}) {{ .Tags }} - {{ .Content }}"

DefaultEventFormat default format template for printing an event.

View Source
var FullEventFormat = "{{ .ID }}:[{{ .Timestamp }}]({{ .Source }}) {{ .Tags }} - {{ .Content }}"

FullEventFormat format template for printing an Event - full data.

View Source
var KnownTypes = TypeHeuristics{
	"error": func(text string) bool {
		text = strings.TrimSpace(strings.ToLower(text))
		match, err := regexp.MatchString("\\[?\\berr?(or)?\\b\\]?", text)
		if err != nil {
			panic(err)
		}
		return match
	},
	"warning": func(text string) bool {
		text = strings.TrimSpace(strings.ToLower(text))
		match, err := regexp.MatchString("\\[?\\bwarn(ing)?\\b\\]?", text)
		if err != nil {
			panic(err)
		}
		return match
	},
	"success": func(text string) bool {
		text = strings.TrimSpace(strings.ToLower(text))
		match, err := regexp.MatchString("\\[?\\bsuccess\\b\\]?", text)
		if err != nil {
			panic(err)
		}
		return match
	},
	"info": func(text string) bool {
		text = strings.TrimSpace(strings.ToLower(text))
		match, err := regexp.MatchString("\\[?\\binfo\\b\\]?", text)
		if err != nil {
			panic(err)
		}
		return match
	},
}

KnownTypes defines base text types like: error, warning, success etc. A given text will be checked if the text content is an error, warning or other registered type of text.

View Source
var ShortEventFormat = "[{{ .Source }}]{{ .Tags }} - {{ .Content }}"

ShortEventFormat format template to print event content, source and tags - short format.

Functions

func EventCommand

func EventCommand(args []string) error

EventCommand implements the 'event' subcommand. Takes a list of arguments to the event subcommand, parses it and then calls RunEventGenerator with the parsed query flags.

func PrintEvent

func PrintEvent(event *model.Event, format string, colors Colors)

PrintEvent prints the event using the provided format template to STDOUT.

func QueryCommand

func QueryCommand(args []string) error

QueryCommand implements the 'query' subcommand. Takes a list of arguments to the query subcommand, parses it and then calls RunQuery with the parsed query flags.

func RandTagColors

func RandTagColors() []string

RandTagColors generates the names of the colors used for tags, but in random order.

func RunEventGenerator

func RunEventGenerator(flags *EventFlags) error

RunEventGenerator generates new event with the given properties and sends it to the Theia server.

func RunQuery

func RunQuery(flags *QueryFlags) error

RunQuery runs a query against the server with the given query flags.

func RunWatcher

func RunWatcher(args *WatcherFlags) error

RunWatcher runs a watcher with the given watcher flags. It creates a WatcherDaemon and attaches the file, given as an input flag, as an EventSource. A connection to theia '/event' endpoint is created and the source events are pushed to the server.

func TagColors

func TagColors() []string

TagColors generates the names of the colors used for tags. The names are not actual color names (like green, blue) but are labels used to lookup the colors in the current palette.

func WatcherCommand

func WatcherCommand(args []string) error

WatcherCommand implements the 'watch' subcommand. Takes a list of arguments to the watch subcommand, parses it and then calls RunWatcher with the parsed watcher flags.

Types

type AuroraColors

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

AuroraColors implements the Color interface using the aurora library.

func (*AuroraColors) ColoredContent

func (a *AuroraColors) ColoredContent(ctx Context, content string) string

ColoredContent colors a content text.

func (*AuroraColors) ColoredTag

func (a *AuroraColors) ColoredTag(ctx Context, tag string) string

ColoredTag returns a colored text for the given tag. Same tags have the same colors, and different tags would get different colors. However, if the number of total tags is larger than the max number of colors reproducible on the terminal, some of the tags may receive same colors. The colors of the tags are random.

func (*AuroraColors) ColoredText

func (a *AuroraColors) ColoredText(ctx Context, text string) string

ColoredText would color a text based on the "color" field in the context. If set, the color would be resolved from the underlying palette.

type Colors

type Colors interface {
	// ColoredText colors the given text based on the provided Context.
	// The text may or may not end up being colored - this is controlled by the
	// values given in the context. How the values in the Context are
	// interpreted, depends completely on the underlying implementation.
	// For example, the function may be called with Context: {'type': 'info'}
	// which may be interpreted that the text is an info message and will be
	// colored in the 'info' color from an exiting palette.
	// If the current terminal is not interactive (tty), then no coloring takes
	// place.
	ColoredText(ctx Context, text string) string

	// ColoredTag colors the given tag name. This is a handy wrapper around
	// ColoredText, which tweaks the context to provide logic for coloring an
	// Event Tag.
	// The tags may be colored all in the same color, or may be colored
	// differently, each tag in different color. The bookkeeping of the tags
	// colors is left to the underlying implementation.
	// If the current terminal is not interactive (tty), then no coloring takes
	// place.
	ColoredTag(ctx Context, tag string) string

	// ColoredContent colors the event content. This is a handy wrapper for
	// ColredText, which adds heuristics for determining the color of the
	// event content - for example, the context may provide the list of
	// tags and if there exists a tag 'error' in that list, then the content
	// may be colored with the 'error' color of the palette. Similarly
	// a heuristic to look up the words 'error'  or 'info' may be applied to
	// determine the type of the content, and the content may be colored
	// accordingly.
	// If the current terminal is not interactive (tty), then no coloring takes
	// place.
	ColoredContent(ctx Context, content string) string
}

Colors defines methods for coloring text in the command line interface.

func NewAuroraColors

func NewAuroraColors() Colors

NewAuroraColors builds new Colors.

type Command

type Command func(args []string) error

Command represents a command runner. It takes subset of the program arguments that apply to the parsed command.

type CommandsCLI

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

CommandsCLI is an implementation of a program CLI based on sub-commands. Parses the command line arguments into subcommands and then executes the command given on the command line.

This is a programmable API for writing programs that use subcommands.

Example

ExampleParrot implements a hypothetical parrot that repeats a phrase given as an argument. Invoking with help would give the following output:

Usage: parrot say [ARGS]

Hypothetical parrot.

Commands:
	say - Say a phrase.

And then the help for the subcommand can be invoked like this:

Usage of say:
-phrase string
	  Phrase to say.
-times int
	  How many times to repeat the phrase. (default 1)
package main

import (
	"flag"
	"fmt"

	"github.com/theia-log/selene/cli"
)

func main() {
	parrot := cli.NewCommandCLI("parrot", "Hypothetical parrot.")

	parrot.AddCommand("say", func(args []string) error {
		fs := flag.NewFlagSet("say", flag.ExitOnError)
		phrase := fs.String("phrase", "", "Phrase to say.")
		times := fs.Int("times", 1, "How many times to repeat the phrase.")

		fs.Parse(args)

		for i := 0; i < *times; i++ {
			fmt.Println(*phrase)
		}

		return nil
	}, "Say a phrase.")

	parrot.Execute()
	// Our hypothetical parrot can then be invoked like this:
	//		parrot say -phrase Hello -times 3
	// and would print:
	//		Hello
	// 		Hello
	// 		Hello
	//
}
Output:

func NewCommandCLI

func NewCommandCLI(prog, description string) *CommandsCLI

NewCommandCLI builds a new CommandsCLI for the given program name and description.

func (*CommandsCLI) AddCommand

func (c *CommandsCLI) AddCommand(name string, command Command, help string) *CommandsCLI

AddCommand add (sub)command. A command is given a name, a handler (Command handler) and a help string.

func (*CommandsCLI) Execute

func (c *CommandsCLI) Execute() error

Execute executes the CLI program with the default arguments. The arguments are obtained from the program invocation (passed by the OS). The zeroth argument is ignored (as this is the program name), and the first argument is used to determine the command name.

func (*CommandsCLI) ExecuteWithArgs

func (c *CommandsCLI) ExecuteWithArgs(args []string) error

ExecuteWithArgs executes the CLI program with the given arguments. The first argument must be the command name. The rest of the arguments are going to be passed down to the appropriate command handler. If no hander exists for the command, an error is returned.

func (*CommandsCLI) PrintHelp

func (c *CommandsCLI) PrintHelp()

PrintHelp prints the help string to the set output stream.

func (*CommandsCLI) UseErr

func (c *CommandsCLI) UseErr(err io.Writer) *CommandsCLI

UseErr replaces the error output writer used (which by default is os.Stderr) with the provided writer. All error messages are going to be written to this writer (like standard error during parsing).

func (*CommandsCLI) UseOut

func (c *CommandsCLI) UseOut(out io.Writer) *CommandsCLI

UseOut replaces the output writer used (which by default is os.Stdout) with the output writer provided as argument. All messages generated by the command CLI (like printing program help) are going to be written to this output writer.

type Context

type Context map[string]interface{}

Context in which the text coloration takes place.

func (Context) GetString

func (c Context) GetString(key string) string

GetString looks up a string stored under a key in the Context.

type EventFlags

type EventFlags struct {
	*GlobalFlags
	ID           *string
	Source       *string
	Time         *string
	Tags         StringNVar
	Content      *string
	Separator    *string
	EofSeparator *string
	FromStdin    *bool
}

func SetupEventGeneratorFlags

func SetupEventGeneratorFlags() (*EventFlags, *flag.FlagSet)

SetupEventGeneratorFlags creates a FlagSet for parsing the 'event' subcommand.

type GlobalFlags

type GlobalFlags struct {
	// ServerURL is the full URL to the theia server. It is a websocket URL.
	ServerURL *string

	// Verbose is a flag for verbose output. If set, selene should provide
	// more verbose output, printing more messages to stdout.
	Verbose *bool

	// Host is the theia host. This is the domain part of the server URL.
	// Either host and port must be given, or a full ServerURL.
	Host *string

	// Port is the theia port. This is the port part of the server URL.
	// Either host and port must be given, or a full ServerURL.
	Port *int
}

GlobalFlags holds the parsed values for the global flags. These flags are shared (common) between all subcommands like watch, query and event.

func SetupGlobalFlagsOn

func SetupGlobalFlagsOn(fg *flag.FlagSet) *GlobalFlags

SetupGlobalFlagsOn adds the global flags to an existing FlagSet and returns the wrapper struct that will hold the parsed values for the flags.

func (*GlobalFlags) GetServerURL

func (gf *GlobalFlags) GetServerURL() (string, error)

GetServerURL returns a valid server URL based on the set up flags. If ServerURL is set, then that value is preferred and returned. If not, the URL is generated from the Host and Port values. If any of them are not set, then an error is returned.

type QueryFlags

type QueryFlags struct {
	*GlobalFlags

	// Start timestamp. Match events that occurred after or at this time.
	Start *float64

	// End timestamp. Match events that occurred before or at this time.
	End *float64

	// Tags list of tags to match. The values may be a regular expression.
	Tags StringNVar

	// Content is a regular expression to match the events content.
	Content *string

	// Order is the order in which the matched events should be returned. It
	// can be 'asc' - ascending, or 'desc' - descending order by the event
	// timestamp.
	Order *string

	// Live is a flag to indicate whether to query live (real-time) events.
	Live *bool
}

QueryFlags holds the parsed values for subcommand 'query'. This struct holds the global flags, and specific flags for the query command. Most of the values are filter values for matching events on the server.

func SetupQueryFlags

func SetupQueryFlags() (*QueryFlags, *flag.FlagSet)

SetupQueryFlags creates a FlagSet for parsing the 'query' subcommand and creates a wrapper QueryFlags to hold the parsed values from the command line.

type StringNVar

type StringNVar []string

StringNVar implements the flag.Value interface for flags that can hold multiple values.

func (*StringNVar) Set

func (n *StringNVar) Set(value string) error

Set adds an additional value to the list of multiple flag values.

func (*StringNVar) String

func (n *StringNVar) String() string

String returns a string representation of the multiple values flag value.

type TextTypeHeuristic

type TextTypeHeuristic func(text string) bool

TextTypeHeuristic is a function that checks if the given text matches some heuristic. Returns true if the texts matches the conditions in the underlying heuristic check.

type TypeHeuristics

type TypeHeuristics map[string]TextTypeHeuristic

TypeHeuristics contains map of heuristics by name.

func (TypeHeuristics) Detect

func (h TypeHeuristics) Detect(text string) string

Detect tries to detect the category in which the text belongs to. It checks against all registered heuristics.

type WatcherFlags

type WatcherFlags struct {
	*GlobalFlags

	// File is the path of the file to be watched for changes.
	File *string

	// Tags is a list of tags to be attached to the generated events.
	Tags StringNVar
}

WatcherFlags holds the parsed values for the subcommand 'watch'. This struct holds the global flags, and additional flags for the watch command.

func SetupWatcherFlags

func SetupWatcherFlags() (*WatcherFlags, *flag.FlagSet)

SetupWatcherFlags creates a FlagSet for parsing the 'watcher' subcommand and creates a wrapper WatcherFlags to hold the parsed values from the command line.

Jump to

Keyboard shortcuts

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