def test_migrate_config_document_marker(tmpdir):
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(
        '# comment\n'
        '\n'
        '---\n'
        '-   repo: local\n'
        '    hooks:\n'
        '    -   id: foo\n'
        '        name: foo\n'
        '        entry: ./bin/foo.sh\n'
        '        language: script\n',
    )
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    contents = cfg.read()
    assert contents == (
        '# comment\n'
        '\n'
        '---\n'
        'repos:\n'
        '-   repo: local\n'
        '    hooks:\n'
        '    -   id: foo\n'
        '        name: foo\n'
        '        entry: ./bin/foo.sh\n'
        '        language: script\n'
    )
Exemple #2
0
def test_empty_configuration_file_user_error(tmpdir, contents):
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(contents)
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    # even though the config is invalid, this should be a noop
    assert cfg.read() == contents
def test_empty_configuration_file_user_error(tmpdir, contents):
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(contents)
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    # even though the config is invalid, this should be a noop
    assert cfg.read() == contents
Exemple #4
0
def test_migrate_config_document_marker(tmpdir):
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(
        '# comment\n'
        '\n'
        '---\n'
        '-   repo: local\n'
        '    hooks:\n'
        '    -   id: foo\n'
        '        name: foo\n'
        '        entry: ./bin/foo.sh\n'
        '        language: script\n', )
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    contents = cfg.read()
    assert contents == ('# comment\n'
                        '\n'
                        '---\n'
                        'repos:\n'
                        '-   repo: local\n'
                        '    hooks:\n'
                        '    -   id: foo\n'
                        '        name: foo\n'
                        '        entry: ./bin/foo.sh\n'
                        '        language: script\n')
Exemple #5
0
def autoupdate(config_file, store, tags_only, freeze, repos=()):
    """Auto-update the pre-commit config to the latest versions of repos."""
    migrate_config(config_file, quiet=True)
    retv = 0
    rev_infos = []
    changed = False

    config = load_config(config_file)
    for repo_config in config['repos']:
        if repo_config['repo'] in {LOCAL, META}:
            continue

        info = RevInfo.from_config(repo_config)
        if repos and info.repo not in repos:
            rev_infos.append(None)
            continue

        output.write('Updating {} ... '.format(info.repo))
        new_info = info.update(tags_only=tags_only, freeze=freeze)
        try:
            _check_hooks_still_exist_at_rev(repo_config, new_info, store)
        except RepositoryCannotBeUpdatedError as error:
            output.write_line(error.args[0])
            rev_infos.append(None)
            retv = 1
            continue

        if new_info.rev != info.rev:
            changed = True
            if new_info.frozen:
                updated_to = '{} (frozen)'.format(new_info.frozen)
            else:
                updated_to = new_info.rev
            msg = 'updating {} -> {}.'.format(info.rev, updated_to)
            output.write_line(msg)
            rev_infos.append(new_info)
        else:
            output.write_line('already up to date.')
            rev_infos.append(None)

    if changed:
        _write_new_config(config_file, rev_infos)

    return retv
Exemple #6
0
def autoupdate(config_file, store, tags_only, repos=()):
    """Auto-update the pre-commit config to the latest versions of repos."""
    migrate_config(config_file, quiet=True)
    retv = 0
    output_repos = []
    changed = False

    input_config = load_config(config_file)

    for repo_config in input_config['repos']:
        if (
            repo_config['repo'] in {LOCAL, META} or
            # Skip updating any repo_configs that aren't for the specified repo
            repos and repo_config['repo'] not in repos
        ):
            output_repos.append(repo_config)
            continue
        output.write('Updating {}...'.format(repo_config['repo']))
        try:
            new_repo_config = _update_repo(repo_config, store, tags_only)
        except RepositoryCannotBeUpdatedError as error:
            output.write_line(error.args[0])
            output_repos.append(repo_config)
            retv = 1
            continue

        if new_repo_config['rev'] != repo_config['rev']:
            changed = True
            output.write_line(
                'updating {} -> {}.'.format(
                    repo_config['rev'], new_repo_config['rev'],
                ),
            )
            output_repos.append(new_repo_config)
        else:
            output.write_line('already up to date.')
            output_repos.append(repo_config)

    if changed:
        output_config = input_config.copy()
        output_config['repos'] = output_repos
        _write_new_config_file(config_file, output_config)

    return retv
