golang linter 总是抱怨

问:如何解决lintersireturn和nolintlintlinters 之间的疯狂问题?


细节:


我有一个带有这个签名的 Golang 函数


func NewClientCredentialsTokenSource(

    issuer string,

    clientId string,

    clientSecret string,

    scope []string,

) (oauth2.TokenSource, error) {

当我运行 golangci-lint v1.43.0 它报告


golangci-lint run

oidc/token_utils.go:19:1: NewClientCredentialsTokenSource returns interface (golang.org/x/oauth2.TokenSource) (ireturn)

func NewClientCredentialsTokenSource(

由于该函数只有两个返回参数,因此很容易推断出它在抱怨oauth2.TokenSource而不是在抱怨error。


调用的下游函数NewClientCredentialsTokenSource返回一个实例,oauth2.TokenSource所以我没有要返回的具体类型。没办法,只好返回oauth2.TokenSource接口。


所以我向函数添加了一个 lint 异常,如下所示:


//nolint:ireturn

func NewClientCredentialsTokenSource(

    issuer string,

    clientId string,

    clientSecret string,

    scope []string,

) (oauth2.TokenSource, error) {

你会认为应该解决它但不是!现在报告了一个新的 lint 问题:


golangci-lint run

oidc/token_utils.go:19:1: directive `//nolint:ireturn` is unused for linter "ireturn" (nolintlint)

//nolint:ireturn

所以现在我在追我的尾巴。ireturn抱怨我正在返回一个界面。我为该函数添加了一个例外只是nolintlint抱怨我有一个不适用的例外。


男人要做什么?


侃侃尔雅
浏览 134回答 3
3回答

沧海一幻觉

我尝试按照 Nico Huysamen 的建议添加允许规则,但这打开了一罐蠕虫。最后我还是想相信ireturnlinter,还不想禁用它。我认为解决此问题的最简洁方法是为两个 linter 添加一个异常,ireturn如下nolintlint所示://nolint:nolintlint,ireturnfunc NewClientCredentialsTokenSource(    issuer string,    clientId string,    clientSecret string,    scope []string,) (oauth2.TokenSource, error) {2022 年 5 月 25 日更新:也许更好的解决方案如下所示。由于某种原因,ireturn异常必须进入函数签名。func NewPasswordGrantTokenSource( //nolint:ireturn    issuer string,    clientId string,    clientSecret string,    username string,    password string,    scope []string,) (oauth2.TokenSource, error) {

小怪兽爱吃肉

.golangci.yml您可以如上所述允许这样做,但由于它取代了标准的 defaults,您也需要包含它们,因此您需要:  ireturn:    # ireturn allows using `allow` and `reject` settings at the same time.    # Both settings are lists of the keywords and regular expressions matched to interface or package names.    # keywords:    # - `empty` for `interface{}`    # - `error` for errors    # - `stdlib` for standard library    # - `anon` for anonymous interfaces    # By default, it allows using errors, empty interfaces, anonymous interfaces,    # and interfaces provided by the standard library.    allow:      - anon      - error      - empty      - stdlib      # You can specify idiomatic endings for interface      - (or|er)$      # Your custom interfaces go here:      - golang.org/x/oauth2.TokenSource

眼眸繁星

您可以将接口添加到ireturn的允许接口列表中。ireturn --allow="golang.org/x/oauth2.TokenSource"或通过中的linter-settings部分.golangci.ymllinters-settings:  ireturn:    allow:      - golang.org/x/oauth2.TokenSource
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go