jcli

package module
v0.2.13 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2024 License: Apache-2.0 Imports: 19 Imported by: 3

README ¶

jcli

A package for building Go applications.

Test Codecov Go Report Card Release License

Getting Started

package main

import (
	"fmt"

	"github.com/shipengqi/jcli"
	"github.com/spf13/cobra"
)

type fakeCliOptions struct {
	Username string
	Password string
}

func (o *fakeCliOptions) Flags() (fss cliflag.NamedFlagSets) {
	fakes := fss.FlagSet("fake")
	fakes.StringVar(&o.Username, "username", o.Username, "fake username.")
	fakes.StringVar(&o.Password, "password", o.Password, "fake password.")

	return fss
}

func (o *fakeCliOptions) Validate() []error {
	return nil
}

func main() {
	// Create a new App instance
	app := jcli.New("demo",
		jcli.WithCliOptions(&fakeCliOptions{}),
		jcli.WithBaseName("demo"),
		jcli.WithExamples("This is a example for demo"),
		jcli.WithDesc("This is a description for demo"),
		jcli.WithAliases("alias1", "alias2"),
		jcli.WithRunFunc(func() error {
			fmt.Println("application running")
			return nil
		}))
	// Add sub commands
	app.AddCommands(
		jcli.NewCommand("sub1", "sub1 command description",
			jcli.WithCommandRunFunc(func(cmd *jcli.Command, args []string) error {
				fmt.Println("sub1 command running")
				return nil
			}),
			jcli.WithCommandDesc("sub1 long desc"),
		),
		jcli.NewCommand("sub2", "sub2 command description",
			jcli.WithCommandRunFunc(func(cmd *jcli.Command, args []string) error {
				fmt.Println("sub2 command running")
				return nil
			}),
		),
		jcli.NewCommand("sub3", "sub3 command description"),
	)
	// Add cobra commands as sub commands
	app.AddCobraCommands(&cobra.Command{
		Use:   "sub4",
		Short: "sub4 command description",
		RunE: func(cmd *cobra.Command, args []string) error {
			fmt.Println("sub4 command running")
			return nil
		},
	})
	app.Run()
}
WithLogger

Use jcli.WithLogger to set a custom Logger

DisableConfig

By default, App will add the --config flag, and use Viper to parse the config file. The ".{{basename}}" file in the home directory and the "{{basename}}" file in the "/etc" directory will be loaded as a configuration file.

You can use DisableConfig to disable it.

DisableVersion

By default, App will add the --version flag, you can use DisableVersion to disable it.

EnableSilence

Use EnableSilence to set the application to silent mode.

WithOnSignalReceived

Use WithOnSignalReceived to set a signals' receiver. SIGTERM and SIGINT are registered by default. Register other signals via the signal parameter.

EnableCompletion

Use EnableCompletion to create a default 'completion' command.

Create a new root command
package main

import (
	"fmt"

	"github.com/shipengqi/jcli"
	"github.com/spf13/cobra"
)

type fakeCliOptions struct {
	Username string
	Password string
}

func (o *fakeCliOptions) Flags() (fss cliflag.NamedFlagSets) {
	fakes := fss.FlagSet("fake")
	fakes.StringVar(&o.Username, "username", o.Username, "fake username.")
	fakes.StringVar(&o.Password, "password", o.Password, "fake password.")

	return fss
}

func (o *fakeCliOptions) Validate() []error {
	return nil
}

func main() {
	// Create a root Command
	app := jcli.NewCommand(
		"demo",
		"This is a short description",
		jcli.WithCommandDesc("This is a long description"),
		jcli.EnableCommandVersion(), // Enable the version flag of the root Command, set only when use the Command as a root command.
		jcli.WithCommandRunFunc(func(cmd *jcli.Command, args []string) error {
			fmt.Printf("%s Version: \n%s", "=======>", "dev")
			return cmd.Help()
		}),
	)

	// Set PersistentPreRun for the root command
	app.CobraCommand().PersistentPreRun = func(cmd *cobra.Command, args []string) {
		fmt.Println("PersistentPreRun")
	}
	// Add sub commands
	app.AddCommands(
		jcli.NewCommand("sub1", "sub1 command description",
			jcli.WithCommandRunFunc(func(cmd *jcli.Command, args []string) error {
				fmt.Println("sub1 command running")
				return nil
			}),
			jcli.WithCommandDesc("sub1 long desc"),
		),
	)
	// Add cobra commands as sub commands
	app.AddCobraCommands(&cobra.Command{
		Use:   "sub2",
		Short: "sub2 command description",
		RunE: func(cmd *cobra.Command, args []string) error {
			fmt.Println("sub2 command running")
			return nil
		},
	})
	cobra.EnableCommandSorting = false
}

