80
|
1 |
// Copyright © 2017 Mikael Berthe <mikael@lilotux.net> |
|
2 |
// |
|
3 |
// Licensed under the MIT license. |
|
4 |
// Please see the LICENSE file is this directory. |
|
5 |
|
|
6 |
package cmd |
|
7 |
|
|
8 |
import ( |
|
9 |
"fmt" |
|
10 |
"io/ioutil" |
|
11 |
"os" |
|
12 |
|
|
13 |
"github.com/pkg/errors" |
|
14 |
"github.com/spf13/cobra" |
|
15 |
"github.com/spf13/viper" |
|
16 |
|
|
17 |
"github.com/McKael/madonctl/printer" |
|
18 |
) |
|
19 |
|
|
20 |
func checkOutputFormat(cmd *cobra.Command, args []string) error { |
|
21 |
of := viper.GetString("output") |
|
22 |
switch of { |
|
23 |
case "", "plain", "json", "yaml", "template": |
|
24 |
return nil // Accepted |
|
25 |
} |
|
26 |
return errors.Errorf("output format '%s' not supported", of) |
|
27 |
} |
|
28 |
|
|
29 |
// getOutputFormat return the requested output format, defaulting to "plain". |
|
30 |
func getOutputFormat() string { |
|
31 |
of := viper.GetString("output") |
|
32 |
if of == "" { |
|
33 |
of = "plain" |
|
34 |
} |
|
35 |
// Override format if a template is provided |
|
36 |
if of == "plain" && (outputTemplate != "" || outputTemplateFile != "") { |
|
37 |
// If the format is plain and there is a template option, |
|
38 |
// set the format to "template". |
|
39 |
of = "template" |
|
40 |
} |
|
41 |
return of |
|
42 |
} |
|
43 |
|
|
44 |
// getPrinter returns a resource printer for the requested output format. |
|
45 |
func getPrinter() (printer.ResourcePrinter, error) { |
|
46 |
var opt string |
|
47 |
of := getOutputFormat() |
|
48 |
|
|
49 |
// Initialize color mode |
|
50 |
switch viper.GetString("color") { |
|
51 |
case "on", "yes", "force": |
|
52 |
printer.ColorMode = 1 |
|
53 |
case "off", "no": |
|
54 |
printer.ColorMode = 2 |
|
55 |
} |
|
56 |
|
|
57 |
if of == "template" { |
|
58 |
opt = outputTemplate |
|
59 |
if outputTemplateFile != "" { |
|
60 |
tmpl, err := ioutil.ReadFile(outputTemplateFile) |
|
61 |
if err != nil { |
|
62 |
return nil, err |
|
63 |
} |
|
64 |
opt = string(tmpl) |
|
65 |
} |
|
66 |
} |
|
67 |
return printer.NewPrinter(of, opt) |
|
68 |
} |
|
69 |
|
|
70 |
func errPrint(format string, a ...interface{}) (n int, err error) { |
|
71 |
return fmt.Fprintf(os.Stderr, format+"\n", a...) |
|
72 |
} |