Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

name generation of generic types #131

Open
olistrik opened this issue Jan 22, 2024 · 2 comments
Open

name generation of generic types #131

olistrik opened this issue Jan 22, 2024 · 2 comments
Labels
enhancement New feature or request

Comments

@olistrik
Copy link

Is it possible to customise how the names of generic references are generated?

If I have for example the following:

type Foo int
type Bar int


type FooMap[T any] map[Foo]T


type struct FooBar {
  FooBar FooMap[Bar]
}

The resulting $ref for the FooBar $def is FooMap[github.com/full/path/to/package.Bar].

I'd like to change this to FooMap[Bar].

@joshstrohminger
Copy link

joshstrohminger commented Feb 16, 2024

I wonder if this will be easier once Go exposes the generic child type via reflection, but for now I've been solving this with a recursive namer. I'm not sure what other types like arrays, maps, or slices show up as though.

var genericTypeRegex = regexp.MustCompile(`^(.+?)\[(.+)]$`)

func getSimpleTypeName(name string) string {
    parts := strings.Split(name, ".")
    return parts[len(parts)-1]
}

func getGenericName(name string) string {
    if matches := genericTypeRegex.FindStringSubmatch(name); matches != nil {
        parent := getSimpleTypeName(matches[1])
        child := getGenericName(matches[2])
        return fmt.Sprintf("%s[%s]", parent, child)
    }
    return getSimpleTypeName(name)
}

func nameGenerics(r reflect.Type) string {
    return getGenericName(r.Name())
}

and then use it like

reflector := jsonschema.Reflector{ Namer: nameGenerics }
s := reflector.Reflect(myType)

@samlown
Copy link
Contributor

samlown commented Feb 19, 2024

If you'd like to add some broken tests for this, it'd be easier to have a look and align expectations. Generics were not available when this library was first built!

@samlown samlown added the enhancement New feature or request label Feb 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants