sigs.k8s.io/kubebuilder/v3@v3.14.0/pkg/cli/webhook.go (about)

     1  /*
     2  Copyright 2020 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package cli //nolint:dupl
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/spf13/cobra"
    23  
    24  	"sigs.k8s.io/kubebuilder/v3/pkg/plugin"
    25  )
    26  
    27  const webhookErrorMsg = "failed to create webhook"
    28  
    29  func (c CLI) newCreateWebhookCmd() *cobra.Command {
    30  	cmd := &cobra.Command{
    31  		Use:   "webhook",
    32  		Short: "Scaffold a webhook for an API resource",
    33  		Long: `Scaffold a webhook for an API resource.
    34  `,
    35  		RunE: errCmdFunc(
    36  			fmt.Errorf("webhook subcommand requires an existing project"),
    37  		),
    38  	}
    39  
    40  	// In case no plugin was resolved, instead of failing the construction of the CLI, fail the execution of
    41  	// this subcommand. This allows the use of subcommands that do not require resolved plugins like help.
    42  	if len(c.resolvedPlugins) == 0 {
    43  		cmdErr(cmd, noResolvedPluginError{})
    44  		return cmd
    45  	}
    46  
    47  	// Obtain the plugin keys and subcommands from the plugins that implement plugin.CreateWebhook.
    48  	subcommands := c.filterSubcommands(
    49  		func(p plugin.Plugin) bool {
    50  			_, isValid := p.(plugin.CreateWebhook)
    51  			return isValid
    52  		},
    53  		func(p plugin.Plugin) plugin.Subcommand {
    54  			return p.(plugin.CreateWebhook).GetCreateWebhookSubcommand()
    55  		},
    56  	)
    57  
    58  	// Verify that there is at least one remaining plugin.
    59  	if len(subcommands) == 0 {
    60  		cmdErr(cmd, noAvailablePluginError{"webhook creation"})
    61  		return cmd
    62  	}
    63  
    64  	c.applySubcommandHooks(cmd, subcommands, webhookErrorMsg, false)
    65  
    66  	return cmd
    67  }