Skip to content

Commit cd315cd

Browse files
authored
fix: write the input to stdout when using stdin and there are no changes (#5827)
1 parent 8eab120 commit cd315cd

File tree

2 files changed

+34
-10
lines changed

2 files changed

+34
-10
lines changed

.golangci.next.reference.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4088,6 +4088,7 @@ formatters:
40884088
# Default: lax
40894089
generated: strict
40904090
# Which file paths to exclude.
4091+
# This option is ignored when using `--stdin` as the path is unknown.
40914092
# Default: []
40924093
paths:
40934094
- ".*\\.my\\.go$"

pkg/goformat/runner.go

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ func (c *Runner) Run(paths []string) error {
5757
}
5858

5959
if c.opts.stdin {
60-
return c.process("<standard input>", savedStdout, os.Stdin)
60+
return c.formatStdIn("<standard input>", savedStdout, os.Stdin)
6161
}
6262

6363
for _, path := range paths {
@@ -121,15 +121,6 @@ func (c *Runner) process(path string, stdout io.Writer, in io.Reader) error {
121121

122122
output := c.metaFormatter.Format(path, input)
123123

124-
if c.opts.stdin {
125-
_, err = stdout.Write(output)
126-
if err != nil {
127-
return err
128-
}
129-
130-
return nil
131-
}
132-
133124
if bytes.Equal(input, output) {
134125
return nil
135126
}
@@ -168,6 +159,38 @@ func (c *Runner) process(path string, stdout io.Writer, in io.Reader) error {
168159
return os.WriteFile(path, output, perms)
169160
}
170161

162+
func (c *Runner) formatStdIn(path string, stdout io.Writer, in io.Reader) error {
163+
input, err := io.ReadAll(in)
164+
if err != nil {
165+
return err
166+
}
167+
168+
match, err := c.matcher.IsGeneratedFile(path, input)
169+
if err != nil {
170+
return err
171+
}
172+
173+
if match {
174+
// If the file is generated,
175+
// the input should be written to the stdout to avoid emptied the file.
176+
_, err = stdout.Write(input)
177+
if err != nil {
178+
return err
179+
}
180+
181+
return nil
182+
}
183+
184+
output := c.metaFormatter.Format(path, input)
185+
186+
_, err = stdout.Write(output)
187+
if err != nil {
188+
return err
189+
}
190+
191+
return nil
192+
}
193+
171194
func (c *Runner) setOutputToDevNull() {
172195
devNull, err := os.Open(os.DevNull)
173196
if err != nil {

0 commit comments

Comments
 (0)