Repository navigation
Expand file tree
/
Copy pathmm
More file actions
executable file
·3967 lines (3814 loc) · 168 KB
/
Copy pathmm
File metadata and controls
executable file
·3967 lines (3814 loc) · 168 KB
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
# -*- python -*-
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2026 all rights reserved
# externals
import json
import os
import re
import shutil
import subprocess
import sys
import urllib.request
# attempt to
try:
# access the framework
import pyre
# if it's not accessible
except ImportError:
# we will download the canonical version
_pyre_release = "v1.14.0"
# of the bootstrapping archive
_pyre_boot = "pyre-boot.zip"
# form the home of the python bootstrap
_mm_pdir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".mm"))
# if it doesn't exist, make it
os.makedirs(_mm_pdir, exist_ok=True)
# and deposit it there
_mm_pyre = os.path.join(_mm_pdir, _pyre_boot)
# if the file is not already there
if not os.path.exists(_mm_pyre):
# form the source url
_pyre_url = f"https://github.com/pyre/pyre/releases/download/{_pyre_release}/{_pyre_boot}"
# let the user know, on stderr, so the output of commands such as {--activate} stays clean
print(f"mm: downloading '{_pyre_url}'", file=sys.stderr)
# and grab the archive from the web
with urllib.request.urlopen(url=_pyre_url) as istream:
# open the local file
with open(_mm_pyre, "wb") as ostream:
# pull data and write it out
ostream.write(istream.read())
# add the pyre archive to the path, right after the cwd
sys.path.insert(1, _mm_pyre)
# and try importing the framework once more
import pyre
# if nothing went wrong
else:
# leave a marker, just in case someone cares
_mm_pyre = None
# set the version
_mm_version = "5.4.2"
# find out where i live
_mm_home = pyre.primitives.path(__file__).resolve().parent
# check whether i'm running from my source directory
_mm_insitu = (_mm_home / "make" / "merlin.mm").exists()
# if i'm running in-place
if _mm_insitu:
# this is the layout i expect to see:
# the {portinfo} headers
_mm_incdir = _mm_home / "include" / "mm"
# the share area
_mm_shrdir = _mm_home
# my makefiles
_mm_mkdir = _mm_shrdir / "make"
# otherwise
else:
# assume i am installed in a u*ixy environment:
# the {portinfo} headers
_mm_incdir = (_mm_home / ".." / "include" / "mm").resolve()
# my share area
_mm_shrdir = (_mm_home / ".." / "share" / "mm").resolve()
# my makefiles
_mm_mkdir = (_mm_shrdir / "make").resolve()
# get journal
import journal
# the app
class Builder(pyre.application, family="pyre.applications.mm", namespace="mm"):
"""
mm {}
An opinionated framework for building software based on GNU make
Michael Aïvázis <michael.aivazis@para-sim.com>
copyright 1998-2026 all rights reserved
"""
# record the version number
__doc__ = __doc__.format(_mm_version)
# project configuration
version = pyre.properties.str()
version.default = None
version.doc = "the project version; try to deduce it, if not set"
# what the build is for, which decides where its products go
mode = pyre.properties.str()
mode.default = "dev"
mode.validators = pyre.constraints.isMember(
"dev", "release", "conda", "macports", "ubuntu", "fedora"
)
mode.doc = "the strategy for generating locations for the build products"
# whether the developer-time checks compile in, whatever the mode says
assertions = pyre.properties.bool()
assertions.default = None
assertions.doc = "compile in the developer-time checks whatever the mode says (False leaves them out; None defers to the mode)"
# whether the build writes the type stubs of the extension modules
stubs = pyre.properties.bool()
stubs.default = False
stubs.doc = "write the type stubs of the extension modules, when their generator is installed"
# whether the tag follows the branch of the repository
branch = pyre.properties.bool()
branch.default = None
branch.doc = (
"derive the {tag} from repository state (False clears it; None leaves it unchanged)"
)
# print the commands that add the build products to the shell session
activate = pyre.properties.bool()
activate.default = False
activate.doc = (
"print shell commands that add the build's bin and python packages to the session"
)
# in the syntax of the shell that reads them
syntax = pyre.properties.str()
syntax.default = "sh"
syntax.validators = pyre.constraints.isMember("sh", "csh", "fish")
syntax.doc = "the shell syntax to use when printing export statements"
# the discriminator that keeps build contexts apart
tag = pyre.properties.str()
tag.default = os.environ.get("mm_tag")
tag.doc = (
"an optional discriminator appended to {bldroot} and {prefix} to separate build contexts"
)
# where the build installs its products
prefix = pyre.properties.path()
prefix.default = None
prefix.doc = "the path to the installation directory"
# where the build keeps its intermediate products
bldroot = pyre.properties.path()
bldroot.default = None
bldroot.doc = "the path to the intermediate build products"
# where the developer toolchains of the environment live
toolchains = pyre.properties.path()
toolchains.default = None
toolchains.doc = "the directory where environment-level developer toolchains are installed"
# the variants to build
target = pyre.properties.strings()
target.default = ["debug", "shared"]
target.doc = "the list of target variants to build"
# the compilers to build with
compilers = pyre.properties.strings()
compilers.default = ["clang", "python/python3"]
compilers.doc = "the set of compilers to use"
# a makefile with targets of the user's own
local = pyre.properties.str()
local.default = None
local.doc = "the name of an optional local makefile with additional targets"
# the package manager that knows where the external dependencies live
pkgdb = pyre.properties.str()
pkgdb.default = "adhoc"
pkgdb.validators = pyre.constraints.isMember("adhoc", "conda", "macports", "dpkg", "rpm")
pkgdb.doc = "use one of the supported package managers for resolving external dependencies"
# mm behavior
setup = pyre.properties.bool()
setup.default = False
setup.doc = "build a package database, instead of invoking make"
# whether make runs one recipe at a time
serial = pyre.properties.bool()
serial.default = False
serial.doc = "control whether to run make in parallel"
# or how many it runs at once
slots = pyre.properties.int()
slots.default = None
slots.aliases |= {"j", "jobs"}
slots.doc = "the number of recipes to execute simultaneously; defaults to all cores"
# show how make is invoked
show = pyre.properties.bool()
show.default = False
show.doc = "display details about the invocation of make"
# go through the motions without invoking make
dry = pyre.properties.bool()
dry.default = False
dry.aliases |= {"n"}
dry.doc = "do everything except invoke make"
# keep the output to what matters
quiet = pyre.properties.bool()
quiet.default = False
quiet.aliases |= {"q"}
quiet.doc = "suppress all non-critical output"
# colorize the output
color = pyre.properties.bool()
color.default = True
color.doc = "colorize screen output on supported terminals"
# with these colors
palette = pyre.properties.str()
palette.default = "builtin"
palette.doc = "color palette for colorizing screen output on supported terminals"
# make behavior
ignore = pyre.properties.bool()
ignore.default = False
ignore.aliases |= {"k"}
ignore.doc = "ask make to ignore build target failures and keep going"
# show the commands make runs
verbose = pyre.properties.bool()
verbose.default = False
verbose.aliases |= {"v"}
verbose.doc = "ask make to show each action taken"
# show the rule database of make
rules = pyre.properties.bool()
rules.default = False
rules.doc = "ask make to print the rule database"
# show why make does what it does
trace = pyre.properties.bool()
trace.default = False
trace.doc = "ask make to print trace information"
# the name of the GNU make executable
make = pyre.properties.path(default=os.environ.get("GNU_MAKE", "gmake"))
make.default = os.environ.get(
"GNU_MAKE", "gmake" if pyre.executive.host.platform == "darwin" else "make"
)
make.doc = "the name of the GNU make executable"
# environment
host = pyre.platforms.platform()
host.doc = "information about the current host"
# the active conda environment
environment = pyre.properties.str()
environment.default = os.environ.get("CONDA_DEFAULT_ENV", "")
environment.doc = "the name of the conda environment"
# the name of the directory with project and user makefile fragments
cfgdir = pyre.properties.path()
cfgdir.default = ".mm"
cfgdir.doc = "the relative path to project and user makefile fragments"
# the layout of the installation area: executables
binPrefix = pyre.properties.path()
binPrefix.default = "bin"
binPrefix.aliases |= {"bin-prefix"}
binPrefix.doc = "installation location for executables"
# libraries and shared objects
libPrefix = pyre.properties.path()
libPrefix.default = "lib"
libPrefix.aliases |= {"lib-prefix"}
libPrefix.doc = "installation location for libraries and shared objects"
# headers
incPrefix = pyre.properties.path()
incPrefix.default = "include"
incPrefix.aliases |= {"include-prefix"}
incPrefix.doc = "installation location for header files"
# python packages
pycPrefix = pyre.properties.path()
pycPrefix.default = "packages"
pycPrefix.aliases |= {"python-prefix"}
pycPrefix.doc = "installation location for python packages"
# documentation
docPrefix = pyre.properties.path()
docPrefix.default = "doc"
docPrefix.aliases |= {"doc-prefix"}
docPrefix.doc = "installation location for documentation files"
# auxiliary files
etcPrefix = pyre.properties.path()
etcPrefix.default = "etc"
etcPrefix.aliases |= {"etc-prefix"}
etcPrefix.doc = "installation location for system auxiliary files"
# platform independent files
sharePrefix = pyre.properties.path()
sharePrefix.default = "share"
sharePrefix.aliases |= {"share-prefix"}
sharePrefix.doc = "installation location for platform independent files"
# runtime files
varPrefix = pyre.properties.path()
varPrefix.default = "var"
varPrefix.aliases |= {"var-prefix"}
varPrefix.doc = "installation location for runtime files"
# my internal layout; users should probably stay away from these
merlin = pyre.properties.path()
merlin.default = "merlin.mm"
merlin.doc = "the name of the top level internal makefile; caveat emptor"
# where the make engine lives
engine = pyre.properties.path()
engine.default = _mm_mkdir
engine.doc = "the path to the built-in make engine; caveat emptor"
# where the portinfo headers live
portinfo = pyre.properties.path(default=_mm_incdir)
portinfo.doc = "the directory with the built-in portinfo headers; caveat emptor"
# more places where make looks for makefiles
runcfg = pyre.properties.paths()
runcfg.doc = "a list of paths to add to the make include path; caveat emptor"
# important environment variables
PATH = pyre.properties.envpath(variable="PATH")
# and where python looks for packages
PYTHONPATH = pyre.properties.envpath(variable="PYTHONPATH")
# compiler search paths
incpath = pyre.properties.paths()
incpath.doc = "a list of paths to search for headers"
# and where to search for libraries
libpath = pyre.properties.paths()
libpath.doc = "a list of paths to search for libraries"
# the main entry point
@pyre.export
def main(self, *args, **kwds):
"""
The main entry point
"""
# if we are just setting up the package database
if self.setup:
# build the package database
return self.buildPackageDatabase()
# if we are setting or clearing the branch context
if self.branch is not None:
# generate the {eval} script
return self.establishBranchContext()
# if we are activating the build in the current session
if self.activate:
# generate the {eval} script
return self.activateSession()
# otherwise, launch the build
return self.launch()
# metamethods
def __init__(self, **kwds):
# chain up
super().__init__(**kwds)
# N.B.:
# the {explore} step could happen here
# there were some corner cases that were raising exceptions
# investigate and rethink
# get the current user
self.user = self.pyre_executive.user
# and the version
self._version = _mm_version
# prime the make executable
self._builder = None
# my top level makefile
self._makefile = None
# the user configuration directory
self._userCfg = None
# the project root
self._root = None
# the project configuration directory
self._projectCfg = None
# the path to the optional makefile with additional configuration and targets
self._localMakefile = None
# the name of the compiler suite used to compile C/C++ code, and hence is responsible
# for setting the runtime ABI
self._suite = None
# the path to the intermediate products of the build
self._bldroot = None
# the target identification
self._bldTarget = None
self._bldVariants = None
self._bldTag = None
# and the install directory
self._prefix = None
# the directory with the environment-level developer toolchains
self._toolchains = None
# the python package installation directory; may be overridden by mode-specific logic
self._pycPrefix = None
# the syntax dispatch table: maps shell names to (var, value) -> export/unset statement
# {value} of None means unset the variable rather than export it; every statement is
# terminated with a ';' so the lines survive being flattened onto one line — an unquoted
# 'eval $(mm --activate)' collapses the newlines, and without the terminator one statement
# runs into the next (zsh errors outright, bash silently mis-parses)
self._syntaxDispatch = {
"sh": lambda var, value: (
f"unset {var};" if value is None else f'export {var}="{value}";'
),
"csh": lambda var, value: (
f"unsetenv {var};" if value is None else f'setenv {var} "{value}";'
),
"fish": lambda var, value: (
f"set -e {var};" if value is None else f'set -x {var} "{value}";'
),
}
# the mode dispatch tables
self._bldrootDispatch = {
"dev": self._devBldroot,
"release": self._releaseBldroot,
"conda": self._condaBldroot,
"macports": self._macportsBldroot,
"ubuntu": self._ubuntuBldroot,
"fedora": self._fedoraBldroot,
}
self._prefixDispatch = {
"dev": self._devPrefix,
"release": self._releasePrefix,
"conda": self._condaPrefix,
"macports": self._macportsPrefix,
"ubuntu": self._ubuntuPrefix,
"fedora": self._fedoraPrefix,
}
# the pkgdb dispatch table
self._pkgdbDispatch = {
"adhoc": self._buildAdhocPackageDatabase,
"conda": self._buildCondaPackageDatabase,
"macports": self._buildMacportsPackageDatabase,
"dpkg": self._buildDpkgPackageDatabase,
"rpm": self._buildRpmPackageDatabase,
}
# verify both mode dispatch tables are in sync with the mode validator; scan for the
# first validator that carries a {choices} attribute (see pyre/pyre#176 for a better API)
for modeValidator in filter(
lambda v: hasattr(v, "choices"), self.pyre_trait("mode").validators
):
# check both tables
for name, table in [
("bldroot", self._bldrootDispatch),
("prefix", self._prefixDispatch),
]:
# if the keys don't match the validator choices, something is wrong
if set(table) != modeValidator.choices:
# make a channel
channel = journal.firewall("mm.mode")
# report
channel.line(f"{name} dispatch table is out of sync with the mode validator")
# indent
channel.indent()
# details:
channel.line(f"dispatch keys: {set(table)}")
# and the choices of the validator
channel.line(f"validator choices: {modeValidator.choices}")
# outdent
channel.outdent()
# flush
channel.log()
# we only care about the first match
break
# verify the pkgdb dispatch table is in sync with the pkgdb validator
for pkgdbValidator in filter(
lambda v: hasattr(v, "choices"), self.pyre_trait("pkgdb").validators
):
# if the keys don't match the validator choices, something is wrong
if set(self._pkgdbDispatch) != pkgdbValidator.choices:
# make a channel
channel = journal.firewall("mm.pkgdb")
# report
channel.line("pkgdb dispatch table is out of sync with the pkgdb validator")
# indent
channel.indent()
# the keys of the table
channel.line(f"dispatch keys: {set(self._pkgdbDispatch)}")
# and the choices of the validator
channel.line(f"validator choices: {pkgdbValidator.choices}")
# outdent
channel.outdent()
# flush
channel.log()
# we only care about the first match
break
# verify the syntax dispatch table is in sync with the syntax validator
for syntaxValidator in filter(
lambda v: hasattr(v, "choices"), self.pyre_trait("syntax").validators
):
# if the keys don't match the validator choices, something is wrong
if set(self._syntaxDispatch) != syntaxValidator.choices:
# make a channel
channel = journal.firewall("mm.syntax")
# report
channel.line("syntax dispatch table is out of sync with the syntax validator")
# indent
channel.indent()
# the keys of the table
channel.line(f"dispatch keys: {set(self._syntaxDispatch)}")
# and the choices of the validator
channel.line(f"validator choices: {syntaxValidator.choices}")
# outdent
channel.outdent()
# flush
channel.log()
# we only care about the first match
break
# all done
return
# implementation details
def launch(self):
"""
Launch GNU make
"""
# explore
self.explore()
# if the user has asked to see the recipe execution details
if self.verbose:
# fall back to serial mode so the output is not garbled
self.serial = True
# build the make command line
argv = list(self.assembleMakeCommandLine())
# if the user asked to see the make command line
if self.show:
# make a channel
channel = journal.help("mm.make")
# show
channel.line(argv[0])
# indent
channel.indent()
# the arguments
channel.report(report=argv[1:])
# outdent
channel.outdent()
# flush
channel.log()
# if this is a dry run
if self.dry:
# do not go any further
return 0
# go to the right place
os.chdir(self._anchor)
# build the environment updates
env = {
"PATH": os.pathsep.join(map(str, self.PATH)),
"PYTHONPATH": os.pathsep.join(map(str, self.PYTHONPATH)),
}
# apply them
os.environ.update(env)
# assemble the subprocess options
settings = {
"executable": str(self.make),
"args": argv,
"universal_newlines": True,
"shell": False,
}
# invoke GNU make; we already know {self.make} is good, since we verified its version.
# any other modes of failure?
with subprocess.Popen(**settings) as make:
# wait for it to finish and harvest its exit code
status = make.wait()
# and share it with the shell
return status
def buildPackageDatabase(self):
"""
Build an external package database for the engine
"""
# explore the project layout so {locateBuildRoot} can find the project root
self.explore()
# get the temporary staging area; already incorporates the build variant tag
stage = self.locateBuildRoot()
# ensure the staging directory exists on a fresh checkout
stage.mkdir(parents=True, exist_ok=True)
# the location of the package database
db = stage / f"pkg-{self.pkgdb}.db"
# dispatch to the mode-specific implementation
return self._pkgdbDispatch[self.pkgdb](db)
def establishBranchContext(self):
"""
Set or clear the branch-keyed tag and activate the corresponding session
"""
# if branch is True, derive a tag from the repository state
if self.branch:
# find the project root to get the project name
root = self.locateProjectRoot()
# get the branch name
branch = self.gitCurrentBranch()
# the tag is the relative path that discriminates this build context; it is
# appended to {bldroot} and {prefix} by {locateBuildRoot} and {locatePrefix}
self.tag = f"{root.name}/{branch}"
# if branch is False, clear the tag so the tag-less paths are used
else:
# by clearing it
self.tag = None
# let {activateSession} emit the full shell context, including the updated {mm_tag}
return self.activateSession()
def activateSession(self):
"""
Print shell commands that establish the build context in the current session
"""
# resolve all paths
self.explore()
# the new installation prefix and python package directory
newPrefix = self._prefix
# and the python packages under it
newPyc = newPrefix / (self._pycPrefix or self.pycPrefix)
# if a previous activation is recorded in the environment, remove its contributions
# from the path variables before injecting the new ones
oldPrefixStr = os.environ.get("mm_prefix")
# along with its python package directory
oldPycStr = os.environ.get("mm_pyc")
# if there was a previous prefix
if oldPrefixStr:
# take its executables off the path
self.PATH = self.eject(var=self.PATH, path=(pyre.primitives.path(oldPrefixStr) / "bin"))
# if there was a previous python package directory
if oldPycStr:
# take it off the python path
self.PYTHONPATH = self.eject(var=self.PYTHONPATH, path=pyre.primitives.path(oldPycStr))
# build the updated PATH and PYTHONPATH with the new entries at the front
path = os.pathsep.join(str(p) for p in self.inject(var=self.PATH, path=(newPrefix / "bin")))
# and the python path
pythonpath = os.pathsep.join(str(p) for p in self.inject(var=self.PYTHONPATH, path=newPyc))
# emit the full shell context
emit = self._syntaxDispatch[self.syntax]
# the tag: None triggers an unset rather than an export
print(emit("mm_tag", self.tag or None))
# the prefix and python package path, so the next activation can undo this one
print(emit("mm_prefix", str(newPrefix)))
# along with the python package directory
print(emit("mm_pyc", str(newPyc)))
# the updated path variables
print(emit("PATH", path))
# and the python path
print(emit("PYTHONPATH", pythonpath))
# all done
return 0
def explore(self):
"""
Gather the locations of all important directories and files
"""
# verify we have the correct make
self._builder = self.verifyGNUMake()
# verify my installation
self._makefile = self.verifyInstallation()
# get the user configuration directory
self._userCfg = self.locateUserConfig()
# find the project root
self._root = self.locateProjectRoot()
# and the project configuration directory
self._projectCfg = self.locateProjectConfig()
# load the project specific configuration files
self.loadProjectConfig()
# locate the local makefile
self._localMakefile = self.locateLocalMakefile()
# mark the location from which mm was invoked
self._origin = pyre.primitives.path.cwd()
# mark the path that will become the {cwd} for make
self._anchor = self._localMakefile.parent if self._localMakefile else self._root
# determine the compiler suite
self._suite = self.deduceCompilerSuite()
# construct the build tag; must precede {locateBuildRoot} since it needs {_bldTag}
self._bldTarget, self._bldVariants, self._bldTag = self.assembleBuildTarget()
# figure out where to put the intermediate products of the build
self._bldroot = self.locateBuildRoot()
# figure out the install directory
self._prefix = self.locatePrefix()
# figure out where the environment-level developer toolchains live
self._toolchains = self.locateToolchains()
# adjust my environment variables with the build configuration
self.updateEnvironmentVariables()
# all done
return
def assembleMakeCommandLine(self):
"""
Put together the GNU make command line
"""
# start with the flags that control the behavior of make
yield from self.configureMake()
# add the project configuration
yield from self.configureProject()
# the product version
yield from self.configureVersion()
# the build target
yield from self.configureTarget()
# information about the user that invoked mm
yield from self.describeUser()
# information about the host mm is running on
yield from self.describeHost()
# configure the engine
yield from self.configureBuilder()
# finally, whatever else the user put on the command line
yield from self.argv
# all done
return
def verifyInstallation(self):
"""
Ensure that this is a valid installation
"""
# anything wrong here is an error
# if the path to the engine doesn't exist
if not self.engine.exists():
# grab a channel
channel = journal.error("mm.installation")
# complain
channel.line(f"could not find the path to my makefiles")
# what we were doing
channel.line(f"while verifying my installation")
# indent
channel.indent()
# the path
channel.line(f"the path '{self.engine}'")
# what is wrong with it
channel.line(f"doesn't exist or is not readable")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'engine' property")
# flush
channel.log()
# form the path to the top level makefile
merlin = self.engine / self.merlin
# check that the top level makefile exists
if not merlin.exists():
# grab a channel
channel = journal.error("mm.installation")
# complain
channel.line(f"could not find my main makefile")
# what we were doing
channel.line(f"while verifying my installation")
# indent
channel.indent()
# the file
channel.line(f"the file '{merlin}'")
# what is wrong with it
channel.line(f"doesn't exist or is not readable")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'makefile' property")
# flush
channel.log()
# if the path to the {portinfo} headers doesn't exist
if not self.portinfo.exists():
# grab a channel
channel = journal.error("mm.installation")
# complain
channel.line(f"can't find my include directory")
# what we were doing
channel.line(f"while verifying my installation")
# indent
channel.indent()
# the path
channel.line(f"the path '{self.portinfo}'")
# what is wrong with it
channel.line(f"doesn't exist or is not readable")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'portinfo' property")
# flush
channel.log()
# form the path to the {portinfo}
portinfo = self.portinfo / "portinfo"
# check that the top level header file exists
if not portinfo.exists():
# grab a channel
channel = journal.error("mm.installation")
# complain
channel.line(f"could not find my top level header file")
# what we were doing
channel.line(f"while verifying my installation")
# indent
channel.indent()
# the file
channel.line(f"the file '{portinfo}'")
# what is wrong with it
channel.line(f"doesn't exist or is not readable")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'portinfo' property")
# flush
channel.log()
# all done
return merlin
def verifyGNUMake(self):
"""
Get the GNU make version and verify it's sufficiently recent
"""
# set up the subprocess settings
settings = {
"executable": str(self.make),
"args": [str(self.make), "--version"],
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"universal_newlines": True,
"shell": False,
}
# attempt to
try:
# invoke GNU make to extract its version
with subprocess.Popen(**settings) as make:
# wait for it to finish and harvest its exit code
stdout, stderr = make.communicate()
# grab the status code
status = make.returncode
# if there was an error
if status != 0:
# grab a channel
channel = journal.error("mm.gnu")
# complain
channel.line(f"failed to launch '{self.make}'")
# what we were doing
channel.line(f"while attempting to retrieve the version of GNU make")
# indent
channel.indent()
# the status it returned
channel.line(f"'{self.make}' returned error code {status}")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'make' property")
# flush
channel.log()
# and bail, just in case errors aren't fatal
return
# otherwise, grab the first line of output
signature = stdout.splitlines()[0]
# take it apart using the GNU make version parser
match = self.gnuMakeVersionParser.match(signature)
# if it doesn't match
if not match:
# we have a problem
channel = journal.error("mm.gnu")
# complain
channel.line(f"could not find a suitable installation of GNU make")
# what we were doing
channel.line(f"while verifying my installation")
# indent
channel.indent()
# what is wrong
channel.line(f"'{self.make}' doesn't seem to be GNU make")
# and what is needed
channel.line(f"you need GNU make 4.4 or higher")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'make' property")
# flush
channel.log()
# and bail, just in case errors aren't fatal
return
# get the version info
major, minor, micro = map(int, match.groups(default=0))
# we need 4.4 or higher, for the {.WAIT} prerequisite ordering primitive
if (major, minor, micro) < (4, 4, 0):
# we have a problem
channel = journal.error("mm.gnu")
# complain
channel.line(f"your version of GNU make is too old")
# what we were doing
channel.line(f"while verifying my installation")
# indent
channel.indent()
# what is needed
channel.line(f"you need GNU make 4.4 or higher")
# and what was found
channel.line(f"your '{self.make}' version is {major}.{minor}.{micro}")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'make' property")
# flush
channel.log()
# and bail, just in case errors aren't fatal
return
# if the executable could not be found
except FileNotFoundError as error:
# we have a problem
channel = journal.error("mm.gnu")
# complain
channel.line(f"an unexpected error occurred")
# what we were doing
channel.line(f"while attempting to retrieve the version of GNU make")
# indent
channel.indent()
# the executable
channel.line(f"could not find '{self.make}'")
# and what happened
channel.line(f"launching it resulted in: {error}")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'make' property")
# flush
channel.log()
# if the launch fails in a more general way
except OSError as error:
# we have a problem
channel = journal.error("mm.gnu")
# complain
channel.line(f"an unexpected error occurred")
# what we were doing
channel.line(f"while attempting to retrieve the version of GNU make")
# indent
channel.indent()
# the executable
channel.line(f"launching '{self.make}' returned")
# and what it said
channel.line(f"{error}")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'make' property")
# flush
channel.log()
# if {subprocess} detected some other kind of problem
except subprocess.SubprocessError as error:
# we have a problem
channel = journal.error("mm.gnu")
# complain
channel.line(f"an unexpected error occurred")
# what we were doing
channel.line(f"while attempting to retrieve the version of GNU make")
# indent
channel.indent()
# the executable
channel.line(f"launching '{self.make}' failed with")
# and the error
channel.line(f"{error}")
# outdent
channel.outdent()
# what to check
channel.line(f"check your setting for my 'make' property")
# flush
channel.log()
# all done
return
def locateUserConfig(self):
"""
Find the user configuration directory
"""
# figure out where the configuration directory is; first, try looking for an XDG compliant
# layout; perhaps the system sets up the mandated environment variable
xdgHome = (
pyre.primitives.path(os.getenv("XDG_CONFIG_HOME", self.XDG_CONFIG))
.expanduser()
.resolve()
)
# point to the {mm} specific directory
xdg = xdgHome / "mm"
# if it is a real directory
if xdg.exists() and xdg.isDirectory():
# hand it off
return xdg
# otherwise, get the user's home directory
home = self.user.home
# if it's not a good place
if not (home and home.exists()):
# and we are allowed to speak
if not self.quiet:
# make a channel
channel = journal.warning("mm.user")
# complain
channel.line(f"could not find your home directory")
# what we were doing
channel.line(f"while looking for user specific makefile fragments")
# indent
channel.indent()
# the home directory
channel.line(f"'{home}' is not a valid path")
# is not usable
channel.line(f"and your system doesn't have any good ideas")