Пример #1
0
// NoteName returns name of note and error if note isnt present
func NoteName(c *cli.Context) (n string, err error) {
	if c.Args().Present() != true {
		return "", errors.New("Missing argument: name")
	}

	return strings.Join(c.Args(), " "), nil
}
Пример #2
0
func Init(c *cli.Context, reg *harness.MetricRegistry) (harness.Collector, error) {
	args := c.Args()

	if len(args) < 2 {
		cli.ShowAppHelp(c)
		return nil, fmt.Errorf("not enough arguments")
	}

	var (
		endpoint   = args[0]
		configPath = args[1]
	)

	configs, err := loadConfig(configPath)
	if err != nil {
		return nil, err
	}

	scrapers := make([]JsonScraper, len(configs))
	for i, config := range configs {
		tpe := ScrapeTypes[config.Type]
		if tpe == nil {
			return nil, fmt.Errorf("unknown scrape type;type:<%s>", config.Type)
		}
		tpe.Configure(config, reg)
		scraper, err := tpe.NewScraper(config)
		if err != nil {
			return nil, fmt.Errorf("failed to create scraper;name:<%s>,err:<%s>", config.Name, err)
		}
		scrapers[i] = scraper
	}

	return NewCollector(endpoint, scrapers), nil
}
Пример #3
0
func connectPeer(ctx *cli.Context) error {
	ctxb := context.Background()
	client := getClient(ctx)

	targetAddress := ctx.Args().Get(0)
	splitAddr := strings.Split(targetAddress, "@")
	if len(splitAddr) != 2 {
		return fmt.Errorf("target address expected in format: " +
			"pubkey@host:port")
	}

	addr := &lnrpc.LightningAddress{
		Pubkey: splitAddr[0],
		Host:   splitAddr[1],
	}
	req := &lnrpc.ConnectPeerRequest{addr}

	lnid, err := client.ConnectPeer(ctxb, req)
	if err != nil {
		return err
	}

	printRespJson(lnid)
	return nil
}
Пример #4
0
func CmdUntaint(c *cli.Context) error {
	operation := initialize(c, "untaint")
	operation.extraArgs = strings.Join(c.Args()[1:], " ")
	run(operation)
	resync(operation)
	return nil
}
Пример #5
0
//Generate generates a migration on the migrations folder
func Generate(c *cli.Context) {
	setupTestingEnv()
	base := os.Getenv("TRANS_TESTING_FOLDER")

	name := "migration"
	if c.App != nil && len(c.Args()) > 0 {
		name = c.Args().First()
	}

	name = snaker.CamelToSnake(name)
	identifier := time.Now().UnixNano()

	migration := MigrationData{
		Identifier: identifier,
		Name:       name,
	}

	buff := bytes.NewBufferString("")
	tmpl, _ := template.New("migration").Parse(utils.MigrationTemplate)
	_ = tmpl.Execute(buff, migration)

	fileName := strconv.FormatInt(identifier, 10) + "_" + name + ".go"
	path := filepath.Join(base, "db", "migrations", fileName)

	err := ioutil.WriteFile(path, buff.Bytes(), generatedFilePermissions)
	if err != nil {
		log.Println(err)
		log.Println("| Could not write migration file, please check db/migrations folder exists")
	}
}
Пример #6
0
func execProcess(context *cli.Context) (int, error) {
	container, err := getContainer(context)
	if err != nil {
		return -1, err
	}
	path := context.String("process")
	if path == "" && len(context.Args()) == 1 {
		return -1, fmt.Errorf("process args cannot be empty")
	}
	detach := context.Bool("detach")
	state, err := container.State()
	if err != nil {
		return -1, err
	}
	bundle := utils.SearchLabels(state.Config.Labels, "bundle")
	p, err := getProcess(context, bundle)
	if err != nil {
		return -1, err
	}
	r := &runner{
		enableSubreaper: false,
		shouldDestroy:   false,
		container:       container,
		console:         context.String("console"),
		detach:          detach,
		pidFile:         context.String("pid-file"),
	}
	return r.run(p)
}
Пример #7
0
func (cmd *CatalogShow) show(c *cli.Context) error {
	if len(c.Args()) != 2 {
		return errors.New(c.App.Name + " " + showCommandName + catalogItemTypesUsage + " ITEM[:VERSION]")
	}
	catalogType, err := GetCatalogType(c)
	if err != nil {
		return err
	}
	item := c.Args().Get(1)
	var version string
	if strings.Contains(item, ":") {
		itemVersion := strings.Split(item, ":")
		item = itemVersion[0]
		version = itemVersion[1]
	}
	switch catalogType {
	case ApplicationsItemType:
		return cmd.showCatalogApplication(c, item, version)
	case EntitiesItemType:
		return cmd.showCatalogEntity(c, item, version)
	case LocationsItemType:
		return cmd.showCatalogLocation(c, item, version)
	case PoliciesItemType:
		return cmd.showPolicy(c, item, version)
	}
	return errors.New("Unrecognised argument")
}
Пример #8
0
// ProjectDelete deletes services.
func ProjectDelete(p project.APIProject, c *cli.Context) error {
	options := options.Delete{
		RemoveVolume: c.Bool("v"),
	}
	if !c.Bool("force") {
		stoppedContainers, err := p.Containers(context.Background(), project.Filter{
			State: project.Stopped,
		}, c.Args()...)
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}
		if len(stoppedContainers) == 0 {
			fmt.Println("No stopped containers")
			return nil
		}
		fmt.Printf("Going to remove %v\nAre you sure? [yN]\n", strings.Join(stoppedContainers, ", "))
		var answer string
		_, err = fmt.Scanln(&answer)
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}
		if answer != "y" && answer != "Y" {
			return nil
		}
	}
	err := p.Delete(context.Background(), options, c.Args()...)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
