本文整理汇总了Golang中github.com/codegangsta/cli.Context.GlobalStringSlice方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.GlobalStringSlice方法的具体用法?Golang Context.GlobalStringSlice怎么用?Golang Context.GlobalStringSlice使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/codegangsta/cli.Context
的用法示例。
在下文中一共展示了Context.GlobalStringSlice方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: processGlobalFlags
func processGlobalFlags(c *cli.Context) time.Duration {
var network string
if c.GlobalBool("tcp") {
network = "tcp"
} else {
network = "udp"
}
client, err := raidman.Dial(network, fmt.Sprintf("%s:%d", c.GlobalString("host"), c.GlobalInt("port")))
if c.GlobalString("event-host") == "nil" {
log.Panic("Failed to automatically get the hostname. Please specify it with --host")
}
if err != nil {
log.Panicf("Failed to connect to the riemann host because %s", err)
}
attribute, err := processAttributes(c.GlobalStringSlice("attribute"))
if err != nil {
log.Panic(err)
}
eventTemplate := raidman.Event{
Ttl: float32(c.GlobalDuration("ttl").Seconds()),
Tags: c.GlobalStringSlice("tags"),
Host: c.GlobalString("event-host"),
Attributes: attribute,
}
riemannSend = func(url, method string, duration float64) {
event := eventTemplate
event.Service = fmt.Sprintf("%s %s", url, method)
event.Time = time.Now().Unix()
event.Metric = duration
client.Send(&event)
}
return c.GlobalDuration("interval")
}
示例2: Populate
// Populate updates the specified project context based on command line arguments and subcommands.
func Populate(context *project.Context, c *cli.Context) {
context.ComposeFiles = c.GlobalStringSlice("file")
if len(context.ComposeFiles) == 0 {
context.ComposeFiles = []string{"docker-compose.yml"}
if _, err := os.Stat("docker-compose.override.yml"); err == nil {
context.ComposeFiles = append(context.ComposeFiles, "docker-compose.override.yml")
}
}
context.ProjectName = c.GlobalString("project-name")
if c.Command.Name == "logs" {
context.Log = true
context.FollowLog = c.Bool("follow")
} else if c.Command.Name == "up" || c.Command.Name == "create" {
context.Log = !c.Bool("d")
context.NoRecreate = c.Bool("no-recreate")
context.ForceRecreate = c.Bool("force-recreate")
context.NoBuild = c.Bool("no-build")
} else if c.Command.Name == "stop" || c.Command.Name == "restart" || c.Command.Name == "scale" {
context.Timeout = uint(c.Int("timeout"))
} else if c.Command.Name == "kill" {
context.Signal = c.String("signal")
} else if c.Command.Name == "rm" {
context.Volume = c.Bool("v")
} else if c.Command.Name == "build" {
context.NoCache = c.Bool("no-cache")
}
}
示例3: cmdReorderTemplateScripts
func cmdReorderTemplateScripts(c *cli.Context) {
utils.FlagsRequired(c, []string{"template_id", "type", "script_ids"})
webservice, err := webservice.NewWebService()
utils.CheckError(err)
v := make(map[string]interface{})
v["type"] = c.String("type")
v["script_ids"] = c.GlobalStringSlice("script_ids")
jsonBytes, err := json.Marshal(v)
utils.CheckError(err)
err, res, code := webservice.Put(fmt.Sprintf("/v1/blueprint/templates/%s/scripts/reorder", c.String("template_id")), jsonBytes)
utils.CheckError(err)
utils.CheckReturnCode(code, res)
var templateScripts []TemplateScript
err = json.Unmarshal(res, &templateScripts)
utils.CheckError(err)
w := tabwriter.NewWriter(os.Stdout, 15, 1, 3, ' ', 0)
fmt.Fprintln(w, "ID\tTYPE\tEXECUTION ORDER\tTEMPLATE ID\tSCRIPT ID\tPARAMETER VALUES\r")
for _, templateScript := range templateScripts {
fmt.Fprintf(w, "%s\t%s\t%d\t%s\t%s\t%s\n", templateScript.Id, templateScript.Type, templateScript.Execution_Order, templateScript.Template_Id, templateScript.Script_Id, templateScript.Parameter_Values)
}
w.Flush()
}
示例4: renew
func renew(c *cli.Context) {
conf, _, client := setup(c)
if len(c.GlobalStringSlice("domains")) <= 0 {
logger().Fatal("Please specify at least one domain.")
}
domain := c.GlobalStringSlice("domains")[0]
// load the cert resource from files.
// We store the certificate, private key and metadata in different files
// as web servers would not be able to work with a combined file.
certPath := path.Join(conf.CertPath(), domain+".crt")
privPath := path.Join(conf.CertPath(), domain+".key")
metaPath := path.Join(conf.CertPath(), domain+".json")
certBytes, err := ioutil.ReadFile(certPath)
if err != nil {
logger().Fatalf("Error while loading the certificate for domain %s\n\t%s", domain, err.Error())
}
if c.IsSet("days") {
expTime, err := acme.GetPEMCertExpiration(certBytes)
if err != nil {
logger().Printf("Could not get Certification expiration for domain %s", domain)
}
if int(expTime.Sub(time.Now()).Hours()/24.0) > c.Int("days") {
return
}
}
metaBytes, err := ioutil.ReadFile(metaPath)
if err != nil {
logger().Fatalf("Error while loading the meta data for domain %s\n\t%s", domain, err.Error())
}
var certRes acme.CertificateResource
err = json.Unmarshal(metaBytes, &certRes)
if err != nil {
logger().Fatalf("Error while marshalling the meta data for domain %s\n\t%s", domain, err.Error())
}
if c.Bool("reuse-key") {
keyBytes, err := ioutil.ReadFile(privPath)
if err != nil {
logger().Fatalf("Error while loading the private key for domain %s\n\t%s", domain, err.Error())
}
certRes.PrivateKey = keyBytes
}
certRes.Certificate = certBytes
newCert, err := client.RenewCertificate(certRes, true)
if err != nil {
logger().Fatalf("%s", err.Error())
}
saveCertRes(newCert, conf)
}
示例5: revoke
func revoke(c *cli.Context) {
err := checkFolder(c.GlobalString("path"))
if err != nil {
logger().Fatalf("Cound not check/create path: %v", err)
}
conf := NewConfiguration(c)
if !c.GlobalIsSet("email") {
logger().Fatal("You have to pass an account (email address) to the program using --email or -m")
}
acc := NewAccount(c.GlobalString("email"), conf)
client := acme.NewClient(c.GlobalString("server"), acc, conf.RsaBits(), conf.OptPort())
err = checkFolder(conf.CertPath())
if err != nil {
logger().Fatalf("Cound not check/create path: %v", err)
}
for _, domain := range c.GlobalStringSlice("domains") {
logger().Printf("Trying to revoke certificate for domain %s", domain)
certPath := path.Join(conf.CertPath(), domain+".crt")
certBytes, err := ioutil.ReadFile(certPath)
err = client.RevokeCertificate(certBytes)
if err != nil {
logger().Printf("Error while revoking the certificate for domain %s\n\t%v", domain, err)
} else {
logger().Print("Certificate was revoked.")
}
}
}
示例6: setup
func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) {
err := checkFolder(c.GlobalString("path"))
if err != nil {
logger().Fatalf("Cound not check/create path: %s", err.Error())
}
conf := NewConfiguration(c)
if len(c.GlobalString("email")) == 0 {
logger().Fatal("You have to pass an account (email address) to the program using --email or -m")
}
//TODO: move to account struct? Currently MUST pass email.
acc := NewAccount(c.GlobalString("email"), conf)
client, err := acme.NewClient(c.GlobalString("server"), acc, conf.RsaBits())
if err != nil {
logger().Fatalf("Could not create client: %s", err.Error())
}
if len(c.GlobalStringSlice("exclude")) > 0 {
client.ExcludeChallenges(conf.ExcludedSolvers())
}
if c.GlobalIsSet("http") {
client.SetHTTPAddress(c.GlobalString("http"))
}
if c.GlobalIsSet("tls") {
client.SetTLSAddress(c.GlobalString("tls"))
}
return conf, acc, client
}
示例7: setIsvcsEnv
func setIsvcsEnv(ctx *cli.Context) error {
for _, val := range ctx.GlobalStringSlice("isvcs-env") {
if err := isvcs.AddEnv(val); err != nil {
return err
}
}
return nil
}
示例8: cmdServiceShell
// serviced service shell [--saveas SAVEAS] [--interactive, -i] SERVICEID [COMMAND]
func (c *ServicedCli) cmdServiceShell(ctx *cli.Context) error {
args := ctx.Args()
if len(args) < 1 {
if !ctx.Bool("help") {
fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
}
cli.ShowSubcommandHelp(ctx)
return c.exit(1)
}
var (
command string
argv []string
isTTY bool
)
svc, err := c.searchForService(args[0])
if err != nil {
fmt.Fprintln(os.Stderr, err)
return c.exit(1)
}
if len(args) < 2 {
command = "/bin/bash"
isTTY = true
} else {
command = args[1]
isTTY = ctx.GlobalBool("interactive")
}
if len(args) > 2 {
argv = args[2:]
}
config := api.ShellConfig{
ServiceID: svc.ID,
Command: command,
Args: argv,
SaveAs: ctx.GlobalString("saveas"),
IsTTY: isTTY,
Mounts: ctx.GlobalStringSlice("mount"),
ServicedEndpoint: fmt.Sprintf("localhost:%s", api.GetOptionsRPCPort()),
}
if err := c.driver.StartShell(config); err != nil {
fmt.Fprintln(os.Stderr, err)
if exitErr, ok := err.(*exec.ExitError); ok {
if exitErr != nil && exitErr.ProcessState != nil && exitErr.ProcessState.Sys() != nil {
if status, ok := exitErr.ProcessState.Sys().(syscall.WaitStatus); ok {
return c.exit(status.ExitStatus())
}
}
}
return c.exit(1)
} else {
return c.exit(0)
}
}
示例9: cmdServiceRun
// serviced service run SERVICEID [COMMAND [ARGS ...]]
func (c *ServicedCli) cmdServiceRun(ctx *cli.Context) error {
args := ctx.Args()
if len(args) < 1 {
if !ctx.Bool("help") {
fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
}
cli.ShowSubcommandHelp(ctx)
return c.exit(1)
}
if len(args) < 2 {
for _, s := range c.serviceRuns(args[0]) {
fmt.Println(s)
}
fmt.Fprintf(os.Stderr, "serviced service run")
return c.exit(1)
}
var (
command string
argv []string
)
svc, err := c.searchForService(args[0])
if err != nil {
fmt.Fprintln(os.Stderr, err)
return c.exit(1)
}
command = args[1]
if len(args) > 2 {
argv = args[2:]
}
config := api.ShellConfig{
ServiceID: svc.ID,
Command: command,
Username: ctx.GlobalString("user"),
Args: argv,
SaveAs: dfs.NewLabel(svc.ID),
IsTTY: ctx.GlobalBool("interactive"),
Mounts: ctx.GlobalStringSlice("mount"),
ServicedEndpoint: fmt.Sprintf("localhost:%s", api.GetOptionsRPCPort()),
LogToStderr: ctx.GlobalBool("logtostderr"),
}
config.LogStash.Enable = ctx.GlobalBool("logstash")
config.LogStash.SettleTime = ctx.GlobalString("logstash-settle-time")
config.LogStash.IdleFlushTime = ctx.GlobalString("logstash-idle-flush-time")
if err := c.driver.RunShell(config); err != nil {
fmt.Fprintln(os.Stderr, err)
return c.exit(1)
}
return c.exit(0)
}
示例10: parseEnvironment
func parseEnvironment(context *cli.Context) (map[string]string, error) {
env := make(map[string]string)
for _, v := range context.GlobalStringSlice("env") {
parts := strings.SplitN(v, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid env format %s", v)
}
env[parts[0]] = parts[1]
}
return env, nil
}
示例11: AppendResource
func AppendResource(fileName, resourceName, key string, c *cli.Context) error {
ignoreList := c.GlobalStringSlice("exclude-attr")
var configJSON ConfigJSON
if _, err := os.Stat(fileName); err == nil {
configJSON = ReadJSON(fileName)
} else {
configJSON = *NewConfigJSON()
}
sys := system.New(c)
// Need to figure out a good way to refactor this
switch resourceName {
case "Addr":
res, _ := configJSON.Addrs.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "Command":
res, _ := configJSON.Commands.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "DNS":
res, _ := configJSON.DNS.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "File":
res, _ := configJSON.Files.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "Group":
res, _ := configJSON.Groups.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "Package":
res, _ := configJSON.Packages.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "Port":
res, _ := configJSON.Ports.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "Process":
res, _ := configJSON.Processes.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "Service":
res, _ := configJSON.Services.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "User":
res, _ := configJSON.Users.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
case "Gossfile":
res, _ := configJSON.Gossfiles.AppendSysResource(key, sys, ignoreList)
resourcePrint(fileName, res)
}
WriteJSON(fileName, configJSON)
return nil
}
示例12: showVersions
func showVersions(ctx *cli.Context) (bool, error) {
if len(ctx.Args()) != 0 {
return true, errorInvalidArgCount(len(ctx.Args()), 0, ctx.Args())
}
e := etcd2.New(ctx.GlobalString("prefix"), ctx.GlobalStringSlice("etcd"))
fmt.Printf("Current local schema version: %d\n", e.CurrentSchemaVersion())
fmt.Printf("Newest available schema version: %d\n", latestMigrationVersion)
return false, nil
}
示例13: run
func run(c *cli.Context) error {
conf, acc, client := setup(c)
if acc.Registration == nil {
reg, err := client.Register()
if err != nil {
logger().Fatalf("Could not complete registration\n\t%s", err.Error())
}
acc.Registration = reg
acc.Save()
logger().Print("!!!! HEADS UP !!!!")
logger().Printf(`
Your account credentials have been saved in your Let's Encrypt
configuration directory at "%s".
You should make a secure backup of this folder now. This
configuration directory will also contain certificates and
private keys obtained from Let's Encrypt so making regular
backups of this folder is ideal.`, conf.AccountPath(c.GlobalString("email")))
}
// If the agreement URL is empty, the account still needs to accept the LE TOS.
if acc.Registration.Body.Agreement == "" {
handleTOS(c, client, acc)
}
if len(c.GlobalStringSlice("domains")) == 0 {
logger().Fatal("Please specify --domains or -d")
}
cert, failures := client.ObtainCertificate(c.GlobalStringSlice("domains"), !c.Bool("no-bundle"), nil)
if len(failures) > 0 {
for k, v := range failures {
logger().Printf("[%s] Could not obtain certificates\n\t%s", k, v.Error())
}
// Make sure to return a non-zero exit code if ObtainSANCertificate
// returned at least one error. Due to us not returning partial
// certificate we can just exit here instead of at the end.
os.Exit(1)
}
err := checkFolder(conf.CertPath())
if err != nil {
logger().Fatalf("Could not check/create path: %s", err.Error())
}
saveCertRes(cert, conf)
return nil
}
示例14: config
func config(context *cli.Context) factory.Config {
configPath := context.GlobalString("config")
var config factory.Config
var err error
if configPath == "" {
config, err = factory.Parse([]byte("{}"))
} else {
config, err = factory.LoadFromFile(configPath)
}
if err != nil {
cli.ShowAppHelp(context)
panic(err)
}
schemeType := context.GlobalString("scheme")
if schemeType != "" {
config.SchemeType = schemeType
}
writerType := context.GlobalString("writer")
if writerType != "" {
config.WriterType = writerType
}
readerType := context.GlobalString("reader")
if readerType != "" {
config.ReaderType = readerType
}
for _, assignment := range context.GlobalStringSlice("config-string") {
keyValue, err := parseAssignment(assignment)
if err != nil {
panic(err)
}
config.Additional.SetString(keyValue[0], keyValue[1])
}
for _, assignment := range context.GlobalStringSlice("config-int") {
keyValue, err := parseAssignment(assignment)
if err != nil {
panic(err)
}
value, err := strconv.Atoi(keyValue[1])
if err != nil {
panic(err)
}
config.Additional.SetInt(keyValue[0], value)
}
return config
}
示例15: processClientTarget
func processClientTarget(c *cli.Context) (isUnix bool, target string, err error) {
for _, v := range c.GlobalStringSlice(`host`) {
if strings.HasPrefix(v, "tcp://") {
isUnix = false
target = strings.TrimPrefix(v, "tcp://")
err = nil
}
if strings.HasPrefix(v, "unix://") {
isUnix = true
target = strings.TrimPrefix(v, "unix://")
err = nil
}
}
return
}