Skip to content

Commit

Permalink
Merge pull request #1 from jparise/parser
Browse files Browse the repository at this point in the history
Manually validate parser options
  • Loading branch information
jparise committed May 11, 2016
2 parents 2044922 + 69e9e07 commit 330e6d7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 19 deletions.
32 changes: 15 additions & 17 deletions flake8_author.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
"""

import ast
import optparse
import re

__author__ = 'Jon Parise'
__version__ = '1.0.0'
__version__ = '1.0.1'


class Checker(object):
Expand All @@ -28,33 +27,32 @@ def __init__(self, tree, filename):

@classmethod
def add_options(cls, parser):
def pattern_callback(option, opt_str, value, parser):
try:
setattr(parser.values, option.dest, re.compile(value))
except re.error as e:
raise optparse.OptionValueError(
"option {}: '{}': {}".format(opt_str, value, e))

parser.add_option(
'--author-attribute',
default='optional',
type='choice',
choices=['optional', 'required', 'forbidden'],
help="__author__ attribute: optional, required, forbidden")
parser.add_option(
'--author-pattern',
default=re.compile(r'.*'),
type='string',
action="callback",
callback=pattern_callback,
default=r'.*',
help="__author__ attribute validation pattern (regex)")
parser.config_options.append('author-attribute')
parser.config_options.append('author-pattern')

@classmethod
def parse_options(cls, options):
cls.options['attribute'] = options.author_attribute
cls.options['pattern'] = options.author_pattern
choices = ('optional', 'required', 'forbidden')
if options.author_attribute in choices:
cls.options['attribute'] = options.author_attribute
else:
raise ValueError(
"author-attribute: '{}' must be one of: {}".format(
options.author_attribute, ', '.join(choices)))

try:
cls.options['pattern'] = re.compile(options.author_pattern)
except re.error as e:
raise ValueError("author-pattern: '{}': {}".format(
options.author_pattern, e))

def find_author_node(self, tree):
for node in tree.body:
Expand Down
4 changes: 2 additions & 2 deletions tests/test_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_author_forbidden_but_present():


def test_author_invalid_attribute():
with pytest.raises(SystemExit):
with pytest.raises(ValueError):
check('Jon Parise', attribute='invalid')


Expand All @@ -75,5 +75,5 @@ def test_author_pattern_not_matched():


def test_author_pattern_invalid_regex():
with pytest.raises(SystemExit):
with pytest.raises(ValueError):
check('Jon Parise', pattern=r'[[[')

0 comments on commit 330e6d7

Please sign in to comment.