summaryrefslogtreecommitdiff
path: root/lib/spack/spack/build_systems/python.py
blob: 3990b95e905c6586ae0b615e7af273a672e1c3a0 (plain) (blame)
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# Copyright 2013-2023 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import inspect
import os
import re
import shutil
from typing import Iterable, List, Mapping, Optional

import archspec

import llnl.util.filesystem as fs
import llnl.util.lang as lang
import llnl.util.tty as tty
from llnl.util.filesystem import HeaderList, LibraryList

import spack.builder
import spack.config
import spack.deptypes as dt
import spack.detection
import spack.multimethod
import spack.package_base
import spack.spec
import spack.store
from spack.directives import build_system, depends_on, extends, maintainers
from spack.error import NoHeadersError, NoLibrariesError
from spack.install_test import test_part
from spack.spec import Spec
from spack.util.prefix import Prefix

from ._checks import BaseBuilder, execute_install_time_tests


def _flatten_dict(dictionary: Mapping[str, object]) -> Iterable[str]:
    """Iterable that yields KEY=VALUE paths through a dictionary.

    Args:
        dictionary: Possibly nested dictionary of arbitrary keys and values.

    Yields:
        A single path through the dictionary.
    """
    for key, item in dictionary.items():
        if isinstance(item, dict):
            # Recursive case
            for value in _flatten_dict(item):
                yield f"{key}={value}"
        else:
            # Base case
            yield f"{key}={item}"


