Пример #1
0
 def test_ne(self):
     """Test __ne__ method."""
     # By default, __ne__ always returns true on different objects.
     # Thus, just check the distinguishing case to verify that the
     # code defines __ne__.
     #
     # Also, see the notes at the top of this module about testing
     # __eq__() and __ne__().
     self.assertFalse(FilterConfiguration().__ne__(FilterConfiguration()))
Пример #2
0
    def test_path_rules_specifier(self):
        all_categories = style_categories()
        for (sub_paths, path_rules) in PATH_RULES_SPECIFIER:
            self.assertTrue(isinstance(path_rules, tuple), "Checking: " + str(path_rules))
            validate_filter_rules(path_rules, self._all_categories())

        # Try using the path specifier (as an "end-to-end" check).
        config = FilterConfiguration(path_specific=PATH_RULES_SPECIFIER)
        self.assertTrue(config.should_check("xxx_any_category", "xxx_non_matching_path"))
        self.assertTrue(config.should_check("xxx_any_category", "WebKitTools/WebKitAPITest/"))
        self.assertFalse(config.should_check("build/include", "WebKitTools/WebKitAPITest/"))
        self.assertFalse(config.should_check("readability/naming", "WebKit/qt/tests/qwebelement/tst_qwebelement.cpp"))
    def test_default_arguments(self):
        # Test that the attributes are getting set correctly to the defaults.
        config = FilterConfiguration()

        self.assertEqual([], config._base_rules)
        self.assertEqual([], config._path_specific)
        self.assertEqual([], config._user_rules)
Пример #4
0
    def __init__(self,
                 extra_flag_values=None,
                 filter_configuration=None,
                 git_commit=None,
                 max_reports_per_category=None,
                 output_format="emacs",
                 verbosity=1):
        if extra_flag_values is None:
            extra_flag_values = {}
        if filter_configuration is None:
            filter_configuration = FilterConfiguration()
        if max_reports_per_category is None:
            max_reports_per_category = {}

        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_configuration = filter_configuration
        self.git_commit = git_commit
        self.max_reports_per_category = max_reports_per_category
        self.output_format = output_format
        self.verbosity = verbosity
    def test_path_rules_specifier(self):
        all_categories = self._all_categories()
        for (sub_paths, path_rules) in PATH_RULES_SPECIFIER:
            validate_filter_rules(path_rules, self._all_categories())

        config = FilterConfiguration(path_specific=PATH_RULES_SPECIFIER)

        def assertCheck(path, category):
            """Assert that the given category should be checked."""
            message = ('Should check category "%s" for path "%s".'
                       % (category, path))
            self.assertTrue(config.should_check(category, path))

        def assertNoCheck(path, category):
            """Assert that the given category should not be checked."""
            message = ('Should not check category "%s" for path "%s".'
                       % (category, path))
            self.assertFalse(config.should_check(category, path), message)

        assertCheck("random_path.cpp",
                    "build/include")
        assertCheck("random_path.cpp",
                    "readability/naming")
        assertNoCheck("Source/core/css/CSSParser-in.cpp",
                      "readability/naming")

        # Third-party Python code: webkitpy/thirdparty
        path = "Tools/Scripts/webkitpy/thirdparty/mock.py"
        assertNoCheck(path, "build/include")
        assertNoCheck(path, "pep8/E401")  # A random pep8 category.
        assertCheck(path, "pep8/W191")
        assertCheck(path, "pep8/W291")
        assertCheck(path, "whitespace/carriage_return")
Пример #6
0
    def setUp(self):
        LoggingTestCase.setUp(self)
        # We can pass an error-message swallower here because error message
        # output is tested instead in the end-to-end test case above.
        configuration = StyleProcessorConfiguration(
                            filter_configuration=FilterConfiguration(),
                            max_reports_per_category={"whitespace/newline": 1},
                            min_confidence=3,
                            output_format="vs7",
                            stderr_write=self._swallow_stderr_message)

        mock_carriage_checker_class = self._create_carriage_checker_class()
        mock_dispatcher = self.MockDispatcher()
        # We do not need to use a real incrementer here because error-count
        # incrementing is tested instead in the end-to-end test case above.
        mock_increment_error_count = self._do_nothing

        processor = StyleProcessor(configuration=configuration,
                        mock_carriage_checker_class=mock_carriage_checker_class,
                        mock_dispatcher=mock_dispatcher,
                        mock_increment_error_count=mock_increment_error_count)

        self._configuration = configuration
        self._mock_dispatcher = mock_dispatcher
        self._processor = processor