def autoupdate(config_file, store, tags_only, repos=()):
    """Auto-update the pre-commit config to the latest versions of repos."""
    migrate_config(config_file, quiet=True)
    retv = 0
    output_repos = []
    changed = False

    input_config = load_config(config_file)

    for repo_config in input_config['repos']:
        if (
            repo_config['repo'] in {LOCAL, META} or
            # Skip updating any repo_configs that aren't for the specified repo
            repos and repo_config['repo'] not in repos
        ):
            output_repos.append(repo_config)
            continue
        output.write('Updating {}...'.format(repo_config['repo']))
        try:
            new_repo_config = _update_repo(repo_config, store, tags_only)
        except RepositoryCannotBeUpdatedError as error:
            output.write_line(error.args[0])
            output_repos.append(repo_config)
            retv = 1
            continue

        if new_repo_config['rev'] != repo_config['rev']:
            changed = True
            output.write_line(
                'updating {} -> {}.'.format(
                    repo_config['rev'], new_repo_config['rev'],
                ),
            )
            output_repos.append(new_repo_config)
        else:
            output.write_line('already up to date.')
            output_repos.append(repo_config)

    if changed:
        output_config = input_config.copy()
        output_config['repos'] = output_repos
        _write_new_config_file(config_file, output_config)

    return retv
Exemple #8
0
def autoupdate(runner, tags_only, repo=None):
    """Auto-update the pre-commit config to the latest versions of repos."""
    migrate_config(runner, quiet=True)
    retv = 0
    output_repos = []
    changed = False

    input_config = load_config(runner.config_file_path)

    for repo_config in input_config['repos']:
        if (is_local_repo(repo_config) or is_meta_repo(repo_config) or
                # Skip updating any repo_configs that aren't for the specified repo
                repo and repo != repo_config['repo']):
            output_repos.append(repo_config)
            continue
        output.write('Updating {}...'.format(repo_config['repo']))
        try:
            new_repo_config = _update_repo(repo_config, runner, tags_only)
        except RepositoryCannotBeUpdatedError as error:
            output.write_line(error.args[0])
            output_repos.append(repo_config)
            retv = 1
            continue

        if new_repo_config['sha'] != repo_config['sha']:
            changed = True
            output.write_line('updating {} -> {}.'.format(
                repo_config['sha'],
                new_repo_config['sha'],
            ))
            output_repos.append(new_repo_config)
        else:
            output.write_line('already up to date.')
            output_repos.append(repo_config)

    if changed:
        output_config = input_config.copy()
        output_config['repos'] = output_repos
        _write_new_config_file(runner.config_file_path, output_config)

    return retv
Exemple #9
0
def autoupdate(runner, tags_only):
    """Auto-update the pre-commit config to the latest versions of repos."""
    migrate_config(runner, quiet=True)
    retv = 0
    output_repos = []
    changed = False

    input_config = load_config(runner.config_file_path)

    for repo_config in input_config['repos']:
        if is_local_repo(repo_config):
            output_repos.append(repo_config)
            continue
        output.write('Updating {}...'.format(repo_config['repo']))
        try:
            new_repo_config = _update_repo(repo_config, runner, tags_only)
        except RepositoryCannotBeUpdatedError as error:
            output.write_line(error.args[0])
            output_repos.append(repo_config)
            retv = 1
            continue

        if new_repo_config['sha'] != repo_config['sha']:
            changed = True
            output.write_line('updating {} -> {}.'.format(
                repo_config['sha'], new_repo_config['sha'],
            ))
            output_repos.append(new_repo_config)
        else:
            output.write_line('already up to date.')
            output_repos.append(repo_config)

    if changed:
        output_config = input_config.copy()
        output_config['repos'] = output_repos
        _write_new_config_file(runner.config_file_path, output_config)

    return retv
Exemple #10
0
def test_already_migrated_configuration_noop(tmpdir, capsys):
    contents = ('repos:\n'
                '-   repo: local\n'
                '    hooks:\n'
                '    -   id: foo\n'
                '        name: foo\n'
                '        entry: ./bin/foo.sh\n'
                '        language: script\n')
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(contents)
    assert not migrate_config(Runner(tmpdir.strpath, C.CONFIG_FILE))
    out, _ = capsys.readouterr()
    assert out == 'Configuration is already migrated.\n'
    assert cfg.read() == contents
def test_already_migrated_configuration_noop(tmpdir, capsys):
    contents = (
        'repos:\n'
        '-   repo: local\n'
        '    hooks:\n'
        '    -   id: foo\n'
        '        name: foo\n'
        '        entry: ./bin/foo.sh\n'
        '        language: script\n'
    )
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(contents)
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    out, _ = capsys.readouterr()
    assert out == 'Configuration is already migrated.\n'
    assert cfg.read() == contents
Exemple #12
0
def test_migrate_config_normal_format(tmpdir, capsys):
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(
        '-   repo: local\n'
        '    hooks:\n'
        '    -   id: foo\n'
        '        name: foo\n'
        '        entry: ./bin/foo.sh\n'
        '        language: script\n', )
    assert not migrate_config(Runner(tmpdir.strpath, C.CONFIG_FILE))
    out, _ = capsys.readouterr()
    assert out == 'Configuration has been migrated.\n'
    contents = cfg.read()
    assert contents == ('repos:\n'
                        '-   repo: local\n'
                        '    hooks:\n'
                        '    -   id: foo\n'
                        '        name: foo\n'
                        '        entry: ./bin/foo.sh\n'
                        '        language: script\n')
Exemple #13
0
def test_migrate_config_list_literal(tmpdir):
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(
        '[{\n'
        '    repo: local,\n'
        '    hooks: [{\n'
        '        id: foo, name: foo, entry: ./bin/foo.sh,\n'
        '        language: script,\n'
        '    }]\n'
        '}]', )
    assert not migrate_config(Runner(tmpdir.strpath, C.CONFIG_FILE))
    contents = cfg.read()
    assert contents == (
        'repos:\n'
        '    [{\n'
        '        repo: local,\n'
        '        hooks: [{\n'
        '            id: foo, name: foo, entry: ./bin/foo.sh,\n'
        '            language: script,\n'
        '        }]\n'
        '    }]')
def test_migrate_config_sha_to_rev(tmpdir):
    contents = ('repos:\n'
                '-   repo: https://github.com/pre-commit/pre-commit-hooks\n'
                '    sha: v1.2.0\n'
                '    hooks: []\n'
                '-   repo: https://github.com/pre-commit/pre-commit-hooks\n'
                '    sha: v1.2.0\n'
                '    hooks: []\n')
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(contents)
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    contents = cfg.read()
    assert contents == (
        'repos:\n'
        '-   repo: https://github.com/pre-commit/pre-commit-hooks\n'
        '    rev: v1.2.0\n'
        '    hooks: []\n'
        '-   repo: https://github.com/pre-commit/pre-commit-hooks\n'
        '    rev: v1.2.0\n'
        '    hooks: []\n')
def test_migrate_config_list_literal(tmpdir):
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(
        '[{\n'
        '    repo: local,\n'
        '    hooks: [{\n'
        '        id: foo, name: foo, entry: ./bin/foo.sh,\n'
        '        language: script,\n'
        '    }]\n'
        '}]',
    )
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    contents = cfg.read()
    assert contents == (
        'repos:\n'
        '    [{\n'
        '        repo: local,\n'
        '        hooks: [{\n'
        '            id: foo, name: foo, entry: ./bin/foo.sh,\n'
        '            language: script,\n'
        '        }]\n'
        '    }]'
    )
def test_migrate_config_normal_format(tmpdir, capsys):
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(
        '-   repo: local\n'
        '    hooks:\n'
        '    -   id: foo\n'
        '        name: foo\n'
        '        entry: ./bin/foo.sh\n'
        '        language: script\n',
    )
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    out, _ = capsys.readouterr()
    assert out == 'Configuration has been migrated.\n'
    contents = cfg.read()
    assert contents == (
        'repos:\n'
        '-   repo: local\n'
        '    hooks:\n'
        '    -   id: foo\n'
        '        name: foo\n'
        '        entry: ./bin/foo.sh\n'
        '        language: script\n'
    )
def test_migrate_config_sha_to_rev(tmpdir):
    contents = (
        'repos:\n'
        '-   repo: https://github.com/pre-commit/pre-commit-hooks\n'
        '    sha: v1.2.0\n'
        '    hooks: []\n'
        '-   repo: https://github.com/pre-commit/pre-commit-hooks\n'
        '    sha: v1.2.0\n'
        '    hooks: []\n'
    )
    cfg = tmpdir.join(C.CONFIG_FILE)
    cfg.write(contents)
    with tmpdir.as_cwd():
        assert not migrate_config(C.CONFIG_FILE)
    contents = cfg.read()
    assert contents == (
        'repos:\n'
        '-   repo: https://github.com/pre-commit/pre-commit-hooks\n'
        '    rev: v1.2.0\n'
        '    hooks: []\n'
        '-   repo: https://github.com/pre-commit/pre-commit-hooks\n'
        '    rev: v1.2.0\n'
        '    hooks: []\n'
    )
