From 9df8f75f2f4b6c7de86df00e5bfe11fb2fb1519d Mon Sep 17 00:00:00 2001 From: Carlos Castillo Date: Mon, 2 Dec 2024 23:31:24 +0100 Subject: [PATCH] Use the embed package to embed the names catalogue file at compile time. --- assets/embed_names.go | 6 ++++++ pkg/generator/default_name_generator.go | 24 ++++-------------------- 2 files changed, 10 insertions(+), 20 deletions(-) create mode 100644 assets/embed_names.go diff --git a/assets/embed_names.go b/assets/embed_names.go new file mode 100644 index 0000000..e5a3fcd --- /dev/null +++ b/assets/embed_names.go @@ -0,0 +1,6 @@ +package assets + +import _ "embed" + +//go:embed names.yml +var EmbedNames []byte diff --git a/pkg/generator/default_name_generator.go b/pkg/generator/default_name_generator.go index 63f9471..139ed4c 100644 --- a/pkg/generator/default_name_generator.go +++ b/pkg/generator/default_name_generator.go @@ -2,38 +2,22 @@ package generator import ( "fmt" + "github.com/carloscasalar/traveller-npc-generator/assets" "gopkg.in/yaml.v3" - "os" - "path/filepath" - "runtime" ) func NewDefaultNameGenerator() (NameGenerator, error) { - const relativeNamesFilePath = "../../assets/names.yml" - absoluteNamesFilePath := absolutePath(relativeNamesFilePath) - namesConfigFile, err := os.ReadFile(absoluteNamesFilePath) - if err != nil { - return nil, fmt.Errorf("error reading names config file at %v: %v\n", absoluteNamesFilePath, err) - } var config nameConfig - err = yaml.Unmarshal(namesConfigFile, &config) - if err != nil { - return nil, fmt.Errorf("error reading names config file at %v: %v\n", absoluteNamesFilePath, err) + if err := yaml.Unmarshal(assets.EmbedNames, &config); err != nil { + return nil, fmt.Errorf("error unmarshalling names config file: %v", err) } if err := config.Validate(); err != nil { - return nil, fmt.Errorf("error parsing names config file at %v: %v\n", absoluteNamesFilePath, err) + return nil, fmt.Errorf("error parsing names config file: %v", err) } return NewCatalogSourcedNameGenerator(config.Surnames, config.NonGenderedNames, config.FemaNames, config.MaleNames), nil } -func absolutePath(relativeNamesFilePath string) string { - _, currentFilePath, _, _ := runtime.Caller(0) - currentDir := filepath.Dir(currentFilePath) - absoluteNamesFilePath := filepath.Join(currentDir, relativeNamesFilePath) - return absoluteNamesFilePath -} - type nameConfig struct { Surnames []string `yaml:",flow"` NonGenderedNames []string `yaml:"non_gendered_names,flow"`