Skip to content

fix: write the input to stdout when using stdin and there are no changes #5827

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .golangci.next.reference.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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$"
Expand Down
43 changes: 33 additions & 10 deletions pkg/goformat/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (c *Runner) Run(paths []string) error {
}

if c.opts.stdin {
return c.process("<standard input>", savedStdout, os.Stdin)
return c.formatStdIn("<standard input>", savedStdout, os.Stdin)
}

for _, path := range paths {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down
Loading