Пример #7
0
    def test_path_rules_specifier(self):
        all_categories = self._all_categories()
        for (sub_paths, path_rules) in PATH_RULES_SPECIFIER:
            validate_filter_rules(path_rules, self._all_categories())

        config = FilterConfiguration(path_specific=PATH_RULES_SPECIFIER)

        def assertCheck(path, category):
            """Assert that the given category should be checked."""
            message = ('Should check category "%s" for path "%s".'
                       % (category, path))
            self.assertTrue(config.should_check(category, path))

        def assertNoCheck(path, category):
            """Assert that the given category should not be checked."""
            message = ('Should not check category "%s" for path "%s".'
                       % (category, path))
            self.assertFalse(config.should_check(category, path), message)

        assertCheck("random_path.cpp",
                    "build/include")
        assertNoCheck(os.path.join('Tools', 'DumpRenderTree', 'TestNetscapePlugIn', 'main.cpp'),
                      "build/include")
        assertNoCheck(os.path.join('Tools', 'DumpRenderTree', 'TestNetscapePlugIn', 'main.cpp'),
                      "readability/naming")
        assertCheck(os.path.join('Tools', 'TestWebKitAPI', 'Tests', 'WTF', 'RefLogger.cpp'),
                      "build/include")
        assertNoCheck(os.path.join('Tools', 'TestWebKitAPI', 'Tests', 'mac', 'WillSendSubmitEvent.mm'),
                      "readability/naming")
        assertCheck("random_path.cpp",
                    "readability/naming")
        assertNoCheck(os.path.join('Source', 'WebKit2', 'UIProcess', 'API', 'efl', 'ewk_view.h'),
                      "readability/naming")
        assertNoCheck(os.path.join('Source', 'WebCore', 'css', 'CSSParser.cpp'),
                      "readability/naming")

        assertNoCheck(os.path.join('Source', 'WebCore', 'ForwardingHeaders', 'debugger', 'Debugger.h'),
                      "build/header_guard")

        assertNoCheck(os.path.join('Source', 'WebCore', 'platform', 'graphics', 'gstreamer', 'VideoSinkGStreamer.cpp'),
                      "readability/naming")

        # Third-party Python code: webkitpy/thirdparty
        path = os.path.join('Tools', 'Scripts', 'webkitpy', 'thirdparty', 'mock.py')
        assertNoCheck(path, "build/include")
        assertNoCheck(path, "pep8/E401")  # A random pep8 category.
        assertCheck(path, "pep8/W191")
        assertCheck(path, "pep8/W291")
        assertCheck(path, "whitespace/carriage_return")

        # Test if the exception for GDBInterface.cpp is in place.
        assertNoCheck(os.path.join('Source', 'JavaScriptCore', 'jit', 'GDBInterface.cpp'),
                      "readability/naming")

        # Javascript keywords.
        assertCheck(os.path.join('Source', 'JavaScriptCore', 'parser', 'Keywords.table'), "whitespace/carriage_return")
    def test_eq(self):
        """Test __eq__ method."""
        # See the notes at the top of this module about testing
        # __eq__() and __ne__().
        self.assertTrue(FilterConfiguration().__eq__(FilterConfiguration()))

        # Verify that a difference in any argument causes equality to fail.
        config = FilterConfiguration()

        # These parameter values are different from the defaults.
        base_rules = ["-"]
        path_specific = [(["path"], ["+a"])]
        user_rules = ["+"]

        self.assertFalse(config.__eq__(FilterConfiguration(
                                           base_rules=base_rules)))
        self.assertFalse(config.__eq__(FilterConfiguration(
                                           path_specific=path_specific)))
        self.assertFalse(config.__eq__(FilterConfiguration(
                                           user_rules=user_rules)))
