cmdutils

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: Apache-2.0 Imports: 26 Imported by: 9

Documentation

Index

Constants

View Source
const (
	TagKeyFlag        = "flag"
	TagKeyDescription = "desc"
	TagFlagSeparator  = ","
	TagFlagRequired   = "required"
)
View Source
const (
	ModulePath = "github.com/cisco-open/go-lanai"
)

Variables

View Source
var (
	GlobalArgs = Global{
		WorkingDir: DefaultWorkingDir(),
		TmpDir:     DefaultTemporaryDir(),
		OutputDir:  DefaultOutputDir(),
	}
)
View Source
var ShCmdLogDisabled bool

ShCmdLogDisabled Disable shell command logging. When set to true, ShCmdOption.ShowCmd no longer take effect

Functions

func BindJsonFile

func BindJsonFile(bind interface{}, filepath string, additionalLookupDirs ...string) (string, error)

BindJsonFile find, read and bind JSON file, returns absolute path of loaded file

func BindYaml

func BindYaml(reader io.Reader, bind interface{}) error

BindYaml read from given io.Reader and parse as YAML

func BindYamlFile

func BindYamlFile(bind interface{}, filepath string, additionalLookupDirs ...string) (string, error)

BindYamlFile find, read and bind YAML file, returns absolute path of loaded file

func DefaultOutputDir

func DefaultOutputDir() string

func DefaultTemporaryDir

func DefaultTemporaryDir() string

func DefaultWorkingDir

func DefaultWorkingDir() string

func DropReplace

func DropReplace(ctx context.Context, module string, version string, opts ...GoCmdOptions) error

func DropRequire

func DropRequire(ctx context.Context, module string, opts ...GoCmdOptions) error

func FindGitRepoRoot

func FindGitRepoRoot(path string) (string, error)

FindGitRepoRoot returns parent folder that containing `.git`

func FindPackages

func FindPackages(ctx context.Context, opts []GoCmdOptions, modules ...string) (map[string]*GoPackage, error)

func GenerateFileWithOption

func GenerateFileWithOption(ctx context.Context, opt *TemplateOption) error

GenerateFileWithOption generate file using given FS and template name

func GoCommandDecodeJson

func GoCommandDecodeJson(ctx context.Context, model interface{}, opts ...ShCmdOptions) (ret []interface{}, err error)

func GoGet

func GoGet(ctx context.Context, module string, versionQuery string, opts ...GoCmdOptions) error

func GoModTidy

func GoModTidy(ctx context.Context, extraShellOptions []ShCmdOptions, opts ...GoCmdOptions) error

func IsGitRepoRoot

func IsGitRepoRoot(path string) bool

func IsLocalPackageExists

func IsLocalPackageExists(ctx context.Context, pkgPath string) (bool, error)

func LoadYamlConfig

func LoadYamlConfig(bind interface{}, filepath string, additionalLookupDirs ...string) error

func LocalFlags

func LocalFlags(cmd *cobra.Command, value interface{})

LocalFlags is similar to PersistentFlags

func LookupFile

func LookupFile(filePath string, additionalLookupDirs ...string) (absPath string, file *os.File, err error)

LookupFile search and open file for read, relative to GlobalArgs.WorkingDir or any additional lookup directories. Returns absolute path and opened file handle if successful. Otherwise, return error

func LookupFiles

func LookupFiles(pattern string, dirs ...string) (absPaths []string, err error)

LookupFiles search files using provided pattern under given lookup directories relative to GlobalArgs.WorkingDir. Returns list of absolute path if successful. Otherwise, return error

func MatchPathPattern

func MatchPathPattern(pattern, path string) (bool, error)

MatchPathPattern given string with path pattern The prefix syntax is:

prefix:
  { term }
term:
  '*'         matches any sequence of non-path-separators
  '**'        matches any sequence of characters, including
              path separators.
  '?'         matches any single non-path-separator character
  '[' [ '^' ] { character-range } ']'
        character class (must be non-empty)
  '{' { term } [ ',' { term } ... ] '}'
  c           matches character c (c != '*', '?', '\\', '[')
  '\\' c      matches character c

