Skip to content

refactor: replace parser hierarchy with a single generic Parse - #223

Merged
obalunenko merged 3 commits into
masterfrom
refactor/internal-parse
Nov 15, 2026
Merged

obalunenko merged 3 commits into
masterfrom
refactor/internal-parse

Conversation

@obalunenko

@obalunenko obalunenko commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Description

A call like Env[int] went through three type switches (NewEnvParser → newIntParser → parseNumberGen), an EnvParser interface with 25 one-line implementations, an any result and a type assertion back to T. Adding a type meant touching about 7 places, and getX functions mixed the env lookup with parsing, so every parser test had to set environment variables.

This PR replaces internal/iface.go and internal/parsers.go with internal.Parse[T]:

  • one type switch over a pointer to the result, with one case per type and its slice (case *int, *[]int:). A small generic parseInto picks the parser or parseSlice. No interface, no any → T assertion;
  • a generic parseSlice for every slice type (it replaces 12 copies of the same loop);
  • strconv bit sizes from reflect.TypeFor[T]().Bits() instead of a switch and bitSize8 = 8 constants.

Env now does the lookup, and Parse does a pure string → T conversion.

Public API:

  • ErrNotSet and ErrInvalidValue alias the internal sentinels, so the publicError adapter is gone. errors.Is works as before.
  • The parser error is wrapped with %w, so errors.Is/errors.As now also reach the cause, for example strconv.ErrSyntax.
  • New getenv.Parsable, an alias of the constraint. Callers could not name internal.EnvParsable before, so they could not write their own generic helpers over Env. Env and EnvOrDefault signatures are unchanged (it is the same type).

Tests: about 9.7k lines of per-type tables become:

  • table tests for Parse with no env vars (all 48 types, plus overflow cases for sized ints and floats that were not covered before);
  • integration tests for Env/EnvOrDefault;
  • a fuzz test of the error contract: every error wraps ErrInvalidValue and comes with the zero value.

Net diff: +675 / −11284.

Testing

  • Behavior: the old getenv_test.go (4566 lines, public API only) and the examples, including the exact error text in ExampleEnv, passed unchanged against the new implementation before I rewrote the tests.
  • Tests: go test -race ./... passes. Coverage: getenv 100%, internal 98.9% (was 87.9%; the only uncovered line is the unreachable default panic), option 100%.
  • Fuzz: go test -fuzz FuzzParse -fuzztime 30s ./internal ran 2.8M executions with no failures.
  • Lint: both .golangci.yml and .golangci.pipe.yml report 0 issues.
  • Benchmark: BenchmarkEnvOrDefault went from 88 ns, 104 B, 4 allocs/op to 84 ns, 80 B, 3 allocs/op.

Possible failures/side-effects

Error messages change only where the old ones were unhelpful:

  • ErrNotSet no longer prints the key twice (...[KEY]: "KEY": not set → ...[KEY]: not set);
  • an empty separator says empty separator: invalid value instead of invalid value;
  • a bad IP says invalid IP address "x": invalid value instead of invalid value;
  • a bad slice element says which one (element 2: ...).

Parse has one default: panic branch. It cannot be reached while every constraint type has a case. It is there so that adding a type to the constraint without a parser fails loudly instead of silently returning a zero value.

Other notes

Parse is one flat type switch with 24 cases, so it carries //nolint:gocyclo,funlen. A flat dispatch is easier to read than splitting it to satisfy the cyclomatic-complexity metric. That metric is likely why the old code was layered. Sonar's go:S1479 (at most 30 switch branches) flagged the first version, which had a case per type and per slice, 49 branches in all. Pairing each type with its slice brings it to 25 branches and lists every type with its parser once. parseInto panics with a constant message so that it stays inlinable and the result does not escape to the heap.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (4ef5865) to head (5e1d7d9).

Additional details and impacted files
@@             Coverage Diff              @@
##           master      #223       +/-   ##
============================================
+ Coverage   88.48%   100.00%   +11.51%     
============================================
  Files           5         3        -2     
  Lines         382        97      -285     
============================================
- Hits          338        97      -241     
+ Misses         44         0       -44     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@obalunenko
obalunenko added this pull request to stack #226 November 15, 2026 18:26
The value went through three type switches, an EnvParser interface with
25 one-line implementations, an `any` result and a type assertion back
to T. Replace it with internal.Parse[T]: one type switch over a pointer
to the result, a generic parseSlice for every slice type, and strconv
bit sizes taken from reflect.TypeFor[T]().Bits().

- Env now does the lookup and Parse does pure string -> T conversion,
  so parsing is tested without touching the environment.
- ErrNotSet and ErrInvalidValue alias the internal sentinels, which
  removes the publicError adapter; errors.Is works as before.
- Parse wraps the parser error with %w, so errors.Is/As also reach the
  cause (for example strconv.ErrSyntax).
- Export Parsable, an alias of the type constraint, so callers can write
  their own generic helpers over Env.
