Beispiel #1
0
    def test_collect_filters_arg_list_custom_parser(self):
        collected = collect_filters(None, [], default_arg_parser())
        self.assertEqual(collected, [])

        collected = collect_filters(None, ['--filter-by', 'sample', 'arg'],
                                    default_arg_parser())
        self.assertEqual(collected, [['sample', 'arg']])
Beispiel #2
0
    def test_collect_filters_arg_list_custom_parser(self):
        collected = collect_filters(None, [], default_arg_parser())
        self.assertEqual(collected, {})

        collected = collect_filters(None,
                                    ['--filter-by', 'sample', 'arg'],
                                    default_arg_parser())
        self.assertEqual(collected, {'sample': ('arg',)})
Beispiel #3
0
    def test_argcomplete_missing(self):
        if coalib.parsing.DefaultArgParser.argcomplete is not None:
            coalib.parsing.DefaultArgParser.argcomplete = None
        real_importer = __import__

        def import_if_not_argcomplete(arg, *args, **kw):
            if arg == 'argcomplete':
                raise ImportError('import missing: %s' % arg)
            else:
                return real_importer(arg, *args, **kw)

        mock = Mock(side_effect=import_if_not_argcomplete)
        with patch('builtins.__import__', new=mock):
            default_arg_parser()
        self.assertFalse(coalib.parsing.DefaultArgParser.argcomplete)
    def test_argcomplete_missing(self):
        if coalib.parsing.DefaultArgParser.argcomplete is not None:
            coalib.parsing.DefaultArgParser.argcomplete = None
        real_importer = __import__

        def import_if_not_argcomplete(arg, *args, **kw):
            if arg == 'argcomplete':
                raise ImportError('import missing: %s' % arg)
            else:
                return real_importer(arg, *args, **kw)

        mock = Mock(side_effect=import_if_not_argcomplete)
        with patch('builtins.__import__', new=mock):
            default_arg_parser()
        self.assertFalse(coalib.parsing.DefaultArgParser.argcomplete)
Beispiel #5
0
def main():
    configure_logging()

    try:
        console_printer = ConsolePrinter()
        log_printer = LogPrinter(console_printer)
        # Note: We parse the args here once to check whether to show bears or
        # not.
        args = default_arg_parser().parse_args()

        # Defer imports so if e.g. --help is called they won't be run
        from coalib.coala_modes import (
            mode_format, mode_json, mode_non_interactive, mode_normal)
        from coalib.output.ConsoleInteraction import (
            show_bears, show_language_bears_capabilities)

        console_printer = ConsolePrinter(print_colored=not args.no_color)
        configure_logging(not args.no_color)

        if args.json:  # needs to be checked in order to display bears in json
            return mode_json(args)

        if args.show_bears:
            from coalib.settings.ConfigurationGathering import (
                get_filtered_bears)

            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)

            show_bears(local_bears,
                       global_bears,
                       args.show_description or args.show_details,
                       args.show_details,
                       console_printer)

            return 0
        elif args.show_capabilities:
            from coalib.collecting.Collectors import (
                filter_capabilities_by_languages)
            from coalib.settings.ConfigurationGathering import (
                get_filtered_bears)

            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)
            capabilities = filter_capabilities_by_languages(
                local_bears, args.show_capabilities)
            show_language_bears_capabilities(capabilities, console_printer)

            return 0

    except BaseException as exception:  # pylint: disable=broad-except
        return get_exitcode(exception, log_printer)

    if args.format:
        return mode_format()

    if args.non_interactive:
        return mode_non_interactive(console_printer, args)

    return mode_normal(console_printer, log_printer)
Beispiel #6
0
def main():
    # Note: We parse the args here once to check whether to show bears or not.
    arg_parser = default_arg_parser()
    args = arg_parser.parse_args()

    console_printer = ConsolePrinter()
    if args.show_bears or args.show_all_bears:
        log_printer = LogPrinter(console_printer)
        sections, _ = load_configuration(arg_list=None, log_printer=log_printer)
        if args.show_all_bears:
            local_bears, global_bears = collect_all_bears_from_sections(
                sections, log_printer)
        else:
            # We ignore missing settings as it's not important.
            local_bears, global_bears = fill_settings(
                sections,
                acquire_settings=lambda *args, **kwargs: {},
                log_printer=log_printer)
        show_bears(local_bears, global_bears, args.show_all_bears,
                   console_printer)
        return 0

    partial_print_sec_beg = functools.partial(
        print_section_beginning,
        console_printer)
    results, exitcode, _ = run_coala(
        print_results=print_results,
        acquire_settings=acquire_settings,
        print_section_beginning=partial_print_sec_beg,
        nothing_done=nothing_done)

    return exitcode