character-range:
  c           matches character c (c != '\\', '-', ']')
  '\\' c      matches character c
  lo '-' hi   matches character c for lo <= c <= hi

func MatchPrefix

func MatchPrefix(prefix, value string, caseInsensitive bool) (bool, error)

func MatchRegex

func MatchRegex(regex, value string) (bool, error)

func MatchRegexPattern

func MatchRegexPattern(regex *regexp.Regexp, value string) (bool, error)

func MatchString

func MatchString(expected, actual string, caseInsensitive bool) bool

func MatchSubString

func MatchSubString(substr, actual string, caseInsensitive bool) bool

func MatchSuffix

func MatchSuffix(suffix, value string, caseInsensitive bool) (bool, error)

func OpenFile

func OpenFile(filePath string, flag int, perm os.FileMode) (absPath string, file *os.File, err error)

OpenFile open file relative to GlobalArgs.WorkingDir. Returns absolute path and opened file handle if successful. Otherwise, return error

func PackageImportPathCache

func PackageImportPathCache(ctx context.Context) map[string]*GoPackage

func PathRelativeToModuleDir

func PathRelativeToModuleDir(relativePath string) string

func PersistentFlags

func PersistentFlags(cmd *cobra.Command, value interface{})

PersistentFlags takes Struct or *Struct value and register its fields using "flag" tag with cmd.PersistentFlags it panic if given value is not a struct Tag syntax:

`flag:"<name>[,<short_name>][,required]" desc:"<description for help cmd>"`

func RestoreInvalidReplace

func RestoreInvalidReplace(ctx context.Context, replaces []*Replace, opts ...GoCmdOptions) error

RestoreInvalidReplace works together with DropInvalidReplace

func RunShellCommands

func RunShellCommands(ctx context.Context, opts ...ShCmdOptions) (uint8, error)

RunShellCommands runs a shell command, returns exit status and an error

func SetReplace

func SetReplace(ctx context.Context, replaces []*Replace, opts ...GoCmdOptions) error

SetReplace Set given replaces in go.mod

Types

type AndMatcher

type AndMatcher[T any] []Matcher[T]

AndMatcher chain a list of matchers with AND operator

func (AndMatcher[T]) And

func (m AndMatcher[T]) And(matchers ...Matcher[T]) ChainableMatcher[T]

func (AndMatcher[T]) Matches

func (m AndMatcher[T]) Matches(i T) (ret bool, err error)

func (AndMatcher[T]) MatchesWithContext

func (m AndMatcher[T]) MatchesWithContext(c context.Context, i T) (ret bool, err error)

func (AndMatcher[T]) Or

func (m AndMatcher[T]) Or(matchers ...Matcher[T]) ChainableMatcher[T]

func (AndMatcher[T]) String

func (m AndMatcher[T]) String() string

type Base64Value

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

Base64Value implements pflag.Value and pflag.SliceValue

func (*Base64Value) Set

func (v *Base64Value) Set(s string) error

func (Base64Value) String

func (v Base64Value) String() string

pflag.Value

func (Base64Value) Type

func (v Base64Value) Type() string

type ChainableMatcher

type ChainableMatcher[T any] interface {
	Matcher[T]
	// Or concat given matchers with OR operator
	Or(matcher ...Matcher[T]) ChainableMatcher[T]
	// And concat given matchers with AND operator
	And(matcher ...Matcher[T]) ChainableMatcher[T]
}

func And

func And[T any](left Matcher[T], right ...Matcher[T]) ChainableMatcher[T]

And concat given matchers with AND operator

func Any

func Any[T any]() ChainableMatcher[T]

Any returns a matcher that matches everything

func None

func None[T any]() ChainableMatcher[T]

None returns a matcher that matches nothing

func Not

func Not[T any](matcher Matcher[T]) ChainableMatcher[T]

