Skip to content

feat: add AddPackageNamespaces option to disambiguate same-name types across packages - #194

Open
AZERDSQ131 wants to merge 1 commit into
invopop:mainfrom
AZERDSQ131:feat/add-package-namespaces
Open

feat: add AddPackageNamespaces option to disambiguate same-name types across packages#194
AZERDSQ131 wants to merge 1 commit into
invopop:mainfrom
AZERDSQ131:feat/add-package-namespaces

Conversation

@AZERDSQ131

Copy link
Copy Markdown

Fixes the case described in #42: two unrelated types with the same name (e.g. http.Config and tcp.Config) declared in different packages collide on the same $defs/$ref entry when both end up referenced in the same schema, silently producing an incorrect schema for one of them.

As suggested in the issue thread, this adds an opt-in Reflector.AddPackageNamespaces bool field. When set, typeName prefixes the type's name with the last segment of its package path (e.g. httpconf.Config, tcpconf.Config) instead of the bare type name, so colliding names get distinct $defs entries. It only applies when Namer doesn't already return a name for the type, and is fully opt-in (default false), so existing output is unaffected unless explicitly enabled.

Note: this repo previously had a similar FullyQualifyTypeNames option that was removed in 3330865 in favor of Namer/DoNotReference. That option always used the full package import path though; this one is scoped to the package's base name only (as the issue's proposed direction describes), and is documented as an additional option alongside Namer/DoNotReference rather than a replacement for either — updated the README's historical note and added a new "Type Naming and Conflicts" section accordingly.

Changes

  • reflect.go: new AddPackageNamespaces field on Reflector; typeName prefixes with path.Base(t.PkgPath()) when enabled and Namer didn't provide a name.
  • internal/nsfixture/{httpconf,tcpconf}: two fixture packages, each with a colliding Config type, used to reproduce the exact scenario from if we have same struct name, then we will got the same $ref #42 in a test.
  • reflect_test.go: TestAddPackageNamespacesDisambiguatesSameNameStructs — verifies distinct $defs/$ref entries with the option enabled, and confirms the pre-existing collision still happens with it disabled (default), as a regression guard.
  • README.md: documents the new option and cross-references it from the historical note about the removed FullyQualifyTypeNames.

Testing

  • go build ./..., go vet ./..., gofmt -l . (clean) and go test ./... all pass.

Fixes #42

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

if we have same struct name, then we will got the same $ref

1 participant