示例#1
0
    def test_add_indent(self, mock_stdout):
        term = Terminal()

        i = 6
        expected_msg = ' ' * i + 'foo\n'

        term.add_indent(i)
        term.print('foo')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

        # clear the buffer
        mock_stdout.truncate(0)
        mock_stdout.seek(0)

        j = 4
        expected_msg = ' ' * (i + j) + 'bar\n'

        term.add_indent(j)
        term.print('bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)
示例#2
0
def check_hook_is_current(term: Terminal,
                          pre_commit_hook: PreCommitHook) -> None:
    if not pre_commit_hook.is_current_autohooks_pre_commit_hook():
        term.warning(
            'autohooks pre-commit hook is outdated. Please run '
            '\'autohooks activate --force\' to update your pre-commit '
            'hook.')
示例#3
0
    def test_print(self):
        term = Terminal()
        term.print('foo bar')

        # printed output at current indent location
        self.terminal_mock.location.assert_called_with(x=0)

        # an actual output has been generated
        self.print_mock.assert_called_with('foo bar')
示例#4
0
 def setUp(self):
     self.maxDiff = None
     # getting the bash-color-codes from the colorful module
     self.red = cf.red.style[0]
     self.green = cf.green.style[0]
     self.yellow = cf.yellow.style[0]
     self.cyan = cf.cyan.style[0]
     self.reset = cf.black.style[
         1]  # every colors second value is the reset value ...
     self.term = Terminal()
     self.term.get_width = MagicMock(return_value=80)
示例#5
0
    def test_print(self, mock_stdout):
        term = Terminal()

        expected_msg = 'foo bar\n'

        term.print('foo bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)
示例#6
0
 def setUp(self):
     self.maxDiff = 180
     # getting the bash-color-codes from the colorful module
     self.red = cf.red
     self.green = cf.green
     self.yellow = cf.yellow
     self.cyan = cf.cyan
     self.reset = cf.reset
     self.bold = cf.bold
     # every colors second value is the reset value ...
     self.term = Terminal()
     self.term.get_width = MagicMock(return_value=80)
示例#7
0
    def test_warning(self):
        term = Terminal()
        term.warning('foo bar')

        # width has been calculated
        self.width_mock.assert_called_with()

        # 68 == 80 - 5 - len('warning')
        self.terminal_mock.move_x.assert_called_with(68)

        # warning has been printed in yellow
        self.terminal_mock.yellow.assert_called_with('warning')

        # an actual output has been generated
        self.assertCalled(self.print_mock)
示例#8
0
    def test_ok(self):
        term = Terminal()
        term.ok('foo bar')

        # width has been calculated
        self.width_mock.assert_called_with()

        # 73 == 80 - 5 - len('ok')
        self.terminal_mock.move_x.assert_called_with(73)

        # ok has been printed in green
        self.terminal_mock.green.assert_called_with('ok')

        # an actual output has been generated
        self.assertCalled(self.print_mock)
示例#9
0
    def test_info(self):
        term = Terminal()
        term.info('foo bar')

        # width has been calculated
        self.width_mock.assert_called_with()

        # 71 == 80 - 5 - len('info')
        self.terminal_mock.move_x.assert_called_with(71)

        # info has been printed in cyan
        self.terminal_mock.cyan.assert_called_with('info')

        # an actual output has been generated
        self.assertCalled(self.print_mock)
示例#10
0
    def test_error(self):
        term = Terminal()
        term.error('foo bar')

        # width has been calculated
        self.width_mock.assert_called_with()

        # 70 == 80 - 5 - len('error')
        self.terminal_mock.move_x.assert_called_with(70)

        # error has been printed in red
        self.terminal_mock.red.assert_called_with('error')

        # an actual output has been generated
        self.assertCalled(self.print_mock)
示例#11
0
    def test_fail(self):
        term = Terminal()
        term.fail('foo bar')

        # width has been calculated
        self.width_mock.assert_called_with()

        # 71 == 80 - 5 - len('fail')
        self.terminal_mock.move_x.assert_called_with(71)

        # fail has been printed in red
        self.terminal_mock.red.assert_called_with('fail')

        # an actual output has been generated
        self.assertCalled(self.print_mock)
示例#12
0
    def test_with_indent(self, mock_stdout):
        term = Terminal()

        expected_msg = '  foo\n'

        with term.indent(2):
            term.print('foo')

            ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

        # clear the buffer
        mock_stdout.truncate(0)
        mock_stdout.seek(0)

        term.print('bar')

        expected_msg = 'bar\n'

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)
示例#13
0
    def test_with_indent(self):
        term = Terminal()

        with term.indent(2):
            term.print('foo')

        self.terminal_mock.location.assert_called_with(x=2)
        self.print_mock.assert_called_with('foo')

        term.print('bar')

        # indentation has been removed
        self.terminal_mock.location.assert_called_with(x=0)
        self.print_mock.assert_called_with('bar')
示例#14
0
def main():
    parser = argparse.ArgumentParser(description=DESCRIPTION)
    parser.add_argument(
        '--version',
        action='version',
        version='%(prog)s {}'.format(version),
    )

    subparsers = parser.add_subparsers(dest='command')
    activate_parser = subparsers.add_parser(
        'activate', help='Activate the pre-commit hook.')
    activate_parser.add_argument(
        '-f',
        '--force',
        action='store_true',
        help='Force activation of hook even if a hook already exists',
    )
    activate_parser.add_argument(
        '-m',
        '--mode',
        dest='mode',
        choices=[
            str(Mode.PYTHONPATH),
            str(Mode.PYTHONPATHVENV),
            str(Mode.PIPENV),
            str(Mode.POETRY)
        ],
        help='Mode for loading autohooks during hook execution. Either load '
        'autohooks from the PYTHON_PATH, via pipenv or via poetry.',
    )

    subparsers.add_parser('check', help='Check installed pre-commit hook')

    args = parser.parse_args()

    if not args.command:
        parser.print_usage()

    term = Terminal()
    if args.command == 'activate':
        install_hooks(term, args)
    elif args.command == 'check':
        check_hooks(term)
示例#15
0
def check_config(
    term: Terminal,
    pyproject_toml: Path,
    pre_commit_hook: PreCommitHook,
) -> None:
    if not pyproject_toml.exists():
        term.error(
            f'Missing {str(pyproject_toml)} file. Please add a pyproject.toml '
            f'file and include a "{AUTOHOOKS_SECTION}" section.'
        )
    else:
        config = load_config_from_pyproject_toml(pyproject_toml)
        if not config.is_autohooks_enabled():
            term.error(
                f'autohooks is not enabled in your {str(pyproject_toml)} file.'
                f' Please add a "{AUTOHOOKS_SECTION}" section.'
            )
        elif pre_commit_hook.exists():
            config_mode = config.get_mode()
            hook_mode = pre_commit_hook.read_mode()

            if config_mode == Mode.UNDEFINED:
                term.warning(
                    f'autohooks mode is not defined in {str(pyproject_toml)}.'
                )
            elif config_mode == Mode.UNKNOWN:
                term.warning(
                    f'Unknown autohooks mode in {str(pyproject_toml)}.'
                )

            if (
                config_mode.get_effective_mode()
                != hook_mode.get_effective_mode()
            ):
                term.warning(
                    f'autohooks mode "{str(hook_mode)}" in pre-commit '
                    f'hook {str(pre_commit_hook)} differs from '
                    f'mode "{str(config_mode)}" in {str(pyproject_toml)}.'
                )

            term.info(
                f'Using autohooks mode "{str(hook_mode.get_effective_mode())}".'
            )

            plugins = config.get_pre_commit_script_names()
            if not plugins:
                term.error(
                    'No autohooks plugin is activated in '
                    f'{str(pyproject_toml)} for your pre commit hook. Please '
                    'add a "pre-commit = [plugin1, plugin2]" setting.'
                )
            else:
                with autohooks_module_path():
                    for name in plugins:
                        try:
                            plugin = load_plugin(name)
                            if not has_precommit_function(plugin):
                                term.error(
                                    f'Plugin "{name}" has no precommit '
                                    'function. The function is required to run'
                                    ' the plugin as git pre commit hook.'
                                )
                            elif not has_precommit_parameters(plugin):
                                term.warning(
                                    f'Plugin "{name}" uses a deprecated '
                                    'signature for its precommit function. It '
                                    'is missing the **kwargs parameter.'
                                )
                            else:
                                term.ok(f'Plugin "{name}" active and loadable.')
                        except ImportError as e:
                            term.error(
                                f'"{name}" is not a valid autohooks '
                                f'plugin. {e}'
                            )
示例#16
0
def check_pre_commit_hook(
    term: Terminal, pre_commit_hook: PreCommitHook
) -> None:
    if pre_commit_hook.exists():
        if pre_commit_hook.is_autohooks_pre_commit_hook():
            term.ok('autohooks pre-commit hook is active.')

            if pre_commit_hook.is_current_autohooks_pre_commit_hook():
                term.ok('autohooks pre-commit hook is up-to-date.')
            else:
                term.warning(
                    'autohooks pre-commit hook is outdated. Please run '
                    '\'autohooks activate --force\' to update your pre-commit '
                    'hook.'
                )

            hook_mode = pre_commit_hook.read_mode()
            if hook_mode == Mode.UNKNOWN:
                term.warning(
                    f'Unknown autohooks mode in {str(pre_commit_hook)}. '
                    f'Falling back to "{str(hook_mode.get_effective_mode())}" '
                    'mode.'
                )
        else:
            term.error(
                'autohooks pre-commit hook is not active. But a different '
                f'pre-commit hook has been found at {str(pre_commit_hook)}.'
            )

    else:
        term.error(
            'autohooks pre-commit hook not active. Please run \'autohooks '
            'activate\'.'
        )
示例#17
0
def check_config(
    term: Terminal, pyproject_toml: Path, pre_commit_hook: PreCommitHook,
) -> None:
    if not pyproject_toml.exists():
        term.error(
            'Missing {} file. Please add a pyproject.toml file and include '
            'a "{}" section.'.format(str(pyproject_toml), AUTOHOOKS_SECTION)
        )
    else:
        config = load_config_from_pyproject_toml(pyproject_toml)
        if not config.is_autohooks_enabled():
            term.error(
                'autohooks is not enabled in your {} file. Please add '
                'a "{}" section.'.format(str(pyproject_toml), AUTOHOOKS_SECTION)
            )
        elif pre_commit_hook.exists():
            config_mode = config.get_mode()
            hook_mode = pre_commit_hook.read_mode()

            if config_mode == Mode.UNDEFINED:
                term.warning(
                    'autohooks mode is not defined in {}.'.format(
                        str(pyproject_toml)
                    )
                )
            elif config_mode == Mode.UNKNOWN:
                term.warning(
                    'Unknown autohooks mode in {}.'.format(str(pyproject_toml))
                )

            if (
                config_mode.get_effective_mode()
                != hook_mode.get_effective_mode()
            ):
                term.warning(
                    'autohooks mode "{}" in pre-commit hook {} differs from '
                    'mode "{}" in {}.'.format(
                        str(hook_mode),
                        str(pre_commit_hook),
                        str(config_mode),
                        str(pyproject_toml),
                    )
                )

            term.info(
                'Using autohooks mode "{}".'.format(
                    str(hook_mode.get_effective_mode())
                )
            )

            plugins = config.get_pre_commit_script_names()
            if not plugins:
                term.error(
                    'No autohooks plugin is activated in {} for your pre '
                    'commit hook. Please add a '
                    '"pre-commit = [plugin1, plugin2]" '
                    'setting.'.format(str(pyproject_toml))
                )
            else:
                with autohooks_module_path():
                    for name in plugins:
                        try:
                            plugin = load_plugin(name)
                            if not has_precommit_function(plugin):
                                term.error(
                                    'Plugin "{}" has no precommit function. '
                                    'The function is required to run the '
                                    'plugin as git pre commit hook.'.format(
                                        name
                                    )
                                )
                            elif not has_precommit_parameters(plugin):
                                term.warning(
                                    'Plugin "{}" uses a deprecated signature '
                                    'for its precommit function. It is missing '
                                    'the **kwargs parameter.'.format(name)
                                )
                            else:
                                term.ok(
                                    'Plugin "{}" active and loadable.'.format(
                                        name
                                    )
                                )
                        except ImportError as e:
                            term.error(
                                '"{}" is not a valid autohooks '
                                'plugin. {}'.format(name, e)
                            )
示例#18
0
def install_hooks(term: Terminal, args: Namespace) -> None:
    pre_commit_hook = PreCommitHook()
    pyproject_toml = get_pyproject_toml_path()
    config = load_config_from_pyproject_toml(pyproject_toml)

    if pre_commit_hook.exists() and not args.force:
        term.ok(
            'autohooks pre-commit hook is already'
            f' installed at {str(pre_commit_hook)}.'
        )
        with term.indent():
            term.print()
            term.info(
                "Run 'autohooks activate --force' to override the current "
                "installed pre-commit hook."
            )
            term.info(
                "Run 'autohooks check' to validate the current status of "
                "the installed pre-commit hook."
            )
    else:
        if not config.is_autohooks_enabled():
            term.warning(
                f'autohooks is not enabled in your {str(pyproject_toml)} '
                'file. Run \'autohooks check\' for more details.'
            )

        if args.mode:
            mode = Mode.from_string(args.mode)
        else:
            mode = config.get_mode()

        pre_commit_hook.write(mode=mode)

        term.ok(
            f'autohooks pre-commit hook installed at {str(pre_commit_hook)}'
            f' using {str(mode.get_effective_mode())} mode.'
        )
示例#19
0
class TerminalTestCase(unittest.TestCase):
    def setUp(self):
        self.maxDiff = 180
        # getting the bash-color-codes from the colorful module
        self.red = cf.red
        self.green = cf.green
        self.yellow = cf.yellow
        self.cyan = cf.cyan
        self.reset = cf.reset
        self.bold = cf.bold
        # every colors second value is the reset value ...
        self.term = Terminal()
        self.term.get_width = MagicMock(return_value=80)

    @patch('sys.stdout', new_callable=StringIO)
    def test_error(self, mock_stdout):
        status = '{} '.format(self.red(Signs.ERROR))
        msg = 'foo bar'

        expected_msg = (self.reset('{}{}'.format(status, msg)).styled_string +
                        '\n')
        expected_len = len(expected_msg)

        self.term.error(msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(ret, expected_msg)
        self.assertEqual(len(ret), expected_len)

    @patch('sys.stdout', new_callable=StringIO)
    def test_fail(self, mock_stdout):
        status = '{} '.format(self.red(Signs.FAIL))
        msg = 'foo bar baz'

        expected_msg = (self.reset('{}{}'.format(status, msg)).styled_string +
                        '\n')
        expected_len = len(expected_msg)

        self.term.fail(msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(ret, expected_msg)
        self.assertEqual(len(ret), expected_len)

    @patch('sys.stdout', new_callable=StringIO)
    def test_info(self, mock_stdout):
        status = '{} '.format(self.cyan(Signs.INFO))
        msg = 'foo bar'

        expected_msg = (self.reset('{}{}'.format(status, msg)).styled_string +
                        '\n')
        expected_len = len(expected_msg)

        self.term.info(msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(ret, expected_msg)
        self.assertEqual(len(ret), expected_len)

    @patch('sys.stdout', new_callable=StringIO)
    def test_bold_info(self, mock_stdout):
        status = '{} '.format(self.cyan(Signs.INFO))
        msg = 'bold foo bar'

        expected_msg = (self.bold('{}{}'.format(status, msg)).styled_string +
                        '\n')
        expected_len = len(expected_msg)

        self.term.bold_info(msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(ret, expected_msg)
        self.assertEqual(len(ret), expected_len)

    @patch('sys.stdout', new_callable=StringIO)
    def test_ok(self, mock_stdout):
        status = '{} '.format(self.green(Signs.OK))
        msg = 'foo bar'

        expected_msg = (self.reset('{}{}'.format(status, msg)).styled_string +
                        '\n')
        expected_len = len(expected_msg)

        self.term.ok(msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(ret, expected_msg)
        self.assertEqual(len(ret), expected_len)

    @patch('sys.stdout', new_callable=StringIO)
    def test_warning(self, mock_stdout):
        msg = 'foo bar'

        status = '{} '.format(self.yellow(Signs.WARNING))

        expected_msg = (self.reset('{}{}'.format(status, msg)).styled_string +
                        '\n')
        expected_len = len(expected_msg)

        self.term.warning(msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(ret, expected_msg)
        self.assertEqual(len(ret), expected_len)

    @patch('sys.stdout', new_callable=StringIO)
    def test_print(self, mock_stdout):
        expected_msg = self.reset('  foo bar').styled_string + '\n'

        self.term.print('foo bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_add_indent(self, mock_stdout):
        i = 6
        expected_msg = self.reset(' ' * i + 'foo').styled_string + '\n'

        self.term.add_indent(i - 2)
        self.term.print('foo')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

        # clear the buffer
        mock_stdout.truncate(0)
        mock_stdout.seek(0)

        j = 4
        expected_msg = self.reset(' ' * (i + j) + 'bar').styled_string + '\n'

        self.term.add_indent(j)
        self.term.print('bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

        # clear the buffer
        mock_stdout.truncate(0)
        mock_stdout.seek(0)

    @patch('sys.stdout', new_callable=StringIO)
    def test_reset_indent(self, mock_stdout):
        i = 6
        expected_msg = self.reset(' ' * i + 'foo').styled_string + '\n'

        self.term.add_indent(i - 2)
        self.term.print('foo')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

        # clear the buffer
        mock_stdout.truncate(0)
        mock_stdout.seek(0)

        expected_msg = self.reset('  bar').styled_string + '\n'

        self.term.reset_indent()
        self.term.print('bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_with_indent(self, mock_stdout):
        expected_msg = self.reset('    foo').styled_string + '\n'

        with self.term.indent(2):
            self.term.print('foo')

            ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

        # clear the buffer
        mock_stdout.truncate(0)
        mock_stdout.seek(0)

        expected_msg = self.reset('  bar').styled_string + '\n'
        self.term.print('bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_long_msg(self, mock_stdout):
        long_msg = (
            'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, '
            'sed diam nonumy eirmod tempor invidunt ut labore et dolore magna'
            ' aliquyam erat, sed diam voluptua.')
        expected_msg = (self.reset(
            '  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, '
            'sed diam nonumy eirmo\n  d tempor invidunt ut labore et'
            ' dolore magna aliquyam erat, sed diam voluptua.').styled_string +
                        '\n')
        expected_len = len(expected_msg)

        self.term.print(long_msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(ret, expected_msg)
        self.assertEqual(len(ret), expected_len)
示例#20
0
class TerminalTestCase(unittest.TestCase):
    def setUp(self):
        self.maxDiff = None
        # getting the bash-color-codes from the colorful module
        self.red = cf.red.style[0]
        self.green = cf.green.style[0]
        self.yellow = cf.yellow.style[0]
        self.cyan = cf.cyan.style[0]
        self.reset = cf.black.style[
            1]  # every colors second value is the reset value ...
        self.term = Terminal()
        self.term.get_width = MagicMock(return_value=80)

    @patch('sys.stdout', new_callable=StringIO)
    def test_error(self, mock_stdout):
        msg = 'foo bar'

        width = self.term.get_width()
        expected_len = width + len(self.red) + len(self.reset) + 1

        status = '[ {}error{} ]\n'.format(self.red, self.reset)
        sep = ' ' * (expected_len - len(msg) - len(status))

        expected_msg = msg + sep + status

        self.term.error(msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), expected_len)
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_fail(self, mock_stdout):
        width = self.term.get_width()
        expected_len = width + len(self.red) + len(self.reset) + 1

        status = '[ {}fail{} ]\n'.format(self.red, self.reset)
        msg = 'foo bar baz'
        sep = ' ' * (expected_len - len(msg) - len(status))

        expected_msg = msg + sep + status

        self.term.fail('foo bar baz')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), expected_len)
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_info(self, mock_stdout):
        width = self.term.get_width()
        expected_len = width + len(self.cyan) + len(self.reset) + 1

        status = '[ {}info{} ]\n'.format(self.cyan, self.reset)
        msg = 'foo bar'
        sep = ' ' * (expected_len - len(msg) - len(status))

        expected_msg = msg + sep + status

        self.term.info('foo bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), expected_len)
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_ok(self, mock_stdout):
        width = self.term.get_width()
        expected_len = width + len(self.green) + len(self.reset) + 1

        status = '[ {}ok{} ]\n'.format(self.green, self.reset)
        msg = 'foo bar'
        sep = ' ' * (expected_len - len(msg) - len(status))
        expected_msg = msg + sep + status

        self.term.ok('foo bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), expected_len)
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_warning(self, mock_stdout):
        width = self.term.get_width()
        expected_len = width + len(self.yellow) + len(self.reset) + 1

        msg = 'foo bar'

        status = '[ {}warning{} ]\n'.format(self.yellow, self.reset)
        sep = ' ' * (expected_len - len(msg) - len(status))

        expected_msg = msg + sep + status

        self.term.warning(msg)

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), expected_len)
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_print(self, mock_stdout):
        term = Terminal()

        expected_msg = 'foo bar\n'

        term.print('foo bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_add_indent(self, mock_stdout):
        term = Terminal()

        i = 6
        expected_msg = ' ' * i + 'foo\n'

        term.add_indent(i)
        term.print('foo')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

        # clear the buffer
        mock_stdout.truncate(0)
        mock_stdout.seek(0)

        j = 4
        expected_msg = ' ' * (i + j) + 'bar\n'

        term.add_indent(j)
        term.print('bar')

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

    @patch('sys.stdout', new_callable=StringIO)
    def test_with_indent(self, mock_stdout):
        term = Terminal()

        expected_msg = '  foo\n'

        with term.indent(2):
            term.print('foo')

            ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)

        # clear the buffer
        mock_stdout.truncate(0)
        mock_stdout.seek(0)

        term.print('bar')

        expected_msg = 'bar\n'

        ret = mock_stdout.getvalue()

        self.assertEqual(len(ret), len(expected_msg))
        self.assertEqual(ret, expected_msg)
示例#21
0
def check_hook_mode(term: Terminal, config_mode: Mode,
                    hook_mode: Mode) -> None:
    if config_mode.get_effective_mode() != hook_mode.get_effective_mode():
        term.warning(
            f'autohooks mode "{str(hook_mode)}" in pre-commit hook differs '
            f'from mode "{str(config_mode)}" in pyproject.toml file.')
示例#22
0
def run() -> int:
    term = Terminal()

    _set_terminal(term)

    config = load_config_from_pyproject_toml()

    pre_commit_hook = PreCommitHook()

    check_hook_is_current(term, pre_commit_hook)

    if config.has_autohooks_config():
        check_hook_mode(term, config.get_mode(), pre_commit_hook.read_mode())

    plugins = get_project_autohooks_plugins_path()
    plugins_dir_name = str(plugins)

    if plugins.is_dir():
        sys.path.append(plugins_dir_name)

    term.bold_info('autohooks => pre-commit')

    with autohooks_module_path(), term.indent():
        for name in config.get_pre_commit_script_names():
            term.info(f'Running {name}')

            with term.indent():
                try:
                    plugin = load_plugin(name)
                    if not has_precommit_function(plugin):
                        term.fail(
                            f'No precommit function found in plugin {name}. '
                            'Your autohooks settings may be invalid.')
                        return 1

                    if has_precommit_parameters(plugin):
                        retval = plugin.precommit(config=config.get_config())
                    else:
                        term.warning(
                            'precommit function without kwargs is deprecated. '
                            f'Please update {name} to a newer version.')
                        retval = plugin.precommit()

                    if retval:
                        return retval

                except ImportError as e:
                    term.error('An error occurred while importing pre-commit '
                               f'hook {name}. {e}.')
                    return 1
                except Exception as e:  # pylint: disable=broad-except
                    term.error('An error occurred while running pre-commit '
                               f'hook {name}. {e}.')
                    return 1

    return 0
示例#23
0
文件: run.py 项目: y0urself/autohooks
def check_hook_mode(term: Terminal, config_mode: Mode,
                    hook_mode: Mode) -> None:
    if config_mode.get_effective_mode() != hook_mode.get_effective_mode():
        term.warning('autohooks mode "{}" in pre-commit hook differs from '
                     'mode "{}" in pyproject.toml file.'.format(
                         str(hook_mode), str(config_mode)))