Generate imports wrong package and gives error
- 主要语言
- Go
- 星标
- 10.8k
- 派生
- 1.3k
- 平均合并
- 2 天 36 分钟
- 30 天内合并 PR
- 26
描述
### What happened?
When running `go run github.com/99designs/gqlgen generate` the generated resolver functions imports the wrong package.
if I use the [github.com/pkg/errors](https://github.com/pkg/errors) library in my resolvers and then later on I trigger the `generate` command, gqlgen will remove this import and instead import the standard library's `errors` package.
**PRE `go run github.com/99designs/gqlgen generate`**
```go
// user.resolvers.go
import (
"context"
"github.com/pkg/errors"
"github.com/foo/bar/app"
)
func (r *queryResolver) Me(ctx context.Context) (*app.User, error) {
user,err := app.UserFromContext(ctx)
if err != nil {
return nil, errors.Wrap(err, "no user in context")
}
return user, nil
}
```
**POST `go run github.com/99designs/gqlgen generate`**
```sh
validation failed: packages.Load: /github.com/foo/bar/graph/resolver/user.resolvers.go: Wrap not declared by package errors
```
Updated generated file...
```go
// user.resolvers.go
import (
"context"
"errors"
"github.com/foo/bar/app"
)
func (r *queryResolver) Me(ctx context.Context) (*app.User, error) {
user,err := app.UserFromContext(ctx)
if err != nil {
return nil, errors.Wrap(err, "no user in context")
}
return user, nil
}
```
So even though stdlib `errors` pkg doesn't have a `Wrap` function, it will still be added to the import statement rather than using the one that was previously declared `github.com/pkg/errors` followed by reporting that the function is not declared in that package.
**gqlconfig.yml**
```yml
schema:
- "graph/schema/**/*.graphql"
exec:
filename: graph/generated/generated.go
package: generated
resolver:
layout: follow-schema
dir: graph/resolver
package: resolver
struct_tag: gql
omit_slice_element_pointers: true
autobind:
- github.com/foo/bar/app
```
### What did you expect?
import / use the already declared package rather than attempting to import it's own
### Minimal graphql.schema and models to reproduce
```graphql
# schema/schema.graphql
schema {
query: Query
mutation: Mutation
}
type Query
type Mutation
```
```graphql
# schema/types/user.graphql
extend type Query {
me: User
}
type User {
id: ID!
email: String!
name: String
}
```
### versions
- `gqlgen version`? v0.11.3
- `go version`? 1.14
- dep or go modules? go mod
贡献指南
调研方向
问题出在处理导入的代码生成逻辑中。查看 resolver 生成代码,它很可能位于 `generate` 包中。测试用例涉及一个使用 `github.com/pkg/errors` 的 resolver。在最小示例上运行生成过程以复现问题,然后跟踪导入的解析和重写过程。修复应在使用 `errors.Wrap` 时保留正确的导入。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- go
- 领域
- backend, devtools
- Issue 类型
- 缺陷
- 难度
- 3/5
- 预计耗时
- 1-2 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 55/100