-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplating.go
More file actions
53 lines (44 loc) · 1.57 KB
/
templating.go
File metadata and controls
53 lines (44 loc) · 1.57 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
package contempt
import (
"bytes"
"encoding/json"
"fmt"
"github.com/csmith/contempt/pkg/materials"
"github.com/csmith/contempt/pkg/template"
"github.com/csmith/contempt/pkg/template/sources"
"io/fs"
"log/slog"
"os"
"path/filepath"
)
var engine *template.Engine
func InitTemplates(imageRegistry, alpineMirror string, includes fs.FS) {
engine = template.NewEngine(
slog.New(slog.NewTextHandler(os.Stdout, nil)),
includes,
)
engine.Register(sources.AlpinePackagesSource(alpineMirror))
engine.Register(sources.ImageSource(imageRegistry))
engine.Register(sources.GitSource())
engine.Register(sources.HttpSource())
engine.Register(sources.AlpineReleaseSource(alpineMirror))
engine.Register(sources.GoReleaseSource())
engine.Register(sources.PostgresReleaseSource())
engine.Register(sources.UtilSource())
}
func Generate(sourceLink, inBase, inRelativePath, outFile string) ([]materials.Change, error) {
oldMaterials := materials.Read(outFile)
inFile := filepath.Join(inBase, inRelativePath)
writer := &bytes.Buffer{}
newMaterials, err := engine.Execute(writer, inFile)
if err != nil {
return nil, fmt.Errorf("unable to render template file %s: %v", outFile, err)
}
bom, _ := json.Marshal(newMaterials)
header := fmt.Sprintf("# Generated from %s%s\n# BOM: %s\n\n", sourceLink, inRelativePath, bom)
content := append([]byte(header), writer.Bytes()...)
if err := os.WriteFile(outFile, content, os.FileMode(0600)); err != nil {
return nil, fmt.Errorf("unable to write container file to %s: %v", outFile, err)
}
return materials.Diff(oldMaterials, newMaterials), nil
}