def emit(self, record: logging.LogRecord) -> None:
     level_msg = color.format_color(
         f"[{record.levelname}]",
         LOG_LEVEL_COLORS[record.levelname],
         self.use_color,
     )
     output.write_line(f"{level_msg} {record.getMessage()}")
Exemplo n.º 2
0
 def emit(self, record):
     self.__write(
         "{0}{1}\n".format(
             color.format_color("[{0}]".format(record.levelname), LOG_LEVEL_COLORS[record.levelname], self.use_color)
             + " ",
             record.getMessage(),
         )
     )
Exemplo n.º 3
0
 def emit(self, record):
     self.__write(u'{0}{1}\n'.format(
         color.format_color(
             '[{0}]'.format(record.levelname),
             LOG_LEVEL_COLORS[record.levelname],
             self.use_color,
         ) + ' ',
         record.getMessage(),
     ))
Exemplo n.º 4
0
 def emit(self, record):
     self.__write('{}{}\n'.format(
         color.format_color(
             '[{}]'.format(record.levelname),
             LOG_LEVEL_COLORS[record.levelname],
             self.use_color,
         ) + ' ',
         record.getMessage(),
     ))
     sys.stdout.flush()
Exemplo n.º 5
0
 def emit(self, record):
     output.write_line(
         '{} {}'.format(
             color.format_color(
                 '[{}]'.format(record.levelname),
                 LOG_LEVEL_COLORS[record.levelname],
                 self.use_color,
             ),
             record.getMessage(),
         ), )
Exemplo n.º 6
0
def _run_single_hook(hook, repo, args, write, skips=frozenset()):
    filenames = get_filenames(args, hook['files'], hook['exclude'])
    if hook['id'] in skips:
        _print_user_skipped(hook, write, args)
        return 0
    elif not filenames and not hook['always_run']:
        _print_no_files_skipped(hook, write, args)
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    write(get_hook_message(_hook_msg_start(hook, args.verbose), end_len=6))
    sys.stdout.flush()

    diff_before = cmd_output('git', 'diff', retcode=None, encoding=None)
    retcode, stdout, stderr = repo.run_hook(hook, tuple(filenames))
    diff_after = cmd_output('git', 'diff', retcode=None, encoding=None)

    file_modifications = diff_before != diff_after

    # If the hook makes changes, fail the commit
    if file_modifications:
        retcode = 1

    if retcode:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    write(color.format_color(pass_fail, print_color, args.color) + '\n')

    if (stdout or stderr or file_modifications) and (retcode or args.verbose):
        write('hookid: {0}\n'.format(hook['id']))
        write('\n')

        # Print a message if failing due to file modifications
        if file_modifications:
            write('Files were modified by this hook.')

            if stdout or stderr:
                write(' Additional output:\n')

            write('\n')

        for output in (stdout, stderr):
            assert type(output) is bytes, type(output)
            if output.strip():
                write(output.strip() + b'\n')
        write('\n')

    return retcode
Exemplo n.º 7
0
def _run_single_hook(hook, repo, args, write, skips=frozenset()):
    filenames = get_filenames(args, hook['files'], hook['exclude'])
    if hook['id'] in skips:
        _print_user_skipped(hook, write, args)
        return 0
    elif not filenames:
        _print_no_files_skipped(hook, write, args)
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    write(get_hook_message(_hook_msg_start(hook, args.verbose), end_len=6))
    sys.stdout.flush()

    diff_before = cmd_output('git', 'diff', retcode=None, encoding=None)
    retcode, stdout, stderr = repo.run_hook(hook, filenames)
    diff_after = cmd_output('git', 'diff', retcode=None, encoding=None)

    file_modifications = diff_before != diff_after

    # If the hook makes changes, fail the commit
    if file_modifications:
        retcode = 1

    if retcode:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    write(color.format_color(pass_fail, print_color, args.color) + '\n')

    if (stdout or stderr or file_modifications) and (retcode or args.verbose):
        write('hookid: {0}\n'.format(hook['id']))
        write('\n')

        # Print a message if failing due to file modifications
        if file_modifications:
            write('Files were modified by this hook.')

            if stdout or stderr:
                write(' Additional output:\n')

            write('\n')

        for output in (stdout, stderr):
            assert type(output) is bytes, type(output)
            if output.strip():
                write(output.strip() + b'\n')
        write('\n')

    return retcode
