-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemplatefile.go
More file actions
83 lines (71 loc) · 1.88 KB
/
templatefile.go
File metadata and controls
83 lines (71 loc) · 1.88 KB
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
81
82
83
package main
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"github.com/webdevops/go-common/log/slogger"
"github.com/webdevops/helm-azure-tpl/azuretpl"
)
type (
TemplateFile struct {
Context context.Context
SourceFile string
TargetFile string
TemplateBaseDir string
Logger *slogger.Logger
}
)
func (f *TemplateFile) Lint() {
var buf strings.Builder
f.Logger.Info(`linting file`)
f.parse(&buf)
f.Logger.Info(`file successfully linted`)
}
func (f *TemplateFile) Apply() {
var buf strings.Builder
f.Logger.Info(`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.Error(err.Error())
os.Exit(1)
}
}
func (f *TemplateFile) write(buf *strings.Builder) {
f.Logger.Info(`writing file`, slog.String("path", f.TargetFile))
err := os.WriteFile(f.TargetFile, []byte(buf.String()), 0600)
if err != nil {
f.Logger.Error(`unable to write target file`, slog.String("path", f.TargetFile), slog.Any("error", err.Error()))
os.Exit(1)
}
}