cobrather

package
v0.0.0-...-c6ea6ab Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2021 License: LGPL-3.0 Imports: 10 Imported by: 23

README

cobrather

Modularized command

  • Simple Module
// Module info
var Module = &cobrather.Module{
	Use: "example",
	Commands: []*cobrather.Module{
		cobrather.VersionModule, // sub command module
	},
}

func main() {
	Module.MustMainRun()
}
  • Custom viper for more config for environment
// Module info
var Module = &cobrather.Module{
	Use: "example",
	Commands: []*cobrather.Module{
		cobrather.VersionModule, // sub command module
	},
}

func main() {
	vr := viper.New()
	vr.AutomaticEnv()
	vr.SetEnvPrefix("ENVPREFIX")
	Module.MustMainRun(
		cobrather.MainRunOptionViper(vr),
	)
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrFlagNotYetBind1 = errutil.NewFactory("flag %q is not yet bind")
	ErrFlagBinded3     = errutil.NewFactory("flag %q binded with different types: %q != %q")
)

errors

View Source
var (
	ErrorVersionNotInRange2 = errutil.NewFactory("current version %q not in range %q")
	ErrorInvalidRange1      = errutil.NewFactory("invalid range string %q")
)

erors

View Source
var VersionModule = &Module{
	Use:   "version",
	Short: "Show version detail",
	Example: strings.TrimSpace(`
version -n
version -c ">=0.3.5"
version -c ">=0.3.5 , <1"
	`),
	Flags: []Flag{
		flagNumber,
		flagContains,
	},
	RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
		return showVersion(flagNumber.Bool(), flagContains.String())
	},
}

VersionModule provide module of version, Set nil to disable version command

Functions

func GenPostRunE

func GenPostRunE(ctx context.Context, modules ...*Module) func(cmd *cobra.Command, args []string) error

GenPostRunE generate PostRunE for all modules, start from tail to head

func GenRunE

func GenRunE(ctx context.Context, modules ...*Module) func(cmd *cobra.Command, args []string) error

GenRunE generate RunE for all modules

Types

type BoolFlag

type BoolFlag struct {
	Name      string
	ShortHand string
	Default   bool
	Usage     string
	EnvVar    string
	Hidden    bool
	// contains filtered or unexported fields
}

BoolFlag represents a flag that takes as bool value

func (*BoolFlag) Bind

func (t *BoolFlag) Bind(flagset *pflag.FlagSet, v *viper.Viper) (err error)

Bind flag to flagset and viper for environment

func (*BoolFlag) Bool

func (t *BoolFlag) Bool() bool

Bool return flag value

type Flag

type Flag interface {
	Bind(flagset *pflag.FlagSet, v *viper.Viper) error
}

Flag is a common interface related to parsing flags in cobra.

type Float64Flag

type Float64Flag struct {
	Name      string
	ShortHand string
	Default   float64
	Usage     string
	EnvVar    string
	Hidden    bool
	// contains filtered or unexported fields
}

Float64Flag represents a flag that takes as float64 value

func (*Float64Flag) Bind

func (t *Float64Flag) Bind(flagset *pflag.FlagSet, v *viper.Viper) (err error)

Bind flag to flagset and viper for environment

func (*Float64Flag) Float64

func (t *Float64Flag) Float64() float64

Float64 return flag value

type Int64Flag

type Int64Flag struct {
	Name      string
	ShortHand string
	Default   int64
	Usage     string
	EnvVar    string
	Hidden    bool
	// contains filtered or unexported fields
}

Int64Flag represents a flag that takes as int64 value

func (*Int64Flag) Bind

func (t *Int64Flag) Bind(flagset *pflag.FlagSet, v *viper.Viper) (err error)

Bind flag to flagset and viper for environment

func (*Int64Flag) Int64

func (t *Int64Flag) Int64() int64

Int64 return flag value

type ListDepsOption

type ListDepsOption int8

ListDepsOption options for ListDeps

const (
	// OIncludeCommand list result contains commands in Module
	OIncludeCommand ListDepsOption = 1 << iota
	// OIncludeDepInCommand list result contains dependencies in commands, but not commands self
	OIncludeDepInCommand
)

func (ListDepsOption) Has

func (t ListDepsOption) Has(opt ListDepsOption) bool

Has return true if ListDepsOption contains opt

type MainRunOption

type MainRunOption interface{}

MainRunOption option for Module.MustMainRun

type MainRunOptionContext

type MainRunOptionContext context.Context

MainRunOptionContext config Context interface for running commands

type MainRunOptionSilenceUsage

type MainRunOptionSilenceUsage bool

MainRunOptionSilenceUsage config SilenceUsage before run, default true

type MainRunOptionViper

type MainRunOptionViper *viper.Viper

MainRunOptionViper config Viper

type Module

type Module struct {
	// The one-line usage message.
	Use string
	// An array of aliases that can be used instead of the first word in Use.
	Aliases []string
	// The short description shown in the 'help' output.
	Short string
	// The long message shown in the 'help <this-command>' output.
	Long string
	// Examples of how to use the command
	Example string
	// RunE: Run but returns an error
	RunE func(ctx context.Context, cmd *cobra.Command, args []string) error
	// PostRunE: PostRun but returns an error
	PostRunE func(ctx context.Context, cmd *cobra.Command, args []string) error

	// extend cobra.Command fields
	GlobalFlags  []Flag
	Flags        []Flag
	Dependencies []*Module
	Commands     []*Module
	// contains filtered or unexported fields
}

Module for cobra, used for cobra.Command

Example
package main

import (
	"context"
	"fmt"

	"github.com/spf13/cobra"
	"github.com/tsaikd/KDGoLib/cliutil/cobrather"
)

func main() {
	modCommon := &cobrather.Module{
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modCommon Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modCommon PostRun")
			return nil
		},
	}
	modForCmd := &cobrather.Module{
		Dependencies: []*cobrather.Module{modCommon},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForCmd Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForCmd PostRun")
			return nil
		},
	}
	modForRoot := &cobrather.Module{
		Dependencies: []*cobrather.Module{modCommon},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForRoot Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForRoot PostRun")
			return nil
		},
	}
	cmd := &cobrather.Module{
		Use:          "cmd",
		Dependencies: []*cobrather.Module{modForCmd},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("cmd Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("cmd PostRun")
			return nil
		},
	}
	root := &cobrather.Module{
		Use:          "root",
		Dependencies: []*cobrather.Module{modForRoot},
		Commands:     []*cobrather.Module{cmd, cobrather.VersionModule},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("root Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("root PostRun")
			return nil
		},
	}

	root.MustMainRun()

}
Output:

modCommon Run
modForRoot Run
root Run
root PostRun
modForRoot PostRun
modCommon PostRun
Example (Cmd)
package main

import (
	"context"
	"fmt"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/tsaikd/KDGoLib/cliutil/cobrather"
)

func main() {
	Viper := viper.New()
	flagCmd := &cobrather.StringFlag{
		Name:    "flagcmd",
		Default: "default flag cmd string",
		Usage:   "flag cmd string type",
	}
	modCommon := &cobrather.Module{
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modCommon Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modCommon PostRun")
			return nil
		},
	}
	modForCmd := &cobrather.Module{
		Dependencies: []*cobrather.Module{modCommon},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForCmd Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForCmd PostRun")
			return nil
		},
	}
	modForRoot := &cobrather.Module{
		Dependencies: []*cobrather.Module{modCommon},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForRoot Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForRoot PostRun")
			return nil
		},
	}
	cmd := &cobrather.Module{
		Use:          "cmd",
		Dependencies: []*cobrather.Module{modForCmd},
		GlobalFlags: []cobrather.Flag{
			flagCmd,
		},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("cmd Run", flagCmd.String())
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("cmd PostRun")
			return nil
		},
	}
	root := &cobrather.Module{
		Use:          "root",
		Dependencies: []*cobrather.Module{modForRoot},
		Commands:     []*cobrather.Module{cmd, cobrather.VersionModule},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("root Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("root PostRun")
			return nil
		},
	}

	ctx := context.Background()
	rootCommand := root.MustNewRootCommand(ctx, Viper)
	rootCommand.SetArgs([]string{"cmd", "--flagcmd", "replace flag cmd"})
	if err := rootCommand.Execute(); err != nil {
		fmt.Println(err)
	}

}
Output:

modCommon Run
modForCmd Run
cmd Run replace flag cmd
cmd PostRun
modForCmd PostRun
modCommon PostRun
Example (Context)
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/spf13/cobra"
	"github.com/tsaikd/KDGoLib/cliutil/cobrather"
)

func main() {
	modCommon := &cobrather.Module{
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modCommon Run")
			select {
			case <-ctx.Done():
				return nil
			case <-time.Tick(1 * time.Second):
				return nil
			}
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modCommon PostRun")
			return nil
		},
	}
	modForCmd := &cobrather.Module{
		Dependencies: []*cobrather.Module{modCommon},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForCmd Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForCmd PostRun")
			return nil
		},
	}
	modForRoot := &cobrather.Module{
		Dependencies: []*cobrather.Module{modCommon},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForRoot Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForRoot PostRun")
			return nil
		},
	}
	cmd := &cobrather.Module{
		Use:          "cmd",
		Dependencies: []*cobrather.Module{modForCmd},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("cmd Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("cmd PostRun")
			return nil
		},
	}
	root := &cobrather.Module{
		Use:          "root",
		Dependencies: []*cobrather.Module{modForRoot},
		Commands:     []*cobrather.Module{cmd, cobrather.VersionModule},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("root Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("root PostRun")
			return nil
		},
	}

	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
	defer cancel()
	root.MustMainRun(cobrather.MainRunOptionContext(ctx))

}
Output:

modCommon Run
modForRoot Run
root PostRun
modForRoot PostRun
modCommon PostRun
Example (Flag)
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/tsaikd/KDGoLib/cliutil/cobrather"
)

func main() {
	Viper := viper.New()
	flagFromArg := &cobrather.StringFlag{
		Name:    "fromarg",
		Default: "default flag arg string",
		Usage:   "flag string from arg",
	}
	flagFromEnv := &cobrather.StringFlag{
		Name:    "fromenv",
		Default: "default flag env string",
		Usage:   "flag string from env",
		EnvVar:  "FROMENV",
	}
	modCommon := &cobrather.Module{
		GlobalFlags: []cobrather.Flag{
			flagFromArg,
			flagFromEnv,
		},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modCommon Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modCommon PostRun")
			return nil
		},
	}
	modForCmd := &cobrather.Module{
		Dependencies: []*cobrather.Module{modCommon},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForCmd Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForCmd PostRun")
			return nil
		},
	}
	modForRoot := &cobrather.Module{
		Dependencies: []*cobrather.Module{modCommon},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForRoot Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("modForRoot PostRun")
			return nil
		},
	}
	cmd := &cobrather.Module{
		Use:          "cmd",
		Dependencies: []*cobrather.Module{modForCmd},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("cmd Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("cmd PostRun")
			return nil
		},
	}
	root := &cobrather.Module{
		Use:          "root",
		Dependencies: []*cobrather.Module{modForRoot},
		Commands:     []*cobrather.Module{cmd, cobrather.VersionModule},
		RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("root Run")
			return nil
		},
		PostRunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
			fmt.Println("root PostRun")
			fmt.Println("from arg:", flagFromArg.String())
			fmt.Println("from env:", flagFromEnv.String())
			return nil
		},
	}

	os.Setenv("FROMENV", "test string from env")
	ctx := context.Background()
	rootCommand := root.MustNewRootCommand(ctx, Viper)
	rootCommand.SetArgs([]string{"--fromarg", "test string from arg"})
	if err := rootCommand.Execute(); err != nil {
		fmt.Println(err)
	}

}
Output:

modCommon Run
modForRoot Run
root Run
root PostRun
from arg: test string from arg
from env: test string from env
modForRoot PostRun
modCommon PostRun

func ListDeps

func ListDeps(opt ListDepsOption, modules ...*Module) []*Module

ListDeps list all dependent modules recursively

Example
package main

import (
	"context"
	"fmt"

	"github.com/spf13/cobra"
	"github.com/tsaikd/KDGoLib/cliutil/cobrather"
)

