support output-dir for 'helm template' cmd

pull/3143/head
Rajat Jindal 8 years ago
parent 15053e6750
commit f908decf1b

@ -21,6 +21,7 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
@ -39,6 +40,7 @@ import (
tversion "k8s.io/helm/pkg/version" tversion "k8s.io/helm/pkg/version"
) )
const defaultDirectoryPermission = 0755
const templateDesc = ` const templateDesc = `
Render chart templates locally and display the output. Render chart templates locally and display the output.
@ -64,6 +66,7 @@ type templateCmd struct {
releaseName string releaseName string
renderFiles []string renderFiles []string
kubeVersion string kubeVersion string
outputDir string
} }
func newTemplateCmd(out io.Writer) *cobra.Command { func newTemplateCmd(out io.Writer) *cobra.Command {
@ -126,6 +129,14 @@ func (t *templateCmd) run(cmd *cobra.Command, args []string) error {
} }
} }
// verify that output-dir exists if provided
if outputDir != "" {
_, err = os.Stat(outputDir)
if os.IsNotExist(err) {
panic(fmt.Sprintf("output-dir '%s' does not exist", outputDir))
}
}
if t.namespace == "" { if t.namespace == "" {
t.namespace = defaultNamespace() t.namespace = defaultNamespace()
} }
@ -248,8 +259,58 @@ func (t *templateCmd) run(cmd *cobra.Command, args []string) error {
if strings.HasPrefix(b, "_") { if strings.HasPrefix(b, "_") {
continue continue
} }
fmt.Printf("---\n# Source: %s\n", m.Name) writeData(m.name, data)
fmt.Println(data)
} }
return nil return nil
} }
func writeData(name string, data string) {
if outputDir != "" {
writeToFile(name, data)
return
}
writeToStdout(name, data)
}
// write the <data> to stdout
func writeToStdout(name string, data string) {
fmt.Printf("---\n# Source: %s\n", name)
fmt.Printf(data)
}
// write the <data> to <output-dir>/<name>
func writeToFile(name string, data string) {
outfileName := strings.Join([]string{outputDir, name}, string(filepath.Separator))
ensureDirectoryForFile(outfileName)
f, err := os.Create(outfileName)
if err != nil {
panic(err)
}
defer f.Close()
_, err = f.WriteString(fmt.Sprintf("---\n# Source: %s\n%s", name, data))
if err != nil {
panic(err)
}
fmt.Printf("wrote %s\n", outfileName)
return
}
// check if the directory exists to create file. creates if don't exists
func ensureDirectoryForFile(file string) {
baseDir := path.Dir(file)
_, err := os.Stat(baseDir)
if !os.IsNotExist(err) {
return
}
err = os.MkdirAll(baseDir, defaultDirectoryPermission)
if err != nil {
panic(err)
}
}

Loading…
Cancel
Save