欢迎关注我的公众号:
————————————————----------------------------------------------------------------------------------------
type RoleBindingOpts struct {//rolebinding结构体
CreateSubcommandOptions *CreateSubcommandOptions
}
//创建rolebinding命令
func NewCmdCreateRoleBinding(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := &RoleBindingOpts{//初始化结构体
CreateSubcommandOptions: NewCreateSubcommandOptions(ioStreams),
}
cmd := &cobra.Command{//创建cobra命令
Use: "rolebinding NAME --clusterrole=NAME|--role=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run]",
DisableFlagsInUseLine: true,
Short: i18n.T("Create a RoleBinding for a particular Role or ClusterRole"),
Long: roleBindingLong,
Example: roleBindingExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))//准备运行
cmdutil.CheckErr(o.Run())//运行
},
}
o.CreateSubcommandOptions.PrintFlags.AddFlags(cmd)//设置print选项
cmdutil.AddApplyAnnotationFlags(cmd)//设置save-config选项
cmdutil.AddValidateFlags(cmd)//设置validate选项
cmdutil.AddGeneratorFlags(cmd, generateversioned.RoleBindingV1GeneratorName)//设置generator选项
cmd.Flags().String("clusterrole", "", i18n.T("ClusterRole this RoleBinding should reference"))//设置clusterrole选项
cmd.Flags().String("role", "", i18n.T("Role this RoleBinding should reference"))//设置role选项
cmd.Flags().StringArray("user", []string{}, "Usernames to bind to the role")//设置user选项
cmd.Flags().StringArray("group", []string{}, "Groups to bind to the role")//设置group选项
cmd.Flags().StringArray("serviceaccount", []string{}, "Service accounts to bind to the role, in the format <namespace>:<name>")//设置serviceaccount选项
return cmd
}
//准备方法
func (o *RoleBindingOpts) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)//获取名称
if err != nil {
return err
}
var generator generate.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case generateversioned.RoleBindingV1GeneratorName://获取generator name并判断
generator = &generateversioned.RoleBindingGeneratorV1{//构造generator对象
Name: name,
ClusterRole: cmdutil.GetFlagString(cmd, "clusterrole"),
Role: cmdutil.GetFlagString(cmd, "role"),
Users: cmdutil.GetFlagStringArray(cmd, "user"),
Groups: cmdutil.GetFlagStringArray(cmd, "group"),
ServiceAccounts: cmdutil.GetFlagStringArray(cmd, "serviceaccount"),
}
default:
return errUnsupportedGenerator(cmd, generatorName)
}
return o.CreateSubcommandOptions.Complete(f, cmd, args, generator)//运行createSubCommandOption的complete方法
}
// Run calls the CreateSubcommandOptions.Run in RoleBindingOpts instance
func (o *RoleBindingOpts) Run() error {//运行命令
return o.CreateSubcommandOptions.Run()//运行createSubCommandOption的run方法
}