Beispiel #7
0
def main():
    try:
        console_printer = ConsolePrinter()
        log_printer = LogPrinter(console_printer)
        # Note: We parse the args here once to check whether to show bears or
        # not.
        args = default_arg_parser().parse_args()

        if args.show_bears:
            sections, _ = load_configuration(arg_list=None,
                                             log_printer=log_printer)
            local_bears, global_bears = collect_all_bears_from_sections(
                sections, log_printer)
            if args.filter_by_language:
                local_bears = filter_section_bears_by_languages(
                    local_bears, args.filter_by_language)
                global_bears = filter_section_bears_by_languages(
                    global_bears, args.filter_by_language)

            show_bears(local_bears, global_bears, args.show_description
                       or args.show_details, args.show_details,
                       console_printer)
            return 0
    except BaseException as exception:  # pylint: disable=broad-except
        return get_exitcode(exception, log_printer)

    partial_print_sec_beg = functools.partial(print_section_beginning,
                                              console_printer)
    results, exitcode, _ = run_coala(
        print_results=print_results,
        acquire_settings=acquire_settings,
        print_section_beginning=partial_print_sec_beg,
        nothing_done=nothing_done)

    return exitcode
Beispiel #8
0
def main():
    # Note: We parse the args here once to find the log printer to use.
    #       Also, commands like -h (help) and -v (version) are executed here.
    #       The args are again parsed later to find the settings and configs
    #       to use during analysis.
    arg_parser = default_arg_parser()
    args = arg_parser.parse_args()

    log_printer = None if args.text_logs else ListLogPrinter()
    results, exitcode, _ = run_coala(log_printer=log_printer, autoapply=False)

    retval = {"results": results}
    if not args.text_logs:
        retval["logs"] = log_printer.logs
    JSONEncoder = create_json_encoder(use_relpath=args.relpath)
    if args.output:
        filename = str(args.output[0])
        with open(filename, 'w+') as fp:
            json.dump(retval,
                      fp,
                      cls=JSONEncoder,
                      sort_keys=True,
                      indent=2,
                      separators=(',', ': '))
    else:
        print(
            json.dumps(retval,
                       cls=JSONEncoder,
                       sort_keys=True,
                       indent=2,
                       separators=(',', ': ')))

    return exitcode
Beispiel #9
0
def main():
    try:
        console_printer = ConsolePrinter()
        log_printer = LogPrinter(console_printer)
        # Note: We parse the args here once to check whether to show bears or
        # not.
        args = default_arg_parser().parse_args()

        if args.show_bears:
            local_bears, global_bears = get_filtered_bears(args.filter_by_language, log_printer)

            show_bears(
                local_bears,
                global_bears,
                args.show_description or args.show_details,
                args.show_details,
                console_printer,
            )
            return 0
    except BaseException as exception:  # pylint: disable=broad-except
        return get_exitcode(exception, log_printer)

    partial_print_sec_beg = functools.partial(print_section_beginning, console_printer)
    results, exitcode, _ = run_coala(
        print_results=print_results,
        acquire_settings=acquire_settings,
        print_section_beginning=partial_print_sec_beg,
        nothing_done=nothing_done,
    )

    return exitcode
    def test_show_bears_with_json(self):
        args = default_arg_parser().parse_args(['--json'])
        with retrieve_stdout() as stdout:
            show_bears({}, {}, True, True, self.console_printer, args)
            self.assertEqual('{\n  "bears": []\n}\n', stdout.getvalue())

        self.logs.check(*self.deprecation_messages)
Beispiel #11
0
def main():
    # Note: We parse the args here once to find the log printer to use.
    #       Also, commands like -h (help) and -v (version) are executed here.
    #       The args are again parsed later to find the settings and configs
    #       to use during analysis.
    arg_parser = default_arg_parser()
    try:
        args = arg_parser.parse_args()
    except BaseException as exception:  # Ignore PyLintBear
        return get_exitcode(exception)

    log_printer = None if args.text_logs else ListLogPrinter()
    results, exitcode = run_coala(log_printer=log_printer, autoapply=False)

    retval = {"results": results}
    if not args.text_logs:
        retval["logs"] = log_printer.logs

    print(
        json.dumps(retval,
                   cls=JSONEncoder,
                   sort_keys=True,
                   indent=2,
                   separators=(',', ': ')))

    return exitcode
    def test_show_bears_with_json(self):
        args = default_arg_parser().parse_args(['--json'])
        with retrieve_stdout() as stdout:
            show_bears({}, {}, True, True, self.console_printer, args)
            self.assertEqual('{\n  "bears": []\n}\n', stdout.getvalue())

        self.logs.check(*self.deprecation_messages)
Beispiel #13
0
def main():
    # Note: We parse the args here once to find the log printer to use.
    #       Also, commands like -h (help) and -v (version) are executed here.
    #       The args are again parsed later to find the settings and configs
    #       to use during analysis.
    arg_parser = default_arg_parser()
    args = arg_parser.parse_args()

    log_printer = None if args.text_logs else ListLogPrinter()
    results, exitcode = run_coala(log_printer=log_printer, autoapply=False)

    retval = {"results": results}
    if not args.text_logs:
        retval["logs"] = log_printer.logs
    JSONEncoder = create_json_encoder(use_relpath=args.relpath)
    if args.output:
        filename = str(args.output)
        with open(filename, 'w+') as fp:
            json.dump(retval, fp,
                      cls=JSONEncoder,
                      sort_keys=True,
                      indent=2,
                      separators=(',', ': '))
    else:
        print(json.dumps(retval,
                         cls=JSONEncoder,
                         sort_keys=True,
                         indent=2,
                         separators=(',', ': ')))

    return exitcode
