Ejemplo n.º 1
0
    def apply(self, result, original_file_dict, file_diff_dict):
        """
        (G)enerate patches
        """

        console_printer = ConsolePrinter()
        log_printer = LogPrinter()
        to_filename = sorted(
            result.diffs.items())[OBJECT_INDEX][FILENAME_INDEX]

        filtered_bears = filter_bears(find_language(to_filename))
        filtered_bears.insert(0, DefaultBear())
        possible_options = [b.name for b in filtered_bears]

        console_printer.print('[{:>4}] *0. Do Nothing'.format(''))

        # Let the user choose a bear that wants to apply on the files
        for i, action in enumerate(possible_options, 1):
            show_possibilities(console_printer, i, action)

        choose_action = str(input('[{:>4}]  Enter a number: '.format('')))
        if choose_action is '' or choose_action is '0':
            return False

        choose_action = int(choose_action)
        chosen_bear = [possible_options[choose_action - 1]]

        return mode_normal(console_printer,
                           log_printer,
                           create_arg_parser([to_filename], chosen_bear),
                           debug=False)
Ejemplo n.º 2
0
class TestLogo(unittest.TestCase):

    def setUp(self):
        self.printer = ConsolePrinter()

    def test_print_side_by_side(self):
        with retrieve_stdout() as custom_stdout:
            print_side_by_side(
                self.printer,
                ["Left side content."],
                ["Right side content",
                 "that is longer than the",
                 "left side."],
                limit=80)
            self.assertIn(
                "side content.\x1b[0m \x1b[34mRight side",
                custom_stdout.getvalue())

    def test_print_welcome_message(self):
        with retrieve_stdout() as custom_stdout:
            print_welcome_message(self.printer)
            self.assertIn("o88Oo", custom_stdout.getvalue())

    def test_print_ask_dir_help_message(self):
        with retrieve_stdout() as custom_stdout:
            self.printer.print(PROJECT_DIR_HELP)
            self.assertIn(PROJECT_DIR_HELP, custom_stdout.getvalue())
Ejemplo n.º 3
0
    def apply(self,
              result,
              original_file_dict,
              file_diff_dict):
        """
        (G)enerate patches
        """

        console_printer = ConsolePrinter()
        log_printer = LogPrinter()
        to_filename = sorted(result.diffs.items())[OBJECT_INDEX][FILENAME_INDEX]

        filtered_bears = filter_bears(find_language(to_filename))
        filtered_bears.insert(0, DefaultBear())
        possible_options = [b.name for b in filtered_bears]

        console_printer.print('[{:>4}] *0. Do Nothing'.format(''))

        # Let the user choose a bear that wants to apply on the files
        for i, action in enumerate(possible_options, 1):
            show_possibilities(console_printer, i, action)

        choose_action = str(input('[{:>4}]  Enter a number: '.format('')))
        if choose_action is '' or choose_action is '0':
            return False

        choose_action = int(choose_action)
        chosen_bear = [possible_options[choose_action - 1]]

        return mode_normal(console_printer, log_printer, create_arg_parser([
            to_filename], chosen_bear), debug=False)
Ejemplo n.º 4
0
def main():
    arg_parser = _get_arg_parser()
    args = arg_parser.parse_args()

    logging.basicConfig(stream=sys.stdout)
    printer = ConsolePrinter()
    logging.getLogger(__name__)

    fpc = None
    project_dir = os.getcwd()

    if args.green_mode:
        args.non_interactive = None
        args.no_filter_by_capabilities = None
        args.incomplete_sections = None

    if not args.non_interactive and not args.green_mode:
        fpc = FilePathCompleter()
        fpc.activate()
        print_welcome_message(printer)
        printer.print(PROJECT_DIR_HELP)
        project_dir = ask_question('What is your project directory?',
                                   default=project_dir,
                                   typecast=valid_path)
        fpc.deactivate()

    project_files, ignore_globs = get_project_files(None, printer, project_dir,
                                                    fpc, args.non_interactive)

    used_languages = list(get_used_languages(project_files))
    print_used_languages(printer, used_languages)

    extracted_information = collect_info(project_dir)

    relevant_bears = filter_relevant_bears(used_languages, printer, arg_parser,
                                           extracted_information)

    if args.green_mode:
        collect_bear_settings(relevant_bears)

    print_relevant_bears(printer, relevant_bears)

    if args.non_interactive and not args.incomplete_sections:
        unusable_bears = get_non_optional_settings_bears(relevant_bears)
        remove_unusable_bears(relevant_bears, unusable_bears)
        print_relevant_bears(printer, relevant_bears, 'usable')

    settings = generate_settings(project_dir, project_files, ignore_globs,
                                 relevant_bears, extracted_information,
                                 args.incomplete_sections)

    write_coafile(printer, project_dir, settings)
