# Path: pre_commit/commands/init_templatedir.py
# def init_templatedir(
#         config_file: str,
#         store: Store,
#         directory: str,
#         hook_types: Sequence[str],
#         skip_on_missing_config: bool = True,
# ) -> int:
#     install(
#         config_file,
#         store,
#         hook_types=hook_types,
#         overwrite=True,
#         skip_on_missing_config=skip_on_missing_config,
#         git_dir=directory,
#     )
#     try:
#         _, out, _ = cmd_output('git', 'config', 'init.templateDir')
#     except CalledProcessError:
#         configured_path = None
#     else:
#         configured_path = os.path.realpath(os.path.expanduser(out.strip()))
#     dest = os.path.realpath(directory)
#     if configured_path != dest:
#         logger.warning('`init.templateDir` not set to the target directory')
#         logger.warning(f'maybe `git config --global init.templateDir {dest}`?')
#     return 0
# 
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
#         patch: PatchesT,
#         _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
#     """In this context, `os.environ` is modified according to `patch`.
# 
#     `patch` is an iterable of 2-tuples (key, value):
#         `key`: string
#         `value`:
#             - string: `environ[key] == value` inside the context.
#             - UNSET: `key not in environ` inside the context.
#             - template: A template is a tuple of strings and Var which will be
#               replaced with the previous environment
#     """
#     env = os.environ if _env is None else _env
#     before = dict(env)
# 
#     for k, v in patch:
#         if v is UNSET:
#             env.pop(k, None)
#         elif isinstance(v, tuple):
#             env[k] = format_env(v, before)
#         else:
#             env[k] = v
# 
#     try:
#         yield
#     finally:
#         env.clear()
#         env.update(before)
# 
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
#     returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
#     stdout = stdout_b.decode() if stdout_b is not None else None
#     stderr = stderr_b.decode() if stderr_b is not None else None
#     return returncode, stdout, stderr
# 
# Path: testing/fixtures.py
# def git_dir(tempdir_factory):
#     path = tempdir_factory.get()
#     cmd_output('git', 'init', path)
#     return path
# 
# Path: testing/fixtures.py
# def make_consuming_repo(tempdir_factory, repo_source):
#     path = make_repo(tempdir_factory, repo_source)
#     config = make_config_from_repo(path)
#     git_path = git_dir(tempdir_factory)
#     return add_config_to_repo(git_path, config)
# 
# Path: testing/util.py
# def cmd_output_mocked_pre_commit_home(
#         *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
# ):
#     if pre_commit_home is None:
#         pre_commit_home = tempdir_factory.get()
#     env = env if env is not None else os.environ
#     kwargs.setdefault('stderr', subprocess.STDOUT)
#     # Don't want to write to the home directory
#     env = dict(env, PRE_COMMIT_HOME=pre_commit_home)
#     ret, out, _ = cmd_output(*args, env=env, **kwargs)
#     return ret, out.replace('\r\n', '\n'), None
# 
# Path: testing/util.py
# @contextlib.contextmanager
# def cwd(path):
#     original_cwd = os.getcwd()
#     os.chdir(path)
#     try:
#         yield
#     finally:
#         os.chdir(original_cwd)
# 
# Path: testing/util.py
# def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
#     kwargs.setdefault('stderr', subprocess.STDOUT)
# 
#     cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args)
#     if all_files:  # allow skipping `-a` with `all_files=False`
#         cmd += ('-a',)
#     if msg is not None:  # allow skipping `-m` with `msg=None`
#         cmd += ('-m', msg)
#     ret, out, _ = fn(*cmd, **kwargs)
#     return ret, out.replace('\r\n', '\n')


import os.path
import pytest
import pre_commit.constants as C
from unittest import mock
from pre_commit.commands.init_templatedir import init_templatedir
from pre_commit.envcontext import envcontext
from pre_commit.util import cmd_output
from testing.fixtures import git_dir
from testing.fixtures import make_consuming_repo
from testing.util import cmd_output_mocked_pre_commit_home
from testing.util import cwd
from testing.util import git_commit
from __future__ import annotations





