common.go 1.6 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
	"github.com/spf13/cobra"
LinuxSuRen's avatar
LinuxSuRen 已提交
9 10 11
	"gopkg.in/yaml.v2"
)

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

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

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

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

// 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
}
68

LinuxSuRen's avatar
LinuxSuRen 已提交
69 70 71 72
func (b *BatchOption) SetFlag(cmd *cobra.Command) {
	cmd.Flags().BoolVarP(&b.Batch, "batch", "b", false, "Batch mode, no need confirm")
}

73 74
// WatchOption for the resources which can be watched
type WatchOption struct {
LinuxSuRen's avatar
LinuxSuRen 已提交
75 76
	Watch    bool
	Interval int
77
}