github.com/KusionStack/kpm@v0.8.4-0.20240326033734-dc72298a30e5/pkg/cmd/cmd_import.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 11 "github.com/urfave/cli/v2" 12 "kcl-lang.io/kcl-go/pkg/tools/gen" 13 "kcl-lang.io/kpm/pkg/client" 14 "kcl-lang.io/kpm/pkg/reporter" 15 ) 16 17 // NewImportCmd new a Command for `kpm import`. 18 func NewImportCmd(kpmcli *client.KpmClient) *cli.Command { 19 return &cli.Command{ 20 Hidden: false, 21 Name: "import", 22 Usage: "convert other formats to KCL file", 23 Description: `import converts other formats to KCL file. 24 25 Supported conversion modes: 26 json: convert JSON data to KCL data 27 yaml: convert YAML data to KCL data 28 gostruct: convert Go struct to KCL schema 29 jsonschema: convert JSON schema to KCL schema 30 terraformschema: convert Terraform schema to KCL schema 31 auto: automatically detect the input format`, 32 ArgsUsage: "<file>", 33 Flags: []cli.Flag{ 34 &cli.StringFlag{ 35 Name: "mode", 36 Aliases: []string{"m"}, 37 Usage: "mode of import", 38 DefaultText: "auto", 39 Value: "auto", 40 }, 41 &cli.StringFlag{ 42 Name: "output", 43 Aliases: []string{"o"}, 44 Usage: "output filename", 45 }, 46 &cli.BoolFlag{ 47 Name: "force", 48 Aliases: []string{"f"}, 49 Usage: "force overwrite output file", 50 }, 51 }, 52 Action: func(c *cli.Context) error { 53 if c.Args().Len() != 1 { 54 return fmt.Errorf("invalid arguments") 55 } 56 inputFile := c.Args().First() 57 58 opt := &gen.GenKclOptions{} 59 switch c.String("mode") { 60 case "json": 61 opt.Mode = gen.ModeJson 62 case "yaml": 63 opt.Mode = gen.ModeYaml 64 case "gostruct": 65 opt.Mode = gen.ModeGoStruct 66 case "jsonschema": 67 opt.Mode = gen.ModeJsonSchema 68 case "terraformschema": 69 opt.Mode = gen.ModeTerraformSchema 70 case "auto": 71 opt.Mode = gen.ModeAuto 72 default: 73 return fmt.Errorf("invalid mode: %s", c.String("mode")) 74 } 75 76 outputFile := c.String("output") 77 if outputFile == "" { 78 outputFile = "generated.k" 79 reporter.ReportMsgTo("output file not specified, use default: generated.k", kpmcli.GetLogWriter()) 80 } 81 82 if _, err := os.Stat(outputFile); err == nil && !c.Bool("force") { 83 return fmt.Errorf("output file already exist, use --force to overwrite: %s", outputFile) 84 } 85 86 outputWriter, err := os.Create(outputFile) 87 if err != nil { 88 return reporter.NewErrorEvent(reporter.FailedCreateFile, err, fmt.Sprintf("failed to create output file: %s", outputFile)) 89 } 90 91 return gen.GenKcl(outputWriter, inputFile, nil, opt) 92 }, 93 } 94 }