Example #1
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)
Example #2
0
    def test_get_filtered_bears(self):
        sys.argv = ['coala', '-I']

        with bear_test_module():
            local_bears, global_bears = get_filtered_bears(
                None, self.log_printer)

        self.assertEqual(len(local_bears['cli']), TEST_BEARS_COUNT)

        self.assertEqual(
            [str(bear) for bear in local_bears['cli']],
            TEST_BEAR_NAME_REPRS)

        with bear_test_module():
            local_bears, global_bears = get_filtered_bears(
                ['Java'], self.log_printer)

        local_bears['cli'] = _sort_bears(local_bears['cli'])
        global_bears['cli'] = _sort_bears(global_bears['cli'])

        self.assertEqual(len(local_bears['cli']), 3)
        self.assertEqual(
            str(local_bears['cli'][0]),
            "<class 'AspectsGeneralTestBear.AspectsGeneralTestBear'>")
        self.assertEqual(str(local_bears['cli'][1]),
                         "<class 'JavaTestBear.JavaTestBear'>")
        self.assertEqual(str(local_bears['cli'][2]),
                         "<class 'LineCountTestBear.LineCountTestBear'>")
        self.assertEqual(len(global_bears['cli']), 0)
Example #3
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)
Example #4
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
Example #5
0
    def test_filter_relevant_bears_green_mode(self):
        from argparse import Namespace
        from coalib.settings.ConfigurationGathering import (
            get_filtered_bears)
        self.arg_parser.parse_args = unittest.mock.MagicMock(
            return_value=Namespace(green_mode=True))
        res = filter_relevant_bears([('Python', 70), ('C', 20)],
                                    self.printer,
                                    self.arg_parser,
                                    {})
        all_bears = get_filtered_bears(['Python', 'C'])[0]
        bears = all_bears['cli']
        important_bears = []

        for bear_set in list(IMPORTANT_BEAR_LIST.values()):
            for bear in bear_set:
                important_bears.append(bear)

        bear_objs = []
        for bear in bears:
            if bear.__name__ in important_bears:
                bear_objs.append(bear)

        bear_obj_dict = dict()
        for key in ['Python', 'C', 'All']:
            bear_obj_dict[key] = set()
            for bear in IMPORTANT_BEAR_LIST[key]:
                if bear in GREEN_MODE_INCOMPATIBLE_BEAR_LIST:
                    continue
                bear_obj_dict[key].update([x for x in bear_objs if (
                    x.__name__ == bear)])

        self.maxDiff = None
        self.assertEqual(res, bear_obj_dict)
Example #6
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_filter_relevant_bears_green_mode(self):
        from argparse import Namespace
        from coalib.settings.ConfigurationGathering import (
            get_filtered_bears)
        self.arg_parser.parse_args = unittest.mock.MagicMock(
            return_value=Namespace(green_mode=True))
        res = filter_relevant_bears([('Python', 70), ('C', 20)],
                                    self.printer,
                                    self.arg_parser,
                                    {})
        all_bears = get_filtered_bears(['Python', 'C'])[0]
        bears = all_bears['cli']
        important_bears = []

        for bear_set in list(IMPORTANT_BEAR_LIST.values()):
            for bear in bear_set:
                important_bears.append(bear)

        bear_objs = []
        for bear in bears:
            if bear.__name__ in important_bears:
                bear_objs.append(bear)

        bear_obj_dict = dict()
        for key in ['Python', 'C', 'All']:
            bear_obj_dict[key] = set()
            for bear in IMPORTANT_BEAR_LIST[key]:
                if bear in GREEN_MODE_INCOMPATIBLE_BEAR_LIST:
                    continue
                bear_obj_dict[key].update([x for x in bear_objs if (
                    x.__name__ == bear)])

        self.maxDiff = None
        self.assertEqual(res, bear_obj_dict)
    def test_get_filtered_bears(self):
        sys.argv = ['coala', '-I']

        with bear_test_module():
            local_bears, global_bears = get_filtered_bears(
                None, self.log_printer)

        self.assertEqual(len(local_bears['cli']), 13)

        with bear_test_module():
            local_bears, global_bears = get_filtered_bears(['Java'],
                                                           self.log_printer)

        self.assertEqual(len(local_bears['cli']), 2)
        self.assertEqual(str(local_bears['cli'][0]),
                         "<class 'JavaTestBear.JavaTestBear'>")
        self.assertEqual(str(local_bears['cli'][1]),
                         "<class 'LineCountTestBear.LineCountTestBear'>")
        self.assertEqual(len(global_bears['cli']), 0)