class PythonExtension(spack.package_base.PackageBase):
    maintainers("adamjstewart")

    @property
    def import_modules(self) -> Iterable[str]:
        """Names of modules that the Python package provides.

        These are used to test whether or not the installation succeeded.
        These names generally come from running:

        .. code-block:: python

           >> import setuptools
           >> setuptools.find_packages()

        in the source tarball directory. If the module names are incorrectly
        detected, this property can be overridden by the package.

        Returns:
            List of strings of module names.
        """
        modules = []
        pkg = self.spec["python"].package

        # Packages may be installed in platform-specific or platform-independent
        # site-packages directories
        for directory in {pkg.platlib, pkg.purelib}:
            root = os.path.join(self.prefix, directory)

            # Some Python libraries are packages: collections of modules
            # distributed in directories containing __init__.py files
            for path in fs.find(root, "__init__.py", recursive=True):
                modules.append(
                    path.replace(root + os.sep, "", 1)
                    .replace(os.sep + "__init__.py", "")
                    .replace("/", ".")
                )

            # Some Python libraries are modules: individual *.py files
            # found in the site-packages directory
            for path in fs.find(root, "*.py", recursive=False):
                modules.append(
                    path.replace(root + os.sep, "", 1).replace(".py", "").replace("/", ".")
                )

        modules = [
            mod
            for mod in modules
            if re.match("[a-zA-Z0-9._]+$", mod) and not any(map(mod.startswith, self.skip_modules))
        ]

        tty.debug("Detected the following modules: {0}".format(modules))

        return modules

    @property
    def skip_modules(self) -> Iterable[str]:
        """Names of modules that should be skipped when running tests.

        These are a subset of import_modules. If a module has submodules,
        they are skipped as well (meaning a.b is skipped if a is contained).

        Returns:
            List of strings of module names.
        """
        return []

    def view_file_conflicts(self, view, merge_map):
        """Report all file conflicts, excepting special cases for python.
        Specifically, this does not report errors for duplicate
        __init__.py files for packages in the same namespace.
        """
        conflicts = list(dst for src, dst in merge_map.items() if os.path.exists(dst))

        if conflicts and self.py_namespace:
            ext_map = view.extensions_layout.extension_map(self.extendee_spec)
            namespaces = set(x.package.py_namespace for x in ext_map.values())
            namespace_re = r"site-packages/{0}/__init__.py".format(self.py_namespace)
            find_namespace = lang.match_predicate(namespace_re)
            if self.py_namespace in namespaces:
                conflicts = list(x for x in conflicts if not find_namespace(x))

        return conflicts

    def add_files_to_view(self, view, merge_map, skip_if_exists=True):
        if not self.extendee_spec:
            return super().add_files_to_view(view, merge_map, skip_if_exists)

        bin_dir = self.spec.prefix.bin
        python_prefix = self.extendee_spec.prefix
        python_is_external = self.extendee_spec.external
        global_view = fs.same_path(python_prefix, view.get_projection_for_spec(self.spec))
        for src, dst in merge_map.items():
            if os.path.exists(dst):
                continue
            elif global_view or not fs.path_contains_subdirectory(src, bin_dir):
                view.link(src, dst)
            elif not os.path.islink(src):
                shutil.copy2(src, dst)
                is_script = fs.is_nonsymlink_exe_with_shebang(src)
                if is_script and not python_is_external:
                    fs.filter_file(
                        python_prefix,
                        os.path.abspath(view.get_projection_for_spec(self.spec)),
                        dst,
                    )
            else:
                orig_link_target = os.path.realpath(src)
                new_link_target = os.path.abspath(merge_map[orig_link_target])
                view.link(new_link_target, dst)

    def remove_files_from_view(self, view, merge_map):
        ignore_namespace = False
        if self.py_namespace:
            ext_map = view.extensions_layout.extension_map(self.extendee_spec)
            remaining_namespaces = set(
                spec.package.py_namespace for name, spec in ext_map.items() if name != self.name
            )
            if self.py_namespace in remaining_namespaces:
                namespace_init = lang.match_predicate(
                    r"site-packages/{0}/__init__.py".format(self.py_namespace)
                )
                ignore_namespace = True

        bin_dir = self.spec.prefix.bin
        global_view = self.extendee_spec.prefix == view.get_projection_for_spec(self.spec)

        to_remove = []
        for src, dst in merge_map.items():
            if ignore_namespace and namespace_init(dst):
                continue

            if global_view or not fs.path_contains_subdirectory(src, bin_dir):
                to_remove.append(dst)
            else:
                os.remove(dst)

        view.remove_files(to_remove)

    def test_imports(self) -> None:
        """Attempts to import modules of the installed package."""

        # Make sure we are importing the installed modules,
        # not the ones in the source directory
        python = inspect.getmodule(self).python  # type: ignore[union-attr]
        for module in self.import_modules:
            with test_part(
                self,
                f"test_imports_{module}",
                purpose=f"checking import of {module}",
                work_dir="spack-test",
            ):
                python("-c", f"import {module}")

    def update_external_dependencies(self, extendee_spec=None):
        """
        Ensure all external python packages have a python dependency

        If another package in the DAG depends on python, we use that
        python for the dependency of the external. If not, we assume
        that the external PythonPackage is installed into the same
        directory as the python it depends on.
        """
        # TODO: Include this in the solve, rather than instantiating post-concretization
        if "python" not in self.spec:
            if extendee_spec:
                python = extendee_spec
            elif "python" in self.spec.root:
                python = self.spec.root["python"]
            else:
                python = self.get_external_python_for_prefix()
                if not python.concrete:
                    repo = spack.repo.PATH.repo_for_pkg(python)
                    python.namespace = repo.namespace

                    # Ensure architecture information is present
                    if not python.architecture:
                        host_platform = spack.platforms.host()
                        host_os = host_platform.operating_system("default_os")
                        host_target = host_platform.target("default_target")
                        python.architecture = spack.spec.ArchSpec(
                            (str(host_platform), str(host_os), str(host_target))
                        )
                    else:
                        if not python.architecture.platform:
                            python.architecture.platform = spack.platforms.host()
                        if not python.architecture.os:
                            python.architecture.os = "default_os"
                        if not python.architecture.target:
                            python.architecture.target = archspec.cpu.host().family.name

                    # Ensure compiler information is present
                    if not python.compiler:
                        python.compiler = self.spec.compiler

                    python.external_path = self.spec.external_path
                    python._mark_concrete()
            self.spec.add_dependency_edge(python, depflag=dt.BUILD | dt.LINK | dt.RUN, virtuals=())

    def get_external_python_for_prefix(self):
        """
        For an external package that extends python, find the most likely spec for the python
        it depends on.

        First search: an "installed" external that shares a prefix with this package
        Second search: a configured external that shares a prefix with this package
        Third search: search this prefix for a python package

        Returns:
          spack.spec.Spec: The external Spec for python most likely to be compatible with self.spec
        """
        python_externals_installed = [
            s for s in spack.store.STORE.db.query("python") if s.prefix == self.spec.external_path
        ]
        if python_externals_installed:
            return python_externals_installed[0]

        python_external_config = spack.config.get("packages:python:externals", [])
        python_externals_configured = [
            spack.spec.parse_with_version_concrete(item["spec"])
            for item in python_external_config
            if item["prefix"] == self.spec.external_path
        ]
        if python_externals_configured:
            return python_externals_configured[0]

        python_externals_detection = spack.detection.by_path(
            ["python"], path_hints=[self.spec.external_path]
        )

        python_externals_detected = [
            d.spec
            for d in python_externals_detection.get("python", [])
            if d.prefix == self.spec.external_path
        ]
        if python_externals_detected:
            return python_externals_detected[0]

        raise StopIteration("No external python could be detected for %s to depend on" % self.spec)


