예제 #1
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
예제 #2
0
def print_result(console_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict,
                 interactive=True):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    :param interactive:     Variable to check whether or not to
                            offer the user actions interactively.
    """
    no_color = not console_printer.print_colored
    if not isinstance(result, Result):
        logging.warning('One of the results can not be printed since it is '
                        'not a valid derivative of the coala result '
                        'class.')
        return

    if hasattr(section, 'name'):
        console_printer.print(
            '\n**** {bear} [Section: {section}] ****\n'.format(
                bear=result.origin, section=section.name),
            color=RESULT_SEVERITY_COLORS[result.severity])
    else:
        console_printer.print(
            '\n**** {bear} [Section: {section}] ****\n'.format(
                bear=result.origin, section='<empty>'),
            color=RESULT_SEVERITY_COLORS[result.severity])
    console_printer.print(format_lines(
        '[Severity: {sev}]'.format(
            sev=RESULT_SEVERITY.__str__(result.severity)), '!'),
                          color=RESULT_SEVERITY_COLORS[result.severity])
    lexer = TextLexer()
    result.message = highlight_text(no_color, result.message, lexer,
                                    BackgroundMessageStyle)
    console_printer.print(format_lines(result.message, symbol='!'))

    if interactive:
        cli_actions = CLI_ACTIONS
        show_patch_action = ShowPatchAction()
        if show_patch_action.is_applicable(result, file_dict,
                                           file_diff_dict) is True:
            diff_size = sum(len(diff) for diff in result.diffs.values())
            if diff_size <= DIFF_EXCERPT_MAX_SIZE:
                show_patch_action.apply_from_section(result, file_dict,
                                                     file_diff_dict, section)
                cli_actions = tuple(action for action in cli_actions
                                    if not isinstance(action, ShowPatchAction))
            else:
                print_diffs_info(result.diffs, console_printer)
        acquire_actions_and_apply(console_printer, section, file_diff_dict,
                                  result, file_dict, cli_actions)
예제 #3
0
def provide_all_actions():
    return [DoNothingAction().get_metadata().desc,
            ShowPatchAction().get_metadata().desc,
            ApplyPatchAction().get_metadata().desc,
            IgnoreResultAction().get_metadata().desc,
            OpenEditorAction().get_metadata().desc,
            PrintAspectAction().get_metadata().desc,
            PrintDebugMessageAction().get_metadata().desc,
            PrintMoreInfoAction().get_metadata().desc]
예제 #4
0
def print_result(console_printer,
                 log_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict,
                 interactive=True):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param log_printer:     Printer responsible for logging the messages.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    :interactive:           Variable to check wether or not to
                            offer the user actions interactively.
    """
    if not isinstance(result, Result):
        log_printer.warn("One of the results can not be printed since it is "
                         "not a valid derivative of the coala result "
                         "class.")
        return

    console_printer.print(format_lines("[{sev}] {bear}:".format(
        sev=RESULT_SEVERITY.__str__(result.severity), bear=result.origin)),
        color=RESULT_SEVERITY_COLORS[result.severity])
    lexer = TextLexer()
    result.message = highlight_text(result.message, lexer,
                                    BackgroundMessageStyle)
    console_printer.print(format_lines(result.message))

    if interactive:
        cli_actions = CLI_ACTIONS
        show_patch_action = ShowPatchAction()
        if show_patch_action.is_applicable(result, file_dict, file_diff_dict):
            diff_size = sum(len(diff) for diff in result.diffs.values())
            if diff_size <= DIFF_EXCERPT_MAX_SIZE:
                show_patch_action.apply_from_section(result,
                                                     file_dict,
                                                     file_diff_dict,
                                                     section)
                cli_actions = tuple(action for action in cli_actions
                                    if not isinstance(action, ShowPatchAction))
            else:
                print_diffs_info(result.diffs, console_printer)
        acquire_actions_and_apply(console_printer,
                                  log_printer,
                                  section,
                                  file_diff_dict,
                                  result,
                                  file_dict,
                                  cli_actions)
예제 #5
0
 def apply(self,
           result,
           original_file_dict,
           file_diff_dict,
           no_color: bool = False):
     self.diffs, result.diffs = result.diffs, self.diffs
     self.update_description(result)
     return ShowPatchAction().apply(result,
                                    original_file_dict,
                                    file_diff_dict,
                                    no_color=no_color)
예제 #6
0
    def setUp(self):
        self.uut = ShowPatchAction()
        self.file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']}
        self.diff_dict = {'a': Diff(self.file_dict['a']),
                          'b': Diff(self.file_dict['b'])}
        self.diff_dict['a'].add_lines(1, ['test\n'])
        self.diff_dict['a'].delete_line(3)
        self.diff_dict['b'].add_lines(0, ['first\n'])

        self.test_result = Result('origin', 'message', diffs=self.diff_dict)
        self.section = Section('name')
        self.section.append(Setting('colored', 'false'))
예제 #7
0
    def setUp(self):
        self.uut = ShowPatchAction()
        self.file_dict = {"a": ["a\n", "b\n", "c\n"], "b": ["old_first\n"]}
        diff_dict = {"a": Diff(self.file_dict['a']),
                     "b": Diff(self.file_dict['b'])}
        diff_dict["a"].add_lines(1, ["test\n"])
        diff_dict["a"].delete_line(3)
        diff_dict["b"].add_lines(0, ["first\n"])

        self.test_result = Result("origin", "message", diffs=diff_dict)
        self.section = Section("name")
        self.section.append(Setting("colored", "false"))
예제 #8
0
                         "that doesn't seem to exist in the given file.")
STR_PROJECT_WIDE = 'Project wide:'
STR_ENTER_NUMBER = ('Enter number (Ctrl-'
                    f"{'Z' if platform.system() == 'Windows' else 'D'} "
                    'to exit): ')
STR_INVALID_OPTION = '*** Invalid Option: ({}) ***\n'
WARNING_COLOR = 'red'
FILE_NAME_COLOR = 'blue'
FILE_LINES_COLOR = 'blue'
CAPABILITY_COLOR = 'green'
HIGHLIGHTED_CODE_COLOR = 'red'
SUCCESS_COLOR = 'green'
REQUIRED_SETTINGS_COLOR = 'green'
CLI_ACTIONS = (OpenEditorAction(), ApplyPatchAction(),
               PrintDebugMessageAction(), PrintMoreInfoAction(),
               ShowPatchAction(), IgnoreResultAction(),
               ShowAppliedPatchesAction(), GeneratePatchesAction())
DIFF_EXCERPT_MAX_SIZE = 4


def color_letter(console_printer, line):
    x = line.find('(')
    if x == -1:
        letter = ''
        y = x + 1
    else:
        letter = line[x + 1]
        y = x + 2
    warn = line.rfind('[')
    if warn == 0:
        warn = len(line)
                         'cannot be printed because it refers to a line '
                         "that doesn't seem to exist in the given file.")
STR_PROJECT_WIDE = 'Project wide:'
STR_ENTER_NUMBER = 'Enter number (Ctrl-{} to exit): '.format(
    'Z' if platform.system() == 'Windows' else 'D')
FILE_NAME_COLOR = 'blue'
FILE_LINES_COLOR = 'blue'
CAPABILITY_COLOR = 'green'
HIGHLIGHTED_CODE_COLOR = 'red'
SUCCESS_COLOR = 'green'
REQUIRED_SETTINGS_COLOR = 'green'
CLI_ACTIONS = (OpenEditorAction(),
               ApplyPatchAction(),
               PrintDebugMessageAction(),
               PrintMoreInfoAction(),
               ShowPatchAction(),
               IgnoreResultAction(),
               ShowAppliedPatchesAction(),
               GeneratePatchesAction())
DIFF_EXCERPT_MAX_SIZE = 4


def color_letter(console_printer, line):
    x = -1
    y = -1
    letter = ''
    for i, l in enumerate(line, 0):
        if line[i] == '(':
            x = i
        if line[i] == ')':
            y = i
예제 #10
0
                           'needed by {} for section \"{}\": ')
STR_LINE_DOESNT_EXIST = ('The line belonging to the following result '
                         'cannot be printed because it refers to a line '
                         "that doesn't seem to exist in the given file.")
STR_PROJECT_WIDE = 'Project wide:'
STR_ENTER_NUMBER = 'Enter number (Ctrl-{} to exit): '.format(
    'Z' if platform.system() == 'Windows' else 'D')
FILE_NAME_COLOR = 'blue'
FILE_LINES_COLOR = 'blue'
CAPABILITY_COLOR = 'green'
HIGHLIGHTED_CODE_COLOR = 'red'
SUCCESS_COLOR = 'green'
REQUIRED_SETTINGS_COLOR = 'green'
CLI_ACTIONS = (OpenEditorAction(), ApplyPatchAction(),
               PrintDebugMessageAction(), PrintMoreInfoAction(),
               ShowPatchAction(), IgnoreResultAction(), ChainPatchAction())
DIFF_EXCERPT_MAX_SIZE = 4


def format_lines(lines, symbol='', line_nr=''):
    def sym(x):
        return ']' if x is '[' else x

    return '\n'.join('{}{:>5}{} {}'.format(symbol, sym(symbol), line_nr, line)
                     for line in lines.rstrip('\n').split('\n'))


def print_section_beginning(console_printer, section):
    """
    Will be called after initialization current_section in
    begin_section()