Not returns a negated matcher

func Or

func Or[T any](left Matcher[T], right ...Matcher[T]) ChainableMatcher[T]

Or concat given matchers with OR operator

type GenericMatcher

type GenericMatcher[T any] struct {
	Description string
	MatchFunc   func(context.Context, T) (bool, error)
}

GenericMatcher implements ChainableMatcher Implementing structs could directly use or embed this struct for convenience

func (*GenericMatcher[T]) And

func (m *GenericMatcher[T]) And(matchers ...Matcher[T]) ChainableMatcher[T]

func (*GenericMatcher[T]) Matches

func (m *GenericMatcher[T]) Matches(i T) (bool, error)

func (*GenericMatcher[T]) MatchesWithContext

func (m *GenericMatcher[T]) MatchesWithContext(c context.Context, i T) (ret bool, err error)

func (*GenericMatcher[T]) Or

func (m *GenericMatcher[T]) Or(matchers ...Matcher[T]) ChainableMatcher[T]

func (*GenericMatcher[T]) String

func (m *GenericMatcher[T]) String() string

type GitFileMatcher

type GitFileMatcher func(path string) bool

func GitFilePattern

func GitFilePattern(patterns ...string) GitFileMatcher

type GitUtils

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

func NewGitUtilsWithPath

func NewGitUtilsWithPath(path string) (*GitUtils, error)

func NewGitUtilsWithWorkingDir

func NewGitUtilsWithWorkingDir() (*GitUtils, error)

func (*GitUtils) CommitIfModified

func (g *GitUtils) CommitIfModified(msg string, matchers ...GitFileMatcher) (plumbing.Hash, error)

CommitIfModified perform commit on matched files (all files if matchers not specified). it returns the commit hash if commit was performed or the current HEAD if commit is not performed (no files committed)

func (*GitUtils) HeadCommitHash

func (g *GitUtils) HeadCommitHash() (plumbing.Hash, error)

HeadCommitHash get current Head commit it returns the commit hash if commit was performed or the current HEAD if commit is not performed (no files committed)

func (*GitUtils) MarkCommit

func (g *GitUtils) MarkCommit(tag string, commitHash plumbing.Hash) error

MarkCommit create a lightweight tag of given commit hash

func (*GitUtils) MarkWorktree

func (g *GitUtils) MarkWorktree(tag string, msg string, detach bool, matchers ...GitFileMatcher) error

MarkWorktree create a local commit with given msg and tag it with given tag. if detach == true, soft reset to initial head after done

func (*GitUtils) MarkedCommit

func (g *GitUtils) MarkedCommit(tag string) (plumbing.Hash, error)

MarkedCommit returns commit hash that previously marked with given TAG

func (*GitUtils) Repository

func (g *GitUtils) Repository() *git.Repository

func (*GitUtils) ResetToCommit

func (g *GitUtils) ResetToCommit(commitHash plumbing.Hash, discardChanges bool) error

ResetToCommit Reset current branch to given commit hash

func (*GitUtils) ResetToMarkedCommit

func (g *GitUtils) ResetToMarkedCommit(markedTag string, discardChanges bool) error

ResetToMarkedCommit find previously marked commit using "markedTag" and reset current branch to the marked commit if current branch doesn't include the marked commit, error would return

func (*GitUtils) TagCommit

func (g *GitUtils) TagCommit(tag string, commitHash plumbing.Hash, opts *git.CreateTagOptions, allowReTag bool) error

TagCommit tag given commit hash. if the tag already exist and allowReTag == true, the existing tag would be redirected to given commit if opts == nil, lightweight tag is created, otherwise annotated tag

func (*GitUtils) TagMarkedCommit

func (g *GitUtils) TagMarkedCommit(markedTag string, newTag string, opts *git.CreateTagOptions) error

TagMarkedCommit find previously marked commit using "markedTag" and re-tag it with "newTag" as name and opts if opts is nil, the new tag is lightweight, otherwise annotated tag

