pass io.Writer when marshaling

don't assume stdout, pass it as io.Writer
This commit is contained in:
Randall McPherson 2016-12-14 15:25:10 -05:00
parent 7f34743bb5
commit 7e55582dde
4 changed files with 11 additions and 11 deletions

View File

@ -19,7 +19,7 @@ package main
import (
"encoding/json"
"fmt"
"os"
"io"
"github.com/spf13/cobra"
api "k8s.io/kops/pkg/apis/kops"
@ -58,19 +58,19 @@ func init() {
type marshalFunc func(obj runtime.Object) ([]byte, error)
func marshalToStdout(obj runtime.Object, marshal marshalFunc) error {
func marshalToWriter(obj runtime.Object, marshal marshalFunc, w io.Writer) error {
b, err := marshal(obj)
if err != nil {
return err
}
_, err = os.Stdout.Write(b)
_, err = w.Write(b)
if err != nil {
return fmt.Errorf("error writing to stdout: %v", err)
}
return nil
}
// v must be a pointer to a marshalable object
// obj must be a pointer to a marshalable object
func marshalYaml(obj runtime.Object) ([]byte, error) {
y, err := api.ToVersionedYaml(obj)
if err != nil {
@ -79,7 +79,7 @@ func marshalYaml(obj runtime.Object) ([]byte, error) {
return y, nil
}
// v must be a pointer to a marshalable object
// obj must be a pointer to a marshalable object
func marshalJSON(obj runtime.Object) ([]byte, error) {
j, err := json.MarshalIndent(obj, "", " ")
if err != nil {

View File

@ -120,14 +120,14 @@ func (c *GetClustersCmd) Run(args []string) error {
case OutputYaml:
for _, cluster := range clusters {
if err := marshalToStdout(cluster, marshalYaml); err != nil {
if err := marshalToWriter(cluster, marshalYaml, os.Stdout); err != nil {
return err
}
}
return nil
case OutputJSON:
for _, cluster := range clusters {
if err := marshalToStdout(cluster, marshalJSON); err != nil {
if err := marshalToWriter(cluster, marshalJSON, os.Stdout); err != nil {
return err
}
}

View File

@ -87,13 +87,13 @@ func RunGetFederations(context Factory, out io.Writer, options *GetFederationOpt
case OutputYaml:
for _, f := range federations {
if err := marshalToStdout(f, marshalYaml); err != nil {
if err := marshalToWriter(f, marshalYaml, os.Stdout); err != nil {
return err
}
}
case OutputJSON:
for _, f := range federations {
if err := marshalToStdout(f, marshalJSON); err != nil {
if err := marshalToWriter(f, marshalJSON, os.Stdout); err != nil {
return err
}
}

View File

@ -120,13 +120,13 @@ func (c *GetInstanceGroupsCmd) Run(args []string) error {
case OutputYaml:
for _, ig := range instancegroups {
if err := marshalToStdout(ig, marshalYaml); err != nil {
if err := marshalToWriter(ig, marshalYaml, os.Stdout); err != nil {
return err
}
}
case OutputJSON:
for _, ig := range instancegroups {
if err := marshalToStdout(ig, marshalJSON); err != nil {
if err := marshalToWriter(ig, marshalJSON, os.Stdout); err != nil {
return err
}
}