Repository navigation
refactor: replace parser hierarchy with a single generic Parse - #223
Merged
Merged
Conversation
This was referenced Nov 15, 2026
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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
force-pushed
the
refactor/internal-parse
branch
from
November 15, 2026 18:38
333b20b to
931ef42
Compare
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>
|
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Description
A call like
Env[int]went through three type switches (NewEnvParser→newIntParser→parseNumberGen), anEnvParserinterface with 25 one-line implementations, ananyresult and a type assertion back toT. Adding a type meant touching about 7 places, andgetXfunctions mixed the env lookup with parsing, so every parser test had to set environment variables.This PR replaces
internal/iface.goandinternal/parsers.gowithinternal.Parse[T]:case *int, *[]int:). A small genericparseIntopicks the parser orparseSlice. No interface, noany→Tassertion;parseSlicefor every slice type (it replaces 12 copies of the same loop);reflect.TypeFor[T]().Bits()instead of a switch andbitSize8 = 8constants.Envnow does the lookup, andParsedoes a purestring → Tconversion.Public API:
ErrNotSetandErrInvalidValuealias the internal sentinels, so thepublicErroradapter is gone.errors.Isworks as before.%w, soerrors.Is/errors.Asnow also reach the cause, for examplestrconv.ErrSyntax.getenv.Parsable, an alias of the constraint. Callers could not nameinternal.EnvParsablebefore, so they could not write their own generic helpers overEnv.EnvandEnvOrDefaultsignatures are unchanged (it is the same type).Tests: about 9.7k lines of per-type tables become:
Parsewith no env vars (all 48 types, plus overflow cases for sized ints and floats that were not covered before);Env/EnvOrDefault;ErrInvalidValueand comes with the zero value.Net diff: +675 / −11284.
Testing
getenv_test.go(4566 lines, public API only) and the examples, including the exact error text inExampleEnv, passed unchanged against the new implementation before I rewrote the tests.go test -race ./...passes. Coverage: getenv 100%, internal 98.9% (was 87.9%; the only uncovered line is the unreachabledefaultpanic), option 100%.go test -fuzz FuzzParse -fuzztime 30s ./internalran 2.8M executions with no failures..golangci.ymland.golangci.pipe.ymlreport 0 issues.BenchmarkEnvOrDefaultwent 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:
ErrNotSetno longer prints the key twice (...[KEY]: "KEY": not set→...[KEY]: not set);empty separator: invalid valueinstead ofinvalid value;invalid IP address "x": invalid valueinstead ofinvalid value;element 2: ...).Parsehas onedefault: panicbranch. 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
Parseis 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'sgo: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.parseIntopanics with a constant message so that it stays inlinable and the result does not escape to the heap.🤖 Generated with Claude Code