func (*GitUtils) WithContext

func (g *GitUtils) WithContext(ctx context.Context) *GitUtils

type Global

type Global struct {
	WorkingDir string `flag:"workspace,w" desc:"working directory containing 'go.mod'. All non-absolute paths are relative to this directory"`
	TmpDir     string `flag:"tmp-dir" desc:"temporary directory."`
	OutputDir  string `flag:"output,o" desc:"output directory. All non-absolute paths for output are relative to this directory"`
	Verbose    bool   `flag:"debug" desc:"show debug information"`
}

func (Global) AbsPath

func (g Global) AbsPath(base, path string) string

type GoCmdOptions

type GoCmdOptions func(goCmd *string)

func GoCmdModFile

func GoCmdModFile(modFile string) GoCmdOptions

type GoMod

type GoMod struct {
	Module  Module
	Go      string
	Require []Require
	Exclude []Module
	Replace []Replace
	Retract []Retract
}

func GetGoMod

func GetGoMod(ctx context.Context, opts ...GoCmdOptions) (*GoMod, error)

type GoModule

type GoModule struct {
	Path      string         // module path
	Version   string         // module version
	Versions  []string       // available module versions (with -versions)
	Replace   *GoModule      // replaced by this module
	Time      *time.Time     // time version was created
	Update    *GoModule      // available update, if any (with -u)
	Main      bool           // is this the main module?
	Indirect  bool           // is this module only an indirect dependency of main module?
	Dir       string         // directory holding files for this module, if any
	GoMod     string         // path to go.mod file used when loading this module, if any
	GoVersion string         // go version used in module
	Retracted string         // retraction information, if any (with -retracted or -u)
	Error     *GoModuleError // error loading module
}

func FindModule

func FindModule(ctx context.Context, opts []GoCmdOptions, modules ...string) ([]*GoModule, error)

func ResolveTargetModule

func ResolveTargetModule(ctx context.Context) *GoModule

type GoModuleError

type GoModuleError struct {
	Err string // the error itself
}

type GoPackage

type GoPackage struct {
	Dir           string    // directory containing package sources
	ImportPath    string    // import path of package in dir
	ImportComment string    // path in import comment on package statement
	Name          string    // package name
	Doc           string    // package documentation string
	Target        string    // install path
	Shlib         string    // the shared library that contains this package (only set when -linkshared)
	Goroot        bool      // is this package in the Go root?
	Standard      bool      // is this package part of the standard Go library?
	Stale         bool      // would 'go install' do anything for this package?
	StaleReason   string    // explanation for Stale==true
	Root          string    // Go root or Go path dir containing this package
	ConflictDir   string    // this directory shadows Dir in $GOPATH
	BinaryOnly    bool      // binary-only package (no longer supported)
	ForTest       string    // package is only for use in named test
	Export        string    // file containing export data (when using -export)
	BuildID       string    // build ID of the compiled package (when using -export)
	Module        *GoModule // info about package's containing module, if any (can be nil)
	Match         []string  // command-line patterns matching this package
	DepOnly       bool      // package is only a dependency, not explicitly listed

	// Source files
	GoFiles           []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
	CgoFiles          []string // .go source files that import "C"
	CompiledGoFiles   []string // .go files presented to compiler (when using -compiled)
	IgnoredGoFiles    []string // .go source files ignored due to build constraints
	IgnoredOtherFiles []string // non-.go source files ignored due to build constraints
	CFiles            []string // .c source files
	CXXFiles          []string // .cc, .cxx and .cpp source files
	MFiles            []string // .m source files
	HFiles            []string // .h, .hh, .hpp and .hxx source files
	FFiles            []string // .f, .F, .for and .f90 Fortran source files
	SFiles            []string // .s source files
	SwigFiles         []string // .swig files
	SwigCXXFiles      []string // .swigcxx files
	SysoFiles         []string // .syso object files to add to archive
	TestGoFiles       []string // _test.go files in package
	XTestGoFiles      []string // _test.go files outside package

	// Embedded files
	EmbedPatterns      []string // //go:embed patterns
	EmbedFiles         []string // files matched by EmbedPatterns
	TestEmbedPatterns  []string // //go:embed patterns in TestGoFiles
	TestEmbedFiles     []string // files matched by TestEmbedPatterns
	XTestEmbedPatterns []string // //go:embed patterns in XTestGoFiles
	XTestEmbedFiles    []string // files matched by XTestEmbedPatterns

	// Cgo directives
	CgoCFLAGS    []string // cgo: flags for C compiler
	CgoCPPFLAGS  []string // cgo: flags for C preprocessor
	CgoCXXFLAGS  []string // cgo: flags for C++ compiler
	CgoFFLAGS    []string // cgo: flags for Fortran compiler
	CgoLDFLAGS   []string // cgo: flags for linker
	CgoPkgConfig []string // cgo: pkg-config names

	// Dependency information
	Imports      []string          // import paths used by this package
	ImportMap    map[string]string // map from source import to ImportPath (identity entries omitted)
	Deps         []string          // all (recursively) imported dependencies
	TestImports  []string          // imports from TestGoFiles
	XTestImports []string          // imports from XTestGoFiles

	// Error information
	Incomplete bool              // this package or a dependency has an error
	Error      *GoPackageError   // error loading package
	DepsErrors []*GoPackageError // errors loading dependencies
}

