/
manager.d
2372 lines (2011 loc) · 67.1 KB
/
manager.d
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
/**
* Code to manage a D checkout and its dependencies.
*
* License:
* This Source Code Form is subject to the terms of
* the Mozilla Public License, v. 2.0. If a copy of
* the MPL was not distributed with this file, You
* can obtain one at http://mozilla.org/MPL/2.0/.
*
* Authors:
* Vladimir Panteleev <vladimir@thecybershadow.net>
*/
module ae.sys.d.manager;
import std.algorithm;
import std.array;
import std.conv;
import std.datetime;
import std.exception;
import std.file;
import std.path;
import std.process : spawnProcess, wait, escapeShellCommand;
import std.range;
import std.regex;
import std.string;
import std.typecons;
import ae.sys.d.cache;
import ae.sys.d.repo;
import ae.sys.file;
import ae.sys.git;
import ae.utils.aa;
import ae.utils.array;
import ae.utils.digest;
import ae.utils.json;
import ae.utils.regex;
alias ensureDirExists = ae.sys.file.ensureDirExists;
version (Windows)
{
import ae.sys.install.dmc;
import ae.sys.install.msys;
import ae.sys.install.vs;
extern(Windows) void SetErrorMode(int);
}
import ae.sys.install.dmd;
import ae.sys.install.git;
import ae.sys.install.kindlegen;
static import std.process;
/// Class which manages a D checkout and its dependencies.
class DManager : ICacheHost
{
// **************************** Configuration ****************************
struct Config /// DManager configuration.
{
struct Build /// Build configuration
{
struct Components
{
bool[string] enable;
string[] getEnabledComponentNames()
{
foreach (componentName; enable.byKey)
enforce(allComponents.canFind(componentName), "Unknown component: " ~ componentName);
return allComponents
.filter!(componentName =>
enable.get(componentName, defaultComponents.canFind(componentName)))
.array
.dup;
}
Component.CommonConfig common;
DMD.Config dmd;
Website.Config website;
}
Components components;
/// Additional environment variables.
/// Supports %VAR% expansion - see applyEnv.
string[string] environment;
}
Build build; /// ditto
/// Machine-local configuration
/// These settings should not affect the build output.
struct Local
{
/// URL of D git repository hosting D components.
/// Defaults to (and must have the layout of) D.git:
/// https://github.com/CyberShadow/D-dot-git
string repoUrl = "https://bitbucket.org/cybershadow/d.git";
/// Location for the checkout, temporary files, etc.
string workDir;
/// If present, passed to GNU make via -j parameter.
/// Can also be "auto" or "unlimited".
string makeJobs;
/// Don't get latest updates from GitHub.
bool offline;
/// How to cache built files.
string cache;
}
Local local; /// ditto
}
Config config; /// ditto
// Behavior options that generally depend on the host program.
/// Automatically re-clone the repository in case
/// "git reset --hard" fails.
bool autoClean;
/// Whether to verify working tree state
/// to make sure we don't clobber user changes
bool verifyWorkTree;
/// Whether we should cache failed builds.
bool cacheFailures = true;
/// Current build environment.
struct Environment
{
struct Deps /// Configuration for software dependencies
{
string dmcDir; /// Where dmc.zip is unpacked.
string vsDir; /// Where Visual Studio is installed
string sdkDir; /// Where the Windows SDK is installed
string hostDC; /// Host D compiler (for DDMD bootstrapping)
}
Deps deps; /// ditto
/// Calculated local environment, incl. dependencies
string[string] vars;
}
/// Get a specific subdirectory of the work directory.
@property string subDir(string name)() { return buildPath(config.local.workDir, name); }
alias repoDir = subDir!"repo"; /// The git repository location.
alias buildDir = subDir!"build"; /// The build directory.
alias dlDir = subDir!"dl"; /// The directory for downloaded software.
/// This number increases with each incompatible change to cached data.
enum cacheVersion = 3;
string cacheEngineDir(string engineName)
{
// Keep compatibility with old cache paths
string engineDirName =
engineName.isOneOf("directory", "true") ? "cache" :
engineName.isOneOf("", "none", "false") ? "temp-cache" :
"cache-" ~ engineName;
return buildPath(
config.local.workDir,
engineDirName,
"v%d".format(cacheVersion),
);
}
version (Windows)
{
enum string binExt = ".exe";
enum configFileName = "sc.ini";
}
else
{
enum string binExt = "";
enum configFileName = "dmd.conf";
}
static bool needConfSwitch() { return exists(std.process.environment.get("HOME", null).buildPath(configFileName)); }
// **************************** Repositories *****************************
class DManagerRepository : ManagedRepository
{
this()
{
this.offline = config.local.offline;
this.verify = this.outer.verifyWorkTree;
}
override void log(string s) { return this.outer.log(s); }
}
class MetaRepository : DManagerRepository
{
override void needRepo()
{
needGit();
if (!repoDir.exists)
{
log("Cloning initial repository...");
atomic!performClone(config.local.repoUrl, repoDir);
}
if (!git.path)
git = Repository(repoDir);
}
static void performClone(string url, string target)
{
import ae.sys.cmd;
run(["git", "clone", url, target]);
}
override void performCheckout(string hash)
{
super.performCheckout(hash);
submodules = null;
}
string[string][string] submoduleCache;
string[string] getSubmoduleCommits(string head)
{
auto pcacheEntry = head in submoduleCache;
if (pcacheEntry)
return (*pcacheEntry).dup;
string[string] result;
needRepo();
foreach (line; git.query("ls-tree", head).splitLines())
{
auto parts = line.split();
if (parts.length == 4 && parts[1] == "commit")
result[parts[3]] = parts[2];
}
assert(result.length, "No submodules found");
submoduleCache[head] = result;
return result.dup;
}
/// Get the submodule state for all commits in the history.
/// Returns: result[commitHash][submoduleName] == submoduleCommitHash
string[string][string] getSubmoduleHistory(string[] refs)
{
auto marksFile = buildPath(config.local.workDir, "temp", "marks.txt");
ensurePathExists(marksFile);
scope(exit) if (marksFile.exists) marksFile.remove();
log("Running fast-export...");
auto fastExportData = git.query([
"fast-export",
"--full-tree",
"--no-data",
"--export-marks=" ~ marksFile.absolutePath,
] ~ refs
);
log("Parsing fast-export marks...");
auto markLines = marksFile.readText.strip.splitLines;
auto marks = new string[markLines.length];
foreach (line; markLines)
{
auto parts = line.split(' ');
auto markIndex = parts[0][1..$].to!int-1;
marks[markIndex] = parts[1];
}
log("Parsing fast-export data...");
string[string][string] result;
foreach (i, commitData; fastExportData.split("deleteall\n")[1..$])
result[marks[i]] = commitData
.matchAll(re!(`^M 160000 ([0-9a-f]{40}) (\S+)$`, "m"))
.map!(m => tuple(m.captures[2], m.captures[1]))
.assocArray
;
return result;
}
}
class SubmoduleRepository : DManagerRepository
{
string dir;
override void needRepo()
{
getMetaRepo().needRepo();
if (!git.path)
git = Repository(dir);
}
override void needHead(string hash)
{
if (!autoClean)
super.needHead(hash);
else
try
super.needHead(hash);
catch (RepositoryCleanException e)
{
log("Error during repository cleanup.");
log("Nuking %s...".format(dir));
rmdirRecurse(dir);
auto name = baseName(dir);
auto gitDir = buildPath(dirName(dir), ".git", "modules", name);
log("Nuking %s...".format(gitDir));
rmdirRecurse(gitDir);
log("Updating submodule...");
getMetaRepo().git.run(["submodule", "update", name]);
reset();
log("Trying again...");
super.needHead(hash);
}
}
}
/// The meta-repository, which contains the sub-project submodules.
private MetaRepository metaRepo;
MetaRepository getMetaRepo() /// ditto
{
if (!metaRepo)
metaRepo = new MetaRepository;
return metaRepo;
}
/// Sub-project repositories.
private SubmoduleRepository[string] submodules;
ManagedRepository getSubmodule(string name) /// ditto
{
assert(name, "This component is not associated with a submodule");
if (name !in submodules)
{
getMetaRepo().needRepo();
enforce(name in getMetaRepo().getSubmoduleCommits(getMetaRepo().getRef("origin/master")),
"Unknown submodule: " ~ name);
auto path = buildPath(metaRepo.git.path, name);
auto gitPath = buildPath(path, ".git");
if (!gitPath.exists)
{
log("Initializing and updating submodule %s...".format(name));
getMetaRepo().git.run(["submodule", "update", "--init", name]);
}
submodules[name] = new SubmoduleRepository();
submodules[name].dir = path;
}
return submodules[name];
}
// ***************************** Components ******************************
/// Base class for a D component.
class Component
{
/// Name of this component, as registered in DManager.components AA.
string name;
/// Corresponding subproject repository name.
@property abstract string submoduleName();
@property ManagedRepository submodule() { return getSubmodule(submoduleName); }
/// Configuration applicable to multiple (not all) components.
/// Note: don't serialize this structure whole!
/// Only serialize used fields.
struct CommonConfig
{
version (Windows)
enum defaultModel = "32";
else
version (D_LP64)
enum defaultModel = "64";
else
enum defaultModel = "32";
string model = defaultModel; /// Target model ("32" or "64").
string[] makeArgs; /// Additional make parameters,
/// e.g. "HOST_CC=g++48"
}
/// A string description of this component's configuration.
abstract @property string configString();
/// Commit in the component's repo from which to build this component.
@property string commit() { return incrementalBuild ? "incremental" : getComponentCommit(name); }
/// The components the source code of which this component depends on.
/// Used for calculating the cache key.
@property abstract string[] sourceDependencies();
/// The components the state and configuration of which this component depends on.
/// Used for calculating the cache key.
@property abstract string[] dependencies();
/// This metadata is saved to a .json file,
/// and is also used to calculate the cache key.
struct Metadata
{
int cacheVersion;
string name;
string commit;
string configString;
string[] sourceDepCommits;
Metadata[] dependencyMetadata;
}
Metadata getMetadata() /// ditto
{
return Metadata(
cacheVersion,
name,
commit,
configString,
sourceDependencies.map!(
dependency => getComponent(dependency).commit
).array(),
dependencies.map!(
dependency => getComponent(dependency).getMetadata()
).array(),
);
}
void saveMetaData(string target)
{
std.file.write(buildPath(target, "digger-metadata.json"), getMetadata().toJson());
// Use a separate file to avoid double-encoding JSON
std.file.write(buildPath(target, "digger-config.json"), configString);
}
/// Calculates the cache key, which should be unique and immutable
/// for the same source, build parameters, and build algorithm.
string getBuildID()
{
auto configBlob = getMetadata().toJson() ~ configString;
return "%s-%s-%s".format(
name,
commit,
configBlob.getDigestString!MD5().toLower(),
);
}
@property string sourceDir() { submodule.needRepo(); return submodule.git.path; }
/// Directory to which built files are copied to.
/// This will then be atomically added to the cache.
protected string stageDir;
/// Prepare the source checkout for this component.
/// Usually needed by other components.
void needSource()
{
tempError++; scope(success) tempError--;
if (incrementalBuild)
return;
if (!submoduleName)
return;
foreach (component; getSubmoduleComponents(submoduleName))
component.haveBuild = false;
submodule.needHead(commit);
}
private bool haveBuild;
/// Build the component in-place, as needed,
/// without moving the built files anywhere.
void needBuild()
{
if (haveBuild) return;
scope(success) haveBuild = true;
log("needBuild: " ~ getBuildID());
needSource();
log("Building " ~ getBuildID());
if (submoduleName)
submodule.clean = false;
performBuild();
log(getBuildID() ~ " built OK!");
}
private bool haveInstalled;
/// Build and "install" the component to buildDir as necessary.
void needInstalled()
{
if (haveInstalled) return;
scope(success) haveInstalled = true;
auto buildID = getBuildID();
log("needInstalled: " ~ buildID);
needCacheEngine();
if (cacheEngine.haveEntry(buildID))
{
log("Cache hit!");
if (cacheEngine.listFiles(buildID).canFind(unbuildableMarker))
throw new Exception(buildID ~ " was cached as unbuildable");
}
else
{
log("Cache miss.");
auto tempDir = buildPath(config.local.workDir, "temp");
if (tempDir.exists)
tempDir.removeRecurse();
stageDir = buildPath(tempDir, buildID);
stageDir.mkdirRecurse();
bool failed = false;
tempError = 0;
// Save the results to cache, failed or not
void saveToCache()
{
// Use a separate function to work around
// "cannot put scope(success) statement inside scope(exit)"
tempError++; scope(success) tempError--;
// tempDir might be removed by a dependency's build failure.
if (!tempDir.exists)
log("Not caching %s dependency build failure.".format(name));
else
// Don't cache failed build results due to temporary/environment problems
if (failed && tempError > 0)
{
log("Not caching %s build failure due to temporary/environment error.".format(name));
rmdirRecurse(tempDir);
}
else
// Don't cache failed build results during delve
if (failed && !cacheFailures)
{
log("Not caching failed %s build.".format(name));
rmdirRecurse(tempDir);
}
else
if (cacheEngine.haveEntry(buildID))
{
// Can happen due to force==true
log("Already in cache.");
rmdirRecurse(tempDir);
}
else
{
log("Saving to cache.");
saveMetaData(stageDir);
cacheEngine.add(buildID, stageDir);
rmdirRecurse(tempDir);
}
}
scope (exit)
saveToCache();
// An incomplete build is useless, nuke the directory
// and create a new one just for the "unbuildable" marker.
scope (failure)
{
failed = true;
if (stageDir.exists)
{
rmdirRecurse(stageDir);
mkdir(stageDir);
buildPath(stageDir, unbuildableMarker).touch();
}
}
needBuild();
performStage();
}
install();
}
/// Build the component in-place, without moving the built files anywhere.
void performBuild() {}
/// Place resulting files to stageDir
void performStage() {}
/// Update the environment post-install, to allow
/// building components that depend on this one.
void updateEnv(ref Environment env) {}
/// Copy build results from cacheDir to buildDir
void install()
{
log("Installing " ~ getBuildID());
needCacheEngine().extract(getBuildID(), buildDir, de => !de.baseName.startsWith("digger-"));
}
/// Prepare the dependencies then run the component's tests.
void test()
{
log("Testing " ~ getBuildID());
needSource();
submodule.clean = false;
performTest();
log(getBuildID() ~ " tests OK!");
}
/// Run the component's tests.
void performTest() {}
protected final:
// Utility declarations for component implementations
@property string modelSuffix() { return config.build.components.common.model == "32" ? "" : config.build.components.common.model; }
version (Windows)
{
enum string makeFileName = "win32.mak";
@property string makeFileNameModel()
{
string model = config.build.components.common.model;
if (model == "32mscoff")
model = "64";
return "win"~model~".mak";
}
enum string binExt = ".exe";
}
else
{
enum string makeFileName = "posix.mak";
enum string makeFileNameModel = "posix.mak";
enum string binExt = "";
}
/// Returns the command for the make utility.
string[] getMake(in ref Environment env)
{
return [env.vars.get("MAKE", "make")];
}
/// Returns the path to the built dmd executable.
@property string dmd() { return buildPath(buildDir, "bin", "dmd" ~ binExt).absolutePath(); }
/// Escape a path for d_do_test's very "special" criteria.
/// Spaces must be escaped, but there must be no double-quote at the end.
private static string dDoTestEscape(string str)
{
return str.replaceAll(re!`\\([^\\ ]*? [^\\]*)(?=\\)`, `\"$1"`);
}
unittest
{
assert(dDoTestEscape(`C:\Foo boo bar\baz quuz\derp.exe`) == `C:\"Foo boo bar"\"baz quuz"\derp.exe`);
}
string[] getPlatformMakeVars(in ref Environment env)
{
string model = config.build.components.common.model;
string[] args;
args ~= "MODEL=" ~ model;
version (Windows)
if (model != "32")
{
args ~= "VCDIR=" ~ env.deps.vsDir.buildPath("VC").absolutePath();
args ~= "SDKDIR=" ~ env.deps.sdkDir.absolutePath();
args ~= "CC=" ~ '"' ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "cl.exe").absolutePath() ~ '"';
args ~= "LD=" ~ '"' ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "link.exe").absolutePath() ~ '"';
args ~= "AR=" ~ '"' ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "lib.exe").absolutePath() ~ '"';
}
return args;
}
@property string[] gnuMakeArgs()
{
string[] args;
if (config.local.makeJobs)
{
if (config.local.makeJobs == "auto")
{
import std.parallelism, std.conv;
args ~= "-j" ~ text(totalCPUs);
}
else
if (config.local.makeJobs == "unlimited")
args ~= "-j";
else
args ~= "-j" ~ config.local.makeJobs;
}
return args;
}
@property string[] dMakeArgs()
{
version (Windows)
return null; // On Windows, DigitalMars make is used for all makefiles except the dmd test suite
else
return gnuMakeArgs;
}
/// Older versions did not use the posix.mak/win32.mak convention.
static string findMakeFile(string dir, string fn)
{
version (OSX)
if (!dir.buildPath(fn).exists && dir.buildPath("osx.mak").exists)
return "osx.mak";
version (Posix)
if (!dir.buildPath(fn).exists && dir.buildPath("linux.mak").exists)
return "linux.mak";
return fn;
}
void needCC(ref Environment env, string model, string dmcVer = null)
{
version (Windows)
{
needDMC(env, dmcVer); // We need DMC even for 64-bit builds (for DM make)
if (model != "32")
needVC(env, model);
}
}
void run(in string[] args, in string[string] newEnv, string dir)
{
log("Running: " ~ escapeShellCommand(args));
// Apply user environment
auto env = applyEnv(newEnv, config.build.environment);
// Temporarily apply PATH from newEnv to our process,
// so process creation lookup can use it.
string oldPath = std.process.environment["PATH"];
scope (exit) std.process.environment["PATH"] = oldPath;
std.process.environment["PATH"] = env["PATH"];
log("PATH=" ~ env["PATH"]);
auto status = spawnProcess(args, env, std.process.Config.newEnv, dir).wait();
enforce(status == 0, "Command %s failed with status %d".format(args, status));
}
}
/// The dmd executable
final class DMD : Component
{
@property override string submoduleName () { return "dmd"; }
@property override string[] sourceDependencies() { return []; }
@property override string[] dependencies() { return []; }
struct Config
{
/// Whether to build a debug DMD.
/// Debug builds are faster to build,
/// but run slower.
@JSONOptional bool debugDMD = false;
/// Whether to build a release DMD.
/// Mutually exclusive with debugDMD.
@JSONOptional bool releaseDMD = false;
/// Model for building DMD itself (on Windows).
/// Can be used to build a 64-bit DMD, to avoid 4GB limit.
/// Currently only implemented on Windows, for DMD 2.072 or later.
@JSONOptional string dmdModel = CommonConfig.defaultModel;
/// How to build DMD versions written in D.
/// We can either download a pre-built binary DMD
/// package, or build an earlier version from source
/// (e.g. starting with the last C++-only version.)
struct Bootstrap
{
/// Whether to download a pre-built D version,
/// or build one from source. If set, then build
/// from source according to the value of ver,
@JSONOptional bool fromSource = false;
/// Version specification.
/// When building from source, syntax can be defined
/// by outer application (see parseSpec method);
/// By default, it is understood as a version number,
/// such as "v2.070.2", which also doubles as a tag name.
@JSONOptional string ver = null;
/// Build configuration for the compiler used for bootstrapping.
/// If not set, then use the same build configuration as for the
/// target build. Used when fromSource is set.
@JSONOptional DManager.Config.Build* build;
}
@JSONOptional Bootstrap bootstrap; /// ditto
/// Use Visual C++ to build DMD instead of DMC.
/// Currently, this is a hack, as msbuild will consult the system
/// registry and use the system-wide installation of Visual Studio.
/// Only relevant for older versions, as newer versions are written in D.
@JSONOptional bool useVC;
}
@property override string configString()
{
static struct FullConfig
{
Config config;
string[] makeArgs;
}
return FullConfig(
config.build.components.dmd,
config.build.components.common.makeArgs,
).toJson();
}
@property string vsConfiguration() { return config.build.components.dmd.debugDMD ? "Debug" : "Release"; }
@property string vsPlatform () { return config.build.components.common.model == "64" ? "x64" : "Win32"; }
override void performBuild()
{
// We need an older DMC for older DMD versions
string dmcVer = null;
auto idgen = buildPath(sourceDir, "src", "idgen.c");
if (idgen.exists && idgen.readText().indexOf(`{ "alignof" },`) >= 0)
dmcVer = "850";
auto env = baseEnvironment;
needCC(env, config.build.components.dmd.dmdModel, dmcVer); // Need VC too for VSINSTALLDIR
if (buildPath(sourceDir, "src", "idgen.d").exists)
{
// Required for bootstrapping.
needDMD(env);
// Go back to our commit.
needSource();
submodule.clean = false;
}
auto srcDir = buildPath(sourceDir, "src");
if (config.build.components.dmd.useVC) // Mostly obsolete, see useVC ddoc
{
version (Windows)
{
needVC(env, config.build.components.dmd.dmdModel);
env.vars["PATH"] = env.vars["PATH"] ~ pathSeparator ~ env.deps.hostDC.dirName;
auto solutionFile = `dmd_msc_vs10.sln`;
if (!exists(srcDir.buildPath(solutionFile)))
solutionFile = `vcbuild\dmd.sln`;
if (!exists(srcDir.buildPath(solutionFile)))
throw new Exception("Can't find Visual Studio solution file");
return run(["msbuild", "/p:Configuration=" ~ vsConfiguration, "/p:Platform=" ~ vsPlatform, solutionFile], env.vars, srcDir);
}
else
throw new Exception("Can only use Visual Studio on Windows");
}
version (Windows)
auto scRoot = env.deps.dmcDir.absolutePath();
string dmdMakeFileName = findMakeFile(srcDir, makeFileName);
string dmdMakeFullName = srcDir.buildPath(dmdMakeFileName);
string modelFlag = config.build.components.common.model;
if (dmdMakeFullName.readText().canFind("MODEL=-m32"))
modelFlag = "-m" ~ modelFlag;
version (Windows)
{
// A make argument is insufficient,
// because of recursive make invocations
auto m = dmdMakeFullName.readText();
m = m
.replace(`CC=\dm\bin\dmc`, `CC=dmc`)
.replace(`SCROOT=$D\dm`, `SCROOT=` ~ scRoot)
;
dmdMakeFullName.write(m);
}
else
{
auto m = dmdMakeFullName.readText();
m = m
// Fix hard-coded reference to gcc as linker
.replace(`gcc -m32 -lstdc++`, `g++ -m32 -lstdc++`)
.replace(`gcc $(MODEL) -lstdc++`, `g++ $(MODEL) -lstdc++`)
;
// Fix pthread linker error
version (linux)
m = m.replace(`-lpthread`, `-pthread`);
dmdMakeFullName.write(m);
}
submodule.saveFileState("src/" ~ dmdMakeFileName);
string[] extraArgs, targets;
version (Posix)
{
if (config.build.components.dmd.debugDMD)
extraArgs ~= "DEBUG=1";
if (config.build.components.dmd.releaseDMD)
extraArgs ~= "ENABLE_RELEASE=1";
}
else
{
if (config.build.components.dmd.debugDMD)
targets ~= [];
else
if (config.build.components.dmd.releaseDMD && dmdMakeFullName.readText().canFind("reldmd"))
targets ~= ["reldmd"];
else
targets ~= ["dmd"];
}
if (config.build.components.dmd.dmdModel != CommonConfig.defaultModel)
{
version (Windows)
{
dmdMakeFileName = "win64.mak";
dmdMakeFullName = srcDir.buildPath(dmdMakeFileName);
enforce(dmdMakeFullName.exists, "dmdModel not supported for this DMD version");
extraArgs ~= "DMODEL=-m" ~ config.build.components.dmd.dmdModel;
if (config.build.components.dmd.dmdModel == "32mscoff")
{
auto objFiles = dmdMakeFullName.readText().splitLines().filter!(line => line.startsWith("OBJ_MSVC="));
enforce(!objFiles.empty, "Can't find OBJ_MSVC in win64.mak");
extraArgs ~= "OBJ_MSVC=" ~ objFiles.front.findSplit("=")[2].split().filter!(obj => obj != "ldfpu.obj").join(" ");
}
}
else
throw new Exception("dmdModel is only supported on Windows");
}
// Avoid HOST_DC reading ~/dmd.conf
string hostDC = env.deps.hostDC;
version (Posix)
if (hostDC && needConfSwitch())
{
auto dcProxy = buildPath(config.local.workDir, "host-dc-proxy.sh");
std.file.write(dcProxy, escapeShellCommand(["exec", hostDC, "-conf=" ~ buildPath(dirName(hostDC), configFileName)]) ~ ` "$@"`);
setAttributes(dcProxy, octal!755);
hostDC = dcProxy;
}
run(getMake(env) ~ [
"-f", dmdMakeFileName,
"MODEL=" ~ modelFlag,
"HOST_DC=" ~ hostDC,
] ~ config.build.components.common.makeArgs ~ dMakeArgs ~ extraArgs ~ targets,
env.vars, srcDir
);
}
override void performStage()
{
if (config.build.components.dmd.useVC)
{
foreach (ext; [".exe", ".pdb"])
cp(
buildPath(sourceDir, "src", "vcbuild", vsPlatform, vsConfiguration, "dmd_msc" ~ ext),
buildPath(stageDir , "bin", "dmd" ~ ext),
);
}
else
{
cp(
buildPath(sourceDir, "src", "dmd" ~ binExt),
buildPath(stageDir , "bin", "dmd" ~ binExt),
);
}
version (Windows)
{
auto ini = q"EOS
[Environment]
LIB="%@P%\..\lib"
DFLAGS="-I%@P%\..\import"
DMC=__DMC__
LINKCMD=%DMC%\link.exe
[Environment64]
LIB="%@P%\..\lib"
DFLAGS=%DFLAGS% -L/OPT:NOICF
VSINSTALLDIR=__VS__\
VCINSTALLDIR=%VSINSTALLDIR%VC\
PATH=%PATH%;%VCINSTALLDIR%\bin\amd64