-
Notifications
You must be signed in to change notification settings - Fork 0
/
templatefile.go
80 lines (68 loc) · 1.78 KB
/
templatefile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"go.uber.org/zap"
"github.com/webdevops/helm-azure-tpl/azuretpl"
)
type (
TemplateFile struct {
Context context.Context
SourceFile string
TargetFile string
TemplateBaseDir string
Logger *zap.SugaredLogger
}
)
func (f *TemplateFile) Lint() {
var buf strings.Builder
f.Logger.Infof(`linting file`)
f.parse(&buf)
f.Logger.Info(`file successfully linted`)
}
func (f *TemplateFile) Apply() {
var buf strings.Builder
f.Logger.Infof(`process file`)
f.parse(&buf)
if opts.Debug {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, strings.Repeat("-", TermColumns))
fmt.Fprintf(os.Stderr, "--- %v\n", f.TargetFile)
fmt.Fprintln(os.Stderr, strings.Repeat("-", TermColumns))
fmt.Fprintln(os.Stderr, buf.String())
}
if opts.Stdout {
fmt.Println("--- # src: " + f.SourceFile)
fmt.Println(buf.String())
fmt.Println()
return
}
if !opts.DryRun {
f.write(&buf)
} else {
f.Logger.Warn(`not writing file, DRY RUN active`)
}
}
func (f *TemplateFile) parse(buf *strings.Builder) {
ctx := f.Context
contextLogger := f.Logger
azureTemplate := azuretpl.New(ctx, opts.AzureTpl, contextLogger)
azureTemplate.SetUserAgent(UserAgent + gitTag)
azureTemplate.SetLintMode(lintMode)
azureTemplate.SetTemplateRootPath(f.TemplateBaseDir)
azureTemplate.SetTemplateRelPath(filepath.Dir(f.SourceFile))
err := azureTemplate.Parse(f.SourceFile, templateData, buf)
if err != nil {
f.Logger.Fatalf(err.Error())
}
}
func (f *TemplateFile) write(buf *strings.Builder) {
f.Logger.Infof(`writing file '%v'`, f.TargetFile)
err := os.WriteFile(f.TargetFile, []byte(buf.String()), 0600)
if err != nil {
f.Logger.Fatalf(`unable to write target file '%v': %v`, f.TargetFile, err.Error())
}
}