diff --git a/cmd/kubecfg/kubecfg.go b/cmd/kubecfg/kubecfg.go index a26c788c555..39392922e65 100644 --- a/cmd/kubecfg/kubecfg.go +++ b/cmd/kubecfg/kubecfg.go @@ -24,6 +24,7 @@ import ( "os" "strconv" "strings" + "text/template" "time" kube_client "github.com/GoogleCloudPlatform/kubernetes/pkg/client" @@ -50,6 +51,8 @@ var ( verbose = flag.Bool("verbose", false, "If true, print extra information") proxy = flag.Bool("proxy", false, "If true, run a proxy to the api server") www = flag.String("www", "", "If -proxy is true, use this directory to serve static files") + templateFile = flag.String("template_file", "", "If present load this file as a golang template and us it for output printing") + templateStr = flag.String("template", "", "If present parse this string as a golang template and us it for output printing") ) func usage() { @@ -184,11 +187,32 @@ func executeAPIRequest(method string, s *kube_client.Client) bool { } var printer kubecfg.ResourcePrinter - if *json { + switch { + case *json: printer = &kubecfg.IdentityPrinter{} - } else if *yaml { + case *yaml: printer = &kubecfg.YAMLPrinter{} - } else { + case len(*templateFile) > 0 || len(*templateStr) > 0: + var data []byte + if len(*templateFile) > 0 { + var err error + data, err = ioutil.ReadFile(*templateFile) + if err != nil { + glog.Fatalf("Error reading template %s, %v\n", *templateFile, err) + return false + } + } else { + data = []byte(*templateStr) + } + tmpl, err := template.New("output").Parse(string(data)) + if err != nil { + glog.Fatalf("Error parsing template %s, %v\n", string(data), err) + return false + } + printer = &kubecfg.TemplatePrinter{ + Template: tmpl, + } + default: printer = &kubecfg.HumanReadablePrinter{} } diff --git a/pkg/kubecfg/resource_printer.go b/pkg/kubecfg/resource_printer.go index bb6066a5a96..39864f75859 100644 --- a/pkg/kubecfg/resource_printer.go +++ b/pkg/kubecfg/resource_printer.go @@ -22,6 +22,7 @@ import ( "io" "strings" "text/tabwriter" + "text/template" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" @@ -235,3 +236,19 @@ func (h *HumanReadablePrinter) PrintObj(obj interface{}, output io.Writer) error return err } } + +type TemplatePrinter struct { + Template *template.Template +} + +func (t *TemplatePrinter) Print(data []byte, w io.Writer) error { + obj, err := api.Decode(data) + if err != nil { + return err + } + return t.PrintObj(obj, w) +} + +func (t *TemplatePrinter) PrintObj(obj interface{}, w io.Writer) error { + return t.Template.Execute(w, obj) +}