Exemple #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)
    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),
        )
def main(argv: Optional[Sequence[str]] = None) -> int:
    argv = argv if argv is not None else sys.argv[1:]
    parser = argparse.ArgumentParser(prog="pre-commit")

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

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

    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(
        "--bleeding-edge",
        action="store_true",
        help=("Update to the bleeding edge of `master` instead of the latest "
              "tagged version (the default behavior)."),
    )
    autoupdate_parser.add_argument(
        "--freeze",
        action="store_true",
        help='Store "frozen" hashes in `rev` instead of tag names',
    )
    autoupdate_parser.add_argument(
        "--repo",
        dest="repos",
        action="append",
        metavar="REPO",
        help="Only update this repository -- may be specified multiple times.",
    )

    clean_parser = subparsers.add_parser(
        "clean",
        help="Clean out pre-commit files.",
    )
    _add_color_option(clean_parser)
    _add_config_option(clean_parser)

    hook_impl_parser = subparsers.add_parser("hook-impl")
    _add_color_option(hook_impl_parser)
    _add_config_option(hook_impl_parser)
    hook_impl_parser.add_argument("--hook-type")
    hook_impl_parser.add_argument("--hook-dir")
    hook_impl_parser.add_argument(
        "--skip-on-missing-config",
        action="store_true",
    )
    hook_impl_parser.add_argument(dest="rest", nargs=argparse.REMAINDER)

    gc_parser = subparsers.add_parser("gc", help="Clean unused cached repos.")
    _add_color_option(gc_parser)
    _add_config_option(gc_parser)

    init_templatedir_parser = subparsers.add_parser(
        "init-templatedir",
        help=("Install hook script in a directory intended for use with "
              "`git config init.templateDir`."),
    )
    _add_color_option(init_templatedir_parser)
    _add_config_option(init_templatedir_parser)
    init_templatedir_parser.add_argument(
        "directory",
        help="The directory in which to write the hook script.",
    )
    _add_hook_type_option(init_templatedir_parser)

    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)

    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=f"Produce a sample {C.CONFIG_FILE} 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",
        "--rev",
        help=("Manually select a rev to run against, otherwise the `HEAD` "
              "revision will be used."),
    )
    _add_run_options(try_repo_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)

    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 == "help" and args.help_cmd:
        parser.parse_args([args.help_cmd, "--help"])
    elif args.command == "help":
        parser.parse_args(["--help"])

    with error_handler(), logging_handler(args.color):
        if args.command not in COMMANDS_NO_GIT:
            _adjust_args_and_chdir(args)

        git.check_for_cygwin_mismatch()

        store = Store()
        store.mark_config_used(args.config)

        if args.command == "autoupdate":
            return autoupdate(
                args.config,
                store,
                tags_only=not args.bleeding_edge,
                freeze=args.freeze,
                repos=args.repos,
            )
        elif args.command == "clean":
            return clean(store)
        elif args.command == "gc":
            return gc(store)
        elif args.command == "hook-impl":
            return hook_impl(
                store,
                config=args.config,
                color=args.color,
                hook_type=args.hook_type,
                hook_dir=args.hook_dir,
                skip_on_missing_config=args.skip_on_missing_config,
                args=args.rest[1:],
            )
        elif args.command == "install":
            return install(
                args.config,
                store,
                hook_types=args.hook_types,
                overwrite=args.overwrite,
                hooks=args.install_hooks,
                skip_on_missing_config=args.allow_missing_config,
            )
        elif args.command == "init-templatedir":
            return init_templatedir(
                args.config,
                store,
                args.directory,
                hook_types=args.hook_types,
            )
        elif args.command == "install-hooks":
            return install_hooks(args.config, store)
        elif args.command == "migrate-config":
            return migrate_config(args.config)
        elif args.command == "run":
            return run(args.config, store, args)
        elif args.command == "sample-config":
            return sample_config()
        elif args.command == "try-repo":
            return try_repo(args)
        elif args.command == "uninstall":
            return uninstall(hook_types=args.hook_types)
        else:
            raise NotImplementedError(
                f"Command {args.command} not implemented.", )

        raise AssertionError(
            f"Command {args.command} failed to exit with a returncode", )
