summaryrefslogtreecommitdiff
path: root/flake8/utils.py
diff options
context:
space:
mode:
authorIan Cordasco <graffatcolmingov@gmail.com>2016-02-22 21:47:43 -0600
committerIan Cordasco <graffatcolmingov@gmail.com>2016-02-22 21:47:43 -0600
commit8792c30872e7e49c2cf2076c5765238b2e92c729 (patch)
treeda610e4ed6a96582ccaadb11b912f5a65d8b160f /flake8/utils.py
parenta21c328870cf177492927687445a55244bfc78ab (diff)
downloadflake8-8792c30872e7e49c2cf2076c5765238b2e92c729.tar.gz
Add utility functions around filename matching
We add utils.fnmatch and utils.filenames_for in anticipation of our checker manager creating file checkers for each file. We also include tests for these functions and a couple previously untested utility functions.
Diffstat (limited to 'flake8/utils.py')
-rw-r--r--flake8/utils.py55
1 files changed, 55 insertions, 0 deletions
diff --git a/flake8/utils.py b/flake8/utils.py
index e642d26..54c1990 100644
--- a/flake8/utils.py
+++ b/flake8/utils.py
@@ -1,4 +1,5 @@
"""Utility methods for flake8."""
+import fnmatch as _fnmatch
import io
import os
import sys
@@ -89,3 +90,57 @@ def is_using_stdin(paths):
bool
"""
return '-' in paths
+
+
+def _default_predicate(*args):
+ return False
+
+
+def filenames_from(arg, predicate=None):
+ # type: (str) -> Generator
+ """Generate filenames from an argument.
+
+ :param str arg:
+ Parameter from the command-line.
+ :param callable predicate:
+ Predicate to use to filter out filenames. If the predicate
+ returns ``True`` we will exclude the filename, otherwise we
+ will yield it.
+ :returns:
+ Generator of paths
+ """
+ if predicate is None:
+ predicate = _default_predicate
+ if os.path.isdir(arg):
+ for root, sub_directories, files in os.walk(arg):
+ for filename in files:
+ joined = os.path.join(root, filename)
+ if predicate(filename) or predicate(joined):
+ continue
+ yield joined
+ # NOTE(sigmavirus24): os.walk() will skip a directory if you
+ # remove it from the list of sub-directories.
+ for directory in sub_directories:
+ if predicate(directory):
+ sub_directories.remove(directory)
+ else:
+ yield arg
+
+
+def fnmatch(filename, patterns, default=True):
+ # type: (str, List[str], bool) -> bool
+ """Wrap :func:`fnmatch.fnmatch` to add some functionality.
+
+ :param str filename:
+ Name of the file we're trying to match.
+ :param list patterns:
+ Patterns we're using to try to match the filename.
+ :param bool default:
+ The default value if patterns is empty
+ :returns:
+ True if a pattern matches the filename, False if it doesn't.
+ ``default`` if patterns is empty.
+ """
+ if not patterns:
+ return default
+ return any(_fnmatch.fnmatch(filename, pattern) for pattern in patterns)