示例#1
1
func startDirectory(c *cli.Context) {
	fmt.Println("Starting full-blown service-directory")

	// var apiReg = svcreg.NewGenericAPIVersionRegistry()
	// var svcReg = svcreg.NewGenericServiceRegistry()
	// var hostReg = svcreg.NewGenericHostRegistry(svcReg)
	//
	// var outboundEvents = make(chan evntsrc.Event)
	// var handler = evntsrc.NewEventHandler()
	// var dirSvc = svcreg.NewServiceRegistryWebService(outboundEvents, apiReg, svcReg, hostReg)
	// var nsqSink, err = utils.NewNsqSink()
	// if err != nil {
	// 	fmt.Println("Failed to initialize the NSQ communications")
	// 	return
	// }
	// handler.Use("ADD_ServiceDefinition", nsqSink.Publish)
	// var nsqCancelChan = keepProcessing(outboundEvents, handler.Handle)
	//
	// var m = martini.Classic()
	// m.Use(render.Renderer())
	// m.Action(dirSvc.Route().Handle)
	// http.HandleFunc("/service-directory/", func(w http.ResponseWriter, r *http.Request) {
	// 	r.URL, _ = url.Parse(strings.TrimPrefix(r.URL.String(), "/service-directory"))
	// 	m.ServeHTTP(w, r)
	// })

	// TODO (enzian) gracefully stop the service.
	log.Fatal(http.ListenAndServe(c.String("u"), nil))
	// nsqCancelChan <- true
}
示例#2
1
func upload(c *cli.Context) {
	if c.NArg() < 2 || c.NArg() > 3 {
		cliutils.Exit(cliutils.ExitCodeError, "Wrong number of arguments. "+cliutils.GetDocumentationMessage())
	}
	localPath := c.Args().Get(0)
	versionDetails, err := utils.CreateVersionDetails(c.Args().Get(1))
	if err != nil {
		cliutils.Exit(cliutils.ExitCodeError, err.Error())
	}
	uploadPath := c.Args().Get(2)
	if strings.HasPrefix(uploadPath, "/") {
		uploadPath = uploadPath[1:]
	}

	uploadFlags, err := createUploadFlags(c)
	if err != nil {
		cliutils.Exit(cliutils.ExitCodeError, err.Error())
	}
	uploaded, failed, err := commands.Upload(versionDetails, localPath, uploadPath, uploadFlags)
	cliutils.ExitOnErr(err)
	if failed > 0 {
		if uploaded > 0 {
			cliutils.Exit(cliutils.ExitCodeWarning, "")
		}
		cliutils.Exit(cliutils.ExitCodeError, "")
	}
}
示例#3
1
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
}
示例#4
1
func GetChain(ctx *cli.Context) (*core.ChainManager, common.Database, common.Database) {
	dataDir := ctx.GlobalString(DataDirFlag.Name)

	blockDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "blockchain"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	stateDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "state"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	extraDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "extra"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	eventMux := new(event.TypeMux)
	chainManager := core.NewChainManager(blockDb, stateDb, eventMux)
	pow := ethash.New()
	txPool := core.NewTxPool(eventMux, chainManager.State, chainManager.GasLimit)
	blockProcessor := core.NewBlockProcessor(stateDb, extraDb, pow, txPool, chainManager, eventMux)
	chainManager.SetProcessor(blockProcessor)

	return chainManager, blockDb, stateDb
}
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 (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))
}
示例#7
0
文件: service.go 项目: rowhit/os
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)
		}
	}
}
示例#8
0
文件: login.go 项目: juggernaut/cli
func (cmd Login) setOrganization(c *cli.Context) (isOrgSet bool) {
	orgName := c.String("o")

	if orgName == "" {
		availableOrgs := []models.Organization{}
		apiErr := cmd.orgRepo.ListOrgs(func(o models.Organization) bool {
			availableOrgs = append(availableOrgs, o)
			return len(availableOrgs) < maxChoices
		})
		if apiErr != nil {
			cmd.ui.Failed("Error finding avilable orgs\n%s", apiErr.Error())
		}

		if len(availableOrgs) == 1 {
			cmd.targetOrganization(availableOrgs[0])
			return true
		}

		orgName = cmd.promptForOrgName(availableOrgs)
		if orgName == "" {
			cmd.ui.Say("")
			return false
		}
	}

	org, err := cmd.orgRepo.FindByName(orgName)
	if err != nil {
		cmd.ui.Failed("Error finding org %s\n%s", terminal.EntityNameColor(orgName), err.Error())
	}

	cmd.targetOrganization(org)
	return true
}
示例#9
0
文件: login.go 项目: juggernaut/cli
func (cmd Login) setSpace(c *cli.Context) {
	spaceName := c.String("s")

	if spaceName == "" {
		var availableSpaces []models.Space
		err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool {
			availableSpaces = append(availableSpaces, space)
			return (len(availableSpaces) < maxChoices)
		})
		if err != nil {
			cmd.ui.Failed("Error finding available spaces\n%s", err.Error())
		}

		// Target only space if possible
		if len(availableSpaces) == 1 {
			cmd.targetSpace(availableSpaces[0])
			return
		}

		spaceName = cmd.promptForSpaceName(availableSpaces)
		if spaceName == "" {
			cmd.ui.Say("")
			return
		}
	}

	space, err := cmd.spaceRepo.FindByName(spaceName)
	if err != nil {
		cmd.ui.Failed("Error finding space %s\n%s", terminal.EntityNameColor(spaceName), err.Error())
	}

	cmd.targetSpace(space)
}
示例#10
0
func (cmd Target) Run(c *cli.Context) {
	orgName := c.String("o")
	spaceName := c.String("s")

	if orgName != "" {
		err := cmd.setOrganization(orgName)
		if err != nil {
			cmd.ui.Failed(err.Error())
		} else if spaceName == "" {
			spaceList, apiErr := cmd.getSpaceList()
			if apiErr == nil && len(spaceList) == 1 {
				cmd.setSpace(spaceList[0].Name)
			}
		}
	}

	if spaceName != "" {
		err := cmd.setSpace(spaceName)
		if err != nil {
			cmd.ui.Failed(err.Error())
		}
	}

	cmd.ui.ShowConfiguration(cmd.config)
	if !cmd.config.IsLoggedIn() {
		cmd.ui.PanicQuietly()
	}
	utils.NotifyUpdateIfNeeded(cmd.ui, cmd.config)
	return
}
示例#11
0
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
		}
	}
}
示例#12
0
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)}))
}
示例#13
0
文件: files.go 项目: normalnorman/cli
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)
}
示例#14
0
文件: push.go 项目: ramirito/cli
func (cmd *Push) Run(c *cli.Context) {
	appSet := cmd.findAndValidateAppsToPush(c)
	_, apiErr := cmd.authRepo.RefreshAuthToken()
	if apiErr != nil {
		cmd.ui.Failed(fmt.Sprintf("Error refreshing auth token.\n%s", apiErr.Error()))
		return
	}

	routeActor := actors.NewRouteActor(cmd.ui, cmd.routeRepo)
	noHostname := c.Bool("no-hostname")

	for _, appParams := range appSet {
		cmd.fetchStackGuid(&appParams)
		app := cmd.createOrUpdateApp(appParams)

		cmd.updateRoutes(routeActor, app, appParams, noHostname)

		cmd.ui.Say(T("Uploading {{.AppName}}...",
			map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)}))

		apiErr := cmd.appBitsRepo.UploadApp(app.Guid, *appParams.Path, cmd.describeUploadOperation)
		if apiErr != nil {
			cmd.ui.Failed(fmt.Sprintf(T("Error uploading application.\n{{.ApiErr}}",
				map[string]interface{}{"ApiErr": apiErr.Error()})))
			return
		}
		cmd.ui.Ok()

		if appParams.ServicesToBind != nil {
			cmd.bindAppToServices(*appParams.ServicesToBind, app)
		}

		cmd.restart(app, appParams, c)
	}
}
示例#15
0
func SecureYamlCmd(c *cli.Context, client drone.Client) error {
	var (
		repo     = c.String("repo")
		inFile   = c.String("in")
		outFile  = c.String("out")
		ymlFile  = c.String("yaml")
		checksum = c.BoolT("checksum")
	)

	owner, name, err := parseRepo(repo)
	if err != nil {
		return err
	}

	keypair, err := client.RepoKey(owner, name)
	if err != nil {
		return err
	}

	key, err := toPublicKey(keypair.Public)
	if err != nil {
		return err
	}

	// read the .drone.sec.yml file (plain text)
	plaintext, err := readInput(inFile)
	if err != nil {
		return err
	}

	// parse the .drone.sec.yml file
	sec := new(secure.Secure)
	err = yaml.Unmarshal(plaintext, sec)
	if err != nil {
		return err
	}

	// read the .drone.yml file and caclulate the
	// checksum. add to the .drone.sec.yml file.
	yml, err := ioutil.ReadFile(ymlFile)
	if err == nil && checksum {
		sec.Checksum = sha256sum(string(yml))
	}

	// re-marshal the .drone.sec.yml file since we've
	// added the checksum
	plaintext, err = yaml.Marshal(sec)
	if err != nil {
		return err
	}

	// encrypt the .drone.sec.yml file
	ciphertext, err := encrypt(plaintext, key)
	if err != nil {
		return err
	}

	// write the encrypted .drone.sec.yml file to .drone.sec
	return writeOutput(outFile, ciphertext)
}
示例#16
0
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()
}
示例#17
0
func (cmd *PluginInstall) GetRequirements(_ requirements.Factory, c *cli.Context) (req []requirements.Requirement, err error) {
	if len(c.Args()) != 1 {
		cmd.ui.FailWithUsage(c)
	}

	return
}
示例#18
0
文件: main.go 项目: sudix/chickenhead
// 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)
}
示例#19
0
func (c *clusterClient) enumerate(context *cli.Context) {
	c.clusterOptions(context)
	jsonOut := context.GlobalBool("json")
	outFd := os.Stdout
	fn := "enumerate"

	cluster, err := c.manager.Enumerate()
	if err != nil {
		cmdError(context, fn, err)
		return
	}

	if jsonOut {
		fmtOutput(context, &Format{Cluster: &cluster})
	} else {
		w := new(tabwriter.Writer)
		w.Init(outFd, 12, 12, 1, ' ', 0)

		fmt.Fprintln(w, "ID\t IMAGE\t STATUS\t NAMES\t NODE")
		for _, n := range cluster.Nodes {
			for _, c := range n.Containers {
				fmt.Fprintln(w, c.ID, "\t", c.Image, "\t", c.Status, "\t",
					c.Names, "\t", n.Ip)
			}
		}

		fmt.Fprintln(w)
		w.Flush()
	}
}
示例#20
0
文件: main.go 项目: sudix/chickenhead
// 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)
	}
}
示例#21
0
func getPassword(context *cli.Context) (password string, err error) {
	password = context.String("password")
	if len(password) > 0 {
		return password, nil
	}
	return gopass.GetPass("Plex password: ")
}
示例#22
0
文件: main.go 项目: sudix/chickenhead
// 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)
	}
}
示例#23
0
// MakeNAT creates a port mapper from set command line flags.
func MakeNAT(ctx *cli.Context) nat.Interface {
	natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
	if err != nil {
		Fatalf("Option %s: %v", NATFlag.Name, err)
	}
	return natif
}
示例#24
0
文件: janus.go 项目: xenolog/janus
func runBot(c *cli.Context) {
	var (
		Sapi     *slack.Slack
		cfg      *config.Config
		cfg_path string
		err      error
		wg       sync.WaitGroup
	)
	cfg_path = c.GlobalString("config")
	Log.Info("Config '%s' will be loaded.", cfg_path)
	cfg, err = config.New(cfg_path)
	if err != nil {
		Log.Error("Config processing error: %s", err)
		return
	}

	Sapi = slack.New(&cfg.Janus)
	Sapi.Connect()
	// start Messsage loop
	wg.Add(1)
	go func() {
		defer wg.Done()
		Sapi.MessageLoop()
	}()
	// start Channel info loop
	wg.Add(1)
	go func() {
		defer wg.Done()
		Sapi.ChannelLoop()
	}()
	// all loops started
	wg.Wait()

}
示例#25
0
func (cmd RepoPlugins) Run(c *cli.Context) {
	var repos []models.PluginRepo
	repoName := c.String("r")

	repos = cmd.config.PluginRepos()

	if repoName == "" {
		cmd.ui.Say(T("Getting plugins from all repositories ... "))
	} else {
		index := cmd.findRepoIndex(repoName)
		if index != -1 {
			cmd.ui.Say(T("Getting plugins from repository '") + repoName + "' ...")
			repos = []models.PluginRepo{repos[index]}
		} else {
			cmd.ui.Failed(repoName + T(" does not exist as an available plugin repo."+"\nTip: use `add-plugin-repo` command to add repos."))
		}
	}

	cmd.ui.Say("")

	repoPlugins, repoError := cmd.pluginRepo.GetPlugins(repos)

	cmd.printTable(repoPlugins)

	cmd.printErrors(repoError)
}
func doObjectStoreAddImage(c *cli.Context) error {
	var err error
	v := url.Values{}

	objectstoreUUID, err := getUUID(c, KEY_OBJECTSTORE, true, err)
	imageUUID, err := getUUID(c, KEY_IMAGE, false, err)
	imageName, err := getName(c, "image-name", false, err)
	if err != nil {
		return err
	}
	imageFile := c.String("image-file")
	if imageFile == "" {
		return genRequiredMissingError("image-file")
	}

	imageConfig := api.ObjectStoreImageConfig{
		ImageFile: imageFile,
	}
	if imageUUID != "" {
		v.Set(KEY_IMAGE, imageUUID)
	}
	if imageName != "" {
		v.Set("image-name", imageName)
	}

	request := "/objectstores/" + objectstoreUUID + "/images/add?" + v.Encode()
	return sendRequestAndPrint("POST", request, imageConfig)
}
示例#27
0
文件: main.go 项目: gernest/apidemic
func server(ctx *cli.Context) {
	port := ctx.Int("port")
	s := apidemic.NewServer()

	log.Println("starting server on port :", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), s))
}
示例#28
0
文件: list.go 项目: imdario/tagopher
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()
			}
		}
	}
}
示例#29
0
文件: set_env.go 项目: BlueSpice/cli
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")}))
}
示例#30
0
文件: actions.go 项目: adamenger/rv
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)
	}
}