英文:
File is not `gofmt`-ed with `-s`: why is this happening and how to resolve it?
问题
我们使用一个(针对Golang的)代码检查工具,在每次打开或更新拉取请求时通过Github Actions工作流运行。
最近它开始返回以下错误:
文件未使用`-s`(gofmt)进行格式化
在这个其他的PR中发生了这种情况,涉及到文件pkg/api/api/go
。
<br>(编辑:添加链接以评估并可能重现错误)
证据:
我想了解这个错误的来源,以及如何解决它?
英文:
We use a linter (for Golang) that run through a Github Actions workflow every time we open or update a Pull Request on our repository.
It recently started to return the following error:
File is not `gofmt`-ed with `-s` (gofmt)
After what happened in this other PR to the file pkg/api/api/go
.
<br>(EDIT: link added to evaluate and eventually reproduce the error)
Evidences:
I would like to understand what was the source of this error, as well as how to resolve it?
答案1
得分: 20
错误的来源
看起来当文件没有按照Go规则正确格式化时,会返回这个错误。
例如:如果你意外地使用了制表符缩进而不是空格。
编辑:blackgreen的答案提供了关于错误来源的更准确细节。
如何解决
你可以使用以下Go命令:
gofmt -s -w <path_to_file>.go
...然后提交代码。
请注意,在我的情况下:gofmt -w pkg/api/api.go
就足以解决问题(没有使用-s
标志,这让我感到奇怪,因为错误明确要求使用-s
)。
英文:
Source of the error
It seems this error can be returned when the file is not properly formatted according to Go rules.
For example: If you accidentally used tab indentation rather than spaces.
EDIT: blackgreen's answer gives more accurate details about the source of the error
How to resolve it
You can use the following Go command:
gofmt -s -w <path_to_file>.go
... then commit the code.
Note that in my case: gofmt -w pkg/api/api.go
was enough to resolve the problem (without the -s
flag, which I found strange as the error specifically asked for the -s
).
答案2
得分: 6
gofmt
中的-s
标志与格式化无关,而是与简化代码有关。你可以在gofmt的文档中找到相关信息:
尝试简化代码(应用重写规则后)。
你看到的警告来自于linter工具golangci-lint
。由于你声称通过运行gofmt -w
修复了错误,出现“with -s
”的提示可能是由于这个bug引起的:https://github.com/golangci/golangci-lint/issues/513。
这个问题在2019年修复,并在v1.17.0
中发布。你可能需要检查你的流水线是否使用的是旧版本。
假设你的文件pkg/api/api.go
触发了警告,只是因为它没有格式化,那么gofmt -w
可以解决这个问题,因为-w
选项会覆盖文件:
如果文件的格式与gofmt的格式不同,用gofmt的版本覆盖它。
英文:
The -s
flag in gofmt
has nothing to do with formatting. It's about simplifying the code:
> Try to simplify code (after applying the rewrite rule, if any).
The warning you see comes from the linter golangci-lint
. Since you claim to have fixed the error by running gofmt -w
, the presence of the hint "with -s
" may be due to this bug: https://github.com/golangci/golangci-lint/issues/513.
The linked issue was fixed in 2019 and released with v1.17.0
. You might want to check if your pipeline is using an older version.
Assuming that your file pkg/api/api.go
triggered the warning just because it was not formatted, gofmt -w
solves the issue because -w
overwrites the file:
> If a file's formatting is different from gofmt's, overwrite it with gofmt's version.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论