|
| 1 | +// Copyright 2018 The Operator-SDK Authors |
| 2 | +// |
| 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 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package generate |
| 16 | + |
| 17 | +import ( |
| 18 | + "errors" |
| 19 | + "fmt" |
| 20 | + "os" |
| 21 | + |
| 22 | + cmdError "github.com/operator-framework/operator-sdk/commands/operator-sdk/error" |
| 23 | + "github.com/operator-framework/operator-sdk/pkg/generator" |
| 24 | + "github.com/spf13/cobra" |
| 25 | +) |
| 26 | + |
| 27 | +var ( |
| 28 | + apiVersion string |
| 29 | + kind string |
| 30 | +) |
| 31 | + |
| 32 | +func NewGenerateCrdCmd() *cobra.Command { |
| 33 | + crdCmd := &cobra.Command{ |
| 34 | + Use: "crd", |
| 35 | + Short: "Generates a custom resource definition", |
| 36 | + Long: `generates a custom resource definition (CRD) file for the . |
| 37 | +`, |
| 38 | + Run: crdFunc, |
| 39 | + } |
| 40 | + crdCmd.Flags().StringVar(&apiVersion, "api-version", "", "Kubernetes apiVersion and has a format of $GROUP_NAME/$VERSION (e.g app.example.com/v1alpha1)") |
| 41 | + crdCmd.MarkFlagRequired("api-version") |
| 42 | + crdCmd.Flags().StringVar(&kind, "kind", "", "Kubernetes CustomResourceDefintion kind. (e.g AppService)") |
| 43 | + crdCmd.MarkFlagRequired("kind") |
| 44 | + return crdCmd |
| 45 | +} |
| 46 | + |
| 47 | +func crdFunc(cmd *cobra.Command, args []string) { |
| 48 | + if len(args) != 0 { |
| 49 | + cmdError.ExitWithError(cmdError.ExitBadArgs, errors.New("crd command doesn't accept any arguments.")) |
| 50 | + } |
| 51 | + verifyCrdFlags() |
| 52 | + |
| 53 | + fmt.Fprintln(os.Stdout, "Generating custom resource definition (CRD) file") |
| 54 | + |
| 55 | + // Generate CRD file |
| 56 | + if err := generator.RenderDeployCrdFile(apiVersion, kind); err != nil { |
| 57 | + cmdError.ExitWithError(cmdError.ExitError, fmt.Errorf("failed to generate CRD file: (%v)", err)) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func verifyCrdFlags() { |
| 62 | + if len(apiVersion) == 0 { |
| 63 | + cmdError.ExitWithError(cmdError.ExitBadArgs, errors.New("--api-version must not have empty value")) |
| 64 | + } |
| 65 | + if len(kind) == 0 { |
| 66 | + cmdError.ExitWithError(cmdError.ExitBadArgs, errors.New("--kind must not have empty value")) |
| 67 | + } |
| 68 | +} |
0 commit comments