————————————————
type kustomizeOptions struct {//kustomize结构体 kustomizationDir string }
//创建kustomize命令 func NewCmdKustomize(streams genericclioptions.IOStreams) *cobra.Command { var o kustomizeOptions cmd := &cobra.Command{//创建cobra命令 Use: "kustomize <dir>", Short: i18n.T("Build a kustomization target from a directory or a remote url."), Long: kustomizeLong, Example: kustomizeExample, RunE: func(cmd *cobra.Command, args []string) error { err := o.Validate(args)//校验 if err != nil { return err } return kustomize.RunKustomizeBuild(streams.Out, fs.MakeRealFS(), o.kustomizationDir)//运行 }, } return cmd }
func (o *kustomizeOptions) Validate(args []string) error {//校验 if len(args) > 1 {//参数不能大于1个 return errors.New("specify one path to a kustomization directory") } if len(args) == 0 {//如果参数是0个,则目录为当前目录 o.kustomizationDir = "./" } else { o.kustomizationDir = args[0]//设置目录 } return nil }
//运行kustomize build func RunKustomizeBuild(out io.Writer, fSys fs.FileSystem, path string) error { f := k8sdeps.NewFactory() o := build.NewOptions(path, "") return o.RunBuild(out, fSys, f.ResmapF, f.TransformerF) }
func (o *Options) RunBuild( out io.Writer, fSys fs.FileSystem, rf *resmap.Factory, ptf transformer.Factory) error {//运行build ldr, err := loader.NewLoader(o.kustomizationPath, fSys)//创建loader if err != nil { return err } defer ldr.Cleanup() kt, err := target.NewKustTarget(ldr, rf, ptf)//创建target if err != nil { return err } allResources, err := kt.MakeCustomizedResMap()//构建customize资源 if err != nil { return err } // Output the objects. res, err := allResources.EncodeAsYaml()//把资源转成yaml if err != nil { return err } if o.outputPath != "" { return fSys.WriteFile(o.outputPath, res) } _, err = out.Write(res)//输出yaml资源 return err }