10

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.
(EDIT: link added to evaluate and eventually reproduce the error)

Evidences:

original commit

linter output

I would like to understand what was the source of this error, as well as how to resolve it?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
GuiFalourd
  • 15,523
  • 8
  • 44
  • 71

2 Answers2

22

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).

Source 1 + Source 2

rustyMagnet
  • 3,479
  • 1
  • 31
  • 41
GuiFalourd
  • 15,523
  • 8
  • 44
  • 71
  • If you found a way to demonstrate the problem you should add it to the question; that will probably get it reopened. – Dour High Arch Sep 23 '21 at 21:02
  • Anybody knows if there is a way to automatically enable this in jetbrains goland, so the command don't need to be executed ? – Mb175 Aug 22 '23 at 09:01
7

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.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
  • how come the formatting went different? I have like 100 of files in the repo which I just checked out, is the only solution to `gofmt` on each file individually? I am using windows system in case if thats screwing the file formatting. – Obaid Maroof Nov 24 '22 at 14:50
  • 1
    @ObaidMaroof you don't have to reformat each file individually. You can supply directory paths to `gofmt` or use shell expansion – blackgreen Nov 24 '22 at 16:19