func main() {
	ctx := context.Background()
	createModule := func(name string) *cobrather.Module {
		return &cobrather.Module{
			RunE: func(ctx context.Context, cmd *cobra.Command, args []string) error {
				fmt.Println(name)
				return nil
			},
		}
	}

	modCommonDep := createModule("modCommonDep")
	modCommon := createModule("modCommon")
	modCommon.Dependencies = []*cobrather.Module{modCommonDep}

	modCmdCmdDep := createModule("modCmdCmdDep")
	modCmdCmdDep.Dependencies = []*cobrather.Module{modCommon}
	modCmdCmd := createModule("modCmdCmd")
	modCmdCmd.Dependencies = []*cobrather.Module{modCmdCmdDep}

	modCmdDep := createModule("modCmdDep")
	modCmdDep.Dependencies = []*cobrather.Module{modCommon}
	modCmd := createModule("modCmd")
	modCmd.Dependencies = []*cobrather.Module{modCmdDep}
	modCmd.Commands = []*cobrather.Module{modCmdCmd}

	modRootDep := createModule("modRootDep")
	modRootDep.Dependencies = []*cobrather.Module{modCommon}
	modRoot := createModule("modRoot")
	modRoot.Dependencies = []*cobrather.Module{modRootDep}
	modRoot.Commands = []*cobrather.Module{modCmd}

	fmt.Println("only list dependencies of modRoot")
	for _, module := range cobrather.ListDeps(0, modRoot) {
		if err := module.RunE(ctx, nil, []string{}); err != nil {
			fmt.Println(err)
		}
	}
	fmt.Println()

	fmt.Println("list all dependencies of modRoot, include commands")
	for _, module := range cobrather.ListDeps(cobrather.OIncludeCommand, modRoot) {
		if err := module.RunE(ctx, nil, []string{}); err != nil {
			fmt.Println(err)
		}
	}
	fmt.Println()

	fmt.Println("list all dependencies of modRoot, include dependencies in commands, except commands")
	for _, module := range cobrather.ListDeps(cobrather.OIncludeDepInCommand, modRoot) {
		if err := module.RunE(ctx, nil, []string{}); err != nil {
			fmt.Println(err)
		}
	}
	fmt.Println()

}
Output:

only list dependencies of modRoot
modCommonDep
modCommon
modRootDep

list all dependencies of modRoot, include commands
modCommonDep
modCommon
modRootDep
modCmdDep
modCmdCmdDep
modCmdCmd
modCmd

list all dependencies of modRoot, include dependencies in commands, except commands
modCommonDep
modCommon
modRootDep
modCmdDep
modCmdCmdDep

func (*Module) MustMainRun

func (t *Module) MustMainRun(options ...MainRunOption)

MustMainRun used for main package to run main module

func (*Module) MustNewCommand

func (t *Module) MustNewCommand(ctx context.Context) *cobra.Command

MustNewCommand create cobra.Command from Module

func (*Module) MustNewRootCommand

func (t *Module) MustNewRootCommand(ctx context.Context, vr *viper.Viper) *cobra.Command

MustNewRootCommand create cobra.Command from Module for root application

type StringFlag

type StringFlag struct {
	Name      string
	ShortHand string
	Default   string
	Usage     string
	EnvVar    string
	Hidden    bool
	// contains filtered or unexported fields
}

StringFlag represents a flag that takes as string value

func (*StringFlag) Bind

func (t *StringFlag) Bind(flagset *pflag.FlagSet, v *viper.Viper) (err error)

Bind flag to flagset and viper for environment

func (*StringFlag) String

func (t *StringFlag) String() string

String return flag value

type StringSliceFlag

type StringSliceFlag struct {
	Name      string
	ShortHand string
	Default   []string
	Usage     string
	Hidden    bool
	// contains filtered or unexported fields
}

StringSliceFlag represents a flag that takes as string value

func (*StringSliceFlag) Bind

func (t *StringSliceFlag) Bind(flagset *pflag.FlagSet, v *viper.Viper) (err error)

Bind flag to flagset and viper for environment

func (*StringSliceFlag) StringSlice

func (t *StringSliceFlag) StringSlice() []string

StringSlice return flag value

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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