Refactor pkgfiles module and depend on only pathlib and re

This commit is contained in:
Eric Torres 2019-03-25 13:46:14 -07:00
parent 284885fc59
commit 9048a55c0f

View File

@ -1,37 +1,50 @@
"""Helper functions for dealing with package files.""" """Helper functions for dealing with package files."""
import glob import re
import os
import os.path from pathlib import Path
# ========== Constants ========== # ========== Constants ==========
PKGEXT = "pkg.tar.xz" # Match any pkgfile of any name with the .pkg.tar.* extension
SIGEXT = f"{PKGEXT}.sig" PKGREGEX = "^[\w]+[.]pkg[.]tar([.][\w]+)?$"
# Match any sigfile of any name with the .pkg.tar.*.sig extension
SIGREGEX = "^[\w]+[.]pkg[.]tar[.][\w]*[.]sig$"
# ========== Functions ========== # ========== Functions ==========
def get_pkgfiles(query=None, directory=None, *, signatures_only=False): def get_pkgfiles(query=None, *, directory=None, signatures_only=False):
"""Return a list of package files in the current working directory. """Return a list of package files in the current working directory.
:param query: names of package files to search for :param query: names of package files to search for
:type query: str :type query: str
:param directory: a directory to search in :param directory: a directory to search in
:type directory: str :type directory: str or path-like object
:param signatures_only: include only signature files :param signatures_only: include only signature files
:type signatures_only: bool :type signatures_only: bool
:returns: paths of package files :returns: paths of package files
:rtype: list :rtype: list
""" """
if directory is not None: path = Path.cwd() if directory is None else Path(directory)
path = directory filequery = f"*{query}*" if query is not None else "*"
else:
path = os.getcwd()
if signatures_only and query is not None: if signatures_only:
return glob.glob(f"{path}/*{query}*.{SIGEXT}") yield from _filter_by_regex(filequery, SIGREGEX, path)
elif signatures_only and query is None: else:
return glob.glob(f"{path}/*.{SIGEXT}") yield from _filter_by_regex(filequery, PKGREGEX, path)
elif not signatures_only and query is not None:
return glob.glob(f"{path}/*{query}*.{PKGEXT}")
elif not signatures_only and query is None: def _filter_by_regex(query, regex_expression, path):
return glob.glob(f"{path}/*.{PKGEXT}") """Filter package files only.
:param query: names of package files to search for
:type query: str
:param regex_expression: the expression to filter by
:type regex_expression: str
:param path: directory to look for files
:type path: path-like object
:yields: package files from either the current working directory
or an arbitrary directory
"""
for pkgfile in path.glob(query):
if re.match(regex_expression, str(pkgfile)):
yield pkgfile