Ejemplo n.º 5
0
def print_results(log_printer,
                  section,
                  result_list,
                  file_dict,
                  file_diff_dict,
                  color=True):
    """
    Print all the results in a section.

    :param log_printer:    Printer responsible for logging the messages.
    :param section:        The section to which the results belong to.
    :param result_list:    List containing the results
    :param file_dict:      A dictionary containing all files with filename as
                           key.
    :param file_diff_dict: A dictionary that contains filenames as keys and
                           diff objects as values.
    :param color:          Boolean variable to print the results in color or
                           not. Can be used for testing.
    """
    console_printer = ConsolePrinter(print_colored=color)

    for result in sorted(result_list):
        if len(result.affected_code) == 0:
            console_printer.print("\n" + STR_PROJECT_WIDE,
                                  color=FILE_NAME_COLOR)
        else:
            for sourcerange in result.affected_code:
                if (
                        sourcerange.file is not None and
                        sourcerange.file not in file_dict):
                    log_printer.warn("The context for the result ({}) cannot "
                                     "be printed because it refers to a file "
                                     "that doesn't seem to exist ({})"
                                     ".".format(str(result), sourcerange.file))
                else:
                    print_affected_lines(console_printer,
                                         file_dict,
                                         sourcerange)

        print_result(console_printer,
                     log_printer,
                     section,
                     file_diff_dict,
                     result,
                     file_dict)
Ejemplo n.º 6
0
    def apply(self,
              result,
              original_file_dict,
              file_diff_dict):
        """
        Show Applied (P)atches
        """
        console_printer = ConsolePrinter()
        applied_actions = result.get_applied_actions()
        show_patch_action = ShowPatchAction()
        RESULT_INDEX = 0
        FILE_DICT_INDEX = 1
        FILE_DIFF_DICT_INDEX = 2
        SECTION_INDEX = 3

        for key, val in applied_actions.items():
            this_result = val[RESULT_INDEX]
            this_section = val[SECTION_INDEX]
            color_res = RESULT_SEVERITY_COLORS[this_result.severity]
            console_printer.print('\n**** {bear} [Section: {section}] ***'
                                  '*\n**** Action Applied: {action} ****\n'
                                  .format(bear=this_result.origin,
                                          section=this_section.name,
                                          action=key),
                                  color=color_res)
            console_printer.print(format_lines('[Severity: {sev}]'.format(
                sev=RESULT_SEVERITY.__str__(this_result.severity)), '!'),
                  color=color_res)
            show_patch_action.apply_from_section(val[RESULT_INDEX],
                                                 val[FILE_DICT_INDEX],
                                                 val[FILE_DIFF_DICT_INDEX],
                                                 val[SECTION_INDEX])
            console_printer.print(
                '\n**************\n', color=color_res)
        return True
Ejemplo n.º 7
0
    def apply(self, result, original_file_dict, file_diff_dict):
        """
        Show Applied (P)atches
        """
        console_printer = ConsolePrinter()
        applied_actions = result.get_applied_actions()
        show_patch_action = ShowPatchAction()
        RESULT_INDEX = 0
        FILE_DICT_INDEX = 1
        FILE_DIFF_DICT_INDEX = 2
        SECTION_INDEX = 3

        for key, val in applied_actions.items():
            this_result = val[RESULT_INDEX]
            this_section = val[SECTION_INDEX]
            color_res = RESULT_SEVERITY_COLORS[this_result.severity]
            console_printer.print(
                '\n**** {bear} [Section: {section}] ***'
                '*\n**** Action Applied: {action} ****\n'.format(
                    bear=this_result.origin,
                    section=this_section.name,
                    action=key),
                color=color_res)
            console_printer.print(format_lines(
                '[Severity: {sev}]'.format(
                    sev=RESULT_SEVERITY.__str__(this_result.severity)), '!'),
                                  color=color_res)
            show_patch_action.apply_from_section(val[RESULT_INDEX],
                                                 val[FILE_DICT_INDEX],
                                                 val[FILE_DIFF_DICT_INDEX],
                                                 val[SECTION_INDEX])
            console_printer.print('\n**************\n', color=color_res)
        return True
Ejemplo n.º 8
0
def print_results(log_printer,
                  section,
                  result_list,
                  file_dict,
                  file_diff_dict,
                  color=True):
    """
    Print all the results in a section.

    :param log_printer:    Printer responsible for logging the messages.
    :param section:        The section to which the results belong to.
    :param result_list:    List containing the results
    :param file_dict:      A dictionary containing all files with filename as
                           key.
    :param file_diff_dict: A dictionary that contains filenames as keys and
                           diff objects as values.
    :param color:          Boolean variable to print the results in color or
                           not. Can be used for testing.
    """
    console_printer = ConsolePrinter(print_colored=color)

    for result in sorted(result_list):
        if len(result.affected_code) == 0:
            console_printer.print("\n" + STR_PROJECT_WIDE,
                                  color=FILE_NAME_COLOR)
        else:
            for sourcerange in result.affected_code:
                if (sourcerange.file is not None
                        and sourcerange.file not in file_dict):
                    log_printer.warn("The context for the result ({}) cannot "
                                     "be printed because it refers to a file "
                                     "that doesn't seem to exist ({})"
                                     ".".format(str(result), sourcerange.file))
                else:
                    print_affected_lines(console_printer, file_dict,
                                         sourcerange)

        print_result(console_printer, log_printer, section, file_diff_dict,
                     result, file_dict)
class TestLogo(unittest.TestCase):
    def setUp(self):
        self.printer = ConsolePrinter()

    def test_print_side_by_side(self):
        with retrieve_stdout() as custom_stdout:
            print_side_by_side(self.printer, ["Left side content."], [
                "Right side content", "that is longer than the", "left side."
            ],
                               limit=80)
            self.assertIn("side content.\x1b[0m \x1b[34mRight side",
                          custom_stdout.getvalue())

    def test_print_welcome_message(self):
        with retrieve_stdout() as custom_stdout:
            print_welcome_message(self.printer)
            self.assertIn("o88Oo", custom_stdout.getvalue())

    def test_print_ask_dir_help_message(self):
        with retrieve_stdout() as custom_stdout:
            self.printer.print(PROJECT_DIR_HELP)
            self.assertIn(PROJECT_DIR_HELP, custom_stdout.getvalue())
Ejemplo n.º 10
0
class ConsolePrinterTest(unittest.TestCase):

    def test_printing(self):
        self.uut = ConsolePrinter(print_colored=True)

        with retrieve_stdout() as stdout:
            self.uut.print("\ntest", "message", color="green")
            self.assertRegex(stdout.getvalue(), "\033.*\ntest message.*")

        with retrieve_stdout() as stdout:
            self.uut.print("\ntest", "message", color="greeeeen")
            self.assertEqual(stdout.getvalue(), "\ntest message\n")

        with retrieve_stdout() as stdout:
            self.uut.print("\ntest", "message")
            self.assertEqual(stdout.getvalue(), "\ntest message\n")