Example #9
0
def mode_json(args):
    import json

    from coalib.coala_main import run_coala
    from coalib.misc.DictUtilities import inverse_dicts
    from coalib.misc.Exceptions import get_exitcode
    from coalib.output.Logging import configure_json_logging
    from coalib.output.JSONEncoder import create_json_encoder
    from coalib.output.printers.LogPrinter import LogPrinter
    from coalib.settings.ConfigurationGathering import get_filtered_bears

    if args.log_json:
        log_stream = configure_json_logging()

    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, LogPrinter())
            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)
    else:
        results, exitcode, _ = run_coala()

    retval = {'bears': results} if args.show_bears else {'results': results}

    if args.log_json:
        retval['logs'] = [
            json.loads(line) for line in log_stream.getvalue().splitlines()
        ]

    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
Example #10
0
File: coala.py Project: zmyer/coala
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
Example #11
0
    def test_get_filtered_bears(self):
        sys.argv = ['coala', '-I']

        with bear_test_module():
            local_bears, global_bears = get_filtered_bears(
                None, self.log_printer)

        self.assertEqual(len(local_bears['cli']), TEST_BEARS_COUNT)

        test_string = [str(bear) for bear in local_bears['cli']]
        test_bear_name_reprs_regex = [
            test.replace('(', '\\(').replace(')', '\\)')
            for test in TEST_BEAR_NAME_REPRS
        ]
        pattern_string = [
            f'{test}'[0:-1] + '( at \\(0x[a-fA-F0-9]+\\))?>'
            for test in test_bear_name_reprs_regex
        ]

        for test, pattern in zip(test_string, pattern_string):
            self.assertRegex(test, pattern)

        with bear_test_module():
            local_bears, global_bears = get_filtered_bears(['Java'],
                                                           self.log_printer)

        local_bears['cli'] = _sort_bears(local_bears['cli'])
        global_bears['cli'] = _sort_bears(global_bears['cli'])

        self.assertEqual(len(local_bears['cli']), 3)
        self.assertEqual(
            str(local_bears['cli'][0]),
            "<class 'AspectsGeneralTestBear.AspectsGeneralTestBear'>")
        self.assertEqual(str(local_bears['cli'][1]),
                         "<class 'JavaTestBear.JavaTestBear'>")
        self.assertEqual(str(local_bears['cli'][2]),
                         "<class 'LineCountTestBear.LineCountTestBear'>")
        self.assertEqual(len(global_bears['cli']), 0)
Example #12
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
Example #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()
    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
Example #14
0
def mode_json(args):
    import json

    from coalib.coala_main import run_coala
    from coalib.misc.DictUtilities import inverse_dicts
    from coalib.misc.Exceptions import get_exitcode
    from coalib.output.JSONEncoder import create_json_encoder
    from coalib.output.printers.LogPrinter import LogPrinter
    from coalib.parsing.DefaultArgParser import default_arg_parser
    from coalib.settings.ConfigurationGathering import get_filtered_bears

    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, LogPrinter())
            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)
    else:
        results, exitcode, _ = run_coala()

    retval = {'bears': results} if args.show_bears else {'results': results}
    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
Example #15
0
def mode_json(args):
    import json

    from coalib.coala_main import run_coala
    from coalib.misc.DictUtilities import inverse_dicts
    from coalib.misc.Exceptions import get_exitcode
    from coalib.output.Logging import configure_json_logging
    from coalib.output.JSONEncoder import create_json_encoder
    from coalib.output.printers.LogPrinter import LogPrinter
    from coalib.settings.ConfigurationGathering import get_filtered_bears

    if args.log_json:
        log_stream = configure_json_logging()

    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, LogPrinter())
            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)
    else:
        results, exitcode, _ = run_coala()

    retval = {"bears": results} if args.show_bears else {"results": results}

    if args.log_json:
        retval["logs"] = [json.loads(line) for line in log_stream.getvalue().splitlines()]

    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
Example #16
0
def filter_relevant_bears(used_languages, arg_parser=None):
    """
    From the bear dict, filter the bears per relevant language.

    :param used_languages:
        A list of tuples with language name as the first element
        and percentage usage as the second element; sorted by
        percentage usage.
    :return:
        A dict with language name as key and bear classes as value.
    """
    log_printer = LogPrinter(NullPrinter())
    used_languages.append(("All", 100))

    all_bears_by_lang = {
        lang: set(
            inverse_dicts(
                *get_filtered_bears([lang], log_printer, arg_parser)).keys())
        for lang, _ in used_languages
    }

    bears_by_lang = {}
    for lang in all_bears_by_lang:
        if lang in IMPORTANT_BEAR_LIST:
            bears_by_lang[lang] = {
                bear
                for bear in all_bears_by_lang[lang]
                if bear.name in IMPORTANT_BEAR_LIST[lang]
            }
        else:
            bears_by_lang[lang] = all_bears_by_lang[lang]

    # Each language would also have the language independent bears. We remove
    # those and put them in the "All" category.
    lang_bears = {
        lang: bears_by_lang[lang] - bears_by_lang["All"]
        for lang, _ in used_languages
    }
    lang_bears["All"] = bears_by_lang["All"]
    return lang_bears
