1
|
|
|
import os |
2
|
|
|
|
3
|
|
|
|
4
|
|
View Code Duplication |
class PathFilters: |
|
|
|
|
5
|
|
|
|
6
|
|
|
def __init__(self, |
7
|
|
|
to_include=None, |
8
|
|
|
to_exclude=None, |
9
|
|
|
min_level=0, |
10
|
|
|
max_level=12, |
11
|
|
|
filters=None, |
12
|
|
|
non_empty_folders=None): |
13
|
|
|
self.to_include = to_include |
14
|
|
|
self.to_exclude = to_exclude |
15
|
|
|
self.min_level = min_level |
16
|
|
|
self.max_level = max_level |
17
|
|
|
self.filters = filters |
18
|
|
|
self.non_empty_folders = non_empty_folders |
19
|
|
|
|
20
|
|
|
@staticmethod |
21
|
|
|
def get_level(path): |
22
|
|
|
return len(path.split(os.sep)) |
23
|
|
|
|
24
|
|
|
def check_level(self, path): |
25
|
|
|
# Check that current path level is more than min path and less than max path |
26
|
|
|
if self.min_level <= self.get_level(path) <= self.max_level: |
27
|
|
|
return True |
28
|
|
|
|
29
|
|
|
def _level_filters(self, path): |
30
|
|
|
path_list = path.split(os.sep) |
31
|
|
|
for i in range(0, len(path_list)): |
32
|
|
|
if i in self.filters: |
33
|
|
|
if 'exclude' in self.filters[i]: |
34
|
|
|
if any(ex.lower() in path_list[i].lower() for ex in self.filters[i]['exclude']): |
35
|
|
|
return False |
36
|
|
|
|
37
|
|
|
if 'include' in self.filters[i]: |
38
|
|
|
inclusion = 0 |
39
|
|
|
for inc in self.filters[i]['include']: |
40
|
|
|
if str(inc).lower() in path_list[i].lower(): |
41
|
|
|
inclusion = 1 |
42
|
|
|
if inclusion != 1: |
43
|
|
|
return False |
44
|
|
|
return True |
45
|
|
|
|
46
|
|
|
def validate_non_empty_folder(self, base, fullname): |
47
|
|
|
# Check that path is a directory |
48
|
|
|
if os.path.isdir(base + os.sep + fullname): |
49
|
|
|
# Check that path is not empty |
50
|
|
|
if os.listdir(base + os.sep + fullname): |
51
|
|
|
# Check that path level is equal to max_level |
52
|
|
|
if self.filters.get_level(fullname) == self.filters.max_level: |
53
|
|
|
return True |
54
|
|
|
|
55
|
|
|
def validate(self, path): |
56
|
|
|
"""Run path against filter sets and return True if all pass""" |
57
|
|
|
# Exclude hidden files and folders with '.' prefix |
58
|
|
|
if os.path.basename(path).startswith('.'): |
59
|
|
|
return False |
60
|
|
|
|
61
|
|
|
# Check that current path level is more than min path and less than max path |
62
|
|
|
if not self.check_level(path): |
63
|
|
|
return False |
64
|
|
|
|
65
|
|
|
if self.filters: |
66
|
|
|
if not self._level_filters(path): |
67
|
|
|
return False |
68
|
|
|
|
69
|
|
|
# Force include and exclude iterations to be strings in case of integer filters |
70
|
|
|
# Handle exclusions |
71
|
|
|
if self.to_exclude: |
72
|
|
|
if any(str(ex).lower() in path.lower() for ex in self.to_exclude): |
73
|
|
|
return False |
74
|
|
|
|
75
|
|
|
# Handle inclusions |
76
|
|
|
if self.to_include: |
77
|
|
|
if not any(str(inc).lower() in path.lower() for inc in self.to_include): |
78
|
|
|
return False |
79
|
|
|
|
80
|
|
|
return True |
81
|
|
|
|