Respect contexts with timeouts (#1948)

rh-pre-commit.version: 2.3.2
rh-pre-commit.check-secrets: ENABLED
This commit is contained in:
bplaxco authored and GitHub committed 2025-10-24 12:30:13 -05:00
1 parent 3821f30b06
commit c5ccbb9468
13 files changed
+350 -245

No files matched your search

+66 -61
View File
@@ -70,12 +70,12 @@ func (s *File) Fragments(ctx context.Context, yield FragmentsFunc) error {
return s.extractorFragments(ctx, extractor, s.Content, yield)
}
if decompressor, ok := format.(archives.Decompressor); ok {
return s.decompressorFragments(decompressor, s.Content, yield)
return s.decompressorFragments(ctx, decompressor, s.Content, yield)
}
logging.Warn().Str("path", s.FullPath()).Msg("skipping unknown archive type")
}
return s.fileFragments(bufio.NewReader(s.Content), yield)
return s.fileFragments(ctx, bufio.NewReader(s.Content), yield)
}
// extractorFragments recursively crawls archives and yields fragments
@@ -139,14 +139,14 @@ func (s *File) extractorFragments(ctx context.Context, extractor archives.Extrac
}
// decompressorFragments recursively crawls archives and yields fragments
func (s *File) decompressorFragments(decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
func (s *File) decompressorFragments(ctx context.Context, decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
innerReader, err := decompressor.OpenReader(reader)
if err != nil {
logging.Error().Str("path", s.FullPath()).Msg("could read compressed file")
return nil
}
if err := s.fileFragments(bufio.NewReader(innerReader), yield); err != nil {
if err := s.fileFragments(ctx, bufio.NewReader(innerReader), yield); err != nil {
_ = innerReader.Close()
return err
}
@@ -156,7 +156,7 @@ func (s *File) decompressorFragments(decompressor archives.Decompressor, reader
}
// fileFragments reads the file into fragments to yield
func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
func (s *File) fileFragments(ctx context.Context, reader *bufio.Reader, yield FragmentsFunc) error {
// Create a buffer if the caller hasn't provided one
if s.Buffer == nil {
s.Buffer = make([]byte, defaultBufferSize)
@@ -164,75 +164,80 @@ func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
totalLines := 0
for {
fragment := Fragment{
FilePath: s.FullPath(),
}
n, err := reader.Read(s.Buffer)
if n == 0 {
if err != nil && err != io.EOF {
return yield(fragment, fmt.Errorf("could not read file: %w", err))
select {
case <-ctx.Done():
return ctx.Err()
default:
fragment := Fragment{
FilePath: s.FullPath(),
}
return nil
}
// Only check the filetype at the start of file.
if totalLines == 0 {
// TODO: could other optimizations be introduced here?
if mimetype, err := filetype.Match(s.Buffer[:n]); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not determine type: %w", err),
)
} else if mimetype.MIME.Type == "application" {
logging.Debug().
Str("mime_type", mimetype.MIME.Value).
Str("path", s.FullPath()).
Msgf("skipping binary file")
n, err := reader.Read(s.Buffer)
if n == 0 {
if err != nil && err != io.EOF {
return yield(fragment, fmt.Errorf("could not read file: %w", err))
}
return nil
}
}
// Try to split chunks across large areas of whitespace, if possible.
peekBuf := bytes.NewBuffer(s.Buffer[:n])
if err := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not read until safe boundary: %w", err),
)
}
// Only check the filetype at the start of file.
if totalLines == 0 {
// TODO: could other optimizations be introduced here?
if mimetype, err := filetype.Match(s.Buffer[:n]); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not determine type: %w", err),
)
} else if mimetype.MIME.Type == "application" {
logging.Debug().
Str("mime_type", mimetype.MIME.Value).
Str("path", s.FullPath()).
Msgf("skipping binary file")
fragment.Raw = peekBuf.String()
fragment.Bytes = peekBuf.Bytes()
fragment.StartLine = totalLines + 1
return nil
}
}
// Count the number of newlines in this chunk
totalLines += strings.Count(fragment.Raw, "\n")
// Try to split chunks across large areas of whitespace, if possible.
peekBuf := bytes.NewBuffer(s.Buffer[:n])
if err := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not read until safe boundary: %w", err),
)
}
if len(s.Symlink) > 0 {
fragment.SymlinkFile = s.Symlink
}
fragment.Raw = peekBuf.String()
fragment.Bytes = peekBuf.Bytes()
fragment.StartLine = totalLines + 1
if isWindows {
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
fragment.WindowsFilePath = s.FullPath()
}
// Count the number of newlines in this chunk
totalLines += strings.Count(fragment.Raw, "\n")
// log errors but continue since there's content
if err != nil && err != io.EOF {
logging.Warn().Err(err).Msgf("issue reading file")
}
if len(s.Symlink) > 0 {
fragment.SymlinkFile = s.Symlink
}
// Done with the file!
if err == io.EOF {
return yield(fragment, nil)
}
if isWindows {
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
fragment.WindowsFilePath = s.FullPath()
}
if err := yield(fragment, err); err != nil {
return err
// log errors but continue since there's content
if err != nil && err != io.EOF {
logging.Warn().Err(err).Msgf("issue reading file")
}
// Done with the file!
if err == io.EOF {
return yield(fragment, nil)
}
if err := yield(fragment, err); err != nil {
return err
}
}
}
}
+43 -32
View File
@@ -34,7 +34,8 @@ func DirectoryTargets(sourcePath string, s *semgroup.Group, followSymlinks bool,
}
s.Go(func() error {
err := files.scanTargets(func(scanTarget ScanTarget, err error) error {
ctx := context.Background()
err := files.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
paths <- scanTarget
return nil
})
@@ -56,7 +57,7 @@ type Files struct {
}
// scanTargets yields scan targets to a callback func
func (s *Files) scanTargets(yield func(ScanTarget, error) error) error {
func (s *Files) scanTargets(ctx context.Context, yield func(ScanTarget, error) error) error {
return filepath.WalkDir(s.Path, func(path string, d fs.DirEntry, err error) error {
scanTarget := ScanTarget{Path: path}
logger := logging.With().Str("path", path).Logger()
@@ -141,40 +142,50 @@ func (s *Files) scanTargets(yield func(ScanTarget, error) error) error {
func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
var wg sync.WaitGroup
err := s.scanTargets(func(scanTarget ScanTarget, err error) error {
wg.Add(1)
s.Sema.Go(func() error {
logger := logging.With().Str("path", scanTarget.Path).Logger()
logger.Trace().Msg("scanning path")
err := s.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Add(1)
s.Sema.Go(func() error {
logger := logging.With().Str("path", scanTarget.Path).Logger()
logger.Trace().Msg("scanning path")
f, err := os.Open(scanTarget.Path)
if err != nil {
if os.IsPermission(err) {
logger.Warn().Msg("skipping file: permission denied")
f, err := os.Open(scanTarget.Path)
if err != nil {
if os.IsPermission(err) {
logger.Warn().Msg("skipping file: permission denied")
}
wg.Done()
return nil
}
// Convert this to a file source
file := File{
Content: f,
Path: scanTarget.Path,
Symlink: scanTarget.Symlink,
Config: s.Config,
MaxArchiveDepth: s.MaxArchiveDepth,
}
err = file.Fragments(ctx, yield)
// Avoiding a defer in a hot loop
_ = f.Close()
wg.Done()
return nil
}
return err
})
// Convert this to a file source
file := File{
Content: f,
Path: scanTarget.Path,
Symlink: scanTarget.Symlink,
Config: s.Config,
MaxArchiveDepth: s.MaxArchiveDepth,
}
err = file.Fragments(ctx, yield)
// Avoiding a defer in a hot loop
_ = f.Close()
wg.Done()
return err
})
return nil
return nil
}
})
wg.Wait()
return err
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Wait()
return err
}
}
+50 -12
View File
@@ -63,6 +63,12 @@ func (br *blobReader) Close() error {
// Caller should read everything from channels until receiving a signal about their closure and call
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
return NewGitLogCmdContext(context.Background(), source, logOpts)
}
// NewGitLogCmdContext is the same as NewGitLogCmd but supports passing in a
// context to use for timeouts
func NewGitLogCmdContext(ctx context.Context, source string, logOpts string) (*GitCmd, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
if logOpts != "" {
@@ -82,9 +88,9 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
}
args = append(args, userArgs...)
cmd = exec.Command("git", args...)
cmd = exec.CommandContext(ctx, "git", args...)
} else {
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "log", "-p", "-U0",
"--full-history", "--all", "--diff-filter=tuxdb")
}
@@ -122,11 +128,17 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
// Caller should read everything from channels until receiving a signal about their closure and call
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
return NewGitDiffCmdContext(context.Background(), source, staged)
}
// NewGitDiffCmdContext is the same as NewGitDiffCmd but supports passing in a
// context to use for timeouts
func NewGitDiffCmdContext(ctx context.Context, source string, staged bool) (*GitCmd, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff", ".")
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff", ".")
if staged {
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
"--staged", ".")
}
logging.Debug().Msgf("executing: %s", cmd.String())
@@ -177,13 +189,24 @@ func (c *GitCmd) Wait() error {
return c.cmd.Wait()
}
// String displays the command used for GitCmd
func (c *GitCmd) String() string {
return c.cmd.String()
}
// NewBlobReader returns an io.ReadCloser that can be used to read a blob
// within the git repo used to create the GitCmd.
//
// The caller is responsible for closing the reader.
func (c *GitCmd) NewBlobReader(commit, path string) (io.ReadCloser, error) {
return c.NewBlobReaderContext(context.Background(), commit, path)
}
// NewBlobReaderContext is the same as NewBlobReader but supports passing in a
// context to use for timeouts
func (c *GitCmd) NewBlobReaderContext(ctx context.Context, commit, path string) (io.ReadCloser, error) {
gitArgs := []string{"-C", c.repoPath, "cat-file", "blob", commit + ":" + path}
cmd := exec.Command("git", gitArgs...)
cmd := exec.CommandContext(ctx, "git", gitArgs...)
cmd.Stderr = io.Discard
stdout, err := cmd.StdoutPipe()
if err != nil {
@@ -275,7 +298,9 @@ type CommitInfo struct {
// Fragments yields fragments from a git repo
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
defer func() {
_ = s.Cmd.Wait()
if err := s.Cmd.Wait(); err != nil {
logging.Debug().Err(err).Str("cmd", s.Cmd.String()).Msg("command aborted")
}
}()
var (
@@ -287,6 +312,8 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
for diffFilesCh != nil || errCh != nil {
select {
case <-ctx.Done():
return ctx.Err()
case gitdiffFile, open := <-diffFilesCh:
if !open {
diffFilesCh = nil
@@ -336,7 +363,7 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
defer wg.Done()
if yieldAsArchive {
blob, err := s.Cmd.NewBlobReader(commitSHA, gitdiffFile.NewName)
blob, err := s.Cmd.NewBlobReaderContext(ctx, commitSHA, gitdiffFile.NewName)
if err != nil {
logging.Error().Err(err).Msg("could not read archive blob")
return nil
@@ -394,17 +421,28 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
}
}
wg.Wait()
return nil
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Wait()
return nil
}
}
// NewRemoteInfo builds a new RemoteInfo for generating finding links
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
return NewRemoteInfoContext(context.Background(), platform, source)
}
// NewRemoteInfoContext is the same as NewRemoteInfo but supports passing in a
// context to use for timeouts
func NewRemoteInfoContext(ctx context.Context, platform scm.Platform, source string) *RemoteInfo {
if platform == scm.NoPlatform {
return &RemoteInfo{Platform: platform}
}
remoteUrl, err := getRemoteUrl(source)
remoteUrl, err := getRemoteUrl(ctx, source)
if err != nil {
if strings.Contains(err.Error(), "No remote configured") {
logging.Debug().Msg("skipping finding links: repository has no configured remote.")
@@ -442,9 +480,9 @@ End:
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):(?:\d{1,5}/)?([\w/.-]+?)(?:\.git)?$`)
func getRemoteUrl(source string) (*url.URL, error) {
func getRemoteUrl(ctx context.Context, source string) (*url.URL, error) {
// This will return the first remote — typically, "origin".
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
cmd := exec.CommandContext(ctx, "git", "ls-remote", "--quiet", "--get-url")
if source != "." {
cmd.Dir = source
}