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

import (
	"encoding/json"
	"fmt"

LinuxSuRen's avatar
LinuxSuRen 已提交
7
	"github.com/AlecAivazis/survey"
LinuxSuRen's avatar
LinuxSuRen 已提交
8 9 10
	"gopkg.in/yaml.v2"
)

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

16 17 18 19
type FormatOutput interface {
	Output(obj interface{}, format string) (data []byte, err error)
}

LinuxSuRen's avatar
LinuxSuRen 已提交
20
const (
21 22 23
	JsonOutputFormat  string = "json"
	YAMLOutputFormat  string = "yaml"
	TableOutputFormat string = "table"
LinuxSuRen's avatar
LinuxSuRen 已提交
24 25
)

26 27 28 29 30 31 32 33 34 35 36
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 已提交
37 38 39 40 41 42 43 44 45
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)
}
LinuxSuRen's avatar
LinuxSuRen 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

// BatchOption represent the options for a batch operation
type BatchOption struct {
	Batch bool
}

// Confirm prompte user if they really want to do this
func (b *BatchOption) Confirm(message string) bool {
	if !b.Batch {
		confirm := false
		prompt := &survey.Confirm{
			Message: message,
		}
		survey.AskOne(prompt, &confirm)
		if !confirm {
			return false
		}
	}

	return true
}
67 68 69

// WatchOption for the resources which can be watched
type WatchOption struct {
LinuxSuRen's avatar
LinuxSuRen 已提交
70 71
	Watch    bool
	Interval int
72
}