本文整理匯總了Golang中github.com/renstrom/dedent.Dedent函數的典型用法代碼示例。如果您正苦於以下問題:Golang Dedent函數的具體用法?Golang Dedent怎麽用?Golang Dedent使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Dedent函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: NewKubeadmCommand
func NewKubeadmCommand(f cmdutil.Factory, in io.Reader, out, err io.Writer) *cobra.Command {
cmds := &cobra.Command{
Use: "kubeadm",
Short: "kubeadm: easily bootstrap a secure Kubernetes cluster",
Long: dedent.Dedent(`
kubeadm: easily bootstrap a secure Kubernetes cluster.
┌──────────────────────────────────────────────────────────┐
│ KUBEADM IS ALPHA, DO NOT USE IT FOR PRODUCTION CLUSTERS! │
│ │
│ But, please try it out! Give us feedback at: │
│ https://github.com/kubernetes/kubernetes/issues │
│ and at-mention @kubernetes/sig-cluster-lifecycle │
└──────────────────────────────────────────────────────────┘
Example usage:
Create a two-machine cluster with one master (which controls the cluster),
and one node (where workloads, like pods and replica sets run).
┌──────────────────────────────────────────────────────────┐
│ On the first machine │
├──────────────────────────────────────────────────────────┤
│ master# kubeadm init │
└──────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────┐
│ On the second machine │
├──────────────────────────────────────────────────────────┤
│ node# kubeadm join --token=<token> <ip-of-master> │
└──────────────────────────────────────────────────────────┘
You can then repeat the second step on as many other machines as you like.
`),
}
// TODO(phase2+) figure out how to avoid running as root
//
// TODO(phase2) detect interactive vs non-interactive use and adjust output accordingly
// i.e. make it automation friendly
//
// TODO(phase2) create an abstraction that defines files and the content that needs to
// be written to disc and write it all in one go at the end as we have a lot of
// crapy little files written from different parts of this code; this could also
// be useful for testing
// by having this model we can allow users to create some files before `kubeadm init` runs, e.g. PKI assets, we
// would then be able to look at files users has given an diff or validate if those are sane, we could also warn
// if any of the files had been deprecated
cmds.ResetFlags()
cmds.SetGlobalNormalizationFunc(flag.WarnWordSepNormalizeFunc)
cmds.AddCommand(NewCmdInit(out))
cmds.AddCommand(NewCmdJoin(out))
cmds.AddCommand(NewCmdReset(out))
cmds.AddCommand(NewCmdToken(out))
cmds.AddCommand(NewCmdVersion(out))
return cmds
}
示例2: TestLoadFromBytesWithInvalidName
func TestLoadFromBytesWithInvalidName(t *testing.T) {
conf := dedent.Dedent(`
image=image:latest:
image: imagename
dockerfile: what
`)
_, err := LoadFromBytes([]byte(conf))
assert.Error(t, err)
assert.Contains(t, err.Error(), "invalid character \":\"")
}
示例3: TestLoadFromBytes
func TestLoadFromBytes(t *testing.T) {
conf := dedent.Dedent(`
meta:
default: alias-def
image=image-def:
image: imagename
dockerfile: what
args:
VERSION: "3.3.3"
DEBUG: 'true'
mount=vol-def:
bind: dist/
path: /target
job=cmd-def:
use: image-dev
mounts: [vol-def]
alias=alias-def:
tasks: [vol-def, cmd-def]
compose=compose-def:
files: ['foo.yml']
`)
config, err := LoadFromBytes([]byte(conf))
assert.Nil(t, err)
assert.Equal(t, 5, len(config.Resources))
assert.IsType(t, &ImageConfig{}, config.Resources["image-def"])
assert.IsType(t, &MountConfig{}, config.Resources["vol-def"])
assert.IsType(t, &JobConfig{}, config.Resources["cmd-def"])
assert.IsType(t, &AliasConfig{}, config.Resources["alias-def"])
// Test default value and override
imageConf := config.Resources["image-def"].(*ImageConfig)
assert.Equal(t, "what", imageConf.Dockerfile)
assert.Equal(t, map[string]string{
"VERSION": "3.3.3",
"DEBUG": "true",
}, imageConf.Args)
mountConf := config.Resources["vol-def"].(*MountConfig)
assert.Equal(t, "dist/", mountConf.Bind)
assert.Equal(t, "/target", mountConf.Path)
assert.Equal(t, false, mountConf.ReadOnly)
aliasConf := config.Resources["alias-def"].(*AliasConfig)
assert.Equal(t, []string{"vol-def", "cmd-def"}, aliasConf.Tasks)
assert.Equal(t, &MetaConfig{Default: "alias-def"}, config.Meta)
}
示例4: TestLoadFromBytesWithReservedName
func TestLoadFromBytesWithReservedName(t *testing.T) {
conf := dedent.Dedent(`
image=image-def:
image: imagename
dockerfile: what
mount=autoclean:
path: dist/
mount: /target
`)
_, err := LoadFromBytes([]byte(conf))
assert.Error(t, err)
assert.Contains(t, err.Error(), "\"autoclean\" is reserved")
}
示例5: NewCmdTokenGenerate
func NewCmdTokenGenerate(out io.Writer) *cobra.Command {
return &cobra.Command{
Use: "generate",
Short: "Generate and print a bootstrap token, but do not create it on the server.",
Long: dedent.Dedent(`
This command will print out a randomly-generated bootstrap token that can be used with
the "init" and "join" commands.
You don't have to use this command in order to generate a token, you can do so
yourself as long as it's in the format "<6 characters>:<16 characters>". This
command is provided for convenience to generate tokens in that format.
You can also use "kubeadm init" without specifying a token, and it will
generate and print one for you.
`),
Run: func(cmd *cobra.Command, args []string) {
err := RunGenerateToken(out)
kubeadmutil.CheckErr(err)
},
}
}
示例6: NewCmdProxy
func NewCmdProxy(f cmdutil.Factory, out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix]",
Short: "Run a proxy to the Kubernetes API server",
Long: dedent.Dedent(`
To proxy all of the kubernetes api and nothing else, use:
kubectl proxy --api-prefix=/
To proxy only part of the kubernetes api and also some static files:
kubectl proxy --www=/my/files --www-prefix=/static/ --api-prefix=/api/
The above lets you 'curl localhost:8001/api/v1/pods'.
To proxy the entire kubernetes api at a different root, use:
kubectl proxy --api-prefix=/custom/
The above lets you 'curl localhost:8001/custom/api/v1/pods'
`),
Example: proxy_example,
Run: func(cmd *cobra.Command, args []string) {
err := RunProxy(f, out, cmd)
cmdutil.CheckErr(err)
},
}
cmd.Flags().StringP("www", "w", "", "Also serve static files from the given directory under the specified prefix.")
cmd.Flags().StringP("www-prefix", "P", "/static/", "Prefix to serve static files under, if static file directory is specified.")
cmd.Flags().StringP("api-prefix", "", "/", "Prefix to serve the proxied API under.")
cmd.Flags().String("accept-paths", kubectl.DefaultPathAcceptRE, "Regular expression for paths that the proxy should accept.")
cmd.Flags().String("reject-paths", kubectl.DefaultPathRejectRE, "Regular expression for paths that the proxy should reject.")
cmd.Flags().String("accept-hosts", kubectl.DefaultHostAcceptRE, "Regular expression for hosts that the proxy should accept.")
cmd.Flags().String("reject-methods", kubectl.DefaultMethodRejectRE, "Regular expression for HTTP methods that the proxy should reject.")
cmd.Flags().IntP("port", "p", default_port, "The port on which to run the proxy. Set to 0 to pick a random port.")
cmd.Flags().StringP("address", "", "127.0.0.1", "The IP address on which to serve on.")
cmd.Flags().Bool("disable-filter", false, "If true, disable request filtering in the proxy. This is dangerous, and can leave you vulnerable to XSRF attacks, when used with an accessible port.")
cmd.Flags().StringP("unix-socket", "u", "", "Unix socket on which to run the proxy.")
return cmd
}
示例7: NewCmdCreateService
func NewCmdCreateService(f *cmdutil.Factory, cmdOut, errOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "service",
Short: "Create a service using specified subcommand.",
Long: "Create a service using specified subcommand.",
Run: cmdutil.DefaultSubCommandRun(errOut),
}
cmd.AddCommand(NewCmdCreateServiceClusterIP(f, cmdOut))
cmd.AddCommand(NewCmdCreateServiceNodePort(f, cmdOut))
cmd.AddCommand(NewCmdCreateServiceLoadBalancer(f, cmdOut))
return cmd
}
var (
serviceClusterIPLong = dedent.Dedent(`
Create a clusterIP service with the specified name.`)
serviceClusterIPExample = dedent.Dedent(`
# Create a new clusterIP service named my-cs
kubectl create service clusterip my-cs --tcp=5678:8080
# Create a new clusterIP service named my-cs (in headless mode)
kubectl create service clusterip my-cs --clusterip="None"`)
)
func addPortFlags(cmd *cobra.Command) {
cmd.Flags().StringSlice("tcp", []string{}, "Port pairs can be specified as '<port>:<targetPort>'.")
}
// NewCmdCreateServiceClusterIP is a command to create generic secrets from files, directories, or literal values
func NewCmdCreateServiceClusterIP(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
示例8:
var patchTypes = map[string]api.PatchType{"json": api.JSONPatchType, "merge": api.MergePatchType, "strategic": api.StrategicMergePatchType}
// PatchOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
// referencing the cmd.Flags()
type PatchOptions struct {
resource.FilenameOptions
Local bool
OutputFormat string
}
var (
patch_long = dedent.Dedent(`
Update field(s) of a resource using strategic merge patch
JSON and YAML formats are accepted.
Please refer to the models in https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.`)
patch_example = dedent.Dedent(`
# Partially update a node using strategic merge patch
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
# Partially update a node identified by the type and name specified in "node.json" using strategic merge patch
kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'
# Update a container's image; spec.containers[*].name is required because it's a merge key
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
# Update a container's image using a json patch with positional arrays
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'`)
示例9: NewCmdInit
"k8s.io/kubernetes/cmd/kubeadm/app/discovery"
kubemaster "k8s.io/kubernetes/cmd/kubeadm/app/master"
"k8s.io/kubernetes/cmd/kubeadm/app/preflight"
kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/runtime"
netutil "k8s.io/kubernetes/pkg/util/net"
)
var (
initDoneMsgf = dedent.Dedent(`
Your Kubernetes master has initialized successfully!
You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
http://kubernetes.io/docs/admin/addons/
You can now join any number of machines by running the following on each node:
kubeadm join --discovery %s
`)
)
// NewCmdInit returns "kubeadm init" command.
func NewCmdInit(out io.Writer) *cobra.Command {
versioned := &kubeadmapiext.MasterConfiguration{}
api.Scheme.Default(versioned)
cfg := kubeadmapi.MasterConfiguration{}
api.Scheme.Convert(versioned, &cfg, nil)
var cfgPath string
示例10: NewCmdCordon
type fatal struct {
string
}
const (
kDaemonsetFatal = "DaemonSet-managed pods (use --ignore-daemonsets to ignore)"
kDaemonsetWarning = "Ignoring DaemonSet-managed pods"
kLocalStorageFatal = "pods with local storage (use --delete-local-data to override)"
kLocalStorageWarning = "Deleting pods with local storage"
kUnmanagedFatal = "pods not managed by ReplicationController, ReplicaSet, Job, or DaemonSet (use --force to override)"
kUnmanagedWarning = "Deleting pods not managed by ReplicationController, ReplicaSet, Job, or DaemonSet"
)
var (
cordon_long = dedent.Dedent(`
Mark node as unschedulable.
`)
cordon_example = dedent.Dedent(`
# Mark node "foo" as unschedulable.
kubectl cordon foo
`)
)
func NewCmdCordon(f *cmdutil.Factory, out io.Writer) *cobra.Command {
options := &DrainOptions{factory: f, out: out}
cmd := &cobra.Command{
Use: "cordon NODE",
Short: "Mark node as unschedulable",
Long: cordon_long,
Example: cordon_example,
示例11: NewCmdApply
"k8s.io/kubernetes/pkg/util/strategicpatch"
)
const (
// maxPatchRetry is the maximum number of conflicts retry for during a patch operation before returning failure
maxPatchRetry = 5
// backOffPeriod is the period to back off when apply patch resutls in error.
backOffPeriod = 1 * time.Second
// how many times we can retry before back off
triesBeforeBackOff = 1
)
var (
apply_long = dedent.Dedent(`
Apply a configuration to a resource by filename or stdin.
This resource will be created if it doesn't exist yet.
To use 'apply', always create the resource initially with either 'apply' or 'create --save-config'.
JSON and YAML formats are accepted.`)
apply_example = dedent.Dedent(`
# Apply the configuration in pod.json to a pod.
kubectl apply -f ./pod.json
# Apply the JSON passed into stdin to a pod.
cat pod.json | kubectl apply -f -`)
)
func NewCmdApply(f *cmdutil.Factory, out io.Writer) *cobra.Command {
options := &resource.FilenameOptions{}
cmd := &cobra.Command{
示例12:
"github.com/golang/glog"
"github.com/spf13/cobra"
)
var (
editLong = dedent.Dedent(`
Edit a resource from the default editor.
The edit command allows you to directly edit any API resource you can retrieve via the
command line tools. It will open the editor defined by your KUBE_EDITOR, or EDITOR
environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows.
You can edit multiple objects, although changes are applied one at a time. The command
accepts filenames as well as command line arguments, although the files you point to must
be previously saved versions of resources.
The files to edit will be output in the default API version, or a version specified
by --output-version. The default format is YAML - if you would like to edit in JSON
pass -o json. The flag --windows-line-endings can be used to force Windows line endings,
otherwise the default for your operating system will be used.
In the event an error occurs while updating, a temporary file will be created on disk
that contains your unapplied changes. The most common error when updating a resource
is another editor changing the resource on the server. When this occurs, you will have
to apply your changes to the newer version of the resource, or update your temporary
saved copy to include the latest resource version.`)
editExample = dedent.Dedent(`
# Edit the service named 'docker-registry':
kubectl edit svc/docker-registry
# Use an alternative editor
示例13:
package cmd
import (
"bytes"
"io"
"github.com/renstrom/dedent"
"github.com/spf13/cobra"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)
var (
completion_long = dedent.Dedent(`
Output shell completion code for the given shell (bash or zsh).
This command prints shell code which must be evaluation to provide interactive
completion of kubectl commands.
`)
completion_example = dedent.Dedent(`
$ source <(kubectl completion bash)
will load the kubectl completion code for bash. Note that this depends on the
bash-completion framework. It must be sourced before sourcing the kubectl
completion, e.g. on the Mac:
$ brew install bash-completion
$ source $(brew --prefix)/etc/bash_completion
$ source <(kubectl completion bash)
If you use zsh*, the following will load kubectl zsh completion:
示例14: NewCmdCreateNamespace
package cmd
import (
"fmt"
"io"
"github.com/renstrom/dedent"
"github.com/spf13/cobra"
"k8s.io/kubernetes/pkg/kubectl"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)
var (
namespaceLong = dedent.Dedent(`
Create a namespace with the specified name.`)
namespaceExample = dedent.Dedent(`
# Create a new namespace named my-namespace
kubectl create namespace my-namespace`)
)
// NewCmdCreateNamespace is a macro command to create a new namespace
func NewCmdCreateNamespace(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "namespace NAME [--dry-run]",
Aliases: []string{"ns"},
Short: "Create a namespace with the specified name",
Long: namespaceLong,
Example: namespaceExample,
Run: func(cmd *cobra.Command, args []string) {
示例15:
taintsToAdd []api.Taint
taintsToRemove []api.Taint
builder *resource.Builder
selector string
overwrite bool
all bool
f cmdutil.Factory
out io.Writer
cmd *cobra.Command
}
var (
taint_long = dedent.Dedent(`
Update the taints on one or more nodes.
A taint consists of a key, value, and effect. As an argument here, it is expressed as key=value:effect.
The key must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[1]d characters.
The value must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[1]d characters.
The effect must be NoSchedule or PreferNoSchedule.
Currently taint can only apply to node.`)
taint_example = dedent.Dedent(`
# Update node 'foo' with a taint with key 'dedicated' and value 'special-user' and effect 'NoSchedule'.
# If a taint with that key and effect already exists, its value is replaced as specified.
kubectl taint nodes foo dedicated=special-user:NoSchedule
# Remove from node 'foo' the taint with key 'dedicated' and effect 'NoSchedule' if one exists.
kubectl taint nodes foo dedicated:NoSchedule-
# Remove from node 'foo' all the taints with key 'dedicated'
kubectl taint nodes foo dedicated-`)
)