Skip to content

Commit

Permalink
Unmarshal entire config
Browse files Browse the repository at this point in the history
  • Loading branch information
ahobsonsayers committed Sep 20, 2024
1 parent 453f075 commit 8b4f319
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 24 deletions.
45 changes: 23 additions & 22 deletions cmd/twitchets/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,41 +15,42 @@ type Config struct {
Events []twickets.Filter `json:"events"`
}

func (c *Config) parseKoanf(k *koanf.Koanf) error {
if k == nil {
return nil
func (c Config) Validate() error {
if c.Country.Value == "" {
return errors.New("country must be set")
}

// Parse country
countryString := k.String("country")
if countryString == "" {
return errors.New("country must be set")
for _, event := range c.Events {
err := event.Validate()
if err != nil {
return err
}
}
country := twickets.Countries.Parse(countryString)
if country == nil {
return fmt.Errorf("%s is not a valid country code", countryString)

return nil
}

func (c *Config) parseKoanf(k *koanf.Koanf) error {
if k == nil {
return nil
}

// Parse filters
var events []twickets.Filter
// Parse config
var config Config
err := k.UnmarshalWithConf(
"events", &events,
"", &config,
koanf.UnmarshalConf{Tag: `json`},
)
if err != nil {
return fmt.Errorf("invalid events: %w", err)
return fmt.Errorf("failed to unmarshal config: %w", err)
}

for _, event := range events {
err = event.Validate()
if err != nil {
return err
}
err = config.Validate()
if err != nil {
return fmt.Errorf("invalid config: %w", err)
}

c.Country = *country
c.Events = events

*c = config
return nil
}

Expand Down
16 changes: 14 additions & 2 deletions twickets/location.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

type Country enum.Member[string]

func (d *Country) UnmarshalJSON(data []byte) error {
func (c *Country) UnmarshalJSON(data []byte) error {
var countryString string
err := json.Unmarshal(data, &countryString)
if err != nil {
Expand All @@ -20,7 +20,19 @@ func (d *Country) UnmarshalJSON(data []byte) error {
if country == nil {
return fmt.Errorf("country '%s' is not valid", countryString)
}
*d = *country

*c = *country
return nil
}

func (c *Country) UnmarshalText(data []byte) error {
countryString := string(data)
country := Countries.Parse(countryString)
if country == nil {
return fmt.Errorf("country '%s' is not valid", countryString)
}

*c = *country
return nil
}

Expand Down

0 comments on commit 8b4f319

Please sign in to comment.