def find_packages(where='.', lib_prefix='', exclude=()):
"""
SNAGGED FROM distribute-0.6.49-py2.7.egg/setuptools/__init__.py
"""
out = []
stack = [(convert_path(where), lib_prefix)]
while stack:
where, prefix = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where,name)
if ('.' not in name and os.path.isdir(fn) and
os.path.isfile(os.path.join(fn, '__init__.py'))
):
out.append(prefix + name); stack.append((fn, prefix+name + '.'))
for pat in list(exclude)+['ez_setup', 'distribute_setup']:
from fnmatch import fnmatchcase
out = [item for item in out if not fnmatchcase(item, pat)]
return out
python类fnmatchcase()的实例源码
def multi_wildcard_match(self, wildcards):
if hasattr(self, 'nkd_fnmatchcase'):
fnmatchcase = self.nkd_fnmatchcase
else:
from fnmatch import fnmatchcase
self.nkd_fnmatchcase = fnmatchcase
wc_list = wildcards.split('|')
return_list = []
for wc in wc_list:
temp_list = [ x for x in self if fnmatchcase(x, wc) ]
for result in temp_list:
return_list.append(result)
return return_list
#------------------------------------------------------------------------------
# XList Cast Methods
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# [ xset method ] (XSet)
# return an XSet with unique XList item values and XList attributes
#------------------------------------------------------------------------------
def Apply(self, url):
""" Process the URL, as above. """
if (not url) or (not url.loc):
return None
if self._wildcard:
if fnmatch.fnmatchcase(url.loc, self._wildcard):
return self._pass
return None
if self._regexp:
if self._regexp.search(url.loc):
return self._pass
return None
assert False # unreachable
#end def Apply
#end class Filter
def _find(cls, pattern, manager, name, version):
name = '*' if name is None else name
installed = glob(
os.path.join(
manager.config.mods_directory,
pattern
)
)
for path in installed:
try:
mod = cls(manager, path)
except Exception as ex:
print('Warning: invalid mod %s: %s' % (path, ex))
continue
if not fnmatchcase(mod.name, name):
continue
if version is not None and version != mod.version:
continue
yield mod
def _chunk_filter(self, extensions):
""" Create a filter from the extensions and ignore files """
if isinstance(extensions, six.string_types):
extensions = extensions.split()
def _filter(chunk):
""" Exclusion filter """
name = chunk['name']
if extensions is not None:
if not any(name.endswith(e) for e in extensions):
return False
for pattern in self.state.ignore_re:
if pattern.match(name):
return False
for pattern in self.state.ignore:
if fnmatch.fnmatchcase(name, pattern):
return False
return True
return _filter
def apply_cors(request):
"""Second part of the cors function to validate."""
from plone.server import app_settings
headers = {}
origin = request.headers.get('Origin', None)
if origin:
if not any([fnmatch.fnmatchcase(origin, o)
for o in app_settings['cors']['allow_origin']]):
logger.error('Origin %s not allowed' % origin)
raise HTTPUnauthorized()
elif request.headers.get('Access-Control-Allow-Credentials', False):
headers['Access-Control-Allow-Origin', origin]
else:
if any([o == "*" for o in app_settings['cors']['allow_origin']]):
headers['Access-Control-Allow-Origin'] = '*'
else:
headers['Access-Control-Allow-Origin'] = origin
if request.headers.get(
'Access-Control-Request-Method', None) != 'OPTIONS':
if app_settings['cors']['allow_credentials']:
headers['Access-Control-Allow-Credentials'] = 'True'
if len(app_settings['cors']['allow_headers']):
headers['Access-Control-Expose-Headers'] = \
', '.join(app_settings['cors']['allow_headers'])
return headers
def find_packages(where='.', lib_prefix='', exclude=()):
"""
SNAGGED FROM distribute-0.6.49-py2.7.egg/setuptools/__init__.py
"""
out = []
stack=[(convert_path(where), lib_prefix)]
while stack:
where,prefix = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where,name)
if ('.' not in name and os.path.isdir(fn) and
os.path.isfile(os.path.join(fn,'__init__.py'))
):
out.append(prefix+name); stack.append((fn,prefix+name+'.'))
for pat in list(exclude)+['ez_setup', 'distribute_setup']:
from fnmatch import fnmatchcase
out = [item for item in out if not fnmatchcase(item,pat)]
return out
def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True
def get_headers(self):
settings = await self.get_settings()
headers = {}
origin = self.request.headers.get('Origin', None)
if origin:
if '*' in settings['allow_origin']:
headers['Access-Control-Allow-Origin'] = '*'
elif any([fnmatch.fnmatchcase(origin, o)
for o in settings['allow_origin']]):
headers['Access-Control-Allow-Origin'] = origin
else:
logger.error('Origin %s not allowed' % origin,
request=self.request)
raise HTTPUnauthorized()
if self.request.headers.get(
'Access-Control-Request-Method', None) != 'OPTIONS':
if settings['allow_credentials']:
headers['Access-Control-Allow-Credentials'] = 'True'
if len(settings['allow_headers']):
headers['Access-Control-Expose-Headers'] = ', '.join(
settings['allow_headers'])
return headers
def fnmatch(self, pattern, normcase=None):
""" Return ``True`` if `self.name` matches the given `pattern`.
`pattern` - A filename pattern with wildcards,
for example ``'*.py'``. If the pattern contains a `normcase`
attribute, it is applied to the name and path prior to comparison.
`normcase` - (optional) A function used to normalize the pattern and
filename before matching. Defaults to :meth:`self.module`, which defaults
to :meth:`os.path.normcase`.
.. seealso:: :func:`fnmatch.fnmatch`
"""
default_normcase = getattr(pattern, 'normcase', self.module.normcase)
normcase = normcase or default_normcase
name = normcase(self.name)
pattern = normcase(pattern)
return fnmatch.fnmatchcase(name, pattern)
def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True
def fnmatch(self, pattern, normcase=None):
"""Return ``True`` if :attr:`name` matches the given ``pattern``.
.. seealso:: :func:`fnmatch.fnmatch`
Args:
pattern (str): A filename pattern with wildcards,
for example ``'*.py'``. If the pattern contains a `normcase`
attribute, it is applied to the name and path prior to comparison.
normcase (func, optional): A function used to normalize the pattern and
filename before matching. Defaults to :meth:`self.module`, which defaults
to :meth:`os.path.normcase`.
"""
default_normcase = getattr(pattern, 'normcase', self.path_module.normcase)
normcase = normcase or default_normcase
name = normcase(self.name)
pattern = normcase(pattern)
return fnmatch.fnmatchcase(name, pattern)
def list_backups(self, pattern=None, since=None, until=None):
labels = self.list_labels()
for label in labels:
if pattern is not None and not fnmatch.fnmatchcase(label, pattern):
continue # Ignore non matching labels
try:
backup = self.get_backup(label)
except MartyObjectDecodeError:
continue # Ignore non-backup labels
if since is not None and backup.start_date < since:
continue # Ignore backups before since date
if until is not None and backup.start_date > until:
continue # Ignore backups before until date
yield label, backup
def clear_wildcard_hooks(hc, stack_id, stack_patterns, hook_type,
resource_pattern):
if stack_patterns:
for resource in hc.resources.list(stack_id):
res_name = resource.resource_name
if fnmatch.fnmatchcase(res_name, stack_patterns[0]):
nested_stack = hc.resources.get(
stack_id=stack_id,
resource_name=res_name)
clear_wildcard_hooks(
hc,
nested_stack.physical_resource_id,
stack_patterns[1:], hook_type, resource_pattern)
else:
for resource in hc.resources.list(stack_id):
res_name = resource.resource_name
if fnmatch.fnmatchcase(res_name, resource_pattern):
clear_hook(hc, stack_id, res_name, hook_type)
def fnmatch(self, pattern, normcase=None):
""" Return ``True`` if `self.name` matches the given `pattern`.
`pattern` - A filename pattern with wildcards,
for example ``'*.py'``. If the pattern contains a `normcase`
attribute, it is applied to the name and path prior to comparison.
`normcase` - (optional) A function used to normalize the pattern and
filename before matching. Defaults to :meth:`self.module`, which defaults
to :meth:`os.path.normcase`.
.. seealso:: :func:`fnmatch.fnmatch`
"""
default_normcase = getattr(pattern, 'normcase', self.module.normcase)
normcase = normcase or default_normcase
name = normcase(self.name)
pattern = normcase(pattern)
return fnmatch.fnmatchcase(name, pattern)
def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True
def find_packages(where='.', exclude=()):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style) path; it
will be converted to the appropriate local path syntax. 'exclude' is a
sequence of package names to exclude; '*' can be used as a wildcard in the
names, such that 'foo.*' will exclude all subpackages of 'foo' (but not
'foo' itself).
"""
out = []
stack=[(convert_path(where), '')]
while stack:
where,prefix = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where,name)
if ('.' not in name and os.path.isdir(fn) and
os.path.isfile(os.path.join(fn,'__init__.py'))
):
out.append(prefix+name); stack.append((fn,prefix+name+'.'))
for pat in list(exclude)+['ez_setup']:
from fnmatch import fnmatchcase
out = [item for item in out if not fnmatchcase(item,pat)]
return out
def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True
def _expand_wildcard_action(action):
"""
:param action: 'autoscaling:*'
:return: A list of all autoscaling permissions matching the wildcard
"""
if isinstance(action, list):
expanded_actions = []
for item in action:
expanded_actions.extend(_expand_wildcard_action(item))
return expanded_actions
else:
if '*' in action:
expanded = [
expanded_action.lower() for expanded_action in all_permissions if fnmatch.fnmatchcase(
expanded_action.lower(), action.lower()
)
]
# if we get a wildcard for a tech we've never heard of, just return the wildcard
if not expanded:
return [action.lower()]
return expanded
return [action.lower()]
def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
def funMatchScm(args, **options):
if len(args) != 2: raise ParseError("matchScm expects two arguments")
name = args[0]
val = args[1]
try:
pkg = options['package']
except KeyError:
raise ParseError('matchScm can only be used for queries')
for scm in pkg.getCheckoutStep().getScmList():
for props in scm.getProperties():
if fnmatch.fnmatchcase(props.get(name), val): return "true"
return "false"
def evalForward(self, nodes, valid):
"""Evaluate the axis, name test and predicate
Despite the result set returns whether we possibly made multiple hops
in the dendency graph, i.e. evaluated a 'descendant' axis. In this
caste it is the responsibility of the caller to calculate all possible
paths that lead to the result set.
"""
search = None
if self.__axis == "child":
nodes = self.__evalAxisChild(nodes, True)
elif self.__axis == "descendant":
nodes = self.__evalAxisDescendant(nodes, True)
search = True
elif self.__axis == "descendant-or-self":
nodes = self.__evalAxisDescendant(nodes, True) | nodes
search = True
elif self.__axis == "direct-child":
nodes = self.__evalAxisChild(nodes, False)
elif self.__axis == "direct-descendant":
nodes = self.__evalAxisDescendant(nodes, False)
search = False
elif self.__axis == "direct-descendant-or-self":
nodes = self.__evalAxisDescendant(nodes, False) | nodes
search = False
elif self.__axis == "self":
pass
else:
assert False, "Invalid axis: " + self.__axis
if self.__test == "*":
pass
elif '*' in self.__test:
nodes = set(i for i in nodes if fnmatchcase(i.getName(), self.__test))
else:
nodes = set(i for i in nodes if i.getName() == self.__test)
if self.__pred:
nodes = nodes & self.__pred.evalBackward()
return (nodes, search)
def evalBackward(self, nodes):
"""Inverse evaluation of location path step."""
if self.__test == "*":
pass
elif '*' in self.__test:
nodes = set(i for i in nodes if fnmatchcase(i.getName(), self.__test))
else:
nodes = set(i for i in nodes if i.getName() == self.__test)
if self.__pred:
nodes = nodes & self.__pred.evalBackward()
if self.__axis == "child":
nodes = self.__evalAxisParent(nodes, True)
elif self.__axis == "descendant":
nodes = self.__evalAxisAncestor(nodes, True)
elif self.__axis == "descendant-or-self":
nodes = self.__evalAxisAncestor(nodes, True) | nodes
elif self.__axis == "direct-child":
nodes = self.__evalAxisParent(nodes, False)
elif self.__axis == "direct-descendant":
nodes = self.__evalAxisAncestor(nodes, False)
elif self.__axis == "direct-descendant-or-self":
nodes = self.__evalAxisAncestor(nodes, False) | nodes
elif self.__axis == "self":
pass
else:
assert False, "Invalid axis: " + self.__axis
return nodes
def __doesMatch(self, scm):
for (key, value) in self.__match.items():
if key not in scm: return False
if not fnmatch.fnmatchcase(scm[key], value): return False
return True
def __maybeGlob(pred):
if pred.startswith("!"):
pred = pred[1:]
if any(i in pred for i in '*?[]'):
return lambda prev, elem: False if fnmatch.fnmatchcase(elem, pred) else prev
else:
return lambda prev, elem: False if elem == pred else prev
else:
if any(i in pred for i in '*?[]'):
return lambda prev, elem: True if fnmatch.fnmatchcase(elem, pred) else prev
else:
return lambda prev, elem: True if elem == pred else prev
def find_packages(where='.', exclude=()):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style) path; it
will be converted to the appropriate local path syntax. 'exclude' is a
sequence of package names to exclude; '*' can be used as a wildcard in the
names, such that 'foo.*' will exclude all subpackages of 'foo' (but not
'foo' itself).
"""
out = []
stack=[(convert_path(where), '')]
while stack:
where,prefix = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where,name)
looks_like_package = (
'.' not in name
and os.path.isdir(fn)
and os.path.isfile(os.path.join(fn, '__init__.py'))
)
if looks_like_package:
out.append(prefix+name)
stack.append((fn, prefix+name+'.'))
for pat in list(exclude)+['ez_setup']:
from fnmatch import fnmatchcase
out = [item for item in out if not fnmatchcase(item,pat)]
return out
def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
def wildcard_match(self, wildcard):
if hasattr(self, 'nkd_fnmatchcase'):
fnmatchcase = self.nkd_fnmatchcase
else:
from fnmatch import fnmatchcase
self.nkd_fnmatchcase = fnmatchcase
return [ x for x in self if fnmatchcase(x, wildcard) ]
#------------------------------------------------------------------------------
# [ multi_wildcard_match method ] (list)
# returns a list of items that match one or more | separated wildcards passed as string
#------------------------------------------------------------------------------
def wildcard_match(self, wildcard):
from fnmatch import fnmatchcase
return fnmatchcase(self, wildcard)
# convert string to normalized UTF-8 in Python 2 and 3 (##TODO: convert to XUnicode with attributes?)