本文整理汇总了Golang中github.com/spf13/cobra.Command.Execute方法的典型用法代码示例。如果您正苦于以下问题:Golang Command.Execute方法的具体用法?Golang Command.Execute怎么用?Golang Command.Execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/spf13/cobra.Command
的用法示例。
在下文中一共展示了Command.Execute方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
app := cobra.Command{
Use: "s3sync <from> <to>",
Short: "Sync files from <from> to <to>",
Run: execSync,
PreRun: func(cmd *cobra.Command, args []string) {
if cfg.PrintVersion {
fmt.Printf("s3sync %s\n", version)
os.Exit(0)
}
},
}
app.Flags().BoolVarP(&cfg.Public, "public", "P", false, "Make files public when syncing to S3")
app.Flags().BoolVarP(&cfg.Delete, "delete", "d", false, "Delete files on remote not existing on local")
app.Flags().BoolVar(&cfg.PrintVersion, "version", false, "Print version and quit")
app.Flags().IntVar(&cfg.MaxThreads, "max-threads", 10, "Use max N parallel threads for file sync")
app.Flags().UintVar(&cfg.logLevel, "loglevel", 2, "Amount of log output (0 = Error only, 3 = Debug)")
app.ParseFlags(os.Args[1:])
stdout = logger.New(logger.LogLevel(cfg.logLevel))
app.Execute()
}
示例2: main
func main() {
server := true
configFile := ""
command := cobra.Command{
Use: "butter",
Short: "butter makes the breads silky smooth",
Long: `Butter is a solid dairy product made by churning fresh or fermented cream or milk, to separate the butterfat from the buttermilk. It is generally used as a spread on plain or toasted bread products and a condiment on cooked vegetables, as well as in cooking, such as baking, sauce making, and pan frying. Butter consists of butterfat, milk proteins and water.`,
Run: func(ccmd *cobra.Command, args []string) {
if !server {
ccmd.HelpFunc()(ccmd, args)
return
}
if configFile != "" {
config.Parse(configFile)
}
serverStart()
},
}
config.AddFlags(&command)
command.Flags().BoolVarP(&server, "server", "s", false, "Run as server")
command.Flags().StringVarP(&configFile, "configFile", "", "", "[server] config file location")
// when we create a cli i will add it here
// cli.AddCli(command)
command.Execute()
}
示例3: main
func main() {
var rootCmd *cobra.Command
rootCmd = &cobra.Command{
Use: "lvbackup",
Short: "lvbackup is a tool to backup and restore LVM2 thinly-provisioned volumes",
Run: func(cmd *cobra.Command, args []string) {
rootCmd.Usage()
os.Exit(-1)
},
}
setupSendCommand(rootCmd)
setupRecvCommand(rootCmd)
setupInfoCommand(rootCmd)
setupMergeCommand(rootCmd)
if err := rootCmd.Execute(); err != nil {
os.Exit(-1)
}
os.Exit(0)
}
示例4: main
func main() {
var (
nodes string
taskList string
tasks []string
confPath string
confData *lib.RunConfig
cliVars string
cliData map[string]interface{}
verbose bool
taskDir string
tmplDir string
etcdClient *etcd.Client
base *cobra.Command
err error
)
base = &cobra.Command{
Use: "atom",
Short: "atom",
Long: "atom",
Run: func(cmd *cobra.Command, args []string) {
confData, err = lib.ParseAtomConfig(confPath)
if err != nil {
log.Printf("Config read error: %s", err)
if (taskDir == "") || (tmplDir == "") {
return
} else {
confData = &lib.RunConfig{
TaskDir: taskDir,
TmplDir: tmplDir,
Verbose: verbose,
}
}
}
if err := yaml.Unmarshal([]byte(cliVars), &cliData); err != nil {
log.Printf("Error: %s", err)
}
if nodes == "" {
etcdClient = nil
} else {
etcdClient = etcd.NewClient([]string{nodes})
etcdClient.SetDialTimeout(time.Duration(3) * time.Second)
if !etcdClient.SyncCluster() {
log.Fatal("Couldn't sync with etcd cluster.")
}
etcdClient.SetConsistency(etcd.STRONG_CONSISTENCY)
}
for _, name := range strings.Split(taskList, ",") {
if name == "" {
continue
}
tasks = append(tasks, name)
}
if len(tasks) <= 0 {
tasks = nil
}
atom := lib.NewAtom(confData, &cliData, etcdClient)
atom.Run(tasks...)
},
}
base.Flags().StringVarP(&taskList, "run", "r", "", "tasks to run")
base.PersistentFlags().StringVarP(&cliVars, "data", "d", "", "cli data (string, yaml)")
base.PersistentFlags().StringVarP(&confPath, "conf", "c", "/etc/atom/atom.yml", "atom.yml")
base.PersistentFlags().StringVarP(&nodes, "nodes", "n", "", "etcd nodes")
base.PersistentFlags().StringVarP(&taskDir, "task", "t", "", "task directory")
base.PersistentFlags().StringVarP(&tmplDir, "template", "m", "", "template directory")
base.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose")
base.Execute()
}
示例5:
It("registers the required flags", func() {
f := root.Flags().Lookup("pkg")
Ω(f).ShouldNot(BeNil())
})
})
Context("with command line flags", func() {
var root *cobra.Command
const flagVal = "testme"
var args []string
BeforeEach(func() {
root = &cobra.Command{Use: "testCmd"}
args = []string{os.Args[0], testCmd, "-o" + flagVal, "-d=design", "--pkg=dummy"}
})
JustBeforeEach(func() {
codegen.RegisterFlags(root)
appCmd.RegisterFlags(root)
os.Args = args
})
It("parses the default flags", func() {
err := root.Execute()
Ω(err).ShouldNot(HaveOccurred())
Ω(codegen.OutputDir).Should(Equal(flagVal))
})
})
})
示例6: main
func main() {
// some parts of apps.go are unable to handle
// interrupts, this logic ensures we exit on system interrupts
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
go func() {
<-interrupt
os.Exit(1)
}()
e := env{
Root: os.Getenv("PARSE_ROOT"),
Server: os.Getenv("PARSE_SERVER"),
ErrorStack: os.Getenv("PARSE_ERROR_STACK") == "1",
ParserEmail: os.Getenv("PARSER_EMAIL"),
Out: os.Stdout,
Err: os.Stderr,
In: os.Stdin,
Exit: os.Exit,
Clock: clock.New(),
}
if e.Root == "" {
cur, err := os.Getwd()
if err != nil {
fmt.Fprintf(e.Err, "Failed to get current directory:\n%s\n", err)
os.Exit(1)
}
root := getProjectRoot(&e, cur)
if isProjectDir(root) {
e.Root = root
config, err := configFromDir(root)
if err != nil {
fmt.Fprintln(e.Err, err)
os.Exit(1)
}
e.Type = config.getProjectConfig().Type
if e.ParserEmail == "" {
e.ParserEmail = config.getProjectConfig().ParserEmail
}
} else {
e.Type = legacyParseFormat
e.Root = getLegacyProjectRoot(&e, cur)
}
}
if e.Type != legacyParseFormat && e.Type != parseFormat {
fmt.Fprintf(e.Err, "Unknown project type %d.\n", e.Type)
os.Exit(1)
}
if e.Server == "" {
e.Server = defaultBaseURL
}
apiClient, err := newParseAPIClient(&e)
if err != nil {
fmt.Fprintln(e.Err, err)
os.Exit(1)
}
e.ParseAPIClient = apiClient
var (
rootCmd *cobra.Command
command []string
)
switch e.Type {
case legacyParseFormat, parseFormat:
command, rootCmd = parseRootCmd(&e)
}
if len(command) == 0 || command[0] != "update" {
message, err := checkIfSupported(&e, version, command...)
if err != nil {
fmt.Fprintln(e.Err, err)
os.Exit(1)
}
if message != "" {
fmt.Fprintln(e.Err, message)
}
}
if err := rootCmd.Execute(); err != nil {
// Error is already printed in Execute()
os.Exit(1)
}
}
示例7: main
func main() {
// Do not route special commands into cobra logic
if len(os.Args) > 1 {
switch os.Args[1] {
case "lockagent":
runLockagent()
os.Exit(0)
}
}
app := cobra.Command{
Use: "awsenv",
Short: "manage different AWS envs on your system",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if cfg.Debug {
log.SetLevel(log.DebugLevel)
}
// Load the password if command is not unlock
if !strings.Contains("unlock version", cmd.Name()) {
if len(cfg.Password) > 0 {
// If a password was provided, use that one
password = security.LoadDatabasePasswordFromInput(cfg.Password)
} else {
// If the token file exists a lockagent should be running and we can use
// the password stored in that logagent
filename := fmt.Sprintf("%s.lock", cfg.Database)
if _, err := os.Stat(filename); os.IsNotExist(err) {
log.Errorf("No password is available. Use 'unlock' or provide --password.")
os.Exit(1)
}
pwd, err := security.LoadDatabasePasswordFromLockagent(filename)
if err != nil {
log.Errorf("Could not load password from lock-file:\n%s", err)
os.Exit(1)
}
password = pwd
}
// As we got a password now try to load the database with that password or
// Create a new one if the encrypted storage file is not available
if _, err := os.Stat(cfg.Database); os.IsNotExist(err) {
awsCredentials = credentials.New(cfg.Database, password)
} else {
s, err := credentials.FromFile(cfg.Database, password)
if err != nil {
log.Error("Unable to read credential database")
os.Exit(1)
}
awsCredentials = s
}
}
},
}
app.PersistentFlags().StringVarP(&cfg.Password, "password", "p", os.Getenv("AWSENV_PASSWORD"), "password to en/decrypt the database")
app.PersistentFlags().StringVar(&cfg.Database, "database", strings.Join([]string{os.Getenv("HOME"), ".config/awsenv"}, "/"), "storage location of the database")
app.PersistentFlags().BoolVar(&cfg.Debug, "debug", false, "print debug information")
app.AddCommand(
getCmdAdd(),
getCmdConsole(),
getCmdDelete(),
getCmdGet(),
getCmdList(),
getCmdLock(),
getCmdShell(),
getCmdPrompt(),
getCmdUnlock(),
getCmdVersion(),
)
_ = app.Execute()
}