Пример #9
0
    def test_init(self):
        """Test __init__ constructor."""
        configuration = StyleProcessorConfiguration(
            filter_configuration=FilterConfiguration(),
            max_reports_per_category={},
            min_confidence=3,
            output_format="vs7",
            commit_queue=False)
        processor = StyleProcessor(configuration)

        self.assertEqual(processor.error_count, 0)
    def _style_checker_configuration(self):
        """Return a StyleProcessorConfiguration instance for testing."""
        base_rules = ["-whitespace", "+whitespace/tab"]
        filter_configuration = FilterConfiguration(base_rules=base_rules)

        return StyleProcessorConfiguration(
            filter_configuration=filter_configuration,
            max_reports_per_category={"whitespace/tab": 2},
            min_confidence=3,
            output_format="vs7",
            commit_queue=False)
Пример #11
0
    def test_path_rules_specifier(self):
        all_categories = self._all_categories()
        for (sub_paths, path_rules) in PATH_RULES_SPECIFIER:
            validate_filter_rules(path_rules, self._all_categories())

        config = FilterConfiguration(path_specific=PATH_RULES_SPECIFIER)

        def assertCheck(path, category):
            """Assert that the given category should be checked."""
            message = ('Should check category "%s" for path "%s".'
                       % (category, path))
            self.assertTrue(config.should_check(category, path))

        def assertNoCheck(path, category):
            """Assert that the given category should not be checked."""
            message = ('Should not check category "%s" for path "%s".'
                       % (category, path))
            self.assertFalse(config.should_check(category, path), message)

        assertCheck("random_path.cpp",
                    "build/include")
        assertNoCheck("Tools/WebKitAPITest/main.cpp",
                      "build/include")
        assertCheck("random_path.cpp",
                    "readability/naming")
        assertNoCheck("Source/WebKit/gtk/webkit/webkit.h",
                      "readability/naming")
        assertNoCheck("Tools/DumpRenderTree/gtk/DumpRenderTree.cpp",
                      "readability/null")
        assertNoCheck("Source/WebKit/efl/ewk/ewk_view.h",
                      "readability/naming")
        assertNoCheck("Source/WebCore/css/CSSParser.cpp",
                      "readability/naming")

        assertNoCheck("Source/WebCore/ForwardingHeaders/debugger/Debugger.h",
                      "build/header_guard")

        assertNoCheck("Source/WebCore/platform/graphics/gstreamer/VideoSinkGStreamer.cpp",
                      "readability/naming")

        # Third-party Python code: webkitpy/thirdparty
        path = "Tools/Scripts/webkitpy/thirdparty/mock.py"
        assertNoCheck(path, "build/include")
        assertNoCheck(path, "pep8/E401")  # A random pep8 category.
        assertCheck(path, "pep8/W191")
        assertCheck(path, "pep8/W291")
        assertCheck(path, "whitespace/carriage_return")

        # Test if the exception for GDBInterface.cpp is in place.
        assertNoCheck("Source/JavaScriptCore/jit/GDBInterface.cpp",
                      "readability/naming")

        # Javascript keywords.
        assertCheck("Source/JavaScriptCore/parser/Keywords.table", "whitespace/carriage_return")
Пример #12
0
    def _style_checker_configuration(self, output_format="vs7"):
        """Return a StyleProcessorConfiguration instance for testing."""
        base_rules = ["-whitespace", "+whitespace/tab"]
        filter_configuration = FilterConfiguration(base_rules=base_rules)

        return StyleProcessorConfiguration(
                   filter_configuration=filter_configuration,
                   max_reports_per_category={"whitespace/newline": 1},
                   min_confidence=3,
                   output_format=output_format,
                   stderr_write=self._mock_stderr_write)
Пример #13
0
    def test_eq(self):
        """Test __eq__ method."""
        # See the notes at the top of this module about testing
        # __eq__() and __ne__().
        self.assertTrue(FilterConfiguration().__eq__(FilterConfiguration()))

        # Verify that a difference in any argument causes equality to fail.
        config = FilterConfiguration()

        # These parameter values are different from the defaults.
        base_rules = ["-"]
        path_specific = [(["path"], ["+a"])]
        user_rules = ["+"]

        self.assertFalse(config.__eq__(FilterConfiguration(
                                           base_rules=base_rules)))
        self.assertFalse(config.__eq__(FilterConfiguration(
                                           path_specific=path_specific)))
        self.assertFalse(config.__eq__(FilterConfiguration(
                                           user_rules=user_rules)))
