Esempio n. 1
0
def test_get_root_deeper(tempdir_factory):
    path = git_dir(tempdir_factory)

    foo_path = os.path.join(path, "foo")
    os.mkdir(foo_path)
    with cwd(foo_path):
        assert git.get_root() == path
Esempio n. 2
0
def _adjust_args_and_chdir(args: argparse.Namespace) -> None:
    # `--config` was specified relative to the non-root working directory
    if os.path.exists(args.config):
        args.config = os.path.abspath(args.config)
    if args.command in {"run", "try-repo"}:
        args.files = [os.path.abspath(filename) for filename in args.files]
    if args.command == "try-repo" and os.path.exists(args.repo):
        args.repo = os.path.abspath(args.repo)

    try:
        toplevel = git.get_root()
    except CalledProcessError:
        raise FatalError(
            "git failed. Is it installed, and are you in a Git repository "
            "directory?", )
    else:
        if toplevel == "":  # pragma: no cover (old git)
            raise FatalError(
                "git toplevel unexpectedly empty! make sure you are not "
                "inside the `.git` directory of your repository.", )
        else:
            os.chdir(toplevel)

    args.config = os.path.relpath(args.config)
    if args.command in {"run", "try-repo"}:
        args.files = [os.path.relpath(filename) for filename in args.files]
    if args.command == "try-repo" and os.path.exists(args.repo):
        args.repo = os.path.relpath(args.repo)
Esempio n. 3
0
def test_get_root_deeper(tempdir_factory):
    path = git_dir(tempdir_factory)

    foo_path = os.path.join(path, 'foo')
    os.mkdir(foo_path)
    with cwd(foo_path):
        assert os.path.normcase(git.get_root()) == os.path.normcase(path)
Esempio n. 4
0
def test_get_root_deeper(tmpdir_factory):
    path = git_dir(tmpdir_factory)

    foo_path = os.path.join(path, 'foo')
    os.mkdir(foo_path)
    with cwd(foo_path):
        assert git.get_root() == path
Esempio n. 5
0
def test_get_root_deeper(tmpdir_factory):
    path = git_dir(tmpdir_factory)

    foo_path = os.path.join(path, 'foo')
    os.mkdir(foo_path)
    with local.cwd(foo_path):
        assert git.get_root() == path
Esempio n. 6
0
def test_get_root_deeper(tempdir_factory):
    path = git_dir(tempdir_factory)

    foo_path = os.path.join(path, 'foo')
    os.mkdir(foo_path)
    with cwd(foo_path):
        assert os.path.normcase(git.get_root()) == os.path.normcase(path)
Esempio n. 7
0
def _adjust_args_and_chdir(args):
    # `--config` was specified relative to the non-root working directory
    if os.path.exists(args.config):
        args.config = os.path.abspath(args.config)
    if args.command in {'run', 'try-repo'}:
        args.files = [os.path.abspath(filename) for filename in args.files]
    if args.command == 'try-repo' and os.path.exists(args.repo):
        args.repo = os.path.abspath(args.repo)

    try:
        toplevel = git.get_root()
    except CalledProcessError:
        raise FatalError(
            'git failed. Is it installed, and are you in a Git repository '
            'directory?', )
    else:
        if toplevel == '':  # pragma: no cover (old git)
            raise FatalError(
                'git toplevel unexpectedly empty! make sure you are not '
                'inside the `.git` directory of your repository.', )
        else:
            os.chdir(toplevel)

    args.config = os.path.relpath(args.config)
    if args.command in {'run', 'try-repo'}:
        args.files = [os.path.relpath(filename) for filename in args.files]
    if args.command == 'try-repo' and os.path.exists(args.repo):
        args.repo = os.path.relpath(args.repo)
Esempio n. 8
0
 def create(cls, config_file):
     """Creates a PreCommitRunner by doing the following:
         - Finds the root of the current git repository
         - chdir to that directory
     """
     root = git.get_root()
     os.chdir(root)
     return cls(root, config_file)
Esempio n. 9
0
 def create(cls):
     """Creates a PreCommitRunner by doing the following:
         - Finds the root of the current git repository
         - chdirs to that directory
     """
     root = git.get_root()
     os.chdir(root)
     return cls(root)
Esempio n. 10
0
 def _cmd_runner_from_deps(self, language_name, deps):
     """local repositories have a cmd runner per hook"""
     language = languages[language_name]
     # pcre / script / system / docker_image do not have environments so
     # they work out of the current directory
     if language.ENVIRONMENT_DIR is None:
         return PrefixedCommandRunner(git.get_root())
     else:
         return PrefixedCommandRunner(self.store.make_local(deps))