Exemple #20
0
def main(argv: Sequence[str] | None = None) -> int:
    argv = argv if argv is not None else sys.argv[1:]
    parser = argparse.ArgumentParser(prog='pre-commit')

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

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

    def _add_cmd(name: str, *, help: str) -> argparse.ArgumentParser:
        parser = subparsers.add_parser(name, help=help)
        add_color_option(parser)
        return parser

    autoupdate_parser = _add_cmd(
        'autoupdate',
        help="Auto-update pre-commit config to the latest repos' versions.",
    )
    _add_config_option(autoupdate_parser)
    autoupdate_parser.add_argument(
        '--bleeding-edge', action='store_true',
        help=(
            'Update to the bleeding edge of `HEAD` instead of the latest '
            'tagged version (the default behavior).'
        ),
    )
    autoupdate_parser.add_argument(
        '--freeze', action='store_true',
        help='Store "frozen" hashes in `rev` instead of tag names',
    )
    autoupdate_parser.add_argument(
        '--repo', dest='repos', action='append', metavar='REPO',
        help='Only update this repository -- may be specified multiple times.',
    )

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

    _add_cmd('gc', help='Clean unused cached repos.')

    init_templatedir_parser = _add_cmd(
        'init-templatedir',
        help=(
            'Install hook script in a directory intended for use with '
            '`git config init.templateDir`.'
        ),
    )
    _add_config_option(init_templatedir_parser)
    init_templatedir_parser.add_argument(
        'directory', help='The directory in which to write the hook script.',
    )
    init_templatedir_parser.add_argument(
        '--no-allow-missing-config',
        action='store_false',
        dest='allow_missing_config',
        help='Assume cloned repos should have a `pre-commit` config.',
    )
    _add_hook_type_option(init_templatedir_parser)

    install_parser = _add_cmd('install', help='Install the pre-commit script.')
    _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 = _add_cmd(
        'install-hooks',
        help=(
            'Install hook environments for all environments in the config '
            'file.  You may find `pre-commit install --install-hooks` more '
            'useful.'
        ),
    )
    _add_config_option(install_hooks_parser)

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

    run_parser = _add_cmd('run', help='Run hooks.')
    _add_config_option(run_parser)
    _add_run_options(run_parser)

    _add_cmd('sample-config', help=f'Produce a sample {C.CONFIG_FILE} file')

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

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

    validate_config_parser = _add_cmd(
        'validate-config', help='Validate .pre-commit-config.yaml files',
    )
    validate_config_parser.add_argument('filenames', nargs='*')

    validate_manifest_parser = _add_cmd(
        'validate-manifest', help='Validate .pre-commit-hooks.yaml files',
    )
    validate_manifest_parser.add_argument('filenames', nargs='*')

    # does not use `_add_cmd` because it doesn't use `--color`
    help = subparsers.add_parser(
        'help', help='Show help for a specific command.',
    )
    help.add_argument('help_cmd', nargs='?', help='Command to show help for.')

    # not intended for users to call this directly
    hook_impl_parser = subparsers.add_parser('hook-impl')
    add_color_option(hook_impl_parser)
    _add_config_option(hook_impl_parser)
    hook_impl_parser.add_argument('--hook-type')
    hook_impl_parser.add_argument('--hook-dir')
    hook_impl_parser.add_argument(
        '--skip-on-missing-config', action='store_true',
    )
    hook_impl_parser.add_argument(dest='rest', nargs=argparse.REMAINDER)

    # 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 == 'help' and args.help_cmd:
        parser.parse_args([args.help_cmd, '--help'])
    elif args.command == 'help':
        parser.parse_args(['--help'])

    with error_handler(), logging_handler(args.color):
        git.check_for_cygwin_mismatch()

        store = Store()

        if args.command not in COMMANDS_NO_GIT:
            _adjust_args_and_chdir(args)
            store.mark_config_used(args.config)

        if args.command == 'autoupdate':
            return autoupdate(
                args.config, store,
                tags_only=not args.bleeding_edge,
                freeze=args.freeze,
                repos=args.repos,
            )
        elif args.command == 'clean':
            return clean(store)
        elif args.command == 'gc':
            return gc(store)
        elif args.command == 'hook-impl':
            return hook_impl(
                store,
                config=args.config,
                color=args.color,
                hook_type=args.hook_type,
                hook_dir=args.hook_dir,
                skip_on_missing_config=args.skip_on_missing_config,
                args=args.rest[1:],
            )
        elif args.command == 'install':
            return install(
                args.config, store,
                hook_types=args.hook_types,
                overwrite=args.overwrite,
                hooks=args.install_hooks,
                skip_on_missing_config=args.allow_missing_config,
            )
        elif args.command == 'init-templatedir':
            return init_templatedir(
                args.config, store, args.directory,
                hook_types=args.hook_types,
                skip_on_missing_config=args.allow_missing_config,
            )
        elif args.command == 'install-hooks':
            return install_hooks(args.config, store)
        elif args.command == 'migrate-config':
            return migrate_config(args.config)
        elif args.command == 'run':
            return run(args.config, store, args)
        elif args.command == 'sample-config':
            return sample_config()
        elif args.command == 'try-repo':
            return try_repo(args)
        elif args.command == 'uninstall':
            return uninstall(
                config_file=args.config,
                hook_types=args.hook_types,
            )
        elif args.command == 'validate-config':
            return validate_config(args.filenames)
        elif args.command == 'validate-manifest':
            return validate_manifest(args.filenames)
        else:
            raise NotImplementedError(
                f'Command {args.command} not implemented.',
            )

        raise AssertionError(
            f'Command {args.command} failed to exit with a returncode',
        )
Exemple #21
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()

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

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

    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).'),
    )
    autoupdate_parser.add_argument(
        '--repo',
        dest='repos',
        action='append',
        metavar='REPO',
        help='Only update this repository -- may be specified multiple times.',
    )

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

    gc_parser = subparsers.add_parser('gc', help='Clean unused cached repos.')
    _add_color_option(gc_parser)
    _add_config_option(gc_parser)

    init_templatedir_parser = subparsers.add_parser(
        'init-templatedir',
        help=('Install hook script in a directory intended for use with '
              '`git config init.templateDir`.'),
    )
    _add_color_option(init_templatedir_parser)
    _add_config_option(init_templatedir_parser)
    init_templatedir_parser.add_argument(
        'directory',
        help='The directory in which to write the hook script.',
    )
    _add_hook_type_option(init_templatedir_parser)

    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)

    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',
        '--rev',
        help=('Manually select a rev to run against, otherwise the `HEAD` '
              'revision will be used.'),
    )
    _add_run_options(try_repo_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)

    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 == 'help' and args.help_cmd:
        parser.parse_args([args.help_cmd, '--help'])
    elif args.command == 'help':
        parser.parse_args(['--help'])

    with error_handler(), logging_handler(args.color):
        if args.command not in COMMANDS_NO_GIT:
            _adjust_args_and_chdir(args)

        git.check_for_cygwin_mismatch()

        store = Store()
        store.mark_config_used(args.config)

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

        raise AssertionError(
            'Command {} failed to exit with a returncode'.format(
                args.command), )
Exemple #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(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), )
Exemple #23
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()

    # https://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)

    gc_parser = subparsers.add_parser('gc', help='Clean unused cached repos.')
    _add_color_option(gc_parser)
    _add_config_option(gc_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).'
        ),
    )
    autoupdate_parser.add_argument(
        '--repo', dest='repos', action='append', metavar='REPO',
        help='Only update this repository -- may be specified multiple times.',
    )

    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', '--rev',
        help=(
            'Manually select a rev 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 == 'help' and args.help_cmd:
        parser.parse_args([args.help_cmd, '--help'])
    elif args.command == 'help':
        parser.parse_args(['--help'])

    with error_handler(), logging_handler(args.color):
        if args.command not in {'clean', 'gc', 'sample-config'}:
            _adjust_args_and_chdir(args)

        git.check_for_cygwin_mismatch()

        store = Store()
        store.mark_config_used(args.config)

        if args.command == 'install':
            return install(
                args.config, store,
                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(args.config, store)
        elif args.command == 'uninstall':
            return uninstall(hook_type=args.hook_type)
        elif args.command == 'clean':
            return clean(store)
        elif args.command == 'gc':
            return gc(store)
        elif args.command == 'autoupdate':
            if args.tags_only:
                logger.warning('--tags-only is the default')
            return autoupdate(
                args.config, store,
                tags_only=not args.bleeding_edge,
                repos=args.repos,
            )
        elif args.command == 'migrate-config':
            return migrate_config(args.config)
        elif args.command == 'run':
            return run(args.config, store, 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),
        )