Ejemplo n.º 11
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)
def main():
    global MAX_ARGS_GREEN_MODE, MAX_VALUES_GREEN_MODE
    arg_parser = _get_arg_parser()
    args = arg_parser.parse_args()

    logging.basicConfig(stream=sys.stdout)
    printer = ConsolePrinter()
    logging.getLogger(__name__)

    fpc = None
    project_dir = os.getcwd()

    if args.green_mode:
        args.no_filter_by_capabilities = None
        args.incomplete_sections = None
        if args.max_args:
            MAX_ARGS_GREEN_MODE = args.max_args
        if args.max_values:
            MAX_VALUES_GREEN_MODE = args.max_values

    if not args.green_mode and (args.max_args or args.max_values):
        logging.warning(' --max-args and --max-values can be used '
                        'only with --green-mode. The arguments will '
                        'be ignored.')

    if not args.non_interactive and not args.green_mode:
        fpc = FilePathCompleter()
        fpc.activate()
        print_welcome_message(printer)
        printer.print(PROJECT_DIR_HELP)
        project_dir = ask_question(
            'What is your project directory?',
            default=project_dir,
            typecast=valid_path)
        fpc.deactivate()

    project_files, ignore_globs = get_project_files(
        None,
        printer,
        project_dir,
        fpc,
        args.non_interactive)

    used_languages = list(get_used_languages(project_files))
    used_languages = ask_to_select_languages(used_languages, printer,
                                             args.non_interactive)

    extracted_information = collect_info(project_dir)

    relevant_bears = filter_relevant_bears(
        used_languages, printer, arg_parser, extracted_information)

    if args.green_mode:
        bear_settings_obj = collect_bear_settings(relevant_bears)
        green_mode(
            project_dir, ignore_globs, relevant_bears, bear_settings_obj,
            MAX_ARGS_GREEN_MODE,
            MAX_VALUES_GREEN_MODE,
            project_files,
            printer,
        )
        exit()

    print_relevant_bears(printer, relevant_bears)

    if args.non_interactive and not args.incomplete_sections:
        unusable_bears = get_non_optional_settings_bears(relevant_bears)
        remove_unusable_bears(relevant_bears, unusable_bears)
        print_relevant_bears(printer, relevant_bears, 'usable')

    settings = generate_settings(
        project_dir,
        project_files,
        ignore_globs,
        relevant_bears,
        extracted_information,
        args.incomplete_sections)

    write_coafile(printer, project_dir, settings)
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
def main():
    global MAX_ARGS_GREEN_MODE, MAX_VALUES_GREEN_MODE
    arg_parser = _get_arg_parser()
    args = arg_parser.parse_args()

    logging.basicConfig(stream=sys.stdout)
    printer = ConsolePrinter()
    logging.getLogger(__name__)

    fpc = None
    project_dir = os.getcwd()

    if args.green_mode:
        args.no_filter_by_capabilities = None
        args.incomplete_sections = None
        if args.max_args:
            MAX_ARGS_GREEN_MODE = args.max_args
        if args.max_values:
            MAX_VALUES_GREEN_MODE = args.max_values

    if not args.green_mode and (args.max_args or args.max_values):
        logging.warning(' --max-args and --max-values can be used '
                        'only with --green-mode. The arguments will '
                        'be ignored.')

    if not args.non_interactive and not args.green_mode:
        fpc = FilePathCompleter()
        fpc.activate()
        print_welcome_message(printer)
        printer.print(PROJECT_DIR_HELP)
        project_dir = ask_question('What is your project directory?',
                                   default=project_dir,
                                   typecast=valid_path)
        fpc.deactivate()

    project_files, ignore_globs = get_project_files(None, printer, project_dir,
                                                    fpc, args.non_interactive)

    used_languages = list(get_used_languages(project_files))
    used_languages = ask_to_select_languages(used_languages, printer,
                                             args.non_interactive)

    extracted_information = collect_info(project_dir)

    relevant_bears = filter_relevant_bears(used_languages, printer, arg_parser,
                                           extracted_information)

    if args.green_mode:
        bear_settings_obj = collect_bear_settings(relevant_bears)
        green_mode(
            project_dir,
            ignore_globs,
            relevant_bears,
            bear_settings_obj,
            MAX_ARGS_GREEN_MODE,
            MAX_VALUES_GREEN_MODE,
            project_files,
            printer,
        )
        exit()

    print_relevant_bears(printer, relevant_bears)

    if args.non_interactive and not args.incomplete_sections:
        unusable_bears = get_non_optional_settings_bears(relevant_bears)
        remove_unusable_bears(relevant_bears, unusable_bears)
        print_relevant_bears(printer, relevant_bears, 'usable')

    settings = generate_settings(project_dir, project_files, ignore_globs,
                                 relevant_bears, extracted_information,
                                 args.incomplete_sections)

    write_coafile(printer, project_dir, settings)