File: install_dev_repos.py

package info (click to toggle)
spyder 5.4.2%2Bds-5%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 25,668 kB
  • sloc: python: 103,527; sh: 511; javascript: 131; xml: 121; cpp: 67; makefile: 22; ansic: 19; erlang: 15; lisp: 11; java: 5
file content (174 lines) | stat: -rwxr-xr-x 5,239 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
#!/usr/bin/env python3
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#

"""
Helper script for installing spyder and external-deps locally in editable mode.
"""

import argparse
import os
import sys
from logging import Formatter, StreamHandler, getLogger
from pathlib import Path
from subprocess import check_output

from importlib_metadata import PackageNotFoundError, distribution
from packaging.requirements import Requirement

# Remove current/script directory from sys.path[0] if added by the Python invocation,
# otherwise Spyder's install status may be incorrectly determined.
SYS_PATH_0 = Path(sys.path[0]).resolve()
if SYS_PATH_0 in (Path(__file__).resolve().parent, Path.cwd()):
    sys.path.pop(0)

DEVPATH = Path(__file__).resolve().parent
DEPS_PATH = DEVPATH / 'external-deps'
BASE_COMMAND = [sys.executable, '-m', 'pip', 'install', '--no-deps']

REPOS = {}
for p in [DEVPATH] + list(DEPS_PATH.iterdir()):
    if (
        p.name.startswith('.')
        or not p.is_dir()
        and not ((p / 'setup.py').exists() or (p / 'pyproject.toml').exists())
    ):
        continue

    try:
        dist = distribution(p.name)
    except PackageNotFoundError:
        dist = None
        editable = None
    else:
        editable = (p == dist._path or p in dist._path.parents)

        # This fixes detecting that PyLSP was installed in editable mode under
        # some scenarios.
        # Fixes spyder-ide/spyder#19712
        if p.name == 'python-lsp-server':
            for f in dist.files:
                if 'editable' in f.name:
                    editable = True
                    break

    REPOS[p.name] = {'repo': p, 'dist': dist, 'editable': editable}

# ---- Setup logger
fmt = Formatter('%(asctime)s [%(levelname)s] [%(name)s] -> %(message)s')
h = StreamHandler()
h.setFormatter(fmt)
logger = getLogger('InstallDevRepos')
logger.addHandler(h)
logger.setLevel('INFO')


def get_python_lsp_version():
    """Get current version to pass it to setuptools-scm."""
    req_file = DEVPATH / 'requirements' / 'main.yml'
    with open(req_file, 'r', encoding='utf-8') as f:
        for line in f:
            if 'python-lsp-server' not in line:
                continue
            line = line.split('-')[-1]
            specifiers = Requirement(line).specifier
            break
        else:
            return "0.0.0"

    for specifier in specifiers:
        if "=" in specifier.operator:
            return specifier.version
    else:
        return "0.0.0"


def install_repo(name, not_editable=False):
    """
    Install a single repo from source located in spyder/external-deps, ignoring
    dependencies, in standard or editable mode.

    Parameters
    ----------
    name : str
        Must be 'spyder' or the distribution name of a repo in
        spyder/external-deps.
    not_editable : bool (False)
        Install repo in standard mode (True) or editable mode (False).
        Editable mode uses pip's `-e` flag.

    """
    try:
        repo_path = REPOS[name]['repo']
    except KeyError:
        logger.warning('Distribution %r not valid. Must be one of %s',
                       name, set(REPOS.keys()))
        return

    install_cmd = BASE_COMMAND.copy()

    # PyLSP requires pretend version
    env = None
    if name == 'python-lsp-server':
        env = {**os.environ}
        env.update(
            {'SETUPTOOLS_SCM_PRETEND_VERSION': get_python_lsp_version()})

    if not_editable:
        mode = 'standard'
    else:
        # Add edit flag to install command
        install_cmd.append('-e')
        mode = 'editable'

    logger.info('Installing %r from source in %s mode.', name, mode)
    install_cmd.append(repo_path.as_posix())
    check_output(install_cmd, env=env)


def main(install=tuple(REPOS.keys()), no_install=tuple(), **kwargs):
    """
    Install all subrepos from source.

    Parameters
    ----------
    install : iterable (spyder and all repos in spyder/external-deps)
        Distribution names of repos to be installed from spyder/external-deps.
    no_install : iterable ()
        Distribution names to exclude from install.
    **kwargs :
        Keyword arguments passed to `install_repo`.

    """
    _install = set(install) - set(no_install)
    for repo in _install:
        install_repo(repo, **kwargs)


if __name__ == '__main__':
    # ---- Parse command line
    parser = argparse.ArgumentParser(
        usage="python install_dev_repos.py [options]")
    parser.add_argument(
        '--install', nargs='+',
        default=REPOS.keys(),
        help="Space-separated list of distribution names to install, e.g. "
             "qtconsole spyder-kernels. If option not provided, then all of "
             "the repos in spyder/external-deps are installed"
    )
    parser.add_argument(
        '--no-install', nargs='+', default=[],
        help="Space-separated list of distribution names to exclude from "
             "install. Default is empty list."
    )
    parser.add_argument(
        '--not-editable', action='store_true', default=False,
        help="Install in standard mode, not editable mode."
    )

    args = parser.parse_args()

    # ---- Install repos locally
    main(**vars(args))