Пример #9
0
func servicesCreateCmd(c *CLI, ctx *cli.Context) {
	usage := func(msg string) {
		fmt.Printf("Usage: %s services create [--name,--version,--instance] <service-kind>\n", c.Name)
		fatal(msg)
	}
	if len(ctx.Args()) == 0 {
		usage("too few arguments")
	}
	api := c.GetAPIClient(ctx)
	instance := c.GetInstance(ctx, nil)
	name := ctx.String("name")
	service := gondor.Service{
		Instance: instance.URL,
		Name:     &name,
		Kind:     &ctx.Args()[0],
	}
	if ctx.String("version") != "" {
		version := ctx.String("version")
		service.Version = &version
	}
	if err := api.Services.Create(&service); err != nil {
		fatal(err.Error())
	}
	success(fmt.Sprintf("%s service has been created.", *service.Kind))
}
Пример #10
0
func cmdSearch(c *cli.Context) error {
	conf, err := config.Open(c.GlobalString("config"))
	if err != nil {
		Logger.Fatalf("Cannot load configuration: %v", err)
		return nil
	}

	needle := c.Args()[0]

	found := []*config.Host{}
	for _, host := range conf.Hosts.SortedList() {
		if host.Matches(needle) {
			found = append(found, host)
		}
	}

	if len(found) == 0 {
		fmt.Println("no results found.")
		return nil
	}

	fmt.Printf("Listing results for %s:\n", needle)
	for _, host := range found {
		fmt.Printf("    %s -> %s\n", host.Name(), host.Prototype())
	}

	return nil
}
Пример #11
0
// Executes the "apply" command
func execApplyCommand(c *cli.Context) error {
	if len(c.Args()) < 1 {
		return cli.NewExitError(errNoModuleName.Error(), 64)
	}

	L := lua.NewState()
	defer L.Close()
	config := &catalog.Config{
		Module:   c.Args()[0],
		DryRun:   c.Bool("dry-run"),
		Logger:   resource.DefaultLogger,
		SiteRepo: c.String("siterepo"),
		L:        L,
	}

	katalog := catalog.New(config)
	if err := katalog.Load(); err != nil {
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}
	}

	if err := katalog.Run(); err != nil {
		return cli.NewExitError(err.Error(), 1)
	}

	return nil
}
Пример #12
0
// the format action is similar to the gofmt command.
// it can be used to format the source of a fzp file.
func commandFormatAction(c *cli.Context) error {
	tmpArgs := c.Args()
	if len(tmpArgs) == 0 {
		fmt.Println("missing source to format. try run")
		fmt.Println("  fzp format part.fzp")
		os.Exit(127)
	}

	source := tmpArgs[0]

	formatDirHandler := func() {
		err := formatFile(source, c.Bool("write"), c.Bool("diff"))
		if err != nil {
			fmt.Println("Error", err)
			os.Exit(127)
		}
	}

	formatFileHandler := func() {
		err := formatDir(source, c.Bool("write"), c.Bool("diff"))
		if err != nil {
			fmt.Println("Error", err)
			os.Exit(127)
		}
	}

	dataHandler(source, formatFileHandler, formatDirHandler)
	return nil
}
Пример #13
0
func actionMemberList(c *cli.Context) error {
	if len(c.Args()) != 0 {
		fmt.Fprintln(os.Stderr, "No arguments accepted")
		os.Exit(1)
	}
	mAPI := mustNewMembersAPI(c)
	ctx, cancel := contextWithTotalTimeout(c)
	defer cancel()

	members, err := mAPI.List(ctx)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
	leader, err := mAPI.Leader(ctx)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Failed to get leader: ", err)
		os.Exit(1)
	}

	for _, m := range members {
		isLeader := false
		if m.ID == leader.ID {
			isLeader = true
		}
		if len(m.Name) == 0 {
			fmt.Printf("%s[unstarted]: peerURLs=%s\n", m.ID, strings.Join(m.PeerURLs, ","))
		} else {
			fmt.Printf("%s: name=%s peerURLs=%s clientURLs=%s isLeader=%v\n", m.ID, m.Name, strings.Join(m.PeerURLs, ","), strings.Join(m.ClientURLs, ","), isLeader)
		}
	}

	return nil
}
Пример #14
0
func run(c *cli.Context) error {
	args := c.Args()
	if len(args) < 3 {
		return errors.New("a directory, log file and command is required")
	}
	workingDir := os.ExpandEnv(args[0])
	logFile := os.ExpandEnv(args[1])
	fullCommand := os.ExpandEnv(args[2])

	command, cmdArgs, err := parseCommand(fullCommand)
	if err != nil {
		return errors.WithStack(err)
	}

	log, err := os.Create(logFile)
	if err != nil {
		return errors.WithStack(err)
	}

	cmd := exec.Command(command, cmdArgs...)
	fmt.Println(cmd.Path)
	cmd.Dir = workingDir
	cmd.Stdout = log
	cmd.Stderr = log
	return cmd.Run()
}
Пример #15
0
//
// deleteFile removes a file from the bucket
//
func deleteFile(o *formatter, cx *cli.Context, cmd *cliCommand) error {
	if len(cx.Args()) <= 0 {
		return fmt.Errorf("you have not specified any files to delete")
	}

	bucket := cx.String("bucket")
	// step: ensure the bucket exists
	if found, err := cmd.hasBucket(bucket); err != nil {
		return err
	} else if !found {
		return fmt.Errorf("the bucket: %s does not exist", bucket)
	}

	for _, path := range getPaths(cx) {
		if err := cmd.removeFile(bucket, path); err != nil {
			o.fields(map[string]interface{}{
				"action": "delete",
				"bucket": bucket,
				"path":   path,
				"error":  err.Error(),
			}).log("failed to remove s3://%s/%s, error: %s", bucket, path, err)
			continue
		}
		o.fields(map[string]interface{}{
			"action": "delete",
			"bucket": bucket,
			"path":   path,
		}).log("successfully deleted the file s3://%s/%s\n", bucket, path)
	}

	return nil
}
Пример #16
0
func parseGocov(c *cli.Context) error {

	pattern := c.Args().First()
	if pattern == "" {
		pattern = "**/*.out"
	}

	matches, err := zglob.Glob(pattern)
	if err != nil {
		return err
	}

	parser := gocov.New()
	var profiles []*cover.Profile
	for _, match := range matches {
		parsed, err := parser.ReadFile(match)
		if err != nil {
			return err
		}
		for _, p := range parsed {
			profiles = addProfile(profiles, p)
		}
	}

	// create the coverage payload that gets sent to the
	// coverage reporting server.
	report := profileToReport(profiles)

	out, err := json.MarshalIndent(report, " ", " ")
	if err != nil {
		return err
	}
	fmt.Fprintf(os.Stdout, "%s", out)
	return nil
}
Пример #17
0
func activityCreate(c *cli.Context) error {
	ctx := context.Background()
	client, err := doaramacli.NewAuthenticatedDoaramaClient(c)
	if err != nil {
		return err
	}
	defer client.Close()
	activityType, err := doarama.DefaultActivityTypes.Find(doaramacli.ActivityType(c))
	if err != nil {
		return err
	}
	activityInfo := &doarama.ActivityInfo{
		TypeID: activityType.ID,
	}
	cache, err := newCache(c, client)
	if err != nil {
		return err
	}
	defer cache.Close()
	for _, arg := range c.Args() {
		a, err := activityCreateOne(ctx, cache, arg, activityInfo)
		if err != nil {
			log.Print(err)
			continue
		}
		fmt.Printf("ActivityId: %d\n", a.ID)
	}
	return nil
}
Пример #18
0
func getLastBlocks(c *gcli.Context) error {
	num := c.Args().First()
	if num == "" {
		num = "1"
	}

	n, err := strconv.ParseUint(num, 10, 64)
	if err != nil {
		return fmt.Errorf("invalid block number, %s", err)
	}

	if n <= 0 {
		return errors.New("block number must >= 0")
	}

	param := []uint64{n}
	req, err := webrpc.NewRequest("get_lastblocks", param, "1")
	if err != nil {
		return fmt.Errorf("do rpc request failed: %v", err)
	}

	rsp, err := webrpc.Do(req, cfg.RPCAddress)
	if err != nil {
		return err
	}

	if rsp.Error != nil {
		return fmt.Errorf("do rpc request failed: %+v", *rsp.Error)
	}

	fmt.Println(string(rsp.Result))
	return nil
}
Пример #19
0
func scheduledTasksCreateCmd(c *CLI, ctx *cli.Context) {
	usage := func(msg string) {
		fmt.Printf("Usage: %s scheduled-tasks create [--instance,--timezone] --name --schedule -- <executable> <arg-or-option>...\n", c.Name)
		fatal(msg)
	}
	if len(ctx.Args()) == 0 {
		usage("too few arguments")
	}
	if ctx.String("name") == "" {
		usage("--name not defined")
	}
	if ctx.String("schedule") == "" {
		usage("--schedule not defined")
	}
	api := c.GetAPIClient(ctx)
	instance := c.GetInstance(ctx, nil)
	name := ctx.String("name")
	schedule := ctx.String("schedule")
	timezone := ctx.String("timezone")
	command := strings.Join(ctx.Args(), " ")
	scheduledTask := gondor.ScheduledTask{
		Instance: instance.URL,
		Name:     &name,
		Schedule: &schedule,
		Timezone: &timezone,
		Command:  &command,
	}
	if err := api.ScheduledTasks.Create(&scheduledTask); err != nil {
		fatal(err.Error())
	}
	success(fmt.Sprintf("%s scheduled task has been created.", *scheduledTask.Name))
}
Пример #20
0
// ProjectLog gets services logs.
func ProjectLog(p project.APIProject, c *cli.Context) error {
	err := p.Log(context.Background(), c.Bool("follow"), c.Args()...)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
Пример #21
0
func (cmd *Config) Run(scope scope.Scope, c *cli.Context) {
	if err := net.VerifyLoginURL(cmd.network); err != nil {
		error_handler.ErrorExit(err)
	}
	if c.Args().Present() {
		configValue, err := entity_config.ConfigValue(cmd.network, scope.Application, scope.Entity, c.Args().First())

		if nil != err {
			error_handler.ErrorExit(err)
		}
		displayValue, err := stringRepresentation(configValue)
		if nil != err {
			error_handler.ErrorExit(err)
		}
		fmt.Println(displayValue)

	} else {
		config, err := entity_config.ConfigCurrentState(cmd.network, scope.Application, scope.Entity)
		if nil != err {
			error_handler.ErrorExit(err)
		}
		table := terminal.NewTable([]string{"Key", "Value"})
		for key, value := range config {
			table.Add(key, fmt.Sprintf("%v", value))
		}
		table.Print()
	}
}
Пример #22
0
// ProjectPull pulls images for services.
func ProjectPull(p project.APIProject, c *cli.Context) error {
	err := p.Pull(context.Background(), c.Args()...)
	if err != nil && !c.Bool("ignore-pull-failures") {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
Пример #23
0
func before(c *cli.Context) error {
	// Log level
	if logLevel, err := log.ParseLevel(c.String(LogLevelKey)); err != nil {
		log.Fatal("Failed to parse log level:", err)
	} else {
		log.SetLevel(logLevel)
	}

	if len(c.Args()) != 0 && c.Args().First() != "version" && !c.Bool(HelpKey) && !c.Bool(VersionKey) {
		if err := MachineWorkdir.Set(c.String(WorkdirKey)); err != nil {
			log.Fatalf("Failed to set MachineWorkdir: %s", err)
		}
		if MachineWorkdir.String() == "" {
			log.Fatalln("No Workdir specified!")
		}
	}
	MachineWorkdir.Freeze()

	if err := MachineConfigTypeID.Set(c.String(ConfigTypeIDParamKey)); err != nil {
		log.Fatalf("Failed to set MachineConfigTypeID: %s", err)
	}
	log.Debugf("MachineConfigTypeID: %s", MachineConfigTypeID)

	if err := MachineParamsAdditionalEnvs.Set(c.StringSlice(EnvironmentParamKey)); err != nil {
		log.Fatalf("Failed to set MachineParamsAdditionalEnvs: %s", err)
	}
	log.Debugf("MachineParamsAdditionalEnvs: %s", MachineParamsAdditionalEnvs)
	MachineParamsAdditionalEnvs.Freeze()

	return nil
}
Пример #24
0
// ProjectKill forces stop service containers.
func ProjectKill(p project.APIProject, c *cli.Context) error {
	err := p.Kill(context.Background(), c.String("signal"), c.Args()...)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
Пример #25
0
func startContainer(context *cli.Context, spec *specs.Spec, create bool) (int, error) {
	id := context.Args().First()
	if id == "" {
		return -1, errEmptyID
	}
	container, err := createContainer(context, id, spec)
	if err != nil {
		return -1, err
	}
	// Support on-demand socket activation by passing file descriptors into the container init process.
	listenFDs := []*os.File{}
	if os.Getenv("LISTEN_FDS") != "" {
		listenFDs = activation.Files(false)
	}
	r := &runner{
		enableSubreaper: !context.Bool("no-subreaper"),
		shouldDestroy:   true,
		container:       container,
		listenFDs:       listenFDs,
		console:         context.String("console"),
		detach:          context.Bool("detach"),
		pidFile:         context.String("pid-file"),
		create:          create,
	}
	return r.run(&spec.Process)
}
Пример #26
0
// ProjectUnpause unpauses service containers.
func ProjectUnpause(p project.APIProject, c *cli.Context) error {
	err := p.Unpause(context.Background(), c.Args()...)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
Пример #27
0
func runUpdate(c *cli.Context) error {
	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 nil
	}

	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)
	}

	return nil
}
Пример #28
0
// ProjectStop stops all services.
func ProjectStop(p project.APIProject, c *cli.Context) error {
	err := p.Stop(context.Background(), c.Int("timeout"), c.Args()...)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
Пример #29
0
func newAddress(ctx *cli.Context) error {
	client := getClient(ctx)

	stringAddrType := ctx.Args().Get(0)

	// Map the string encoded address type, to the concrete typed address
	// type enum. An unrecognized address type will result in an error.
	var addrType lnrpc.NewAddressRequest_AddressType
	switch stringAddrType { // TODO(roasbeef): make them ints on the cli?
	case "p2wkh":
		addrType = lnrpc.NewAddressRequest_WITNESS_PUBKEY_HASH
	case "np2wkh":
		addrType = lnrpc.NewAddressRequest_NESTED_PUBKEY_HASH
	case "p2pkh":
		addrType = lnrpc.NewAddressRequest_PUBKEY_HASH
	default:
		return fmt.Errorf("invalid address type %v, support address type "+
			"are: p2wkh, np2wkh, p2pkh", stringAddrType)
	}

	ctxb := context.Background()
	addr, err := client.NewAddress(ctxb, &lnrpc.NewAddressRequest{
		Type: addrType,
	})
	if err != nil {
		return err
	}

	printRespJson(addr)
	return nil
}
Пример #30
0
// ListCommand lists Notes
func ListCommand(c *cli.Context, i storage.Impl) (rnotes []string) {
	nName := strings.Join(c.Args(), " ")
	notes := i.ListNotes(nName)

	return FormatNoteList(notes)

}