abstract the project filter logic a bit

This commit is contained in:
Doug Hellmann 2014-12-22 20:04:22 +00:00
parent 85dc323561
commit f8b9b8cda0
3 changed files with 43 additions and 13 deletions

View File

@ -4,6 +4,7 @@ import logging
import os
from aeromancer import project
from aeromancer import project_filter
from cliff.command import Command
@ -15,13 +16,7 @@ class Grep(Command):
def get_parser(self, prog_name):
parser = super(Grep, self).get_parser(prog_name)
parser.add_argument(
'--project',
action='append',
default=[],
dest='projects',
help='projects to limit search',
)
project_filter.ProjectFilter.add_arguments(parser)
parser.add_argument('pattern',
action='store',
help='regular expression',
@ -31,7 +26,8 @@ class Grep(Command):
def take_action(self, parsed_args):
session = self.app.get_db_session()
pm = project.ProjectManager(session)
for r in pm.grep(parsed_args.pattern, parsed_args.projects):
prj_filt = project_filter.ProjectFilter.from_parsed_args(parsed_args)
for r in pm.grep(parsed_args.pattern, prj_filt):
line_num, content, filename, project_name = r
print('%s/%s:%s:%s' %
(project_name, filename, line_num, content.rstrip())

View File

@ -194,7 +194,7 @@ class ProjectManager(object):
self._remove_file_data(obj, reason='file no longer exists')
self.session.flush()
def grep(self, pattern, projects=[]):
def grep(self, pattern, prj_filter):
"""Given a pattern, search for lines in files in all projects that match it.
Returns results of the query, including the four columns line
@ -210,9 +210,7 @@ class ProjectManager(object):
).join(File, Project).filter(
Line.content.op('regexp')(pattern)
)
if projects:
query = query.filter(
Project.name.in_(projects)
)
if prj_filter:
query = prj_filter.update_query(query)
query = query.order_by(Project.name, File.name, Line.number)
return query.yield_per(20).all()

View File

@ -0,0 +1,36 @@
import argparse
from aeromancer.db.models import Project
class ProjectFilter(object):
"""Manage the arguments for filtering queries by project.
"""
@staticmethod
def add_arguments(parser):
"""Given an argparse.ArgumentParser add arguments.
"""
grp = parser.add_argument_group('Project Filter')
grp.add_argument(
'--project',
action='append',
default=[],
dest='projects',
help='projects to limit search, by exact name',
)
@classmethod
def from_parsed_args(cls, parsed_args):
return cls(projects=parsed_args.projects)
def __init__(self, projects):
self.projects = projects
def update_query(self, query):
if self.projects:
query = query.filter(
Project.name.in_(self.projects)
)
return query