Skip to content

Commit

Permalink
Merge pull request #407 from jfly/fix-hang
Browse files Browse the repository at this point in the history
Avoid hanging: ensure we always close `f.filesCh`
  • Loading branch information
brianmcgee authored Sep 14, 2024
2 parents f927a83 + 074be54 commit 985fdfe
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
8 changes: 4 additions & 4 deletions cli/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,9 @@ func (f *Format) Run() (err error) {

func (f *Format) walkFilesystem(ctx context.Context) func() error {
return func() error {
// close the files channel when we're done walking the file system
defer close(f.filesCh)

eg, ctx := errgroup.WithContext(ctx)
pathsCh := make(chan string, BatchSize)

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

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

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

// close the files channel when we're done walking the file system
defer close(f.filesCh)

// if no cache has been configured, or we are processing from stdin, we invoke the walker directly
if f.NoCache || f.Stdin {
return walker.Walk(ctx, func(file *walk.File, err error) error {
Expand Down
12 changes: 10 additions & 2 deletions cli/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -604,11 +604,19 @@ func TestStdIn(t *testing.T) {
os.Stdin = prevStdIn
})

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

out, err := cmd(t, "-C", tempDir, "--allow-missing-formatter", "--stdin", "test.nix")
// now pass along the filename parameter
contents = `{ foo, ... }: "hello"`
os.Stdin = test.TempFile(t, "", "stdin", &contents)

out, err = cmd(t, "-C", tempDir, "--allow-missing-formatter", "--stdin", "test.nix")
as.NoError(err)
assertStats(t, as, 1, 1, 1, 1)

Expand Down

0 comments on commit 985fdfe

Please sign in to comment.