common.go 1.0 KB
Newer Older
LinuxSuRen's avatar
LinuxSuRen 已提交
1 2 3 4 5 6 7 8 9
package cmd

import (
	"encoding/json"
	"fmt"

	"gopkg.in/yaml.v2"
)

LinuxSuRen's avatar
LinuxSuRen 已提交
10
// OutputOption represent the format of output
LinuxSuRen's avatar
LinuxSuRen 已提交
11 12 13 14
type OutputOption struct {
	Format string
}

LinuxSuRen's avatar
LinuxSuRen 已提交
15 16 17 18 19
// BatchOption represent the options for a batch operation
type BatchOption struct {
	Batch bool
}

20 21 22 23
type FormatOutput interface {
	Output(obj interface{}, format string) (data []byte, err error)
}

LinuxSuRen's avatar
LinuxSuRen 已提交
24
const (
25 26 27
	JsonOutputFormat  string = "json"
	YAMLOutputFormat  string = "yaml"
	TableOutputFormat string = "table"
LinuxSuRen's avatar
LinuxSuRen 已提交
28 29
)

30 31 32 33 34 35 36 37 38 39 40
func (o *OutputOption) Output(obj interface{}) (data []byte, err error) {
	switch o.Format {
	case JsonOutputFormat:
		return json.MarshalIndent(obj, "", "  ")
	case YAMLOutputFormat:
		return yaml.Marshal(obj)
	}

	return nil, fmt.Errorf("not support format %s", o.Format)
}

LinuxSuRen's avatar
LinuxSuRen 已提交
41 42 43 44 45 46 47 48 49
func Format(obj interface{}, format string) (data []byte, err error) {
	if format == JsonOutputFormat {
		return json.MarshalIndent(obj, "", "  ")
	} else if format == YAMLOutputFormat {
		return yaml.Marshal(obj)
	}

	return nil, fmt.Errorf("not support format %s", format)
}