예제 #1
0
파일: flag.go 프로젝트: yckrasnodar/docker
// PrintDefaults prints, to standard error unless configured
// otherwise, the default values of all defined flags in the set.
func (f *FlagSet) PrintDefaults() {
	writer := tabwriter.NewWriter(f.Out(), 20, 1, 3, ' ', 0)
	home := homedir.Get()

	// Don't substitute when HOME is /
	if runtime.GOOS != "windows" && home == "/" {
		home = ""
	}
	f.VisitAll(func(flag *Flag) {
		format := "  -%s=%s"
		names := []string{}
		for _, name := range flag.Names {
			if name[0] != '#' {
				names = append(names, name)
			}
		}
		if len(names) > 0 {
			val := flag.DefValue

			if home != "" && strings.HasPrefix(val, home) {
				val = homedir.GetShortcutString() + val[len(home):]
			}

			fmt.Fprintf(writer, format, strings.Join(names, ", -"), val)
			for i, line := range strings.Split(flag.Usage, "\n") {
				if i != 0 {
					line = "  " + line
				}
				fmt.Fprintln(writer, "\t", line)
			}
		}
	})
	writer.Flush()
}
예제 #2
0
파일: main.go 프로젝트: juliengk/pony
// preload initializes any global options and configuration
// before the main or sub commands are run
func preload(c *cli.Context) (err error) {
	if c.GlobalBool("debug") {
		logrus.SetLevel(logrus.DebugLevel)
	}

	defaultGPGKey = c.GlobalString("keyid")

	home := homedir.Get()
	homeShort := homedir.GetShortcutString()

	// set the filestore variable
	filestore = strings.Replace(c.GlobalString("file"), homeShort, home, 1)

	// set gpg path variables
	gpgPath = strings.Replace(c.GlobalString("gpgpath"), homeShort, home, 1)
	publicKeyring = filepath.Join(gpgPath, "pubring.gpg")
	secretKeyring = filepath.Join(gpgPath, "secring.gpg")

	// if they passed an arguement, run the prechecks
	// TODO(jfrazelle): this will run even if the command they issue
	// does not exist, which is kinda shitty
	if len(c.Args()) > 0 {
		preChecks()
	}

	// we need to read the secrets file for all commands
	// might as well be dry about it
	s, err = readSecretsFile(filestore)
	if err != nil {
		logrus.Fatal(err)
	}

	return nil
}
예제 #3
0
파일: flag.go 프로젝트: winsx/libnetwork
// PrintDefaults prints, to standard error unless configured
// otherwise, the default values of all defined flags in the set.
func (fs *FlagSet) PrintDefaults() {
	writer := tabwriter.NewWriter(fs.Out(), 20, 1, 3, ' ', 0)
	home := homedir.Get()

	// Don't substitute when HOME is /
	if runtime.GOOS != "windows" && home == "/" {
		home = ""
	}

	// Add a blank line between cmd description and list of options
	if fs.FlagCount() > 0 {
		fmt.Fprintln(writer, "")
	}

	fs.VisitAll(func(flag *Flag) {
		names := []string{}
		for _, name := range flag.Names {
			if name[0] != '#' {
				names = append(names, name)
			}
		}
		if len(names) > 0 && len(flag.Usage) > 0 {
			val := flag.DefValue

			if home != "" && strings.HasPrefix(val, home) {
				val = homedir.GetShortcutString() + val[len(home):]
			}

			if isZeroValue(val) {
				format := "  -%s"
				fmt.Fprintf(writer, format, strings.Join(names, ", -"))
			} else {
				format := "  -%s=%s"
				fmt.Fprintf(writer, format, strings.Join(names, ", -"), val)
			}
			for i, line := range strings.Split(flag.Usage, "\n") {
				if i != 0 {
					line = "  " + line
				}
				fmt.Fprintln(writer, "\t", line)
			}
		}
	})
	writer.Flush()
}
예제 #4
0
func (s *DockerSuite) TestHelpTextVerify(c *check.C) {
	testRequires(c, DaemonIsLinux)

	// Make sure main help text fits within 80 chars and that
	// on non-windows system we use ~ when possible (to shorten things).
	// Test for HOME set to its default value and set to "/" on linux
	// Yes on windows setting up an array and looping (right now) isn't
	// necessary because we just have one value, but we'll need the
	// array/loop on linux so we might as well set it up so that we can
	// test any number of home dirs later on and all we need to do is
	// modify the array - the rest of the testing infrastructure should work
	homes := []string{homedir.Get()}

	// Non-Windows machines need to test for this special case of $HOME
	if runtime.GOOS != "windows" {
		homes = append(homes, "/")
	}

	homeKey := homedir.Key()
	baseEnvs := appendBaseEnv(true)

	// Remove HOME env var from list so we can add a new value later.
	for i, env := range baseEnvs {
		if strings.HasPrefix(env, homeKey+"=") {
			baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...)
			break
		}
	}

	for _, home := range homes {

		// Dup baseEnvs and add our new HOME value
		newEnvs := make([]string, len(baseEnvs)+1)
		copy(newEnvs, baseEnvs)
		newEnvs[len(newEnvs)-1] = homeKey + "=" + home

		scanForHome := runtime.GOOS != "windows" && home != "/"

		// Check main help text to make sure its not over 80 chars
		helpCmd := exec.Command(dockerBinary, "help")
		helpCmd.Env = newEnvs
		out, _, err := runCommandWithOutput(helpCmd)
		c.Assert(err, checker.IsNil, check.Commentf(out))
		lines := strings.Split(out, "\n")
		foundTooLongLine := false
		for _, line := range lines {
			if !foundTooLongLine && len(line) > 80 {
				c.Logf("Line is too long:\n%s", line)
				foundTooLongLine = true
			}
			// All lines should not end with a space
			c.Assert(line, checker.Not(checker.HasSuffix), " ", check.Commentf("Line should not end with a space"))

			if scanForHome && strings.Contains(line, `=`+home) {
				c.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line)
			}
			if runtime.GOOS != "windows" {
				i := strings.Index(line, homedir.GetShortcutString())
				if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
					c.Fatalf("Main help should not have used home shortcut:\n%s", line)
				}
			}
		}

		// Make sure each cmd's help text fits within 90 chars and that
		// on non-windows system we use ~ when possible (to shorten things).
		// Pull the list of commands from the "Commands:" section of docker help
		helpCmd = exec.Command(dockerBinary, "help")
		helpCmd.Env = newEnvs
		out, _, err = runCommandWithOutput(helpCmd)
		c.Assert(err, checker.IsNil, check.Commentf(out))
		i := strings.Index(out, "Commands:")
		c.Assert(i, checker.GreaterOrEqualThan, 0, check.Commentf("Missing 'Commands:' in:\n%s", out))

		cmds := []string{}
		// Grab all chars starting at "Commands:"
		helpOut := strings.Split(out[i:], "\n")
		// First line is just "Commands:"
		if isLocalDaemon {
			// Replace first line with "daemon" command since it's not part of the list of commands.
			helpOut[0] = " daemon"
		} else {
			// Skip first line
			helpOut = helpOut[1:]
		}

		// Create the list of commands we want to test
		cmdsToTest := []string{}
		for _, cmd := range helpOut {
			// Stop on blank line or non-idented line
			if cmd == "" || !unicode.IsSpace(rune(cmd[0])) {
				break
			}

			// Grab just the first word of each line
			cmd = strings.Split(strings.TrimSpace(cmd), " ")[0]
			cmds = append(cmds, cmd) // Saving count for later

			cmdsToTest = append(cmdsToTest, cmd)
		}

		// Add some 'two word' commands - would be nice to automatically
		// calculate this list - somehow
		cmdsToTest = append(cmdsToTest, "volume create")
		cmdsToTest = append(cmdsToTest, "volume inspect")
		cmdsToTest = append(cmdsToTest, "volume ls")
		cmdsToTest = append(cmdsToTest, "volume rm")

		// Divide the list of commands into go routines and  run the func testcommand on the commands in parallel
		// to save runtime of test

		errChan := make(chan error)

		for index := 0; index < len(cmdsToTest); index++ {
			go func(index int) {
				errChan <- testCommand(cmdsToTest[index], newEnvs, scanForHome, home)
			}(index)
		}

		for index := 0; index < len(cmdsToTest); index++ {
			err := <-errChan
			if err != nil {
				c.Fatal(err)
			}
		}

		// Number of commands for standard release and experimental release
		standard := 41
		experimental := 1
		expected := standard + experimental
		if isLocalDaemon {
			expected++ // for the daemon command
		}
		c.Assert(len(cmds), checker.LessOrEqualThan, expected, check.Commentf("Wrong # of cmds, it should be: %d\nThe list:\n%q", expected, cmds))
	}

}
func TestHelpTextVerify(t *testing.T) {
	// Make sure main help text fits within 80 chars and that
	// on non-windows system we use ~ when possible (to shorten things).
	// Test for HOME set to its default value and set to "/" on linux
	// Yes on windows setting up an array and looping (right now) isn't
	// necessary because we just have one value, but we'll need the
	// array/loop on linux so we might as well set it up so that we can
	// test any number of home dirs later on and all we need to do is
	// modify the array - the rest of the testing infrastructure should work
	homes := []string{homedir.Get()}

	// Non-Windows machines need to test for this special case of $HOME
	if runtime.GOOS != "windows" {
		homes = append(homes, "/")
	}

	homeKey := homedir.Key()
	baseEnvs := os.Environ()

	// Remove HOME env var from list so we can add a new value later.
	for i, env := range baseEnvs {
		if strings.HasPrefix(env, homeKey+"=") {
			baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...)
			break
		}
	}

	for _, home := range homes {
		// Dup baseEnvs and add our new HOME value
		newEnvs := make([]string, len(baseEnvs)+1)
		copy(newEnvs, baseEnvs)
		newEnvs[len(newEnvs)-1] = homeKey + "=" + home

		scanForHome := runtime.GOOS != "windows" && home != "/"

		// Check main help text to make sure its not over 80 chars
		helpCmd := exec.Command(dockerBinary, "help")
		helpCmd.Env = newEnvs
		out, ec, err := runCommandWithOutput(helpCmd)
		if err != nil || ec != 0 {
			t.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec)
		}
		lines := strings.Split(out, "\n")
		for _, line := range lines {
			if len(line) > 80 {
				t.Fatalf("Line is too long(%d chars):\n%s", len(line), line)
			}

			// All lines should not end with a space
			if strings.HasSuffix(line, " ") {
				t.Fatalf("Line should not end with a space: %s", line)
			}

			if scanForHome && strings.Contains(line, `=`+home) {
				t.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line)
			}
			if runtime.GOOS != "windows" {
				i := strings.Index(line, homedir.GetShortcutString())
				if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
					t.Fatalf("Main help should not have used home shortcut:\n%s", line)
				}
			}
		}

		// Make sure each cmd's help text fits within 80 chars and that
		// on non-windows system we use ~ when possible (to shorten things).
		// Pull the list of commands from the "Commands:" section of docker help
		helpCmd = exec.Command(dockerBinary, "help")
		helpCmd.Env = newEnvs
		out, ec, err = runCommandWithOutput(helpCmd)
		if err != nil || ec != 0 {
			t.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec)
		}
		i := strings.Index(out, "Commands:")
		if i < 0 {
			t.Fatalf("Missing 'Commands:' in:\n%s", out)
		}

		// Grab all chars starting at "Commands:"
		// Skip first line, its "Commands:"
		cmds := []string{}
		for _, cmd := range strings.Split(out[i:], "\n")[1:] {
			// Stop on blank line or non-idented line
			if cmd == "" || !unicode.IsSpace(rune(cmd[0])) {
				break
			}

			// Grab just the first word of each line
			cmd = strings.Split(strings.TrimSpace(cmd), " ")[0]
			cmds = append(cmds, cmd)

			helpCmd := exec.Command(dockerBinary, cmd, "--help")
			helpCmd.Env = newEnvs
			out, ec, err := runCommandWithOutput(helpCmd)
			if err != nil || ec != 0 {
				t.Fatalf("Error on %q help: %s\nexit code:%d", cmd, out, ec)
			}
			lines := strings.Split(out, "\n")
			for _, line := range lines {
				if len(line) > 80 {
					t.Fatalf("Help for %q is too long(%d chars):\n%s", cmd,
						len(line), line)
				}

				if scanForHome && strings.Contains(line, `"`+home) {
					t.Fatalf("Help for %q should use ~ instead of %q on:\n%s",
						cmd, home, line)
				}
				i := strings.Index(line, "~")
				if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
					t.Fatalf("Help for %q should not have used ~:\n%s", cmd, line)
				}

				// If a line starts with 4 spaces then assume someone
				// added a multi-line description for an option and we need
				// to flag it
				if strings.HasPrefix(line, "    ") {
					t.Fatalf("Help for %q should not have a multi-line option: %s", cmd, line)
				}

				// Options should NOT end with a period
				if strings.HasPrefix(line, "  -") && strings.HasSuffix(line, ".") {
					t.Fatalf("Help for %q should not end with a period: %s", cmd, line)
				}

				// Options should NOT end with a space
				if strings.HasSuffix(line, " ") {
					t.Fatalf("Help for %q should not end with a space: %s", cmd, line)
				}

			}
		}

		expected := 39
		if len(cmds) != expected {
			t.Fatalf("Wrong # of cmds(%d), it should be: %d\nThe list:\n%q",
				len(cmds), expected, cmds)
		}
	}

	logDone("help - verify text")
}
예제 #6
0
func (s *DockerSuite) TestHelpTextVerify(c *check.C) {
	testRequires(c, DaemonIsLinux)
	// Make sure main help text fits within 80 chars and that
	// on non-windows system we use ~ when possible (to shorten things).
	// Test for HOME set to its default value and set to "/" on linux
	// Yes on windows setting up an array and looping (right now) isn't
	// necessary because we just have one value, but we'll need the
	// array/loop on linux so we might as well set it up so that we can
	// test any number of home dirs later on and all we need to do is
	// modify the array - the rest of the testing infrastructure should work
	homes := []string{homedir.Get()}

	// Non-Windows machines need to test for this special case of $HOME
	if runtime.GOOS != "windows" {
		homes = append(homes, "/")
	}

	homeKey := homedir.Key()
	baseEnvs := os.Environ()

	// Remove HOME env var from list so we can add a new value later.
	for i, env := range baseEnvs {
		if strings.HasPrefix(env, homeKey+"=") {
			baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...)
			break
		}
	}

	for _, home := range homes {
		// Dup baseEnvs and add our new HOME value
		newEnvs := make([]string, len(baseEnvs)+1)
		copy(newEnvs, baseEnvs)
		newEnvs[len(newEnvs)-1] = homeKey + "=" + home

		scanForHome := runtime.GOOS != "windows" && home != "/"

		// Check main help text to make sure its not over 80 chars
		helpCmd := exec.Command(dockerBinary, "help")
		helpCmd.Env = newEnvs
		out, _, err := runCommandWithOutput(helpCmd)
		c.Assert(err, checker.IsNil, check.Commentf(out))
		lines := strings.Split(out, "\n")
		for _, line := range lines {
			c.Assert(len(line), checker.LessOrEqualThan, 80, check.Commentf("Line is too long:\n%s", line))

			// All lines should not end with a space
			c.Assert(line, checker.Not(checker.HasSuffix), " ", check.Commentf("Line should not end with a space"))

			if scanForHome && strings.Contains(line, `=`+home) {
				c.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line)
			}
			if runtime.GOOS != "windows" {
				i := strings.Index(line, homedir.GetShortcutString())
				if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
					c.Fatalf("Main help should not have used home shortcut:\n%s", line)
				}
			}
		}

		// Make sure each cmd's help text fits within 90 chars and that
		// on non-windows system we use ~ when possible (to shorten things).
		// Pull the list of commands from the "Commands:" section of docker help
		helpCmd = exec.Command(dockerBinary, "help")
		helpCmd.Env = newEnvs
		out, _, err = runCommandWithOutput(helpCmd)
		c.Assert(err, checker.IsNil, check.Commentf(out))
		i := strings.Index(out, "Commands:")
		c.Assert(i, checker.GreaterOrEqualThan, 0, check.Commentf("Missing 'Commands:' in:\n%s", out))

		cmds := []string{}
		// Grab all chars starting at "Commands:"
		helpOut := strings.Split(out[i:], "\n")
		// First line is just "Commands:"
		if isLocalDaemon {
			// Replace first line with "daemon" command since it's not part of the list of commands.
			helpOut[0] = " daemon"
		} else {
			// Skip first line
			helpOut = helpOut[1:]
		}

		// Create the list of commands we want to test
		cmdsToTest := []string{}
		for _, cmd := range helpOut {
			// Stop on blank line or non-idented line
			if cmd == "" || !unicode.IsSpace(rune(cmd[0])) {
				break
			}

			// Grab just the first word of each line
			cmd = strings.Split(strings.TrimSpace(cmd), " ")[0]
			cmds = append(cmds, cmd) // Saving count for later

			cmdsToTest = append(cmdsToTest, cmd)
		}

		// Add some 'two word' commands - would be nice to automatically
		// calculate this list - somehow
		cmdsToTest = append(cmdsToTest, "volume create")
		cmdsToTest = append(cmdsToTest, "volume inspect")
		cmdsToTest = append(cmdsToTest, "volume ls")
		cmdsToTest = append(cmdsToTest, "volume rm")

		for _, cmd := range cmdsToTest {
			var stderr string

			args := strings.Split(cmd+" --help", " ")

			// Check the full usage text
			helpCmd := exec.Command(dockerBinary, args...)
			helpCmd.Env = newEnvs
			out, stderr, _, err = runCommandWithStdoutStderr(helpCmd)
			c.Assert(len(stderr), checker.Equals, 0, check.Commentf("Error on %q help. non-empty stderr:%q", cmd, stderr))
			c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have blank line on %q\n", cmd))
			c.Assert(out, checker.Contains, "--help=false", check.Commentf("Should show full usage on %q\n", cmd))

			c.Assert(err, checker.IsNil, check.Commentf(out))

			// Check each line for lots of stuff
			lines := strings.Split(out, "\n")
			for _, line := range lines {
				c.Assert(len(line), checker.LessOrEqualThan, 90, check.Commentf("Help for %q is too long:\n%s", cmd, line))

				if scanForHome && strings.Contains(line, `"`+home) {
					c.Fatalf("Help for %q should use ~ instead of %q on:\n%s",
						cmd, home, line)
				}
				i := strings.Index(line, "~")
				if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
					c.Fatalf("Help for %q should not have used ~:\n%s", cmd, line)
				}

				// If a line starts with 4 spaces then assume someone
				// added a multi-line description for an option and we need
				// to flag it
				c.Assert(line, checker.Not(checker.HasPrefix), "    ", check.Commentf("Help for %q should not have a multi-line option", cmd))

				// Options should NOT end with a period
				if strings.HasPrefix(line, "  -") && strings.HasSuffix(line, ".") {
					c.Fatalf("Help for %q should not end with a period: %s", cmd, line)
				}

				// Options should NOT end with a space
				c.Assert(line, checker.Not(checker.HasSuffix), " ", check.Commentf("Help for %q should not end with a space", cmd))

			}

			// For each command make sure we generate an error
			// if we give a bad arg
			args = strings.Split(cmd+" --badArg", " ")

			out, _, err = dockerCmdWithError(args...)
			c.Assert(err, checker.NotNil, check.Commentf(out))
			// Be really picky
			c.Assert(stderr, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker rm'\n"))

			// Now make sure that each command will print a short-usage
			// (not a full usage - meaning no opts section) if we
			// are missing a required arg or pass in a bad arg

			// These commands will never print a short-usage so don't test
			noShortUsage := map[string]string{
				"images":  "",
				"login":   "",
				"logout":  "",
				"network": "",
				"stats":   "",
			}

			if _, ok := noShortUsage[cmd]; !ok {
				// For each command run it w/o any args. It will either return
				// valid output or print a short-usage
				var dCmd *exec.Cmd
				var stdout, stderr string
				var args []string

				// skipNoArgs are ones that we don't want to try w/o
				// any args. Either because it'll hang the test or
				// lead to incorrect test result (like false negative).
				// Whatever the reason, skip trying to run w/o args and
				// jump to trying with a bogus arg.
				skipNoArgs := map[string]struct{}{
					"daemon": {},
					"events": {},
					"load":   {},
				}

				ec := 0
				if _, ok := skipNoArgs[cmd]; !ok {
					args = strings.Split(cmd, " ")
					dCmd = exec.Command(dockerBinary, args...)
					stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd)
				}

				// If its ok w/o any args then try again with an arg
				if ec == 0 {
					args = strings.Split(cmd+" badArg", " ")
					dCmd = exec.Command(dockerBinary, args...)
					stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd)
				}

				if len(stdout) != 0 || len(stderr) == 0 || ec == 0 || err == nil {
					c.Fatalf("Bad output from %q\nstdout:%q\nstderr:%q\nec:%d\nerr:%q", args, stdout, stderr, ec, err)
				}
				// Should have just short usage
				c.Assert(stderr, checker.Contains, "\nUsage:\t", check.Commentf("Missing short usage on %q\n", args))
				// But shouldn't have full usage
				c.Assert(stderr, checker.Not(checker.Contains), "--help=false", check.Commentf("Should not have full usage on %q\n", args))
				c.Assert(stderr, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line on %q\n", args))
			}

		}

		// Number of commands for standard release and experimental release
		standard := 40
		experimental := 1
		expected := standard + experimental
		if isLocalDaemon {
			expected++ // for the daemon command
		}
		c.Assert(len(cmds), checker.LessOrEqualThan, expected, check.Commentf("Wrong # of cmds, it should be: %d\nThe list:\n%q", expected, cmds))
	}

}
예제 #7
0
파일: main.go 프로젝트: juliengk/pony
func main() {
	app := cli.NewApp()
	app.Name = "pony"
	app.Version = VERSION
	app.Author = "@jfrazelle"
	app.Email = "*****@*****.**"
	app.Usage = "Local File-Based Password, API Key, Secret, Recovery Code Store Backed By GPG"
	app.Before = preload
	app.EnableBashCompletion = true
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "debug, d",
			Usage: "run in debug mode",
		},
		cli.StringFlag{
			Name:  "file, f",
			Value: fmt.Sprintf("%s/%s", homedir.GetShortcutString(), defaultFilestore),
			Usage: "file to use for saving encrypted secrets",
		},
		cli.StringFlag{
			Name:  "gpgpath",
			Value: fmt.Sprintf("%s/%s", homedir.GetShortcutString(), defaultGPGPath),
			Usage: "filepath used for gpg keys",
		},
		cli.StringFlag{
			Name:   "keyid",
			Usage:  "optionally set specific gpg keyid/fingerprint to use for encryption & decryption",
			EnvVar: fmt.Sprintf("%s_KEYID", strings.ToUpper(app.Name)),
		},
	}
	app.Commands = []cli.Command{
		{
			Name:    "add",
			Aliases: []string{"save"},
			Usage:   "Add a new secret",
			Action: func(c *cli.Context) {
				args := c.Args()
				if len(args) < 2 {
					logrus.Errorf("You need to pass a key and value to the command. ex: %s %s com.example.apikey EUSJCLLAWE", app.Name, c.Command.Name)
					cli.ShowSubcommandHelp(c)
					return
				}

				// add the key value pair to secrets
				key, value := args[0], args[1]
				s.setKeyValue(key, value, false)

				fmt.Printf("Added %s %s to secrets", key, value)
			},
		},
		{
			Name:    "delete",
			Aliases: []string{"rm"},
			Usage:   "Delete a secret",
			Action: func(c *cli.Context) {
				args := c.Args()
				if len(args) < 1 {
					cli.ShowSubcommandHelp(c)
					return
				}

				key := args[0]
				if _, ok := s.Secrets[key]; !ok {
					logrus.Fatalf("Secret for (%s) does not exist", key)
				}
				delete(s.Secrets, key)

				if err := writeSecretsFile(filestore, s); err != nil {
					logrus.Fatal(err)
				}

				fmt.Printf("Secret %q deleted successfully", key)
			},
		},
		{
			Name:  "get",
			Usage: "Get the value of a secret",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "copy, c",
					Usage: "copy the secret to your clipboard",
				},
			},
			Action: func(c *cli.Context) {
				args := c.Args()
				if len(args) < 1 {
					cli.ShowSubcommandHelp(c)
					return
				}

				// add the key value pair to secrets
				key := args[0]
				if _, ok := s.Secrets[key]; !ok {
					logrus.Fatalf("Secret for (%s) does not exist", key)
				}

				fmt.Println(s.Secrets[key])

				// copy to clipboard
				if c.Bool("copy") {
					if err := clipboard.WriteAll(s.Secrets[key]); err != nil {
						logrus.Fatalf("Clipboard copy failed: %v", err)
					}
					fmt.Println("Copied to clipboard!")
				}
			},
		},
		{
			Name:    "list",
			Aliases: []string{"ls"},
			Usage:   "List all secrets",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "filter, f",
					Usage: "filter secrets keys by a regular expression",
				},
			},
			Action: func(c *cli.Context) {
				w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)

				// print header
				fmt.Fprintln(w, "KEY\tVALUE")

				// print the keys alphabetically
				printSorted := func(m map[string]string) {
					mk := make([]string, len(m))
					i := 0
					for k := range m {
						mk[i] = k
						i++
					}
					sort.Strings(mk)

					for _, key := range mk {
						filter := c.String("filter")
						if filter != "" {
							if ok, _ := regexp.MatchString(c.String("filter"), key); !ok {
								continue
							}
						}
						fmt.Fprintf(w, "%s\t%s\n", key, m[key])
					}
				}

				printSorted(s.Secrets)

				w.Flush()
			},
		},
		{
			Name:  "update",
			Usage: "Update a secret",
			Action: func(c *cli.Context) {
				args := c.Args()
				if len(args) < 2 {
					logrus.Errorf("You need to pass a key and value to the command. ex: %s %s com.example.apikey EUSJCLLAWE", app.Name, c.Command.Name)
					cli.ShowSubcommandHelp(c)
					return
				}

				// add the key value pair to secrets
				key, value := args[0], args[1]
				s.setKeyValue(key, value, true)

				fmt.Printf("Updated secret %s to %s", key, value)
			},
		},
	}
	app.Run(os.Args)
}
예제 #8
0
func (s *DockerSuite) TestHelpTextVerify(c *check.C) {
	// Make sure main help text fits within 80 chars and that
	// on non-windows system we use ~ when possible (to shorten things).
	// Test for HOME set to its default value and set to "/" on linux
	// Yes on windows setting up an array and looping (right now) isn't
	// necessary because we just have one value, but we'll need the
	// array/loop on linux so we might as well set it up so that we can
	// test any number of home dirs later on and all we need to do is
	// modify the array - the rest of the testing infrastructure should work
	homes := []string{homedir.Get()}

	// Non-Windows machines need to test for this special case of $HOME
	if runtime.GOOS != "windows" {
		homes = append(homes, "/")
	}

	homeKey := homedir.Key()
	baseEnvs := os.Environ()

	// Remove HOME env var from list so we can add a new value later.
	for i, env := range baseEnvs {
		if strings.HasPrefix(env, homeKey+"=") {
			baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...)
			break
		}
	}

	for _, home := range homes {
		// Dup baseEnvs and add our new HOME value
		newEnvs := make([]string, len(baseEnvs)+1)
		copy(newEnvs, baseEnvs)
		newEnvs[len(newEnvs)-1] = homeKey + "=" + home

		scanForHome := runtime.GOOS != "windows" && home != "/"

		// Check main help text to make sure its not over 80 chars
		helpCmd := exec.Command(dockerBinary, "help")
		helpCmd.Env = newEnvs
		out, ec, err := runCommandWithOutput(helpCmd)
		if err != nil || ec != 0 {
			c.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec)
		}
		lines := strings.Split(out, "\n")
		for _, line := range lines {
			if len(line) > 80 {
				c.Fatalf("Line is too long(%d chars):\n%s", len(line), line)
			}

			// All lines should not end with a space
			if strings.HasSuffix(line, " ") {
				c.Fatalf("Line should not end with a space: %s", line)
			}

			if scanForHome && strings.Contains(line, `=`+home) {
				c.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line)
			}
			if runtime.GOOS != "windows" {
				i := strings.Index(line, homedir.GetShortcutString())
				if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
					c.Fatalf("Main help should not have used home shortcut:\n%s", line)
				}
			}
		}

		// Make sure each cmd's help text fits within 80 chars and that
		// on non-windows system we use ~ when possible (to shorten things).
		// Pull the list of commands from the "Commands:" section of docker help
		helpCmd = exec.Command(dockerBinary, "help")
		helpCmd.Env = newEnvs
		out, ec, err = runCommandWithOutput(helpCmd)
		if err != nil || ec != 0 {
			c.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec)
		}
		i := strings.Index(out, "Commands:")
		if i < 0 {
			c.Fatalf("Missing 'Commands:' in:\n%s", out)
		}

		// Grab all chars starting at "Commands:"
		// Skip first line, its "Commands:"
		cmds := []string{}
		for _, cmd := range strings.Split(out[i:], "\n")[1:] {
			var stderr string

			// Stop on blank line or non-idented line
			if cmd == "" || !unicode.IsSpace(rune(cmd[0])) {
				break
			}

			// Grab just the first word of each line
			cmd = strings.Split(strings.TrimSpace(cmd), " ")[0]
			cmds = append(cmds, cmd)

			// Check the full usage text
			helpCmd := exec.Command(dockerBinary, cmd, "--help")
			helpCmd.Env = newEnvs
			out, stderr, ec, err = runCommandWithStdoutStderr(helpCmd)
			if len(stderr) != 0 {
				c.Fatalf("Error on %q help. non-empty stderr:%q", cmd, stderr)
			}
			if strings.HasSuffix(out, "\n\n") {
				c.Fatalf("Should not have blank line on %q\nout:%q", cmd, out)
			}
			if !strings.Contains(out, "--help=false") {
				c.Fatalf("Should show full usage on %q\nout:%q", cmd, out)
			}
			if err != nil || ec != 0 {
				c.Fatalf("Error on %q help: %s\nexit code:%d", cmd, out, ec)
			}

			// Check each line for lots of stuff
			lines := strings.Split(out, "\n")
			for _, line := range lines {
				if len(line) > 80 {
					c.Fatalf("Help for %q is too long(%d chars):\n%s", cmd,
						len(line), line)
				}

				if scanForHome && strings.Contains(line, `"`+home) {
					c.Fatalf("Help for %q should use ~ instead of %q on:\n%s",
						cmd, home, line)
				}
				i := strings.Index(line, "~")
				if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
					c.Fatalf("Help for %q should not have used ~:\n%s", cmd, line)
				}

				// If a line starts with 4 spaces then assume someone
				// added a multi-line description for an option and we need
				// to flag it
				if strings.HasPrefix(line, "    ") {
					c.Fatalf("Help for %q should not have a multi-line option: %s", cmd, line)
				}

				// Options should NOT end with a period
				if strings.HasPrefix(line, "  -") && strings.HasSuffix(line, ".") {
					c.Fatalf("Help for %q should not end with a period: %s", cmd, line)
				}

				// Options should NOT end with a space
				if strings.HasSuffix(line, " ") {
					c.Fatalf("Help for %q should not end with a space: %s", cmd, line)
				}

			}

			// For each command make sure we generate an error
			// if we give a bad arg
			dCmd := exec.Command(dockerBinary, cmd, "--badArg")
			out, stderr, ec, err = runCommandWithStdoutStderr(dCmd)
			if len(out) != 0 || len(stderr) == 0 || ec == 0 || err == nil {
				c.Fatalf("Bad results from 'docker %s --badArg'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", cmd, ec, out, stderr, err)
			}
			// Be really picky
			if strings.HasSuffix(stderr, "\n\n") {
				c.Fatalf("Should not have a blank line at the end of 'docker rm'\n%s", stderr)
			}

			// Now make sure that each command will print a short-usage
			// (not a full usage - meaning no opts section) if we
			// are missing a required arg or pass in a bad arg

			// These commands will never print a short-usage so don't test
			noShortUsage := map[string]string{
				"images": "",
				"login":  "",
				"logout": "",
			}

			if _, ok := noShortUsage[cmd]; !ok {
				// For each command run it w/o any args. It will either return
				// valid output or print a short-usage
				var dCmd *exec.Cmd
				var stdout, stderr string
				var args []string

				// skipNoArgs are ones that we don't want to try w/o
				// any args. Either because it'll hang the test or
				// lead to incorrect test result (like false negative).
				// Whatever the reason, skip trying to run w/o args and
				// jump to trying with a bogus arg.
				skipNoArgs := map[string]string{
					"events": "",
					"load":   "",
				}

				ec = 0
				if _, ok := skipNoArgs[cmd]; !ok {
					args = []string{cmd}
					dCmd = exec.Command(dockerBinary, args...)
					stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd)
				}

				// If its ok w/o any args then try again with an arg
				if ec == 0 {
					args = []string{cmd, "badArg"}
					dCmd = exec.Command(dockerBinary, args...)
					stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd)
				}

				if len(stdout) != 0 || len(stderr) == 0 || ec == 0 || err == nil {
					c.Fatalf("Bad output from %q\nstdout:%q\nstderr:%q\nec:%d\nerr:%q", args, stdout, stderr, ec, err)
				}
				// Should have just short usage
				if !strings.Contains(stderr, "\nUsage: ") {
					c.Fatalf("Missing short usage on %q\nstderr:%q", args, stderr)
				}
				// But shouldn't have full usage
				if strings.Contains(stderr, "--help=false") {
					c.Fatalf("Should not have full usage on %q\nstderr:%q", args, stderr)
				}
				if strings.HasSuffix(stderr, "\n\n") {
					c.Fatalf("Should not have a blank line on %q\nstderr:%q", args, stderr)
				}
			}

		}

		expected := 39
		if len(cmds) != expected {
			c.Fatalf("Wrong # of cmds(%d), it should be: %d\nThe list:\n%q",
				len(cmds), expected, cmds)
		}
	}

}