Beispiel #14
0
def main():
    # Note: We parse the args here once to find the log printer to use.
    #       Also, commands like -h (help) and -v (version) are executed here.
    #       The args are again parsed later to find the settings and configs
    #       to use during analysis.
    arg_parser = default_arg_parser()
    try:
        args = arg_parser.parse_args()
    except BaseException as exception:  # Ignore PyLintBear
        return get_exitcode(exception)

    log_printer = None if args.text_logs else ListLogPrinter()
    results, exitcode = run_coala(log_printer=log_printer, autoapply=False)

    retval = {"results": results}
    if not args.text_logs:
        retval["logs"] = log_printer.logs

    print(json.dumps(retval,
                     cls=JSONEncoder,
                     sort_keys=True,
                     indent=2,
                     separators=(',', ': ')))

    return exitcode
Beispiel #15
0
def main():
    configure_logging()

    try:
        console_printer = ConsolePrinter()
        log_printer = LogPrinter(console_printer)
        # Note: We parse the args here once to check whether to show bears or
        # not.
        args = default_arg_parser().parse_args()

        # Defer imports so if e.g. --help is called they won't be run
        from coalib.coala_modes import (mode_format, mode_json,
                                        mode_non_interactive, mode_normal)
        from coalib.output.ConsoleInteraction import (
            show_bears, show_language_bears_capabilities)

        console_printer = ConsolePrinter(print_colored=not args.no_color)
        configure_logging(not args.no_color)

        if args.json:  # needs to be checked in order to display bears in json
            return mode_json(args)

        if args.show_bears:
            from coalib.settings.ConfigurationGathering import (
                get_filtered_bears)

            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)

            show_bears(local_bears, global_bears, args.show_description
                       or args.show_details, args.show_details,
                       console_printer)

            return 0
        elif args.show_capabilities:
            from coalib.collecting.Collectors import (
                filter_capabilities_by_languages)
            from coalib.settings.ConfigurationGathering import (
                get_filtered_bears)

            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)
            capabilities = filter_capabilities_by_languages(
                local_bears, args.show_capabilities)
            show_language_bears_capabilities(capabilities, console_printer)

            return 0

    except BaseException as exception:  # pylint: disable=broad-except
        return get_exitcode(exception, log_printer)

    if args.format:
        return mode_format()

    if args.non_interactive:
        return mode_non_interactive(console_printer, args)

    return mode_normal(console_printer, log_printer)
Beispiel #16
0
def parse_cli(arg_list=None,
              origin=os.getcwd(),
              arg_parser=None,
              key_value_delimiters=('=', ':'),
              comment_seperators=(),
              key_delimiters=(',',),
              section_override_delimiters=(".",)):
    """
    Parses the CLI arguments and creates sections out of it.

    :param arg_list:                    The CLI argument list.
    :param origin:                      Directory used to interpret relative
                                        paths given as argument.
    :param arg_parser:                  Instance of ArgParser that is used to
                                        parse none-setting arguments.
    :param key_value_delimiters:        Delimiters to separate key and value
                                        in setting arguments.
    :param comment_seperators:          Allowed prefixes for comments.
    :param key_delimiters:              Delimiter to separate multiple keys of
                                        a setting argument.
    :param section_override_delimiters: The delimiter to delimit the section
                                        from the key name (e.g. the '.' in
                                        sect.key = value).
    :return:                            A dictionary holding section names
                                        as keys and the sections themselves
                                        as value.
    """
    # Note: arg_list can also be []. Hence we cannot use
    # `arg_list = arg_list or default_list`
    arg_list = sys.argv[1:] if arg_list is None else arg_list
    arg_parser = arg_parser or default_arg_parser()
    origin += os.path.sep
    sections = OrderedDict(default=Section('Default'))
    line_parser = LineParser(key_value_delimiters,
                             comment_seperators,
                             key_delimiters,
                             {},
                             section_override_delimiters)

    for arg_key, arg_value in sorted(
            vars(arg_parser.parse_args(arg_list)).items()):
        if arg_key == 'settings' and arg_value is not None:
            parse_custom_settings(sections,
                                  arg_value,
                                  origin,
                                  line_parser)
        else:
            if isinstance(arg_value, list):
                arg_value = ",".join([str(val) for val in arg_value])

            append_to_sections(sections,
                               arg_key,
                               arg_value,
                               origin,
                               from_cli=True)

    return sections