Exemplo n.º 8
0
def get_hook_message(
        start,
        postfix='',
        end_msg=None,
        end_len=0,
        end_color=None,
        use_color=None,
        cols=COLS,
):
    """Prints a message for running a hook.

    This currently supports three approaches:

    # Print `start` followed by dots, leaving 6 characters at the end
    >>> print_hook_message('start', end_len=6)
    start...............................................................

    # Print `start` followed by dots with the end message colored if coloring
    # is specified and a newline afterwards
    >>> print_hook_message(
        'start',
        end_msg='end',
        end_color=color.RED,
        use_color=True,
    )
    start...................................................................end

    # Print `start` followed by dots, followed by the `postfix` message
    # uncolored, followed by the `end_msg` colored if specified and a newline
    # afterwards
    >>> print_hook_message(
        'start',
        postfix='postfix ',
        end_msg='end',
        end_color=color.RED,
        use_color=True,
    )
    start...........................................................postfix end
    """
    if bool(end_msg) == bool(end_len):
        raise ValueError('Expected one of (`end_msg`, `end_len`)')
    if end_msg is not None and (end_color is None or use_color is None):
        raise ValueError(
            '`end_color` and `use_color` are required with `end_msg`'
        )

    if end_len:
        return start + '.' * (cols - len(start) - end_len - 1)
    else:
        return '{0}{1}{2}{3}\n'.format(
            start,
            '.' * (cols - len(start) - len(postfix) - len(end_msg) - 1),
            postfix,
            color.format_color(end_msg, end_color, use_color),
        )
Exemplo n.º 9
0
def get_hook_message(
        start,
        postfix='',
        end_msg=None,
        end_len=0,
        end_color=None,
        use_color=None,
        cols=COLS,
):
    """Prints a message for running a hook.

    This currently supports three approaches:

    # Print `start` followed by dots, leaving 6 characters at the end
    >>> print_hook_message('start', end_len=6)
    start...............................................................

    # Print `start` followed by dots with the end message colored if coloring
    # is specified and a newline afterwards
    >>> print_hook_message(
        'start',
        end_msg='end',
        end_color=color.RED,
        use_color=True,
    )
    start...................................................................end

    # Print `start` followed by dots, followed by the `postfix` message
    # uncolored, followed by the `end_msg` colored if specified and a newline
    # afterwards
    >>> print_hook_message(
        'start',
        postfix='postfix ',
        end_msg='end',
        end_color=color.RED,
        use_color=True,
    )
    start...........................................................postfix end
    """
    if bool(end_msg) == bool(end_len):
        raise ValueError('Expected one of (`end_msg`, `end_len`)')
    if end_msg is not None and (end_color is None or use_color is None):
        raise ValueError(
            '`end_color` and `use_color` are required with `end_msg`'
        )

    if end_len:
        return start + '.' * (cols - len(start) - end_len - 1)
    else:
        return '{0}{1}{2}{3}\n'.format(
            start,
            '.' * (cols - len(start) - len(postfix) - len(end_msg) - 1),
            postfix,
            color.format_color(end_msg, end_color, use_color),
        )
Exemplo n.º 10
0
 def emit(self, record):
     output.write_line(
         '{}{}'.format(
             color.format_color(
                 '[{}]'.format(record.levelname),
                 LOG_LEVEL_COLORS[record.levelname],
                 self.use_color,
             ) + ' ',
             record.getMessage(),
         ),
     )
Exemplo n.º 11
0
def _full_msg(
    *,
    start: str,
    cols: int,
    end_msg: str,
    end_color: str,
    use_color: bool,
    postfix: str = '',
) -> str:
    dots = '.' * (cols - _len_cjk(start) - len(postfix) - len(end_msg) - 1)
    end = color.format_color(end_msg, end_color, use_color)
    return f'{start}{dots}{postfix}{end}\n'
