github.com/KusionStack/kpm@v0.8.4-0.20240326033734-dc72298a30e5/pkg/cmd/cmd_init.go (about) 1 // Copyright 2023 The KCL Authors. All rights reserved. 2 // Deprecated: The entire contents of this file will be deprecated. 3 // Please use the kcl cli - https://github.com/kcl-lang/cli. 4 5 package cmd 6 7 import ( 8 "fmt" 9 "os" 10 "path/filepath" 11 12 "github.com/urfave/cli/v2" 13 "kcl-lang.io/kpm/pkg/client" 14 "kcl-lang.io/kpm/pkg/env" 15 "kcl-lang.io/kpm/pkg/opt" 16 pkg "kcl-lang.io/kpm/pkg/package" 17 reporter "kcl-lang.io/kpm/pkg/reporter" 18 ) 19 20 // NewInitCmd new a Command for `kpm init`. 21 func NewInitCmd(kpmcli *client.KpmClient) *cli.Command { 22 return &cli.Command{ 23 Hidden: false, 24 Name: "init", 25 Usage: "initialize new module in current directory", 26 Action: func(c *cli.Context) error { 27 pwd, err := os.Getwd() 28 29 if err != nil { 30 return reporter.NewErrorEvent(reporter.Bug, err, "internal bugs, failed to load working directory.") 31 } 32 33 var pkgName string 34 var pkgRootPath string 35 // 1. If no package name is given, the current directory name is used as the package name. 36 if c.NArg() == 0 { 37 pkgName = filepath.Base(pwd) 38 pkgRootPath = pwd 39 } else { 40 // 2. If the package name is given, create a new directory for the package. 41 pkgName = c.Args().First() 42 pkgRootPath = filepath.Join(pwd, pkgName) 43 err = os.MkdirAll(pkgRootPath, 0755) 44 if err != nil { 45 return err 46 } 47 } 48 49 initOpts := opt.InitOptions{ 50 Name: pkgName, 51 InitPath: pkgRootPath, 52 } 53 54 err = initOpts.Validate() 55 if err != nil { 56 return err 57 } 58 59 kclPkg := pkg.NewKclPkg(&initOpts) 60 61 globalPkgPath, err := env.GetAbsPkgPath() 62 63 if err != nil { 64 return err 65 } 66 67 err = kclPkg.ValidateKpmHome(globalPkgPath) 68 69 if err != (*reporter.KpmEvent)(nil) { 70 return err 71 } 72 73 err = kpmcli.InitEmptyPkg(&kclPkg) 74 if err != nil { 75 return err 76 } 77 78 reporter.ReportMsgTo(fmt.Sprintf("package '%s' init finished", pkgName), kpmcli.GetLogWriter()) 79 return nil 80 }, 81 } 82 }