当前位置: 首页>>代码示例>>Golang>>正文


Golang FlagSet.Parse方法代码示例

本文整理汇总了Golang中github.com/docker/docker/pkg/mflag.FlagSet.Parse方法的典型用法代码示例。如果您正苦于以下问题:Golang FlagSet.Parse方法的具体用法?Golang FlagSet.Parse怎么用?Golang FlagSet.Parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/docker/docker/pkg/mflag.FlagSet的用法示例。


在下文中一共展示了FlagSet.Parse方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: parseRun

func parseRun(cmd *flag.FlagSet, args []string) (*docker.CreateContainerOptions, error) {
	var (
		flStdin  = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached")
		flTty    = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY")
		flDetach = cmd.Bool([]string{"d", "-detach"}, false, "[NOT SUPPORTED] Run container in background and print container ID")
		flName   = cmd.String([]string{"-name"}, "", "Assign a name to the container")
		// the caller should handle "-rm" with cmd.IsSet()
		_ = cmd.Bool([]string{"-rm"}, false, "Automatically remove the container when it exits")
		// the caller should handle "-eq-config"
		_ = cmd.String([]string{"-eq-config"}, "", "Earthquake configuration file")
	)
	if err := cmd.Parse(args); err != nil {
		return nil, err
	}
	if !*flStdin {
		return nil, fmt.Errorf("-interactive is expected.")
	}
	if !*flTty {
		return nil, fmt.Errorf("-tty is expected.")
	}
	if *flDetach {
		return nil, fmt.Errorf("Currently, -detach is not supported.")
	}

	parsedArgs := cmd.Args()
	if len(parsedArgs) < 2 {
		return nil, fmt.Errorf("requires a minimum of 2 arguments")
	}
	image := parsedArgs[0]
	execCmd := parsedArgs[1:]

	dockerOpt := docker.CreateContainerOptions{
		Name: *flName,
		Config: &docker.Config{
			Image:        image,
			Cmd:          execCmd,
			OpenStdin:    *flStdin,
			StdinOnce:    true,
			AttachStdin:  true,
			AttachStdout: true,
			AttachStderr: true,
			Tty:          *flTty,
		},
		HostConfig: &docker.HostConfig{},
	}
	return &dockerOpt, nil
}
开发者ID:terminiter,项目名称:earthquake,代码行数:47,代码来源:runflag.go

示例2: ParseFlags

// ParseFlags is a utility function that adds a help flag if withHelp is true,
// calls cmd.Parse(args) and prints a relevant error message if there are
// incorrect number of arguments. It returns error only if error handling is
// set to ContinueOnError and parsing fails. If error handling is set to
// ExitOnError, it's safe to ignore the return value.
// TODO: move this to a better package than utils
func ParseFlags(cmd *flag.FlagSet, args []string, withHelp bool) error {
	var help *bool
	if withHelp {
		help = cmd.Bool([]string{"#help", "-help"}, false, "Print usage")
	}
	if err := cmd.Parse(args); err != nil {
		return err
	}
	if help != nil && *help {
		cmd.Usage()
		// just in case Usage does not exit
		os.Exit(0)
	}
	if str := cmd.CheckArgs(); str != "" {
		ReportError(cmd, str, withHelp)
	}
	return nil
}
开发者ID:Crispy1975,项目名称:deis,代码行数:24,代码来源:flags.go

示例3: ParseExec

func ParseExec(cmd *flag.FlagSet, args []string) (*ExecConfig, error) {
	var (
		flStdin   = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached")
		flTty     = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY")
		flDetach  = cmd.Bool([]string{"d", "-detach"}, false, "Detached mode: run command in the background")
		execCmd   []string
		container string
	)
	if err := cmd.Parse(args); err != nil {
		return nil, err
	}
	parsedArgs := cmd.Args()
	if len(parsedArgs) > 1 {
		container = cmd.Arg(0)
		execCmd = parsedArgs[1:]
	}

	execConfig := &ExecConfig{
		// TODO(vishh): Expose '-u' flag once it is supported.
		User: "",
		// TODO(vishh): Expose '-p' flag once it is supported.
		Privileged: false,
		Tty:        *flTty,
		Cmd:        execCmd,
		Container:  container,
		Detach:     *flDetach,
	}

	// If -d is not set, attach to everything by default
	if !*flDetach {
		execConfig.AttachStdout = true
		execConfig.AttachStderr = true
		if *flStdin {
			execConfig.AttachStdin = true
		}
	}

	return execConfig, nil
}
开发者ID:baa-archieve,项目名称:docker,代码行数:39,代码来源:exec.go

示例4: Parse

func Parse(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Config, *HostConfig, *flag.FlagSet, error) {
	var (
		// FIXME: use utils.ListOpts for attach and volumes?
		flAttach  = opts.NewListOpts(opts.ValidateAttach)
		flVolumes = opts.NewListOpts(opts.ValidatePath)
		flLinks   = opts.NewListOpts(opts.ValidateLink)
		flEnv     = opts.NewListOpts(opts.ValidateEnv)
		flDevices = opts.NewListOpts(opts.ValidatePath)

		flPublish     = opts.NewListOpts(nil)
		flExpose      = opts.NewListOpts(nil)
		flDns         = opts.NewListOpts(opts.ValidateIPAddress)
		flDnsSearch   = opts.NewListOpts(opts.ValidateDnsSearch)
		flExtraHosts  = opts.NewListOpts(opts.ValidateExtraHost)
		flVolumesFrom = opts.NewListOpts(nil)
		flLxcOpts     = opts.NewListOpts(nil)
		flEnvFile     = opts.NewListOpts(nil)
		flCapAdd      = opts.NewListOpts(nil)
		flCapDrop     = opts.NewListOpts(nil)
		flSecurityOpt = opts.NewListOpts(nil)

		flNetwork         = cmd.Bool([]string{"#n", "#-networking"}, true, "Enable networking for this container")
		flPrivileged      = cmd.Bool([]string{"#privileged", "-privileged"}, false, "Give extended privileges to this container")
		flPublishAll      = cmd.Bool([]string{"P", "-publish-all"}, false, "Publish all exposed ports to the host interfaces")
		flStdin           = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached")
		flTty             = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY")
		flContainerIDFile = cmd.String([]string{"#cidfile", "-cidfile"}, "", "Write the container ID to the file")
		flEntrypoint      = cmd.String([]string{"#entrypoint", "-entrypoint"}, "", "Overwrite the default ENTRYPOINT of the image")
		flHostname        = cmd.String([]string{"h", "-hostname"}, "", "Container host name")
		flMemoryString    = cmd.String([]string{"m", "-memory"}, "", "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)")
		flUser            = cmd.String([]string{"u", "-user"}, "", "Username or UID")
		flWorkingDir      = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container")
		flCpuShares       = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
		flCpuset          = cmd.String([]string{"-cpuset"}, "", "CPUs in which to allow execution (0-3, 0,1)")
		flNetMode         = cmd.String([]string{"-net"}, "bridge", "Set the Network mode for the container\n'bridge': creates a new network stack for the container on the docker bridge\n'none': no networking for this container\n'container:<name|id>': reuses another container network stack\n'host': use the host network stack inside the container.  Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.")
		flRestartPolicy   = cmd.String([]string{"-restart"}, "", "Restart policy to apply when a container exits (no, on-failure[:max-retry], always)")
		flMonitorDriver   = cmd.String([]string{"-mon"}, "builtin", "Monitor driver")
	)

	cmd.Var(&flAttach, []string{"a", "-attach"}, "Attach to STDIN, STDOUT or STDERR.")
	cmd.Var(&flVolumes, []string{"v", "-volume"}, "Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)")
	cmd.Var(&flLinks, []string{"#link", "-link"}, "Add link to another container in the form of name:alias")
	cmd.Var(&flDevices, []string{"-device"}, "Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc)")

	cmd.Var(&flEnv, []string{"e", "-env"}, "Set environment variables")
	cmd.Var(&flEnvFile, []string{"-env-file"}, "Read in a line delimited file of environment variables")

	cmd.Var(&flPublish, []string{"p", "-publish"}, fmt.Sprintf("Publish a container's port to the host\nformat: %s\n(use 'docker port' to see the actual mapping)", nat.PortSpecTemplateFormat))
	cmd.Var(&flExpose, []string{"#expose", "-expose"}, "Expose a port from the container without publishing it to your host")
	cmd.Var(&flDns, []string{"#dns", "-dns"}, "Set custom DNS servers")
	cmd.Var(&flDnsSearch, []string{"-dns-search"}, "Set custom DNS search domains")
	cmd.Var(&flExtraHosts, []string{"-add-host"}, "Add a custom host-to-IP mapping (host:ip)")
	cmd.Var(&flVolumesFrom, []string{"#volumes-from", "-volumes-from"}, "Mount volumes from the specified container(s)")
	cmd.Var(&flLxcOpts, []string{"#lxc-conf", "-lxc-conf"}, "(lxc exec-driver only) Add custom lxc options --lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"")

	cmd.Var(&flCapAdd, []string{"-cap-add"}, "Add Linux capabilities")
	cmd.Var(&flCapDrop, []string{"-cap-drop"}, "Drop Linux capabilities")
	cmd.Var(&flSecurityOpt, []string{"-security-opt"}, "Security Options")

	if err := cmd.Parse(args); err != nil {
		return nil, nil, cmd, err
	}

	// Check if the kernel supports memory limit cgroup.
	if sysInfo != nil && *flMemoryString != "" && !sysInfo.MemoryLimit {
		*flMemoryString = ""
	}

	// Validate input params
	if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
		return nil, nil, cmd, ErrInvalidWorkingDirectory
	}

	var (
		attachStdin  = flAttach.Get("stdin")
		attachStdout = flAttach.Get("stdout")
		attachStderr = flAttach.Get("stderr")
	)

	if *flNetMode != "bridge" && *flNetMode != "none" && *flHostname != "" {
		return nil, nil, cmd, ErrConflictNetworkHostname
	}

	if *flNetMode == "host" && flLinks.Len() > 0 {
		return nil, nil, cmd, ErrConflictHostNetworkAndLinks
	}

	if *flNetMode == "container" && flLinks.Len() > 0 {
		return nil, nil, cmd, ErrConflictContainerNetworkAndLinks
	}

	if *flNetMode == "host" && flDns.Len() > 0 {
		return nil, nil, cmd, ErrConflictHostNetworkAndDns
	}

	if *flNetMode == "container" && flDns.Len() > 0 {
		return nil, nil, cmd, ErrConflictContainerNetworkAndDns
	}

	// If neither -d or -a are set, attach to everything by default
//.........这里部分代码省略.........
开发者ID:TencentSA,项目名称:docker-1.3,代码行数:101,代码来源:parse.go


注:本文中的github.com/docker/docker/pkg/mflag.FlagSet.Parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。