class PythonPackage(PythonExtension):
    """Specialized class for packages that are built using pip."""

    #: Package name, version, and extension on PyPI
    pypi: Optional[str] = None

    # To be used in UI queries that require to know which
    # build-system class we are using
    build_system_class = "PythonPackage"
    #: Legacy buildsystem attribute used to deserialize and install old specs
    legacy_buildsystem = "python_pip"

    #: Callback names for install-time test
    install_time_test_callbacks = ["test"]

    build_system("python_pip")

    with spack.multimethod.when("build_system=python_pip"):
        extends("python")
        depends_on("py-pip", type="build")
        # FIXME: technically wheel is only needed when building from source, not when
        # installing a downloaded wheel, but I don't want to add wheel as a dep to every
        # package manually
        depends_on("py-wheel", type="build")

    py_namespace: Optional[str] = None

    @lang.classproperty
    def homepage(cls) -> Optional[str]:  # type: ignore[override]
        if cls.pypi:
            name = cls.pypi.split("/")[0]
            return f"https://pypi.org/project/{name}/"
        return None

    @lang.classproperty
    def url(cls) -> Optional[str]:
        if cls.pypi:
            return f"https://files.pythonhosted.org/packages/source/{cls.pypi[0]}/{cls.pypi}"
        return None

    @lang.classproperty
    def list_url(cls) -> Optional[str]:  # type: ignore[override]
        if cls.pypi:
            name = cls.pypi.split("/")[0]
            return f"https://pypi.org/simple/{name}/"
        return None

    @property
    def headers(self) -> HeaderList:
        """Discover header files in platlib."""

        # Remove py- prefix in package name
        name = self.spec.name[3:]

        # Headers may be in either location
        include = self.prefix.join(self.spec["python"].package.include).join(name)
        platlib = self.prefix.join(self.spec["python"].package.platlib).join(name)
        headers = fs.find_all_headers(include) + fs.find_all_headers(platlib)

        if headers:
            return headers

        msg = "Unable to locate {} headers in {} or {}"
        raise NoHeadersError(msg.format(self.spec.name, include, platlib))

    @property
    def libs(self) -> LibraryList:
        """Discover libraries in platlib."""

        # Remove py- prefix in package name
        name = self.spec.name[3:]

        root = self.prefix.join(self.spec["python"].package.platlib).join(name)

        libs = fs.find_all_libraries(root, recursive=True)

        if libs:
            return libs

        msg = "Unable to recursively locate {} libraries in {}"
        raise NoLibrariesError(msg.format(self.spec.name, root))


