diff --git a/pkg/sources/git/git.go b/pkg/sources/git/git.go index 5843f49b83a2..8922f06dbd4e 100644 --- a/pkg/sources/git/git.go +++ b/pkg/sources/git/git.go @@ -1241,19 +1241,18 @@ func (s *Git) handleBinary(ctx context.Context, gitDir string, reporter sources. } cmd := exec.Command("git", "-C", gitDir, "cat-file", "blob", commitHash.String()+":"+path) - stdout, catCmd, err := s.executeCatFileCmd(cmd) + stdout, err := s.executeCatFileCmd(cmd) if err != nil { return err } - // Wait must be called after closing the pipe (defer is a stack, so first defer is executed last) - defer func() { - _ = catCmd.Wait() - }() - defer stdout.Close() err = handlers.HandleFile(ctx, stdout, chunkSkel, reporter, handlers.WithSkipArchives(s.skipArchives)) // Always call Wait() to ensure the process is properly cleaned up + // Wait must be called after closing the pipe (https://stackoverflow.com/a/40706762). + if closeErr := stdout.Close(); closeErr != nil { + fileCtx.Logger().Error(closeErr, "error closing stdout for cat-file command") + } waitErr := cmd.Wait() // If there was an error in HandleFile, return that error @@ -1265,20 +1264,20 @@ func (s *Git) handleBinary(ctx context.Context, gitDir string, reporter sources. return waitErr } -func (s *Git) executeCatFileCmd(cmd *exec.Cmd) (io.ReadCloser, *exec.Cmd, error) { +func (s *Git) executeCatFileCmd(cmd *exec.Cmd) (io.ReadCloser, error) { var stderr bytes.Buffer cmd.Stderr = &stderr stdout, err := cmd.StdoutPipe() if err != nil { - return nil, nil, fmt.Errorf("error running git cat-file: %w\n%s", err, stderr.Bytes()) + return nil, fmt.Errorf("error running git cat-file: %w\n%s", err, stderr.Bytes()) } if err := cmd.Start(); err != nil { - return nil, nil, fmt.Errorf("error starting git cat-file: %w\n%s", err, stderr.Bytes()) + return nil, fmt.Errorf("error starting git cat-file: %w\n%s", err, stderr.Bytes()) } - return stdout, cmd, nil + return stdout, nil } func (s *Source) Enumerate(ctx context.Context, reporter sources.UnitReporter) error {