Beispiel #17
0
def parse_cli(arg_list=None,
              origin=os.getcwd(),
              arg_parser=None,
              key_value_delimiters=('=', ':'),
              comment_seperators=(),
              key_delimiters=(',',),
              section_override_delimiters=(".",)):
    """
    Parses the CLI arguments and creates sections out of it.

    :param arg_list:                    The CLI argument list.
    :param origin:                      Directory used to interpret relative
                                        paths given as argument.
    :param arg_parser:                  Instance of ArgParser that is used to
                                        parse none-setting arguments.
    :param key_value_delimiters:        Delimiters to separate key and value
                                        in setting arguments.
    :param comment_seperators:          Allowed prefixes for comments.
    :param key_delimiters:              Delimiter to separate multiple keys of
                                        a setting argument.
    :param section_override_delimiters: The delimiter to delimit the section
                                        from the key name (e.g. the '.' in
                                        sect.key = value).
    :return:                            A dictionary holding section names
                                        as keys and the sections themselves
                                        as value.
    """
    # Note: arg_list can also be []. Hence we cannot use
    # `arg_list = arg_list or default_list`
    arg_list = sys.argv[1:] if arg_list is None else arg_list
    arg_parser = arg_parser or default_arg_parser()
    origin += os.path.sep
    sections = OrderedDict(default=Section('Default'))
    line_parser = LineParser(key_value_delimiters,
                             comment_seperators,
                             key_delimiters,
                             {},
                             section_override_delimiters)

    for arg_key, arg_value in sorted(
            vars(arg_parser.parse_args(arg_list)).items()):
        if arg_key == 'settings' and arg_value is not None:
            parse_custom_settings(sections,
                                  arg_value,
                                  origin,
                                  line_parser)
        else:
            if isinstance(arg_value, list):
                arg_value = ",".join([str(val) for val in arg_value])

            append_to_sections(sections,
                               arg_key,
                               arg_value,
                               origin,
                               from_cli=True)

    return sections
Beispiel #18
0
 def test_argcomplete_imported(self):
     if coalib.parsing.DefaultArgParser.argcomplete is not None:
         coalib.parsing.DefaultArgParser.argcomplete = None
     parser = default_arg_parser()
     self.assertEqual(coalib.parsing.DefaultArgParser.argcomplete,
                      argcomplete)
     arg = _get_arg(parser, '--bears')
     self.assertTrue(hasattr(arg, 'completer'))
     bears = list(arg.completer())
     self.assertEqual(bears, get_all_bears_names())
 def test_argcomplete_imported(self):
     if coalib.parsing.DefaultArgParser.argcomplete is not None:
         coalib.parsing.DefaultArgParser.argcomplete = None
     parser = default_arg_parser()
     self.assertEqual(coalib.parsing.DefaultArgParser.argcomplete,
                      argcomplete)
     arg = _get_arg(parser, '--bears')
     self.assertTrue(hasattr(arg, 'completer'))
     bears = list(arg.completer())
     self.assertEqual(bears, get_all_bears_names())
 def test_show_bear_settings_only(self):
     with retrieve_stdout() as stdout:
         args = default_arg_parser().parse_args(['--show-settings'])
         show_bear(TestBear, False, False, self.console_printer, args)
         self.assertEqual(stdout.getvalue(),
                          'TestBear\n'
                          '  Needed Settings:\n'
                          '   * setting1: Required Setting.\n\n'
                          '  Optional Settings:\n'
                          '   * setting2: Optional Setting. ('
                          "Optional, defaults to 'None'.)\n\n")
Beispiel #21
0
def main():
    configure_logging()

    try:
        console_printer = ConsolePrinter()
        log_printer = LogPrinter(console_printer)
        # Note: We parse the args here once to check whether to show bears or
        # not.
        args = default_arg_parser().parse_args()
        console_printer = ConsolePrinter(print_colored=not args.no_color)

        if args.show_bears:
            from coalib.settings.ConfigurationGathering import (
                get_filtered_bears)

            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)

            show_bears(local_bears, global_bears, args.show_description
                       or args.show_details, args.show_details,
                       console_printer)

            return 0
        elif args.show_capabilities:
            from coalib.collecting.Collectors import (
                filter_capabilities_by_languages)
            from coalib.settings.ConfigurationGathering import (
                get_filtered_bears)

            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)
            capabilities = filter_capabilities_by_languages(
                local_bears, args.show_capabilities)
            show_language_bears_capabilities(capabilities, console_printer)

            return 0

    except BaseException as exception:  # pylint: disable=broad-except
        return get_exitcode(exception, log_printer)

    import functools

    from coalib.coala_main import run_coala

    partial_print_sec_beg = functools.partial(print_section_beginning,
                                              console_printer)
    results, exitcode, _ = run_coala(
        print_results=print_results,
        acquire_settings=acquire_settings,
        print_section_beginning=partial_print_sec_beg,
        nothing_done=nothing_done,
        console_printer=console_printer)

    return exitcode
 def test_show_bear_settings_only(self):
     with retrieve_stdout() as stdout:
         args = default_arg_parser().parse_args(['--show-settings'])
         show_bear(TestBear, False, False, self.console_printer, args)
         self.assertEqual(
             stdout.getvalue(), 'TestBear\n'
             '  Needed Settings:\n'
             '   * setting1: Required Setting.\n\n'
             '  Optional Settings:\n'
             '   * setting2: Optional Setting. ('
             "Optional, defaults to 'None'.)\n\n")
