create_namespace.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cmd
  14. import (
  15. "fmt"
  16. "io"
  17. "github.com/renstrom/dedent"
  18. "github.com/spf13/cobra"
  19. "k8s.io/kubernetes/pkg/kubectl"
  20. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  21. )
  22. var (
  23. namespaceLong = dedent.Dedent(`
  24. Create a namespace with the specified name.`)
  25. namespaceExample = dedent.Dedent(`
  26. # Create a new namespace named my-namespace
  27. kubectl create namespace my-namespace`)
  28. )
  29. // NewCmdCreateNamespace is a macro command to create a new namespace
  30. func NewCmdCreateNamespace(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
  31. cmd := &cobra.Command{
  32. Use: "namespace NAME [--dry-run]",
  33. Aliases: []string{"ns"},
  34. Short: "Create a namespace with the specified name",
  35. Long: namespaceLong,
  36. Example: namespaceExample,
  37. Run: func(cmd *cobra.Command, args []string) {
  38. err := CreateNamespace(f, cmdOut, cmd, args)
  39. cmdutil.CheckErr(err)
  40. },
  41. }
  42. cmdutil.AddApplyAnnotationFlags(cmd)
  43. cmdutil.AddValidateFlags(cmd)
  44. cmdutil.AddPrinterFlags(cmd)
  45. cmdutil.AddGeneratorFlags(cmd, cmdutil.NamespaceV1GeneratorName)
  46. return cmd
  47. }
  48. // CreateNamespace implements the behavior to run the create namespace command
  49. func CreateNamespace(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
  50. name, err := NameFromCommandArgs(cmd, args)
  51. if err != nil {
  52. return err
  53. }
  54. var generator kubectl.StructuredGenerator
  55. switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
  56. case cmdutil.NamespaceV1GeneratorName:
  57. generator = &kubectl.NamespaceGeneratorV1{Name: name}
  58. default:
  59. return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
  60. }
  61. return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
  62. Name: name,
  63. StructuredGenerator: generator,
  64. DryRun: cmdutil.GetDryRunFlag(cmd),
  65. OutputFormat: cmdutil.GetFlagString(cmd, "output"),
  66. })
  67. }