Skip to content

Commit 6b566fd

Browse files
committed
Refactored code
1 parent 001925a commit 6b566fd

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

yaml.go

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,20 @@ var inputJSON = false
1717
var outputToJSON = false
1818

1919
func main() {
20-
var cmdRead = &cobra.Command{
20+
var cmdRead = createReadCmd()
21+
var cmdWrite = createWriteCmd()
22+
23+
var rootCmd = &cobra.Command{Use: "yaml"}
24+
rootCmd.PersistentFlags().BoolVarP(&trimOutput, "trim", "t", true, "trim yaml output")
25+
rootCmd.PersistentFlags().BoolVarP(&outputToJSON, "tojson", "j", false, "output as json")
26+
rootCmd.PersistentFlags().BoolVarP(&inputJSON, "fromjson", "J", false, "input as json")
27+
28+
rootCmd.AddCommand(cmdRead, cmdWrite)
29+
rootCmd.Execute()
30+
}
31+
32+
func createReadCmd() *cobra.Command {
33+
return &cobra.Command{
2134
Use: "read [yaml_file] [path]",
2235
Aliases: []string{"r"},
2336
Short: "yaml r sample.yaml a.b.c",
@@ -27,11 +40,13 @@ yaml r - a.b.c (reads from stdin)
2740
yaml r things.yaml a.*.c
2841
yaml r things.yaml a.array[0].blah
2942
yaml r things.yaml a.array[*].blah
30-
`,
43+
`,
3144
Long: "Outputs the value of the given path in the yaml file to STDOUT",
3245
Run: readProperty,
3346
}
47+
}
3448

49+
func createWriteCmd() *cobra.Command {
3550
var cmdWrite = &cobra.Command{
3651
Use: "write [yaml_file] [path] [value]",
3752
Aliases: []string{"w"},
@@ -42,7 +57,7 @@ yaml write --inplace things.yaml a.b.c cat
4257
yaml w -i things.yaml a.b.c cat
4358
yaml w --script update_script.yaml things.yaml
4459
yaml w -i -s update_script.yaml things.yaml
45-
`,
60+
`,
4661
Long: `Updates the yaml file w.r.t the given path and value.
4762
Outputs to STDOUT unless the inplace flag is used, in which case the file is updated instead.
4863
@@ -58,14 +73,7 @@ a.b.e:
5873
}
5974
cmdWrite.PersistentFlags().BoolVarP(&writeInplace, "inplace", "i", false, "update the yaml file inplace")
6075
cmdWrite.PersistentFlags().StringVarP(&writeScript, "script", "s", "", "yaml script for updating yaml")
61-
62-
var rootCmd = &cobra.Command{Use: "yaml"}
63-
rootCmd.PersistentFlags().BoolVarP(&trimOutput, "trim", "t", true, "trim yaml output")
64-
rootCmd.PersistentFlags().BoolVarP(&outputToJSON, "tojson", "j", false, "output as json")
65-
rootCmd.PersistentFlags().BoolVarP(&inputJSON, "fromjson", "J", false, "input as json")
66-
67-
rootCmd.AddCommand(cmdRead, cmdWrite)
68-
rootCmd.Execute()
76+
return cmdWrite
6977
}
7078

7179
func readProperty(cmd *cobra.Command, args []string) {

0 commit comments

Comments
 (0)