Beispiel #23
0
def main():
    args = default_arg_parser().parse_args()
    console_printer = ConsolePrinter(print_colored=not args.no_color)
    partial_print_sec_beg = functools.partial(print_section_beginning,
                                              console_printer)
    results, exitcode, _ = run_coala(
        print_results=print_results_no_input,
        print_section_beginning=partial_print_sec_beg,
        force_show_patch=True,
        console_printer=console_printer)

    return exitcode
Beispiel #24
0
def main():
    args = default_arg_parser().parse_args()
    console_printer = ConsolePrinter(print_colored=not args.no_color)
    partial_print_sec_beg = functools.partial(
        print_section_beginning,
        console_printer)
    results, exitcode, _ = run_coala(
        print_results=print_results_no_input,
        print_section_beginning=partial_print_sec_beg,
        force_show_patch=True,
        console_printer=console_printer)

    return exitcode
Beispiel #25
0
def create_arg_parser(files, bears):
    """
    A function that generates a `default_arg_parser`.

    :param files: A list that contains filenames.
    :param bears: A list that contains name of bears.
    :return:      An object of type `default_arg_parser`.
    """
    args = default_arg_parser().parse_args()
    args.files = files
    args.bears = bears
    args.default_actions = '**: ApplyPatchAction'

    return args
def create_arg_parser(files, bears):
    """
    A function that generates a `default_arg_parser`.

    :param files: A list that contains filenames.
    :param bears: A list that contains name of bears.
    :return:      An object of type `default_arg_parser`.
    """
    args = default_arg_parser().parse_args()
    args.files = files
    args.bears = bears
    args.default_actions = '*: ApplyPatchAction'

    return args
Beispiel #27
0
def main():
    # Note: We parse the args here once to find the log printer to use.
    #       Also, commands like -h (help) and -v (version) are executed here.
    #       The args are again parsed later to find the settings and configs
    #       to use during analysis.
    arg_parser = default_arg_parser()
    args = arg_parser.parse_args()

    log_printer = None if args.text_logs else ListLogPrinter()
    JSONEncoder = create_json_encoder(use_relpath=args.relpath)
    results = []

    if args.show_bears:
        try:
            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)
            bears = inverse_dicts(local_bears, global_bears)
            for bear, _ in sorted(bears.items(),
                                  key=lambda bear_tuple: bear_tuple[0].name):
                results.append(bear)
        except BaseException as exception:  # pylint: disable=broad-except
            return get_exitcode(exception, log_printer)
    else:
        results, exitcode, _ = run_coala(log_printer=log_printer,
                                         autoapply=False)

    retval = {"bears": results} if args.show_bears else {"results": results}
    if not args.text_logs:
        retval["logs"] = log_printer.logs
    if args.output:
        filename = str(args.output[0])
        with open(filename, 'w+') as fp:
            json.dump(retval,
                      fp,
                      cls=JSONEncoder,
                      sort_keys=True,
                      indent=2,
                      separators=(',', ': '))
    else:
        print(
            json.dumps(retval,
                       cls=JSONEncoder,
                       sort_keys=True,
                       indent=2,
                       separators=(',', ': ')))

    return 0 if args.show_bears else exitcode
Beispiel #28
0
    def test_argcomplete_missing_other(self):
        if coalib.parsing.DefaultArgParser.argcomplete is not None:
            coalib.parsing.DefaultArgParser.argcomplete = None
        real_importer = __import__

        def import_if_not_bear_names(arg, *args, **kw):
            if arg == 'coalib.collecting.Collectors':
                raise ImportError('import missing: %s' % arg)
            else:
                return real_importer(arg, *args, **kw)

        mock = Mock(side_effect=import_if_not_bear_names)
        with patch('builtins.__import__', new=mock):
            parser = default_arg_parser()
        self.assertTrue(coalib.parsing.DefaultArgParser.argcomplete)
        arg = _get_arg(parser, '--bears')
        self.assertFalse(hasattr(arg, 'completer'))
    def test_argcomplete_missing_other(self):
        if coalib.parsing.DefaultArgParser.argcomplete is not None:
            coalib.parsing.DefaultArgParser.argcomplete = None
        real_importer = __import__

        def import_if_not_bear_names(arg, *args, **kw):
            if arg == 'coalib.collecting.Collectors':
                raise ImportError('import missing: %s' % arg)
            else:
                return real_importer(arg, *args, **kw)

        mock = Mock(side_effect=import_if_not_bear_names)
        with patch('builtins.__import__', new=mock):
            parser = default_arg_parser()
        self.assertTrue(coalib.parsing.DefaultArgParser.argcomplete)
        arg = _get_arg(parser, '--bears')
        self.assertFalse(hasattr(arg, 'completer'))
