cheekybits / genny

Elegant generics for Go
MIT License
1.71k stars 127 forks source link

genny imports.Parse usage drops aliased imports #19

Open falun opened 8 years ago

falun commented 8 years ago

Problem

If your genny templates include renamed imports they'll be incorrectly removed from the output. Initially I thought this was a bug in imports.Parse but when running goimports (which I believe uses the imports lib as it's backend) i don't see the same behavior.

I think what's going on is that because genny passes the generated code into imports.Parse without any imports included the renamed packages aren't able to resolve.

Repro case genny-test

Possible solution

  1. Add -trustImports which will bypass the import processing from imports; I've made this modification locally and it works well enough. Two issues with it a) you lose the implicit formatting that imports does for you b) it doesn't remove the generic import that you pick up from your template. I'm side stepped (b) by not compiling my templates and just leaving the generic import out.
  2. Don't strip imports from the cleaned output that gets passed into imports.Process. I think this should let imports do its thing without genny intervention.

I know 1 works, I didn't bother trying 2 as I found a suitable work around for my case.

Work around

Since 1 & 2 both require library changes some work arounds for anyone else that may hit this

  1. Just stop renaming! If that's not possible...
  2. declare your package imported as the name you're trying to use (i.e. package $name differs from directory); this may necessitate changes in other places the package is imported but often works...
  3. add a non-generated file that references the things you need access to within the imported package (in limited cases this is sufficient).
  4. and, lest we forget, fork genny and implement solution 1 or 2 (and provide a PR 😀)
falun commented 8 years ago

To update -- I implemented suggestion solution 2 and it totally works! ... Except in the case where you have multiple type completions (because the second pass through the imports break imports.Process since you shouldn't have imports in the middle of code).

I believe a modified version of 2 will work if you strip the imports only on pass >1; will take a shot at that soonish.