Skip to content

Commit

Permalink
Use the embed package to embed the names catalogue file at compile time.
Browse files Browse the repository at this point in the history
  • Loading branch information
carloscasalar committed Dec 2, 2024
1 parent 761eaee commit 9df8f75
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 20 deletions.
6 changes: 6 additions & 0 deletions assets/embed_names.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package assets

import _ "embed"

//go:embed names.yml
var EmbedNames []byte
24 changes: 4 additions & 20 deletions pkg/generator/default_name_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down

0 comments on commit 9df8f75

Please sign in to comment.