Skip to content

Fix --exclude with bare directory names when scanning with -r .#1366

Open
stefanoginella wants to merge 1 commit intoPyCQA:mainfrom
stefanoginella:fix/exclude-relative-path-matching
Open

Fix --exclude with bare directory names when scanning with -r .#1366
stefanoginella wants to merge 1 commit intoPyCQA:mainfrom
stefanoginella:fix/exclude-relative-path-matching

Conversation

@stefanoginella
Copy link
Copy Markdown

@stefanoginella stefanoginella commented Mar 4, 2026

Summary

  • Fixes --exclude flag silently failing when bare directory names (e.g., venv instead of ./venv) are passed while scanning with -r .
  • Root cause: os.walk(".") yields ./-prefixed paths, but excluded dirs become glob patterns (e.g., venv/*) that don't match the ./-prefixed paths in either fnmatch or substring checks
  • Fix: apply os.path.normpath() to normalize paths consistently before comparison

Test plan

  • Added test_get_files_from_dir_excludes_dot_prefixed_paths covering the os.walk ./-prefix scenario
  • Extended test_discover_files_exclude_dir with a case for bare dir names when the directory exists
  • All 262 existing tests pass
  • Manual verification: bandit -r . --exclude excluded_dir now correctly excludes the directory

Resolves #975
See also #966

When scanning with -r ., os.walk yields ./-prefixed paths (e.g.,
./venv/file.py). The discover_files method converts bare directory
names to glob patterns (venv -> venv/*), but neither fnmatch nor
substring matching catches the ./-prefixed walked paths.

Apply os.path.normpath in three places:
- _is_file_included: normalize the path before matching
- _get_files_from_dir: normalize walked paths before checking
- discover_files: normalize --exclude paths before glob conversion

Resolves: PyCQA#975
See also: PyCQA#966
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Exclusion filter not working correctly with relative paths

1 participant