- Tests: ~9.7k lines of per-type tables become table tests for Parse,
  integration tests for Env/EnvOrDefault and a fuzz test of the error
  contract.

Error messages change only where the old ones were unhelpful: the key
is no longer printed twice for ErrNotSet, and an empty separator, a bad
IP or a bad slice element now say what went wrong.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@obalunenko
obalunenko force-pushed the refactor/internal-parse branch from 333b20b to 931ef42 Compare November 15, 2026 18:38
obalunenko and others added 2 commits November 15, 2026 22:44
Sonar (go:S1479) flagged the 49 branches of the type switch in Parse.
Each type had two cases, one for the value and one for its slice. Pair
them, `case *int, *[]int:`, and let a small generic parseInto choose
between the parser and parseSlice. Parse has 24 cases instead of 48,
and every type with its parser is listed once.

parseInto panics with a constant message, so it stays inlinable and
the result does not escape to the heap: BenchmarkParse keeps 48 B and
2 allocs/op.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both panics guard against programming errors and cannot be reached
through Parse: the constraint rejects types without a parser at compile
time. Move the type switch from the generic Parse into a non-generic
parseValue(dst any, ...), so a test can pass it an unsupported type,
and test parseInto with a parser that does not match its destination.

The panic message names the type with reflect.TypeOf instead of
fmt.Sprintf("%T"): fmt would make dst escape and move the parsed value
to the heap. BenchmarkParse keeps 48 B and 2 allocs/op. Coverage of
internal is 100%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@obalunenko
obalunenko merged commit 9886d21 into master Nov 15, 2026
11 checks passed
@obalunenko
obalunenko deleted the refactor/internal-parse branch November 15, 2026 18:56
obalunenko added a commit that referenced this pull request Nov 15, 2026
* fix: put "invalid value" before the cause in parse errors

Parse wrapped the parser error first and ErrInvalidValue last, so the
message read backwards:

  strconv.ParseInt: parsing "x": invalid syntax: invalid value

Swap the operands so the message goes from the general error to its
cause, as Go error chains usually do:

  invalid value: strconv.ParseInt: parsing "x": invalid syntax

Only the text changes: errors.Is still matches both ErrInvalidValue and
the cause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(option): describe Option without the removed EnvParser

The EnvParser interface was removed with the parser hierarchy in #223,
but the Option comment still called it "a contract for EnvParser
parameters options". Describe what an option does instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
obalunenko added a commit that referenced this pull request Nov 15, 2026
* fix: put "invalid value" before the cause in parse errors

Parse wrapped the parser error first and ErrInvalidValue last, so the
message read backwards:

  strconv.ParseInt: parsing "x": invalid syntax: invalid value

Swap the operands so the message goes from the general error to its
cause, as Go error chains usually do:

  invalid value: strconv.ParseInt: parsing "x": invalid syntax

Only the text changes: errors.Is still matches both ErrInvalidValue and
the cause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(option): describe Option without the removed EnvParser

The EnvParser interface was removed with the parser hierarchy in #223,
but the Option comment still called it "a contract for EnvParser
parameters options". Describe what an option does instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep url.URL values out of parse errors

url.Parse returns a *url.Error that quotes the whole input, so an invalid
DSN such as postgres://user:password@host put the password into the error
and from there into logs. Return the underlying cause instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: merge internal and option into the root package

The option package could not import getenv, so the parameters it sets had
to live in a third package, internal. That leaked into the public API:
Option.Apply took an *internal.Parameters that callers cannot name, and
Parsable was an alias of internal.EnvParsable, so godoc did not list the
supported types and the package doc had to repeat them by hand.

Everything now lives in package getenv:

- Option, WithSeparator and WithTimeLayout. Option is sealed with an
  unexported method instead of by an unimportable parameter type.
- Parsable spells out its types, so godoc shows them and the package doc
  points there instead of repeating them.

Package option stays as a deprecated forwarder: option.Option is an alias
of getenv.Option, so existing calls keep compiling. Option.Apply is gone;
it could not be called outside the module, as internal.Parameters cannot
be constructed there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: state how slice values are split

Elements are not trimmed and a trailing separator adds an empty element.
Both are easy to trip over, so say it in the package doc and pin it with
tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: tidy error messages and split the examples

- Errors read `environment variable "KEY": not set` instead of
  `failed to get environment variable[KEY]: not set`: %q is the usual way
  to quote a name, and "failed to" only adds length to a wrapped chain.
- Use the literal base 10 for strconv: a named constant for it is noise.
- Replace the two examples that printed every type through an any with one
  short example per use case, so godoc shows the typed results and how to
  tell ErrNotSet from ErrInvalidValue.
- Regenerate the README examples. The old url.URL example printed the
  struct fields, not the URL its output claimed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: drop the unreachable return in parseURL

url.Parse wraps every error in *url.Error, so the fallback return never
ran and was the only statement left without coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant