Support project filter with wildcard

Translate glob-style wildcards to ILIKE comparisons for the database.
This commit is contained in:
Doug Hellmann 2014-12-30 12:05:06 -05:00
parent f8b9b8cda0
commit 80d5fc4ec2
1 changed files with 22 additions and 6 deletions

View File

@ -1,8 +1,10 @@
import argparse
import logging
from aeromancer.db.models import Project
LOG = logging.getLogger(__name__)
class ProjectFilter(object):
"""Manage the arguments for filtering queries by project.
@ -18,7 +20,8 @@ class ProjectFilter(object):
action='append',
default=[],
dest='projects',
help='projects to limit search, by exact name',
help=('projects to limit search, '
'by exact name or glob-style patterns'),
)
@classmethod
@ -26,11 +29,24 @@ class ProjectFilter(object):
return cls(projects=parsed_args.projects)
def __init__(self, projects):
self.exact = []
self.patterns = []
for p in projects:
if '*' in p:
self.patterns.append(p.replace('*', '%'))
else:
self.exact.append(p)
self.projects = projects
def update_query(self, query):
if self.projects:
query = query.filter(
Project.name.in_(self.projects)
)
the_filter = ()
if self.exact:
LOG.debug('filtering on projects in %s', self.exact)
the_filter += (Project.name.in_(self.exact),)
if self.patterns:
LOG.debug('filtering on projects matching %s', self.patterns)
the_filter += tuple(Project.name.ilike(p)
for p in self.patterns)
if the_filter:
query = query.filter(*the_filter)
return query