Example #17
0
def filter_relevant_bears(used_languages):
    """
    From the bear dict, filter the bears per relevant language.

    :param used_languages:
        A list of tuples with language name as the first element
        and percentage usage as the second element; sorted by
        percentage usage.
    :return:
        A dict with language name as key and bear classes as value.
    """
    log_printer = LogPrinter(NullPrinter())
    used_languages.append(("All", 100))

    bears_by_lang = {lang: set(inverse_dicts(*get_filtered_bears(
        [lang], log_printer)).keys()) for lang, _ in used_languages}

    # Each language would also have the language independent bears. We remove
    # those and put them in the "All" category.
    lang_bears = {lang: bears_by_lang[lang] - bears_by_lang["All"]
                  for lang, _ in used_languages}
    lang_bears["All"] = bears_by_lang["All"]
    return lang_bears
Example #18
0
def filter_relevant_bears(used_languages,
                          printer,
                          arg_parser,
                          extracted_info,
                          log_printer=None):
    """
    From the bear dict, filter the bears per relevant language.

    :param used_languages:
        A list of tuples with language name as the first element
        and percentage usage as the second element; sorted by
        percentage usage.
    :param printer:
        ``ConsolePrinter`` object to be used for console interactions.
    :param arg_parser:
        ``argparse.ArgumentParser`` object containing the arguments
        passed.
    :param extracted_info:
        list of information extracted from ``InfoExtractor`` classes.
    :return:
        A dict with language name as key and bear classes as value.
    """
    args = arg_parser.parse_args() if arg_parser else None
    used_languages.append(('All', 100))

    bears_by_lang = {
        lang: set(
            inverse_dicts(*get_filtered_bears(
                [lang], log_printer, arg_parser, silent=True)).keys())
        for lang, _ in used_languages
    }

    # Each language would also have the language independent bears. We remove
    # those and put them in the "All" category.
    all_lang_bears = bears_by_lang['All']
    bears_by_lang = {
        lang: bears_by_lang[lang] - bears_by_lang['All']
        for lang, _ in used_languages
    }
    bears_by_lang['All'] = all_lang_bears

    selected_bears = {}
    candidate_bears = copy.copy(bears_by_lang)
    to_propose_bears = {}

    REQUIRED_BEAR_LIST = IMPORTANT_BEAR_LIST

    if args.green_mode:
        from coala_quickstart.Constants import (
            GREEN_MODE_COMPATIBLE_BEAR_LIST,
            GREEN_MODE_INCOMPATIBLE_BEAR_LIST,
        )
        REQUIRED_BEAR_LIST = concatenate(IMPORTANT_BEAR_LIST,
                                         GREEN_MODE_COMPATIBLE_BEAR_LIST)
        NEW_REQUIRED_BEAR_LIST = {}
        for lang in REQUIRED_BEAR_LIST:
            NEW_REQUIRED_BEAR_LIST[lang] = set()
            for bear in REQUIRED_BEAR_LIST[lang]:
                if bear not in GREEN_MODE_INCOMPATIBLE_BEAR_LIST:
                    NEW_REQUIRED_BEAR_LIST[lang].add(bear)
        REQUIRED_BEAR_LIST = NEW_REQUIRED_BEAR_LIST

    # Initialize selected_bears with REQUIRED_BEAR_LIST
    for lang, lang_bears in candidate_bears.items():
        if lang_bears and lang in REQUIRED_BEAR_LIST:
            selected_bears[lang] = set()
            for bear in lang_bears:
                if bear.__name__ in REQUIRED_BEAR_LIST[lang]:
                    selected_bears[lang].add(bear)
        if lang_bears and lang not in REQUIRED_BEAR_LIST and (
                not args.green_mode):
            selected_bears[lang] = set(lang_bears)

        candidate_bears[lang] = set([
            bear for bear in lang_bears
            if lang in selected_bears and bear not in selected_bears[lang]
        ])

    if args.green_mode:
        return selected_bears

    if not args.no_filter_by_capabilities:
        # Ask user for capablities
        user_selected_capabilities = set()
        if not args.non_interactive:
            user_selected_capabilities = ask_to_select_capabilities(
                list(ALL_CAPABILITIES), list(DEFAULT_CAPABILITIES), printer)

        desired_capabilities = (user_selected_capabilities
                                if user_selected_capabilities else
                                DEFAULT_CAPABILITIES)

        # Filter bears based on capabilities
        for lang, lang_bears in candidate_bears.items():
            # Eliminate bears which doesn't contain the desired capabilities
            capable_bears = get_bears_with_given_capabilities(
                lang_bears, desired_capabilities)
            candidate_bears[lang] = capable_bears

    lint_task_info = extracted_info.get('LintTaskInfo', [])
    project_dependency_info = extracted_info.get('ProjectDependencyInfo', [])

    # Use lint_task_info to propose bears to user.
    for lang, lang_bears in candidate_bears.items():
        matching_linter_bears = get_matching_linter_bears(
            lang_bears, lint_task_info)
        to_propose_bears[lang] = matching_linter_bears

    # Use project_dependency_info to propose bears to user.
    for lang, lang_bears in candidate_bears.items():
        matching_dep_bears = get_bears_with_matching_dependencies(
            lang_bears, project_dependency_info)
        if to_propose_bears.get(lang):
            to_propose_bears[lang].update(matching_dep_bears)
        else:
            to_propose_bears[lang] = matching_dep_bears

    for lang, lang_bears in to_propose_bears.items():
        for bear in lang_bears:
            # get the non-optional settings of the bears
            settings = bear.get_non_optional_settings()
            if settings:
                user_input_reqd = False
                for setting in settings:
                    if not is_autofill_possible(setting, lang, bear,
                                                extracted_info):
                        user_input_reqd = True
                        break

                if user_input_reqd:
                    # Ask user to activate the bear
                    if (args and not args.non_interactive
                            and prompt_to_activate(bear, printer)):
                        selected_bears[lang].add(bear)
                else:
                    # All the non-optional settings can be filled automatically
                    selected_bears[lang].add(bear)
            else:
                # no non-optional setting, select it right away!
                selected_bears[lang].add(bear)

    if not args.no_filter_by_capabilities:
        # capabilities satisfied till now
        satisfied_capabilities = get_bears_capabilities(selected_bears)
        remaining_capabilities = {
            lang: [
                cap for cap in desired_capabilities
                if lang in satisfied_capabilities
                and cap not in satisfied_capabilities[lang]
            ]
            for lang in candidate_bears
        }

        filtered_bears = {}
        for lang, lang_bears in candidate_bears.items():
            filtered_bears[lang] = get_bears_with_given_capabilities(
                lang_bears, remaining_capabilities[lang])

        # Remove overlapping capability bears
        filtered_bears = remove_bears_with_conflicting_capabilities(
            filtered_bears)

        # Add to the selected_bears
        for lang, lang_bears in filtered_bears.items():
            if not selected_bears.get(lang):
                selected_bears[lang] = lang_bears
            else:
                selected_bears[lang].update(lang_bears)

    return selected_bears
