From b8c32640196618b697b3c6ca58d416097f87dd3d Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Tue, 8 May 2018 11:15:57 +0200 Subject: fix(main): Handle errors & logic when templating to directory This does several changes to the new "template to directory" feature introduced in the previous commit: 1. Errors are now "handled". In classic Go-style, it is of course all too easy to do absolutely nothing with errors, but we can't have that. I'm onto you, Renee French's husband! 2. Resource sets containing similarly named files are now templated correctly by prepending the resource set name to the filename. 3. In the same vein as the previous point, nested resource sets are now also output correctly by replacing slashes (`/`) with dashes (`-`) to guarantee that the output files are a flat list. Some minor cosmetic fixes have also been applied. --- main.go | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index 7d0b33aa772e..bd5d4cbaf1e7 100644 --- a/main.go +++ b/main.go @@ -19,6 +19,7 @@ import ( "fmt" "os" "os/exec" + "strings" "github.com/tazjin/kontemplate/context" "github.com/tazjin/kontemplate/templater" @@ -99,19 +100,45 @@ func templateCommand() { continue } - for _, r := range rs.Resources { - fmt.Fprintf(os.Stderr, "Rendered file %s/%s:\n", rs.Name, r.Filename) - if *templateOutputDir != "" { - os.MkdirAll(*templateOutputDir, 0777) - f, _ := os.Create(*templateOutputDir + "/" + r.Filename) - fmt.Fprintf(f, r.Rendered) - } else { + if *templateOutputDir != "" { + templateIntoDirectory(templateOutputDir, rs) + } else { + for _, r := range rs.Resources { + fmt.Fprintf(os.Stderr, "Rendered file %s/%s:\n", rs.Name, r.Filename) fmt.Println(r.Rendered) } } } } +func templateIntoDirectory(outputDir *string, rs templater.RenderedResourceSet) { + // Attempt to create the output directory if it does not + // already exist: + if err := os.MkdirAll(*templateOutputDir, 0775); err != nil { + app.Fatalf("Could not create output directory: %v\n", err) + } + + // Nested resource sets may contain slashes in their names. + // These are replaced with dashes for the purpose of writing a + // flat list of output files: + setName := strings.Replace(rs.Name, "/", "-", -1) + + for _, r := range rs.Resources { + filename := fmt.Sprintf("%s/%s-%s", *templateOutputDir, setName, r.Filename) + fmt.Fprintf(os.Stderr, "Writing file %s\n", filename) + + file, err := os.Create(filename) + if err != nil { + app.Fatalf("Could not create file %s: %v\n", filename, err) + } + + _, err = fmt.Fprintf(file, r.Rendered) + if err != nil { + app.Fatalf("Error writing file %s: %v\n", filename, err) + } + } +} + func applyCommand() { ctx, resources := loadContextAndResources(applyFile) -- cgit 1.4.1