func (cmd *unbindFromRunningGroup) Run(context *cli.Context) { name := context.Args()[0] securityGroup, err := cmd.securityGroupRepo.Read(name) switch (err).(type) { case nil: case *errors.ModelNotFoundError: cmd.ui.Ok() cmd.ui.Warn(T("Security group {{.security_group}} {{.error_message}}", map[string]interface{}{ "security_group": terminal.EntityNameColor(name), "error_message": terminal.WarningColor(T("does not exist.")), })) return default: cmd.ui.Failed(err.Error()) } cmd.ui.Say(T("Unbinding security group {{.security_group}} from defaults for running as {{.username}}", map[string]interface{}{ "security_group": terminal.EntityNameColor(securityGroup.Name), "username": terminal.EntityNameColor(cmd.configRepo.Username()), })) err = cmd.runningGroupRepo.UnbindFromRunningSet(securityGroup.Guid) if err != nil { cmd.ui.Failed(err.Error()) } cmd.ui.Ok() cmd.ui.Say("\n\n") cmd.ui.Say(T("TIP: Changes will not apply to existing running applications until they are restarted.")) }
func (cmd ListServiceBrokers) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) { if len(c.Args()) != 0 { cmd.ui.FailWithUsage(c) } reqs = append(reqs, requirementsFactory.NewLoginRequirement()) return }
func attach(ctx *cli.Context) { utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name)) var client comms.EthereumClient var err error if ctx.Args().Present() { client, err = comms.ClientFromEndpoint(ctx.Args().First(), codec.JSON) } else { cfg := comms.IpcConfig{ Endpoint: ctx.GlobalString(utils.IPCPathFlag.Name), } client, err = comms.NewIpcClient(cfg, codec.JSON) } if err != nil { utils.Fatalf("Unable to attach to geth node - %v", err) } repl := newLightweightJSRE( ctx.GlobalString(utils.JSpathFlag.Name), client, true, ) if ctx.GlobalString(utils.ExecFlag.Name) != "" { repl.batch(ctx.GlobalString(utils.ExecFlag.Name)) } else { repl.welcome() repl.interactive() } }
func logs(c *cli.Context) { bintrayDetails, err := createBintrayDetails(c, true) if err != nil { cliutils.Exit(cliutils.ExitCodeError, err.Error()) } if c.NArg() == 1 { packageDetails, err := utils.CreatePackageDetails(c.Args().Get(0)) cliutils.ExitOnErr(err) err = commands.LogsList(packageDetails, bintrayDetails) cliutils.ExitOnErr(err) } else if c.NArg() == 3 { if c.Args().Get(0) == "download" { packageDetails, err := utils.CreatePackageDetails(c.Args().Get(1)) if err != nil { cliutils.Exit(cliutils.ExitCodeError, err.Error()) } err = commands.DownloadLog(packageDetails, c.Args().Get(2), bintrayDetails) cliutils.ExitOnErr(err) } else { cliutils.Exit(cliutils.ExitCodeError, "Unkown argument "+c.Args().Get(0)+". "+cliutils.GetDocumentationMessage()) } } else { cliutils.Exit(cliutils.ExitCodeError, "Wrong number of arguments. "+cliutils.GetDocumentationMessage()) } }
func enable(c *cli.Context) { changed := false cfg, err := config.LoadConfig() if err != nil { log.Fatal(err) } for _, service := range c.Args() { if val, ok := cfg.Rancher.ServicesInclude[service]; !ok || !val { if strings.HasPrefix(service, "/") && !strings.HasPrefix(service, "/var/lib/rancher/conf") { log.Fatalf("ERROR: Service should be in path /var/lib/rancher/conf") } if _, err := compose.LoadServiceResource(service, true, cfg); err != nil { log.Fatalf("could not load service %s", service) } cfg.Rancher.ServicesInclude[service] = true changed = true } } if changed { if err := cfg.Set("rancher.services_include", cfg.Rancher.ServicesInclude); err != nil { log.Fatal(err) } } }
func (cmd CreateUserProvidedService) Run(c *cli.Context) { name := c.Args()[0] drainUrl := c.String("l") params := c.String("p") params = strings.Trim(params, `"`) paramsMap := make(map[string]interface{}) err := json.Unmarshal([]byte(params), ¶msMap) if err != nil && params != "" { paramsMap = cmd.mapValuesFromPrompt(params, paramsMap) } cmd.ui.Say(T("Creating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username()), })) apiErr := cmd.userProvidedServiceInstanceRepo.Create(name, drainUrl, paramsMap) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } cmd.ui.Ok() }
func (cmd *PluginInstall) GetRequirements(_ requirements.Factory, c *cli.Context) (req []requirements.Requirement, err error) { if len(c.Args()) != 1 { cmd.ui.FailWithUsage(c) } return }
func (cmd CreateBuildpack) createBuildpack(buildpackName string, c *cli.Context) (buildpack models.Buildpack, apiErr error) { position, err := strconv.Atoi(c.Args()[2]) if err != nil { apiErr = errors.NewWithFmt("Invalid position. %s", err.Error()) return } enabled := c.Bool("enable") disabled := c.Bool("disable") if enabled && disabled { apiErr = errors.New("Cannot specify both enabled and disabled.") return } var enableOption *bool = nil if enabled { enableOption = &enabled } if disabled { disabled = false enableOption = &disabled } buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil) return }
func runUpdate(c *cli.Context) { if c.IsSet("config") { setting.CustomConf = c.String("config") } cmd := os.Getenv("SSH_ORIGINAL_COMMAND") if cmd == "" { return } setup("update.log") args := c.Args() if len(args) != 3 { log.GitLogger.Fatal(2, "received less 3 parameters") } else if args[0] == "" { log.GitLogger.Fatal(2, "refName is empty, shouldn't use") } task := models.UpdateTask{ UUID: os.Getenv("uuid"), RefName: args[0], OldCommitID: args[1], NewCommitID: args[2], } if err := models.AddUpdateTask(&task); err != nil { log.GitLogger.Fatal(2, "AddUpdateTask: %v", err) } }
func CMD(c *cli.Context) { checkCache(c) args := c.Args().First() hosts := []string{} for name, ip := range allNodes() { hosts = append(hosts, name, ip) } r := strings.NewReplacer(hosts...) argsWithIPs := fmt.Sprintf(r.Replace(args)) parts := strings.Split(argsWithIPs, " ") cmd := exec.Command(parts[0], parts[1:]...) cmd.Stdout = stdout cmd.Stdin = os.Stdin err := cmd.Run() if err != nil { fmt.Println(err) os.Exit(1) } }
func runUpdate(c *cli.Context) { if c.IsSet("config") { setting.CustomConf = c.String("config") } setup("update.log") if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 { log.GitLogger.Trace("SSH_ORIGINAL_COMMAND is empty") return } args := c.Args() if len(args) != 3 { log.GitLogger.Fatal(2, "Arguments received are not equal to three") } else if len(args[0]) == 0 { log.GitLogger.Fatal(2, "First argument 'refName' is empty, shouldn't use") } task := models.UpdateTask{ UUID: os.Getenv("uuid"), RefName: args[0], OldCommitID: args[1], NewCommitID: args[2], } if err := models.AddUpdateTask(&task); err != nil { log.GitLogger.Fatal(2, "AddUpdateTask: %v", err) } }
func makedag(ctx *cli.Context) { utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name)) args := ctx.Args() wrongArgs := func() { utils.Fatalf(`Usage: geth makedag <block number> <outputdir>`) } switch { case len(args) == 2: blockNum, err := strconv.ParseUint(args[0], 0, 64) dir := args[1] if err != nil { wrongArgs() } else { dir = filepath.Clean(dir) // seems to require a trailing slash if !strings.HasSuffix(dir, "/") { dir = dir + "/" } _, err = ioutil.ReadDir(dir) if err != nil { utils.Fatalf("Can't find dir") } fmt.Println("making DAG, this could take awhile...") ethash.MakeDAG(blockNum, dir) } default: wrongArgs() } }
func blockRecovery(ctx *cli.Context) { utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name)) arg := ctx.Args().First() if len(ctx.Args()) < 1 && len(arg) > 0 { glog.Fatal("recover requires block number or hash") } cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx) utils.CheckLegalese(cfg.DataDir) blockDb, err := ethdb.NewLDBDatabase(filepath.Join(cfg.DataDir, "blockchain"), cfg.DatabaseCache) if err != nil { glog.Fatalln("could not open db:", err) } var block *types.Block if arg[0] == '#' { block = core.GetBlockByNumber(blockDb, common.String2Big(arg[1:]).Uint64()) } else { block = core.GetBlockByHash(blockDb, common.HexToHash(arg)) } if block == nil { glog.Fatalln("block not found. Recovery failed") } err = core.WriteHead(blockDb, block) if err != nil { glog.Fatalln("block write err", err) } glog.Infof("Recovery succesful. New HEAD %x\n", block.Hash()) }
func execJSFiles(ctx *cli.Context) { utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name)) cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx) ethereum, err := eth.New(cfg) if err != nil { utils.Fatalf("%v", err) } client := comms.NewInProcClient(codec.JSON) startEth(ctx, ethereum) repl := newJSRE( ethereum, ctx.GlobalString(utils.JSpathFlag.Name), ctx.GlobalString(utils.RPCCORSDomainFlag.Name), client, false, nil, ) for _, file := range ctx.Args() { repl.exec(file) } ethereum.Stop() ethereum.WaitForShutdown() }
// add is a subcommand to create a new snippet. func add(c *cli.Context) { snippetName := c.Args().First() if len(snippetName) == 0 { log.Fatal("please enter snippet name") } s := NewSnippet(conf.SnippetDirectory, snippetName) if s.Exists() { log.Fatal("This snippet already exists.") } stdinFlag := c.Bool("s") switch { case stdinFlag: // read contents from standard input buf, err := ioutil.ReadAll(os.Stdin) if err != nil { log.Fatal(err) } // write contents to snippet s.Write(buf) default: f, err := s.Create() if err != nil { log.Fatal(err) } f.Close() openSnippetWithEditor(s) } }
func (cmd *Files) Run(c *cli.Context) { app := cmd.appReq.GetApplication() cmd.ui.Say("Getting files for app %s in org %s / space %s as %s...", terminal.EntityNameColor(app.Name), terminal.EntityNameColor(cmd.config.OrganizationFields().Name), terminal.EntityNameColor(cmd.config.SpaceFields().Name), terminal.EntityNameColor(cmd.config.Username()), ) path := "/" if len(c.Args()) > 1 { path = c.Args()[1] } list, apiResponse := cmd.appFilesRepo.ListFiles(app.Guid, path) if apiResponse.IsNotSuccessful() { cmd.ui.Failed(apiResponse.Message) return } cmd.ui.Ok() cmd.ui.Say("") cmd.ui.Say("%s", list) }
func listAction(c *cli.Context) { paths := c.Args() if len(paths) == 0 { cwd, err := os.Getwd() if err != nil { panic(err) } paths = []string{cwd} } for _, path := range paths { files, err := tagopher.List(path) if err != nil { fmt.Printf("%s\n", err) } else { if len(paths) > 1 { fmt.Printf("%s:\n", path) } t := termtable.NewTable(asTermtableRows(files), &termtable.TableOptions{ Padding: 2, }) fmt.Println(t.Render()) if len(paths) > 1 { fmt.Println() } } } }
func (cmd CreateOrg) Run(c *cli.Context) { name := c.Args()[0] cmd.ui.Say(T("Creating org {{.OrgName}} as {{.Username}}...", map[string]interface{}{ "OrgName": terminal.EntityNameColor(name), "Username": terminal.EntityNameColor(cmd.config.Username())})) org := models.Organization{OrganizationFields: models.OrganizationFields{Name: name}} quotaName := c.String("q") if quotaName != "" { quota, err := cmd.quotaRepo.FindByName(quotaName) if err != nil { cmd.ui.Failed(err.Error()) } org.QuotaDefinition.Guid = quota.Guid } err := cmd.orgRepo.Create(org) if err != nil { if apiErr, ok := err.(errors.HttpError); ok && apiErr.ErrorCode() == errors.ORG_EXISTS { cmd.ui.Ok() cmd.ui.Warn(T("Org {{.OrgName}} already exists", map[string]interface{}{"OrgName": name})) return } else { cmd.ui.Failed(err.Error()) } } cmd.ui.Ok() cmd.ui.Say(T("\nTIP: Use '{{.Command}}' to target new org", map[string]interface{}{"Command": terminal.CommandColor(cf.Name() + " target -o " + name)})) }
func createImageCommandFunc(c *cli.Context) { var image string if len(c.Args()) == 0 { log.Fatal("You need to specify a image") } else { image = c.Args()[0] } clnt := client.New(c.GlobalString("server")) if c.GlobalBool("debug") { clnt.SetDebug() } s := client.Image{ Image: image, Type: prompt.String("Type", prompt.Prompt{Default: "docker", FuncPtr: prompt.Enum, FuncInp: "file,docker"}), BootTagID: *chooseTag(clnt, ""), } // Is this correct? fmt.Println(string(s.JSON())) if !prompt.Bool("Is this correct", true) { os.Exit(1) } // Create image clnt.Image.Create(&s) }
func (cmd *SpaceUsers) Run(c *cli.Context) { spaceName := c.Args()[1] org := cmd.orgReq.GetOrganization() space, apiErr := cmd.spaceRepo.FindByNameInOrg(spaceName, org.Guid) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) } cmd.ui.Say("Getting users in org %s / space %s as %s", terminal.EntityNameColor(org.Name), terminal.EntityNameColor(space.Name), terminal.EntityNameColor(cmd.config.Username()), ) for _, role := range spaceRoles { displayName := spaceRoleToDisplayName[role] users, apiErr := cmd.userRepo.ListUsersInSpaceForRole(space.Guid, role) cmd.ui.Say("") cmd.ui.Say("%s", terminal.HeaderColor(displayName)) for _, user := range users { cmd.ui.Say(" %s", user.Username) } if apiErr != nil { cmd.ui.Failed("Failed fetching space-users for role %s.\n%s", apiErr.Error(), displayName) return } } }
func (factory *DropletRunnerCommandFactory) exportDroplet(context *cli.Context) { dropletName := context.Args().First() if dropletName == "" { factory.UI.SayIncorrectUsage("<droplet-name> is required") factory.ExitHandler.Exit(exit_codes.InvalidSyntax) return } dropletReader, err := factory.dropletRunner.ExportDroplet(dropletName) if err != nil { factory.UI.SayLine(fmt.Sprintf("Error exporting droplet %s: %s", dropletName, err)) factory.ExitHandler.Exit(exit_codes.CommandFailed) return } defer dropletReader.Close() dropletPath := dropletName + ".tgz" dropletWriter, err := os.OpenFile(dropletPath, os.O_WRONLY|os.O_CREATE, os.FileMode(0644)) if err != nil { factory.UI.SayLine(fmt.Sprintf("Error exporting droplet '%s' to %s: %s", dropletName, dropletPath, err)) factory.ExitHandler.Exit(exit_codes.CommandFailed) return } defer dropletWriter.Close() _, err = io.Copy(dropletWriter, dropletReader) if err != nil { factory.UI.SayLine(fmt.Sprintf("Error exporting droplet '%s' to %s: %s", dropletName, dropletPath, err)) factory.ExitHandler.Exit(exit_codes.CommandFailed) return } factory.UI.SayLine(fmt.Sprintf("Droplet '%s' exported to %s.", dropletName, dropletPath)) }
func (cmd CreateBuildpack) createBuildpack(buildpackName string, c *cli.Context) (buildpack cf.Buildpack, apiResponse net.ApiResponse) { position, err := strconv.Atoi(c.Args()[2]) if err != nil { apiResponse = net.NewApiResponseWithMessage("Invalid position. %s", err.Error()) return } enabled := c.Bool("enable") disabled := c.Bool("disable") if enabled && disabled { apiResponse = net.NewApiResponseWithMessage("Cannot specify both enabled and disabled.") return } var enableOption *bool = nil if enabled { enableOption = &enabled } if disabled { disabled = false enableOption = &disabled } buildpack, apiResponse = cmd.buildpackRepo.Create(buildpackName, &position, enableOption) return }
func doLbCreate(c *cli.Context) { if len(c.Args()) == 0 { displayWrongNumOfArgsAndExit(c) } lbname := c.Args().Get(0) path := "/load-balancer" if c.Int("subscription-id") > 0 { path += "/" + strconv.Itoa(c.Int("subscription-id")) } path += "/create/" + lbname resp, err := client.SendRequest("POST", path, nil) assert(err) if resp.StatusCode >= 400 { displayErrorAndExit(string(resp.Body)) } pwd := lib.PasswordResponse{} assert(xml.Unmarshal(resp.Body, &pwd)) outputResult(c, pwd, func(format string) { lib.PrintXMLStruct(pwd) }) }
func (cmd SetSpaceQuota) Run(context *cli.Context) { spaceName := context.Args()[0] quotaName := context.Args()[1] cmd.ui.Say(T("Assigning space quota {{.QuotaName}} to space {{.SpaceName}} as {{.Username}}...", map[string]interface{}{ "QuotaName": terminal.EntityNameColor(quotaName), "SpaceName": terminal.EntityNameColor(spaceName), "Username": terminal.EntityNameColor(cmd.config.Username()), })) space, err := cmd.spaceRepo.FindByName(spaceName) if err != nil { cmd.ui.Failed(err.Error()) } if space.SpaceQuotaGuid != "" { cmd.ui.Failed(T("This space already has an assigned space quota.")) } quota, err := cmd.quotaRepo.FindByName(quotaName) if err != nil { cmd.ui.Failed(err.Error()) } err = cmd.quotaRepo.AssociateSpaceWithQuota(space.Guid, quota.Guid) if err != nil { cmd.ui.Failed(err.Error()) } cmd.ui.Ok() }
func deleteVersion(c *cli.Context) { if c.NArg() != 1 { cliutils.Exit(cliutils.ExitCodeError, "Wrong number of arguments. "+cliutils.GetDocumentationMessage()) } versionDetails, err := utils.CreateVersionDetails(c.Args().Get(0)) if err != nil { cliutils.Exit(cliutils.ExitCodeError, err.Error()) } bintrayDetails, err := createBintrayDetails(c, true) if err != nil { cliutils.Exit(cliutils.ExitCodeError, err.Error()) } if !c.Bool("quiet") { var confirm string fmt.Print("Delete version " + versionDetails.Version + " of package " + versionDetails.Package + "? (y/n): ") fmt.Scanln(&confirm) if !cliutils.ConfirmAnswer(confirm) { return } } err = commands.DeleteVersion(versionDetails, bintrayDetails) cliutils.ExitOnErr(err) }
// delete is a subcommand to delete a snippet. func delete(c *cli.Context) { force := c.Bool("f") snippetName := c.Args().First() if len(snippetName) == 0 { log.Fatal("please enter snippet name") } s := NewSnippet(conf.SnippetDirectory, snippetName) if !s.Exists() { log.Fatal("This snippet doesn't exists.") } if !force { reader := bufio.NewReader(os.Stdin) fmt.Print("sure you want to delete %s [yn]?") ret, err := reader.ReadString('\n') if err != nil { log.Fatal(err) } if ret != "y\n" { return } } if err := s.Delete(); err != nil { log.Fatal(err) } fmt.Printf("%s has been deleted.\n", snippetName) }
func cmdFrom(c *cli.Context) error { repos, err := repos(c.Bool("all"), c.Args()...) if err != nil { return cli.NewMultiError(fmt.Errorf(`failed gathering repo list`), err) } uniq := c.Bool("uniq") namespace := "" applyConstraints := c.Bool("apply-constraints") for _, repo := range repos { r, err := fetch(repo) if err != nil { return cli.NewMultiError(fmt.Errorf(`failed fetching repo %q`, repo), err) } for _, entry := range r.Entries() { if applyConstraints && r.SkipConstraints(entry) { continue } from, err := r.DockerFrom(&entry) if err != nil { return cli.NewMultiError(fmt.Errorf(`failed fetching/scraping FROM for %q (tags %q)`, r.RepoName, entry.TagsString()), err) } for _, tag := range r.Tags(namespace, uniq, entry) { fmt.Printf("%s: %s\n", tag, from) } } } return nil }
// list is a subcommand to list up snippets. // It just finds snippet files in the snippet directory and listed them. func list(c *cli.Context) { var pattern *regexp.Regexp var err error query := c.Args().First() if len(query) > 0 { pattern, err = regexp.Compile(fmt.Sprintf(".*%s.*", query)) if err != nil { log.Fatal(err) } } err = filepath.Walk( conf.SnippetDirectory, func(path string, info os.FileInfo, err error) error { if info.IsDir() { return nil } rel, err := filepath.Rel(conf.SnippetDirectory, path) if pattern != nil { if pattern.MatchString(rel) { fmt.Println(rel) } return nil } fmt.Println(rel) return nil }, ) if err != nil { log.Fatal(err) } }
func (cmd *SetEnv) Run(c *cli.Context) { varName := c.Args()[1] varValue := c.Args()[2] app := cmd.appReq.GetApplication() cmd.ui.Say(T("Setting env variable '{{.VarName}}' to '{{.VarValue}}' for app {{.AppName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...", map[string]interface{}{ "VarName": terminal.EntityNameColor(varName), "VarValue": terminal.EntityNameColor(varValue), "AppName": terminal.EntityNameColor(app.Name), "OrgName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name), "SpaceName": terminal.EntityNameColor(cmd.config.SpaceFields().Name), "CurrentUser": terminal.EntityNameColor(cmd.config.Username())})) if len(app.EnvironmentVars) == 0 { app.EnvironmentVars = map[string]string{} } envParams := app.EnvironmentVars envParams[varName] = varValue _, apiErr := cmd.appRepo.Update(app.Guid, models.AppParams{EnvironmentVars: &envParams}) if apiErr != nil { cmd.ui.Failed(apiErr.Error()) return } cmd.ui.Ok() cmd.ui.Say(T("TIP: Use '{{.Command}}' to ensure your env variable changes take effect", map[string]interface{}{"Command": terminal.CommandColor(cf.Name() + " restage")})) }
func a2(c *cli.Context, msg string) string { a := c.Args() if len(a) < 2 { die(errors.New(msg)) } return a[1] }