Beispiel #30
0
def main():
    # Note: We parse the args here once to find the log printer to use.
    #       Also, commands like -h (help) and -v (version) are executed here.
    #       The args are again parsed later to find the settings and configs
    #       to use during analysis.
    arg_parser = default_arg_parser()
    args = arg_parser.parse_args()

    log_printer = None if args.text_logs else ListLogPrinter()
    JSONEncoder = create_json_encoder(use_relpath=args.relpath)
    results = []

    if args.show_bears:
        try:
            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)
            bears = inverse_dicts(local_bears, global_bears)
            for bear, _ in sorted(bears.items(),
                                  key=lambda bear_tuple:
                                  bear_tuple[0].name):
                results.append(bear)
        except BaseException as exception:  # pylint: disable=broad-except
            return get_exitcode(exception, log_printer)
    else:
        results, exitcode, _ = run_coala(
            log_printer=log_printer, autoapply=False)

    retval = {"bears": results} if args.show_bears else {"results": results}
    if not args.text_logs:
        retval["logs"] = log_printer.logs
    if args.output:
        filename = str(args.output[0])
        with open(filename, 'w+') as fp:
            json.dump(retval, fp,
                      cls=JSONEncoder,
                      sort_keys=True,
                      indent=2,
                      separators=(',', ': '))
    else:
        print(json.dumps(retval,
                         cls=JSONEncoder,
                         sort_keys=True,
                         indent=2,
                         separators=(',', ': ')))

    return 0 if args.show_bears else exitcode
Beispiel #31
0
def collect_filters(args, arg_list=None, arg_parser=None):
    """
    Collects all filters from based on cli arguments.

    :param args:
        Parsed CLI args using which the filters are to be collected.
    :param arg_list:
        The CLI argument list.
    :param arg_parser:
        Instance of ArgParser that is used to parse arg list.
    :return:
        List of filters in standard filter format, i.e
        ``[['filter_name', 'arg1', 'arg2']]``.
    """
    if args is None:
        arg_parser = default_arg_parser() if arg_parser is None else arg_parser
        args = arg_parser.parse_args(arg_list)

    return getattr(args, 'filter_by', None) or []
Beispiel #32
0
def get_args():
    arg_parser = default_arg_parser()
    arg_parser.add_argument('--noupdate',
                            nargs='?',
                            const=True,
                            metavar='BOOL',
                            default=False,
                            help='Launch webserver from existing results.')
    arg_parser.add_argument('--dir',
                            nargs='?',
                            metavar='FILE',
                            default=os.path.abspath('./coalahtmlapp'),
                            help='Absolute path for storing webpages in '
                            'directory.')
    arg_parser.add_argument('--nolaunch',
                            nargs='?',
                            const=True,
                            metavar='BOOL',
                            default=False,
                            help='Do not launch webserver.')
    return arg_parser
Beispiel #33
0
def get_args():
    arg_parser = default_arg_parser()
    arg_parser.add_argument('--noupdate',
                            nargs='?',
                            const=True,
                            metavar='BOOL',
                            default=False,
                            help='Launch webserver from existing results.')
    arg_parser.add_argument('--dir',
                            nargs='?',
                            metavar='FILE',
                            default=os.path.abspath('./coalahtmlapp'),
                            help='Absolute path for storing webpages in '
                            'directory.')
    arg_parser.add_argument('--nolaunch',
                            nargs='?',
                            const=True,
                            metavar='BOOL',
                            default=False,
                            help='Do not launch webserver.')
    return arg_parser
Beispiel #34
0
def collect_filters(args, arg_list=None, arg_parser=None):
    """
    Collects all filters from based on cli arguments.

    :param args:
        Parsed CLI args using which the filters are to be collected.
    :param arg_list:
        The CLI argument list.
    :param arg_parser:
        Instance of ArgParser that is used to parse arg list.
    :return:
        List of filters in standard filter format, i.e
        ``{'filter_name': ('arg1', 'arg2')}``.
    """
    if args is None:
        arg_parser = default_arg_parser() if arg_parser is None else arg_parser
        args = arg_parser.parse_args(arg_list)

    filters = getattr(args, 'filter_by', None) or []
    filters = filter_vector_to_dict(filters)
    return filters
Beispiel #35
0
def main():
    try:
        console_printer = ConsolePrinter()
        log_printer = LogPrinter(console_printer)
        # Note: We parse the args here once to check whether to show bears or
        # not.
        args = default_arg_parser().parse_args()

        if args.show_bears:
            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)

            show_bears(local_bears, global_bears, args.show_description
                       or args.show_details, args.show_details,
                       console_printer)

            return 0
        elif args.show_capabilities:
            local_bears, global_bears = get_filtered_bears(
                args.filter_by_language, log_printer)
            capabilities = filter_capabilities_by_languages(
                local_bears, args.show_capabilities)
            show_language_bears_capabilities(capabilities, console_printer)

            return 0

    except BaseException as exception:  # pylint: disable=broad-except
        return get_exitcode(exception, log_printer)

    partial_print_sec_beg = functools.partial(print_section_beginning,
                                              console_printer)
    results, exitcode, _ = run_coala(
        print_results=print_results,
        acquire_settings=acquire_settings,
        print_section_beginning=partial_print_sec_beg,
        nothing_done=nothing_done)

    return exitcode
