gopoet icon indicating copy to clipboard operation
gopoet copied to clipboard

Add option to customize imported package names

Open gonzojive opened this issue 4 years ago • 3 comments

Without this, I don't believe it's possible to specify the alias used by a GoFile. This can be important if gopoet would otherwise output an un-aliased import that is not desired.

e.g.

poet was producing

import "x/y/z/blah_go_proto"

Such imports are disliked by the lint tool we use.

See related issue #10.

gonzojive avatar Oct 03 '21 01:10 gonzojive

Instead of a new registration method, I think it might instead be better to provide an option (new vararg param) to ImportSpecs that tells it to always use an alias if the package name differs from the import path's bae name, and also add that to WriteGoFile.

As you see from the checks and possible errors, the import aliases are not intended to be explicitly managed because of the fact that it is easy for the caller to make an error and provide the same path with a different alias or the re-use the same alias for a different import path.

A new configuration option instead of the new registration method could work. What about adding such an option to NewGoFile and NewImportsFor? Or just adding a configuration option or two that can be set on an *Imports object? My concern with adding an option to ImportSpecs is it will not provide enough control - I need to ensure the package name values being generated by Imports are valid.

I did some experimenting here with gopoet but felt it was a bit verbose: https://github.com/gonzojive/gopoet/commits/fix-10

I also put some import management facilities into a totally separate package: https://pkg.go.dev/github.com/google/[email protected]/codegen In that code, there is a "suggestAliases" method that can be customized (see here and here). There is also a UseAssumedPackageNameFunc option that allows specifying the logic used to guess a package name from an import path, and there is also a copy of the logic used by the go tools (which is slightly more nuanced than path.Base).

gonzojive avatar Oct 04 '21 03:10 gonzojive

The latest commit removes the new method and uses a vararg option to NewGoFile to configure how ImportSpecs and identifier prefixes get generated. Please take a look.

(Relevant commit: https://github.com/jhump/gopoet/pull/11/commits/859c06de4aeb9930b68b5f3ee93f43c215dbb308)

gonzojive avatar Oct 05 '21 01:10 gonzojive

Any comments on the latest revision of the pull request? I'm using it in the version of gopoet at Google, and it's useful for dealing with the linter's quirks.

gonzojive avatar Oct 24 '21 20:10 gonzojive