Documentation

You can find the docs at go docs.

🔋 JetBrains OS licenses

jcli had been being developed with GoLand under the free JetBrains Open Source license(s) granted by JetBrains s.r.o., hence I would like to express my thanks here.

JetBrains Logo (Main) logo.

Documentation ¶

Index ¶

Constants ¶

View Source
const ConfigFlagName = "config"
View Source
const (
	FlagSetNameGlobal = "global"
)

Variables ¶

This section is empty.

Functions ¶

func Blue ¶

func Blue(msg string) string

func Colorize ¶

func Colorize(msg string, attrs ...color.Attribute) string

func Green ¶

func Green(msg string) string

func IconBlue ¶ added in v0.1.2

func IconBlue(msg string) string

func NormalizeCliName ¶

func NormalizeCliName(basename string) string

func Red ¶

func Red(msg string) string

func Yellow ¶

func Yellow(msg string) string

Types ¶

type App ¶

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

App is the main structure of a cli application.

func New ¶

func New(name string, opts ...Option) *App

New create a new cli application.

func (*App) AddCobraCommands ¶ added in v0.1.1

func (a *App) AddCobraCommands(commands ...*cobra.Command)

AddCobraCommands adds multiple sub cobra.Command to the App.

func (*App) AddCommands ¶

func (a *App) AddCommands(commands ...*Command)

AddCommands adds multiple sub commands to the App.

func (*App) Command ¶

func (a *App) Command() *cobra.Command

Command returns cobra command instance inside the App.

func (*App) Logger ¶ added in v0.2.0

func (a *App) Logger() Logger

Logger return the (logger) of the App.

func (*App) PrintWorkingDir ¶ added in v0.2.0

func (a *App) PrintWorkingDir()

func (*App) Run ¶

func (a *App) Run()

Run is used to launch the application.

type CliOptions ¶

type CliOptions interface {
	Flags() (fss cliflag.NamedFlagSets)
	Validate() []error
}

CliOptions abstracts configuration options for reading parameters from the command line.

type Command ¶ added in v0.1.1

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

Command is a sub command structure of a cli application. It is recommended that a command be created with the app.NewCommand() function.

func NewCommand ¶ added in v0.1.1

func NewCommand(name string, short string, opts ...CommandOption) *Command

NewCommand creates a new sub command instance based on the given command name and other options.

func (*Command) AddCobraCommands ¶ added in v0.1.1

func (c *Command) AddCobraCommands(commands ...*cobra.Command)

AddCobraCommands adds multiple sub cobra.Command to the current command.

func (*Command) AddCommands ¶ added in v0.1.1

func (c *Command) AddCommands(commands ...*Command)

AddCommands adds multiple sub commands to the current command.

func (*Command) CobraCommand ¶ added in v0.1.6

func (c *Command) CobraCommand() *cobra.Command

CobraCommand returns cobra command instance inside the Command.

func (*Command) Flags ¶ added in v0.1.19

func (c *Command) Flags() *pflag.FlagSet

Flags returns the complete FlagSet that applies to this command.

func (*Command) Help ¶ added in v0.1.16

func (c *Command) Help() error

Help runs the Help of cobra command.

func (*Command) MarkHidden ¶ added in v0.1.19

func (c *Command) MarkHidden(flags ...string)

MarkHidden sets flags to 'hidden' in your program.

func (*Command) Name ¶ added in v0.1.18

func (c *Command) Name() string

Name returns the command's name: the first word in the use line.

func (*Command) Run ¶ added in v0.1.16

func (c *Command) Run()

Run runs the command.

type CommandOption ¶ added in v0.1.1

type CommandOption interface {
	// contains filtered or unexported methods
}

CommandOption defines optional parameters for initializing the command structure.

func EnableCommandCompletion ¶ added in v0.2.0

func EnableCommandCompletion(hidden bool) CommandOption

EnableCommandCompletion creating a default 'completion' command of the Command. Set only when use the Command as a root command.

func EnableCommandVersion ¶ added in v0.1.22

func EnableCommandVersion() CommandOption

EnableCommandVersion enable the version flag of the Command. Set only when use the Command as a root command.

func WithCommandAliases ¶ added in v0.1.1

func WithCommandAliases(aliases ...string) CommandOption

WithCommandAliases sets the Command aliases.

func WithCommandCliOptions ¶ added in v0.1.1

func WithCommandCliOptions(opts CliOptions) CommandOption

WithCommandCliOptions to open the command's function to read from the command line.

func WithCommandDesc ¶ added in v0.1.2

func WithCommandDesc(desc string) CommandOption

WithCommandDesc sets the Command description.

func WithCommandExamples ¶ added in v0.1.20

func WithCommandExamples(examples string) CommandOption

WithCommandExamples is used to set the examples of the Command.

func WithCommandRunFunc ¶ added in v0.1.1

func WithCommandRunFunc(run RunCommandFunc) CommandOption

WithCommandRunFunc is used to set the command startup callback function option.

type CompletableOptions ¶

type CompletableOptions interface {
	Complete() error
}

CompletableOptions abstracts options which can be completed.

type FlagPrinter ¶ added in v0.2.11

type FlagPrinter interface {
	Printf(template string, args ...interface{})
}

type Logger ¶ added in v0.2.0

type Logger interface {
	Debugf(template string, args ...interface{})
	Debug(msg string, keysAndValues ...interface{})
	Infof(template string, args ...interface{})
	Info(msg string, keysAndValues ...interface{})
	Warnf(template string, args ...interface{})
	Warn(msg string, keysAndValues ...interface{})
	Errorf(template string, args ...interface{})
	Error(msg string, keysAndValues ...interface{})
	Fatalf(template string, args ...interface{})
	Fatal(msg string, keysAndValues ...interface{})
}

type Option ¶

type Option interface {
	// contains filtered or unexported methods
}

Option defines optional parameters for initializing the application structure.

func DisableConfig ¶

func DisableConfig() Option

DisableConfig disable the config flag.

func DisableVersion ¶

func DisableVersion() Option

DisableVersion disable the version flag.

func EnableCompletion ¶ added in v0.2.0

func EnableCompletion(hidden bool) Option

EnableCompletion creating a default 'completion' command

func EnableSilence ¶ added in v0.2.11

func EnableSilence() Option

EnableSilence sets the application to silent mode, in which the program startup information, flags, configuration information, and version information are not printed in the console.

func WithAliases ¶ added in v0.1.1

func WithAliases(aliases ...string) Option

WithAliases sets the application aliases.

func WithBaseName ¶

func WithBaseName(basename string) Option

WithBaseName is used to set the basename of the cli.

func WithCliOptions ¶

func WithCliOptions(opts CliOptions) Option

WithCliOptions to open the application's function to read from the command line or read parameters from the configuration file.

func WithDesc ¶

func WithDesc(desc string) Option

WithDesc is used to set the description of the application.

func WithExamples ¶ added in v0.1.20

func WithExamples(examples string) Option

WithExamples is used to set the examples of the application.

func WithFlagPrinter ¶ added in v0.2.11

func WithFlagPrinter(printer FlagPrinter) Option

WithFlagPrinter is used print the flags of the application.

func WithLogger ¶ added in v0.2.0

func WithLogger(logger Logger) Option

WithLogger is used to set the (logger) of the application.

func WithOnSignalReceived ¶ added in v0.1.11

func WithOnSignalReceived(receiver func(os.Signal), signals ...os.Signal) Option

WithOnSignalReceived sets a signals' receiver. SIGTERM and SIGINT are registered by default. Register other signals via the signal parameter.

func WithRunFunc ¶

func WithRunFunc(run RunFunc) Option

WithRunFunc is used to set the application run callback function option.

type PrintableOptions ¶

type PrintableOptions interface {
	String() string
}

PrintableOptions abstracts options which can be printed.

type RunCommandFunc ¶ added in v0.1.1

type RunCommandFunc func(cmd *Command, args []string) error

RunCommandFunc defines the command startup callback function.

type RunFunc ¶

type RunFunc func() error

RunFunc defines the application's run callback function.

type SignalReceiver ¶ added in v0.1.11

type SignalReceiver func(os.Signal)

Jump to

Keyboard shortcuts

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