Debian Codegraph @

bindings/python/setup.py

raw symbols SCIP
1 # SPDX-License-Identifier: GPL-2.0-or-later
2 # SPDX-FileCopyrightText: 2022 Bartosz Golaszewski <[email protected]>
3
4 from os import getenv, path, unlink
5 from shutil import copytree, rmtree
6
7 from setuptools import Extension, find_packages, setup
8 from setuptools.command.build_ext import build_ext as orig_build_ext
9 from setuptools.command.sdist import log
10 from setuptools.command.sdist import sdist as orig_sdist
11 from setuptools.errors import BaseError
12
13 LINK_SYSTEM_LIBGPIOD = getenv("LINK_SYSTEM_LIBGPIOD") == "1"
14 LIBGPIOD_MINIMUM_VERSION = "2.1"
15 LIBGPIOD_VERSION = getenv("LIBGPIOD_VERSION")
16 SRC_BASE_URL = "https://mirrors.edge.kernel.org/pub/software/libs/libgpiod/"
17 TAR_FILENAME = "libgpiod-{version}.tar.gz"
18 ASC_FILENAME = "sha256sums.asc"
19 SHA256_CHUNK_SIZE = 2048
20
21 # __version__
22 with open("gpiod/version.py", "r") as fd:
23 exec(fd.read())
24
25
26 def sha256(filename):
27 """
28 Return a sha256sum for a specific filename, loading the file in chunks
29 to avoid potentially excessive memory use.
30 """
31 from hashlib import sha256
32
33 sha256sum = sha256()
34 with open(filename, "rb") as f:
35 for chunk in iter(lambda: f.read(SHA256_CHUNK_SIZE), b""):
36 sha256sum.update(chunk)
37
38 return sha256sum.hexdigest()
39
40
41 def find_sha256sum(asc_file, tar_filename):
42 """
43 Search through a local copy of sha256sums.asc for a specific filename
44 and return the associated sha256 sum.
45 """
46 with open(asc_file, "r") as f:
47 for line in f:
48 line = line.strip().split(" ")
49 if len(line) == 2 and line[1] == tar_filename:
50 return line[0]
51
52 raise BaseError(f"no signature found for {tar_filename}")
53
54
55 def fetch_tarball(command):
56 """
57 Verify the requested LIBGPIOD_VERSION tarball exists in sha256sums.asc,
58 fetch it from https://mirrors.edge.kernel.org/pub/software/libs/libgpiod/
59 and verify its sha256sum.
60
61 If the check passes, extract the tarball and copy the lib and include
62 dirs into our source tree.
63 """
64
65 # If no LIBGPIOD_VERSION is specified in env, just run the command
66 if LIBGPIOD_VERSION is None:
67 return command
68
69 # If LIBGPIOD_VERSION is specified, apply the tarball wrapper
70 def wrapper(self):
71 # Just-in-time import of tarfile and urllib.request so these are
72 # not required for Yocto to build a vendored or linked package
73 import tarfile
74 from tempfile import TemporaryDirectory
75 from urllib.request import urlretrieve
76
77 from packaging.version import Version
78
79 # The "build" frontend will run setup.py twice within the same
80 # temporary output directory. First for "sdist" and then for "wheel"
81 # This would cause the build to fail with dirty "lib" and "include"
82 # directories.
83 # If the version in "libgpiod-version.txt" already matches our
84 # requested tarball, then skip the fetch altogether.
85 try:
86 if open("libgpiod-version.txt", "r").read() == LIBGPIOD_VERSION:
87 log.info(f"skipping tarball fetch")
88 command(self)
89 return
90 except OSError:
91 pass
92
93 # Early exit for build tree with dirty lib/include dirs
94 for check_dir in "lib", "include":
95 if path.isdir(f"./{check_dir}"):
96 raise BaseError(f"refusing to overwrite ./{check_dir}")
97
98 with TemporaryDirectory(prefix="libgpiod-") as temp_dir:
99 tarball_filename = TAR_FILENAME.format(version=LIBGPIOD_VERSION)
100 tarball_url = f"{SRC_BASE_URL}{tarball_filename}"
101 asc_url = f"{SRC_BASE_URL}{ASC_FILENAME}"
102
103 log.info(f"fetching: {asc_url}")
104
105 asc_filename, _ = urlretrieve(asc_url, path.join(temp_dir, ASC_FILENAME))
106
107 tarball_sha256 = find_sha256sum(asc_filename, tarball_filename)
108
109 if Version(LIBGPIOD_VERSION) < Version(LIBGPIOD_MINIMUM_VERSION):
110 raise BaseError(f"requires libgpiod>={LIBGPIOD_MINIMUM_VERSION}")
111
112 log.info(f"fetching: {tarball_url}")
113
114 downloaded_tarball, _ = urlretrieve(
115 tarball_url, path.join(temp_dir, tarball_filename)
116 )
117
118 log.info(f"verifying: {tarball_filename}")
119 if sha256(downloaded_tarball) != tarball_sha256:
120 raise BaseError(f"signature mismatch for {tarball_filename}")
121
122 # Unpack the downloaded tarball
123 log.info(f"unpacking: {tarball_filename}")
124 with tarfile.open(downloaded_tarball) as f:
125 f.extractall(temp_dir)
126
127 # Copy the include and lib directories we need to build libgpiod
128 base_dir = path.join(temp_dir, f"libgpiod-{LIBGPIOD_VERSION}")
129 copytree(path.join(base_dir, "include"), "./include")
130 copytree(path.join(base_dir, "lib"), "./lib")
131
132 # Save the libgpiod version for sdist
133 open("libgpiod-version.txt", "w").write(LIBGPIOD_VERSION)
134
135 # Run the command
136 command(self)
137
138 # Clean up the build directory
139 rmtree("./lib", ignore_errors=True)
140 rmtree("./include", ignore_errors=True)
141 unlink("libgpiod-version.txt")
142
143 return wrapper
144
145
146 class build_ext(orig_build_ext):
147 """
148 Wrap build_ext to amend the module sources and settings to build
149 the bindings and gpiod into a combined module when a version is
150 specified and LINK_SYSTEM_LIBGPIOD=1 is not present in env.
151
152 run is wrapped with @fetch_tarball in order to fetch the sources
153 needed to build binary wheels when LIBGPIOD_VERSION is specified, eg:
154
155 LIBGPIOD_VERSION="2.0.2" python3 -m build .
156 """
157
158 @fetch_tarball
159 def run(self):
160 # Try to get the gpiod version from the .txt file included in sdist
161 try:
162 libgpiod_version = open("libgpiod-version.txt", "r").read()
163 except OSError:
164 libgpiod_version = LIBGPIOD_VERSION
165
166 if libgpiod_version and not LINK_SYSTEM_LIBGPIOD:
167 # When building the extension from an sdist with a vendored
168 # amend gpiod._ext sources and settings accordingly.
169 gpiod_ext = self.ext_map["gpiod._ext"]
170 gpiod_ext.sources += [
171 "lib/chip.c",
172 "lib/chip-info.c",
173 "lib/edge-event.c",
174 "lib/info-event.c",
175 "lib/internal.c",
176 "lib/line-config.c",
177 "lib/line-info.c",
178 "lib/line-request.c",
179 "lib/line-settings.c",
180 "lib/misc.c",
181 "lib/request-config.c",
182 ]
183 gpiod_ext.libraries = []
184 gpiod_ext.include_dirs = ["include", "lib", "gpiod/ext"]
185 gpiod_ext.extra_compile_args.append(
186 f'-DGPIOD_VERSION_STR="{libgpiod_version}"',
187 )
188
189 super().run()
190
191
192 class sdist(orig_sdist):
193 """
194 Wrap sdist in order to fetch the libgpiod source files for vendoring
195 into a source distribution.
196
197 run is wrapped with @fetch_tarball in order to fetch the sources
198 needed to build binary wheels when LIBGPIOD_VERSION is specified, eg:
199
200 LIBGPIOD_VERSION="2.0.2" python3 -m build . --sdist
201 """
202
203 @fetch_tarball
204 def run(self):
205 super().run()
206
207
208 gpiod_ext = Extension(
209 "gpiod._ext",
210 sources=[
211 "gpiod/ext/chip.c",
212 "gpiod/ext/common.c",
213 "gpiod/ext/line-config.c",
214 "gpiod/ext/line-settings.c",
215 "gpiod/ext/module.c",
216 "gpiod/ext/request.c",
217 ],
218 define_macros=[("_GNU_SOURCE", "1")],
219 libraries=["gpiod"],
220 extra_compile_args=["-Wall", "-Wextra"],
221 )
222
223 setup(
224 name="gpiod",
225 url="https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git",
226 packages=find_packages(exclude=["tests", "tests.*"]),
227 package_data={"gpiod": ["py.typed"]},
228 python_requires=">=3.9.0",
229 ext_modules=[gpiod_ext],
230 cmdclass={"build_ext": build_ext, "sdist": sdist},
231 version=__version__,
232 author="Bartosz Golaszewski",
233 author_email="[email protected]",
234 description="Python bindings for libgpiod",
235 long_description=open("README.md", "r").read(),
236 long_description_content_type="text/markdown",
237 platforms=["linux"],
238 license="LGPLv2.1",
239 )