Пример #14
0
    def test_init(self):
        """Test __init__ constructor."""
        configuration = StyleProcessorConfiguration(
                            filter_configuration=FilterConfiguration(),
                            max_reports_per_category={},
                            min_confidence=3,
                            output_format="vs7",
                            stderr_write=self._mock_stderr_write)
        processor = StyleProcessor(configuration)

        self.assertEquals(processor.error_count, 0)
        self.assertEquals(self._messages, [])
Пример #15
0
    def test_path_rules_specifier(self):
        all_categories = self._all_categories()
        for (sub_paths, path_rules) in PATH_RULES_SPECIFIER:
            validate_filter_rules(path_rules, self._all_categories())

        config = FilterConfiguration(path_specific=PATH_RULES_SPECIFIER)

        def assertCheck(path, category):
            """Assert that the given category should be checked."""
            message = ('Should check category "%s" for path "%s".'
                       % (category, path))
            self.assertTrue(config.should_check(category, path))

        def assertNoCheck(path, category):
            """Assert that the given category should not be checked."""
            message = ('Should not check category "%s" for path "%s".'
                       % (category, path))
            self.assertFalse(config.should_check(category, path), message)

        assertCheck("random_path.cpp",
                    "build/include")
        assertNoCheck("WebKitTools/WebKitAPITest/main.cpp",
                      "build/include")
        assertNoCheck("WebKit/qt/QGVLauncher/main.cpp",
                      "build/include")
        assertNoCheck("WebKit/qt/QGVLauncher/main.cpp",
                      "readability/streams")

        assertCheck("random_path.cpp",
                    "readability/naming")
        assertNoCheck("WebKit/gtk/webkit/webkit.h",
                      "readability/naming")
        assertNoCheck("WebKitTools/DumpRenderTree/gtk/DumpRenderTree.cpp",
                      "readability/null")
        assertNoCheck("WebKit/efl/ewk/ewk_view.h",
                      "readability/naming")
        assertNoCheck("WebCore/css/CSSParser.cpp",
                      "readability/naming")
        assertNoCheck("WebKit/qt/tests/qwebelement/tst_qwebelement.cpp",
                      "readability/naming")
        assertNoCheck(
            "JavaScriptCore/qt/tests/qscriptengine/tst_qscriptengine.cpp",
            "readability/naming")
        assertNoCheck("WebCore/ForwardingHeaders/debugger/Debugger.h",
                      "build/header_guard")

        # Third-party Python code: webkitpy/thirdparty
        path = "WebKitTools/Scripts/webkitpy/thirdparty/mock.py"
        assertNoCheck(path, "build/include")
        assertNoCheck(path, "pep8/E401")  # A random pep8 category.
        assertCheck(path, "pep8/W191")
        assertCheck(path, "pep8/W291")
        assertCheck(path, "whitespace/carriage_return")
Пример #16
0
 def _create_options(self,
                     output_format='emacs',
                     verbosity=3,
                     user_rules=[],
                     git_commit=None,
                     extra_flag_values={}):
     filter_configuration = FilterConfiguration(user_rules=user_rules)
     return style.ProcessorOptions(
         extra_flag_values=extra_flag_values,
         filter_configuration=filter_configuration,
         git_commit=git_commit,
         output_format=output_format,
         verbosity=verbosity)
Пример #17
0
    def test_is_reportable(self):
        """Test is_reportable()."""
        filter_configuration = FilterConfiguration(base_rules=["-xyz"])
        options = ProcessorOptions(filter_configuration=filter_configuration,
                                   verbosity=3)

        # Test verbosity
        self.assertTrue(options.is_reportable("abc", 3, "foo.h"))
        self.assertFalse(options.is_reportable("abc", 2, "foo.h"))

        # Test filter
        self.assertTrue(options.is_reportable("xy", 3, "foo.h"))
        self.assertFalse(options.is_reportable("xyz", 3, "foo.h"))
