Example #1
0
func loadPlugin(ctx *cli.Context) {
	pAsc := ctx.String("plugin-asc")
	var paths []string
	if len(ctx.Args()) != 1 {
		fmt.Println("Incorrect usage:")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		os.Exit(1)
	}
	paths = append(paths, ctx.Args().First())
	if pAsc != "" {
		if !strings.Contains(pAsc, ".asc") {
			fmt.Println("Must be a .asc file for the -a flag")
			cli.ShowCommandHelp(ctx, ctx.Command.Name)
			os.Exit(1)
		}
		paths = append(paths, pAsc)
	}
	r := pClient.LoadPlugin(paths)
	if r.Err != nil {
		if r.Err.Fields()["error"] != nil {
			fmt.Printf("Error loading plugin:\n%v\n%v\n", r.Err.Error(), r.Err.Fields()["error"])
		} else {
			fmt.Printf("Error loading plugin:\n%v\n", r.Err.Error())
		}
		os.Exit(1)
	}
	for _, p := range r.LoadedPlugins {
		fmt.Println("Plugin loaded")
		fmt.Printf("Name: %s\n", p.Name)
		fmt.Printf("Version: %d\n", p.Version)
		fmt.Printf("Type: %s\n", p.Type)
		fmt.Printf("Signed: %v\n", p.Signed)
		fmt.Printf("Loaded Time: %s\n\n", p.LoadedTime().Format(timeFormat))
	}
}
Example #2
0
func cmdServer(ctx *cli.Context) {
	c, err := config.GetConfiguration(ctx)
	if err != nil {
		cli.ShowCommandHelp(ctx, "server")
		fmt.Println("Could not get configuration. Reason:", err)
		log.Fatalln("Exiting....")
	}

	if ctx.String("port") == "" {
		cli.ShowCommandHelp(ctx, "server")
		fmt.Println("Missing port")
		log.Fatalln("Exiting....")
	}

	executor := execution.NewExecutor(c.AggregateOutput, c.FailuresOnly, c.StateChangeOnly, c.ResultFormatter(), c.Writer(), c.Workers)

	asrt := NewAsrtHandler(c, executor)
	asrt.refreshServerCache()
	go asrt.loopServerCacheRefresh()

	http.Handle("/data", asrt)
	http.HandleFunc("/", serveStaticWebFiles)

	fmt.Println("Listening on port:", ctx.String("port"))
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", ctx.String("port")), nil))
}
Example #3
0
func cliDeleteRevNat(ctx *cli.Context) {
	if ctx.Bool("all") {
		if err := client.RevNATDeleteAll(); err != nil {
			fmt.Fprintf(os.Stderr, "%s", err)
			os.Exit(1)
		}
	} else {
		if len(ctx.Args()) == 0 {
			cli.ShowCommandHelp(ctx, "delete-rev-nat")
			os.Exit(1)
		}

		id, err := strconv.ParseUint(ctx.Args().Get(0), 10, 16)
		if err != nil {
			cli.ShowCommandHelp(ctx, "delete-rev-nat")
			os.Exit(1)
		}

		if err := client.RevNATDelete(types.ServiceID(id)); err != nil {
			fmt.Fprintf(os.Stderr, "%s\n", err)
			os.Exit(1)
		}
	}
	fmt.Printf("Successfully deleted\n")
}
Example #4
0
func oci2docker(c *cli.Context) {
	ociPath := c.String("oci-bundle")
	imgName := c.String("image-name")
	port := c.String("port")

	if ociPath == "" {
		cli.ShowCommandHelp(c, "convert")
		return
	}

	if imgName == "" {
		cli.ShowCommandHelp(c, "convert")
		return
	}

	_, err := os.Stat(ociPath)
	if os.IsNotExist(err) {
		cli.ShowCommandHelp(c, "convert")
		return
	}

	convert.RunOCI2Docker(ociPath, imgName, port)

	return
}
Example #5
0
File: main.go Project: whawty/auth
func cmdSetAdmin(c *cli.Context) error {
	s, err := openAndCheck(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 3)
	}

	username := c.Args().First()
	if username == "" {
		cli.ShowCommandHelp(c, "set-admin")
		return cli.NewExitError("", 0)
	}

	isAdmin, err := strconv.ParseBool(c.Args().Get(1))
	if err != nil {
		cli.ShowCommandHelp(c, "set-admin")
		return cli.NewExitError("", 0)
	}

	if err := s.GetInterface().SetAdmin(username, isAdmin); err != nil {
		return cli.NewExitError(fmt.Sprintf("Error changing admin status of user '%s': %s", username, err), 3)
	}

	if isAdmin {
		return cli.NewExitError(fmt.Sprintf("user '%s' is now an admin!", username), 0)
	} else {
		return cli.NewExitError(fmt.Sprintf("user '%s' is now a normal user!", username), 0)
	}
}
Example #6
0
func getClientCredentials(c *cli.Context) []string {
	credentials := []string{c.GlobalString("client-id"), c.GlobalString("client-secret")}

	if credentials[0] == "" || credentials[1] == "" {
		color.Yellow("No client credentials given. Fallback to builtin default...")
		color.Yellow("Keep in mind that your document might be visible to other users.")
		color.Yellow("Your unique user-id is the only secret to protect your data.\n\n")

		superSecretSecret := []byte("V;4nJvuANmoywKNYk.yewNhqwmAQctc3BvByxeozQVpiK")

		// Decode HEX default credentials
		credentialsBytes, err := hex.DecodeString(defaultClientCredentials)
		if err != nil {
			color.Red("Error: client-id and client-secret missing and fallback decoding (step 1) failed: %s\n\n", err)
			cli.ShowCommandHelp(c, c.Command.FullName())
			os.Exit(1)
		}

		decodedCredentials := strings.Split(string(xorBytes(credentialsBytes, superSecretSecret)), ":")

		if len(decodedCredentials) < 2 {
			color.Red("Error: client-id and client-secret missing and fallback decoding (step 2) failed: %s\n\n", err)
			cli.ShowCommandHelp(c, c.Command.FullName())
			os.Exit(1)
		}
		credentials = decodedCredentials
	}

	return credentials
}
Example #7
0
func unloadPlugin(ctx *cli.Context) {
	pType := ctx.String("plugin-type")
	pName := ctx.String("plugin-name")
	pVer := ctx.Int("plugin-version")
	if pName == "" {
		fmt.Println("Must provide plugin name")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		os.Exit(1)
	}
	if pVer < 1 {
		fmt.Println("Must provide plugin version")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		os.Exit(1)
	}

	r := pClient.UnloadPlugin(pType, pName, pVer)
	if r.Err != nil {
		fmt.Printf("Error unloading plugin:\n%v\n", r.Err.Error())
		os.Exit(1)
	}

	fmt.Println("Plugin unloaded")
	fmt.Printf("Name: %s\n", r.Name)
	fmt.Printf("Version: %d\n", r.Version)
	fmt.Printf("Type: %s\n", r.Type)
}
Example #8
0
func getConfig(ctx *cli.Context) {
	pDetails := filepath.SplitList(ctx.Args().First())
	var ptyp string
	var pname string
	var pver int
	var err error

	if len(pDetails) == 3 {
		ptyp = pDetails[0]
		pname = pDetails[1]
		pver, err = strconv.Atoi(pDetails[2])
		if err != nil {
			fmt.Println("Can't convert version string to integer")
			cli.ShowCommandHelp(ctx, ctx.Command.Name)
			os.Exit(1)
		}
	} else {
		ptyp = ctx.String("plugin-type")
		pname = ctx.String("plugin-name")
		pver = ctx.Int("plugin-version")
	}

	if ptyp == "" {
		fmt.Println("Must provide plugin type")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		os.Exit(1)
	}
	if pname == "" {
		fmt.Println("Must provide plugin name")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		os.Exit(1)
	}
	if pver < 1 {
		fmt.Println("Must provide plugin version")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		os.Exit(1)
	}
	w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
	defer w.Flush()
	printFields(w, false, 0,
		"NAME",
		"VALUE",
		"TYPE",
	)
	r := pClient.GetPluginConfig(ptyp, pname, strconv.Itoa(pver))
	for k, v := range r.Table() {
		switch t := v.(type) {
		case ctypes.ConfigValueInt:
			printFields(w, false, 0, k, t.Value, t.Type())
		case ctypes.ConfigValueBool:
			printFields(w, false, 0, k, t.Value, t.Type())
		case ctypes.ConfigValueFloat:
			printFields(w, false, 0, k, t.Value, t.Type())
		case ctypes.ConfigValueStr:
			printFields(w, false, 0, k, t.Value, t.Type())
		}
	}
}
Example #9
0
File: gini.go Project: gini/gapicmd
func uploadDocument(c *cli.Context) {
	filename := c.String("filename")
	doctype := c.String("doctype")
	userid := getUserIdentifier(c)

	if len(c.Args()) < 1 {
		cli.ShowCommandHelp(c, c.Command.FullName())
		return
	}

	if _, err := os.Stat(c.Args().First()); os.IsNotExist(err) {
		color.Red("\nError: cannot find %s\n\n", c.Args().First())
		cli.ShowCommandHelp(c, c.Command.FullName())
		return
	}

	bodyBuf, err := os.Open(c.Args().First())
	if err != nil {
		color.Red("\nError: failed to read %s\n\n", c.Args().First())
		cli.ShowCommandHelp(c, c.Command.FullName())
		return
	}

	api := getApiClient(c)

	doc, err := api.Upload(bodyBuf, giniapi.UploadOptions{
		FileName:       filename,
		DocType:        doctype,
		UserIdentifier: userid,
	})

	if err != nil {
		color.Red("\nError: %s\n\n", err)
		return
	}

	done <- true
	wg.Wait()

	renderResults(doc)

	if c.GlobalBool("curl") {
		curl := curlData{
			Headers: map[string]string{
				"Accept":            "application/vnd.gini.v1+json",
				"X-User-Identifier": userid,
			},
			Body:   fmt.Sprintf("--data-binary '@%s'", c.Args().First()),
			URL:    fmt.Sprintf("%s/documents", api.Endpoints.API),
			Method: "POST",
		}

		curl.render(c)
	}
}
Example #10
0
func doUpdate(c *cli.Context) {
	conffile := c.GlobalString("conf")
	argHostIDs := c.Args()
	optName := c.String("name")
	optStatus := c.String("status")
	optRoleFullnames := c.StringSlice("roleFullname")

	if len(argHostIDs) < 1 {
		argHostIDs = make([]string, 1)
		if argHostIDs[0] = LoadHostIDFromConfig(conffile); argHostIDs[0] == "" {
			cli.ShowCommandHelp(c, "update")
			os.Exit(1)
		}
	}

	needUpdateHostStatus := optStatus != ""
	needUpdateHost := (optName != "" || len(optRoleFullnames) > 0)

	if !needUpdateHostStatus && !needUpdateHost {
		cli.ShowCommandHelp(c, "update")
		os.Exit(1)
	}

	client := newMackerel(conffile)

	var wg sync.WaitGroup
	for _, hostID := range argHostIDs {
		wg.Add(1)
		go func(hostID string) {
			defer wg.Done()

			if needUpdateHostStatus {
				err := client.UpdateHostStatus(hostID, optStatus)
				logger.DieIf(err)
			}

			if needUpdateHost {
				_, err := client.UpdateHost(hostID, &mkr.UpdateHostParam{
					Name:          optName,
					RoleFullnames: optRoleFullnames,
				})
				logger.DieIf(err)
			}

			logger.Log("updated", hostID)
		}(hostID)
	}

	wg.Wait()
}
Example #11
0
func unloadPlugin(ctx *cli.Context) error {
	pDetails := filepath.SplitList(ctx.Args().First())
	var pType, pName string
	var pVer int
	var err error

	if len(pDetails) == 3 {
		pType = pDetails[0]
		pName = pDetails[1]
		pVer, err = strconv.Atoi(pDetails[2])
		if err != nil {
			fmt.Println("Can't convert version string to integer")
			cli.ShowCommandHelp(ctx, ctx.Command.Name)
			return errCritical
		}
	} else {
		pType = ctx.String("plugin-type")
		pName = ctx.String("plugin-name")
		pVer = ctx.Int("plugin-version")
	}
	if pType == "" {
		fmt.Println("Must provide plugin type")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		return errCritical
	}
	if pName == "" {
		fmt.Println("Must provide plugin name")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		return errCritical
	}
	if pVer < 1 {
		fmt.Println("Must provide plugin version")
		cli.ShowCommandHelp(ctx, ctx.Command.Name)
		return errCritical
	}

	r := pClient.UnloadPlugin(pType, pName, pVer)
	if r.Err != nil {
		fmt.Printf("Error unloading plugin:\n%v\n", r.Err.Error())
		return errCritical
	}

	fmt.Println("Plugin unloaded")
	fmt.Printf("Name: %s\n", r.Name)
	fmt.Printf("Version: %d\n", r.Version)
	fmt.Printf("Type: %s\n", r.Type)

	return nil
}
Example #12
0
func main() {
	app := cli.NewApp()
	app.Name = "spiff"
	app.Usage = "BOSH deployment manifest toolkit"
	app.Version = "1.0.8dev"

	app.Commands = []cli.Command{
		{
			Name:      "merge",
			ShortName: "m",
			Usage:     "merge stub files into a manifest template",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "debug",
					Usage: "print state info",
				},
			},
			Action: func(c *cli.Context) {
				if len(c.Args()) < 1 {
					cli.ShowCommandHelp(c, "merge")
					os.Exit(1)
				}
				debug.DebugFlag = c.Bool("debug")
				merge(c.Args()[0], c.Args()[1:])
			},
		},
		{
			Name:      "diff",
			ShortName: "d",
			Usage:     "structurally compare two YAML files",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "separator",
					Usage: "separator to print between diffs",
				},
			},
			Action: func(c *cli.Context) {
				if len(c.Args()) < 2 {
					cli.ShowCommandHelp(c, "diff")
					os.Exit(1)
				}

				diff(c.Args()[0], c.Args()[1], c.String("separator"))
			},
		},
	}

	app.Run(os.Args)
}
Example #13
0
File: ui.go Project: raghulsid/cli
func (c *terminalUI) FailWithUsage(context *cli.Context) {
	c.Say(FailureColor(T("FAILED")))
	c.Say(T("Incorrect Usage.\n"))
	cli.ShowCommandHelp(context, context.Command.Name)
	c.Say("")
	os.Exit(1)
}
Example #14
0
func doGet(c *cli.Context) {
	argURL := c.Args().Get(0)
	doUpdate := c.Bool("update")

	if argURL == "" {
		cli.ShowCommandHelp(c, "get")
		os.Exit(1)
	}

	url, err := url.Parse(argURL)
	utils.DieIf(err)

	if !url.IsAbs() {
		url.Scheme = "https"
		url.Host = "github.com"
		if url.Path[0] != '/' {
			url.Path = "/" + url.Path
		}
	}

	remote, err := NewRemoteRepository(url)
	utils.DieIf(err)

	if remote.IsValid() == false {
		utils.Log("error", fmt.Sprintf("Not a valid repository: %s", url))
		os.Exit(1)
	}

	getRemoteRepository(remote, doUpdate)
}
Example #15
0
func (c *ServicedCli) cmdSquash(ctx *cli.Context) {

	imageName := ""
	baseLayer := ""
	newName := ""
	args := ctx.Args()
	switch len(ctx.Args()) {
	case 3:
		newName = args[2]
		fallthrough
	case 2:
		baseLayer = args[1]
		fallthrough
	case 1:
		imageName = args[0]
		break
	default:
		cli.ShowCommandHelp(ctx, "squash")
		return
	}

	imageID, err := c.driver.Squash(imageName, baseLayer, newName, ctx.String("tempdir"))
	if err != nil {
		glog.Fatalf("error squashing: %s", err)
	}
	fmt.Println(imageID)
}
Example #16
0
func cmdScp(c *cli.Context) {
	args := c.Args()
	if len(args) != 2 {
		cli.ShowCommandHelp(c, "scp")
		log.Fatal("Improper number of arguments.")
	}

	// TODO: Check that "-3" flag is available in user's version of scp.
	// It is on every system I've checked, but the manual mentioned it's "newer"
	sshArgs := append(baseSSHArgs, "-3")

	if c.Bool("recursive") {
		sshArgs = append(sshArgs, "-r")
	}

	src := args[0]
	dest := args[1]

	store := getStore(c)
	cmd, err := getScpCmd(src, dest, sshArgs, store)

	if err != nil {
		log.Fatal(err)
	}
	if err := runCmdWithStdIo(*cmd); err != nil {
		log.Fatal(err)
	}
}
Example #17
0
func doGet(c *cli.Context) {
	argURL := c.Args().Get(0)
	branch := c.String("branch")
	doUpdate := c.Bool("update")
	isShallow := c.Bool("shallow")
	isRecursive := c.Bool("recursive")

	if argURL == "" {
		cli.ShowCommandHelp(c, "get")
		os.Exit(1)
	}

	if isShallow && isRecursive {
		utils.Log("error", "Cannot specify both --shallow and --recursive options")
		os.Exit(1)
	}

	// If argURL is a "./foo" or "../bar" form,
	// find repository name trailing after github.com/USER/.
	parts := strings.Split(argURL, string(filepath.Separator))
	if parts[0] == "." || parts[0] == ".." {
		if wd, err := os.Getwd(); err == nil {
			path := filepath.Clean(filepath.Join(wd, filepath.Join(parts...)))

			var repoPath string
			for _, r := range localRepositoryRoots() {
				p := strings.TrimPrefix(path, r+string(filepath.Separator))
				if p != path && (repoPath == "" || len(p) < len(repoPath)) {
					repoPath = p
				}
			}

			if repoPath != "" {
				// Guess it
				utils.Log("resolved", fmt.Sprintf("relative %q to %q", argURL, "https://"+repoPath))
				argURL = "https://" + repoPath
			}
		}
	}

	url, err := NewURL(argURL)
	utils.DieIf(err)

	isSSH := c.Bool("p")
	if isSSH {
		// Assume Git repository if `-p` is given.
		url, err = ConvertGitURLHTTPToSSH(url)
		utils.DieIf(err)
	}

	remote, err := NewRemoteRepository(url)
	utils.DieIf(err)

	if remote.IsValid() == false {
		utils.Log("error", fmt.Sprintf("Not a valid repository: %s", url))
		os.Exit(1)
	}

	getRemoteRepository(remote, branch, doUpdate, isShallow, isRecursive)
}
Example #18
0
File: main.go Project: whawty/auth
func cmdInit(c *cli.Context) error {
	username := c.Args().First()
	if username == "" {
		cli.ShowCommandHelp(c, "init")
		return cli.NewExitError("", 0)
	}

	password := c.Args().Get(1)
	if password == "" {
		pwd, err := askPass()
		if err != nil {
			if err != gopass.ErrInterrupted {
				return cli.NewExitError(err.Error(), 2)
			}
			return cli.NewExitError("", 2)
		}
		password = pwd
	}

	s, err := NewStore(c.GlobalString("store"), c.GlobalString("do-upgrades"),
		c.GlobalString("policy-type"), c.GlobalString("policy-condition"), c.GlobalString("hooks-dir"))
	if err != nil {
		return cli.NewExitError(fmt.Sprintf("Error initializing whawty store: %s", err), 3)
	}
	if err := s.GetInterface().Init(username, password); err != nil {
		return cli.NewExitError(fmt.Sprintf("Error initializing whawty store: %s", err), 3)
	}
	return cli.NewExitError(fmt.Sprintf("whawty store successfully initialized!"), 0)
}
Example #19
0
// remove untagged images
func removeImages(c *cli.Context) {
	dry := c.Bool("dry")
	untagged := c.Bool("untagged")

	if !untagged {
		cli.ShowCommandHelp(c, "rmi")
		fmt.Println("EXAMPLE:")
		fmt.Println("   command rmi --untagged")
		return
	}

	ctx := getUtilContext()
	if ctx == nil {
		return
	}

	ctx = getUtilContext()
	if ctx == nil {
		return
	}

	if untagged == true {
		ctx.RemoveUntaggedDockerImages(dry)
	}
	return
}
Example #20
0
func showError(ctx *cli.Context, err error) {
	fmt.Fprintf(ctx.App.Writer, "ERROR: %s\n\n", err.Error())

	fmt.Println(errors.Wrap(err, 0).ErrorStack())

	cli.ShowCommandHelp(ctx, ctx.Command.Name)
}
Example #21
0
func remove(c *cli.Context) {
	if len(c.Args()) != 1 {
		cli.ShowCommandHelp(c, "remove")
		fatalErrorf("Expected exactly 1 argument instead of %d", len(c.Args()))
	}

	project, err := godm.NewLocalProject(path.Dir(os.Args[0]), "")
	if err != nil {
		fatalErrorf("Error building the current project : %s", err.Error())
	}
	Log.Debug("Project's Type : %T", project, project.GetBaseDir())
	Log.Debug("Project's Base Dir : %s", project.GetBaseDir())

	importPath := c.Args().First()

	err = project.RemoveVendor(importPath)

	if err == godm.ErrUnknownVendor {
		Log.Warning("Import path %q cannot be removed from vendors because it is not vendored in current project", importPath)
		return
	} else if err != nil {
		fatalErrorf("Error removing import path %q from vendors : %s", importPath, err.Error())
	}
	Log.Notice("%q removed from vendors", importPath)
}
Example #22
0
func cliLookupService(ctx *cli.Context) {
	if len(ctx.Args()) == 0 {
		cli.ShowCommandHelp(ctx, "get-service")
		os.Exit(1)
	}
	key := parseServiceKey(ctx.Args().Get(0))

	lbSVC, err := client.SVCGet(*key)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to receive service from daemon: %s\n", err)
		os.Exit(1)
	}
	if lbSVC == nil {
		fmt.Fprintf(os.Stderr, "Entry not found \n")
		os.Exit(1)
	}

	besSlice := []string{}
	for _, revNat := range lbSVC.BES {
		besSlice = append(besSlice, revNat.String())
	}

	fmt.Printf("%s =>\n", key.String())
	for i, svcBackend := range besSlice {
		fmt.Printf("\t\t%d => %s (%d)\n", i+1, svcBackend, lbSVC.FE.ID)
	}
}
Example #23
0
func cmdValidate(c *cli.Context) {

	processFlags(c)

	if fileLocation == "" {
		cli.ShowCommandHelp(c, "create")
		log.Fatal("You must specify a configuration file to use")
	}

	log.Infof("Config file %s", fileLocation)

	file, e := ioutil.ReadFile(fileLocation)
	if e != nil {
		fmt.Printf("File error: %v\n", e)
		os.Exit(1)
	}

	jsontype := providers.JSONObject{}
	json.Unmarshal(file, &jsontype)

	log.Info("*********************************************************************************")
	log.Info("** Loading configuration file " + fileLocation)
	log.Info("*********************************************************************************")

	log.Info("Configuration for environment " + jsontype.Provider.ProviderConfig.Aws.Vpc.Name)
	log.Info("Environment has " + strconv.Itoa(len(jsontype.Containers)) + " servers defined")

	//Validate Provider document using JSONSchema
	validated, validateErrors := vmproviders.ValidateDocument()
	if validated {
		log.Info("Successfully validated provider configuration")
	} else {
		log.Error("Error validating provider configuration %v", validateErrors)
	}

	homedir := os.Getenv("HOME")

	creds := credentials.NewSharedCredentials(homedir+"/.aws/credentials", profile)

	credValue, err := creds.Get()
	if err != nil {
		fmt.Printf("Credential token= %v\n", credValue)
		fmt.Println(err)
		os.Exit(1)
	}

	ec2client := vmproviders.GetEC2Client(creds, "us-east-1")

	validateSuccess, validateWarnings, validateErr := vmproviders.Validate(ec2client, &jsontype)
	if validateSuccess {
		log.Infof("Successfully validated environment %v", jsontype.Provider.ProviderConfig.Aws.Vpc.Name)
		for w := range validateWarnings {
			log.Warnf(validateWarnings[w])
		}
	} else {
		for e := range validateErr {
			log.Errorf(validateErr[e].Error())
		}
	}
}
Example #24
0
File: gen.go Project: rendon/cf
func gen(c *cli.Context) {
	if len(c.Args()) != 1 {
		cli.ShowCommandHelp(c, "gen")
		return
	}
	var srcFile = c.Args()[0]
	if err := GenerateSampleSolution(srcFile); err != nil {
		log.Fatalf("Failed to generate sample solution: %s", err)
	}

	// At this point we know srcFile contains a valid extension
	ext := filepath.Ext(srcFile)[1:]
	settings, err := ReadKeyValueYamlFile(".settings.yml")
	if err != nil {
		log.Printf("Failed to read settings file: %s\n", err)
		settings = make(map[string]interface{})
	}
	settings["lang"] = ext
	settings["src_file"] = filepath.Base(srcFile)
	settingsFile := ".settings.yml"
	if dir := filepath.Dir(srcFile); dir != "" {
		settingsFile = dir + "/" + settingsFile
	}
	if err = WriteKeyValueYamlFile(settingsFile, settings); err != nil {
		log.Printf("Failed to write settings file: %s\n", err)
	}

}
func showError(c *cli.Context, err error) error {
	fmt.Println("ERROR: ")
	fmt.Println(err.Error())
	fmt.Println("")
	cli.ShowCommandHelp(c, c.Command.Name)
	return err
}
Example #26
0
File: list.go Project: Cretezy/fddp
func ListAction(c *cli.Context) {
	// Figure out input
	if len(c.Args()) < 1 {
		cli.ShowCommandHelp(c, c.Command.Name)
		return
	}

	jsonFile := c.Args()[0]

	data := FromJSON(GetFileContent(jsonFile))

	count := c.Int("count")

	threads := data.Threads

	if count > len(threads) {
		count = len(threads)
	}

	// Sort by message count
	sort.Sort(ByMessage(threads))

	// Reverse (top = more)
	for i, j := 0, len(threads)-1; i < j; i, j = i+1, j-1 {
		threads[i], threads[j] = threads[j], threads[i]
	}

	threads = threads[:count]

	for _, thread := range threads {
		fmt.Println(strings.Join(DeleteElementFromSlice(thread.Persons, data.WhoAmI), ", ")+" > Messages:", thread.CountMessages(), "Words:", thread.CountWords())
	}
}
Example #27
0
func GenerateSignature(c *cli.Context) {
	url := c.String("url")

	if url == "" {
		cli.ShowCommandHelp(c, "generate")
		os.Exit(1)
	}

	crypto, err := common.CreateCrypto(c)
	if err != nil {
		os.Exit(1)
	}

	signature, err := createSigFromArgs(c)
	if err != nil {
		os.Exit(1)
	}

	sigEncoded, metaEncoded, err := route_service.BuildSignatureAndMetadata(crypto, &signature)
	if err != nil {
		fmt.Printf("Failed to create signature: %s", err.Error())
		os.Exit(1)
	}

	fmt.Printf("Encoded Signature:\n%s\n\n", sigEncoded)
	fmt.Printf("Encoded Metadata:\n%s\n\n", metaEncoded)
}
Example #28
0
File: main.go Project: whawty/auth
func cmdUpdate(c *cli.Context) error {
	s, err := openAndCheck(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 3)
	}

	username := c.Args().First()
	if username == "" {
		cli.ShowCommandHelp(c, "update")
		return cli.NewExitError("", 0)
	}

	password := c.Args().Get(1)
	if password == "" {
		pwd, err := askPass()
		if err != nil {
			if err != gopass.ErrInterrupted {
				return cli.NewExitError(err.Error(), 2)
			}
			return cli.NewExitError("", 2)
		}
		password = pwd
	}

	if err := s.GetInterface().Update(username, password); err != nil {
		return cli.NewExitError(fmt.Sprintf("Error updating user '%s': %s", username, err), 3)
	}
	return cli.NewExitError(fmt.Sprintf("user '%s' successfully updated!", username), 0)
}
Example #29
0
File: ui.go Project: knolleary/cli
func (c terminalUI) FailWithUsage(ctxt *cli.Context, cmdName string) {
	c.Say(FailureColor("FAILED"))
	c.Say("Incorrect Usage.\n")
	cli.ShowCommandHelp(ctxt, cmdName)
	c.Say("")
	os.Exit(1)
}
Example #30
0
// delete containers which are not running
func removeContainers(c *cli.Context) {
	dry := c.Bool("dry")
	exited := c.Bool("exited")
	hours := c.Int("hours")

	if !exited {
		cli.ShowCommandHelp(c, "rm")
		fmt.Println("EXAMPLE:")
		fmt.Println("   command rm --exited")
		return
	}
	if hours <= 0 {
		hours = 24
	}

	ctx := getUtilContext()
	if ctx == nil {
		return
	}

	if exited == true {
		ctx.DeleteExitedContainers(dry, hours)
	}

	return
}