Skip to content

Commit

Permalink
refmt: add set subcommand
Browse files Browse the repository at this point in the history
  • Loading branch information
rjeczalik committed Oct 30, 2017
1 parent a526389 commit 8321d9f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
18 changes: 18 additions & 0 deletions format.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,23 @@ func (f *Format) Merge(orig, mixin, out string) error {
return f.marshal(morig, out)
}

func (f *Format) Set(in, key, value string) error {
v, err := f.unmarshal(in)
if fi, e := os.Stat(in); os.IsNotExist(e) || fi.Size() == 0 {
v = make(map[string]interface{})
} else if err != nil {
return err
}
vobj, ok := v.(map[string]interface{})
if !ok {
return fmt.Errorf("original object is %T, expected %T", v, (map[string]interface{})(nil))
}
if err := object.SetFlatKeyValue(vobj, key, value); err != nil {
return fmt.Errorf("unable to set %s=%s: %s", key, value, err)
}
return f.marshal(vobj, in)
}

func (f *Format) stdin() io.Reader {
if f.Stdin != nil {
return f.Stdin
Expand Down Expand Up @@ -219,3 +236,4 @@ func jsonMarshal(v interface{}) ([]byte, error) {

func Refmt(in, out string) error { return f.Refmt(in, out) }
func Merge(orig, mixin, out string) error { return f.Merge(orig, mixin, out) }
func Set(in, key, value string) error { return f.Set(in, key, value) }
8 changes: 7 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ If MIXIN_FILE's extension is not recognized or MIXIN_FILE is "-" (stdin),
refmt will try to guess mixin format.
If OUTPUT_FILE is "-" (stdout), destination format type is required to be
passed with -t flag.`
passed with -t flag.
refmt [-t type] set INPUT_FILE key value
`

func die(v ...interface{}) {
fmt.Fprintln(os.Stderr, v...)
Expand All @@ -55,6 +59,8 @@ func main() {

var err error
switch flag.Arg(0) {
case "set":
err = Set(flag.Arg(1), flag.Arg(2), flag.Arg(3))
case "merge":
err = Merge(flag.Arg(1), flag.Arg(2), flag.Arg(3))
default:
Expand Down

0 comments on commit 8321d9f

Please sign in to comment.