type GoPackageError

type GoPackageError struct {
	ImportStack []string // shortest path from package named on command line to this one
	Pos         string   // position of error (if present, file:line:col)
	Err         string   // the error itself
}

type Matcher

type Matcher[T any] interface {
	Matches(T) (bool, error)
	MatchesWithContext(context.Context, T) (bool, error)
}

type Module

type Module struct {
	Path    string
	Version string
}

type NegateMatcher

type NegateMatcher[T any] struct {
	Matcher[T]
}

NegateMatcher apply ! operator to embedded Matcher

func (NegateMatcher[T]) And

func (m NegateMatcher[T]) And(matchers ...Matcher[T]) ChainableMatcher[T]

func (NegateMatcher[T]) Matches

func (m NegateMatcher[T]) Matches(i T) (ret bool, err error)

func (NegateMatcher[T]) MatchesWithContext

func (m NegateMatcher[T]) MatchesWithContext(c context.Context, i T) (ret bool, err error)

func (NegateMatcher[T]) Or

func (m NegateMatcher[T]) Or(matchers ...Matcher[T]) ChainableMatcher[T]

func (NegateMatcher[T]) String

func (m NegateMatcher[T]) String() string

type NoopMatcher

type NoopMatcher[T any] bool

NoopMatcher matches stuff literally

func (NoopMatcher[T]) And

func (m NoopMatcher[T]) And(matchers ...Matcher[T]) ChainableMatcher[T]

func (NoopMatcher[T]) Matches

func (m NoopMatcher[T]) Matches(_ T) (bool, error)

func (NoopMatcher[T]) MatchesWithContext

func (m NoopMatcher[T]) MatchesWithContext(context.Context, T) (bool, error)

func (NoopMatcher[T]) Or

func (m NoopMatcher[T]) Or(matchers ...Matcher[T]) ChainableMatcher[T]

func (NoopMatcher[T]) String

func (m NoopMatcher[T]) String() string

type OrMatcher

type OrMatcher[T any] []Matcher[T]

OrMatcher chain a list of matchers with OR operator

func (OrMatcher[T]) And

func (m OrMatcher[T]) And(matchers ...Matcher[T]) ChainableMatcher[T]

func (OrMatcher[T]) Matches

func (m OrMatcher[T]) Matches(i T) (ret bool, err error)

func (OrMatcher[T]) MatchesWithContext

func (m OrMatcher[T]) MatchesWithContext(c context.Context, i T) (ret bool, err error)

func (OrMatcher[T]) Or

