diff --git a/precheckin.sh b/precheckin.sh index dd5bdf78..61c04441 100755 --- a/precheckin.sh +++ b/precheckin.sh @@ -3,12 +3,12 @@ gofmt -w . golint go test +go build # acceptance test -go build -X=$(./yaml r sample.yaml b.c) +X=$(./yaml w sample.yaml b.c 3 | ./yaml r - b.c) -if [ $X != 2 ] +if [ $X != 3 ] then echo "Failed acceptance test: expected 2 but was $X" exit 1 diff --git a/yaml.go b/yaml.go index a9ac6d31..bf507c71 100644 --- a/yaml.go +++ b/yaml.go @@ -53,27 +53,40 @@ Outputs to STDOUT unless the inplace flag is used, in which case the file is upd } func readProperty(cmd *cobra.Command, args []string) { + printYaml(read(args)) +} + +func read(args []string) interface{} { var parsedData map[interface{}]interface{} readYaml(args[0], &parsedData) if len(args) == 1 { - printYaml(parsedData) - os.Exit(0) + return parsedData } var paths = parsePath(args[1]) - printYaml(readMap(parsedData, paths[0], paths[1:len(paths)])) + return readMap(parsedData, paths[0], paths[1:len(paths)]) } func writeProperty(cmd *cobra.Command, args []string) { + updatedData := updateYaml(args) + if writeInplace { + ioutil.WriteFile(args[0], []byte(yamlToString(updatedData)), 0644) + } else { + printYaml(updatedData) + } +} + +func updateYaml(args []string) interface{} { var writeCommands map[string]interface{} if writeScript != "" { readYaml(writeScript, &writeCommands) } else if len(args) < 3 { die("Must provide ") } else { + writeCommands = make(map[string]interface{}) writeCommands[args[1]] = parseValue(args[2]) } @@ -84,13 +97,9 @@ func writeProperty(cmd *cobra.Command, args []string) { var paths = parsePath(path) write(parsedData, paths[0], paths[1:len(paths)], value) } - - if writeInplace { - ioutil.WriteFile(args[0], []byte(yamlToString(parsedData)), 0644) - } else { - printYaml(parsedData) - } + return parsedData } + func parseValue(argument string) interface{} { var value, err interface{} var inQuotes = argument[0] == '"' diff --git a/yaml_test.go b/yaml_test.go index 105f1656..9365040f 100644 --- a/yaml_test.go +++ b/yaml_test.go @@ -20,3 +20,17 @@ func TestParseValue(t *testing.T) { assertResultWithContext(t, tt.expectedResult, parseValue(tt.argument), tt.testDescription) } } + +func TestRead(t *testing.T) { + result := read([]string{"sample.yaml", "b.c"}) + assertResult(t, 2, result) +} + +func TestUpdateYaml(t *testing.T) { + updateYaml([]string{"sample.yaml", "b.c", "3"}) +} + +func TestUpdateYaml_WithScript(t *testing.T) { + writeScript = "instruction_sample.yaml" + updateYaml([]string{"sample.yaml"}) +}