Пример #18
0
    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.
        filter_configuration = FilterConfiguration(base_rules=["+"])
        options = ProcessorOptions(extra_flag_values={"extra_value": 1},
                                   filter_configuration=filter_configuration,
                                   git_commit="commit",
                                   max_reports_per_category={"category": 3},
                                   output_format="vs7",
                                   verbosity=1)
        self.assertFalse(options == ProcessorOptions(
            extra_flag_values={"extra_value": 2}))
        new_config = FilterConfiguration(base_rules=["-"])
        self.assertFalse(options == ProcessorOptions(
            filter_configuration=new_config))
        self.assertFalse(options == ProcessorOptions(git_commit="commit2"))
        self.assertFalse(options == ProcessorOptions(
            max_reports_per_category={"category": 2}))
        self.assertFalse(options == ProcessorOptions(output_format="emacs"))
        self.assertFalse(options == ProcessorOptions(verbosity=2))
Пример #19
0
    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_configuration,
            FilterConfiguration(base_rules=["-", "+whitespace"],
                                path_specific=PATH_RULES_SPECIFIER))
        self.assertEquals(options.git_commit, None)
Пример #20
0
    def test_process(self):
        configuration = StyleProcessorConfiguration(
                            filter_configuration=FilterConfiguration(),
                            max_reports_per_category={},
                            min_confidence=3,
                            output_format="vs7",
                            stderr_write=self._mock_stderr_write)
        processor = StyleProcessor(configuration)

        processor.process(lines=['line1', 'Line with tab:\t'],
                          file_path='foo.txt')
        self.assertEquals(processor.error_count, 1)
        expected_messages = ['foo.txt(2):  Line contains tab character.  '
                             '[whitespace/tab] [5]\n']
        self.assertEquals(self._messages, expected_messages)
Пример #21
0
def check_webkit_style_configuration(options):
    """Return a StyleProcessorConfiguration instance for check-webkit-style.

    Args:
      options: A CommandOptionValues instance.

    """
    filter_configuration = FilterConfiguration(
                               base_rules=_BASE_FILTER_RULES,
                               user_rules=options.filter_rules)

    return StyleProcessorConfiguration(filter_configuration=filter_configuration,
               max_reports_per_category=_MAX_REPORTS_PER_CATEGORY,
               min_confidence=options.min_confidence,
               output_format=options.output_format,
               stderr_write=sys.stderr.write)
Пример #22
0
def check_webkit_style_configuration(options):
    """Return a StyleProcessorConfiguration instance for check-webkit-style.

    Args:
      options: A CommandOptionValues instance.

    """
    filter_configuration = FilterConfiguration(
                               base_rules=_BASE_FILTER_RULES,
                               path_specific=_PATH_RULES_SPECIFIER,
                               user_rules=options.filter_rules)

    return StyleProcessorConfiguration(filter_configuration=filter_configuration,
               max_reports_per_category=_MAX_REPORTS_PER_CATEGORY,
               min_confidence=options.min_confidence,
               output_format=options.output_format,
               commit_queue=options.commit_queue)
Пример #23
0
    def test_path_rules_specifier(self):
        all_categories = style_categories()
        for (sub_paths, path_rules) in PATH_RULES_SPECIFIER:
            self.assertTrue(isinstance(path_rules, tuple),
                            "Checking: " + str(path_rules))
            validate_filter_rules(path_rules, self._all_categories())

        # Try using the path specifier (as an "end-to-end" check).
        config = FilterConfiguration(path_specific=PATH_RULES_SPECIFIER)
        self.assertTrue(
            config.should_check("xxx_any_category", "xxx_non_matching_path"))
        self.assertTrue(
            config.should_check("xxx_any_category",
                                "WebKitTools/WebKitAPITest/"))
        self.assertFalse(
            config.should_check("build/include", "WebKitTools/WebKitAPITest/"))
        self.assertFalse(
            config.should_check(
                "readability/naming",
                "WebKit/qt/tests/qwebelement/tst_qwebelement.cpp"))