Beispiel #36
0
def main(debug=False):
    configure_logging()

    args = None  # to have args variable in except block when parse_args fails
    try:
        # Note: We parse the args here once to check whether to show bears or
        # not.
        args = default_arg_parser().parse_args()
        if args.debug:
            req_ipdb = PipRequirement('ipdb')
            if not req_ipdb.is_installed():
                logging.error(
                    '--debug flag requires ipdb. '
                    'You can install it with:\n%s',
                    ' '.join(req_ipdb.install_command()))
                sys.exit(13)

        if debug or args.debug:
            args.log_level = 'DEBUG'

        # Defer imports so if e.g. --help is called they won't be run
        from coalib.coala_modes import (mode_format, mode_json,
                                        mode_non_interactive, mode_normal)
        from coalib.output.ConsoleInteraction import (
            show_bears, show_language_bears_capabilities)

        console_printer = ConsolePrinter(print_colored=not args.no_color)
        configure_logging(not args.no_color)

        if args.show_bears:
            from coalib.settings.ConfigurationGathering import get_all_bears
            kwargs = {}
            if args.bears:
                kwargs['bear_globs'] = args.bears
            filtered_bears = get_all_bears(**kwargs)
            if args.filter_by_language:
                logging.warning("'--filter-by-language ...' is deprecated. "
                                "Use '--filter-by language ...' instead.")
                if args.filter_by is None:
                    args.filter_by = []
                args.filter_by.append(['language'] + args.filter_by_language)
            if args.filter_by:
                # Each iteration of the following loop applies
                # filters one by one provided as arguments
                try:
                    filtered_bears = apply_filters(args.filter_by,
                                                   filtered_bears)
                except (InvalidFilterException, NotImplementedError) as ex:
                    # If filter is not available or is unusable
                    console_printer.print(ex)
                    return 2

            local_bears, global_bears = filtered_bears
            show_bears(local_bears, global_bears, args.show_description
                       or args.show_details, args.show_details,
                       console_printer, args)

            return 0
        elif args.show_capabilities:
            from coalib.collecting.Collectors import (
                filter_capabilities_by_languages)
            local_bears, _ = apply_filter('language', args.show_capabilities)
            capabilities = filter_capabilities_by_languages(
                local_bears, args.show_capabilities)
            show_language_bears_capabilities(capabilities, console_printer)

            return 0

        if args.json:
            return mode_json(args, debug=debug)

    except BaseException as exception:  # pylint: disable=broad-except
        if not isinstance(exception, SystemExit):
            if args and args.debug:
                import ipdb
                with ipdb.launch_ipdb_on_exception():
                    raise

            if debug:
                raise

        return get_exitcode(exception)

    if args.format:
        return mode_format(args, debug=debug)

    if args.non_interactive:
        return mode_non_interactive(console_printer, args, debug=debug)

    return mode_normal(console_printer, None, args, debug=debug)
Beispiel #37
0
def parse_cli(arg_list=None,
              origin=os.getcwd(),
              arg_parser=None,
              args=None,
              key_value_delimiters=('=', ':'),
              comment_seperators=(),
              key_delimiters=(',',),
              section_override_delimiters=('.',),
              key_value_append_delimiters=('+=',)):
    """
    Parses the CLI arguments and creates sections out of it.

    :param arg_list:                    The CLI argument list.
    :param origin:                      Directory used to interpret relative
                                        paths given as argument.
    :param arg_parser:                  Instance of ArgParser that is used to
                                        parse none-setting arguments.
    :param args:                        Alternative pre-parsed CLI arguments.
    :param key_value_delimiters:        Delimiters to separate key and value
                                        in setting arguments where settings are
                                        being defined.
    :param comment_seperators:          Allowed prefixes for comments.
    :param key_delimiters:              Delimiter to separate multiple keys of
                                        a setting argument.
    :param section_override_delimiters: The delimiter to delimit the section
                                        from the key name (e.g. the '.' in
                                        sect.key = value).
    :param key_value_append_delimiters: Delimiters to separate key and value
                                        in setting arguments where settings are
                                        being appended.
    :return:                            A dictionary holding section names
                                        as keys and the sections themselves
                                        as value.
    """
    assert not (arg_list and args), (
        'Either call parse_cli() with an arg_list of CLI arguments or '
        'with pre-parsed args, but not with both.')

    if args is None:
        arg_parser = default_arg_parser() if arg_parser is None else arg_parser
        args = arg_parser.parse_args(arg_list)

    origin += os.path.sep
    sections = OrderedDict(cli=Section('cli'))
    line_parser = LineParser(key_value_delimiters,
                             comment_seperators,
                             key_delimiters,
                             {},
                             section_override_delimiters,
                             key_value_append_delimiters)

    for arg_key, arg_value in sorted(vars(args).items()):
        if arg_key == 'settings' and arg_value is not None:
            parse_custom_settings(sections,
                                  arg_value,
                                  origin,
                                  line_parser)
        else:
            if isinstance(arg_value, list):
                arg_value = ','.join([str(val) for val in arg_value])

            append_to_sections(sections,
                               arg_key,
                               arg_value,
                               origin,
                               section_name='cli',
                               from_cli=True)

    return sections
