Completed
Push — master ( 45efa4...7cacd0 )
by
unknown
59s
created

valid_hook()   A

Complexity

Conditions 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 15
rs 9.4285
1
# -*- coding: utf-8 -*-
2
3
"""Functions for discovering and executing various cookiecutter hooks."""
4
5
import io
6
import logging
7
import os
8
import subprocess
9
import sys
10
import tempfile
11
12
from jinja2 import Template
13
14
from cookiecutter import utils
15
from .exceptions import FailedHookException
16
17
logger = logging.getLogger(__name__)
18
19
_HOOKS = [
20
    'pre_gen_project',
21
    'post_gen_project',
22
]
23
EXIT_SUCCESS = 0
24
25
26
def valid_hook(hook_file, hook_name):
27
    """Determine if a hook file is valid.
28
29
    :param hook_file: The hook file to consider for validity
30
    :param hook_name: The hook to find
31
    :return: The hook file validity
32
    """
33
    filename = os.path.basename(hook_file)
34
    basename = os.path.splitext(filename)[0]
35
36
    matching_hook = basename == hook_name
37
    supported_hook = basename in _HOOKS
38
    backup_file = filename.endswith('~')
39
40
    return matching_hook and supported_hook and not backup_file
41
42
43
def find_hook(hook_name, hooks_dir='hooks'):
44
    """Return a dict of all hook scripts provided.
45
46
    Must be called with the project template as the current working directory.
47
    Dict's key will be the hook/script's name, without extension, while values
48
    will be the absolute path to the script. Missing scripts will not be
49
    included in the returned dict.
50
51
    :param hook_name: The hook to find
52
    :param hooks_dir: The hook directory in the template
53
    :return: The absolute path to the hook script or None
54
    """
55
    logger.debug('hooks_dir is {}'.format(os.path.abspath(hooks_dir)))
56
57
    if not os.path.isdir(hooks_dir):
58
        logger.debug('No hooks/ dir in template_dir')
59
        return None
60
61
    for hook_file in os.listdir(hooks_dir):
62
        if valid_hook(hook_file, hook_name):
63
            return os.path.abspath(os.path.join(hooks_dir, hook_file))
64
65
    return None
66
67
68
def run_script(script_path, cwd='.'):
69
    """Execute a script from a working directory.
70
71
    :param script_path: Absolute path to the script to run.
72
    :param cwd: The directory to run the script from.
73
    """
74
    run_thru_shell = sys.platform.startswith('win')
75
    if script_path.endswith('.py'):
76
        script_command = [sys.executable, script_path]
77
    else:
78
        script_command = [script_path]
79
80
    utils.make_executable(script_path)
81
82
    proc = subprocess.Popen(
83
        script_command,
84
        shell=run_thru_shell,
85
        cwd=cwd
86
    )
87
    exit_status = proc.wait()
88
    if exit_status != EXIT_SUCCESS:
89
        raise FailedHookException(
90
            "Hook script failed (exit status: %d)" % exit_status)
91
92
93
def run_script_with_context(script_path, cwd, context):
94
    """Execute a script after rendering it with Jinja.
95
96
    :param script_path: Absolute path to the script to run.
97
    :param cwd: The directory to run the script from.
98
    :param context: Cookiecutter project template context.
99
    """
100
    _, extension = os.path.splitext(script_path)
101
102
    contents = io.open(script_path, 'r', encoding='utf-8').read()
103
104
    with tempfile.NamedTemporaryFile(
105
        delete=False,
106
        mode='wb',
107
        suffix=extension
108
    ) as temp:
109
        output = Template(contents).render(**context)
110
        temp.write(output.encode('utf-8'))
111
112
    run_script(temp.name, cwd)
113
114
115
def run_hook(hook_name, project_dir, context):
116
    """
117
    Try to find and execute a hook from the specified project directory.
118
119
    :param hook_name: The hook to execute.
120
    :param project_dir: The directory to execute the script from.
121
    :param context: Cookiecutter project context.
122
    """
123
    script = find_hook(hook_name)
124
    if script is None:
125
        logger.debug('No hooks found')
126
        return
127
    logger.debug('Running hook {}'.format(hook_name))
128
    run_script_with_context(script, project_dir, context)
129