desc.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package env
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "maps"
  6. "os"
  7. "slices"
  8. "strings"
  9. )
  10. // Desc describes an environment variable
  11. type Desc struct {
  12. Name string
  13. Format string
  14. }
  15. // Describe creates a new EnvDesc
  16. func Describe(name string, format string) Desc {
  17. return Desc{
  18. Name: name,
  19. Format: format,
  20. }
  21. }
  22. // DescribeByMap creates a new EnvDesc with format based on a map keys
  23. func DescribeByMap[T any](name string, m map[string]T) Desc {
  24. format := strings.Join(slices.Collect(maps.Keys(m)), "|")
  25. return Describe(name, format)
  26. }
  27. // Getenv returns the value of the env variable
  28. func (d Desc) Get() (string, bool) {
  29. value := os.Getenv(d.Name)
  30. return value, len(value) > 0
  31. }
  32. // Warn logs a warning with the env var details
  33. func (d Desc) Warn(msg string, args ...any) {
  34. v, _ := d.Get()
  35. args = append(args, "name", d.Name, "format", d.Format, "value", v)
  36. slog.Warn(msg, args...)
  37. }
  38. // Errorf formats an error message for invalid env var
  39. func (d Desc) Errorf(msg string, args ...any) error {
  40. return fmt.Errorf(
  41. "invalid %s value (format: %s): %s",
  42. d.Name,
  43. d.Format,
  44. fmt.Sprintf(msg, args...),
  45. )
  46. }
  47. // WarnParseError logs a warning when an env var fails to parse
  48. func (d Desc) ErrorParse(err error) error {
  49. return d.Errorf("failed to parse: %s", err)
  50. }
  51. // ErrorEmpty formats an error message for empty env var
  52. func (d Desc) ErrorEmpty() error {
  53. return d.Errorf("cannot be empty")
  54. }
  55. // ErrorRange formats an error message for out of range env var
  56. func (d Desc) ErrorRange() error {
  57. return d.Errorf("out of range")
  58. }
  59. // ErrorZeroOrLess formats an error message for zero or less env var
  60. func (d Desc) ErrorZeroOrNegative() error {
  61. return d.Errorf("cannot be zero or negative")
  62. }
  63. // ErrorNegative formats an error message for negative env var
  64. func (d Desc) ErrorNegative() error {
  65. return d.Errorf("cannot be negative")
  66. }