Esempio n. 11
0
def test_get_root_worktree_in_git(tmpdir):
    src = tmpdir.join('src').ensure_dir()
    cmd_output('git', 'init', str(src))
    git_commit(cwd=str(src))

    cmd_output('git', 'worktree', 'add', '.git/trees/foo', 'HEAD', cwd=src)

    with src.join('.git/trees/foo').as_cwd():
        assert git.get_root() == os.path.abspath('.')
Esempio n. 12
0
 def _cmd_runner_from_deps(self, language_name, deps):
     """local repositories have a cmd runner per hook"""
     language = languages[language_name]
     # pcre / script / system do not have environments so they work out
     # of the current directory
     if language.ENVIRONMENT_DIR is None:
         return PrefixedCommandRunner(git.get_root())
     else:
         return PrefixedCommandRunner(self.store.make_local(deps))
Esempio n. 13
0
 def _prefix_from_deps(self, language_name, deps):
     """local repositories have a prefix per hook"""
     language = languages[language_name]
     # pcre / pygrep / script / system / docker_image do not have
     # environments so they work out of the current directory
     if language.ENVIRONMENT_DIR is None:
         return Prefix(git.get_root())
     else:
         return Prefix(self.store.make_local(deps))
Esempio n. 14
0
def test_get_root_bare_worktree(tmpdir):
    src = tmpdir.join('src').ensure_dir()
    cmd_output('git', 'init', str(src))
    git_commit(cwd=str(src))

    bare = tmpdir.join('bare.git').ensure_dir()
    cmd_output('git', 'clone', '--bare', str(src), str(bare))

    cmd_output('git', 'worktree', 'add', 'foo', 'HEAD', cwd=bare)

    with bare.join('foo').as_cwd():
        assert git.get_root() == os.path.abspath('.')
Esempio n. 15
0
def _adjust_args_and_chdir(args: argparse.Namespace) -> None:
    # `--config` was specified relative to the non-root working directory
    if os.path.exists(args.config):
        args.config = os.path.abspath(args.config)
    if args.command in {'run', 'try-repo'}:
        args.files = [os.path.abspath(filename) for filename in args.files]
    if args.command == 'try-repo' and os.path.exists(args.repo):
        args.repo = os.path.abspath(args.repo)

    toplevel = git.get_root()
    os.chdir(toplevel)

    args.config = os.path.relpath(args.config)
    if args.command in {'run', 'try-repo'}:
        args.files = [os.path.relpath(filename) for filename in args.files]
    if args.command == 'try-repo' and os.path.exists(args.repo):
        args.repo = os.path.relpath(args.repo)
Esempio n. 16
0
def _adjust_args_and_chdir(args):
    # `--config` was specified relative to the non-root working directory
    if os.path.exists(args.config):
        args.config = os.path.abspath(args.config)
    if args.command in {'run', 'try-repo'}:
        args.files = [os.path.abspath(filename) for filename in args.files]
    if args.command == 'try-repo' and os.path.exists(args.repo):
        args.repo = os.path.abspath(args.repo)

    try:
        os.chdir(git.get_root())
    except CalledProcessError:
        raise FatalError(
            'git failed. Is it installed, and are you in a Git repository '
            'directory?', )

    args.config = os.path.relpath(args.config)
    if args.command in {'run', 'try-repo'}:
        args.files = [os.path.relpath(filename) for filename in args.files]
    if args.command == 'try-repo' and os.path.exists(args.repo):
        args.repo = os.path.relpath(args.repo)
Esempio n. 17
0
def _adjust_args_and_chdir(args):
    # `--config` was specified relative to the non-root working directory
    if os.path.exists(args.config):
        args.config = os.path.abspath(args.config)
    if args.command in {'run', 'try-repo'}:
        args.files = [os.path.abspath(filename) for filename in args.files]
    if args.command == 'try-repo' and os.path.exists(args.repo):
        args.repo = os.path.abspath(args.repo)

    try:
        os.chdir(git.get_root())
    except CalledProcessError:
        raise FatalError(
            'git failed. Is it installed, and are you in a Git repository '
            'directory?',
        )

    args.config = os.path.relpath(args.config)
    if args.command in {'run', 'try-repo'}:
        args.files = [os.path.relpath(filename) for filename in args.files]
    if args.command == 'try-repo' and os.path.exists(args.repo):
        args.repo = os.path.relpath(args.repo)
