From 3f18d74f2915c34ed94cf94dc488965d908dae8a Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Fri, 23 May 2025 23:57:12 +0200 Subject: [PATCH 1/2] fix: write the input to stdout when using stdin and there are no changes --- .golangci.next.reference.yml | 1 + pkg/goformat/runner.go | 41 +++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 10 deletions(-) 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..17ad63a556e5 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,36 @@ 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 { + _, 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 { From 871084b41d0ec361ccf3f803d752e47111879f90 Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Sat, 24 May 2025 00:13:07 +0200 Subject: [PATCH 2/2] docs: add comment --- pkg/goformat/runner.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pkg/goformat/runner.go b/pkg/goformat/runner.go index 17ad63a556e5..f87626158179 100644 --- a/pkg/goformat/runner.go +++ b/pkg/goformat/runner.go @@ -171,6 +171,8 @@ func (c *Runner) formatStdIn(path string, stdout io.Writer, in io.Reader) error } 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