def test_init_templatedir(tmpdir, tempdir_factory, store, cap_out):
    target = str(tmpdir.join('tmpl'))
    init_templatedir(C.CONFIG_FILE, store, target, hook_types=['pre-commit'])
    lines = cap_out.get().splitlines()
    assert lines[0].startswith('pre-commit installed at ')
    assert lines[1] == (
        '[WARNING] `init.templateDir` not set to the target directory'
    )
    assert lines[2].startswith(
        '[WARNING] maybe `git config --global init.templateDir',
    )

    with envcontext((('GIT_TEMPLATE_DIR', target),)):
        path = make_consuming_repo(tempdir_factory, 'script_hooks_repo')

        with cwd(path):
            retcode, output = git_commit(

# Path: pre_commit/commands/init_templatedir.py
# def init_templatedir(
#         config_file: str,
#         store: Store,
#         directory: str,
#         hook_types: Sequence[str],
#         skip_on_missing_config: bool = True,
# ) -> int:
#     install(
#         config_file,
#         store,
#         hook_types=hook_types,
#         overwrite=True,
#         skip_on_missing_config=skip_on_missing_config,
#         git_dir=directory,
#     )
#     try:
#         _, out, _ = cmd_output('git', 'config', 'init.templateDir')
#     except CalledProcessError:
#         configured_path = None
#     else:
#         configured_path = os.path.realpath(os.path.expanduser(out.strip()))
#     dest = os.path.realpath(directory)
#     if configured_path != dest:
#         logger.warning('`init.templateDir` not set to the target directory')
#         logger.warning(f'maybe `git config --global init.templateDir {dest}`?')
#     return 0
# 
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
#         patch: PatchesT,
#         _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
#     """In this context, `os.environ` is modified according to `patch`.
# 
#     `patch` is an iterable of 2-tuples (key, value):
#         `key`: string
#         `value`:
#             - string: `environ[key] == value` inside the context.
#             - UNSET: `key not in environ` inside the context.
#             - template: A template is a tuple of strings and Var which will be
#               replaced with the previous environment
#     """
#     env = os.environ if _env is None else _env
#     before = dict(env)
# 
#     for k, v in patch:
#         if v is UNSET:
#             env.pop(k, None)
#         elif isinstance(v, tuple):
#             env[k] = format_env(v, before)
#         else:
#             env[k] = v
# 
#     try:
#         yield
#     finally:
#         env.clear()
#         env.update(before)
# 
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
#     returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
#     stdout = stdout_b.decode() if stdout_b is not None else None
#     stderr = stderr_b.decode() if stderr_b is not None else None
#     return returncode, stdout, stderr
# 
# Path: testing/fixtures.py
# def git_dir(tempdir_factory):
#     path = tempdir_factory.get()
#     cmd_output('git', 'init', path)
#     return path
# 
# Path: testing/fixtures.py
# def make_consuming_repo(tempdir_factory, repo_source):
#     path = make_repo(tempdir_factory, repo_source)
#     config = make_config_from_repo(path)
#     git_path = git_dir(tempdir_factory)
#     return add_config_to_repo(git_path, config)
# 
# Path: testing/util.py
# def cmd_output_mocked_pre_commit_home(
#         *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
# ):
#     if pre_commit_home is None:
#         pre_commit_home = tempdir_factory.get()
#     env = env if env is not None else os.environ
#     kwargs.setdefault('stderr', subprocess.STDOUT)
#     # Don't want to write to the home directory
#     env = dict(env, PRE_COMMIT_HOME=pre_commit_home)
#     ret, out, _ = cmd_output(*args, env=env, **kwargs)
#     return ret, out.replace('\r\n', '\n'), None
# 
# Path: testing/util.py
# @contextlib.contextmanager
# def cwd(path):
#     original_cwd = os.getcwd()
#     os.chdir(path)
#     try:
#         yield
#     finally:
#         os.chdir(original_cwd)
# 
# Path: testing/util.py
# def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
#     kwargs.setdefault('stderr', subprocess.STDOUT)
# 
#     cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args)
#     if all_files:  # allow skipping `-a` with `all_files=False`
#         cmd += ('-a',)
#     if msg is not None:  # allow skipping `-m` with `msg=None`
#         cmd += ('-m', msg)
#     ret, out, _ = fn(*cmd, **kwargs)
#     return ret, out.replace('\r\n', '\n')


# Path: tests/commands/init_templatedir_test.py
import os.path
import pytest
import pre_commit.constants as C
from unittest import mock
from pre_commit.commands.init_templatedir import init_templatedir
from pre_commit.envcontext import envcontext
from pre_commit.util import cmd_output
from testing.fixtures import git_dir
from testing.fixtures import make_consuming_repo
from testing.util import cmd_output_mocked_pre_commit_home
from testing.util import cwd
from testing.util import git_commit

from __future__ import annotations





def test_init_templatedir(tmpdir, tempdir_factory, store, cap_out):
    target = str(tmpdir.join('tmpl'))
    init_templatedir(C.CONFIG_FILE, store, target, hook_types=['pre-commit'])
    lines = cap_out.get().splitlines()
    assert lines[0].startswith('pre-commit installed at ')
    assert lines[1] == (
        '[WARNING] `init.templateDir` not set to the target directory'
    )
    assert lines[2].startswith(
        '[WARNING] maybe `git config --global init.templateDir',
    )

    with envcontext((('GIT_TEMPLATE_DIR', target),)):
        path = make_consuming_repo(tempdir_factory, 'script_hooks_repo')

        with cwd(path):
            retcode, output = git_commit(

                fn=cmd_output_mocked_pre_commit_home,