Esempio n. 18
0
def main(argv=None):
    argv = argv if argv is not None else sys.argv[1:]
    argv = [five.to_text(arg) for arg in argv]
    parser = argparse.ArgumentParser()

    # http://stackoverflow.com/a/8521644/812183
    parser.add_argument(
        '-V',
        '--version',
        action='version',
        version='%(prog)s {}'.format(C.VERSION),
    )

    subparsers = parser.add_subparsers(dest='command')

    install_parser = subparsers.add_parser(
        'install',
        help='Install the pre-commit script.',
    )
    _add_color_option(install_parser)
    _add_config_option(install_parser)
    install_parser.add_argument(
        '-f',
        '--overwrite',
        action='store_true',
        help='Overwrite existing hooks / remove migration mode.',
    )
    install_parser.add_argument(
        '--install-hooks',
        action='store_true',
        help=('Whether to install hook environments for all environments '
              'in the config file.'),
    )
    _add_hook_type_option(install_parser)
    install_parser.add_argument(
        '--allow-missing-config',
        action='store_true',
        default=False,
        help=('Whether to allow a missing `pre-commit` configuration file '
              'or exit with a failure code.'),
    )

    install_hooks_parser = subparsers.add_parser(
        'install-hooks',
        help=('Install hook environments for all environments in the config '
              'file.  You may find `pre-commit install --install-hooks` more '
              'useful.'),
    )
    _add_color_option(install_hooks_parser)
    _add_config_option(install_hooks_parser)

    uninstall_parser = subparsers.add_parser(
        'uninstall',
        help='Uninstall the pre-commit script.',
    )
    _add_color_option(uninstall_parser)
    _add_config_option(uninstall_parser)
    _add_hook_type_option(uninstall_parser)

    clean_parser = subparsers.add_parser(
        'clean',
        help='Clean out pre-commit files.',
    )
    _add_color_option(clean_parser)
    _add_config_option(clean_parser)
    autoupdate_parser = subparsers.add_parser(
        'autoupdate',
        help="Auto-update pre-commit config to the latest repos' versions.",
    )
    _add_color_option(autoupdate_parser)
    _add_config_option(autoupdate_parser)
    autoupdate_parser.add_argument(
        '--tags-only',
        action='store_true',
        help='LEGACY: for compatibility',
    )
    autoupdate_parser.add_argument(
        '--bleeding-edge',
        action='store_true',
        help=('Update to the bleeding edge of `master` instead of the latest '
              'tagged version (the default behavior).'),
    )

    migrate_config_parser = subparsers.add_parser(
        'migrate-config',
        help='Migrate list configuration to new map configuration.',
    )
    _add_color_option(migrate_config_parser)
    _add_config_option(migrate_config_parser)

    run_parser = subparsers.add_parser('run', help='Run hooks.')
    _add_color_option(run_parser)
    _add_config_option(run_parser)
    _add_run_options(run_parser)

    sample_config_parser = subparsers.add_parser(
        'sample-config',
        help='Produce a sample {} file'.format(C.CONFIG_FILE),
    )
    _add_color_option(sample_config_parser)
    _add_config_option(sample_config_parser)

    try_repo_parser = subparsers.add_parser(
        'try-repo',
        help='Try the hooks in a repository, useful for developing new hooks.',
    )
    _add_color_option(try_repo_parser)
    _add_config_option(try_repo_parser)
    try_repo_parser.add_argument(
        'repo',
        help='Repository to source hooks from.',
    )
    try_repo_parser.add_argument(
        '--ref',
        help=('Manually select a ref to run against, otherwise the `HEAD` '
              'revision will be used.'),
    )
    _add_run_options(try_repo_parser)

    help = subparsers.add_parser(
        'help',
        help='Show help for a specific command.',
    )
    help.add_argument('help_cmd', nargs='?', help='Command to show help for.')

    # Argparse doesn't really provide a way to use a `default` subparser
    if len(argv) == 0:
        argv = ['run']
    args = parser.parse_args(argv)
    if args.command == 'run':
        args.files = [
            os.path.relpath(os.path.abspath(filename), git.get_root())
            for filename in args.files
        ]

    if args.command == 'help':
        if args.help_cmd:
            parser.parse_args([args.help_cmd, '--help'])
        else:
            parser.parse_args(['--help'])

    with error_handler():
        add_logging_handler(args.color)
        runner = Runner.create(args.config)
        git.check_for_cygwin_mismatch()

        if args.command == 'install':
            return install(
                runner,
                overwrite=args.overwrite,
                hooks=args.install_hooks,
                hook_type=args.hook_type,
                skip_on_missing_conf=args.allow_missing_config,
            )
        elif args.command == 'install-hooks':
            return install_hooks(runner)
        elif args.command == 'uninstall':
            return uninstall(runner, hook_type=args.hook_type)
        elif args.command == 'clean':
            return clean(runner)
        elif args.command == 'autoupdate':
            if args.tags_only:
                logger.warning('--tags-only is the default')
            return autoupdate(runner, tags_only=not args.bleeding_edge)
        elif args.command == 'migrate-config':
            return migrate_config(runner)
        elif args.command == 'run':
            return run(runner, args)
        elif args.command == 'sample-config':
            return sample_config()
        elif args.command == 'try-repo':
            return try_repo(args)
        else:
            raise NotImplementedError(
                'Command {} not implemented.'.format(args.command), )

        raise AssertionError(
            'Command {} failed to exit with a returncode'.format(
                args.command), )
Esempio n. 19
0
 def cmd_runner(self):
     return PrefixedCommandRunner(git.get_root())
Esempio n. 20
0
def test_get_root_at_root(tmpdir_factory):
    path = git_dir(tmpdir_factory)
    with cwd(path):
        assert git.get_root() == path
Esempio n. 21
0
def test_get_root_at_root(tempdir_factory):
    path = git_dir(tempdir_factory)
    with cwd(path):
        assert os.path.normcase(git.get_root()) == os.path.normcase(path)
Esempio n. 22
0
def main(argv=None):
    argv = argv if argv is not None else sys.argv[1:]
    argv = [five.to_text(arg) for arg in argv]
    parser = argparse.ArgumentParser()

    # http://stackoverflow.com/a/8521644/812183
    parser.add_argument(
        '-V', '--version',
        action='version',
        version='%(prog)s {}'.format(
            pkg_resources.get_distribution('pre-commit').version
        )
    )

    subparsers = parser.add_subparsers(dest='command')

    install_parser = subparsers.add_parser(
        'install', help='Install the pre-commit script.',
    )
    _add_color_option(install_parser)
    _add_config_option(install_parser)
    install_parser.add_argument(
        '-f', '--overwrite', action='store_true',
        help='Overwrite existing hooks / remove migration mode.',
    )
    install_parser.add_argument(
        '--install-hooks', action='store_true',
        help=(
            'Whether to install hook environments for all environments '
            'in the config file.'
        ),
    )
    install_parser.add_argument(
        '-t', '--hook-type', choices=('pre-commit', 'pre-push'),
        default='pre-commit',
    )

    install_hooks_parser = subparsers.add_parser(
        'install-hooks',
        help=(
            'Install hook environemnts for all environemnts in the config '
            'file.  You may find `pre-commit install --install-hooks` more '
            'useful.'
        ),
    )
    _add_color_option(install_hooks_parser)
    _add_config_option(install_hooks_parser)

    uninstall_parser = subparsers.add_parser(
        'uninstall', help='Uninstall the pre-commit script.',
    )
    _add_color_option(uninstall_parser)
    _add_config_option(uninstall_parser)
    uninstall_parser.add_argument(
        '-t', '--hook-type', choices=('pre-commit', 'pre-push'),
        default='pre-commit',
    )

    clean_parser = subparsers.add_parser(
        'clean', help='Clean out pre-commit files.',
    )
    _add_color_option(clean_parser)
    _add_config_option(clean_parser)
    autoupdate_parser = subparsers.add_parser(
        'autoupdate',
        help="Auto-update pre-commit config to the latest repos' versions.",
    )
    _add_color_option(autoupdate_parser)
    _add_config_option(autoupdate_parser)

    run_parser = subparsers.add_parser('run', help='Run hooks.')
    _add_color_option(run_parser)
    _add_config_option(run_parser)
    run_parser.add_argument('hook', nargs='?', help='A single hook-id to run')
    run_parser.add_argument(
        '--no-stash', default=False, action='store_true',
        help='Use this option to prevent auto stashing of unstaged files.',
    )
    run_parser.add_argument(
        '--verbose', '-v', action='store_true', default=False,
    )
    run_parser.add_argument(
        '--origin', '-o',
        help="The origin branch's commit_id when using `git push`.",
    )
    run_parser.add_argument(
        '--source', '-s',
        help="The remote branch's commit_id when using `git push`.",
    )
    run_parser.add_argument(
        '--allow-unstaged-config', default=False, action='store_true',
        help=(
            'Allow an unstaged config to be present.  Note that this will '
            'be stashed before parsing unless --no-stash is specified.'
        ),
    )
    run_parser.add_argument(
        '--hook-stage', choices=('commit', 'push'), default='commit',
        help='The stage during which the hook is fired e.g. commit or push.',
    )
    run_mutex_group = run_parser.add_mutually_exclusive_group(required=False)
    run_mutex_group.add_argument(
        '--all-files', '-a', action='store_true', default=False,
        help='Run on all the files in the repo.  Implies --no-stash.',
    )
    run_mutex_group.add_argument(
        '--files', nargs='*', default=[],
        help='Specific filenames to run hooks on.',
    )

    help = subparsers.add_parser(
        'help', help='Show help for a specific command.',
    )
    help.add_argument('help_cmd', nargs='?', help='Command to show help for.')

    # Argparse doesn't really provide a way to use a `default` subparser
    if len(argv) == 0:
        argv = ['run']
    args = parser.parse_args(argv)
    if args.command == 'run':
        args.files = [
            os.path.relpath(os.path.abspath(filename), git.get_root())
            for filename in args.files
        ]

    if args.command == 'help':
        if args.help_cmd:
            parser.parse_args([args.help_cmd, '--help'])
        else:
            parser.parse_args(['--help'])

    with error_handler():
        add_logging_handler(args.color)
        runner = Runner.create(args.config)
        git.check_for_cygwin_mismatch()

        if args.command == 'install':
            return install(
                runner, overwrite=args.overwrite, hooks=args.install_hooks,
                hook_type=args.hook_type,
            )
        elif args.command == 'install-hooks':
            return install_hooks(runner)
        elif args.command == 'uninstall':
            return uninstall(runner, hook_type=args.hook_type)
        elif args.command == 'clean':
            return clean(runner)
        elif args.command == 'autoupdate':
            return autoupdate(runner)
        elif args.command == 'run':
            return run(runner, args)
        else:
            raise NotImplementedError(
                'Command {} not implemented.'.format(args.command)
            )

        raise AssertionError(
            'Command {} failed to exit with a returncode'.format(args.command)
        )
Esempio n. 23
0
def test_get_root_not_git_dir(tempdir_factory):
    with cwd(tempdir_factory.get()):
        with pytest.raises(FatalError):
            git.get_root()
Esempio n. 24
0
def main(argv=None):
    argv = argv if argv is not None else sys.argv[1:]
    argv = [five.to_text(arg) for arg in argv]
    parser = argparse.ArgumentParser()

    # http://stackoverflow.com/a/8521644/812183
    parser.add_argument(
        '-V',
        '--version',
        action='version',
        version='%(prog)s {}'.format(C.VERSION),
    )

    subparsers = parser.add_subparsers(dest='command')

    install_parser = subparsers.add_parser(
        'install',
        help='Install the pre-commit script.',
    )
    _add_color_option(install_parser)
    _add_config_option(install_parser)
    install_parser.add_argument(
        '-f',
        '--overwrite',
        action='store_true',
        help='Overwrite existing hooks / remove migration mode.',
    )
    install_parser.add_argument(
        '--install-hooks',
        action='store_true',
        help=('Whether to install hook environments for all environments '
              'in the config file.'),
    )
    install_parser.add_argument(
        '-t',
        '--hook-type',
        choices=('pre-commit', 'pre-push'),
        default='pre-commit',
    )
    install_parser.add_argument(
        '--allow-missing-config',
        action='store_true',
        default=False,
        help=('Whether to allow a missing `pre-config` configuration file '
              'or exit with a failure code.'),
    )

    install_hooks_parser = subparsers.add_parser(
        'install-hooks',
        help=('Install hook environments for all environments in the config '
              'file.  You may find `pre-commit install --install-hooks` more '
              'useful.'),
    )
    _add_color_option(install_hooks_parser)
    _add_config_option(install_hooks_parser)

    uninstall_parser = subparsers.add_parser(
        'uninstall',
        help='Uninstall the pre-commit script.',
    )
    _add_color_option(uninstall_parser)
    _add_config_option(uninstall_parser)
    uninstall_parser.add_argument(
        '-t',
        '--hook-type',
        choices=('pre-commit', 'pre-push'),
        default='pre-commit',
    )

    clean_parser = subparsers.add_parser(
        'clean',
        help='Clean out pre-commit files.',
    )
    _add_color_option(clean_parser)
    _add_config_option(clean_parser)
    autoupdate_parser = subparsers.add_parser(
        'autoupdate',
        help="Auto-update pre-commit config to the latest repos' versions.",
    )
    _add_color_option(autoupdate_parser)
    _add_config_option(autoupdate_parser)
    autoupdate_parser.add_argument(
        '--tags-only',
        action='store_true',
        help='Update to tags only.',
    )

    run_parser = subparsers.add_parser('run', help='Run hooks.')
    _add_color_option(run_parser)
    _add_config_option(run_parser)
    run_parser.add_argument('hook', nargs='?', help='A single hook-id to run')
    run_parser.add_argument(
        '--no-stash',
        default=False,
        action='store_true',
        help='Use this option to prevent auto stashing of unstaged files.',
    )
    run_parser.add_argument(
        '--verbose',
        '-v',
        action='store_true',
        default=False,
    )
    run_parser.add_argument(
        '--origin',
        '-o',
        help="The origin branch's commit_id when using `git push`.",
    )
    run_parser.add_argument(
        '--source',
        '-s',
        help="The remote branch's commit_id when using `git push`.",
    )
    run_parser.add_argument(
        '--allow-unstaged-config',
        default=False,
        action='store_true',
        help=('Allow an unstaged config to be present.  Note that this will '
              'be stashed before parsing unless --no-stash is specified.'),
    )
    run_parser.add_argument(
        '--hook-stage',
        choices=('commit', 'push'),
        default='commit',
        help='The stage during which the hook is fired e.g. commit or push.',
    )
    run_parser.add_argument(
        '--show-diff-on-failure',
        action='store_true',
        help='When hooks fail, run `git diff` directly afterward.',
    )
    run_mutex_group = run_parser.add_mutually_exclusive_group(required=False)
    run_mutex_group.add_argument(
        '--all-files',
        '-a',
        action='store_true',
        default=False,
        help='Run on all the files in the repo.  Implies --no-stash.',
    )
    run_mutex_group.add_argument(
        '--files',
        nargs='*',
        default=[],
        help='Specific filenames to run hooks on.',
    )

    help = subparsers.add_parser(
        'help',
        help='Show help for a specific command.',
    )
    help.add_argument('help_cmd', nargs='?', help='Command to show help for.')

    # Argparse doesn't really provide a way to use a `default` subparser
    if len(argv) == 0:
        argv = ['run']
    args = parser.parse_args(argv)
    if args.command == 'run':
        args.files = [
            os.path.relpath(os.path.abspath(filename), git.get_root())
            for filename in args.files
        ]

    if args.command == 'help':
        if args.help_cmd:
            parser.parse_args([args.help_cmd, '--help'])
        else:
            parser.parse_args(['--help'])

    with error_handler():
        add_logging_handler(args.color)
        runner = Runner.create(args.config)
        git.check_for_cygwin_mismatch()

        if args.command == 'install':
            return install(
                runner,
                overwrite=args.overwrite,
                hooks=args.install_hooks,
                hook_type=args.hook_type,
                skip_on_missing_conf=args.allow_missing_config,
            )
        elif args.command == 'install-hooks':
            return install_hooks(runner)
        elif args.command == 'uninstall':
            return uninstall(runner, hook_type=args.hook_type)
        elif args.command == 'clean':
            return clean(runner)
        elif args.command == 'autoupdate':
            return autoupdate(runner, args.tags_only)
        elif args.command == 'run':
            return run(runner, args)
        else:
            raise NotImplementedError('Command {} not implemented.'.format(
                args.command))

        raise AssertionError(
            'Command {} failed to exit with a returncode'.format(args.command))