Exemplo n.º 12
0
 def emit(self, record):
     self.__write(
         u'{0}{1}\n'.format(
             color.format_color(
                 '[{0}]'.format(record.levelname),
                 LOG_LEVEL_COLORS[record.levelname],
                 self.use_color,
             ) + ' ',
             record.getMessage(),
         )
     )
     sys.stdout.flush()
Exemplo n.º 13
0
def _run_single_hook(runner, repository, hook, args, write, skips=set()):
    if args.origin and args.source:
        get_filenames = git.get_files_matching(
            lambda: get_changed_files(args.origin, args.source), )
    elif args.files:
        get_filenames = git.get_files_matching(lambda: args.files)
    elif args.all_files:
        get_filenames = git.get_all_files_matching
    elif git.is_in_merge_conflict():
        get_filenames = git.get_conflicted_files_matching
    else:
        get_filenames = git.get_staged_files_matching

    filenames = get_filenames(hook['files'], hook['exclude'])
    if hook['id'] in skips:
        _print_user_skipped(hook, write, args)
        return 0
    elif not filenames:
        _print_no_files_skipped(hook, write, args)
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    write(get_hook_message(_hook_msg_start(hook, args.verbose), end_len=6))
    sys.stdout.flush()

    retcode, stdout, stderr = repository.run_hook(hook, filenames)

    if retcode != hook['expected_return_value']:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    write(color.format_color(pass_fail, print_color, args.color) + '\n')

    if (stdout or stderr) and (retcode or args.verbose):
        write('hookid: {0}\n'.format(hook['id']))
        write('\n')
        for output in (stdout, stderr):
            if output.strip():
                write(output.strip() + '\n')
        write('\n')

    return retcode
Exemplo n.º 14
0
def _run_single_hook(runner, repository, hook, args, write, skips=set()):
    if args.all_files:
        get_filenames = git.get_all_files_matching
    elif git.is_in_merge_conflict():
        get_filenames = git.get_conflicted_files_matching
    else:
        get_filenames = git.get_staged_files_matching

    filenames = get_filenames(hook['files'], hook['exclude'])
    if hook['id'] in skips:
        _print_user_skipped(hook, write, args)
        return 0
    elif not filenames:
        _print_no_files_skipped(hook, write, args)
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    write(get_hook_message(_hook_msg_start(hook, args.verbose), end_len=6))
    sys.stdout.flush()

    retcode, stdout, stderr = repository.run_hook(hook, filenames)

    if retcode != hook['expected_return_value']:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    write(color.format_color(pass_fail, print_color, args.color) + '\n')

    if (stdout or stderr) and (retcode or args.verbose):
        write('hookid: {0}\n'.format(hook['id']))
        write('\n')
        for output in (stdout, stderr):
            if output.strip():
                write(output.strip() + '\n')
        write('\n')

    return retcode
Exemplo n.º 15
0
def _run_single_hook(hook, repo, args, write, skips=frozenset()):
    filenames = get_filenames(args, hook['files'], hook['exclude'])
    if hook['id'] in skips:
        _print_user_skipped(hook, write, args)
        return 0
    elif not filenames:
        _print_no_files_skipped(hook, write, args)
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    write(get_hook_message(_hook_msg_start(hook, args.verbose), end_len=6))
    sys.stdout.flush()

    retcode, stdout, stderr = repo.run_hook(hook, filenames)

    if retcode != hook['expected_return_value']:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    write(color.format_color(pass_fail, print_color, args.color) + '\n')

    if (stdout or stderr) and (retcode or args.verbose):
        write('hookid: {0}\n'.format(hook['id']))
        write('\n')
        for output in (stdout, stderr):
            assert type(output) is bytes, type(output)
            if output.strip():
                write(output.strip() + b'\n')
        write('\n')

    return retcode
Exemplo n.º 16
0
def _subtle_line(s, use_color):
    output.write_line(color.format_color(s, color.SUBTLE, use_color))