Beispiel #38
0
def parse_cli(arg_list=None,
              origin=os.getcwd(),
              arg_parser=None,
              args=None,
              key_value_delimiters=('=', ':'),
              comment_seperators=(),
              key_delimiters=(',', ),
              section_override_delimiters=('.', ),
              key_value_append_delimiters=('+=', )):
    """
    Parses the CLI arguments and creates sections out of it.

    :param arg_list:                    The CLI argument list.
    :param origin:                      Directory used to interpret relative
                                        paths given as argument.
    :param arg_parser:                  Instance of ArgParser that is used to
                                        parse none-setting arguments.
    :param args:                        Alternative pre-parsed CLI arguments.
    :param key_value_delimiters:        Delimiters to separate key and value
                                        in setting arguments where settings are
                                        being defined.
    :param comment_seperators:          Allowed prefixes for comments.
    :param key_delimiters:              Delimiter to separate multiple keys of
                                        a setting argument.
    :param section_override_delimiters: The delimiter to delimit the section
                                        from the key name (e.g. the '.' in
                                        sect.key = value).
    :param key_value_append_delimiters: Delimiters to separate key and value
                                        in setting arguments where settings are
                                        being appended.
    :return:                            A dictionary holding section names
                                        as keys and the sections themselves
                                        as value.
    """
    assert not (arg_list and args), (
        'Either call parse_cli() with an arg_list of CLI arguments or '
        'with pre-parsed args, but not with both.')

    if args is None:
        arg_parser = default_arg_parser() if arg_parser is None else arg_parser
        args = arg_parser.parse_args(arg_list)

    origin += os.path.sep
    sections = OrderedDict(cli=Section('cli'))
    line_parser = LineParser(key_value_delimiters, comment_seperators,
                             key_delimiters, {}, section_override_delimiters,
                             key_value_append_delimiters)

    for arg_key, arg_value in sorted(vars(args).items()):
        if arg_key == 'settings' and arg_value is not None:
            parse_custom_settings(sections, arg_value, origin, line_parser)
        else:
            if isinstance(arg_value, list):
                arg_value = ','.join([str(val) for val in arg_value])

            append_to_sections(sections,
                               arg_key,
                               arg_value,
                               origin,
                               section_name='cli',
                               from_cli=True)

    return sections
Beispiel #39
0
def main(debug=False):
    configure_logging()

    args = None  # to have args variable in except block when parse_args fails
    try:
        # Note: We parse the args here once to check whether to show bears or
        # not.
        args = default_arg_parser().parse_args()
        if args.debug:
            req_ipdb = PipRequirement('ipdb')
            if not req_ipdb.is_installed():
                logging.error('--debug flag requires ipdb. '
                              'You can install it with:\n%s',
                              ' '.join(req_ipdb.install_command()))
                sys.exit(13)

        if debug or args.debug:
            args.log_level = 'DEBUG'

        # Defer imports so if e.g. --help is called they won't be run
        from coalib.coala_modes import (
            mode_format, mode_json, mode_non_interactive, mode_normal)
        from coalib.output.ConsoleInteraction import (
            show_bears, show_language_bears_capabilities)

        console_printer = ConsolePrinter(print_colored=not args.no_color)
        configure_logging(not args.no_color)

        if args.show_bears:
            from coalib.settings.ConfigurationGathering import get_all_bears
            kwargs = {}
            if args.bears:
                kwargs['bear_globs'] = args.bears
            filtered_bears = get_all_bears(**kwargs)
            if args.filter_by_language:
                logging.warning(
                    "'--filter-by-language ...' is deprecated. "
                    "Use '--filter-by language ...' instead.")
                if args.filter_by is None:
                    args.filter_by = []
                args.filter_by.append(['language'] + args.filter_by_language)
            if args.filter_by:
                # Each iteration of the following loop applies
                # filters one by one provided as arguments
                try:
                    args.filter_by = filter_vector_to_dict(args.filter_by)
                    filtered_bears = apply_filters(
                        args.filter_by, filtered_bears)
                except (InvalidFilterException, NotImplementedError) as ex:
                    # If filter is not available or is unusable
                    console_printer.print(ex)
                    return 2

            local_bears, global_bears = filtered_bears
            show_bears(local_bears,
                       global_bears,
                       args.show_description or args.show_details,
                       args.show_details,
                       console_printer,
                       args)

            return 0
        elif args.show_capabilities:
            from coalib.collecting.Collectors import (
                filter_capabilities_by_languages)
            local_bears, _ = apply_filter('language', args.show_capabilities)
            capabilities = filter_capabilities_by_languages(
                local_bears, args.show_capabilities)
            show_language_bears_capabilities(capabilities, console_printer)

            return 0

        if args.json:
            return mode_json(args, debug=debug)

    except BaseException as exception:  # pylint: disable=broad-except
        if not isinstance(exception, SystemExit):
            if args and args.debug:
                import ipdb
                with ipdb.launch_ipdb_on_exception():
                    raise

            if debug:
                raise

        return get_exitcode(exception)

    if args.format:
        return mode_format(args, debug=debug)

    if args.non_interactive:
        return mode_non_interactive(console_printer, args, debug=debug)

    return mode_normal(console_printer, None, args, debug=debug)