Skip to content
This repository has been archived by the owner on Jun 14, 2022. It is now read-only.

Allow Go code comments to be used as source of schema descriptions #106

Merged
merged 6 commits into from
Feb 3, 2022
Merged

Conversation

samlown
Copy link
Contributor

@samlown samlown commented Dec 22, 2021

This is a bit of an experimental feature for consideration.

Our use-case is that we want to be able to use a single set of "descriptions" for both Go documentation and the generated JSON Schema. It get's boring very quickly adding both a comment describing a type of field, and a jsonschema_description.

This PR adds a CommentsMap property to the reflector which is essentially a dictionary that maps fully qualified package paths alongside types and fields, pointing to comment strings.

The AddGoComments method included in the Reflector takes a base import module and a path, extracts all the comments, and adds them to the CommentsMap:

r := new(jsonschema.Reflector)
if err := r.AddGoComments("github.com/alecthomas/jsonschema", "./examples"); err != nil {
  // deal with error
}

I couldn't figure out a way to automatically determine the full module name, so it has to be defined manually for each package you'd like to use comments from.

The end result is that you can define Go comments, and have them imported into your Schema. The tests provide a complete example of the results. One of the big advantages of this approach is that it makes it much easier to add descriptions to types.

@alecthomas
Copy link
Owner

This is an interesting idea, I quite like it.

//
// When parsing type comments, we use the `go/doc`'s Synopsis method to extract the first phrase
// only. Field comments, which tend to be much short, will include everything.
func (r *Reflector) AddGoComments(base, path string) error {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be good to move this to a new file, this is getting quite long.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. I'll see what I can do.

@samlown samlown marked this pull request as ready for review December 30, 2021 18:07
@samlown
Copy link
Contributor Author

samlown commented Dec 30, 2021

I've extracted the main comment parser part to it's own file with a "reflector independent" method. Please let me know if you'd prefer a different approach!

@alecthomas alecthomas merged commit cc89723 into alecthomas:master Feb 3, 2022
@alecthomas
Copy link
Owner

Thanks!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
2 participants