Exemplo n.º 17
0
def _run_single_hook(classifier, hook, args, skips, cols):
    filenames = classifier.filenames_for_hook(hook)

    if hook.language == 'pcre':
        logger.warning(
            '`{}` (from {}) uses the deprecated pcre language.\n'
            'The pcre language is scheduled for removal in pre-commit 2.x.\n'
            'The pygrep language is a more portable (and usually drop-in) '
            'replacement.'.format(hook.id, hook.src),
        )

    if hook.id in skips or hook.alias in skips:
        output.write(
            get_hook_message(
                _hook_msg_start(hook, args.verbose),
                end_msg=SKIPPED,
                end_color=color.YELLOW,
                use_color=args.color,
                cols=cols,
            ),
        )
        return 0
    elif not filenames and not hook.always_run:
        output.write(
            get_hook_message(
                _hook_msg_start(hook, args.verbose),
                postfix=NO_FILES,
                end_msg=SKIPPED,
                end_color=color.TURQUOISE,
                use_color=args.color,
                cols=cols,
            ),
        )
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    output.write(
        get_hook_message(
            _hook_msg_start(hook, args.verbose), end_len=6, cols=cols,
        ),
    )
    sys.stdout.flush()

    diff_before = cmd_output(
        'git', 'diff', '--no-ext-diff', retcode=None, encoding=None,
    )
    retcode, stdout, stderr = hook.run(
        tuple(filenames) if hook.pass_filenames else (),
    )
    diff_after = cmd_output(
        'git', 'diff', '--no-ext-diff', retcode=None, encoding=None,
    )

    file_modifications = diff_before != diff_after

    # If the hook makes changes, fail the commit
    if file_modifications:
        retcode = 1

    if retcode:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    output.write_line(color.format_color(pass_fail, print_color, args.color))

    if (
            (stdout or stderr or file_modifications) and
            (retcode or args.verbose or hook.verbose)
    ):
        output.write_line('hookid: {}\n'.format(hook.id))

        # Print a message if failing due to file modifications
        if file_modifications:
            output.write('Files were modified by this hook.')

            if stdout or stderr:
                output.write_line(' Additional output:')

            output.write_line()

        for out in (stdout, stderr):
            assert type(out) is bytes, type(out)
            if out.strip():
                output.write_line(out.strip(), logfile_name=hook.log_file)
        output.write_line()

    return retcode
Exemplo n.º 18
0
def test_format_color(in_text, in_color, in_use_color, expected):
    ret = format_color(in_text, in_color, in_use_color)
    assert ret == expected
Exemplo n.º 19
0
def _run_single_hook(hook, repo, args, skips, cols):
    filenames = get_filenames(args, hook['files'], hook['exclude'])
    filenames = filter_filenames_by_types(
        filenames,
        hook['types'],
        hook['exclude_types'],
    )
    if hook['id'] in skips:
        output.write(
            get_hook_message(
                _hook_msg_start(hook, args.verbose),
                end_msg=SKIPPED,
                end_color=color.YELLOW,
                use_color=args.color,
                cols=cols,
            ))
        return 0
    elif not filenames and not hook['always_run']:
        output.write(
            get_hook_message(
                _hook_msg_start(hook, args.verbose),
                postfix=NO_FILES,
                end_msg=SKIPPED,
                end_color=color.TURQUOISE,
                use_color=args.color,
                cols=cols,
            ))
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    output.write(
        get_hook_message(
            _hook_msg_start(hook, args.verbose),
            end_len=6,
            cols=cols,
        ))
    sys.stdout.flush()

    diff_before = cmd_output(
        'git',
        'diff',
        '--no-ext-diff',
        retcode=None,
        encoding=None,
    )
    retcode, stdout, stderr = repo.run_hook(
        hook,
        tuple(filenames) if hook['pass_filenames'] else (),
    )
    diff_after = cmd_output(
        'git',
        'diff',
        '--no-ext-diff',
        retcode=None,
        encoding=None,
    )

    file_modifications = diff_before != diff_after

    # If the hook makes changes, fail the commit
    if file_modifications:
        retcode = 1

    if retcode:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    output.write_line(color.format_color(pass_fail, print_color, args.color))

    if (stdout or stderr or file_modifications) and (retcode or args.verbose):
        output.write_line('hookid: {}\n'.format(hook['id']))

        # Print a message if failing due to file modifications
        if file_modifications:
            output.write('Files were modified by this hook.')

            if stdout or stderr:
                output.write_line(' Additional output:')

            output.write_line()

        for out in (stdout, stderr):
            assert type(out) is bytes, type(out)
            if out.strip():
                output.write_line(out.strip(), logfile_name=hook['log_file'])
        output.write_line()

    return retcode
