// GenerateBashCompletion generates the completion for the bash shell
347025
func GenerateBashCompletion(w io.Writer, cmd *cobra.Command) error {
	_, err := w.Write([]byte(boilerPlate))
	if err != nil {
		return err
	}

	err = cmd.GenBashCompletion(w)
	if err != nil {
		return errors.Wrap(err, "Error generating bash completion")
	}

	return nil
}
471755
func (api *SSHKeyAPI) Generate(name string, passPhrase string, desc string) (*sacloud.SSHKeyGenerated, error) {

	var (
		method = "POST"
		uri    = fmt.Sprintf("%s/generate", api.getResourceURL())
	)

	type genRequest struct {
		Name           string
		GenerateFormat string
		Description    string
		PassPhrase     string
	}

	type request struct {
		SSHKey genRequest
	}
	type response struct {
		*sacloud.ResultFlagValue
		SSHKey *sacloud.SSHKeyGenerated
	}

	body := &request{
		SSHKey: genRequest{
			Name:           name,
			GenerateFormat: "openssh",
			PassPhrase:     passPhrase,
			Description:    desc,
		},
	}

	res := &response{}

	_, err := api.action(method, uri, body, res)
	if err != nil {
		return nil, fmt.Errorf("SSHKeyAPI: generate SSHKey is failed: %s", err)
	}
	return res.SSHKey, nil
}
504979
func (g *Generator) generateHeader() {
	g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
	if g.file.GetOptions().GetDeprecated() {
		g.P("// ", g.file.Name, " is a deprecated file.")
	} else {
		g.P("// source: ", g.file.Name)
	}
	g.P()
	g.PrintComments(strconv.Itoa(packagePath))
	g.P()
	g.P("package ", g.file.packageName)
	g.P()
}
84658
func (o *ObjectGeneratorOptions) Complete(baseName, commandName string, f kcmdutil.Factory, c *cobra.Command, args []string) error {
	cmdutil.WarnAboutCommaSeparation(o.ErrOut, o.Config.Environment, "--env")
	cmdutil.WarnAboutCommaSeparation(o.ErrOut, o.Config.BuildEnvironment, "--build-env")

	o.Action.IOStreams = o.IOStreams

	if o.PrintFlags.OutputFormat != nil {
		o.Action.Output = *o.PrintFlags.OutputFormat
	}

	// Only output="" should print descriptions of intermediate steps. Everything
	// else should print only some specific output (json, yaml, go-template, ...)
	o.Config.In = o.In
	if len(o.Action.Output) == 0 {
		o.Config.Out = o.Out
	} else {
		o.Config.Out = ioutil.Discard
	}
	o.Config.ErrOut = o.ErrOut

	clientConfig, err := f.ToRESTConfig()
	if err != nil {
		return err
	}
	mapper, err := f.ToRESTMapper()
	if err != nil {
		return err
	}
	dynamicClient, err := dynamic.NewForConfig(clientConfig)
	if err != nil {
		return err
	}

	o.Action.Bulk.Scheme = legacyscheme.Scheme
	o.Action.Bulk.Op = bulk.Creator{Client: dynamicClient, RESTMapper: mapper}.Create
	// Retry is used to support previous versions of the API server that will
	// consider the presence of an unknown trigger type to be an error.
	o.Action.Bulk.Retry = retryBuildConfig

	o.Config.DryRun = o.Action.DryRun
	o.CommandPath = c.CommandPath()
	o.BaseName = baseName
	o.CommandName = commandName

	o.LogsForObject = polymorphichelpers.LogsForObjectFn
	o.Printer, err = o.PrintFlags.ToPrinter()
	if err != nil {
		return err
	}

	if err := CompleteAppConfig(o.Config, f, c, args); err != nil {
		return err
	}
	if err := setAppConfigLabels(c, o.Config); err != nil {
		return err
	}
	return nil
}
95263
func (s SecretForTLSGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	err := generate.ValidateParams(s.ParamNames(), genericParams)
	if err != nil {
		return nil, err
	}
	delegate := &SecretForTLSGeneratorV1{}
	hashParam, found := genericParams["append-hash"]
	if found {
		hashBool, isBool := hashParam.(bool)
		if !isBool {
			return nil, fmt.Errorf("expected bool, found :%v", hashParam)
		}
		delegate.AppendHash = hashBool
		delete(genericParams, "append-hash")
	}
	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}
	delegate.Name = params["name"]
	delegate.Key = params["key"]
	delegate.Cert = params["cert"]
	return delegate.StructuredGenerate()
}
237917
func RunCompletion(out io.Writer, cmd *cobra.Command, root *cobra.Command, args []string) error {
	var msg string
	if len(args) == 0 {
		msg = fmt.Sprintf("shell not specified.\nSee '%s -h' for help and examples.", cmd.CommandPath())
		return s2ierr.UsageError(msg)
	}
	if len(args) > 1 {
		msg = fmt.Sprintf("too many arguments. Expected only the shell type.\nSee '%s -h' for help and examples.", cmd.CommandPath())
		return s2ierr.UsageError(msg)
	}
	run, found := completionShells[args[0]]
	if !found {
		msg = fmt.Sprintf("unsupported shell type %q.\nSee '%s -h' for help and examples.", args[0], cmd.CommandPath())
		return s2ierr.UsageError(msg)
	}

	return run(out, root)
}
613732
func (a *AuthCommand) GenerateAndSignKeys(clusterApi auth.ClientI) error {
	switch {
	case a.genUser != "" && a.genHost == "":
		return a.generateUserKeys(clusterApi)
	case a.genUser == "" && a.genHost != "":
		return a.generateHostKeys(clusterApi)
	default:
		return trace.BadParameter("--user or --host must be specified")
	}
}
1234093
func GenerateExtension(schemaFile string, outDir string) error {
	outFileBaseName := getBaseFileNameWithoutExt(schemaFile)
	extensionNameWithoutXDashPrefix := outFileBaseName[len("x-"):]
	outDir = path.Join(outDir, "gnostic-x-"+extensionNameWithoutXDashPrefix)
	protoPackage := toProtoPackageName(extensionNameWithoutXDashPrefix)
	protoPackageName := strings.ToLower(protoPackage)
	goPackageName := protoPackageName

	protoOutDirectory := outDir + "/" + "proto"
	var err error

	projectRoot := os.Getenv("GOPATH") + "/src/github.com/googleapis/gnostic/"
	baseSchema, err := jsonschema.NewSchemaFromFile(projectRoot + "jsonschema/schema.json")
	if err != nil {
		return err
	}
	baseSchema.ResolveRefs()
	baseSchema.ResolveAllOfs()

	openapiSchema, err := jsonschema.NewSchemaFromFile(schemaFile)
	if err != nil {
		return err
	}
	openapiSchema.ResolveRefs()
	openapiSchema.ResolveAllOfs()

	// build a simplified model of the types described by the schema
	cc := NewDomain(openapiSchema, "v2") // TODO fix for OpenAPI v3

	// create a type for each object defined in the schema
	extensionNameToMessageName := make(map[string]generatedTypeInfo)
	schemaErrors := make([]error, 0)
	supportedPrimitives := make([]string, 0)
	for key := range supportedPrimitiveTypeInfos {
		supportedPrimitives = append(supportedPrimitives, key)
	}
	sort.Strings(supportedPrimitives)
	if cc.Schema.Definitions != nil {
		for _, pair := range *(cc.Schema.Definitions) {
			definitionName := pair.Name
			definitionSchema := pair.Value
			// ensure the id field is set
			if definitionSchema.ID == nil || len(*(definitionSchema.ID)) == 0 {
				schemaErrors = append(schemaErrors,
					fmt.Errorf("schema %s has no 'id' field, which must match the "+
						"name of the OpenAPI extension that the schema represents",
						definitionName))
			} else {
				if _, ok := extensionNameToMessageName[*(definitionSchema.ID)]; ok {
					schemaErrors = append(schemaErrors,
						fmt.Errorf("schema %s and %s have the same 'id' field value",
							definitionName, extensionNameToMessageName[*(definitionSchema.ID)].schemaName))
				} else if (definitionSchema.Type == nil) || (*definitionSchema.Type.String == "object") {
					extensionNameToMessageName[*(definitionSchema.ID)] = generatedTypeInfo{schemaName: definitionName}
				} else {
					// this is a primitive type
					if val, ok := supportedPrimitiveTypeInfos[*definitionSchema.Type.String]; ok {
						extensionNameToMessageName[*(definitionSchema.ID)] = generatedTypeInfo{schemaName: definitionName, optionalPrimitiveTypeInfo: &val}
					} else {
						schemaErrors = append(schemaErrors,
							fmt.Errorf("Schema %s has type '%s' which is "+
								"not supported. Supported primitive types are "+
								"%s.\n", definitionName,
								*definitionSchema.Type.String,
								supportedPrimitives))
					}
				}
			}
			typeName := cc.TypeNameForStub(definitionName)
			typeModel := cc.BuildTypeForDefinition(typeName, definitionName, definitionSchema)
			if typeModel != nil {
				cc.TypeModels[typeName] = typeModel
			}
		}
	}
	if len(schemaErrors) > 0 {
		// error has been reported.
		return compiler.NewErrorGroupOrNil(schemaErrors)
	}

	err = os.MkdirAll(outDir, os.ModePerm)
	if err != nil {
		return err
	}

	err = os.MkdirAll(protoOutDirectory, os.ModePerm)
	if err != nil {
		return err
	}

	// generate the protocol buffer description
	protoOptions := append(protoOptionsForExtensions,
		ProtoOption{Name: "java_package", Value: "org.openapi.extension." + strings.ToLower(protoPackage), Comment: "// The Java package name must be proto package name with proper prefix."},
		ProtoOption{Name: "objc_class_prefix", Value: strings.ToLower(protoPackage),
			Comment: "// A reasonable prefix for the Objective-C symbols generated from the package.\n" +
				"// It should at a minimum be 3 characters long, all uppercase, and convention\n" +
				"// is to use an abbreviation of the package name. Something short, but\n" +
				"// hopefully unique enough to not conflict with things that may come along in\n" +
				"// the future. 'GPB' is reserved for the protocol buffer implementation itself.",
		})

	proto := cc.generateProto(protoPackageName, License, protoOptions, nil)
	protoFilename := path.Join(protoOutDirectory, outFileBaseName+".proto")

	err = ioutil.WriteFile(protoFilename, []byte(proto), 0644)
	if err != nil {
		return err
	}

	// generate the compiler
	compiler := cc.GenerateCompiler(goPackageName, License, []string{
		"fmt",
		"regexp",
		"strings",
		"github.com/googleapis/gnostic/compiler",
		"gopkg.in/yaml.v2",
	})
	goFilename := path.Join(protoOutDirectory, outFileBaseName+".go")
	err = ioutil.WriteFile(goFilename, []byte(compiler), 0644)
	if err != nil {
		return err
	}
	err = exec.Command(runtime.GOROOT()+"/bin/gofmt", "-w", goFilename).Run()

	// generate the main file.
	outDirRelativeToGoPathSrc := strings.Replace(outDir, path.Join(os.Getenv("GOPATH"), "src")+"/", "", 1)

	var extensionNameKeys []string
	for k := range extensionNameToMessageName {
		extensionNameKeys = append(extensionNameKeys, k)
	}
	sort.Strings(extensionNameKeys)

	wrapperTypeIncluded := false
	var cases string
	for _, extensionName := range extensionNameKeys {
		if extensionNameToMessageName[extensionName].optionalPrimitiveTypeInfo == nil {
			cases += fmt.Sprintf(caseStringForObjectTypes, extensionName, goPackageName, extensionNameToMessageName[extensionName].schemaName)
		} else {
			wrapperTypeIncluded = true
			cases += fmt.Sprintf(caseStringForWrapperTypes, extensionName, extensionNameToMessageName[extensionName].optionalPrimitiveTypeInfo.goTypeName, extensionNameToMessageName[extensionName].optionalPrimitiveTypeInfo.wrapperProtoName)
		}

	}
	extMainCode := fmt.Sprintf(additionalCompilerCodeWithMain, cases)
	imports := []string{
		"github.com/golang/protobuf/proto",
		"github.com/googleapis/gnostic/extensions",
		"github.com/googleapis/gnostic/compiler",
		"gopkg.in/yaml.v2",
		outDirRelativeToGoPathSrc + "/" + "proto",
	}
	if wrapperTypeIncluded {
		imports = append(imports, "github.com/golang/protobuf/ptypes/wrappers")
	}
	main := generateMainFile("main", License, extMainCode, imports)
	mainFileName := path.Join(outDir, "main.go")
	err = ioutil.WriteFile(mainFileName, []byte(main), 0644)
	if err != nil {
		return err
	}

	// format the compiler
	return exec.Command(runtime.GOROOT()+"/bin/gofmt", "-w", mainFileName).Run()
}
386416
func (a *completionsMixin) addHintActionBuiltin(action HintAction) {
	a.builtinHintActions = append(a.builtinHintActions, action)
}
453578
func GenerateENITemplate(interfaces []network.InterfaceInfo) (string, error) {
	if len(interfaces) == 0 {
		return "", errors.Errorf("missing container network config")
	}
	logger.Debugf("generating /e/n/i template from %#v", interfaces)

	prepared := PrepareNetworkConfigFromInterfaces(interfaces)

	var output bytes.Buffer
	gateway4Handled := false
	gateway6Handled := false
	hasV4Interface := false
	hasV6Interface := false
	for _, name := range prepared.InterfaceNames {
		output.WriteString("\n")
		if name == "lo" {
			output.WriteString("auto ")
			autoStarted := strings.Join(prepared.AutoStarted, " ")
			output.WriteString(autoStarted + "\n\n")
			output.WriteString("iface lo inet loopback\n")

			dnsServers := strings.Join(prepared.DNSServers, " ")
			if dnsServers != "" {
				output.WriteString("  dns-nameservers ")
				output.WriteString(dnsServers + "\n")
			}

			dnsSearchDomains := strings.Join(prepared.DNSSearchDomains, " ")
			if dnsSearchDomains != "" {
				output.WriteString("  dns-search ")
				output.WriteString(dnsSearchDomains + "\n")
			}
			continue
		}

		address, hasAddress := prepared.NameToAddress[name]
		if !hasAddress {
			output.WriteString("iface " + name + " inet manual\n")
			continue
		} else if address == string(network.ConfigDHCP) {
			output.WriteString("iface " + name + " inet dhcp\n")
			// We're expecting to get a default gateway
			// from the DHCP lease.
			gateway4Handled = true
			continue
		}

		_, network, err := net.ParseCIDR(address)
		if err != nil {
			return "", errors.Annotatef(err, "invalid address for interface %q: %q", name, address)
		}

		isIpv4 := network.IP.To4() != nil

		if isIpv4 {
			output.WriteString("iface " + name + " inet static\n")
			hasV4Interface = true
		} else {
			output.WriteString("iface " + name + " inet6 static\n")
			hasV6Interface = true
		}
		output.WriteString("  address " + address + "\n")

		if isIpv4 {
			if !gateway4Handled && prepared.Gateway4Address != "" {
				gatewayIP := net.ParseIP(prepared.Gateway4Address)
				if network.Contains(gatewayIP) {
					output.WriteString("  gateway " + prepared.Gateway4Address + "\n")
					gateway4Handled = true // write it only once
				}
			}
		} else {
			if !gateway6Handled && prepared.Gateway6Address != "" {
				gatewayIP := net.ParseIP(prepared.Gateway6Address)
				if network.Contains(gatewayIP) {
					output.WriteString("  gateway " + prepared.Gateway6Address + "\n")
					gateway4Handled = true // write it only once
				}
			}
		}

		if mtu, ok := prepared.NameToMTU[name]; ok {
			output.WriteString(fmt.Sprintf("  mtu %d\n", mtu))
		}

		for _, route := range prepared.NameToRoutes[name] {
			output.WriteString(fmt.Sprintf("  post-up ip route add %s via %s metric %d\n",
				route.DestinationCIDR, route.GatewayIP, route.Metric))
			output.WriteString(fmt.Sprintf("  pre-down ip route del %s via %s metric %d\n",
				route.DestinationCIDR, route.GatewayIP, route.Metric))
		}
	}

	generatedConfig := output.String()
	logger.Debugf("generated network config:\n%s", generatedConfig)

	if hasV4Interface && !gateway4Handled {
		logger.Infof("generated network config has no ipv4 gateway")
	}

	if hasV6Interface && !gateway6Handled {
		logger.Infof("generated network config has no ipv6 gateway")
	}

	return generatedConfig, nil
}
1342082
func (c *cmdMixin) CmdCompletion(context *ParseContext) []string {
	var options []string

	// Count args already satisfied - we won't complete those, and add any
	// default commands' alternatives, since they weren't listed explicitly
	// and the user may want to explicitly list something else.
	argsSatisfied := 0
	allSatisfied := false
ElementLoop:
	for _, el := range context.Elements {
		switch clause := el.Clause.(type) {
		case *ArgClause:
			// Each new element should reset the previous state
			allSatisfied = false
			options = nil

			if el.Value != nil && *el.Value != "" {
				// Get the list of valid options for the last argument
				validOptions := c.argGroup.args[argsSatisfied].resolveCompletions()
				if len(validOptions) == 0 {
					// If there are no options for this argument,
					// mark is as allSatisfied as we can't suggest anything
					argsSatisfied++
					allSatisfied = true
					continue ElementLoop
				}

				for _, opt := range validOptions {
					if opt == *el.Value {
						// We have an exact match
						// We don't need to suggest any option
						argsSatisfied++
						continue ElementLoop
					}
					if strings.HasPrefix(opt, *el.Value) {
						// If the option match the partially entered argument, add it to the list
						options = append(options, opt)
					}
				}
				// Avoid further completion as we have done everything we could
				argsSatisfied++
				allSatisfied = true
			}
		case *CmdClause:
			options = append(options, clause.completionAlts...)
		default:
		}
	}

	if argsSatisfied < len(c.argGroup.args) && !allSatisfied {
		// Since not all args have been satisfied, show options for the current one
		options = append(options, c.argGroup.args[argsSatisfied].resolveCompletions()...)
	} else {
		// If all args are satisfied, then go back to completing commands
		for _, cmd := range c.cmdGroup.commandOrder {
			if !cmd.hidden {
				options = append(options, cmd.name)
			}
		}
	}

	return options
}
478655
func generateVerbatim(p *parser, out *bytes.Buffer, data []byte, offset int) int {
	return generator(p, out, data, offset, '=', false, p.r.CodeSpan)
}
1088327
func (c *SSHCommon) generateKnownHosts(targets []*resolvedTarget) (string, error) {
	knownHosts := newKnownHostsBuilder()
	agentCount := 0
	nonAgentCount := 0
	for _, target := range targets {
		if target.isAgent() {
			agentCount++
			keys, err := c.apiClient.PublicKeys(target.entity)
			if err != nil {
				return "", errors.Annotatef(err, "retrieving SSH host keys for %q", target.entity)
			}
			knownHosts.add(target.host, keys)
		} else {
			nonAgentCount++
		}
	}

	if agentCount > 0 && nonAgentCount > 0 {
		return "", errors.New("can't determine host keys for all targets: consider --no-host-key-checks")
	}

	if knownHosts.size() == 0 {
		// No public keys to write so exit early.
		return "", nil
	}

	f, err := ioutil.TempFile("", "ssh_known_hosts")
	if err != nil {
		return "", errors.Annotate(err, "creating known hosts file")
	}
	defer f.Close()
	c.knownHostsPath = f.Name() // Record for later deletion
	if knownHosts.write(f); err != nil {
		return "", errors.Trace(err)
	}
	return c.knownHostsPath, nil
}
590166
func generateHeader(outHeaderPath string, features []string) error {
	inHeaderPath := "cairo.h"
	if err := generateInputHeader(inHeaderPath, features); err != nil {
		return err
	}
	inf, err := os.Open(inHeaderPath)
	if err != nil {
		return fmt.Errorf("open %q: %s", inHeaderPath, err)
	}
	defer inf.Close()

	outf, err := os.Create(outHeaderPath)
	if err != nil {
		return fmt.Errorf("create %q: %s", outHeaderPath, err)
	}
	defer outf.Close()

	// Gather cflags from pkg-config --cflags.
	cmd := exec.Command("pkg-config", "--cflags", "cairo")
	for _, feature := range features {
		cmd.Args = append(cmd.Args, feature)
	}
	cmd.Stderr = os.Stderr
	out, err := cmd.Output()
	if err != nil {
		return err
	}
	cflags := strings.Split(strings.TrimSpace(string(out)), " ")

	// Preprocess the cairo header.
	cmd = exec.Command("gcc", "-E")
	cmd.Args = append(cmd.Args, cflags...)
	cmd.Args = append(cmd.Args, "-")
	cmd.Stdin = inf
	cmd.Stdout = outf
	return cmd.Run()
}
640105
func GenerateZshCompletion(out io.Writer, cmd *cobra.Command) error {
	zshAutoloadTag := `#compdef minikube
`

	zshInitialization := `
__minikube_bash_source() {
	alias shopt=':'
	alias _expand=_bash_expand
	alias _complete=_bash_comp
	emulate -L sh
	setopt kshglob noshglob braceexpand
	source "$@"
}
__minikube_type() {
	# -t is not supported by zsh
	if [ "$1" == "-t" ]; then
		shift
		# fake Bash 4 to disable "complete -o nospace". Instead
		# "compopt +-o nospace" is used in the code to toggle trailing
		# spaces. We don't support that, but leave trailing spaces on
		# all the time
		if [ "$1" = "__minikube_compopt" ]; then
			echo builtin
			return 0
		fi
	fi
	type "$@"
}
__minikube_compgen() {
	local completions w
	completions=( $(compgen "$@") ) || return $?
	# filter by given word as prefix
	while [[ "$1" = -* && "$1" != -- ]]; do
		shift
		shift
	done
	if [[ "$1" == -- ]]; then
		shift
	fi
	for w in "${completions[@]}"; do
		if [[ "${w}" = "$1"* ]]; then
			echo "${w}"
		fi
	done
}
__minikube_compopt() {
	true # don't do anything. Not supported by bashcompinit in zsh
}
__minikube_declare() {
	if [ "$1" == "-F" ]; then
		whence -w "$@"
	else
		builtin declare "$@"
	fi
}
__minikube_ltrim_colon_completions()
{
	if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then
		# Remove colon-word prefix from COMPREPLY items
		local colon_word=${1%${1##*:}}
		local i=${#COMPREPLY[*]}
		while [[ $((--i)) -ge 0 ]]; do
			COMPREPLY[$i]=${COMPREPLY[$i]#"$colon_word"}
		done
	fi
}
__minikube_get_comp_words_by_ref() {
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[${COMP_CWORD}-1]}"
	words=("${COMP_WORDS[@]}")
	cword=("${COMP_CWORD[@]}")
}
__minikube_filedir() {
	local RET OLD_IFS w qw
	__debug "_filedir $@ cur=$cur"
	if [[ "$1" = \~* ]]; then
		# somehow does not work. Maybe, zsh does not call this at all
		eval echo "$1"
		return 0
	fi
	OLD_IFS="$IFS"
	IFS=$'\n'
	if [ "$1" = "-d" ]; then
		shift
		RET=( $(compgen -d) )
	else
		RET=( $(compgen -f) )
	fi
	IFS="$OLD_IFS"
	IFS="," __debug "RET=${RET[@]} len=${#RET[@]}"
	for w in ${RET[@]}; do
		if [[ ! "${w}" = "${cur}"* ]]; then
			continue
		fi
		if eval "[[ \"\${w}\" = *.$1 || -d \"\${w}\" ]]"; then
			qw="$(__minikube_quote "${w}")"
			if [ -d "${w}" ]; then
				COMPREPLY+=("${qw}/")
			else
				COMPREPLY+=("${qw}")
			fi
		fi
	done
}
__minikube_quote() {
	if [[ $1 == \'* || $1 == \"* ]]; then
		# Leave out first character
		printf %q "${1:1}"
	else
		printf %q "$1"
	fi
}
autoload -U +X bashcompinit && bashcompinit
# use word boundary patterns for BSD or GNU sed
LWORD='[[:<:]]'
RWORD='[[:>:]]'
if sed --help 2>&1 | grep -q GNU; then
	LWORD='\<'
	RWORD='\>'
fi
__minikube_convert_bash_to_zsh() {
	sed \
	-e 's/declare -F/whence -w/' \
	-e 's/_get_comp_words_by_ref "\$@"/_get_comp_words_by_ref "\$*"/' \
	-e 's/local \([a-zA-Z0-9_]*\)=/local \1; \1=/' \
	-e 's/flags+=("\(--.*\)=")/flags+=("\1"); two_word_flags+=("\1")/' \
	-e 's/must_have_one_flag+=("\(--.*\)=")/must_have_one_flag+=("\1")/' \
	-e "s/${LWORD}_filedir${RWORD}/__minikube_filedir/g" \
	-e "s/${LWORD}_get_comp_words_by_ref${RWORD}/__minikube_get_comp_words_by_ref/g" \
	-e "s/${LWORD}__ltrim_colon_completions${RWORD}/__minikube_ltrim_colon_completions/g" \
	-e "s/${LWORD}compgen${RWORD}/__minikube_compgen/g" \
	-e "s/${LWORD}compopt${RWORD}/__minikube_compopt/g" \
	-e "s/${LWORD}declare${RWORD}/__minikube_declare/g" \
	-e "s/\\\$(type${RWORD}/\$(__minikube_type/g" \
	<<'BASH_COMPLETION_EOF'
`

	_, err := out.Write([]byte(zshAutoloadTag))
	if err != nil {
		return err
	}

	_, err = out.Write([]byte(boilerPlate))
	if err != nil {
		return err
	}

	_, err = out.Write([]byte(zshInitialization))
	if err != nil {
		return err
	}

	buf := new(bytes.Buffer)
	err = cmd.GenBashCompletion(buf)
	if err != nil {
		return errors.Wrap(err, "Error generating zsh completion")
	}
	_, err = out.Write(buf.Bytes())
	if err != nil {
		return err
	}

	zshTail := `
BASH_COMPLETION_EOF
}
__minikube_bash_source <(__minikube_convert_bash_to_zsh)
`
	_, err = out.Write([]byte(zshTail))
	if err != nil {
		return err
	}

	return nil
}
903693
func generateDockerExecCommand(containerID string, bashcmd []string, prependBash bool) ([]string, error) {
	if containerID == "" {
		return []string{}, fmt.Errorf("will not attach to container with empty containerID")
	}

	exeMap, err := exePaths([]string{"docker"})
	if err != nil {
		return []string{}, err
	}

	// TODO: add '-h' hostname to specify the container hostname when that
	// feature becomes available
	attachCmd := []string{exeMap["docker"], "exec"}

	if Isatty(os.Stdin) {
		attachCmd = append(attachCmd, "-t")
	}
	if Isatty(os.Stdout) && Isatty(os.Stdin) {
		attachCmd = append(attachCmd, "-i")
	}
	attachCmd = append(attachCmd, containerID)

	if prependBash {
		attachCmd = append(attachCmd, "/bin/bash", "-c", fmt.Sprintf("%s", strings.Join(bashcmd, " ")))
	} else {
		attachCmd = append(attachCmd, bashcmd...)
	}
	glog.V(1).Infof("attach command for container:%v command: %v\n", containerID, attachCmd)
	return attachCmd, nil
}
78365
func GenerateSpec(ctx context.Context, meta executor.Meta, mounts []executor.Mount, id, resolvConf, hostsFile string, namespace network.Namespace, processMode ProcessMode, idmap *idtools.IdentityMapping, opts ...oci.SpecOpts) (*specs.Spec, func(), error) {
	c := &containers.Container{
		ID: id,
	}
	_, ok := namespaces.Namespace(ctx)
	if !ok {
		ctx = namespaces.WithNamespace(ctx, "buildkit")
	}
	if meta.SecurityMode == pb.SecurityMode_INSECURE {
		opts = append(opts, entitlements.WithInsecureSpec())
	} else if system.SeccompSupported() && meta.SecurityMode == pb.SecurityMode_SANDBOX {
		opts = append(opts, seccomp.WithDefaultProfile())
	}

	switch processMode {
	case NoProcessSandbox:
		// Mount for /proc is replaced in GetMounts()
		opts = append(opts,
			oci.WithHostNamespace(specs.PIDNamespace))
		// TODO(AkihiroSuda): Configure seccomp to disable ptrace (and prctl?) explicitly
	}

	// Note that containerd.GenerateSpec is namespaced so as to make
	// specs.Linux.CgroupsPath namespaced
	s, err := oci.GenerateSpec(ctx, nil, c, opts...)
	if err != nil {
		return nil, nil, err
	}
	// set the networking information on the spec
	namespace.Set(s)

	s.Process.Args = meta.Args
	s.Process.Env = meta.Env
	s.Process.Cwd = meta.Cwd
	s.Process.Rlimits = nil           // reset open files limit
	s.Process.NoNewPrivileges = false // reset nonewprivileges
	s.Hostname = "buildkitsandbox"

	s.Mounts, err = GetMounts(ctx,
		withProcessMode(processMode),
		withROBind(resolvConf, "/etc/resolv.conf"),
		withROBind(hostsFile, "/etc/hosts"),
	)
	if err != nil {
		return nil, nil, err
	}

	s.Mounts = append(s.Mounts, specs.Mount{
		Destination: "/sys/fs/cgroup",
		Type:        "cgroup",
		Source:      "cgroup",
		Options:     []string{"ro", "nosuid", "noexec", "nodev"},
	})

	if meta.SecurityMode == pb.SecurityMode_INSECURE {
		//make sysfs rw mount for insecure mode.
		for _, m := range s.Mounts {
			if m.Type == "sysfs" {
				m.Options = []string{"nosuid", "noexec", "nodev", "rw"}
			}
		}
	}

	if idmap != nil {
		s.Linux.Namespaces = append(s.Linux.Namespaces, specs.LinuxNamespace{
			Type: specs.UserNamespace,
		})
		s.Linux.UIDMappings = specMapping(idmap.UIDs())
		s.Linux.GIDMappings = specMapping(idmap.GIDs())
	}

	sm := &submounts{}

	var releasers []func() error
	releaseAll := func() {
		sm.cleanup()
		for _, f := range releasers {
			f()
		}
	}

	for _, m := range mounts {
		if m.Src == nil {
			return nil, nil, errors.Errorf("mount %s has no source", m.Dest)
		}
		mountable, err := m.Src.Mount(ctx, m.Readonly)
		if err != nil {
			releaseAll()
			return nil, nil, errors.Wrapf(err, "failed to mount %s", m.Dest)
		}
		mounts, err := mountable.Mount()
		if err != nil {
			releaseAll()
			return nil, nil, errors.WithStack(err)
		}
		releasers = append(releasers, mountable.Release)
		for _, mount := range mounts {
			mount, err = sm.subMount(mount, m.Selector)
			if err != nil {
				releaseAll()
				return nil, nil, err
			}
			s.Mounts = append(s.Mounts, specs.Mount{
				Destination: m.Dest,
				Type:        mount.Type,
				Source:      mount.Source,
				Options:     mount.Options,
			})
		}
	}

	return s, releaseAll, nil
}