about summary refs log tree commit diff stats
path: root/internal/config/cspgenerator.go
blob: 5ad3ef07bf650703abadf6ff94f1511670866806 (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
71
72
73
74
75
76
77
78
79
80
81
82
package config

//go:generate go run ../../cmd/cspgenerator/

import (
	"fmt"
	"os"
	"reflect"

	"github.com/crewjam/csp"
	"github.com/fatih/structtag"
)

func GenerateCSP() error {
	t := reflect.TypeFor[csp.Header]()
	file, err := os.OpenFile("./csp.go", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = fmt.Fprintf(file, `package config

// Code generated  DO NOT EDIT.

import (
	"github.com/crewjam/csp"
)

`)
	if err != nil {
		return err
	}

	_, err = fmt.Fprintf(file, "type CSP struct {\n")
	if err != nil {
		return err
	}

	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		var t reflect.Type
		if field.Type.Kind() == reflect.Slice {
			t = field.Type
		} else {
			t = field.Type
		}
		tags, err := structtag.Parse(string(field.Tag))
		if err != nil {
			return err
		}
		cspTag, err := tags.Get("csp")
		if err != nil {
			return err
		}
		err = tags.Set(&structtag.Tag{
			Key:  "toml",
			Name: cspTag.Name,
		})
		if err != nil {
			return err
		}

		_, err = fmt.Fprintf(file, "\t%-23s %-28s `%s`\n", field.Name, t, tags.String())
		if err != nil {
			return err
		}
	}
	_, err = fmt.Fprintln(file, "}")
	if err != nil {
		return err
	}

	_, err = fmt.Fprintln(file, `
func (c *CSP) String() string {
	return csp.Header(*c).String()
}`)
	if err != nil {
		return err
	}
	return nil
}