Exemplo n.º 20
0
def _run_single_hook(
    classifier: Classifier,
    hook: Hook,
    skips: Set[str],
    cols: int,
    diff_before: bytes,
    verbose: bool,
    use_color: bool,
) -> Tuple[bool, bytes]:
    filenames = classifier.filenames_for_hook(hook)

    if hook.id in skips or hook.alias in skips:
        output.write(
            _full_msg(
                start=hook.name,
                end_msg=SKIPPED,
                end_color=color.YELLOW,
                use_color=use_color,
                cols=cols,
            ), )
        duration = None
        retcode = 0
        diff_after = diff_before
        files_modified = False
        out = b''
    elif not filenames and not hook.always_run:
        output.write(
            _full_msg(
                start=hook.name,
                postfix=NO_FILES,
                end_msg=SKIPPED,
                end_color=color.TURQUOISE,
                use_color=use_color,
                cols=cols,
            ), )
        duration = None
        retcode = 0
        diff_after = diff_before
        files_modified = False
        out = b''
    else:
        # print hook and dots first in case the hook takes a while to run
        output.write(_start_msg(start=hook.name, end_len=6, cols=cols))

        if not hook.pass_filenames:
            filenames = ()
        time_before = time.time()
        language = languages[hook.language]
        retcode, out = language.run_hook(hook, filenames, use_color)
        duration = round(time.time() - time_before, 2) or 0
        diff_after = _get_diff()

        # if the hook makes changes, fail the commit
        files_modified = diff_before != diff_after

        if retcode or files_modified:
            print_color = color.RED
            status = 'Failed'
        else:
            print_color = color.GREEN
            status = 'Passed'

        output.write_line(color.format_color(status, print_color, use_color))

    if verbose or hook.verbose or retcode or files_modified:
        _subtle_line(f'- hook id: {hook.id}', use_color)

        if (verbose or hook.verbose) and duration is not None:
            _subtle_line(f'- duration: {duration}s', use_color)

        if retcode:
            _subtle_line(f'- exit code: {retcode}', use_color)

        # Print a message if failing due to file modifications
        if files_modified:
            _subtle_line('- files were modified by this hook', use_color)

        if out.strip():
            output.write_line()
            output.write_line_b(out.strip(), logfile_name=hook.log_file)
            output.write_line()

    return files_modified or bool(retcode), diff_after
Exemplo n.º 21
0
def _subtle_line(s: str, use_color: bool) -> None:
    output.write_line(color.format_color(s, color.SUBTLE, use_color))
Exemplo n.º 22
0
def _run_single_hook(filenames, hook, repo, args, skips, cols):
    include, exclude = hook['files'], hook['exclude']
    filenames = _filter_by_include_exclude(filenames, include, exclude)
    types, exclude_types = hook['types'], hook['exclude_types']
    filenames = _filter_by_types(filenames, types, exclude_types)

    if hook['language'] == 'pcre':
        logger.warning(
            '`{}` (from {}) uses the deprecated pcre language.\n'
            'The pcre language is scheduled for removal in pre-commit 2.x.\n'
            'The pygrep language is a more portable (and usually drop-in) '
            'replacement.'.format(hook['id'], repo.repo_config['repo']), )

    if hook['id'] in skips:
        output.write(
            get_hook_message(
                _hook_msg_start(hook, args.verbose),
                end_msg=SKIPPED,
                end_color=color.YELLOW,
                use_color=args.color,
                cols=cols,
            ))
        return 0
    elif not filenames and not hook['always_run']:
        output.write(
            get_hook_message(
                _hook_msg_start(hook, args.verbose),
                postfix=NO_FILES,
                end_msg=SKIPPED,
                end_color=color.TURQUOISE,
                use_color=args.color,
                cols=cols,
            ))
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    output.write(
        get_hook_message(
            _hook_msg_start(hook, args.verbose),
            end_len=6,
            cols=cols,
        ))
    sys.stdout.flush()

    diff_before = cmd_output(
        'git',
        'diff',
        '--no-ext-diff',
        retcode=None,
        encoding=None,
    )
    retcode, stdout, stderr = repo.run_hook(
        hook,
        tuple(filenames) if hook['pass_filenames'] else (),
    )
    diff_after = cmd_output(
        'git',
        'diff',
        '--no-ext-diff',
        retcode=None,
        encoding=None,
    )

    file_modifications = diff_before != diff_after

    # If the hook makes changes, fail the commit
    if file_modifications:
        retcode = 1

    if retcode:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    output.write_line(color.format_color(pass_fail, print_color, args.color))

    if ((stdout or stderr or file_modifications)
            and (retcode or args.verbose or hook['verbose'])):
        output.write_line('hookid: {}\n'.format(hook['id']))

        # Print a message if failing due to file modifications
        if file_modifications:
            output.write('Files were modified by this hook.')

            if stdout or stderr:
                output.write_line(' Additional output:')

            output.write_line()

        for out in (stdout, stderr):
            assert type(out) is bytes, type(out)
            if out.strip():
                output.write_line(out.strip(), logfile_name=hook['log_file'])
        output.write_line()

    return retcode
Exemplo n.º 23
0
def _run_single_hook(hook, repo, args, skips, cols):
    filenames = get_filenames(args, hook.get('files', '^$'), hook['exclude'])
    if hook['id'] in skips:
        output.write(get_hook_message(
            _hook_msg_start(hook, args.verbose),
            end_msg=SKIPPED,
            end_color=color.YELLOW,
            use_color=args.color,
            cols=cols,
        ))
        return 0
    elif not filenames and not hook['always_run']:
        output.write(get_hook_message(
            _hook_msg_start(hook, args.verbose),
            postfix=NO_FILES,
            end_msg=SKIPPED,
            end_color=color.TURQUOISE,
            use_color=args.color,
            cols=cols,
        ))
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    output.write(get_hook_message(
        _hook_msg_start(hook, args.verbose), end_len=6, cols=cols,
    ))
    sys.stdout.flush()

    diff_before = cmd_output(
        'git', 'diff', '--no-ext-diff', retcode=None, encoding=None,
    )
    retcode, stdout, stderr = repo.run_hook(
        hook,
        tuple(filenames) if hook['pass_filenames'] else (),
    )
    diff_after = cmd_output(
        'git', 'diff', '--no-ext-diff', retcode=None, encoding=None,
    )

    file_modifications = diff_before != diff_after

    # If the hook makes changes, fail the commit
    if file_modifications:
        retcode = 1

    if retcode:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    output.write_line(color.format_color(pass_fail, print_color, args.color))

    if (stdout or stderr or file_modifications) and (retcode or args.verbose):
        output.write_line('hookid: {}\n'.format(hook['id']))

        # Print a message if failing due to file modifications
        if file_modifications:
            output.write('Files were modified by this hook.')

            if stdout or stderr:
                output.write_line(' Additional output:')

            output.write_line()

        for out in (stdout, stderr):
            assert type(out) is bytes, type(out)
            if out.strip():
                output.write_line(out.strip(), logfile_name=hook['log_file'])
        output.write_line()

    return retcode
Exemplo n.º 24
0
def test_format_color(in_text, in_color, in_use_color, expected):
    ret = format_color(in_text, in_color, in_use_color)
    assert ret == expected