Example #19
0
def filter_relevant_bears(used_languages,
                          printer,
                          arg_parser,
                          extracted_info,
                          log_printer=None):
    """
    From the bear dict, filter the bears per relevant language.

    :param used_languages:
        A list of tuples with language name as the first element
        and percentage usage as the second element; sorted by
        percentage usage.
    :param printer:
        ``ConsolePrinter`` object to be used for console interactions.
    :param arg_parser:
        ``argparse.ArgumentParser`` object containing the arguments
        passed.
    :param extracted_info:
        list of information extracted from ``InfoExtractor`` classes.
    :return:
        A dict with language name as key and bear classes as value.
    """
    args = arg_parser.parse_args() if arg_parser else None
    used_languages.append(('All', 100))

    bears_by_lang = {
        lang: set(inverse_dicts(*get_filtered_bears([lang],
                                                    log_printer,
                                                    arg_parser,
                                                    silent=True)).keys())
        for lang, _ in used_languages
    }

    # Each language would also have the language independent bears. We remove
    # those and put them in the "All" category.
    all_lang_bears = bears_by_lang['All']
    bears_by_lang = {lang: bears_by_lang[lang] - bears_by_lang['All']
                     for lang, _ in used_languages}
    bears_by_lang['All'] = all_lang_bears

    selected_bears = {}
    candidate_bears = copy.copy(bears_by_lang)
    to_propose_bears = {}

    REQUIRED_BEAR_LIST = IMPORTANT_BEAR_LIST

    if args.green_mode:
        from coala_quickstart.Constants import (
            GREEN_MODE_COMPATIBLE_BEAR_LIST,
            GREEN_MODE_INCOMPATIBLE_BEAR_LIST,
            )
        REQUIRED_BEAR_LIST = concatenate(IMPORTANT_BEAR_LIST,
                                         GREEN_MODE_COMPATIBLE_BEAR_LIST)
        NEW_REQUIRED_BEAR_LIST = {}
        for lang in REQUIRED_BEAR_LIST:
            NEW_REQUIRED_BEAR_LIST[lang] = set()
            for bear in REQUIRED_BEAR_LIST[lang]:
                if bear not in GREEN_MODE_INCOMPATIBLE_BEAR_LIST:
                    NEW_REQUIRED_BEAR_LIST[lang].add(bear)
        REQUIRED_BEAR_LIST = NEW_REQUIRED_BEAR_LIST

    # Initialize selected_bears with REQUIRED_BEAR_LIST
    for lang, lang_bears in candidate_bears.items():
        if lang_bears and lang in REQUIRED_BEAR_LIST:
            selected_bears[lang] = set()
            for bear in lang_bears:
                if bear.__name__ in REQUIRED_BEAR_LIST[lang]:
                    selected_bears[lang].add(bear)
        if lang_bears and lang not in REQUIRED_BEAR_LIST and (
                not args.green_mode):
            selected_bears[lang] = set(lang_bears)

        candidate_bears[lang] = set(
            [bear for bear in lang_bears
             if lang in selected_bears and
             bear not in selected_bears[lang]])

    if args.green_mode:
        return selected_bears

    if not args.no_filter_by_capabilities:
        # Ask user for capablities
        user_selected_capabilities = set()
        if not args.non_interactive:
            user_selected_capabilities = ask_to_select_capabilties(
                list(ALL_CAPABILITIES), list(DEFAULT_CAPABILTIES), printer)

        desired_capabilities = (
            user_selected_capabilities if user_selected_capabilities
            else DEFAULT_CAPABILTIES)

        # Filter bears based on capabilties
        for lang, lang_bears in candidate_bears.items():
            # Eliminate bears which doesn't contain the desired capabilites
            capable_bears = get_bears_with_given_capabilities(
                lang_bears, desired_capabilities)
            candidate_bears[lang] = capable_bears

    lint_task_info = extracted_info.get('LintTaskInfo', [])
    project_dependency_info = extracted_info.get('ProjectDependencyInfo', [])

    # Use lint_task_info to propose bears to user.
    for lang, lang_bears in candidate_bears.items():
        matching_linter_bears = get_matching_linter_bears(
                lang_bears, lint_task_info)
        to_propose_bears[lang] = matching_linter_bears

    # Use project_dependency_info to propose bears to user.
    for lang, lang_bears in candidate_bears.items():
        matching_dep_bears = get_bears_with_matching_dependencies(
            lang_bears, project_dependency_info)
        if to_propose_bears.get(lang):
            to_propose_bears[lang].update(matching_dep_bears)
        else:
            to_propose_bears[lang] = matching_dep_bears

    for lang, lang_bears in to_propose_bears.items():
        for bear in lang_bears:
            # get the non-optional settings of the bears
            settings = bear.get_non_optional_settings()
            if settings:
                user_input_reqd = False
                for setting in settings:
                    if not is_autofill_possible(
                            setting, lang, bear, extracted_info):
                        user_input_reqd = True
                        break

                if user_input_reqd:
                    # Ask user to activate the bear
                    if (args and not args.non_interactive and
                            prompt_to_activate(bear, printer)):
                        selected_bears[lang].add(bear)
                else:
                    # All the non-optional settings can be filled automatically
                    selected_bears[lang].add(bear)
            else:
                # no non-optional setting, select it right away!
                selected_bears[lang].add(bear)

    if not args.no_filter_by_capabilities:
        # capabilities satisfied till now
        satisfied_capabilities = get_bears_capabilties(selected_bears)
        remaining_capabilities = {
            lang: [cap for cap in desired_capabilities
                   if lang in satisfied_capabilities and
                   cap not in satisfied_capabilities[lang]]
            for lang in candidate_bears}

        filtered_bears = {}
        for lang, lang_bears in candidate_bears.items():
            filtered_bears[lang] = get_bears_with_given_capabilities(
                lang_bears, remaining_capabilities[lang])

        # Remove overlapping capabilty bears
        filtered_bears = remove_bears_with_conflicting_capabilties(
            filtered_bears)

        # Add to the selected_bears
        for lang, lang_bears in filtered_bears.items():
            if not selected_bears.get(lang):
                selected_bears[lang] = lang_bears
            else:
                selected_bears[lang].update(lang_bears)

    return selected_bears