File: utils.py

package info (click to toggle)
hatch-jupyter-builder 0.8.3-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 632 kB
  • sloc: python: 1,506; javascript: 135; makefile: 23
file content (272 lines) | stat: -rw-r--r-- 8,730 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""Utilities for hatch_jupyter_builder."""
import importlib
import logging
import os
import shlex
import subprocess
import sys
from pathlib import Path
from shutil import which
from typing import Any, Callable, Dict, List, Mapping, Optional, Union

if sys.platform == "win32":  # pragma: no cover
    from subprocess import list2cmdline
else:

    def list2cmdline(cmd_list):
        """Implementation of list2cmdline for posix systems."""
        return " ".join(map(shlex.quote, cmd_list))


_logger = None


def _get_log() -> logging.Logger:
    global _logger  # noqa
    if _logger:
        return _logger
    _logger = logging.getLogger(__name__)
    _logger.setLevel(logging.INFO)
    logging.basicConfig(level=logging.INFO)
    return _logger


def npm_builder(
    target_name: str,
    version: str,
    path: str = ".",
    build_dir: Optional[str] = None,
    source_dir: Optional[str] = None,
    build_cmd: Optional[str] = "build",
    force: bool = False,
    npm: Optional[Union[str, List]] = None,
    editable_build_cmd: Optional[str] = None,
) -> None:
    """Build function for managing an npm installation.

    Parameters
    ----------
    target_name: str
        The build target name ("wheel" or "sdist").
    version: str
        The version name ("standard" or "editable").
    path: str, optional
        The base path of the node package. Defaults to the current directory.
    build_dir: str, optional
        The target build directory.  If this and source_dir are given,
        the JavaScript will only be built if necessary.
    source_dir: str, optional
        The source code directory.
    build_cmd: str, optional
        The npm command to build assets to the build_dir.
    editable_build_cmd: str, optional.
        The npm command to build assets to the build_dir when building in editable mode.
    npm: str or list, optional.
        The npm executable name, or a tuple of ['node', executable].

    Notes
    -----
    The function is a no-op if the `--skip-npm` cli flag is used
        or HATCH_JUPYTER_BUILDER_SKIP_NPM env is set.
    """

    # Check if we are building a wheel from an sdist.
    abs_path = Path(path).resolve()
    log = _get_log()

    if "--skip-npm" in sys.argv or os.environ.get("HATCH_JUPYTER_BUILDER_SKIP_NPM") == "1":
        log.info("Skipping npm install as requested.")
        skip_npm = True
        if "--skip-npm" in sys.argv:
            sys.argv.remove("--skip-npm")
    else:
        skip_npm = False

    if skip_npm:
        log.info("Skipping npm-installation")
        return

    if version == "editable":
        build_cmd = editable_build_cmd or build_cmd

    if isinstance(npm, str):
        npm = [npm]

    # Find a suitable default for the npm command.
    if npm is None:
        is_yarn = (abs_path / "yarn.lock").exists()
        if is_yarn and not which("yarn"):
            log.warning("yarn not found, ignoring yarn.lock file")
            is_yarn = False

        npm = ["yarn"] if is_yarn else ["npm"]

    npm_cmd = normalize_cmd(npm)

    if build_dir and source_dir and not force:
        should_build = is_stale(build_dir, source_dir)
    else:
        should_build = True

    if should_build:
        log.info("Installing build dependencies with npm.  This may take a while...")
        run([*npm_cmd, "install"], cwd=str(abs_path))
        if build_cmd:
            run([*npm_cmd, "run", build_cmd], cwd=str(abs_path))
    else:
        log.info("No build required")


def is_stale(target: Union[str, Path], source: Union[str, Path]) -> bool:
    """Test whether the target file/directory is stale based on the source
    file/directory.
    """
    if not Path(source).exists():
        return False
    if not Path(target).exists():
        return True
    target_mtime = recursive_mtime(target) or 0
    return compare_recursive_mtime(source, cutoff=target_mtime)


def compare_recursive_mtime(path: Union[str, Path], cutoff: float, newest: bool = True) -> bool:
    """Compare the newest/oldest mtime for all files in a directory.
    Cutoff should be another mtime to be compared against. If an mtime that is
    newer/older than the cutoff is found it will return True.
    E.g. if newest=True, and a file in path is newer than the cutoff, it will
    return True.
    """
    path = Path(path)
    if path.is_file():
        mt = mtime(path)
        if newest:
            if mt > cutoff:
                return True
        elif mt < cutoff:
            return True
    for dirname, _, filenames in os.walk(str(path), topdown=False):
        for filename in filenames:
            mt = mtime(Path(dirname) / filename)
            if newest:  # Put outside of loop?
                if mt > cutoff:
                    return True
            elif mt < cutoff:
                return True
    return False


def recursive_mtime(path: Union[str, Path], newest: bool = True) -> float:
    """Gets the newest/oldest mtime for all files in a directory."""
    path = Path(path)
    if path.is_file():
        return mtime(path)
    current_extreme = -1.0
    for dirname, _, filenames in os.walk(str(path), topdown=False):
        for filename in filenames:
            mt = mtime(Path(dirname) / filename)
            if newest:  # Put outside of loop?
                if mt >= (current_extreme or mt):
                    current_extreme = mt
            elif mt <= (current_extreme or mt):
                current_extreme = mt
    return current_extreme


def mtime(path: Union[str, Path]) -> float:
    """shorthand for mtime"""
    return Path(path).stat().st_mtime


def get_build_func(build_func_str: str) -> Callable[..., None]:
    """Get a build function by name."""
    # Get the build function by importing it.
    mod_name, _, func_name = build_func_str.rpartition(".")

    # If the module fails to import, try importing as a local script.
    try:
        sys.path.insert(0, str(Path.cwd()))
        mod = importlib.import_module(mod_name)
    finally:
        sys.path.pop(0)

    return getattr(mod, func_name)


def normalize_cmd(cmd: Union[str, list]) -> List[str]:
    """Normalize a subprocess command."""
    if not isinstance(cmd, (list, tuple)):
        cmd = shlex.split(cmd, posix=os.name != "nt")
    if not Path(cmd[0]).is_absolute():
        # If a command is not an absolute path find it first.
        cmd_path = which(cmd[0])
        if not cmd_path:
            msg = (
                f"Aborting. Could not find cmd ({cmd[0]}) in path. "
                "If command is not expected to be in user's path, "
                "use an absolute path."
            )
            raise ValueError(msg)
        cmd[0] = cmd_path
    return cmd


def normalize_kwargs(kwargs: Mapping[str, str]) -> Dict[str, Any]:
    """Normalize the key names in a kwargs input dictionary"""
    result = {}
    for key, value in kwargs.items():
        if isinstance(value, bool):
            value = str(value)  # noqa
        result[key.replace("-", "_")] = value
    return result


def run(cmd: Union[str, list], **kwargs: Any) -> int:
    """Echo a command before running it."""
    kwargs.setdefault("shell", os.name == "nt")
    cmd = normalize_cmd(cmd)
    log = _get_log()
    log.info(f"> {list2cmdline(cmd)}")
    return subprocess.check_call(cmd, **kwargs)


def ensure_targets(ensured_targets: List[str]) -> None:
    """Ensure that target files are available"""
    for target in ensured_targets:
        if not Path(target).exists():
            msg = f'Ensured target "{target}" does not exist'
            raise ValueError(msg)
    _get_log().info("Ensured target(s) exist!")


def should_skip(skip_if_exists):
    """Detect whether all the paths in skip_if_exists exist"""
    if not isinstance(skip_if_exists, list) or not len(skip_if_exists):
        return False
    return all(os.path.exists(p) for p in skip_if_exists)


def install_pre_commit_hook():
    """Install a pre-commit hook."""
    data = f"""#!/usr/bin/env bash
INSTALL_PYTHON={sys.executable}
ARGS=(hook-impl --config=.pre-commit-config.yaml --hook-type=pre-commit)
HERE="$(cd "$(dirname "$0")" && pwd)"
ARGS+=(--hook-dir "$HERE" -- "$@")
exec "$INSTALL_PYTHON" -m pre_commit "${{ARGS[@]}}"
"""
    log = _get_log()
    if not os.path.exists(".git"):
        log.warning("Refusing to install pre-commit hook since this is not a git repository")
        return

    path = Path(".git/hooks/pre-commit")
    if not path.exists():
        log.info("Writing pre-commit hook")
        with open(path, "w") as fid:
            fid.write(data)
    else:
        log.warning("Refusing to overwrite pre-commit hook")

    mode = os.stat(path).st_mode
    mode |= (mode & 0o444) >> 2  # copy R bits to X
    os.chmod(path, mode)