diff --git a/.golangci.next.reference.yml b/.golangci.next.reference.yml index 4c8e1615682b..d372c128b82d 100644 --- a/.golangci.next.reference.yml +++ b/.golangci.next.reference.yml @@ -4088,6 +4088,7 @@ formatters: # Default: lax generated: strict # Which file paths to exclude. + # This option is ignored when using `--stdin` as the path is unknown. # Default: [] paths: - ".*\\.my\\.go$" diff --git a/pkg/goformat/runner.go b/pkg/goformat/runner.go index fa1d1acc3019..f87626158179 100644 --- a/pkg/goformat/runner.go +++ b/pkg/goformat/runner.go @@ -57,7 +57,7 @@ func (c *Runner) Run(paths []string) error { } if c.opts.stdin { - return c.process("", savedStdout, os.Stdin) + return c.formatStdIn("", savedStdout, os.Stdin) } for _, path := range paths { @@ -121,15 +121,6 @@ func (c *Runner) process(path string, stdout io.Writer, in io.Reader) error { output := c.metaFormatter.Format(path, input) - if c.opts.stdin { - _, err = stdout.Write(output) - if err != nil { - return err - } - - return nil - } - if bytes.Equal(input, output) { return nil } @@ -168,6 +159,38 @@ func (c *Runner) process(path string, stdout io.Writer, in io.Reader) error { return os.WriteFile(path, output, perms) } +func (c *Runner) formatStdIn(path string, stdout io.Writer, in io.Reader) error { + input, err := io.ReadAll(in) + if err != nil { + return err + } + + match, err := c.matcher.IsGeneratedFile(path, input) + if err != nil { + return err + } + + if match { + // If the file is generated, + // the input should be written to the stdout to avoid emptied the file. + _, err = stdout.Write(input) + if err != nil { + return err + } + + return nil + } + + output := c.metaFormatter.Format(path, input) + + _, err = stdout.Write(output) + if err != nil { + return err + } + + return nil +} + func (c *Runner) setOutputToDevNull() { devNull, err := os.Open(os.DevNull) if err != nil {