From 0ba085bdb35386acbbba364327c249c7918b2ac2 Mon Sep 17 00:00:00 2001 From: Wiktor Zykubek Date: Sat, 28 Dec 2024 20:44:10 +0100 Subject: [PATCH] feat: handle new template format --- go.mod | 2 ++ go.sum | 3 +++ main.go | 41 +++++++++++++++++++++++++++++++++++++++-- 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 go.sum diff --git a/go.mod b/go.mod index c8226ec..c16dd31 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module git.brono.cloud/wzykubek/licensmith go 1.23.4 + +require gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..4bc0337 --- /dev/null +++ b/go.sum @@ -0,0 +1,3 @@ +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 4a3aed2..57cd281 100644 --- a/main.go +++ b/main.go @@ -11,6 +11,8 @@ import ( "strings" "text/template" "time" + + "gopkg.in/yaml.v3" ) type LicensingData struct { @@ -19,11 +21,21 @@ type LicensingData struct { Year int } +type LicenseData struct { + FullName string `yaml:"title"` + ID string `yaml:"spdx-id"` + Description string `yaml:"description"` // TODO + Permissions []string `yaml:"permissions"` // TODO + Limitations []string `yaml:"limitations"` // TODO + Conditions []string `yaml:"conditions"` // TODO +} + //go:embed all:templates var Templates embed.FS var GitConfigError = errors.New("Can't read Git config") var NotSupportedError = errors.New("Not supported license") +var InvalidFrontMatter = errors.New("Template front matter is invalid") func getGitUserData() (string, string, error) { var userData [2]string @@ -59,9 +71,34 @@ func listTemplates() { fmt.Println(strings.Join(tmplList, ", ")) } +func parseFrontMatter(tmplPath string) (LicenseData, string, error) { + data, err := Templates.ReadFile(tmplPath) + if err != nil { + panic(err) + } + + parts := strings.SplitN(string(data), "---", 3) + if len(parts) < 3 { + return LicenseData{}, "", InvalidFrontMatter + } + + var licenseData LicenseData + err = yaml.Unmarshal([]byte(parts[1]), &licenseData) + if err != nil { + return LicenseData{}, "", InvalidFrontMatter + } + + return licenseData, strings.TrimSpace(parts[2]), nil +} + func genLicense(lcnsName string, lcnsData LicensingData, outFileName string) error { tmplFile := "templates/" + lcnsName + ".tmpl" - tmpl, err := template.ParseFS(Templates, tmplFile) + _, lcnsBody, err := parseFrontMatter(tmplFile) + if err != nil { + panic(err) + } + + tmpl, err := template.New(lcnsName).Parse(lcnsBody) if err != nil { return NotSupportedError } @@ -88,7 +125,7 @@ func main() { ListTemplates := flag.Bool("list", false, "List available licenses") flag.Parse() - *License = strings.ToUpper(*License) + *License = strings.ToUpper(*License) if *ListTemplates { listTemplates()