Пример #24
0
    def test_path_rules_specifier(self):
        all_categories = self._all_categories()
        for (sub_paths, path_rules) in PATH_RULES_SPECIFIER:
            validate_filter_rules(path_rules, self._all_categories())

        config = FilterConfiguration(path_specific=PATH_RULES_SPECIFIER)

        def assertCheck(path, category):
            """Assert that the given category should be checked."""
            message = ('Should check category "%s" for path "%s".'
                       % (category, path))
            self.assertTrue(config.should_check(category, path))

        def assertNoCheck(path, category):
            """Assert that the given category should not be checked."""
            message = ('Should not check category "%s" for path "%s".'
                       % (category, path))
            self.assertFalse(config.should_check(category, path), message)

        assertCheck("random_path.cpp",
                    "build/include")
        assertNoCheck("Tools/WebKitAPITest/main.cpp",
                      "build/include")
        assertCheck("random_path.cpp",
                    "readability/naming")
        assertNoCheck("Source/WebKit/gtk/webkit/webkit.h",
                      "readability/naming")
        assertNoCheck("Tools/DumpRenderTree/gtk/DumpRenderTree.cpp",
                      "readability/null")
        assertNoCheck("Source/WebKit/efl/ewk/ewk_view.h",
                      "readability/naming")
        assertNoCheck("Source/WebCore/css/CSSParser.cpp",
                      "readability/naming")

        # Test if Qt exceptions are indeed working
        assertCheck("Source/JavaScriptCore/qt/api/qscriptengine.cpp",
                    "readability/braces")
        assertCheck("Source/WebKit/qt/Api/qwebpage.cpp",
                    "readability/braces")
        assertCheck("Source/WebKit/qt/tests/qwebelement/tst_qwebelement.cpp",
                    "readability/braces")
        assertCheck("Source/WebKit/qt/declarative/platformplugin/WebPlugin.cpp",
                    "readability/braces")
        assertCheck("Source/WebKit/qt/examples/platformplugin/WebPlugin.cpp",
                    "readability/braces")
        assertCheck("Source/WebKit/qt/symbian/platformplugin/WebPlugin.cpp",
                    "readability/braces")
        assertNoCheck("Source/JavaScriptCore/qt/api/qscriptengine.cpp",
                      "readability/naming")
        assertNoCheck("Source/JavaScriptCore/qt/benchmarks"
                      "/qscriptengine/tst_qscriptengine.cpp",
                      "readability/naming")
        assertNoCheck("Source/WebKit/qt/Api/qwebpage.cpp",
                      "readability/naming")
        assertNoCheck("Source/WebKit/qt/tests/qwebelement/tst_qwebelement.cpp",
                      "readability/naming")
        assertNoCheck("Source/WebKit/qt/declarative/platformplugin/WebPlugin.cpp",
                      "readability/naming")
        assertNoCheck("Source/WebKit/qt/examples/platformplugin/WebPlugin.cpp",
                      "readability/naming")
        assertNoCheck("Source/WebKit/qt/symbian/platformplugin/WebPlugin.cpp",
                      "build/header_guard")

        assertNoCheck("Tools/MiniBrowser/qt/UrlLoader.cpp",
                    "build/include")

        assertNoCheck("Source/WebKit2/UIProcess/API/qt",
                    "readability/parameter_name")

        assertNoCheck("Source/WebCore/ForwardingHeaders/debugger/Debugger.h",
                      "build/header_guard")

        # Third-party Python code: webkitpy/thirdparty
        path = "Tools/Scripts/webkitpy/thirdparty/mock.py"
        assertNoCheck(path, "build/include")
        assertNoCheck(path, "pep8/E401")  # A random pep8 category.
        assertCheck(path, "pep8/W191")
        assertCheck(path, "pep8/W291")
        assertCheck(path, "whitespace/carriage_return")
Пример #25
0
    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 ProcessorOptions 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 ProcessorOptions instance.

        """
        if extra_flags is None:
            extra_flags = []

        output_format = self.defaults.output_format
        verbosity = self.defaults.verbosity
        base_rules = self.defaults.base_filter_rules

        # The flags already supported by the ProcessorOptions 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
        user_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()
                # Prepend the defaults.
                user_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 = style_categories()
        validate_filter_rules(user_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)

        filter_configuration = FilterConfiguration(
            base_rules=base_rules,
            path_specific=_PATH_RULES_SPECIFIER,
            user_rules=user_rules)

        options = ProcessorOptions(
            extra_flag_values=extra_flag_values,
            filter_configuration=filter_configuration,
            git_commit=git_commit,
            max_reports_per_category=MAX_REPORTS_PER_CATEGORY,
            output_format=output_format,
            verbosity=verbosity)

        return (filenames, options)
Пример #26
0
 def _config(self, base_rules, path_specific, user_rules):
     """Return a FilterConfiguration instance."""
     return FilterConfiguration(base_rules=base_rules,
                                path_specific=path_specific,
                                user_rules=user_rules)