-
Notifications
You must be signed in to change notification settings - Fork 86
/
build-runtime.py
executable file
·1738 lines (1448 loc) · 43.9 KB
/
build-runtime.py
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Script to build and install packages into the Steam runtime
import calendar
import errno
import os
import re
import sys
import glob
import gzip
import hashlib
import shutil
import subprocess
import tarfile
import tempfile
import time
from pathlib import Path
from debian import deb822
from debian.debian_support import Version
import argparse
try:
import typing
except ImportError:
pass
else:
typing # noqa
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO # type: ignore
try:
from urllib.request import (urlopen, urlretrieve)
except ImportError:
from urllib import (urlopen, urlretrieve) # type: ignore
destdir="newpkg"
# The top level directory
top = sys.path[0]
ONE_MEGABYTE = 1024 * 1024
SPLIT_MEGABYTES = 50
MIN_PARTS = 3
# Order is significant: the first architecture is considered primary
DEFAULT_ARCHITECTURES = ('amd64', 'i386')
ARCHITECTURES = {
'amd64': 'x86_64-linux-gnu',
'i386': 'i386-linux-gnu',
}
def hard_link_or_copy(source, dest):
"""
Copy source to dest, optimizing by creating a hard-link instead
of a full copy if possible.
"""
try:
os.remove(dest)
except OSError as e:
if e.errno != errno.ENOENT:
raise
try:
os.link(source, dest)
except OSError:
shutil.copyfile(source, dest)
def warn_if_different(
path1, # type: str
path2 # type: str
):
# type: (...) -> None
# Deliberately ignoring exit status
subprocess.call([
'diff', '--brief', '--', path1, path2,
])
def str2bool (b):
return b.lower() in ("yes", "true", "t", "1")
def check_path_traversal(s):
if '..' in s or s.startswith('/'):
raise ValueError('Path traversal detected in %r' % s)
class AptSource:
def __init__(
self,
kind,
url,
suite,
components=('main',),
trusted=False
):
self.kind = kind
self.url = url
self.suite = suite
self.components = components
self.trusted = trusted
def __str__(self):
if self.trusted:
maybe_options = ' [trusted=yes]'
else:
maybe_options = ''
return '%s%s %s %s %s' % (
self.kind,
maybe_options,
self.url,
self.suite,
' '.join(self.components),
)
@property # type: ignore
def release_url(self):
# type: () -> str
if self.suite.endswith('/') and not self.components:
suite = self.suite
if suite == './':
suite = ''
return '%s/%sRelease' % (self.url, suite)
return '%s/dists/%s/Release' % (self.url, self.suite)
@property # type: ignore
def sources_urls(self):
# type: () -> typing.List[str]
if self.kind != 'deb-src':
return []
if self.suite.endswith('/') and not self.components:
suite = self.suite
if suite == './':
suite = ''
return ['%s/%sSources.gz' % (self.url, suite)]
return [
"%s/dists/%s/%s/source/Sources.gz" % (
self.url, self.suite, component)
for component in self.components
]
def get_packages_urls(self, arch, dbgsym=False):
# type: (str, bool) -> typing.List[str]
if self.kind != 'deb':
return []
if self.suite.endswith('/') and not self.components:
suite = self.suite
if suite == './':
suite = ''
return ['%s/%sPackages.gz' % (self.url, suite)]
ret = [] # type: typing.List[str]
for component in self.components:
ret.append(
"%s/dists/%s/%s/binary-%s/Packages.gz" % (
self.url, self.suite, component,
arch)
)
if dbgsym:
ret.append(
"%s/dists/%s/%s/debug/binary-%s/Packages.gz" % (
self.url, self.suite,
component, arch)
)
return ret
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--templates",
help="specify template files to include in runtime",
default=os.path.join(top, "templates"))
parser.add_argument(
"-o", "--output", default=None,
help="specify output directory [default: delete after archiving]")
parser.add_argument("--suite", help="specify apt suite", default='scout')
parser.add_argument("-b", "--beta", help="build beta runtime", dest='suite', action="store_const", const='scout_beta')
parser.add_argument("-d", "--debug", help="build debug runtime", action="store_true")
parser.add_argument("--source", help="include sources", action="store_true")
parser.add_argument("--symbols", help="include debugging symbols", action="store_true")
parser.add_argument(
"--repo", help="main apt repository URL",
default="https://repo.steampowered.com/steamrt",
)
parser.add_argument(
"--upstream-apt-source", dest='upstream_apt_sources',
default=[], action='append',
help=(
"additional apt sources in the form "
"'deb https://URL SUITE COMPONENT [COMPONENT...]' "
"(may be repeated)"
),
)
parser.add_argument(
"--extra-apt-source", dest='extra_apt_sources',
default=[], action='append',
help=(
"additional apt sources in the form "
"'deb https://URL SUITE COMPONENT [COMPONENT...]' "
"(may be repeated)"
),
)
parser.add_argument("-v", "--verbose", help="verbose", action="store_true")
parser.add_argument("--official", help="mark this as an official runtime", action="store_true")
parser.add_argument("--set-name", help="set name for this runtime", default=None)
parser.add_argument("--set-version", help="set version number for this runtime", default=None)
parser.add_argument("--debug-url", help="set URL for debug/source version", default=None)
parser.add_argument("--archive", help="pack Steam Runtime into a tarball", default=None)
parser.add_argument(
"--compression", help="set compression [xz|gx|bz2|none]",
choices=('xz', 'gz', 'bz2', 'none'),
default='xz')
parser.add_argument(
'--strict', action="store_true",
help='Exit unsuccessfully when something seems wrong')
parser.add_argument(
'--split', default=None,
help='Also generate an archive split into 50M parts')
parser.add_argument(
'--architecture', '--arch',
help='include architecture (the first is assumed to be primary)',
action='append', dest='architectures', default=[],
)
parser.add_argument(
'--metapackage',
help='Include the given package and its dependencies',
action='append', dest='metapackages', default=[],
)
parser.add_argument(
'--packages-from',
help='Include packages listed in the given file',
action='append', default=[],
)
parser.add_argument(
'--dump-options', action='store_true',
help=argparse.SUPPRESS, # deliberately undocumented
)
args = parser.parse_args()
if args.output is None and args.archive is None:
parser.error(
'At least one of --output and --archive is required')
if args.split is not None and args.archive is None:
parser.error('--split requires --archive')
if not os.path.isdir(args.templates):
parser.error(
'Argument to --templates, %r, must be a directory'
% args.templates)
# os.path.exists is false for dangling symlinks, so check for both
if args.output is not None and (
os.path.exists(args.output)
or os.path.islink(args.output)
):
parser.error(
'Argument to --output, %r, must not already exist'
% args.output)
if not args.architectures:
if args.suite in ('heavy', 'heavy_beta'):
args.architectures = ['amd64']
else:
args.architectures = list(DEFAULT_ARCHITECTURES)
if not args.packages_from and not args.metapackages:
args.metapackages = ['steamrt-ld-library-path', 'steamrt-libs']
if args.suite in ('scout', 'scout_beta'):
args.metapackages.append('steamrt-legacy')
if args.debug:
args.metapackages.append('steamrt-libdevel')
args.metapackages.append('steamrt-libdevel-non-multiarch')
# Not really a metapackage, but we want it in the
# debug tarball only; container/chroot/Docker
# environments get libgl1-mesa-dev instead
if args.suite in ('scout', 'scout_beta'):
args.metapackages.append('dummygl-dev')
return args
def download_file(file_url, file_path):
try:
if os.path.getsize(file_path) > 0:
if args.verbose:
print("Skipping download of existing file: %s" % file_path)
return False
except OSError:
pass
try:
if args.verbose:
print("Downloading %s to %s" % (file_url, file_path))
urlretrieve(file_url, file_path)
except Exception:
sys.stderr.write('Error downloading %s:\n' % file_url)
raise
return True
class SourcePackage:
def __init__(self, apt_source, stanza):
self.apt_source = apt_source
self.stanza = stanza
def install_sources(apt_sources, sourcelist):
# Load the Sources files so we can find the location of each source package
source_packages = []
for apt_source in apt_sources:
for url in apt_source.sources_urls:
print("Downloading sources from %s" % url)
sz = urlopen(url)
url_file_handle=BytesIO(sz.read())
sources = gzip.GzipFile(fileobj=url_file_handle)
for stanza in deb822.Sources.iter_paragraphs(sources):
source_packages.append(
SourcePackage(apt_source, stanza))
skipped = 0
failed = False
included = {}
manifest_lines = set()
# Walk through the Sources file and process any requested packages.
# If a particular source package name appears more than once (for
# example in scout and also in an overlay suite), we err on the side
# of completeness and download all of them.
for sp in source_packages:
p = sp.stanza['package']
# Skip packages with Extra-Source-Only: yes.
# These don't necessarily appear in the package pool.
if sp.stanza.get('Extra-Source-Only', 'no') == 'yes':
continue
if p in sourcelist:
if args.verbose:
print("DOWNLOADING SOURCE: %s" % p)
#
# Create the destination directory if necessary
#
cache_dir = os.path.join(top, destdir, "source", p)
if not os.access(cache_dir, os.W_OK):
os.makedirs(cache_dir)
#
# Download each file
#
for file in sp.stanza['files']:
check_path_traversal(file['name'])
file_path = os.path.join(cache_dir, file['name'])
file_url = "%s/%s/%s" % (
sp.apt_source.url,
sp.stanza['directory'],
file['name']
)
if not download_file(file_url, file_path):
skipped += 1
for file in sp.stanza['files']:
if args.strict:
hasher = hashlib.md5()
with open(
os.path.join(cache_dir, file['name']),
'rb'
) as bin_reader:
blob = bin_reader.read(4096)
while blob:
hasher.update(blob)
blob = bin_reader.read(4096)
if hasher.hexdigest() != file['md5sum']:
print('ERROR: %s has unexpected content' % file['name'])
failed = True
# Copy the source package into the output directory
# (optimizing the copy as a hardlink if possible)
os.makedirs(os.path.join(args.output, 'source'), exist_ok=True)
hard_link_or_copy(
os.path.join(cache_dir, file['name']),
os.path.join(
args.output, 'source', file['name']))
included[(p, sp.stanza['Version'])] = sp.stanza
manifest_lines.add(
'%s\t%s\t%s\n' % (
p, sp.stanza['Version'],
sp.stanza['files'][0]['name']))
if failed:
sys.exit(1)
# sources.txt: Tab-separated table of source packages, their
# versions, and the corresponding .dsc file.
with open(os.path.join(args.output, 'source', 'sources.txt'), 'w') as writer:
writer.write('#Source\t#Version\t#dsc\n')
for line in sorted(manifest_lines):
writer.write(line)
# sources.deb822.gz: The full Sources stanza for each included source
# package, suitable for later analysis.
with open(
os.path.join(args.output, 'source', 'sources.deb822.gz'), 'wb'
) as gz_writer:
with gzip.GzipFile(
filename='', mode='wb', fileobj=gz_writer, mtime=0
) as stanza_writer:
done_one = False
for key, stanza in sorted(included.items()):
if done_one:
stanza_writer.write(b'\n')
stanza.dump(stanza_writer)
done_one = True
if skipped > 0:
print("Skipped downloading %i deb source file(s) that were already present." % skipped)
class Binary:
def __init__(self, apt_source, stanza):
self.apt_source = apt_source
self.stanza = stanza
self.name = stanza['Package']
self.arch = stanza['Architecture']
self.version = stanza['Version']
source = stanza.get('Source', self.name)
if ' (' in source:
self.source, tmp = source.split(' (', 1)
self.source_version = tmp.rstrip(')')
else:
self.source = source
self.source_version = self.version
self.dependency_names = set()
for field in ('Depends', 'Pre-Depends'):
value = stanza.get(field, '')
deps = value.split(',')
for d in deps:
# ignore alternatives
d = d.split('|')[0]
# ignore version number
d = d.split('(')[0]
d = d.strip()
if d:
self.dependency_names.add(d)
def list_binaries(
apt_sources, # type: typing.List[AptSource]
dbgsym=False # type: bool
):
# type: (...) -> typing.Dict[str, typing.Dict[str, typing.List[Binary]]]
# {'amd64': {'libc6': [<Binary>, ...]}}
by_arch = {} # type: typing.Dict[str, typing.Dict[str, typing.List[Binary]]]
if dbgsym:
description = 'debug symbols'
else:
description = 'binaries'
for arch in args.architectures:
by_name = {} # type: typing.Dict[str, typing.List[Binary]]
# Load the Packages files so we can find the location of each
# binary package
for apt_source in apt_sources:
for url in apt_source.get_packages_urls(
arch,
dbgsym=dbgsym,
):
print("Downloading %s %s from %s" % (
arch, description, url))
try:
# Python 2 does not catch a 404 here
url_file_handle = gzip.GzipFile(
fileobj=BytesIO(
urlopen(url).read()
),
mode='rb',
)
except Exception as e:
if dbgsym:
print(e)
continue
else:
raise
for stanza in deb822.Packages.iter_paragraphs(
url_file_handle
):
if stanza['Architecture'] not in ('all', arch):
print('Found %s package %s in %s Packages file' % (
stanza['Architecture'],
stanza['Package'],
arch,
))
continue
p = stanza['Package']
binary = Binary(apt_source, stanza)
by_name.setdefault(p, []).append(
binary)
by_arch[arch] = by_name
return by_arch
def ignore_metapackage_dependency(name):
"""
Return True if @name should not be installed in Steam Runtime
tarballs, even if it's depended on by the metapackage.
"""
return name in (
# Must be provided by host system
'libc6',
'libegl-mesa0',
'libegl1-mesa',
'libegl1-mesa-drivers',
'libgl1-mesa-dri',
'libgl1-mesa-glx',
'libgles1-mesa',
'libgles2-mesa',
'libglx-mesa0',
'mesa-opencl-icd',
'mesa-va-drivers',
'mesa-vdpau-drivers',
'mesa-vulkan-drivers',
# Provided by host system alongside Mesa if needed
'libtxc-dxtn-s2tc0',
# Actually a virtual package
'libcggl',
# Experimental
'libcasefold-dev',
)
def accept_transitive_dependency(name):
"""
Return True if @name should be included in the Steam Runtime
tarball whenever it is depended on a package depended on by
the metapackage, but should not be a direct dependency of the
metapackage.
"""
return name in (
'gcc-4.6-base',
'gcc-4.8-base',
'gcc-4.9-base',
'gcc-5-base',
'libelf1',
'libx11-data',
)
def ignore_transitive_dependency(name):
"""
Return True if @name should not be included in the Steam Runtime
tarball or directly depended on by the metapackage, even though
packages in the Steam Runtime might have dependencies on it.
"""
return name in (
# Must be provided by host system
'libc6',
'libegl-mesa0',
'libegl1-mesa',
'libegl1-mesa-drivers',
'libgl1-mesa-dri',
'libgl1-mesa-glx',
'libgles1-mesa',
'libgles2-mesa',
'libglx-mesa0',
'mesa-opencl-icd',
'mesa-va-drivers',
'mesa-vdpau-drivers',
'mesa-vulkan-drivers',
# Assumed to be provided by host system if needed
'ca-certificates',
'fontconfig',
'fontconfig-config',
'gconf2-common',
'iso-codes',
'libasound2-data',
'libatk1.0-data',
'libavahi-common-data',
'libdb5.1',
'libdconf0',
'libdrm-intel1',
'libdrm-radeon1',
'libdrm-nouveau1a',
'libdrm2',
'libglapi-mesa',
'libllvm3.0',
'libopenal-data',
'libthai-data',
'libthai0',
'libtxc-dxtn-s2tc0',
'passwd',
'shared-mime-info',
'sound-theme-freedesktop',
'x11-common',
# Non-essential: only contains localizations
'libgdk-pixbuf2.0-common',
'libjson-glib-1.0-common',
# Depended on by packages that are present for historical
# reasons
'libcggl',
'libstdc++6-4.6-dev',
'zenity-common',
# Only exists for packaging/dependency purposes
'debconf',
'libjpeg8', # transitions to libjpeg-turbo8
'multiarch-support',
# Used for development in Steam Runtime, but not in
# chroots/containers that satisfy dependencies
'dummygl-dev',
)
def expand_metapackages(architectures, binaries_by_arch, metapackages):
sources_from_apt = set()
binaries_from_apt = {}
error = False
for arch in architectures:
arch_binaries = binaries_by_arch[arch]
binaries_from_apt[arch] = set()
for metapackage in metapackages:
if metapackage not in arch_binaries:
print('ERROR: Metapackage %s not found in Packages files' % metapackage)
error = True
continue
binary = max(
arch_binaries[metapackage],
key=lambda b: Version(b.stanza['Version']))
sources_from_apt.add(binary.source)
binaries_from_apt[arch].add(metapackage)
for d in binary.dependency_names:
if not ignore_metapackage_dependency(d):
binaries_from_apt[arch].add(d)
for arch, arch_binaries in sorted(binaries_by_arch.items()):
for library in sorted(binaries_from_apt[arch]):
if not _recurse_dependency(
arch_binaries,
library,
binaries_from_apt[arch],
sources_from_apt,
):
error = True
if error and args.strict:
sys.exit(1)
return sources_from_apt, binaries_from_apt
def _recurse_dependency(
arch_binaries, # type: typing.Dict[str, typing.List[Binary]]
library, # type: str
binaries_from_apt, # type: typing.Set[str]
sources_from_apt # type: typing.Set[str]
):
if library not in arch_binaries:
print('ERROR: Package %s not found in Packages files' % library)
return False
binary = max(
arch_binaries[library],
key=lambda b: Version(b.stanza['Version']))
sources_from_apt.add(binary.source)
error = False
for d in binary.dependency_names:
if accept_transitive_dependency(d):
if d not in binaries_from_apt:
binaries_from_apt.add(d)
if not _recurse_dependency(
arch_binaries,
d,
binaries_from_apt,
sources_from_apt,
):
error = True
elif library.endswith(('-dev', '-dbg', '-multidev')):
# When building a -debug runtime we
# disregard transitive dependencies of
# development-only packages
pass
elif d in binaries_from_apt:
pass
elif ignore_metapackage_dependency(d):
pass
elif ignore_transitive_dependency(d):
pass
else:
print('ERROR: %s depends on %s but the metapackages do not' % (library, d))
_recurse_dependency(
arch_binaries,
d,
binaries_from_apt,
sources_from_apt,
)
error = True
return not error
def check_consistency(
binaries_from_apt, # type: typing.Dict[str, typing.Set[str]]
binaries_from_lists, # type: typing.Set[str]
):
for arch, binaries in sorted(binaries_from_apt.items()):
for b in sorted(binaries - binaries_from_lists):
print('Installing %s only because of --metapackage' % b)
for b in sorted(binaries_from_lists - binaries):
print('Installing %s only because of --packages-from' % b)
for arch, binaries in sorted(binaries_from_apt.items()):
for name in sorted(binaries):
if name in binaries_from_lists:
pass
elif ignore_metapackage_dependency(name):
pass
elif ignore_transitive_dependency(name):
pass
elif name in args.metapackages:
pass
else:
print('WARNING: Binary package %s on %s depended on by %s but not in %s' % (name, arch, args.metapackages, args.packages_from))
for name in sorted(binaries_from_lists):
if name in binaries:
pass
elif ignore_transitive_dependency(name):
pass
else:
print('WARNING: Binary package %s in %s but not depended on by %s on %s' % (name, args.packages_from, args.metapackages, arch))
def get_output_dir_for_arch(arch: str) -> Path:
"""Generates the canonical output directory for the provided architecture"""
return Path(args.output) / arch
def keep_only_primary_arch(relative_path: str) -> bool:
# For some paths below /usr/libexec it's unimportant whether we have
# a 32- or 64-bit executable, so silently keep the one from the
# primary architecture, without logging a warning.
return relative_path.startswith(( # any of these prefixes:
'usr/libexec/flatpak-xdg-utils/',
'usr/libexec/steam-runtime-tools-0/',
))
def install_binaries(architectures, binaries_by_arch, binarylists, manifest):
skipped = 0
for arch, arch_binaries in sorted(binaries_by_arch.items()):
installset = binarylists[arch].copy()
#
# Create the destination directory if necessary
#
dir = os.path.join(top,destdir,"binary" if not args.debug else "debug", arch)
if not os.access(dir, os.W_OK):
os.makedirs(dir)
out_dir = get_output_dir_for_arch(arch)
for p, binaries in sorted(arch_binaries.items()):
if p in installset:
if args.verbose:
print("DOWNLOADING BINARY: %s" % p)
newest = max(
binaries,
key=lambda b:
Version(b.stanza['Version']))
manifest[(p, arch)] = newest
#
# Download the package and install it
#
check_path_traversal(newest.stanza['Filename'])
file_url = "%s/%s" % (
newest.apt_source.url,
newest.stanza['Filename'],
)
dest_deb = os.path.join(
dir,
os.path.basename(newest.stanza['Filename']),
)
if not download_file(file_url, dest_deb):
skipped += 1
install_deb(
os.path.splitext(
os.path.basename(
newest.stanza['Filename']
)
)[0],
dest_deb,
str(out_dir)
)
installset.remove(p)
prune_files(out_dir)
for p in installset:
#
# There was a binary package in the list to be installed that is not in the repo
#
e = "ERROR: Package %s not found in Packages files\n" % p
sys.stderr.write(e)
if installset and args.strict:
raise SystemExit('Not all binary packages were found')
# Combine basically all directories, except for {usr/,}{s,}bin
# which collides (see
# templates/scripts/check-runtime-conflicts.sh) and installed
# which is only metadata anyway
for pattern in ('*', 'usr/*'):
for dir in glob.glob(str(out_dir / pattern)):
if dir.endswith(('/bin', '/sbin', '/usr')):
# Don't merge bin, sbin - they
# will definitely collide.
# Don't merge all of usr - we merge its
# subdirectories instead, because we
# want to skip usr/bin and usr/sbin.
continue
for (dirpath, dirnames, filenames) in os.walk(dir):
relative_path = os.path.relpath(
dirpath,
str(out_dir),
)
for member in dirnames:
merged = os.path.join(
args.output,
relative_path,
member,
)
os.makedirs(merged, exist_ok=True)
for member in filenames:
source = os.path.join(
dirpath,
member,
)
merged = os.path.join(
args.output,
relative_path,
member,
)
if os.path.exists(merged):
if not keep_only_primary_arch(relative_path):
warn_if_different(source, merged)
else:
os.makedirs(os.path.dirname(merged), exist_ok=True)
shutil.move(source, merged)
# Replace amd64/usr/lib with a symlink to
# ../usr/lib, etc.
relative_path = os.path.relpath(
dir,
str(out_dir),
)
merged = os.path.join(
args.output,
relative_path,
)
shutil.rmtree(dir)
os.symlink(
os.path.join(
'../' * (relative_path.count('/') + 1),
relative_path,
),
dir,
)
for pattern in ('bin/{}-*', 'usr/bin/{}-*'):
for exe in glob.glob(str(out_dir / pattern.format(ARCHITECTURES[arch]))):
# Populate OUTPUT/usr/bin with symlinks
# to OUTPUT/amd64/[usr/]bin/x86_64-linux-gnu-*
# and OUTPUT/i386/[usr/]bin/i386-linux-gnu-*
os.makedirs(os.path.join(args.output, 'usr', 'bin'), exist_ok=True)
relative_path = os.path.relpath(exe, args.output)
os.symlink(
os.path.join('..', '..', relative_path),
os.path.join(
args.output, 'usr', 'bin',
os.path.basename(exe),
)
)
out_dir = Path(args.output)
# We want some executables to be in the PATH for apps/games, but not
# for Steam components, to avoid a cyclic dependency.
(out_dir / 'game-bin').mkdir(exist_ok=True, mode=0o755, parents=True)
for exe, name in (
('usr/bin/steam-runtime-steam-remote', 'steam'),
('usr/bin/steam-runtime-urlopen', 'xdg-open'),
# TODO: Maybe consider this too?
# ('usr/libexec/flatpak-xdg-utils/xdg-email', 'xdg-email'),
):
if (out_dir / exe).exists():
(out_dir / 'game-bin' / name).symlink_to('../' + exe)
elif (out_dir / architectures[0] / exe).exists():
(out_dir / 'game-bin' / name).symlink_to(
'../%s/%s' % (architectures[0], exe)
)
if skipped > 0:
print("Skipped downloading %i file(s) that were already present." % skipped)
def prune_files(directory: Path) -> None:
"""Remove files that are considered to be unnecessary"""
usr_share = directory / 'usr' / 'share'
doc = usr_share / 'doc'
paths: list[Path] = [
# Nvidia cg toolkit manuals, tutorials and documentation
doc / 'nvidia-cg-toolkit' / 'html',
*doc.glob('nvidia-cg-toolkit/*.pdf.gz'),
# Sample code
*doc.glob('**/examples'),
# Debian bug reporting scripts
usr_share / 'bug',
# Debian documentation metadata
usr_share / 'doc-base',
# Debian QA metadata
usr_share / 'lintian',
# Programs and utilities manuals
usr_share / 'man',
# Remove the localized messages that are likely never going to be used.
# Keep only "en", because that's the default language we are using.
*[x for x in usr_share.glob('locale/*') if x.name != 'en'],
]
for path in paths:
if path.is_dir():
shutil.rmtree(path)
else: