-
Notifications
You must be signed in to change notification settings - Fork 25
/
concierge.py
executable file
·1827 lines (1431 loc) · 59 KB
/
concierge.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
# The concierge utility is a basic package manager for cm3.
#
# The concierge has partial knowledge of package dependencies, as
# encoded in the file `scripts/pkginfo.txt` which topologically sorts
# all known packages in dependency order. Given a request to operate
# on (build, clean, or install) a collection of packages, the
# concierge searches the source tree to find the requested packages
# and uses the available information to ensure the operations are
# carried-out in a consistent order.
#
# Unfortunately the concierge does not have full knowledge of package
# dependencies, so it is not able to ensure that all required
# dependencies for a package are either up-to-date or installed. For
# some operations, such as upgrades, those requirements are hard-coded
# in this script.
#
# The concierge is also unable to invalidate packages whose
# dependencies have changed incompatibly. Such functionality properly
# belongs to cm3 itself but is not implemented.
#
# The ability of the concierge to locate packages and--at least
# partially--manage their dependencies is the primary reason to
# contribute new libraries to the cm3 repo, instead of distributing
# them separately.
# Concierge features:
#
# * Package management
# The primary purpose of the concierge is to build and install
# packages, respecting their dependency order. Specify packages on
# either by individual name (i.e., `m3tohtml`) or set name (i.e.,
# `m3devtool`). Construct more complex requests using an add (`+`)
# and remove (`-`) syntax, i.e., `+m3devtool -m3tohtml`.
#
# * Compiler upgrades
# The concierge additionally knows what packages to rebuild and in
# what order to upgrade the compiler from source. This is primarily
# useful to developers working from git.
#
# * System upgrades
# After upgrading the compiler, the concierge can optionally rebuild
# all libraries and applications to upgrade the entire CM3 system.
#
# * New system installs
# On a new system without a pre-existing CM3 compiler, the concierge
# can build and install a bootstrap compiler (from C) then build and
# install a new compiler. Optionally, it can build and install all
# libraries and applications to construct a full system.
#
# * Boostrap creation
# For developers the concierge can produce sources for a bootstrap
# compiler by compiling the required sources to C.
#
# * Distribution creation
# Finally, the concierge can produce a distribution tarball
# including a bootstrap compiler that can be installed on a fresh
# system.
# A note on CM3 backends:
#
# CM3 properly considers the integrated backend (Win32) and GCC
# backend (some systems) to be the default, most mature code
# generators where they are available.
#
# The concierge considers these defaults to be obsolete (integrated)
# and unmaintainable (GCC), and instead prefers the C backend. Unless
# otherwise instructed the concierge will build only the C and
# integrated backends (only on I386_NT) and will not build GCC.
#
# Developers can specify `-gcc` or `--backend gcc` the build the GCC
# backend.
#
# GCC is not included in the distribution tarball and is not available
# on new system installs, it must be built from source using
#
# scripts/concierge.py upgrade -gcc
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
# The canonical package set defined in pkginfo.txt.
ALL = "all"
# Packages without UI dependencies.
HEADLESS = "headless"
# Operating system classifications.
POSIX = "POSIX"
WIN32 = "WIN32"
# Setup logging to `concierge.log`
class Tee:
"Utility for capturing all output to logfile"
def __init__(self, left, right):
self._left = left
self._right = right
def write(self, data):
self._left.write(data)
self._right.write(data)
def flush(self):
self._left.flush()
self._right.flush()
# Capture all output to logfile in the current directory.
logfile = Path(sys.argv[0]).with_suffix(".log").name
# Replace any existing logfile.
sys.stdout = Tee(sys.stdout, open(logfile, "w"))
sys.stderr = sys.stdout
# Start by logging the command-line.
print(*sys.argv)
def show_usage():
print(f"""usage:
{sys.argv[0]} (COMMAND | PACKAGE_ACTIONS) {{GENERAL_OPTION}} [COMPILER_OPTIONS] [PACKAGE_SELECTION]
Specify a command or a sequence of one-or-more package actions. All
commands and package actions accept both general options and compiler
options, and most commands accept a package selection.
The available commands are
COMMAND = install [INSTALL_OPTIONS] | upgrade | full-upgrade | make-bootstrap | make-dist
* install :: install a new system from a distribution
* upgrade :: upgrade the compiler
* full-upgrade :: upgrade the compiler and all libraries
* make-bootstrap :: prepare a bootsrap compiler
* make-dist :: prepare a distribution
"install" can take additional arguments
INSTALL_OPTIONS = [INSTALL_PREFIX] [CMAKE_OPTIONS]
The prefix specifies where to install the new system. By default,
install will overwrite any existing cm3 installation.
INSTALL_PREFIX = --prefix <path>
Other options are passed directly to cmake when building the bootstrap
compiler.
CMAKE_OPTIONS = [GENERATOR_OPTION] {{CMAKE_DEFINE}}
GENERATOR_OPTION = -G <cmake_generator>
CMAKE_DEFINE = -DCMAKE_<name> | -DCMAKE_<name>=<value>
After building the bootstrap compiler, "install" finishes by
performing a "full-upgrade". Both "install" and "full-upgrade" accept
a PACKAGE_SELECTION which defaults to "headless".
Lacking a command, the default behavior is to execute one-or-more
package actions. Any number of package actions can be requested, and
they are applied in sequence (i.e., "realclean buildship").
PACKAGE_ACTIONS = PACKAGE_ACTION {{PACKAGE_ACTION}}
PACKAGE_ACTION = build | buildglobal | buildlocal | buildship | clean | cleanglobal | cleanlocal | realclean | ship
* build :: alias for buildlocal
* buildglobal :: build without local overrides
* buildlocal :: build with local overrides (i.e, "-override")
* buildship :: build without local overrides then install
* clean :: alias for cleanlocal
* cleanglobal :: clean without local overrides
* cleanlocal :: clean with local override
* realclean :: "rm -R" all build directories
* ship :: install packages
Options can be applied to all commands and package actions.
GENERAL_OPTION = -k | --keep-going | -l | --list-only | -n | --no-action
* -k | --keep-going :: ignore errors and continue with commands
* -l | --list-only :: list packages that would be affected
* -n | --no-action :: print commands that would be executed, but make no changes
Compiler options are passed through to cm3.
COMPILER_OPTIONS = {{COMPILER_FLAG}} {{COMPILER_DEFINE}} [BACKEND_OPTION] [TARGET_OPTION]
The various flags are exactly those accepted by cm3.
COMPILER_FLAG = -boot | -commands | -debug | -keep | -override | -silent | -times | -trace | -verbose | -why
* -commands :: list system commands as they are performed
* -debug :: dump internal debugging information
* -keep :: preserve intermediate and temporary files
* -override :: include the "m3overrides" file
* -silent :: produce no diagnostic output
* -times :: produce a dump of elapsed times
* -trace :: trace quake code execution
* -verbose :: list internal steps as they are performed
* -why :: explain why code is being recompiled
Defines are passed verbatim to cm3.
COMPILER_DEFINE = -D<name> | -D<name>=<value>
Select the backend to use for compliation. Breaking from tradition,
the "c" backend is used as the default if nothing is specified, and
the gcc backend is only built when explicitly requested.
BACKEND_OPTION = --backend (c|gcc|integrated) | -c | -gcc | -integrated
Select the compile target. The command-line "--target" takes
precedence over the "CM3_TARGET" environment variable, which takes
precedence over the default (usually matching the host).
TARGET_OPTION = --target <name>
Packages are specified using either package sets or individual
packages names (scripts/pkginfo.txt lists known packages and their
containing sets), and can optionally be specified using a subtractive
notation.
PACKAGE_SELECTION = {{<name> | +<name> | -<name>}}
Examples
* "database -mysql" selects "odbc postgres95 db smalldb"
* "-mysql database" selects "odbc mysql postgres95 db smalldb"
Package selections are processed in-order. An empty package selection
is always interpreted to mean "headless", and any selection that
begins with a subtraction is subtracted from an implicit "headless".
Examples
* "buildship" builds and installs everything
* "buildship -gui" builds and installs everything except the gui libraries
ENVIRONMENT VARIABLES
* CM3 :: provide the name of the cm3 executable, if it is other than "cm3"
* CM3_ALL :: define to build all packages without considering the target environment
* CM3_INSTALL :: provide the root of an existing cm3 installation, if not in path
* CM3_TARGET :: another way to specify "--target"
* HAVE_SERIAL :: define to build the serial libraries on Posix systems
* HAVE_TCL :: define to build the tcl integration
""")
class Error(Exception):
pass
class FatalError(Error):
def __init__(self, message):
self.message = message
class UsageError(Error):
def __init__(self, message):
self.message = message
class Platform:
"""Describes compilation host or target
Given a CM3 platform name, this class provides knowledge of what
backends and features CM3 supports on that platform.
"""
@staticmethod
def normalize_platform(name):
"Error if name does not match a known platform"
for target in Platform._all_platforms():
if name.upper() == target.upper():
return target
raise UsageError(f"{name} is not a recognized target")
@staticmethod
def _all_platforms():
"Not all named platforms are actually supported"
machines = [
"ALPHA", "ALPHA32", "ALPHA64", "AMD64", "ARM", "ARMEL", "ARM32",
"ARM64", "ARM64EC", "IA64", "I386", "PPC", "PPC32", "PPC64",
"SPARC", "SPARC32", "SPARC64", "MIPS32", "MIPS64EL", "MIPS64",
"PA32", "PA64", "RISCV64", "SH"
]
systems = [
"AIX", "CE", "CYGWIN", "DARWIN", "FREEBSD", "HAIKU",
"HPUX", "HPUX32", "HPUX64", "INTERIX", "IRIX", "LINUX",
"MINGW", "NETBSD", "NT", "NT32", "NT64",
"OPENBSD", "OSF", "SOLARIS", "VMS", "VMS32", "VMS64"
]
legacy_platforms = ["NT386", "LINUXLIBC6", "SOLsun", "SOLgnu", "FreeBSD4"]
return [f"{arch}_{os}" for arch in machines for os in systems] + legacy_platforms
def __init__(self, name = None):
if not name:
# Some attempts to disambiguate _MINGW and _NT.
if os.environ.get("MINGW_CHOST", "").startswith("x86_64"): name = "AMD64_MINGW"
elif os.environ.get("MSYSTEM") == "MINGW64": name = "AMD64_MINGW"
elif os.environ.get("MINGW_CHOST", "").startswith("i686"): name = "I386_MINGW"
elif os.environ.get("MSYSTEM") == "MINGW32": name = "I386_MINGW"
if not name:
arch = self._map_arch(platform.machine())
plat = self._map_os(sys.platform) # better matches our naming scheme than does `platform.system()`
name = f"{arch}_{plat}".upper()
self._name = Platform.normalize_platform(name)
def has_gcc_backend(self):
"Supported by GCC backend"
name = self.name()
# These backends require Visual Studio.
if name == "NT386" or name.endswith("_NT"):
return False
# Our GCC is too old for ARM support.
if re.match(r"ARM|SOL", name):
return False
# Many platforms only work on the C backend, or at least
# there are no protesting users.
if re.search(r"ALPHA|CYGWIN|MINGW|OSF|RISCV|SOLARIS|HPUX|IA64|HAIKU", name):
return False
return True
def has_gdb(self):
# So, no...
return self.name() in \
["FreeBSD4", "I386_CYGWIN", "I386_FREEBSD", "I386_LINUX", "I386_NETBSD", "LINUXLIBC6", "SOLgnu"]
def has_integrated_backend(self):
"The integrated backend supports only 32-bit Windows"
return self.name() in ["NT386", "I386_NT"]
def has_serial(self):
return self.is_win32()
def is_mingw(self):
return self.name().endswith("_MINGW")
def is_nt(self):
return self.name() == "NT386" or self.name().endswith("_NT")
def is_posix(self):
return not self.is_win32()
def is_win32(self):
return self.is_mingw() or self.is_nt()
def name(self):
"As recognized by cm3"
return self._name
def os(self):
"As recognized by cm3"
return WIN32 if self.is_win32() else POSIX
def _map_arch(self, arch):
"Map Python's architecture name to CM3's architecture name"
if arch == "x86_64": arch = "amd64"
if arch == "x86": arch = "i386"
return arch
def _map_os(self, os):
if os == "win32": os = "nt"
if os.startswith("openbsd"): os = "openbsd" # e.g. openbsd7
return os
class Cm3:
"""CM3 build environment
This class is primarily responsible for running the CM3 compiler.
It locates the compiler and the CM3 source and install
directories. It tracks requested compiler options (flags and
defines) and the current compilation target.
"""
def __init__(self, script, backend="c", defines=None, flags=None, target=None):
# The script is used to locate the source directory.
self._script = script
# Defines the backend to use when compiling packages.
self._backend = backend
# Various CM3 compiler options requested by the user.
self._defines = defines or []
self._flags = flags or []
# Compilation host and target platforms.
self._host = None
self._target = None
if target:
self._target = target if isinstance(target, Platform) else Platform(target)
# Misc. options to direct the overall behavior of the
# concierge script.
self._keep_going = False
self._list_only = False
self._no_action = False
def backend(self):
"The compiler backend to use when building packages"
# Don't try to use GCC when not available.
if self._backend == "gcc" and not self.target().has_gcc_backend():
self._backend = "c"
# Don't try to use the integrated backend when not available.
if self._backend == "integrated" and not self.target().has_integrated_backend():
self._backend = "c"
assert self._backend in ["c", "gcc", "integrated"]
return self._backend
def build(self, *paths):
"Relative to root of current build directory"
return self.source(*paths) / self.build_dir()
def build_dir(self):
"Basename of build directory"
return self.config()
def config(self):
"Used as an alias of target name"
return self.target().name()
def defines(self):
"Any '-D' command-line arguments intended for cm3"
return self._defines
def env(self):
"Execution environment for cm3 child processes"
# TODO it is not clear if some or all of these are redundant,
# given the defines passed to cm3 on the command-line (in
# `PackageAction.run`). These may simply have been an
# out-of-band communication mechanism for the legacy scripts.
return dict(
os.environ,
CM3_INSTALL=str(self.install()),
CM3_ROOT=str(self.source()),
CM3_TARGET=self.config()
)
def exe(self):
"Full path to cm3 executable"
def fail():
raise FatalError("environment variable CM3_INSTALL not set AND cm3 not found in PATH")
# Environment may override name of executable.
basename = os.environ.get("CM3", "cm3")
# If the environment specified a path, it should work as-is.
candidate = Path(basename)
if len(candidate.parents) > 1:
if candidate.is_file():
return candidate.resolve()
else:
fail()
# Environment may also override search path.
if os.environ.get("CM3_INSTALL"):
# Posix
candidate = Path(os.environ["CM3_INSTALL"], "bin", basename)
if candidate.is_file() and os.access(candidate, os.X_OK):
return candidate.resolve()
# Windows
candidate = candidate.with_suffix(".exe")
if candidate.is_file():
return candidate.resolve()
fail()
# With no overrides, we search PATH.
candidate = self._find_exe(basename)
if candidate is None:
fail()
return candidate
def _find_exe(self, basename):
"Look for an executable in PATH"
# Search PATH.
for dir in os.get_exec_path():
# Posix
candidate = Path(dir, basename)
if candidate.is_file() and os.access(candidate, os.X_OK):
return candidate.resolve()
# Windows
candidate = candidate.with_suffix(".exe")
if candidate.is_file():
return candidate.resolve()
# Not found.
return None
def flags(self):
"Command-line arguments intended for cm3"
return self._flags
def host(self):
"Compilation host, only used as default for target"
if not self._host:
self._host = self._sniff_host()
return self._host
def _sniff_host(self):
"Guess the host platform"
try:
# Ask cm3.
output = subprocess.check_output([str(self.exe()), "-version"], errors="ignore")
for line in output.splitlines():
host = line.find("host: ")
if host >= 0:
return Platform(line[host + 6:].rstrip())
except:
pass
# If there's a problem, we'll make our best guess.
return Platform()
def install(self, *paths):
"Relative to root of current installation directory"
install_dir = None
if os.environ.get("CM3_INSTALL"):
install_dir = Path(os.environ["CM3_INSTALL"]).resolve()
else:
exe_path = self.exe();
bin_dir = exe_path.parent
install_dir = bin_dir.parent
return install_dir.joinpath(*paths)
def keep_going(self):
"Continue running the concierge script in event of errors"
return self._keep_going
def list_only(self):
"List packages selected by current command-line"
return self._list_only
def no_action(self):
"Perform a dry-run, do not make any changes to the system"
return self._no_action
def script(self):
"The script is used to locate the source directory"
return Path(self._script).resolve()
def set_options(self, namespace):
"Inform CM3 of options detected in argument parsing"
for attr in ["_keep_going", "_list_only", "_no_action"]:
if hasattr(namespace, attr):
setattr(self, attr, getattr(namespace, attr))
def source(self, *paths):
"Relative to root of current source directory"
script_path = self.script()
script_dir = script_path.parent
source_dir = script_dir.parent
return source_dir.joinpath(*paths)
def target(self):
"Compilation target, passed to CM3"
if not self._target:
self._target = self._sniff_target()
return self._target
def _sniff_target(self):
"Guess the target platform"
try:
# Ask cm3.
output = subprocess.check_output([str(self.exe()), "-version"], errors="ignore")
for line in output.splitlines():
target = line.find("target: ")
if target >= 0:
return Platform(line[target + 8:].rstrip())
except:
pass
# If there's a problem, assume we're compiling for the host machine.
return self.host()
def use_c_backend(self):
return self.backend() == "c"
def use_gcc_backend(self):
return self.backend() == "gcc"
class WithCm3:
"Provides access to cm3 build context"
def __init__(self, cm3):
self._cm3 = cm3
def __getattr__(self, method_name):
"Delegate some requests to CM3"
forwards = [
"build",
"build_dir",
"config",
"defines",
"env",
"exe",
"flags",
"host",
"install",
"keep_going",
"list_only",
"no_action",
"source",
"target",
"use_c_backend",
"use_gcc_backend"
]
if method_name not in forwards:
raise AttributeError
return getattr(self.cm3(), method_name)
def cm3(self):
return self._cm3
def rmdir(self, dir):
"Recursively remove a directory"
if dir.is_dir():
print("rm", "-Rf", dir)
if not self.no_action():
shutil.rmtree(dir)
class PackageDatabase(WithCm3):
"""Knows what packages are available and their dependency order
Whereas `Cm3` knows *how* to run the compiler, the package
database knows *where* and *when* (in what order) to run the
compiler to build a set of requested packages.
"""
def __init__(self, cm3):
super().__init__(cm3)
# There is an order dependency here, sets must be loaded
# before the index.
self._load_package_sets()
self._load_package_index()
def all_packages(self):
"Canonical list of packages, in dependency order, as defined in pkginfo.txt"
# This is a superset of the packages available on the system.
return self._package_sets[ALL]
def get_package_paths(self, names):
"""Locations of all requested packages, where `names` is a mixed list
of individual packages and package sets"""
# These packages will be present on the system.
return [self.get_package_path(pkg) for pkg in self.get_packages(names)]
def get_package_path(self, name):
"Location of package relative to root of source tree"
try:
return self._package_index[name]
except:
raise FatalError(f"package {name} requested but not found")
def get_packages(self, names):
"""List of requested packages, in dependency order
Here `names` is a mixed list of packages and package sets, and
may use the add/remove syntax (`+` or `-`) to make specific
requests.
The returned packages may be a subset of those requested,
limited by what is available on the system. For example, a
request to build the GCC backend (`m3cc`) may come up empty
when GCC is not included in the distribution.
"""
# First determine what packages are requested, then later we
# will work-out the bulid order.
requested = set()
# Incorporate each listed package or set into requested.
for name in names:
remove = name.startswith("-")
if name.startswith("+") or name.startswith("-"):
name = name[1:]
if name in self._package_sets:
# name identifies a package set
if remove:
for package in self._package_sets[name]:
if package in requested:
requested.remove(package)
else:
for package in self._package_sets[name]:
requested.add(package)
elif name in self._package_index:
# name identifies an individual package
package = name
if remove:
if package in requested:
requested.remove(package)
else:
requested.add(package)
# Determine the canonical order for all requested packages.
packages = []
for package in self.all_packages():
if package in requested and package in self._package_index:
packages.append(package)
# Finally, omit anything not available to the current target.
return self._filter_packages(packages)
def is_package(self, name):
"Name identifies a package or package set"
if name.startswith("+") or name.startswith("-"):
name = name[1:]
return self._package_sets.get(name) or self._package_index.get(name)
def _filter_packages(self, packages):
"Exclude from packages anything that can't work in the target environment"
return [pkg for pkg in packages if self._include_package(pkg)]
def _include_package(self, name):
"Do we try to build this package?"
if os.environ.get("CM3_ALL"):
return True
if name == "X11R4": return self.target().is_posix()
if name == "m3cc": return self.use_gcc_backend()
if name == "m3gdb": return self.use_gcc_backend() and self.target().has_gdb()
if name == "serial": return self.target().has_serial() or os.environ.get("HAVE_SERIAL")
if name == "tapi": return self.target().is_win32()
if name == "tcl": return os.environ.get("HAVE_TCL")
return True
def _load_package_index(self):
"""Scan the source directory for available packages
Importantly, the package index reflects what packages actually
exist and can be installed. The packages listed in
pkginfo.txt are a superset of what is actually available.
"""
# Find all the fully-qualified package paths.
package_paths = []
root = self.source()
for dir, children, files in os.walk(root):
dir = Path(dir)
# src may be a package directory
if dir.name == "src" and "m3makefile" in files:
package_dir = dir.parent
package_path = package_dir.relative_to(root).as_posix()
package_paths.append(package_path)
# We can prune the search here.
children.clear()
# We can also prune specific, named directories.
if dir.name.startswith(".") or dir.name.startswith("_"):
children.clear()
if str(dir.as_posix()).endswith("examples/web"):
children.clear()
# Look for package names in the canonical list.
self._package_index = dict()
package_list = self.all_packages()
for package_path in package_paths:
# Find the canonical name of the package. The canonical
# name is some sub-path of the relative directory that
# uniquely identifies the package in `pkginfo.txt`.
package_name = str(package_path)
while package_name not in package_list and package_name.find("/") >= 0:
# Keep stripping off leading directories until we find
# a match.
package_name = package_name[package_name.find("/")+1:]
# Index the package by its canonical name, if found.
if package_name in package_list:
self._package_index[package_name] = package_path
def _load_package_sets(self):
"""Read package definitions from pkginfo.txt
pkginfo.txt defines the canonical names of all known packages
and their relative dependency order. This is separate from
the information about what packages are actually available.
"""
self._package_sets = dict()
with open(self.source("scripts/pkginfo.txt"), "r") as pkginfo:
for line in pkginfo:
line = line.rstrip()
if not line:
continue
package, *sets = line.split()
sets.insert(0, ALL)
for set in sets:
self._package_sets.setdefault(set, []).append(package)
class PackageAction(WithCm3):
"Runs cm3 on a list of packages identified by relative paths"
def __init__(self, cm3):
super().__init__(cm3)
self._success = False
def execute(self, package_paths):
"Runs cm3 for each listed package"
self._success = True
for package_path in package_paths:
try:
self.execute_path(package_path)
except:
self._success = False
if not self.keep_going():
raise
def run(self, package_path, args):
"Execute a cm3 child process"
cwd = self.source(package_path)
args = [str(self.exe())] + args + self.defines() + self.flags()
print("cd", cwd)
print(*args)
if self.no_action():
return
proc = subprocess.run(
args,
cwd=cwd,
env=self.env(),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
errors="ignore"
)
sys.stdout.write(proc.stdout)
proc.check_returncode()
def success(self):
"The last action was fully successful, with no failures"
return self._success
def defines(self):
"List of '-D' arguments to pass to cm3"
# TODO see comment in `Cm3.env`
defines = [
f"-DBUILD_DIR={self.build_dir()}",
f"-DROOT={self.source()}",
f"-DTARGET={self.config()}"
]
# Where the gcc or integrated backends are available, they are
# the default for their respective platforms and do not need
# to be specified.
if self.use_c_backend():
defines.append(f"-DM3_BACKEND_MODE=C")
# Include any defines given on the command-line.
return defines + self.cm3().defines()
class CleanAction(PackageAction):
"Clean actions need to reverse the package order, and can safely ignore errors"
def execute(self, package_paths):
# Clean in reverse dependency order to avoid warnings.
self._success = True
for package_path in reversed(package_paths):
try:
self.execute_path(package_path)
except:
self._success = False
if not self.keep_going():
raise
def keep_going(self):
"Ignore errors when cleaning"
return True
class BuildGlobal(PackageAction):
"Build package without overrides"
def execute_path(self, package_path):
self.run(package_path, ["-build"])
class BuildLocal(PackageAction):
"Build package with local overrides"
def execute_path(self, package_path):
self.run(package_path, ["-build", "-override"])
class CleanGlobal(CleanAction):
"Clean package without overrides"
def execute_path(self, package_path):
self.run(package_path, ["-clean"])
class CleanLocal(CleanAction):
"Clean package with local overrides"
def execute_path(self, package_path):
self.run(package_path, ["-clean", "-override"])
class RealClean(CleanAction):
"Remove target directory of package"
def execute_path(self, package_path):
self.rmdir(self.build(package_path))
class Ship(PackageAction):
"Install package"
def execute_path(self, package_path):
self.run(package_path, ["-ship"])
class BuildShip(PackageAction):
"Build package *without* overrides and install it"
def __init__(self, cm3):
super(BuildShip, self).__init__(cm3)
self._buildglobal = BuildGlobal(cm3)
self._ship = Ship(cm3)
def execute_path(self, package_path):
# These have to be done in lockstep. Because of various
# unclear dependencies, building everything before shipping
# anything yields a broken system.
self._buildglobal.execute_path(package_path)
self._ship.execute_path(package_path)
def keep_going(self):
"If the build fails, we don't ship"
return False
class CompositeAction(PackageAction):
"Executes sequential package actions"
def __init__(self, cm3, actions):
super().__init__(cm3)
self._actions = actions
def execute(self, package_paths):
self._success = True
for action in self._actions:
try:
action.execute(package_paths)
self._success = self._success and action.success()
except:
self._success = False
if not self.keep_going():
raise
class WithPackageDb(WithCm3):
"Provides access to package database"
def __init__(self, cm3, package_db):
super().__init__(cm3)