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
|
#!/usr/bin/env python3
"""
A Python 3.11 standard library only utility to help install an
environment for `trimesh` in a Debian Docker image.
It probably isn't useful for most people unless you are running
this exact configuration.
"""
import argparse
import json
import logging
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
from fnmatch import fnmatch
from io import BytesIO
# define system packages for our debian docker image
# someday possibly add this to the `pyproject.toml` config
# but for now store them locally in the installer script
config_json = """
{
"apt": {
"build": [
"build-essential",
"g++",
"make",
"git"
],
"docs": [
"make",
"pandoc"
],
"llvmpipe": [
"libgl1-mesa-dri",
"xvfb",
"xauth",
"ca-certificates",
"freeglut3-dev"
],
"test": [
"curl",
"git"
],
"gmsh": ["libxft2", "libxinerama-dev", "libxcursor1","libgomp1"]
},
"fetch": {
"gltf_validator": {
"url": "https://github.com/KhronosGroup/glTF-Validator/releases/download/2.0.0-dev.3.8/gltf_validator-2.0.0-dev.3.8-linux64.tar.xz",
"sha256": "374c7807e28fe481b5075f3bb271f580ddfc0af3e930a0449be94ec2c1f6f49a",
"target": "$PATH",
"chmod": 755,
"extract_only": "gltf_validator"
},
"pandoc": {
"url": "https://github.com/jgm/pandoc/releases/download/3.1.1/pandoc-3.1.1-linux-amd64.tar.gz",
"sha256": "52b25f0115517e32047a06d821e63729108027bd06d9605fe8eac0fa83e0bf81",
"target": "$PATH",
"chmod": 755,
"extract_only": "pandoc"
},
"binvox": {
"url": "https://trimesh.s3-us-west-1.amazonaws.com/binvox",
"sha256": "82ee314a75986f67f1d2b5b3ccdfb3661fe57a6b428aa0e0f798fdb3e1734fe0",
"target": "$PATH",
"chmod": 755
}
}
}
"""
log = logging.getLogger("trimesh")
log.setLevel(logging.DEBUG)
log.addHandler(logging.StreamHandler(sys.stdout))
_cwd = os.path.abspath(os.path.expanduser(os.path.dirname(__file__)))
def apt(packages):
"""
Install a list of debian packages using suprocess to call apt-get.
Parameters
------------
packages : iterable
List, set, or other with package names.
"""
if len(packages) == 0:
return
# start with updating the sources
log.debug(subprocess.check_output("apt-get update -qq".split()).decode("utf-8"))
# the install command
install = "apt-get install -qq --no-install-recommends".split()
# de-duplicate package list
install.extend(set(packages))
# call the install command
log.debug(subprocess.check_output(install).decode("utf-8"))
# delete any temporary files
subprocess.check_output("rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*".split())
def argsort(items):
"""
A standard-library implementation of `numpy.argsort`, a way
to get a list sorted by index instead of by the sorted values.
Parameters
--------------
item : (n,) any
Items that are sortable.
Returns
--------------
index : int
Index such `items[index] == min(items)`
"""
return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(items))]
def fetch(url, sha256):
"""
A simple standard-library only "fetch remote URL" function.
Parameters
------------
url : str
Location of remote resource.
sha256: str
The SHA256 hash of the resource once retrieved,
will raise a `ValueError` if the hash doesn't match.
Returns
-------------
data : bytes
Retrieved data in memory with correct hash.
"""
import hashlib
from urllib.request import urlopen
data = urlopen(url).read()
hashed = hashlib.sha256(data).hexdigest()
if hashed != sha256:
log.error(f"`{hashed}` != `{sha256}`")
raise ValueError("sha256 hash does not match!")
return data
def copy_to_path(file_path, prefix="~"):
"""
Copy an executable file onto `PATH`, typically one of
the options in the current user's home directory.
Parameters
--------------
file_path : str
Location of of file to copy into PATH.
prefix : str
The path prefix it is acceptable to copy into,
typically `~` for `/home/{current_user}`.
"""
# get the full path of the requested file
source = os.path.abspath(os.path.expanduser(file_path))
# get the file name
file_name = os.path.split(source)[-1]
# make sure the source file is readable and not empty
with open(source, "rb") as f:
file_data = f.read()
# check for empty files
if len(file_data) == 0:
raise ValueError(f"empty file: {file_path}")
# get all locations in PATH
candidates = [
os.path.abspath(os.path.expanduser(i)) for i in os.environ["PATH"].split(":")
]
# cull candidates that don't start with our prefix
if prefix is not None:
# expand shortcut for user's home directory
prefix = os.path.abspath(os.path.expanduser(prefix))
# if we are the root user don't cull the available copy locations
if not prefix.endswith("root"):
# cull non-prefixed path entries
candidates = [c for c in candidates if c.startswith(prefix)]
# we want to encourage it to put stuff in the home directory
encourage = [os.path.expanduser("~"), ".local"]
# rank the candidate paths
scores = [len(c) - sum(len(e) for e in encourage if e in c) for c in candidates]
# try writing to the shortest paths first
for index in argsort(scores):
path = os.path.join(candidates[index], file_name)
try:
shutil.copy(source, path)
print(f"wrote `{path}`")
return path
except BaseException:
pass
# none of our candidates worked
raise ValueError("unable to write to file")
def extract(tar, member, path, chmod):
"""
Extract a single member from a tarfile to a path.
"""
if os.path.isdir(path):
return
data = tar.extractfile(member=member)
if not hasattr(data, "read"):
return
data = data.read()
if len(data) == 0:
return
# make sure root path exists
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
f.write(data)
if chmod is not None:
# python os.chmod takes an octal value
os.chmod(path, int(str(chmod), base=8))
def handle_fetch(
url,
sha256,
target,
chmod=None,
extract_skip=None,
extract_only=None,
strip_components=0,
):
"""
A macro to fetch a remote resource (usually an executable) and
move it somewhere on the file system.
Parameters
------------
url : str
A string with a remote resource.
sha256 : str
A hex string for the hash of the remote resource.
target : str
Target location on the local file system.
chmod : None or int.
Change permissions for extracted files.
extract_skip : None or iterable
Skip a certain member of the archive.
extract_only : None or str
Extract *only* a single file from the archive,
overrides `extract_skip`.
strip_components : int
Strip off this many components from the file path
in the archive, i.e. at `1`, `a/b/c` is extracted to `target/b/c`
"""
# get the raw bytes
log.debug(f"fetching: `{url}`")
raw = fetch(url=url, sha256=sha256)
if len(raw) == 0:
raise ValueError(f"{url} is empty!")
# if we have an archive that tar supports
if url.endswith((".tar.gz", ".tar.xz", "tar.bz2")):
# mode needs to know what type of compression
mode = f'r:{url.split(".")[-1]}'
# get the archive
tar = tarfile.open(fileobj=BytesIO(raw), mode=mode)
if extract_skip is None:
extract_skip = []
for member in tar.getmembers():
# final name after stripping components
name = "/".join(member.name.split("/")[strip_components:])
# if any of the skip patterns match continue
if any(fnmatch(name, p) for p in extract_skip):
log.debug(f"skipping: `{name}`")
continue
if extract_only is None:
path = os.path.join(target, name)
log.debug(f"extracting: `{path}`")
extract(tar=tar, member=member, path=path, chmod=chmod)
else:
name = name.split("/")[-1]
if name == extract_only:
if target.lower() == "$path":
with tempfile.TemporaryDirectory() as D:
path = os.path.join(D, name)
log.debug(f"extracting `{path}`")
extract(tar=tar, member=member, path=path, chmod=chmod)
copy_to_path(path)
return
path = os.path.join(target, name)
log.debug(f"extracting `{path}`")
extract(tar=tar, member=member, path=path, chmod=chmod)
return
else:
# a single file
name = url.split("/")[-1].strip()
if target.lower() == "$path":
with tempfile.TemporaryDirectory() as D:
temp_path = os.path.join(D, name)
with open(temp_path, "wb") as f:
f.write(raw)
# move the file somewhere on the path
path = copy_to_path(temp_path)
else:
path = target
with open(path, "wb") as f:
f.write(raw)
# apply chmod if requested
if chmod is not None:
# python os.chmod takes an octal value
os.chmod(path, int(str(chmod), base=8))
def load_config():
""" """
return json.loads(config_json)
if __name__ == "__main__":
config = load_config()
options = set()
for v in config.values():
options.update(v.keys())
parser = argparse.ArgumentParser(description="Install system packages for trimesh.")
parser.add_argument(
"--install", type=str, action="append", help=f"Install metapackages: {options}"
)
args = parser.parse_args()
# collect `apt-get install`-able package
apt_select = []
handlers = {
"fetch": lambda x: handle_fetch(**x),
"apt": lambda x: apt_select.extend(x),
}
# allow comma delimiters and de-duplicate
if args.install is None:
parser.print_help()
exit()
else:
select = set(" ".join(args.install).replace(",", " ").split())
log.debug(f'installing metapackages: `{", ".join(select)}`')
for key in select:
for handle_name, handler in handlers.items():
if key in config[handle_name]:
handler(config[handle_name][key])
# run the apt-get install
apt(apt_select)
|