————————————————
type ViewLastAppliedOptions struct {//viewlastapplied结构体 FilenameOptions resource.FilenameOptions Selector string LastAppliedConfigurationList []string OutputFormat string All bool Factory cmdutil.Factory genericclioptions.IOStreams }
func NewViewLastAppliedOptions(ioStreams genericclioptions.IOStreams) *ViewLastAppliedOptions {//初始化结构体 return &ViewLastAppliedOptions{ OutputFormat: "yaml", IOStreams: ioStreams, } }
//创建viewLastApplied命令 func NewCmdApplyViewLastApplied(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { options := NewViewLastAppliedOptions(ioStreams)//初始化结构体 cmd := &cobra.Command{//创建cobra命令 Use: "view-last-applied (TYPE [NAME | -l label] | TYPE/NAME | -f FILENAME)", DisableFlagsInUseLine: true, Short: i18n.T("View latest last-applied-configuration annotations of a resource/object"), Long: applyViewLastAppliedLong, Example: applyViewLastAppliedExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(options.Complete(cmd, f, args))//准备 cmdutil.CheckErr(options.Validate(cmd))//校验 cmdutil.CheckErr(options.RunApplyViewLastApplied(cmd))//运行 }, } cmd.Flags().StringVarP(&options.OutputFormat, "output", "o", options.OutputFormat, "Output format. Must be one of yaml|json")//输出选项 cmd.Flags().StringVarP(&options.Selector, "selector", "l", options.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")//selector选项 cmd.Flags().BoolVar(&options.All, "all", options.All, "Select all resources in the namespace of the specified resource types")//all选项 usage := "that contains the last-applied-configuration annotations" cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage)//文件选项 return cmd }
//准备 func (o *ViewLastAppliedOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error { cmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()//获取名称空间和enforce名称空间 if err != nil { return err } r := f.NewBuilder(). Unstructured(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, &o.FilenameOptions). ResourceTypeOrNameArgs(enforceNamespace, args...). SelectAllParam(o.All). LabelSelectorParam(o.Selector). Latest(). Flatten(). Do()//用builder构造result对象 err = r.Err() if err != nil { return err } err = r.Visit(func(info *resource.Info, err error) error {visit result if err != nil { return err } configString, err := util.GetOriginalConfiguration(info.Object)//获取last-applied-configuration配置 if err != nil { return err } if configString == nil {//配置为空返回错误 return cmdutil.AddSourceToErr(fmt.Sprintf("no last-applied-configuration annotation found on resource: %s\n", info.Name), info.Source, err) } o.LastAppliedConfigurationList = append(o.LastAppliedConfigurationList, string(configString))//追加配置 return nil }) if err != nil { return err } return nil } // Validate checks ViewLastAppliedOptions for validity. func (o *ViewLastAppliedOptions) Validate(cmd *cobra.Command) error { return nil }
//运行 func (o *ViewLastAppliedOptions) RunApplyViewLastApplied(cmd *cobra.Command) error { for _, str := range o.LastAppliedConfigurationList {//遍历配置 switch o.OutputFormat { case "json"://json格式输出 jsonBuffer := &bytes.Buffer{} err := json.Indent(jsonBuffer, []byte(str), "", " ") if err != nil { return err } fmt.Fprint(o.Out, string(jsonBuffer.Bytes())) case "yaml"://yaml格式输出 yamlOutput, err := yaml.JSONToYAML([]byte(str)) if err != nil { return err } fmt.Fprint(o.Out, string(yamlOutput)) default: return cmdutil.UsageErrorf( cmd, "Unexpected -o output mode: %s, the flag 'output' must be one of yaml|json", o.OutputFormat) } } return nil }