func (m OrMatcher[T]) Or(matchers ...Matcher[T]) ChainableMatcher[T]

func (OrMatcher[T]) String

func (m OrMatcher[T]) String() string

type Replace

type Replace struct {
	Old Module
	New Module
}

func DropInvalidReplace

func DropInvalidReplace(ctx context.Context, opts ...GoCmdOptions) (ret []*Replace, err error)

DropInvalidReplace go through the go.mod file and find replace directives that point to a non-existing local directory

type Require

type Require struct {
	Path     string
	Version  string
	Indirect bool
}

type Retract

type Retract struct {
	Low       string
	High      string
	Rationale string
}

type RunE

type RunE func(cmd *cobra.Command, args []string) error

func EnsureDir

func EnsureDir(dirPath *string, base string, cleanIfExist bool, desc string) RunE

func EnsureGlobalDirectories

func EnsureGlobalDirectories() RunE

func MergeRunE

func MergeRunE(funcs ...RunE) RunE

func PrintEnvironment

func PrintEnvironment() RunE

type ShCmdOption

type ShCmdOption struct {
	Cmds    []string
	Dir     string
	Env     []string
	ShowCmd bool
	Stdin   io.Reader
	Stdout  io.Writer
	Stderr  io.Writer
}

type ShCmdOptions

type ShCmdOptions func(opt *ShCmdOption)

ShCmdOptions is the options for the RunShellCommands func

func ShellCmd

func ShellCmd(cmds ...string) ShCmdOptions

ShellCmd add shell commends

func ShellDir

func ShellDir(dir string) ShCmdOptions

ShellDir set working dir of to-be-executed commands

func ShellEnv

func ShellEnv(env ...string) ShCmdOptions

ShellEnv set additional environment variable in format of "key=value"

func ShellShowCmd

func ShellShowCmd(show bool) ShCmdOptions

ShellShowCmd toggle display command in log

func ShellStdErr

func ShellStdErr(w io.Writer) ShCmdOptions

ShellStdErr toggle display command in log

func ShellStdIn

func ShellStdIn(r io.Reader) ShCmdOptions

ShellStdIn toggle display command in log

func ShellStdOut

func ShellStdOut(w io.Writer) ShCmdOptions

ShellStdOut toggle display command in log

func ShellUseOutputDir

func ShellUseOutputDir() ShCmdOptions

ShellUseOutputDir set working dir of to-be-executed commands to GlobalArgs.OutputDir

func ShellUseTmpDir

func ShellUseTmpDir() ShCmdOptions

ShellUseTmpDir set working dir of to-be-executed commands to GlobalArgs.TmpDir

func ShellUseWorkingDir

func ShellUseWorkingDir() ShCmdOptions

ShellUseWorkingDir set working dir of to-be-executed commands to GlobalArgs.WorkingDir

type StringMatcher

type StringMatcher interface {
	ChainableMatcher[string]
}

StringMatcher is a typed ChainableMatcher that accept String

func AnyNonEmptyString

func AnyNonEmptyString() StringMatcher

func WithPathPattern

func WithPathPattern(pattern string) StringMatcher

func WithPrefix

func WithPrefix(prefix string, caseInsensitive bool) StringMatcher

func WithRegex

func WithRegex(regex string) StringMatcher

func WithRegexPattern

func WithRegexPattern(regex *regexp.Regexp) StringMatcher

func WithString

func WithString(expected string, caseInsensitive bool) StringMatcher

func WithSubString

func WithSubString(substr string, caseInsensitive bool) StringMatcher

func WithSuffix

func WithSuffix(suffix string, caseInsensitive bool) StringMatcher

type TemplateOption

type TemplateOption struct {
	FS         embed.FS
	TmplName   string      // template name
	Output     string      // output path
	OutputPerm os.FileMode // output file permission when create
	Overwrite  bool        // should overwrite if output file already exists
	Model      interface{}
	Customizer func(*template.Template)
	CommonTmpl string
}

Jump to

Keyboard shortcuts

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