summaryrefslogtreecommitdiff
path: root/template.go
blob: 67cd565e305d9e48c67b75ba1207d9b504b41c4c (plain)
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
package main

import (
	"embed"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path"

	"golang.org/x/text/encoding/charmap"
)

const verbatimPath = "templates/verbatim"

//go:embed templates/verbatim
var verbatim embed.FS

//goland:noinspection GoUnhandledErrorResult
func writeVerbatimFile(outputDir string, entry fs.DirEntry) error {
	inName := path.Join(verbatimPath, entry.Name())

	input, err := verbatim.Open(inName)
	if err != nil {
		return fmt.Errorf("reading bundled file '%s': %w", entry.Name(), err)
	}
	defer input.Close()

	outName := path.Join(outputDir, entry.Name())
	output, err := os.Create(outName)
	if err != nil {
		return fmt.Errorf("creating '%s': %w", outName, err)
	}
	defer output.Close()

	encodedOutput := charmap.ISO8859_1.NewEncoder().Writer(output)

	if _, err = io.Copy(encodedOutput, input); err != nil {
		return fmt.Errorf("writing to '%s': %w", outName, err)
	}

	return nil
}

func writeVerbatim(outputDir string) error {
	entries, err := verbatim.ReadDir(verbatimPath)
	if err != nil {
		return err
	}

	for _, e := range entries {
		if err = writeVerbatimFile(outputDir, e); err != nil {
			return err
		}
	}

	return nil
}

func write(config EngardeConfig) error {
	if err := os.MkdirAll(config.outputDir, 0755); err != nil {
		return fmt.Errorf("creating output directory '%s': %w", config.outputDir, err)
	}

	if err := writeVerbatim(config.outputDir); err != nil {
		return fmt.Errorf("copying default files: %w", err)
	}

	return nil
}