| 1 |
# |
| 2 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
# you may not use this file except in compliance with the License. |
| 4 |
# You may obtain a copy of the License at |
| 5 |
# |
| 6 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
# |
| 8 |
# Unless required by applicable law or agreed to in writing, software |
| 9 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
# See the License for the specific language governing permissions and |
| 12 |
# limitations under the License. |
| 13 |
# |
| 14 |
# Authors: |
| 15 |
# Chandan Singh <[email protected]> |
| 16 |
|
| 17 |
# |
| 18 |
# This plugin was originally developped in the https://github.com/apache/buildstream/ |
| 19 |
# repository and was copied from 1a3c707a6c46573ab159de64ac9cd92e7f6027e6 |
| 20 |
# |
| 21 |
|
| 22 |
""" |
| 23 |
pip - stage python packages using pip |
| 24 |
===================================== |
| 25 |
|
| 26 |
**Host depndencies:** |
| 27 |
|
| 28 |
* ``pip`` python module |
| 29 |
|
| 30 |
This plugin will download source distributions for specified packages using |
| 31 |
``pip`` but will not install them. It is expected that the elements using this |
| 32 |
source will install the downloaded packages. |
| 33 |
|
| 34 |
Downloaded tarballs will be stored in a directory called ".bst_pip_downloads". |
| 35 |
|
| 36 |
**Usage:** |
| 37 |
|
| 38 |
.. code:: yaml |
| 39 |
|
| 40 |
# Specify the pip source kind |
| 41 |
kind: pip |
| 42 |
|
| 43 |
# Optionally specify index url, defaults to PyPi |
| 44 |
# This url is used to discover new versions of packages and download them |
| 45 |
# Projects intending to mirror their sources to a permanent location should |
| 46 |
# use an aliased url, and declare the alias in the project configuration |
| 47 |
url: https://mypypi.example.com/simple |
| 48 |
|
| 49 |
# Optionally specify the path to requirements files |
| 50 |
# Note that either 'requirements-files' or 'packages' must be defined |
| 51 |
requirements-files: |
| 52 |
- requirements.txt |
| 53 |
|
| 54 |
# Optionally specify a list of additional packages |
| 55 |
# Note that either 'requirements-files' or 'packages' must be defined |
| 56 |
packages: |
| 57 |
- flake8 |
| 58 |
|
| 59 |
# Specify the ref. It is a list of strings of format |
| 60 |
# "<package-name>==<version>", separated by "\\n". |
| 61 |
# Usually this will be contents of a requirements.txt file where all |
| 62 |
# package versions have been frozen. |
| 63 |
ref: "flake8==3.5.0\\nmccabe==0.6.1\\npkg-resources==0.0.0\\npycodestyle==2.3.1\\npyflakes==1.6.0" |
| 64 |
|
| 65 |
See `built-in functionality doumentation |
| 66 |
<https://docs.buildstream.build/master/buildstream.source.html#core-source-builtins>`_ for |
| 67 |
details on common configuration options for sources. |
| 68 |
|
| 69 |
|
| 70 |
Reporting `SourceInfo <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceInfo>`_ |
| 71 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 72 |
The pip source reports the python package index (PyPI) instance as the *url*. |
| 73 |
|
| 74 |
Further, the pip source reports the `SourceInfoMedium.PYTHON_PACKAGE_INDEX |
| 75 |
<https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceInfoMedium.PYTHON_PACKAGE_INDEX>`_ |
| 76 |
*medium* and the `SourceVersionType.INDEXED_VERSION |
| 77 |
<https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceVersionType.INDEXED_VERSION>`_ |
| 78 |
*version_type*, for which it reports the tracked package version as the *version* and the *version_guess*. |
| 79 |
|
| 80 |
Additionally, the pip source reports the package name through |
| 81 |
the ``package-name`` key of the *extra_data*. |
| 82 |
|
| 83 |
The pip source will report one SourceInfo instance for each of the packages discovered in tracking. |
| 84 |
""" |
| 85 |
|
| 86 |
import hashlib |
| 87 |
import os |
| 88 |
import re |
| 89 |
|
| 90 |
from buildstream import Source, SourceError |
| 91 |
from buildstream import utils |
| 92 |
|
| 93 |
# |
| 94 |
# Soft import of buildstream symbols only available in newer versions |
| 95 |
# |
| 96 |
# The BST_MIN_VERSION will provide a better user experience. |
| 97 |
# |
| 98 |
try: |
| 99 |
from buildstream import SourceInfoMedium, SourceVersionType |
| 100 |
except ImportError: |
| 101 |
pass |
| 102 |
|
| 103 |
_OUTPUT_DIRNAME = ".bst_pip_downloads" |
| 104 |
_PYPI_INDEX_URL = "https://pypi.org/simple/" |
| 105 |
|
| 106 |
# Used only for finding pip command |
| 107 |
_PYTHON_VERSIONS = [ |
| 108 |
"python", # when running in a venv, we might not have the exact version |
| 109 |
"python2.7", |
| 110 |
"python3.0", |
| 111 |
"python3.1", |
| 112 |
"python3.2", |
| 113 |
"python3.3", |
| 114 |
"python3.4", |
| 115 |
"python3.5", |
| 116 |
"python3.6", |
| 117 |
"python3.7", |
| 118 |
"python3.8", |
| 119 |
"python3.9", |
| 120 |
"python3.10", |
| 121 |
"python3.11", |
| 122 |
"python3.12", |
| 123 |
"python3", |
| 124 |
] |
| 125 |
|
| 126 |
# List of allowed extensions taken from |
| 127 |
# https://docs.python.org/3/distutils/sourcedist.html. |
| 128 |
# Names of source distribution archives must be of the form |
| 129 |
# '%{package-name}-%{version}.%{extension}'. |
| 130 |
_SDIST_RE = re.compile( |
| 131 |
r"^([\w.-]+?)-((?:[\d.]+){2,})\.(?:tar|tar.bz2|tar.gz|tar.xz|tar.Z|zip)$", |
| 132 |
re.IGNORECASE, |
| 133 |
) |
| 134 |
|
| 135 |
|
| 136 |
class PipSource(Source): |
| 137 |
# pylint: disable=attribute-defined-outside-init |
| 138 |
BST_MIN_VERSION = "2.5" |
| 139 |
|
| 140 |
# We need access to previous sources at track time to use requirements.txt |
| 141 |
# but not at fetch time as self.ref should contain sufficient information |
| 142 |
# for this plugin |
| 143 |
BST_REQUIRES_PREVIOUS_SOURCES_TRACK = True |
| 144 |
|
| 145 |
def configure(self, node): |
| 146 |
node.validate_keys(["url", "packages", "ref", "requirements-files"] + Source.COMMON_CONFIG_KEYS) |
| 147 |
self.ref = node.get_str("ref", None) |
| 148 |
self.original_url = node.get_str("url", _PYPI_INDEX_URL) |
| 149 |
self.index_url = self.translate_url(self.original_url) |
| 150 |
self.packages = node.get_str_list("packages", []) |
| 151 |
self.requirements_files = node.get_str_list("requirements-files", []) |
| 152 |
|
| 153 |
if not (self.packages or self.requirements_files): |
| 154 |
raise SourceError("{}: Either 'packages' or 'requirements-files' must be specified".format(self)) |
| 155 |
|
| 156 |
def preflight(self): |
| 157 |
# Try to find a pip version that spports download command |
| 158 |
self.host_pip = None |
| 159 |
for python in reversed(_PYTHON_VERSIONS): |
| 160 |
try: |
| 161 |
host_python = utils.get_host_tool(python) |
| 162 |
rc = self.call([host_python, "-m", "pip", "download", "--help"]) |
| 163 |
if rc == 0: |
| 164 |
self.host_pip = [host_python, "-m", "pip"] |
| 165 |
break |
| 166 |
except utils.ProgramNotFoundError: |
| 167 |
pass |
| 168 |
|
| 169 |
if self.host_pip is None: |
| 170 |
raise SourceError("{}: Unable to find a suitable pip command".format(self)) |
| 171 |
|
| 172 |
def get_unique_key(self): |
| 173 |
return [self.original_url, self.ref] |
| 174 |
|
| 175 |
def is_cached(self): |
| 176 |
return os.path.exists(self._mirror) and os.listdir(self._mirror) |
| 177 |
|
| 178 |
def get_ref(self): |
| 179 |
return self.ref |
| 180 |
|
| 181 |
def load_ref(self, node): |
| 182 |
self.ref = node.get_str("ref", None) |
| 183 |
|
| 184 |
def set_ref(self, ref, node): |
| 185 |
node["ref"] = self.ref = ref |
| 186 |
|
| 187 |
def track(self, previous_sources_dir): # pylint: disable=arguments-differ |
| 188 |
# XXX pip does not offer any public API other than the CLI tool so it |
| 189 |
# is not feasible to correctly parse the requirements file or to check |
| 190 |
# which package versions pip is going to install. |
| 191 |
# See https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program |
| 192 |
# for details. |
| 193 |
# As a result, we have to wastefully install the packages during track. |
| 194 |
with self.tempdir() as tmpdir: |
| 195 |
install_args = self.host_pip + [ |
| 196 |
"download", |
| 197 |
"--no-binary", |
| 198 |
":all:", |
| 199 |
"--index-url", |
| 200 |
self.index_url, |
| 201 |
"--dest", |
| 202 |
tmpdir, |
| 203 |
] |
| 204 |
for requirement_file in self.requirements_files: |
| 205 |
fpath = os.path.join(previous_sources_dir, requirement_file) |
| 206 |
install_args += ["-r", fpath] |
| 207 |
install_args += self.packages |
| 208 |
|
| 209 |
self.call(install_args, fail="Failed to install python packages") |
| 210 |
reqs = self._parse_sdist_names(tmpdir) |
| 211 |
|
| 212 |
return "\n".join(["{}=={}".format(pkg, ver) for pkg, ver in reqs]) |
| 213 |
|
| 214 |
def fetch(self): # pylint: disable=arguments-differ |
| 215 |
with self.tempdir() as tmpdir: |
| 216 |
packages = self.ref.strip().split("\n") |
| 217 |
package_dir = os.path.join(tmpdir, "packages") |
| 218 |
os.makedirs(package_dir) |
| 219 |
self.call( |
| 220 |
[ |
| 221 |
*self.host_pip, |
| 222 |
"download", |
| 223 |
"--no-binary", |
| 224 |
":all:", |
| 225 |
"--index-url", |
| 226 |
self.index_url, |
| 227 |
"--dest", |
| 228 |
package_dir, |
| 229 |
*packages, |
| 230 |
], |
| 231 |
fail="Failed to install python packages: {}".format(packages), |
| 232 |
) |
| 233 |
|
| 234 |
# If the mirror directory already exists, assume that some other |
| 235 |
# process has fetched the sources before us and ensure that we do |
| 236 |
# not raise an error in that case. |
| 237 |
try: |
| 238 |
utils.move_atomic(package_dir, self._mirror) |
| 239 |
except utils.DirectoryExistsError: |
| 240 |
# Another process has beaten us and has fetched the sources |
| 241 |
# before us. |
| 242 |
pass |
| 243 |
except OSError as e: |
| 244 |
raise SourceError( |
| 245 |
"{}: Failed to move downloaded pip packages from '{}' to '{}': {}".format( |
| 246 |
self, package_dir, self._mirror, e |
| 247 |
) |
| 248 |
) from e |
| 249 |
|
| 250 |
def stage(self, directory): |
| 251 |
with self.timed_activity("Staging Python packages", silent_nested=True): |
| 252 |
utils.copy_files(self._mirror, os.path.join(directory, _OUTPUT_DIRNAME)) |
| 253 |
|
| 254 |
def collect_source_info(self): |
| 255 |
infos = [] |
| 256 |
packages_versions = self.ref.splitlines() |
| 257 |
for package_version in packages_versions: |
| 258 |
split = package_version.split("==") |
| 259 |
package = split[0] |
| 260 |
version = split[1] |
| 261 |
infos.append( |
| 262 |
self.create_source_info( |
| 263 |
self.index_url, |
| 264 |
SourceInfoMedium.PYTHON_PACKAGE_INDEX, |
| 265 |
SourceVersionType.INDEXED_VERSION, |
| 266 |
version, |
| 267 |
version_guess=version, |
| 268 |
extra_data={"package-name": package}, |
| 269 |
) |
| 270 |
) |
| 271 |
return infos |
| 272 |
|
| 273 |
# Directory where this source should stage its files |
| 274 |
# |
| 275 |
@property |
| 276 |
def _mirror(self): |
| 277 |
if not self.ref: |
| 278 |
return None |
| 279 |
return os.path.join( |
| 280 |
self.get_mirror_directory(), |
| 281 |
utils.url_directory_name(self.original_url), |
| 282 |
hashlib.sha256(self.ref.encode()).hexdigest(), |
| 283 |
) |
| 284 |
|
| 285 |
# Parse names of downloaded source distributions |
| 286 |
# |
| 287 |
# Args: |
| 288 |
# basedir (str): Directory containing source distribution archives |
| 289 |
# |
| 290 |
# Returns: |
| 291 |
# (list): List of (package_name, version) tuples in sorted order |
| 292 |
# |
| 293 |
def _parse_sdist_names(self, basedir): |
| 294 |
reqs = [] |
| 295 |
for f in os.listdir(basedir): |
| 296 |
pkg = _match_package_name(f) |
| 297 |
if pkg is not None: |
| 298 |
reqs.append(pkg) |
| 299 |
|
| 300 |
return sorted(reqs) |
| 301 |
|
| 302 |
|
| 303 |
# Extract the package name and version of a source distribution |
| 304 |
# |
| 305 |
# Args: |
| 306 |
# filename (str): Filename of the source distribution |
| 307 |
# |
| 308 |
# Returns: |
| 309 |
# (tuple): A tuple of (package_name, version) |
| 310 |
# |
| 311 |
def _match_package_name(filename): |
| 312 |
pkg_match = _SDIST_RE.match(filename) |
| 313 |
if pkg_match is None: |
| 314 |
return None |
| 315 |
return pkg_match.groups() |
| 316 |
|
| 317 |
|
| 318 |
def setup(): |
| 319 |
return PipSource |