Skip to content

Commit d776a97

Browse files
authored
Merge pull request #7 from dwoz/relenvimport
Refactor common module to avoid setuptools import
2 parents ed11d22 + e141901 commit d776a97

File tree

4 files changed

+100
-86
lines changed

4 files changed

+100
-86
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
0.1.8
2+
=====
3+
- Refactor to support early import of ppbt.common at relenv runtime.
4+
5+
16
0.1.7
27
=====
38
- Use tar instead of tarfile to create toolchain tarballs

pyproject.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ requires = [
44
"wheel>=0.31.0",
55
"twine>=1.11.0"
66
]
7-
build-backend = "build"
8-
backend-path = ["src/ppbt"]
7+
build-backend = "ppbt.build"
8+
backend-path = ["src"]
99

1010
[tool.pytest.ini_options]
1111
pythonpath = [

src/ppbt/build.py

Lines changed: 7 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,14 @@
1414
import shutil
1515
import subprocess
1616
import sys
17-
import tarfile
1817
import time
1918
import urllib.error
2019
import urllib.request
2120

2221
from setuptools.build_meta import build_sdist, build_wheel
2322

23+
import ppbt.common
24+
2425
CT_NG_VER = "1.26.0"
2526
CT_URL = "http://crosstool-ng.org/download/crosstool-ng/crosstool-ng-{version}.tar.bz2"
2627
CT_GIT_REPO = "https://github.com/crosstool-ng/crosstool-ng.git"
@@ -35,69 +36,10 @@
3536
_build_sdist = build_sdist
3637

3738

38-
class BuildError(RuntimeError):
39+
class BuildError(ppbt.common.PPBTException, RuntimeError):
3940
"""Generic build error."""
4041

4142

42-
def build_arch():
43-
"""
44-
Return the current machine.
45-
"""
46-
machine = platform.machine()
47-
return machine.lower()
48-
49-
50-
def get_triplet(machine=None, plat=None):
51-
"""
52-
Get the target triplet for the specified machine and platform.
53-
54-
If any of the args are None, it will try to deduce what they should be.
55-
56-
:param machine: The machine for the triplet
57-
:type machine: str
58-
:param plat: The platform for the triplet
59-
:type plat: str
60-
61-
:raises BuildError: If the platform is unknown
62-
63-
:return: The target triplet
64-
:rtype: str
65-
"""
66-
if not plat:
67-
plat = sys.platform
68-
if not machine:
69-
machine = build_arch()
70-
if plat == "darwin":
71-
return f"{machine}-macos"
72-
elif plat == "win32":
73-
return f"{machine}-win"
74-
elif plat == "linux":
75-
return f"{machine}-linux-gnu"
76-
else:
77-
raise BuildError(f"Unknown platform {plat}")
78-
79-
80-
def extract_archive(to_dir, archive):
81-
"""
82-
Extract an archive to a specific location.
83-
84-
:param to_dir: The directory to extract to
85-
:type to_dir: str
86-
:param archive: The archive to extract
87-
:type archive: str
88-
"""
89-
if archive.endswith("tgz"):
90-
read_type = "r:gz"
91-
elif archive.endswith("xz"):
92-
read_type = "r:xz"
93-
elif archive.endswith("bz2"):
94-
read_type = "r:bz2"
95-
else:
96-
read_type = "r"
97-
with tarfile.open(archive, read_type) as t:
98-
t.extractall(to_dir)
99-
100-
10143
def get_download_location(url, dest):
10244
"""
10345
Get the full path to where the url will be downloaded to.
@@ -224,7 +166,7 @@ def build_ppbt(branch=None, use_tempdir=True):
224166
if not ctngdir.exists():
225167
url = CT_URL.format(version=CT_NG_VER)
226168
archive = download_url(url, build)
227-
extract_archive(build, archive)
169+
ppbt.common.extract_archive(build, archive)
228170

229171
os.chdir(ctngdir)
230172
ctng = ctngdir / "ct-ng"
@@ -237,15 +179,15 @@ def build_ppbt(branch=None, use_tempdir=True):
237179
runcmd(["make"])
238180
print(f"Using compiled ct-ng: {ctng}")
239181

240-
arch = build_arch()
182+
arch = ppbt.common.build_arch()
241183
machine = platform.machine()
242184
toolchain = cwd / "src" / "ppbt" / "_toolchain"
243185

244186
print(f"toolchain: {toolchain}")
245187

246188
toolchain.mkdir(exist_ok=True)
247189

248-
triplet = get_triplet(arch)
190+
triplet = ppbt.common.get_triplet(arch)
249191
archdir = build / triplet
250192
print(f"Arch dir is {archdir}")
251193
if archdir.exists():
@@ -296,7 +238,7 @@ def build_ppbt(branch=None, use_tempdir=True):
296238
else:
297239
print(f"Fetchin patchelf source: {PATCHELF_SOURCE}")
298240
archive = download_url(PATCHELF_SOURCE, build)
299-
extract_archive(build, archive)
241+
ppbt.common.extract_archive(build, archive)
300242
os.chdir(source)
301243

302244
if patchelf.exists():

src/ppbt/common.py

Lines changed: 86 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,42 +8,109 @@
88
import csv
99
import logging
1010
import pathlib
11+
import platform
12+
import sys
13+
import tarfile
1114

12-
from .build import build_arch, extract_archive, get_triplet
15+
__version__ = "0.1.8"
16+
17+
log = logging.getLogger(__name__)
1318

14-
__version__ = "0.1.7"
1519

16-
triplet = get_triplet(build_arch())
20+
class PPBTException(Exception):
21+
"""
22+
Base class for all ppbt exceptions.
1723
18-
archive = pathlib.Path(__file__).parent / "_toolchain" / f"{triplet}.tar.xz"
19-
toolchain = pathlib.Path(__file__).parent / "_toolchain" / triplet
20-
toolchain_root = pathlib.Path(__file__).parent / "_toolchain"
24+
"""
25+
26+
27+
def get_triplet(machine=None, plat=None):
28+
"""
29+
Get the target triplet for the specified machine and platform.
30+
31+
If any of the args are None, it will try to deduce what they should be.
32+
33+
:param machine: The machine for the triplet
34+
:type machine: str
35+
:param plat: The platform for the triplet
36+
:type plat: str
37+
38+
:raises BuildError: If the platform is unknown
39+
40+
:return: The target triplet
41+
:rtype: str
42+
"""
43+
if not plat:
44+
plat = sys.platform
45+
if not machine:
46+
machine = build_arch()
47+
if plat == "darwin":
48+
return f"{machine}-macos"
49+
elif plat == "win32":
50+
return f"{machine}-win"
51+
elif plat == "linux":
52+
return f"{machine}-linux-gnu"
53+
else:
54+
raise PPBTException(f"Unknown platform {plat}")
55+
56+
57+
def build_arch():
58+
"""
59+
Return the current machine.
60+
"""
61+
machine = platform.machine()
62+
return machine.lower()
63+
64+
65+
TRIPLET = get_triplet(build_arch())
66+
ARCHIVE = pathlib.Path(__file__).parent / "_toolchain" / f"{TRIPLET}.tar.xz"
67+
TOOLCHAIN_ROOT = pathlib.Path(__file__).parent / "_toolchain"
68+
TOOLCHAIN = TOOLCHAIN_ROOT / TRIPLET
2169

2270
# This is not reliable, the version can be modified by setuptools at build time.
23-
distinfo = (
71+
DISTINFO = (
2472
pathlib.Path(__file__).resolve().parent.parent / f"ppbt-{__version__}.dist-info"
2573
)
2674

27-
log = logging.getLogger(__name__)
75+
76+
def extract_archive(to_dir, archive):
77+
"""
78+
Extract an archive to a specific location.
79+
80+
:param to_dir: The directory to extract to
81+
:type to_dir: str
82+
:param archive: The archive to extract
83+
:type archive: str
84+
"""
85+
if archive.endswith("tgz"):
86+
read_type = "r:gz"
87+
elif archive.endswith("xz"):
88+
read_type = "r:xz"
89+
elif archive.endswith("bz2"):
90+
read_type = "r:bz2"
91+
else:
92+
read_type = "r"
93+
with tarfile.open(archive, read_type) as t:
94+
t.extractall(to_dir)
2895

2996

3097
def extract(overwrite=False):
3198
"""
3299
Extract the toolchain tarball.
33100
"""
34-
if toolchain.exists() and not overwrite:
101+
if TOOLCHAIN.exists() and not overwrite:
35102
log.debug("Toolchain directory exists")
36103
else:
37104
log.info("Extract archive")
38-
extract_archive(toolchain_root, str(archive))
39-
record = distinfo / "RECORD"
105+
extract_archive(TOOLCHAIN_ROOT, str(ARCHIVE))
106+
record = DISTINFO / "RECORD"
40107
if record.exists():
41108
records = []
42109
log.info("Update pkg metadata")
43110
with open(record, "r") as fp:
44111
for row in csv.reader(fp):
45112
records.append(row)
46-
with open(str(archive) + ".record", "r") as fp:
113+
with open(str(ARCHIVE) + ".record", "r") as fp:
47114
for row in csv.reader(fp):
48115
records.append(row)
49116
records = sorted(records, key=lambda _: _[0])
@@ -57,18 +124,18 @@ def environ(auto_extract=False):
57124
"""
58125
Toolchain build environment.
59126
"""
60-
if not toolchain.exists():
127+
if not TOOLCHAIN.exists():
61128
if auto_extract:
62129
extract()
63130
else:
64131
raise RuntimeError("Toolchain not extracted")
65-
basebin = toolchain / "bin" / triplet
132+
basebin = TOOLCHAIN / "bin" / TRIPLET
66133
return {
67-
"TOOLCHAIN_PATH": f"{toolchain}",
134+
"TOOLCHAIN_PATH": f"{TOOLCHAIN}",
68135
"CC": f"{basebin}-gcc",
69136
"CXX": f"{basebin}-g++",
70-
"CFLAGS": f"-I{toolchain}/{triplet}/sysroot/usr/include",
71-
"CPPFLAGS": f"-I{toolchain}/{triplet}/sysroot/usr/include",
72-
"CMAKE_FLAGS": f"-I{toolchain}/{triplet}/sysroot/usr/include",
73-
"LDFLAGS": f"-L{toolchain}/{triplet}/sysroot/lib",
137+
"CFLAGS": f"-I{TOOLCHAIN}/{TRIPLET}/sysroot/usr/include",
138+
"CPPFLAGS": f"-I{TOOLCHAIN}/{TRIPLET}/sysroot/usr/include",
139+
"CMAKE_FLAGS": f"-I{TOOLCHAIN}/{TRIPLET}/sysroot/usr/include",
140+
"LDFLAGS": f"-L{TOOLCHAIN}/{TRIPLET}/sysroot/lib",
74141
}

0 commit comments

Comments
 (0)