[SCM] WebKit Debian packaging branch, webkit-1.1, updated. upstream/1.1.21-584-g1e41756
eric at webkit.org
eric at webkit.org
Fri Feb 26 22:25:27 UTC 2010
The following commit has been merged in the webkit-1.1 branch:
commit 41be1baa4ae98e72127efd98eafc01329bbeb7c1
Author: eric at webkit.org <eric at webkit.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Date: Fri Feb 19 05:17:04 2010 +0000
2010-02-18 Chris Jerdonek <cjerdonek at webkit.org>
Reviewed by Shinichiro Hamaji.
Moved parsing-related code to a separate file. Also increased
the unit test coverage in some affected areas.
https://bugs.webkit.org/show_bug.cgi?id=34675
This revision contains no new functionality.
* Scripts/check-webkit-style:
- Adjusted to call check_webkit_style_parser().
* Scripts/webkitpy/style/checker.py:
- Added check_webkit_style_parser() to pass checker.py
configuration settings to optparser.py.
- Moved _create_usage() and the CommandOptionValues,
DefaultCommandOptionValues, ArgumentPrinter, and
ArgumentParser classes to optparser.py.
* Scripts/webkitpy/style/checker_unittest.py:
- Moved the ProcessorOptionsTest, ArgumentPrinterTest, and
ArgumentParserTest classes to optparser.py.
- Added the CheckWebKitStyleFunctionTest class to check
the check_webkit_style_configuration() and
check_webkit_style_parser() code paths.
* Scripts/webkitpy/style/optparser.py: Added.
- From checker.py, added _create_usage() and the
CommandOptionValues, DefaultCommandOptionValues,
ArgumentPrinter, and ArgumentParser classes.
- In the ArgumentParser constructor--
- Added all_categories as a required parameter.
- Removed the default value from the default_options parameter.
* Scripts/webkitpy/style/optparser_unittest.py: Added.
- From checker_unittest.py, added the ProcessorOptionsTest,
ArgumentPrinterTest, and ArgumentParserTest classes.
- Added the CreateUsageTest class to test _create_usage().
* Scripts/webkitpy/style/unittests.py:
- Added optparser_unittest import.
git-svn-id: http://svn.webkit.org/repository/webkit/trunk@55001 268f45cc-cd09-0410-ab3c-d52691b4dbfc
diff --git a/WebKitTools/ChangeLog b/WebKitTools/ChangeLog
index ac98a3b..4dcaf4c 100644
--- a/WebKitTools/ChangeLog
+++ b/WebKitTools/ChangeLog
@@ -1,3 +1,47 @@
+2010-02-18 Chris Jerdonek <cjerdonek at webkit.org>
+
+ Reviewed by Shinichiro Hamaji.
+
+ Moved parsing-related code to a separate file. Also increased
+ the unit test coverage in some affected areas.
+
+ https://bugs.webkit.org/show_bug.cgi?id=34675
+
+ This revision contains no new functionality.
+
+ * Scripts/check-webkit-style:
+ - Adjusted to call check_webkit_style_parser().
+
+ * Scripts/webkitpy/style/checker.py:
+ - Added check_webkit_style_parser() to pass checker.py
+ configuration settings to optparser.py.
+ - Moved _create_usage() and the CommandOptionValues,
+ DefaultCommandOptionValues, ArgumentPrinter, and
+ ArgumentParser classes to optparser.py.
+
+ * Scripts/webkitpy/style/checker_unittest.py:
+ - Moved the ProcessorOptionsTest, ArgumentPrinterTest, and
+ ArgumentParserTest classes to optparser.py.
+ - Added the CheckWebKitStyleFunctionTest class to check
+ the check_webkit_style_configuration() and
+ check_webkit_style_parser() code paths.
+
+ * Scripts/webkitpy/style/optparser.py: Added.
+ - From checker.py, added _create_usage() and the
+ CommandOptionValues, DefaultCommandOptionValues,
+ ArgumentPrinter, and ArgumentParser classes.
+ - In the ArgumentParser constructor--
+ - Added all_categories as a required parameter.
+ - Removed the default value from the default_options parameter.
+
+ * Scripts/webkitpy/style/optparser_unittest.py: Added.
+ - From checker_unittest.py, added the ProcessorOptionsTest,
+ ArgumentPrinterTest, and ArgumentParserTest classes.
+ - Added the CreateUsageTest class to test _create_usage().
+
+ * Scripts/webkitpy/style/unittests.py:
+ - Added optparser_unittest import.
+
2010-02-18 Alexey Proskuryakov <ap at apple.com>
Reviewed by Dan Bernstein.
diff --git a/WebKitTools/Scripts/check-webkit-style b/WebKitTools/Scripts/check-webkit-style
index 74ddc01..ea2e943 100755
--- a/WebKitTools/Scripts/check-webkit-style
+++ b/WebKitTools/Scripts/check-webkit-style
@@ -57,8 +57,7 @@ def main():
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace')
-
- parser = checker.ArgumentParser()
+ parser = checker.check_webkit_style_parser()
(files, options) = parser.parse(sys.argv[1:])
configuration = checker.check_webkit_style_configuration(options)
diff --git a/WebKitTools/Scripts/webkitpy/style/checker.py b/WebKitTools/Scripts/webkitpy/style/checker.py
index bd99d0b..9beda9e 100644
--- a/WebKitTools/Scripts/webkitpy/style/checker.py
+++ b/WebKitTools/Scripts/webkitpy/style/checker.py
@@ -30,15 +30,15 @@
"""Front end of some style-checker modules."""
import codecs
-import getopt
import os.path
import sys
from .. style_references import parse_patch
from error_handlers import DefaultStyleErrorHandler
from error_handlers import PatchStyleErrorHandler
-from filter import validate_filter_rules
from filter import FilterConfiguration
+from optparser import ArgumentParser
+from optparser import DefaultCommandOptionValues
from processors.common import check_no_carriage_return
from processors.common import categories as CommonCategories
from processors.cpp import CppProcessor
@@ -163,6 +163,15 @@ def _check_webkit_style_defaults():
verbosity=_DEFAULT_VERBOSITY)
+# This function assists in optparser not having to import from checker.
+def check_webkit_style_parser():
+ all_categories = _all_categories()
+ default_options = _check_webkit_style_defaults()
+ return ArgumentParser(all_categories=all_categories,
+ base_filter_rules=_BASE_FILTER_RULES,
+ default_options=default_options)
+
+
def check_webkit_style_configuration(options):
"""Return a StyleCheckerConfiguration instance for check-webkit-style.
@@ -182,400 +191,6 @@ def check_webkit_style_configuration(options):
verbosity=options.verbosity)
-def _create_usage(default_options):
- """Return the usage string to display for command help.
-
- Args:
- default_options: A DefaultCommandOptionValues instance.
-
- """
- usage = """
-Syntax: %(program_name)s [--verbose=#] [--git-commit=<SingleCommit>] [--output=vs7]
- [--filter=-x,+y,...] [file] ...
-
- The style guidelines this tries to follow are here:
- http://webkit.org/coding/coding-style.html
-
- Every style error is given a confidence score from 1-5, with 5 meaning
- we are certain of the problem, and 1 meaning it could be a legitimate
- construct. This can miss some errors and does not substitute for
- code review.
-
- To prevent specific lines from being linted, add a '// NOLINT' comment to the
- end of the line.
-
- Linted extensions are .cpp, .c and .h. Other file types are ignored.
-
- The file parameter is optional and accepts multiple files. Leaving
- out the file parameter applies the check to all files considered changed
- by your source control management system.
-
- Flags:
-
- verbose=#
- A number 1-5 that restricts output to errors with a confidence
- score at or above this value. In particular, the value 1 displays
- all errors. The default is %(default_verbosity)s.
-
- git-commit=<SingleCommit>
- Checks the style of everything from the given commit to the local tree.
-
- output=vs7
- The output format, which may be one of
- emacs : to ease emacs parsing
- vs7 : compatible with Visual Studio
- Defaults to "%(default_output_format)s". Other formats are unsupported.
-
- filter=-x,+y,...
- A comma-separated list of boolean filter rules used to filter
- which categories of style guidelines to check. The script checks
- a category if the category passes the filter rules, as follows.
-
- Any webkit category starts out passing. All filter rules are then
- evaluated left to right, with later rules taking precedence. For
- example, the rule "+foo" passes any category that starts with "foo",
- and "-foo" fails any such category. The filter input "-whitespace,
- +whitespace/braces" fails the category "whitespace/tab" and passes
- "whitespace/braces".
-
- Examples: --filter=-whitespace,+whitespace/braces
- --filter=-whitespace,-runtime/printf,+runtime/printf_format
- --filter=-,+build/include_what_you_use
-
- Category names appear in error messages in brackets, for example
- [whitespace/indent]. To see a list of all categories available to
- %(program_name)s, along with which are enabled by default, pass
- the empty filter as follows:
- --filter=
-""" % {'program_name': os.path.basename(sys.argv[0]),
- 'default_verbosity': default_options.verbosity,
- 'default_output_format': default_options.output_format}
-
- return usage
-
-
-# FIXME: Eliminate support for "extra_flag_values".
-#
-# This class should not have knowledge of the flag key names.
-class CommandOptionValues(object):
-
- """Stores the option values passed by the user via the command line.
-
- Attributes:
- extra_flag_values: A string-string dictionary of all flag key-value
- pairs that are not otherwise represented by this
- class. The default is the empty dictionary.
-
- filter_rules: The list of filter rules provided by the user.
- These rules are appended to the base rules and
- path-specific rules and so take precedence over
- the base filter rules, etc.
-
- git_commit: A string representing the git commit to check.
- The default is None.
-
- output_format: A string that is the output format. The supported
- output formats are "emacs" which emacs can parse
- and "vs7" which Microsoft Visual Studio 7 can parse.
-
- verbosity: An integer between 1-5 inclusive that restricts output
- to errors with a confidence score at or above this value.
- The default is 1, which reports all errors.
-
- """
- def __init__(self,
- extra_flag_values=None,
- filter_rules=None,
- git_commit=None,
- output_format="emacs",
- verbosity=1):
- if extra_flag_values is None:
- extra_flag_values = {}
- if filter_rules is None:
- filter_rules = []
-
- if output_format not in ("emacs", "vs7"):
- raise ValueError('Invalid "output_format" parameter: '
- 'value must be "emacs" or "vs7". '
- 'Value given: "%s".' % output_format)
-
- if (verbosity < 1) or (verbosity > 5):
- raise ValueError('Invalid "verbosity" parameter: '
- "value must be an integer between 1-5 inclusive. "
- 'Value given: "%s".' % verbosity)
-
- self.extra_flag_values = extra_flag_values
- self.filter_rules = filter_rules
- self.git_commit = git_commit
- self.output_format = output_format
- self.verbosity = verbosity
-
- # Useful for unit testing.
- def __eq__(self, other):
- """Return whether this instance is equal to another."""
- if self.extra_flag_values != other.extra_flag_values:
- return False
- if self.filter_rules != other.filter_rules:
- return False
- if self.git_commit != other.git_commit:
- return False
- if self.output_format != other.output_format:
- return False
- if self.verbosity != other.verbosity:
- return False
-
- return True
-
- # Useful for unit testing.
- def __ne__(self, other):
- # Python does not automatically deduce this from __eq__().
- return not self.__eq__(other)
-
-
-# This class should not have knowledge of the flag key names.
-class DefaultCommandOptionValues(object):
-
- """Stores the default check-webkit-style command-line options.
-
- Attributes:
- output_format: A string that is the default output format.
- verbosity: An integer that is the default verbosity level.
-
- """
-
- def __init__(self, output_format, verbosity):
- self.output_format = output_format
- self.verbosity = verbosity
-
-
-class ArgumentPrinter(object):
-
- """Supports the printing of check-webkit-style command arguments."""
-
- def _flag_pair_to_string(self, flag_key, flag_value):
- return '--%(key)s=%(val)s' % {'key': flag_key, 'val': flag_value }
-
- def to_flag_string(self, options):
- """Return a flag string of the given CommandOptionValues instance.
-
- This method orders the flag values alphabetically by the flag key.
-
- Args:
- options: A CommandOptionValues instance.
-
- """
- flags = options.extra_flag_values.copy()
-
- flags['output'] = options.output_format
- flags['verbose'] = options.verbosity
- # Only include the filter flag if user-provided rules are present.
- filter_rules = options.filter_rules
- if filter_rules:
- flags['filter'] = ",".join(filter_rules)
- if options.git_commit:
- flags['git-commit'] = options.git_commit
-
- flag_string = ''
- # Alphabetizing lets us unit test this method.
- for key in sorted(flags.keys()):
- flag_string += self._flag_pair_to_string(key, flags[key]) + ' '
-
- return flag_string.strip()
-
-
-# FIXME: Replace the use of getopt.getopt() with optparse.OptionParser.
-class ArgumentParser(object):
-
- # FIXME: Move the documentation of the attributes to the __init__
- # docstring after making the attributes internal.
- """Supports the parsing of check-webkit-style command arguments.
-
- Attributes:
- create_usage: A function that accepts a DefaultCommandOptionValues
- instance and returns a string of usage instructions.
- Defaults to the function that generates the usage
- string for check-webkit-style.
- default_options: A DefaultCommandOptionValues instance. Defaults
- to the default command option values used by
- check-webkit-style.
- stderr_write: A function that takes a string as a parameter and
- serves as stderr.write. Defaults to sys.stderr.write.
- This parameter should be specified only for unit tests.
-
- """
-
- def __init__(self,
- base_filter_rules=None,
- create_usage=None,
- default_options=None,
- stderr_write=None):
- """Create an ArgumentParser instance.
-
- Args:
- base_filter_rules: The list of filter rules at the beginning of
- the list of rules used to check style. This
- list has the least precedence when checking
- style and precedes any user-provided rules.
- The class uses this parameter only for display
- purposes to the user. Defaults to the base
- filter rules for check-webkit-style.
- create_usage: See the documentation of the corresponding
- attribute in the class docstring.
- default_options: See the documentation of the corresponding
- attribute in the class docstring.
- stderr_write: See the documentation of the corresponding
- attribute in the class docstring.
-
- """
- if base_filter_rules is None:
- base_filter_rules = _BASE_FILTER_RULES
- if create_usage is None:
- create_usage = _create_usage
- if default_options is None:
- default_options = _check_webkit_style_defaults()
- if stderr_write is None:
- stderr_write = sys.stderr.write
-
- self._base_filter_rules = base_filter_rules
- # FIXME: Rename these to reflect that they are internal.
- self.create_usage = create_usage
- self.default_options = default_options
- self.stderr_write = stderr_write
-
- def _exit_with_usage(self, error_message=''):
- """Exit and print a usage string with an optional error message.
-
- Args:
- error_message: A string that is an error message to print.
-
- """
- usage = self.create_usage(self.default_options)
- self.stderr_write(usage)
- if error_message:
- sys.exit('\nFATAL ERROR: ' + error_message)
- else:
- sys.exit(1)
-
- def _exit_with_categories(self):
- """Exit and print the style categories and default filter rules."""
- self.stderr_write('\nAll categories:\n')
- categories = _all_categories()
- for category in sorted(categories):
- self.stderr_write(' ' + category + '\n')
-
- self.stderr_write('\nDefault filter rules**:\n')
- for filter_rule in sorted(self._base_filter_rules):
- self.stderr_write(' ' + filter_rule + '\n')
- self.stderr_write('\n**The command always evaluates the above rules, '
- 'and before any --filter flag.\n\n')
-
- sys.exit(0)
-
- def _parse_filter_flag(self, flag_value):
- """Parse the --filter flag, and return a list of filter rules.
-
- Args:
- flag_value: A string of comma-separated filter rules, for
- example "-whitespace,+whitespace/indent".
-
- """
- filters = []
- for uncleaned_filter in flag_value.split(','):
- filter = uncleaned_filter.strip()
- if not filter:
- continue
- filters.append(filter)
- return filters
-
- def parse(self, args, extra_flags=None):
- """Parse the command line arguments to check-webkit-style.
-
- Args:
- args: A list of command-line arguments as returned by sys.argv[1:].
- extra_flags: A list of flags whose values we want to extract, but
- are not supported by the CommandOptionValues class.
- An example flag "new_flag=". This defaults to the
- empty list.
-
- Returns:
- A tuple of (filenames, options)
-
- filenames: The list of filenames to check.
- options: A CommandOptionValues instance.
-
- """
- if extra_flags is None:
- extra_flags = []
-
- output_format = self.default_options.output_format
- verbosity = self.default_options.verbosity
-
- # The flags already supported by the CommandOptionValues class.
- flags = ['help', 'output=', 'verbose=', 'filter=', 'git-commit=']
-
- for extra_flag in extra_flags:
- if extra_flag in flags:
- raise ValueError('Flag \'%(extra_flag)s is duplicated '
- 'or already supported.' %
- {'extra_flag': extra_flag})
- flags.append(extra_flag)
-
- try:
- (opts, filenames) = getopt.getopt(args, '', flags)
- except getopt.GetoptError:
- # FIXME: Settle on an error handling approach: come up
- # with a consistent guideline as to when and whether
- # a ValueError should be raised versus calling
- # sys.exit when needing to interrupt execution.
- self._exit_with_usage('Invalid arguments.')
-
- extra_flag_values = {}
- git_commit = None
- filter_rules = []
-
- for (opt, val) in opts:
- if opt == '--help':
- self._exit_with_usage()
- elif opt == '--output':
- output_format = val
- elif opt == '--verbose':
- verbosity = val
- elif opt == '--git-commit':
- git_commit = val
- elif opt == '--filter':
- if not val:
- self._exit_with_categories()
- filter_rules = self._parse_filter_flag(val)
- else:
- extra_flag_values[opt] = val
-
- # Check validity of resulting values.
- if filenames and (git_commit != None):
- self._exit_with_usage('It is not possible to check files and a '
- 'specific commit at the same time.')
-
- if output_format not in ('emacs', 'vs7'):
- raise ValueError('Invalid --output value "%s": The only '
- 'allowed output formats are emacs and vs7.' %
- output_format)
-
- all_categories = _all_categories()
- validate_filter_rules(filter_rules, all_categories)
-
- verbosity = int(verbosity)
- if (verbosity < 1) or (verbosity > 5):
- raise ValueError('Invalid --verbose value %s: value must '
- 'be between 1-5.' % verbosity)
-
- options = CommandOptionValues(extra_flag_values=extra_flag_values,
- filter_rules=filter_rules,
- git_commit=git_commit,
- output_format=output_format,
- verbosity=verbosity)
-
- return (filenames, options)
-
-
# Enum-like idiom
class FileType:
diff --git a/WebKitTools/Scripts/webkitpy/style/checker_unittest.py b/WebKitTools/Scripts/webkitpy/style/checker_unittest.py
index ba1bb4d..fe12512 100755
--- a/WebKitTools/Scripts/webkitpy/style/checker_unittest.py
+++ b/WebKitTools/Scripts/webkitpy/style/checker_unittest.py
@@ -41,79 +41,19 @@ from checker import _BASE_FILTER_RULES
from checker import _MAX_REPORTS_PER_CATEGORY
from checker import _PATH_RULES_SPECIFIER as PATH_RULES_SPECIFIER
from checker import _all_categories
-from checker import CommandOptionValues as ProcessorOptions
-from checker import DefaultCommandOptionValues
+from checker import check_webkit_style_configuration
+from checker import check_webkit_style_parser
from checker import ProcessorDispatcher
from checker import StyleChecker
from checker import StyleCheckerConfiguration
from filter import validate_filter_rules
from filter import FilterConfiguration
+from optparser import ArgumentParser
+from optparser import CommandOptionValues
from processors.cpp import CppProcessor
from processors.text import TextProcessor
-class ProcessorOptionsTest(unittest.TestCase):
-
- """Tests ProcessorOptions class."""
-
- def test_init(self):
- """Test __init__ constructor."""
- # Check default parameters.
- options = ProcessorOptions()
- self.assertEquals(options.extra_flag_values, {})
- self.assertEquals(options.filter_rules, [])
- self.assertEquals(options.git_commit, None)
- self.assertEquals(options.output_format, "emacs")
- self.assertEquals(options.verbosity, 1)
-
- # Check argument validation.
- self.assertRaises(ValueError, ProcessorOptions, output_format="bad")
- ProcessorOptions(output_format="emacs") # No ValueError: works
- ProcessorOptions(output_format="vs7") # works
- self.assertRaises(ValueError, ProcessorOptions, verbosity=0)
- self.assertRaises(ValueError, ProcessorOptions, verbosity=6)
- ProcessorOptions(verbosity=1) # works
- ProcessorOptions(verbosity=5) # works
-
- # Check attributes.
- options = ProcessorOptions(extra_flag_values={"extra_value" : 2},
- filter_rules=["+"],
- git_commit="commit",
- output_format="vs7",
- verbosity=3)
- self.assertEquals(options.extra_flag_values, {"extra_value" : 2})
- self.assertEquals(options.filter_rules, ["+"])
- self.assertEquals(options.git_commit, "commit")
- self.assertEquals(options.output_format, "vs7")
- self.assertEquals(options.verbosity, 3)
-
- def test_eq(self):
- """Test __eq__ equality function."""
- # == calls __eq__.
- self.assertTrue(ProcessorOptions() == ProcessorOptions())
-
- # Verify that a difference in any argument causes equality to fail.
- options = ProcessorOptions(extra_flag_values={"extra_value" : 1},
- filter_rules=["+"],
- git_commit="commit",
- output_format="vs7",
- verbosity=1)
- self.assertFalse(options == ProcessorOptions(extra_flag_values=
- {"extra_value" : 2}))
- self.assertFalse(options == ProcessorOptions(filter_rules=["-"]))
- self.assertFalse(options == ProcessorOptions(git_commit="commit2"))
- self.assertFalse(options == ProcessorOptions(output_format="emacs"))
- self.assertFalse(options == ProcessorOptions(verbosity=2))
-
- def test_ne(self):
- """Test __ne__ inequality function."""
- # != calls __ne__.
- # By default, __ne__ always returns true on different objects.
- # Thus, just check the distinguishing case to verify that the
- # code defines __ne__.
- self.assertFalse(ProcessorOptions() != ProcessorOptions())
-
-
class GlobalVariablesTest(unittest.TestCase):
"""Tests validity of the global variables."""
@@ -146,7 +86,9 @@ class GlobalVariablesTest(unittest.TestCase):
# FIXME: We should not need to call parse() to determine
# whether the default arguments are valid.
- parser = style.ArgumentParser(default_options=default_options)
+ parser = ArgumentParser(all_categories=self._all_categories(),
+ base_filter_rules=[],
+ default_options=default_options)
# No need to test the return value here since we test parse()
# on valid arguments elsewhere.
parser.parse([]) # arguments valid: no error or SystemExit
@@ -191,7 +133,6 @@ class GlobalVariablesTest(unittest.TestCase):
"JavaScriptCore/qt/tests/qscriptengine/tst_qscriptengine.cpp",
"readability/naming")
-
def test_max_reports_per_category(self):
"""Check that _MAX_REPORTS_PER_CATEGORY is valid."""
all_categories = self._all_categories()
@@ -200,159 +141,18 @@ class GlobalVariablesTest(unittest.TestCase):
'Key "%s" is not a category' % category)
-class ArgumentPrinterTest(unittest.TestCase):
-
- """Tests the ArgumentPrinter class."""
-
- _printer = style.ArgumentPrinter()
-
- def _create_options(self,
- output_format='emacs',
- verbosity=3,
- filter_rules=[],
- git_commit=None,
- extra_flag_values={}):
- return ProcessorOptions(extra_flag_values=extra_flag_values,
- filter_rules=filter_rules,
- git_commit=git_commit,
- output_format=output_format,
- verbosity=verbosity)
-
- def test_to_flag_string(self):
- options = self._create_options('vs7', 5, ['+foo', '-bar'], 'git',
- {'a': 0, 'z': 1})
- self.assertEquals('--a=0 --filter=+foo,-bar --git-commit=git '
- '--output=vs7 --verbose=5 --z=1',
- self._printer.to_flag_string(options))
-
- # This is to check that --filter and --git-commit do not
- # show up when not user-specified.
- options = self._create_options()
- self.assertEquals('--output=emacs --verbose=3',
- self._printer.to_flag_string(options))
-
+class CheckWebKitStyleFunctionTest(unittest.TestCase):
-class ArgumentParserTest(unittest.TestCase):
-
- """Test the ArgumentParser class."""
+ """Tests the functions with names of the form check_webkit_style_*."""
- def _parse(self):
- """Return a default parse() function for testing."""
- return self._create_parser().parse
-
- def _create_defaults(self):
- """Return a DefaultCommandOptionValues instance for testing."""
- base_filter_rules = ["-", "+whitespace"]
- return DefaultCommandOptionValues(output_format="vs7",
- verbosity=3)
-
- def _create_parser(self):
- """Return an ArgumentParser instance for testing."""
- def create_usage(_default_options):
- """Return a usage string for testing."""
- return "usage"
-
- def stderr_write(message):
- # We do not want the usage string or style categories
- # to print during unit tests, so print nothing.
- return
-
- default_options = self._create_defaults()
-
- return style.ArgumentParser(create_usage=create_usage,
- default_options=default_options,
- stderr_write=stderr_write)
-
- def test_parse_documentation(self):
- parse = self._parse()
-
- # FIXME: Test both the printing of the usage string and the
- # filter categories help.
-
- # Request the usage string.
- self.assertRaises(SystemExit, parse, ['--help'])
- # Request default filter rules and available style categories.
- self.assertRaises(SystemExit, parse, ['--filter='])
-
- def test_parse_bad_values(self):
- parse = self._parse()
-
- # Pass an unsupported argument.
- self.assertRaises(SystemExit, parse, ['--bad'])
-
- self.assertRaises(ValueError, parse, ['--verbose=bad'])
- self.assertRaises(ValueError, parse, ['--verbose=0'])
- self.assertRaises(ValueError, parse, ['--verbose=6'])
- parse(['--verbose=1']) # works
- parse(['--verbose=5']) # works
-
- self.assertRaises(ValueError, parse, ['--output=bad'])
- parse(['--output=vs7']) # works
-
- # Pass a filter rule not beginning with + or -.
- self.assertRaises(ValueError, parse, ['--filter=build'])
- parse(['--filter=+build']) # works
- # Pass files and git-commit at the same time.
- self.assertRaises(SystemExit, parse, ['--git-commit=', 'file.txt'])
- # Pass an extra flag already supported.
- self.assertRaises(ValueError, parse, [], ['filter='])
- parse([], ['extra=']) # works
- # Pass an extra flag with typo.
- self.assertRaises(SystemExit, parse, ['--extratypo='], ['extra='])
- parse(['--extra='], ['extra=']) # works
- self.assertRaises(ValueError, parse, [], ['extra=', 'extra='])
-
-
- def test_parse_default_arguments(self):
- parse = self._parse()
-
- (files, options) = parse([])
-
- self.assertEquals(files, [])
-
- self.assertEquals(options.output_format, 'vs7')
- self.assertEquals(options.verbosity, 3)
- self.assertEquals(options.filter_rules, [])
- self.assertEquals(options.git_commit, None)
-
- def test_parse_explicit_arguments(self):
- parse = self._parse()
-
- # Pass non-default explicit values.
- (files, options) = parse(['--output=emacs'])
- self.assertEquals(options.output_format, 'emacs')
- (files, options) = parse(['--verbose=4'])
- self.assertEquals(options.verbosity, 4)
- (files, options) = parse(['--git-commit=commit'])
- self.assertEquals(options.git_commit, 'commit')
-
- # Pass user_rules.
- (files, options) = parse(['--filter=+build,-whitespace'])
- self.assertEquals(options.filter_rules,
- ["+build", "-whitespace"])
+ def test_check_webkit_style_configuration(self):
+ # Exercise the code path to make sure the function does not error out.
+ option_values = CommandOptionValues()
+ configuration = check_webkit_style_configuration(option_values)
- # Pass spurious white space in user rules.
- (files, options) = parse(['--filter=+build, -whitespace'])
- self.assertEquals(options.filter_rules,
- ["+build", "-whitespace"])
-
- # Pass extra flag values.
- (files, options) = parse(['--extra'], ['extra'])
- self.assertEquals(options.extra_flag_values, {'--extra': ''})
- (files, options) = parse(['--extra='], ['extra='])
- self.assertEquals(options.extra_flag_values, {'--extra': ''})
- (files, options) = parse(['--extra=x'], ['extra='])
- self.assertEquals(options.extra_flag_values, {'--extra': 'x'})
-
- def test_parse_files(self):
- parse = self._parse()
-
- (files, options) = parse(['foo.cpp'])
- self.assertEquals(files, ['foo.cpp'])
-
- # Pass multiple files.
- (files, options) = parse(['--output=emacs', 'foo.cpp', 'bar.cpp'])
- self.assertEquals(files, ['foo.cpp', 'bar.cpp'])
+ def test_check_webkit_style_parser(self):
+ # Exercise the code path to make sure the function does not error out.
+ parser = check_webkit_style_parser()
class ProcessorDispatcherSkipTest(unittest.TestCase):
diff --git a/WebKitTools/Scripts/webkitpy/style/optparser.py b/WebKitTools/Scripts/webkitpy/style/optparser.py
new file mode 100644
index 0000000..4137c8b
--- /dev/null
+++ b/WebKitTools/Scripts/webkitpy/style/optparser.py
@@ -0,0 +1,424 @@
+# Copyright (C) 2010 Chris Jerdonek (cjerdonek at webkit.org)
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Supports the parsing of command-line options for check-webkit-style."""
+
+import getopt
+import os.path
+import sys
+
+from filter import validate_filter_rules
+# This module should not import anything from checker.py.
+
+
+def _create_usage(default_options):
+ """Return the usage string to display for command help.
+
+ Args:
+ default_options: A DefaultCommandOptionValues instance.
+
+ """
+ usage = """
+Syntax: %(program_name)s [--verbose=#] [--git-commit=<SingleCommit>] [--output=vs7]
+ [--filter=-x,+y,...] [file] ...
+
+ The style guidelines this tries to follow are here:
+ http://webkit.org/coding/coding-style.html
+
+ Every style error is given a confidence score from 1-5, with 5 meaning
+ we are certain of the problem, and 1 meaning it could be a legitimate
+ construct. This can miss some errors and does not substitute for
+ code review.
+
+ To prevent specific lines from being linted, add a '// NOLINT' comment to the
+ end of the line.
+
+ Linted extensions are .cpp, .c and .h. Other file types are ignored.
+
+ The file parameter is optional and accepts multiple files. Leaving
+ out the file parameter applies the check to all files considered changed
+ by your source control management system.
+
+ Flags:
+
+ verbose=#
+ A number 1-5 that restricts output to errors with a confidence
+ score at or above this value. In particular, the value 1 displays
+ all errors. The default is %(default_verbosity)s.
+
+ git-commit=<SingleCommit>
+ Checks the style of everything from the given commit to the local tree.
+
+ output=vs7
+ The output format, which may be one of
+ emacs : to ease emacs parsing
+ vs7 : compatible with Visual Studio
+ Defaults to "%(default_output_format)s". Other formats are unsupported.
+
+ filter=-x,+y,...
+ A comma-separated list of boolean filter rules used to filter
+ which categories of style guidelines to check. The script checks
+ a category if the category passes the filter rules, as follows.
+
+ Any webkit category starts out passing. All filter rules are then
+ evaluated left to right, with later rules taking precedence. For
+ example, the rule "+foo" passes any category that starts with "foo",
+ and "-foo" fails any such category. The filter input "-whitespace,
+ +whitespace/braces" fails the category "whitespace/tab" and passes
+ "whitespace/braces".
+
+ Examples: --filter=-whitespace,+whitespace/braces
+ --filter=-whitespace,-runtime/printf,+runtime/printf_format
+ --filter=-,+build/include_what_you_use
+
+ Category names appear in error messages in brackets, for example
+ [whitespace/indent]. To see a list of all categories available to
+ %(program_name)s, along with which are enabled by default, pass
+ the empty filter as follows:
+ --filter=
+""" % {'program_name': os.path.basename(sys.argv[0]),
+ 'default_verbosity': default_options.verbosity,
+ 'default_output_format': default_options.output_format}
+
+ return usage
+
+
+# This class should not have knowledge of the flag key names.
+class DefaultCommandOptionValues(object):
+
+ """Stores the default check-webkit-style command-line options.
+
+ Attributes:
+ output_format: A string that is the default output format.
+ verbosity: An integer that is the default verbosity level.
+
+ """
+
+ def __init__(self, output_format, verbosity):
+ self.output_format = output_format
+ self.verbosity = verbosity
+
+
+# FIXME: Eliminate support for "extra_flag_values".
+#
+# This class should not have knowledge of the flag key names.
+class CommandOptionValues(object):
+
+ """Stores the option values passed by the user via the command line.
+
+ Attributes:
+ extra_flag_values: A string-string dictionary of all flag key-value
+ pairs that are not otherwise represented by this
+ class. The default is the empty dictionary.
+
+ filter_rules: The list of filter rules provided by the user.
+ These rules are appended to the base rules and
+ path-specific rules and so take precedence over
+ the base filter rules, etc.
+
+ git_commit: A string representing the git commit to check.
+ The default is None.
+
+ output_format: A string that is the output format. The supported
+ output formats are "emacs" which emacs can parse
+ and "vs7" which Microsoft Visual Studio 7 can parse.
+
+ verbosity: An integer between 1-5 inclusive that restricts output
+ to errors with a confidence score at or above this value.
+ The default is 1, which reports all errors.
+
+ """
+ def __init__(self,
+ extra_flag_values=None,
+ filter_rules=None,
+ git_commit=None,
+ output_format="emacs",
+ verbosity=1):
+ if extra_flag_values is None:
+ extra_flag_values = {}
+ if filter_rules is None:
+ filter_rules = []
+
+ if output_format not in ("emacs", "vs7"):
+ raise ValueError('Invalid "output_format" parameter: '
+ 'value must be "emacs" or "vs7". '
+ 'Value given: "%s".' % output_format)
+
+ if (verbosity < 1) or (verbosity > 5):
+ raise ValueError('Invalid "verbosity" parameter: '
+ "value must be an integer between 1-5 inclusive. "
+ 'Value given: "%s".' % verbosity)
+
+ self.extra_flag_values = extra_flag_values
+ self.filter_rules = filter_rules
+ self.git_commit = git_commit
+ self.output_format = output_format
+ self.verbosity = verbosity
+
+ # Useful for unit testing.
+ def __eq__(self, other):
+ """Return whether this instance is equal to another."""
+ if self.extra_flag_values != other.extra_flag_values:
+ return False
+ if self.filter_rules != other.filter_rules:
+ return False
+ if self.git_commit != other.git_commit:
+ return False
+ if self.output_format != other.output_format:
+ return False
+ if self.verbosity != other.verbosity:
+ return False
+
+ return True
+
+ # Useful for unit testing.
+ def __ne__(self, other):
+ # Python does not automatically deduce this from __eq__().
+ return not self.__eq__(other)
+
+
+class ArgumentPrinter(object):
+
+ """Supports the printing of check-webkit-style command arguments."""
+
+ def _flag_pair_to_string(self, flag_key, flag_value):
+ return '--%(key)s=%(val)s' % {'key': flag_key, 'val': flag_value }
+
+ def to_flag_string(self, options):
+ """Return a flag string of the given CommandOptionValues instance.
+
+ This method orders the flag values alphabetically by the flag key.
+
+ Args:
+ options: A CommandOptionValues instance.
+
+ """
+ flags = options.extra_flag_values.copy()
+
+ flags['output'] = options.output_format
+ flags['verbose'] = options.verbosity
+ # Only include the filter flag if user-provided rules are present.
+ filter_rules = options.filter_rules
+ if filter_rules:
+ flags['filter'] = ",".join(filter_rules)
+ if options.git_commit:
+ flags['git-commit'] = options.git_commit
+
+ flag_string = ''
+ # Alphabetizing lets us unit test this method.
+ for key in sorted(flags.keys()):
+ flag_string += self._flag_pair_to_string(key, flags[key]) + ' '
+
+ return flag_string.strip()
+
+
+# FIXME: Replace the use of getopt.getopt() with optparse.OptionParser.
+class ArgumentParser(object):
+
+ # FIXME: Move the documentation of the attributes to the __init__
+ # docstring after making the attributes internal.
+ """Supports the parsing of check-webkit-style command arguments.
+
+ Attributes:
+ create_usage: A function that accepts a DefaultCommandOptionValues
+ instance and returns a string of usage instructions.
+ Defaults to the function that generates the usage
+ string for check-webkit-style.
+ default_options: A DefaultCommandOptionValues instance that provides
+ the default values for options not explicitly
+ provided by the user.
+ stderr_write: A function that takes a string as a parameter and
+ serves as stderr.write. Defaults to sys.stderr.write.
+ This parameter should be specified only for unit tests.
+
+ """
+
+ def __init__(self,
+ all_categories,
+ default_options,
+ base_filter_rules=None,
+ create_usage=None,
+ stderr_write=None):
+ """Create an ArgumentParser instance.
+
+ Args:
+ all_categories: The set of all available style categories.
+ default_options: See the corresponding attribute in the class
+ docstring.
+ Keyword Args:
+ base_filter_rules: The list of filter rules at the beginning of
+ the list of rules used to check style. This
+ list has the least precedence when checking
+ style and precedes any user-provided rules.
+ The class uses this parameter only for display
+ purposes to the user. Defaults to the empty list.
+ create_usage: See the documentation of the corresponding
+ attribute in the class docstring.
+ stderr_write: See the documentation of the corresponding
+ attribute in the class docstring.
+
+ """
+ if base_filter_rules is None:
+ base_filter_rules = []
+ if create_usage is None:
+ create_usage = _create_usage
+ if stderr_write is None:
+ stderr_write = sys.stderr.write
+
+ self._all_categories = all_categories
+ self._base_filter_rules = base_filter_rules
+ # FIXME: Rename these to reflect that they are internal.
+ self.create_usage = create_usage
+ self.default_options = default_options
+ self.stderr_write = stderr_write
+
+ def _exit_with_usage(self, error_message=''):
+ """Exit and print a usage string with an optional error message.
+
+ Args:
+ error_message: A string that is an error message to print.
+
+ """
+ usage = self.create_usage(self.default_options)
+ self.stderr_write(usage)
+ if error_message:
+ sys.exit('\nFATAL ERROR: ' + error_message)
+ else:
+ sys.exit(1)
+
+ def _exit_with_categories(self):
+ """Exit and print the style categories and default filter rules."""
+ self.stderr_write('\nAll categories:\n')
+ for category in sorted(self._all_categories):
+ self.stderr_write(' ' + category + '\n')
+
+ self.stderr_write('\nDefault filter rules**:\n')
+ for filter_rule in sorted(self._base_filter_rules):
+ self.stderr_write(' ' + filter_rule + '\n')
+ self.stderr_write('\n**The command always evaluates the above rules, '
+ 'and before any --filter flag.\n\n')
+
+ sys.exit(0)
+
+ def _parse_filter_flag(self, flag_value):
+ """Parse the --filter flag, and return a list of filter rules.
+
+ Args:
+ flag_value: A string of comma-separated filter rules, for
+ example "-whitespace,+whitespace/indent".
+
+ """
+ filters = []
+ for uncleaned_filter in flag_value.split(','):
+ filter = uncleaned_filter.strip()
+ if not filter:
+ continue
+ filters.append(filter)
+ return filters
+
+ def parse(self, args, extra_flags=None):
+ """Parse the command line arguments to check-webkit-style.
+
+ Args:
+ args: A list of command-line arguments as returned by sys.argv[1:].
+ extra_flags: A list of flags whose values we want to extract, but
+ are not supported by the CommandOptionValues class.
+ An example flag "new_flag=". This defaults to the
+ empty list.
+
+ Returns:
+ A tuple of (filenames, options)
+
+ filenames: The list of filenames to check.
+ options: A CommandOptionValues instance.
+
+ """
+ if extra_flags is None:
+ extra_flags = []
+
+ output_format = self.default_options.output_format
+ verbosity = self.default_options.verbosity
+
+ # The flags already supported by the CommandOptionValues class.
+ flags = ['help', 'output=', 'verbose=', 'filter=', 'git-commit=']
+
+ for extra_flag in extra_flags:
+ if extra_flag in flags:
+ raise ValueError('Flag \'%(extra_flag)s is duplicated '
+ 'or already supported.' %
+ {'extra_flag': extra_flag})
+ flags.append(extra_flag)
+
+ try:
+ (opts, filenames) = getopt.getopt(args, '', flags)
+ except getopt.GetoptError:
+ # FIXME: Settle on an error handling approach: come up
+ # with a consistent guideline as to when and whether
+ # a ValueError should be raised versus calling
+ # sys.exit when needing to interrupt execution.
+ self._exit_with_usage('Invalid arguments.')
+
+ extra_flag_values = {}
+ git_commit = None
+ filter_rules = []
+
+ for (opt, val) in opts:
+ if opt == '--help':
+ self._exit_with_usage()
+ elif opt == '--output':
+ output_format = val
+ elif opt == '--verbose':
+ verbosity = val
+ elif opt == '--git-commit':
+ git_commit = val
+ elif opt == '--filter':
+ if not val:
+ self._exit_with_categories()
+ filter_rules = self._parse_filter_flag(val)
+ else:
+ extra_flag_values[opt] = val
+
+ # Check validity of resulting values.
+ if filenames and (git_commit != None):
+ self._exit_with_usage('It is not possible to check files and a '
+ 'specific commit at the same time.')
+
+ if output_format not in ('emacs', 'vs7'):
+ raise ValueError('Invalid --output value "%s": The only '
+ 'allowed output formats are emacs and vs7.' %
+ output_format)
+
+ validate_filter_rules(filter_rules, self._all_categories)
+
+ verbosity = int(verbosity)
+ if (verbosity < 1) or (verbosity > 5):
+ raise ValueError('Invalid --verbose value %s: value must '
+ 'be between 1-5.' % verbosity)
+
+ options = CommandOptionValues(extra_flag_values=extra_flag_values,
+ filter_rules=filter_rules,
+ git_commit=git_commit,
+ output_format=output_format,
+ verbosity=verbosity)
+
+ return (filenames, options)
+
diff --git a/WebKitTools/Scripts/webkitpy/style/optparser_unittest.py b/WebKitTools/Scripts/webkitpy/style/optparser_unittest.py
new file mode 100644
index 0000000..f23c5d1
--- /dev/null
+++ b/WebKitTools/Scripts/webkitpy/style/optparser_unittest.py
@@ -0,0 +1,258 @@
+# Copyright (C) 2010 Chris Jerdonek (cjerdonek at webkit.org)
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Unit tests for parser.py."""
+
+import unittest
+
+from optparser import _create_usage
+from optparser import ArgumentParser
+from optparser import ArgumentPrinter
+from optparser import CommandOptionValues as ProcessorOptions
+from optparser import DefaultCommandOptionValues
+
+
+class CreateUsageTest(unittest.TestCase):
+
+ """Tests the _create_usage() function."""
+
+ def test_create_usage(self):
+ default_options = DefaultCommandOptionValues(output_format="vs7",
+ verbosity=3)
+ # Exercise the code path to make sure the function does not error out.
+ _create_usage(default_options)
+
+
+class ArgumentPrinterTest(unittest.TestCase):
+
+ """Tests the ArgumentPrinter class."""
+
+ _printer = ArgumentPrinter()
+
+ def _create_options(self,
+ output_format='emacs',
+ verbosity=3,
+ filter_rules=[],
+ git_commit=None,
+ extra_flag_values={}):
+ return ProcessorOptions(extra_flag_values=extra_flag_values,
+ filter_rules=filter_rules,
+ git_commit=git_commit,
+ output_format=output_format,
+ verbosity=verbosity)
+
+ def test_to_flag_string(self):
+ options = self._create_options('vs7', 5, ['+foo', '-bar'], 'git',
+ {'a': 0, 'z': 1})
+ self.assertEquals('--a=0 --filter=+foo,-bar --git-commit=git '
+ '--output=vs7 --verbose=5 --z=1',
+ self._printer.to_flag_string(options))
+
+ # This is to check that --filter and --git-commit do not
+ # show up when not user-specified.
+ options = self._create_options()
+ self.assertEquals('--output=emacs --verbose=3',
+ self._printer.to_flag_string(options))
+
+
+class ArgumentParserTest(unittest.TestCase):
+
+ """Test the ArgumentParser class."""
+
+ def _parse(self):
+ """Return a default parse() function for testing."""
+ return self._create_parser().parse
+
+ def _create_defaults(self):
+ """Return a DefaultCommandOptionValues instance for testing."""
+ base_filter_rules = ["-", "+whitespace"]
+ return DefaultCommandOptionValues(output_format="vs7",
+ verbosity=3)
+
+ def _create_parser(self):
+ """Return an ArgumentParser instance for testing."""
+ def stderr_write(message):
+ # We do not want the usage string or style categories
+ # to print during unit tests, so print nothing.
+ return
+
+ default_options = self._create_defaults()
+
+ all_categories = ["build" ,"whitespace"]
+ return ArgumentParser(all_categories=all_categories,
+ base_filter_rules=[],
+ default_options=default_options,
+ stderr_write=stderr_write)
+
+ def test_parse_documentation(self):
+ parse = self._parse()
+
+ # FIXME: Test both the printing of the usage string and the
+ # filter categories help.
+
+ # Request the usage string.
+ self.assertRaises(SystemExit, parse, ['--help'])
+ # Request default filter rules and available style categories.
+ self.assertRaises(SystemExit, parse, ['--filter='])
+
+ def test_parse_bad_values(self):
+ parse = self._parse()
+
+ # Pass an unsupported argument.
+ self.assertRaises(SystemExit, parse, ['--bad'])
+
+ self.assertRaises(ValueError, parse, ['--verbose=bad'])
+ self.assertRaises(ValueError, parse, ['--verbose=0'])
+ self.assertRaises(ValueError, parse, ['--verbose=6'])
+ parse(['--verbose=1']) # works
+ parse(['--verbose=5']) # works
+
+ self.assertRaises(ValueError, parse, ['--output=bad'])
+ parse(['--output=vs7']) # works
+
+ # Pass a filter rule not beginning with + or -.
+ self.assertRaises(ValueError, parse, ['--filter=build'])
+ parse(['--filter=+build']) # works
+ # Pass files and git-commit at the same time.
+ self.assertRaises(SystemExit, parse, ['--git-commit=', 'file.txt'])
+ # Pass an extra flag already supported.
+ self.assertRaises(ValueError, parse, [], ['filter='])
+ parse([], ['extra=']) # works
+ # Pass an extra flag with typo.
+ self.assertRaises(SystemExit, parse, ['--extratypo='], ['extra='])
+ parse(['--extra='], ['extra=']) # works
+ self.assertRaises(ValueError, parse, [], ['extra=', 'extra='])
+
+
+ def test_parse_default_arguments(self):
+ parse = self._parse()
+
+ (files, options) = parse([])
+
+ self.assertEquals(files, [])
+
+ self.assertEquals(options.output_format, 'vs7')
+ self.assertEquals(options.verbosity, 3)
+ self.assertEquals(options.filter_rules, [])
+ self.assertEquals(options.git_commit, None)
+
+ def test_parse_explicit_arguments(self):
+ parse = self._parse()
+
+ # Pass non-default explicit values.
+ (files, options) = parse(['--output=emacs'])
+ self.assertEquals(options.output_format, 'emacs')
+ (files, options) = parse(['--verbose=4'])
+ self.assertEquals(options.verbosity, 4)
+ (files, options) = parse(['--git-commit=commit'])
+ self.assertEquals(options.git_commit, 'commit')
+
+ # Pass user_rules.
+ (files, options) = parse(['--filter=+build,-whitespace'])
+ self.assertEquals(options.filter_rules,
+ ["+build", "-whitespace"])
+
+ # Pass spurious white space in user rules.
+ (files, options) = parse(['--filter=+build, -whitespace'])
+ self.assertEquals(options.filter_rules,
+ ["+build", "-whitespace"])
+
+ # Pass extra flag values.
+ (files, options) = parse(['--extra'], ['extra'])
+ self.assertEquals(options.extra_flag_values, {'--extra': ''})
+ (files, options) = parse(['--extra='], ['extra='])
+ self.assertEquals(options.extra_flag_values, {'--extra': ''})
+ (files, options) = parse(['--extra=x'], ['extra='])
+ self.assertEquals(options.extra_flag_values, {'--extra': 'x'})
+
+ def test_parse_files(self):
+ parse = self._parse()
+
+ (files, options) = parse(['foo.cpp'])
+ self.assertEquals(files, ['foo.cpp'])
+
+ # Pass multiple files.
+ (files, options) = parse(['--output=emacs', 'foo.cpp', 'bar.cpp'])
+ self.assertEquals(files, ['foo.cpp', 'bar.cpp'])
+
+
+class CommandOptionValuesTest(unittest.TestCase):
+
+ """Tests CommandOptionValues class."""
+
+ def test_init(self):
+ """Test __init__ constructor."""
+ # Check default parameters.
+ options = ProcessorOptions()
+ self.assertEquals(options.extra_flag_values, {})
+ self.assertEquals(options.filter_rules, [])
+ self.assertEquals(options.git_commit, None)
+ self.assertEquals(options.output_format, "emacs")
+ self.assertEquals(options.verbosity, 1)
+
+ # Check argument validation.
+ self.assertRaises(ValueError, ProcessorOptions, output_format="bad")
+ ProcessorOptions(output_format="emacs") # No ValueError: works
+ ProcessorOptions(output_format="vs7") # works
+ self.assertRaises(ValueError, ProcessorOptions, verbosity=0)
+ self.assertRaises(ValueError, ProcessorOptions, verbosity=6)
+ ProcessorOptions(verbosity=1) # works
+ ProcessorOptions(verbosity=5) # works
+
+ # Check attributes.
+ options = ProcessorOptions(extra_flag_values={"extra_value" : 2},
+ filter_rules=["+"],
+ git_commit="commit",
+ output_format="vs7",
+ verbosity=3)
+ self.assertEquals(options.extra_flag_values, {"extra_value" : 2})
+ self.assertEquals(options.filter_rules, ["+"])
+ self.assertEquals(options.git_commit, "commit")
+ self.assertEquals(options.output_format, "vs7")
+ self.assertEquals(options.verbosity, 3)
+
+ def test_eq(self):
+ """Test __eq__ equality function."""
+ # == calls __eq__.
+ self.assertTrue(ProcessorOptions() == ProcessorOptions())
+
+ # Verify that a difference in any argument causes equality to fail.
+ options = ProcessorOptions(extra_flag_values={"extra_value" : 1},
+ filter_rules=["+"],
+ git_commit="commit",
+ output_format="vs7",
+ verbosity=1)
+ self.assertFalse(options == ProcessorOptions(extra_flag_values=
+ {"extra_value" : 2}))
+ self.assertFalse(options == ProcessorOptions(filter_rules=["-"]))
+ self.assertFalse(options == ProcessorOptions(git_commit="commit2"))
+ self.assertFalse(options == ProcessorOptions(output_format="emacs"))
+ self.assertFalse(options == ProcessorOptions(verbosity=2))
+
+ def test_ne(self):
+ """Test __ne__ inequality function."""
+ # != calls __ne__.
+ # By default, __ne__ always returns true on different objects.
+ # Thus, just check the distinguishing case to verify that the
+ # code defines __ne__.
+ self.assertFalse(ProcessorOptions() != ProcessorOptions())
+
diff --git a/WebKitTools/Scripts/webkitpy/style/unittests.py b/WebKitTools/Scripts/webkitpy/style/unittests.py
index f8e3f71..62615ab 100644
--- a/WebKitTools/Scripts/webkitpy/style/unittests.py
+++ b/WebKitTools/Scripts/webkitpy/style/unittests.py
@@ -38,6 +38,7 @@ import unittest
from checker_unittest import *
from error_handlers_unittest import *
from filter_unittest import *
+from optparser_unittest import *
from processors.common_unittest import *
from processors.cpp_unittest import *
from processors.text_unittest import *
--
WebKit Debian packaging
More information about the Pkg-webkit-commits
mailing list