Exemplo n.º 25
0
def _run_single_hook(classifier, hook, args, skips, cols, use_color):
    filenames = classifier.filenames_for_hook(hook)

    if hook.language == 'pcre':
        logger.warning(
            '`{}` (from {}) uses the deprecated pcre language.\n'
            'The pcre language is scheduled for removal in pre-commit 2.x.\n'
            'The pygrep language is a more portable (and usually drop-in) '
            'replacement.'.format(hook.id, hook.src), )

    if hook.id in skips or hook.alias in skips:
        output.write(
            get_hook_message(
                _hook_msg_start(hook, args.verbose),
                end_msg=SKIPPED,
                end_color=color.YELLOW,
                use_color=args.color,
                cols=cols,
            ), )
        return 0
    elif not filenames and not hook.always_run:
        output.write(
            get_hook_message(
                _hook_msg_start(hook, args.verbose),
                postfix=NO_FILES,
                end_msg=SKIPPED,
                end_color=color.TURQUOISE,
                use_color=args.color,
                cols=cols,
            ), )
        return 0

    # Print the hook and the dots first in case the hook takes hella long to
    # run.
    output.write(
        get_hook_message(
            _hook_msg_start(hook, args.verbose),
            end_len=6,
            cols=cols,
        ), )
    sys.stdout.flush()

    diff_before = cmd_output_b('git', 'diff', '--no-ext-diff', retcode=None)
    filenames = tuple(filenames) if hook.pass_filenames else ()
    retcode, out = hook.run(filenames, use_color)
    diff_after = cmd_output_b('git', 'diff', '--no-ext-diff', retcode=None)

    file_modifications = diff_before != diff_after

    # If the hook makes changes, fail the commit
    if file_modifications:
        retcode = 1

    if retcode:
        retcode = 1
        print_color = color.RED
        pass_fail = 'Failed'
    else:
        retcode = 0
        print_color = color.GREEN
        pass_fail = 'Passed'

    output.write_line(color.format_color(pass_fail, print_color, args.color))

    if ((out or file_modifications)
            and (retcode or args.verbose or hook.verbose)):
        output.write_line('hookid: {}\n'.format(hook.id))

        # Print a message if failing due to file modifications
        if file_modifications:
            output.write('Files were modified by this hook.')

            if out:
                output.write_line(' Additional output:')

            output.write_line()

        if out.strip():
            output.write_line(out.strip(), logfile_name=hook.log_file)
        output.write_line()

    return retcode
Exemplo n.º 26
0
def _run_single_hook(classifier, hook, skips, cols, verbose, use_color):
    filenames = classifier.filenames_for_hook(hook)

    if hook.id in skips or hook.alias in skips:
        output.write(
            get_hook_message(
                hook.name,
                end_msg=SKIPPED,
                end_color=color.YELLOW,
                use_color=use_color,
                cols=cols,
            ), )
        duration = None
        retcode = 0
        files_modified = False
        out = b''
    elif not filenames and not hook.always_run:
        output.write(
            get_hook_message(
                hook.name,
                postfix=NO_FILES,
                end_msg=SKIPPED,
                end_color=color.TURQUOISE,
                use_color=use_color,
                cols=cols,
            ), )
        duration = None
        retcode = 0
        files_modified = False
        out = b''
    else:
        # print hook and dots first in case the hook takes a while to run
        output.write(get_hook_message(hook.name, end_len=6, cols=cols))

        diff_cmd = ('git', 'diff', '--no-ext-diff')
        diff_before = cmd_output_b(*diff_cmd, retcode=None)
        filenames = tuple(filenames) if hook.pass_filenames else ()
        time_before = time.time()
        retcode, out = hook.run(filenames, use_color)
        duration = round(time.time() - time_before, 2) or 0
        diff_after = cmd_output_b(*diff_cmd, retcode=None)

        # if the hook makes changes, fail the commit
        files_modified = diff_before != diff_after

        if retcode or files_modified:
            print_color = color.RED
            status = 'Failed'
        else:
            print_color = color.GREEN
            status = 'Passed'

        output.write_line(color.format_color(status, print_color, use_color))

    if verbose or hook.verbose or retcode or files_modified:
        _subtle_line('- hook id: {}'.format(hook.id), use_color)

        if (verbose or hook.verbose) and duration is not None:
            _subtle_line('- duration: {}s'.format(duration), use_color)

        if retcode:
            _subtle_line('- exit code: {}'.format(retcode), use_color)

        # Print a message if failing due to file modifications
        if files_modified:
            _subtle_line('- files were modified by this hook', use_color)

        if out.strip():
            output.write_line()
            output.write_line(out.strip(), logfile_name=hook.log_file)
            output.write_line()

    return files_modified or bool(retcode)