Serge Bazanski | be538db | 2020-11-12 00:22:42 +0100 | [diff] [blame] | 1 | // Copyright 2017 The kubecfg authors |
| 2 | // |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | package kubecfg |
| 17 | |
| 18 | import ( |
| 19 | "encoding/json" |
| 20 | "fmt" |
| 21 | "io" |
| 22 | |
| 23 | yaml "gopkg.in/yaml.v2" |
| 24 | "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 25 | ) |
| 26 | |
| 27 | // ShowCmd represents the show subcommand |
| 28 | type ShowCmd struct { |
| 29 | Format string |
| 30 | } |
| 31 | |
| 32 | func (c ShowCmd) Run(apiObjects []*unstructured.Unstructured, out io.Writer) error { |
| 33 | switch c.Format { |
| 34 | case "yaml": |
| 35 | for _, obj := range apiObjects { |
| 36 | fmt.Fprintln(out, "---") |
| 37 | // Urgh. Go via json because we need |
| 38 | // to trigger the custom scheme |
| 39 | // encoding. |
| 40 | buf, err := json.Marshal(obj) |
| 41 | if err != nil { |
| 42 | return err |
| 43 | } |
| 44 | o := map[string]interface{}{} |
| 45 | if err := json.Unmarshal(buf, &o); err != nil { |
| 46 | return err |
| 47 | } |
| 48 | buf, err = yaml.Marshal(o) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | out.Write(buf) |
| 53 | } |
| 54 | case "json": |
| 55 | enc := json.NewEncoder(out) |
| 56 | enc.SetIndent("", " ") |
| 57 | for _, obj := range apiObjects { |
| 58 | // TODO: this is not valid framing for JSON |
| 59 | if len(apiObjects) > 1 { |
| 60 | fmt.Fprintln(out, "---") |
| 61 | } |
| 62 | if err := enc.Encode(obj); err != nil { |
| 63 | return err |
| 64 | } |
| 65 | } |
| 66 | default: |
| 67 | return fmt.Errorf("Unknown --format: %s", c.Format) |
| 68 | } |
| 69 | |
| 70 | return nil |
| 71 | } |