Skip to content

Commit 985fdfe

Browse files
authored
Merge pull request #407 from jfly/fix-hang
Avoid hanging: ensure we always close `f.filesCh`
2 parents f927a83 + 074be54 commit 985fdfe

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

cli/format.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,9 @@ func (f *Format) Run() (err error) {
201201

202202
func (f *Format) walkFilesystem(ctx context.Context) func() error {
203203
return func() error {
204+
// close the files channel when we're done walking the file system
205+
defer close(f.filesCh)
206+
204207
eg, ctx := errgroup.WithContext(ctx)
205208
pathsCh := make(chan string, BatchSize)
206209

@@ -213,7 +216,7 @@ func (f *Format) walkFilesystem(ctx context.Context) func() error {
213216

214217
// check we have only received one path arg which we use for the file extension / matching to formatters
215218
if len(f.Paths) != 1 {
216-
return fmt.Errorf("only one path should be specified when using the --stdin flag")
219+
return fmt.Errorf("exactly one path should be specified when using the --stdin flag")
217220
}
218221

219222
// read stdin into a temporary file with the same file extension
@@ -261,9 +264,6 @@ func (f *Format) walkFilesystem(ctx context.Context) func() error {
261264
return fmt.Errorf("failed to create walker: %w", err)
262265
}
263266

264-
// close the files channel when we're done walking the file system
265-
defer close(f.filesCh)
266-
267267
// if no cache has been configured, or we are processing from stdin, we invoke the walker directly
268268
if f.NoCache || f.Stdin {
269269
return walker.Walk(ctx, func(file *walk.File, err error) error {

cli/format_test.go

+10-2
Original file line numberDiff line numberDiff line change
@@ -604,11 +604,19 @@ func TestStdIn(t *testing.T) {
604604
os.Stdin = prevStdIn
605605
})
606606

607-
//
607+
// omit the required filename parameter
608608
contents := `{ foo, ... }: "hello"`
609609
os.Stdin = test.TempFile(t, "", "stdin", &contents)
610+
// we get an error about the missing filename parameter.
611+
out, err := cmd(t, "-C", tempDir, "--allow-missing-formatter", "--stdin")
612+
as.EqualError(err, "exactly one path should be specified when using the --stdin flag")
613+
as.Equal("", string(out))
610614

611-
out, err := cmd(t, "-C", tempDir, "--allow-missing-formatter", "--stdin", "test.nix")
615+
// now pass along the filename parameter
616+
contents = `{ foo, ... }: "hello"`
617+
os.Stdin = test.TempFile(t, "", "stdin", &contents)
618+
619+
out, err = cmd(t, "-C", tempDir, "--allow-missing-formatter", "--stdin", "test.nix")
612620
as.NoError(err)
613621
assertStats(t, as, 1, 1, 1, 1)
614622

0 commit comments

Comments
 (0)