-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcode_directory.py
More file actions
65 lines (48 loc) · 2.17 KB
/
code_directory.py
File metadata and controls
65 lines (48 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from pathlib import Path
DEFAULT_INCLUDE = "*.py"
def py_file_matches(file_path, patterns):
"""
file_path is suffixed with `.py` and matches at least one pattern.
"""
is_py_file = file_path.match(DEFAULT_INCLUDE)
if not patterns:
return is_py_file
return is_py_file and any(
file_path.match(pattern.rsplit(":")[0]) for pattern in patterns
)
def file_line_patterns(file_path, patterns):
"""
Find the lines included or excluded for a given file_path among the patterns
"""
lines = []
for pattern in patterns or []:
split = pattern.rsplit(":")
if len(split) == 2:
if file_path.match(split[0]):
lines.append(int(split[1]))
return lines
def match_files(parent_path, exclude_paths=None, include_paths=None):
"""
Find pattern-matching files starting at the parent_path, recursively.
If a file matches any exclude pattern, it is not matched. If any include
patterns are passed in, a file must match `*.py` and at least one include patterns.
:param parent_path: str name for starting directory
:param exclude_paths: comma-separated set of UNIX glob patterns to exclude
:param include_paths: comma-separated set of UNIX glob patterns to exclude
:return: list of <pathlib.PosixPath> files found within (including recursively) the parent directory
that match the criteria of both exclude and include patterns.
"""
exclude_paths = list(exclude_paths) if exclude_paths is not None else []
include_paths = list(include_paths) if include_paths is not None else []
matched_files = []
for file_path in Path(parent_path).rglob("*"):
if file_path.is_file():
# Exclude patterns take precedence over include patterns.
if exclude_file(file_path, exclude_paths):
continue
if py_file_matches(file_path, include_paths):
matched_files.append(file_path)
return matched_files
def exclude_file(file_path, exclude_patterns):
# if a file matches any excluded pattern, return True so it is not included for analysis
return any(file_path.match(exclude) for exclude in exclude_patterns)