Esempio n. 25
0
def test_get_root_deeper(in_git_dir):
    expected = os.path.normcase(in_git_dir.strpath)
    with in_git_dir.join('foo').ensure_dir().as_cwd():
        assert os.path.normcase(git.get_root()) == expected
Esempio n. 26
0
def test_get_root_not_in_working_dir(in_git_dir):
    expected = os.path.normcase(in_git_dir.strpath)
    with pytest.raises(FatalError):
        with in_git_dir.join('..').ensure_dir().as_cwd():
            assert os.path.normcase(git.get_root()) == expected
Esempio n. 27
0
def main(argv=None):
    argv = argv if argv is not None else sys.argv[1:]
    argv = [five.to_text(arg) for arg in argv]
    parser = argparse.ArgumentParser()

    # http://stackoverflow.com/a/8521644/812183
    parser.add_argument(
        '-V', '--version',
        action='version',
        version='%(prog)s {}'.format(
            pkg_resources.get_distribution('pre-commit').version
        )
    )

    subparsers = parser.add_subparsers(dest='command')

    install_parser = subparsers.add_parser(
        'install', help='Install the pre-commit script.',
    )
    install_parser.add_argument(
        '-f', '--overwrite', action='store_true',
        help='Overwrite existing hooks / remove migration mode.',
    )
    install_parser.add_argument(
        '--install-hooks', action='store_true',
        help=(
            'Whether to install hook environments for all environments '
            'in the config file.'
        ),
    )
    install_parser.add_argument(
        '-t', '--hook-type', choices=('pre-commit', 'pre-push'),
        default='pre-commit',
    )

    uninstall_parser = subparsers.add_parser(
        'uninstall', help='Uninstall the pre-commit script.',
    )
    uninstall_parser.add_argument(
        '-t', '--hook-type', choices=('pre-commit', 'pre-push'),
        default='pre-commit',
    )

    subparsers.add_parser('clean', help='Clean out pre-commit files.')

    subparsers.add_parser(
        'autoupdate',
        help="Auto-update pre-commit config to the latest repos' versions.",
    )

    run_parser = subparsers.add_parser('run', help='Run hooks.')
    run_parser.add_argument('hook', nargs='?', help='A single hook-id to run')
    run_parser.add_argument(
        '--color', default='auto', type=color.use_color,
        metavar='{' + ','.join(color.COLOR_CHOICES) + '}',
        help='Whether to use color in output.  Defaults to `%(default)s`.',
    )
    run_parser.add_argument(
        '--no-stash', default=False, action='store_true',
        help='Use this option to prevent auto stashing of unstaged files.',
    )
    run_parser.add_argument(
        '--verbose', '-v', action='store_true', default=False,
    )
    run_parser.add_argument(
        '--origin', '-o',
        help="The origin branch's commit_id when using `git push`.",
    )
    run_parser.add_argument(
        '--source', '-s',
        help="The remote branch's commit_id when using `git push`.",
    )
    run_parser.add_argument(
        '--allow-unstaged-config', default=False, action='store_true',
        help=(
            'Allow an unstaged config to be present.  Note that this will '
            'be stashed before parsing unless --no-stash is specified.'
        ),
    )
    run_parser.add_argument(
        '--hook-stage', choices=('commit', 'push'), default='commit',
        help='The stage during which the hook is fired e.g. commit or push.',
    )
    run_mutex_group = run_parser.add_mutually_exclusive_group(required=False)
    run_mutex_group.add_argument(
        '--all-files', '-a', action='store_true', default=False,
        help='Run on all the files in the repo.  Implies --no-stash.',
    )
    run_mutex_group.add_argument(
        '--files', nargs='*', default=[],
        help='Specific filenames to run hooks on.',
    )

    help = subparsers.add_parser(
        'help', help='Show help for a specific command.',
    )
    help.add_argument('help_cmd', nargs='?', help='Command to show help for.')

    # Argparse doesn't really provide a way to use a `default` subparser
    if len(argv) == 0:
        argv = ['run']
    args = parser.parse_args(argv)
    if args.command == 'run':
        args.files = [
            os.path.relpath(os.path.abspath(filename), git.get_root())
            for filename in args.files
        ]

    if args.command == 'help':
        if args.help_cmd:
            parser.parse_args([args.help_cmd, '--help'])
        else:
            parser.parse_args(['--help'])

    with error_handler():
        runner = Runner.create()

        if args.command == 'install':
            return install(
                runner, overwrite=args.overwrite, hooks=args.install_hooks,
                hook_type=args.hook_type,
            )
        elif args.command == 'uninstall':
            return uninstall(runner, hook_type=args.hook_type)
        elif args.command == 'clean':
            return clean(runner)
        elif args.command == 'autoupdate':
            return autoupdate(runner)
        elif args.command == 'run':
            return run(runner, args)
        else:
            raise NotImplementedError(
                'Command {} not implemented.'.format(args.command)
            )

        raise AssertionError(
            'Command {} failed to exit with a returncode'.format(args.command)
        )