@spack.builder.builder("python_pip")
class PythonPipBuilder(BaseBuilder):
    phases = ("install",)

    #: Names associated with package methods in the old build-system format
    legacy_methods = ("test",)

    #: Same as legacy_methods, but the signature is different
    legacy_long_methods = ("install_options", "global_options", "config_settings")

    #: Names associated with package attributes in the old build-system format
    legacy_attributes = ("archive_files", "build_directory", "install_time_test_callbacks")

    #: Callback names for install-time test
    install_time_test_callbacks = ["test"]

    @staticmethod
    def std_args(cls) -> List[str]:
        return [
            # Verbose
            "-vvv",
            # Disable prompting for input
            "--no-input",
            # Disable the cache
            "--no-cache-dir",
            # Don't check to see if pip is up-to-date
            "--disable-pip-version-check",
            # Install packages
            "install",
            # Don't install package dependencies
            "--no-deps",
            # Overwrite existing packages
            "--ignore-installed",
            # Use env vars like PYTHONPATH
            "--no-build-isolation",
            # Don't warn that prefix.bin is not in PATH
            "--no-warn-script-location",
            # Ignore the PyPI package index
            "--no-index",
        ]

    @property
    def build_directory(self) -> str:
        """The root directory of the Python package.

        This is usually the directory containing one of the following files:

        * ``pyproject.toml``
        * ``setup.cfg``
        * ``setup.py``
        """
        return self.pkg.stage.source_path

    def config_settings(self, spec: Spec, prefix: Prefix) -> Mapping[str, object]:
        """Configuration settings to be passed to the PEP 517 build backend.

        Requires pip 22.1 or newer for keys that appear only a single time,
        or pip 23.1 or newer if the same key appears multiple times.

        Args:
            spec: Build spec.
            prefix: Installation prefix.

        Returns:
            Possibly nested dictionary of KEY, VALUE settings.
        """
        return {}

    def install_options(self, spec: Spec, prefix: Prefix) -> Iterable[str]:
        """Extra arguments to be supplied to the setup.py install command.

        Requires pip 23.0 or older.

        Args:
            spec: Build spec.
            prefix: Installation prefix.

        Returns:
            List of options.
        """
        return []

    def global_options(self, spec: Spec, prefix: Prefix) -> Iterable[str]:
        """Extra global options to be supplied to the setup.py call before the install
        or bdist_wheel command.

        Deprecated in pip 23.1.

        Args:
            spec: Build spec.
            prefix: Installation prefix.

        Returns:
            List of options.
        """
        return []

    def install(self, pkg: PythonPackage, spec: Spec, prefix: Prefix) -> None:
        """Install everything from build directory."""

        args = PythonPipBuilder.std_args(pkg) + [f"--prefix={prefix}"]

        for setting in _flatten_dict(self.config_settings(spec, prefix)):
            args.append(f"--config-settings={setting}")
        for option in self.install_options(spec, prefix):
            args.append(f"--install-option={option}")
        for option in self.global_options(spec, prefix):
            args.append(f"--global-option={option}")

        if pkg.stage.archive_file and pkg.stage.archive_file.endswith(".whl"):
            args.append(pkg.stage.archive_file)
        else:
            args.append(".")

        pip = spec["python"].command
        # Hide user packages, since we don't have build isolation. This is
        # necessary because pip / setuptools may run hooks from arbitrary
        # packages during the build. There is no equivalent variable to hide
        # system packages, so this is not reliable for external Python.
        pip.add_default_env("PYTHONNOUSERSITE", "1")
        pip.add_default_arg("-m")
        pip.add_default_arg("pip")
        with fs.working_dir(self.build_directory):
            pip(*args)

    spack.builder.run_after("install")(execute_install_time_tests)