Esempio n. 28
0
def test_get_root_at_root(in_git_dir):
    expected = os.path.normcase(in_git_dir.strpath)
    assert os.path.normcase(git.get_root()) == expected
Esempio n. 29
0
def test_get_root_not_git_dir(tempdir_factory):
    with cwd(tempdir_factory.get()):
        with pytest.raises(FatalError):
            git.get_root()
Esempio n. 30
0
def test_get_root_at_root(tempdir_factory):
    path = git_dir(tempdir_factory)
    with cwd(path):
        assert git.get_root() == path
Esempio n. 31
0
def test_get_root_at_root(tempdir_factory):
    path = git_dir(tempdir_factory)
    with cwd(path):
        assert os.path.normcase(git.get_root()) == os.path.normcase(path)
Esempio n. 32
0
def test_get_root_deeper(in_git_dir):
    expected = os.path.normcase(in_git_dir.strpath)
    with in_git_dir.join('foo').ensure_dir().as_cwd():
        assert os.path.normcase(git.get_root()) == expected
Esempio n. 33
0
def test_in_exactly_dot_git(in_git_dir):
    with in_git_dir.join('.git').as_cwd(), pytest.raises(FatalError):
        git.get_root()
Esempio n. 34
0
def main(argv=None):
    argv = argv if argv is not None else sys.argv[1:]
    argv = [five.to_text(arg) for arg in argv]
    parser = argparse.ArgumentParser()

    # http://stackoverflow.com/a/8521644/812183
    parser.add_argument(
        '-V', '--version',
        action='version',
        version='%(prog)s {}'.format(C.VERSION),
    )

    subparsers = parser.add_subparsers(dest='command')

    install_parser = subparsers.add_parser(
        'install', help='Install the pre-commit script.',
    )
    _add_color_option(install_parser)
    _add_config_option(install_parser)
    install_parser.add_argument(
        '-f', '--overwrite', action='store_true',
        help='Overwrite existing hooks / remove migration mode.',
    )
    install_parser.add_argument(
        '--install-hooks', action='store_true',
        help=(
            'Whether to install hook environments for all environments '
            'in the config file.'
        ),
    )
    _add_hook_type_option(install_parser)
    install_parser.add_argument(
        '--allow-missing-config', action='store_true', default=False,
        help=(
            'Whether to allow a missing `pre-commit` configuration file '
            'or exit with a failure code.'
        ),
    )

    install_hooks_parser = subparsers.add_parser(
        'install-hooks',
        help=(
            'Install hook environments for all environments in the config '
            'file.  You may find `pre-commit install --install-hooks` more '
            'useful.'
        ),
    )
    _add_color_option(install_hooks_parser)
    _add_config_option(install_hooks_parser)

    uninstall_parser = subparsers.add_parser(
        'uninstall', help='Uninstall the pre-commit script.',
    )
    _add_color_option(uninstall_parser)
    _add_config_option(uninstall_parser)
    _add_hook_type_option(uninstall_parser)

    clean_parser = subparsers.add_parser(
        'clean', help='Clean out pre-commit files.',
    )
    _add_color_option(clean_parser)
    _add_config_option(clean_parser)
    autoupdate_parser = subparsers.add_parser(
        'autoupdate',
        help="Auto-update pre-commit config to the latest repos' versions.",
    )
    _add_color_option(autoupdate_parser)
    _add_config_option(autoupdate_parser)
    autoupdate_parser.add_argument(
        '--tags-only', action='store_true', help='LEGACY: for compatibility',
    )
    autoupdate_parser.add_argument(
        '--bleeding-edge', action='store_true',
        help=(
            'Update to the bleeding edge of `master` instead of the latest '
            'tagged version (the default behavior).'
        ),
    )

    migrate_config_parser = subparsers.add_parser(
        'migrate-config',
        help='Migrate list configuration to new map configuration.',
    )
    _add_color_option(migrate_config_parser)
    _add_config_option(migrate_config_parser)

    run_parser = subparsers.add_parser('run', help='Run hooks.')
    _add_color_option(run_parser)
    _add_config_option(run_parser)
    run_parser.add_argument('hook', nargs='?', help='A single hook-id to run')
    run_parser.add_argument(
        '--verbose', '-v', action='store_true', default=False,
    )
    run_parser.add_argument(
        '--origin', '-o',
        help="The origin branch's commit_id when using `git push`.",
    )
    run_parser.add_argument(
        '--source', '-s',
        help="The remote branch's commit_id when using `git push`.",
    )
    run_parser.add_argument(
        '--commit-msg-filename',
        help='Filename to check when running during `commit-msg`',
    )
    run_parser.add_argument(
        '--hook-stage', choices=('commit', 'push', 'commit-msg'),
        default='commit',
        help='The stage during which the hook is fired e.g. commit or push.',
    )
    run_parser.add_argument(
        '--show-diff-on-failure', action='store_true',
        help='When hooks fail, run `git diff` directly afterward.',
    )
    run_mutex_group = run_parser.add_mutually_exclusive_group(required=False)
    run_mutex_group.add_argument(
        '--all-files', '-a', action='store_true', default=False,
        help='Run on all the files in the repo.',
    )
    run_mutex_group.add_argument(
        '--files', nargs='*', default=[],
        help='Specific filenames to run hooks on.',
    )

    sample_config_parser = subparsers.add_parser(
        'sample-config', help='Produce a sample {} file'.format(C.CONFIG_FILE),
    )
    _add_color_option(sample_config_parser)
    _add_config_option(sample_config_parser)

    help = subparsers.add_parser(
        'help', help='Show help for a specific command.',
    )
    help.add_argument('help_cmd', nargs='?', help='Command to show help for.')

    # Argparse doesn't really provide a way to use a `default` subparser
    if len(argv) == 0:
        argv = ['run']
    args = parser.parse_args(argv)
    if args.command == 'run':
        args.files = [
            os.path.relpath(os.path.abspath(filename), git.get_root())
            for filename in args.files
        ]

    if args.command == 'help':
        if args.help_cmd:
            parser.parse_args([args.help_cmd, '--help'])
        else:
            parser.parse_args(['--help'])

    with error_handler():
        add_logging_handler(args.color)
        runner = Runner.create(args.config)
        git.check_for_cygwin_mismatch()

        if args.command == 'install':
            return install(
                runner, overwrite=args.overwrite, hooks=args.install_hooks,
                hook_type=args.hook_type,
                skip_on_missing_conf=args.allow_missing_config,
            )
        elif args.command == 'install-hooks':
            return install_hooks(runner)
        elif args.command == 'uninstall':
            return uninstall(runner, hook_type=args.hook_type)
        elif args.command == 'clean':
            return clean(runner)
        elif args.command == 'autoupdate':
            if args.tags_only:
                logger.warning('--tags-only is the default')
            return autoupdate(runner, tags_only=not args.bleeding_edge)
        elif args.command == 'migrate-config':
            return migrate_config(runner)
        elif args.command == 'run':
            return run(runner, args)
        elif args.command == 'sample-config':
            return sample_config()
        else:
            raise NotImplementedError(
                'Command {} not implemented.'.format(args.command),
            )

        raise AssertionError(
            'Command {} failed to exit with a returncode'.format(args.command),
        )
Esempio n. 35
0
def test_get_root_at_root(in_git_dir):
    expected = os.path.normcase(in_git_dir.strpath)
    assert os.path.normcase(git.get_root()) == expected