1 /** 2 * Code to manage a D checkout and its dependencies. 3 * 4 * License: 5 * This Source Code Form is subject to the terms of 6 * the Mozilla Public License, v. 2.0. If a copy of 7 * the MPL was not distributed with this file, You 8 * can obtain one at http://mozilla.org/MPL/2.0/. 9 * 10 * Authors: 11 * Vladimir Panteleev <ae@cy.md> 12 */ 13 14 module ae.sys.d.manager; 15 16 import std.algorithm; 17 import std.array; 18 import std.conv; 19 import std.datetime; 20 import std.exception; 21 import std.file; 22 import std.json : parseJSON; 23 import std.path; 24 import std.process : spawnProcess, wait, escapeShellCommand; 25 import std.range; 26 import std.regex; 27 import std.string; 28 import std.typecons; 29 30 import ae.net.github.rest; 31 import ae.sys.d.cache; 32 import ae.sys.d.repo; 33 import ae.sys.file; 34 import ae.sys.git; 35 import ae.utils.aa; 36 import ae.utils.array; 37 import ae.utils.digest; 38 import ae.utils.json; 39 import ae.utils.meta; 40 import ae.utils.regex; 41 42 private alias ensureDirExists = ae.sys.file.ensureDirExists; 43 44 version (Windows) private 45 { 46 import ae.sys.install.dmc; 47 import ae.sys.install.msys; 48 import ae.sys.install.vs; 49 50 import ae.sys.windows.misc; 51 52 extern(Windows) void SetErrorMode(int); 53 } 54 55 import ae.sys.install.dmd; 56 import ae.sys.install.git; 57 import ae.sys.install.kindlegen; 58 59 static import std.process; 60 61 /// Class which manages a D checkout and its dependencies. 62 class DManager : ICacheHost 63 { 64 // **************************** Configuration **************************** 65 66 /// DManager configuration. 67 struct Config 68 { 69 /// Build configuration 70 struct Build 71 { 72 /// Per-component build configuration. 73 struct Components 74 { 75 /// Explicitly enable or disable a component. 76 bool[string] enable; 77 78 /// Returns a list of all enabled components, whether 79 /// they're enabled explicitly or by default. 80 string[] getEnabledComponentNames() 81 { 82 foreach (componentName; enable.byKey) 83 enforce(allComponents.canFind(componentName), "Unknown component: " ~ componentName); 84 return allComponents 85 .filter!(componentName => 86 enable.get(componentName, defaultComponents.canFind(componentName))) 87 .array 88 .dup; 89 } 90 91 Component.CommonConfig common; /// Configuration which applies to all components. 92 DMD.Config dmd; /// Configuration for building the compiler. 93 Website.Config website; /// Configuration for building the website. 94 } 95 Components components; /// ditto 96 97 /// Additional environment variables. 98 /// Supports %VAR% expansion - see applyEnv. 99 string[string] environment; 100 101 /// Optional cache key. 102 /// Can be used to force a rebuild and bypass the cache for one build. 103 string cacheKey; 104 } 105 Build build; /// ditto 106 107 /// Machine-local configuration 108 /// These settings should not affect the build output. 109 struct Local 110 { 111 /// URL of D git repository hosting D components. 112 /// Defaults to (and must have the layout of) D.git: 113 /// https://github.com/CyberShadow/D-dot-git 114 string repoUrl = "https://bitbucket.org/cybershadow/d.git"; 115 116 /// Location for the checkout, temporary files, etc. 117 string workDir; 118 119 /// If present, passed to GNU make via -j parameter. 120 /// Can also be "auto" or "unlimited". 121 string makeJobs; 122 123 /// Don't get latest updates from GitHub. 124 bool offline; 125 126 /// How to cache built files. 127 string cache; 128 129 /// Maximum execution time, in seconds, of any single 130 /// command. 131 int timeout; 132 133 /// API token to access the GitHub REST API (optional). 134 string githubToken; 135 } 136 Local local; /// ditto 137 } 138 Config config; /// ditto 139 140 // Behavior options that generally depend on the host program. 141 142 /// Automatically re-clone the repository in case 143 /// "git reset --hard" fails. 144 bool autoClean; 145 146 /// Whether to verify working tree state 147 /// to make sure we don't clobber user changes 148 bool verifyWorkTree; 149 150 /// Whether we should cache failed builds. 151 bool cacheFailures = true; 152 153 /// Current build environment. 154 struct Environment 155 { 156 /// Configuration for software dependencies 157 struct Deps 158 { 159 string dmcDir; /// Where dmc.zip is unpacked. 160 string vsDir; /// Where Visual Studio is installed 161 string sdkDir; /// Where the Windows SDK is installed 162 string hostDC; /// Host D compiler (for DDMD bootstrapping) 163 } 164 Deps deps; /// ditto 165 166 /// Calculated local environment, incl. dependencies 167 string[string] vars; 168 } 169 170 /// Get a specific subdirectory of the work directory. 171 @property string subDir(string name)() { return buildPath(config.local.workDir, name); } 172 173 alias repoDir = subDir!"repo"; /// The git repository location. 174 alias buildDir = subDir!"build"; /// The build directory. 175 alias dlDir = subDir!"dl"; /// The directory for downloaded software. 176 alias tmpDir = subDir!"tmp"; /// Directory for $TMPDIR etc. 177 alias homeDir = subDir!"home"; /// Directory for $HOME. 178 alias binDir = subDir!"bin" ; /// For wrapper scripts. 179 alias githubDir = subDir!"github-cache";/// For the GitHub API cache. 180 181 /// This number increases with each incompatible change to cached data. 182 enum cacheVersion = 3; 183 184 /// Returns the path to cached data for the given cache engine 185 /// (as in `config.local.cache`). 186 string cacheEngineDir(string engineName) 187 { 188 // Keep compatibility with old cache paths 189 string engineDirName = 190 engineName.isOneOf("directory", "true") ? "cache" : 191 engineName.isOneOf("", "none", "false") ? "temp-cache" : 192 "cache-" ~ engineName; 193 return buildPath( 194 config.local.workDir, 195 engineDirName, 196 "v%d".format(cacheVersion), 197 ); 198 } 199 200 /// Executable file name suffix for the current platform. 201 version (Windows) 202 enum string binExt = ".exe"; 203 else 204 enum string binExt = ""; 205 206 /// DMD configuration file name for the current platform. 207 version (Windows) 208 enum configFileName = "sc.ini"; 209 else 210 enum configFileName = "dmd.conf"; 211 212 /// Do we need to explicitly specify a `-conf=` switch to DMD 213 /// This is true when there exists a configuration file in the home directory. 214 static bool needConfSwitch() { return exists(std.process.environment.get("HOME", null).buildPath(configFileName)); } 215 216 // **************************** Repositories ***************************** 217 218 /// Base class for a `DManager` Git repository. 219 class DManagerRepository : ManagedRepository 220 { 221 this() 222 { 223 this.offline = config.local.offline; 224 this.verify = this.outer.verifyWorkTree; 225 } /// 226 227 protected override void log(string s) { return this.outer.log(s); } 228 } 229 230 /// The meta-repository, which contains the sub-project submodules. 231 class MetaRepository : DManagerRepository 232 { 233 protected override Git getRepo() 234 { 235 needGit(); 236 237 if (!repoDir.exists) 238 { 239 log("Cloning initial repository..."); 240 atomic!_performClone(config.local.repoUrl, repoDir); 241 } 242 243 return Git(repoDir); 244 } 245 246 static void _performClone(string url, string target) 247 { 248 import ae.sys.cmd; 249 run(["git", "clone", url, target]); 250 } 251 252 protected override void performCheckout(string hash) 253 { 254 super.performCheckout(hash); 255 submodules = null; 256 } 257 258 protected string[string][string] submoduleCache; 259 260 /// Get submodule commit hashes at the given commit-ish. 261 string[string] getSubmoduleCommits(string head) 262 { 263 auto pcacheEntry = head in submoduleCache; 264 if (pcacheEntry) 265 return (*pcacheEntry).dup; 266 267 string[string] result; 268 foreach (line; git.query("ls-tree", head).splitLines()) 269 { 270 auto parts = line.split(); 271 if (parts.length == 4 && parts[1] == "commit") 272 result[parts[3]] = parts[2]; 273 } 274 assert(result.length, "No submodules found"); 275 submoduleCache[head] = result; 276 return result.dup; 277 } 278 279 /// Get the submodule state for all commits in the history. 280 /// Returns: result[commitHash][submoduleName] == submoduleCommitHash 281 string[string][string] getSubmoduleHistory(string[] refs) 282 { 283 auto marksFile = buildPath(config.local.workDir, "temp", "marks.txt"); 284 ensurePathExists(marksFile); 285 scope(exit) if (marksFile.exists) marksFile.remove(); 286 log("Running fast-export..."); 287 auto fastExportData = git.query([ 288 "fast-export", 289 "--full-tree", 290 "--no-data", 291 "--export-marks=" ~ marksFile.absolutePath, 292 ] ~ refs 293 ); 294 295 log("Parsing fast-export marks..."); 296 297 auto markLines = marksFile.readText.strip.splitLines; 298 auto marks = new string[markLines.length]; 299 foreach (line; markLines) 300 { 301 auto parts = line.split(' '); 302 auto markIndex = parts[0][1..$].to!int-1; 303 marks[markIndex] = parts[1]; 304 } 305 306 log("Parsing fast-export data..."); 307 308 string[string][string] result; 309 foreach (i, commitData; fastExportData.split("deleteall\n")[1..$]) 310 result[marks[i]] = commitData 311 .matchAll(re!(`^M 160000 ([0-9a-f]{40}) (\S+)$`, "m")) 312 .map!(m => tuple(m.captures[2], m.captures[1])) 313 .assocArray 314 ; 315 return result; 316 } 317 } 318 319 private MetaRepository metaRepo; /// ditto 320 321 MetaRepository getMetaRepo() 322 { 323 if (!metaRepo) 324 metaRepo = new MetaRepository; 325 return metaRepo; 326 } /// ditto 327 328 /// Sub-project repositories. 329 class SubmoduleRepository : DManagerRepository 330 { 331 string dir; /// Full path to the repository. 332 333 protected override Git getRepo() 334 { 335 getMetaRepo().git; // ensure meta-repository is cloned 336 auto git = Git(dir); 337 git.commandPrefix ~= ["-c", `url.https://.insteadOf=git://`]; 338 return git; 339 } 340 341 protected override void needHead(string hash) 342 { 343 if (!autoClean) 344 super.needHead(hash); 345 else 346 try 347 super.needHead(hash); 348 catch (RepositoryCleanException e) 349 { 350 log("Error during repository cleanup."); 351 352 log("Nuking %s...".format(dir)); 353 rmdirRecurse(dir); 354 355 auto name = baseName(dir); 356 auto gitDir = buildPath(dirName(dir), ".git", "modules", name); 357 log("Nuking %s...".format(gitDir)); 358 rmdirRecurse(gitDir); 359 360 log("Updating submodule..."); 361 getMetaRepo().git.run(["submodule", "update", name]); 362 363 reset(); 364 365 log("Trying again..."); 366 super.needHead(hash); 367 } 368 } 369 } 370 371 private SubmoduleRepository[string] submodules; /// ditto 372 373 ManagedRepository getSubmodule(string name) 374 { 375 assert(name, "This component is not associated with a submodule"); 376 if (name !in submodules) 377 { 378 enforce(name in getMetaRepo().getSubmoduleCommits(getMetaRepo().getRef("origin/master")), 379 "Unknown submodule: " ~ name); 380 381 auto path = buildPath(metaRepo.git.path, name); 382 auto gitPath = buildPath(path, ".git"); 383 384 if (!gitPath.exists) 385 { 386 log("Initializing and updating submodule %s...".format(name)); 387 getMetaRepo().git.run(["submodule", "update", "--init", name]); 388 } 389 390 submodules[name] = new SubmoduleRepository(); 391 submodules[name].dir = path; 392 } 393 394 return submodules[name]; 395 } /// ditto 396 397 // ***************************** Components ****************************** 398 399 /// Base class for a D component. 400 class Component 401 { 402 /// Name of this component, as registered in DManager.components AA. 403 string name; 404 405 /// Corresponding subproject repository name. 406 @property abstract string submoduleName(); 407 /// Corresponding subproject repository. 408 @property ManagedRepository submodule() { return getSubmodule(submoduleName); } 409 410 /// Configuration applicable to multiple (not all) components. 411 // Note: don't serialize this structure whole! 412 // Only serialize used fields. 413 struct CommonConfig 414 { 415 /// The default target model on this platform. 416 version (Windows) 417 enum defaultModel = "32"; 418 else 419 version (D_LP64) 420 enum defaultModel = "64"; 421 else 422 enum defaultModel = "32"; 423 424 /// Target comma-separated models ("32", "64", and on Windows, "32mscoff"). 425 /// Controls the models of the built Phobos and Druntime libraries. 426 string model = defaultModel; 427 428 @property string[] models() { return model.split(","); } /// Get/set `model` as list. 429 @property void models(string[] value) { this.model = value.join(","); } /// ditto 430 431 /// Additional make parameters, e.g. "HOST_CC=g++48" 432 string[] makeArgs; 433 434 /// Build debug versions of Druntime / Phobos. 435 bool debugLib; 436 } 437 438 /// A string description of this component's configuration. 439 abstract @property string configString(); 440 441 /// Commit in the component's repo from which to build this component. 442 @property string commit() { return incrementalBuild ? "incremental" : getComponentCommit(name); } 443 444 /// The components the source code of which this component depends on. 445 /// Used for calculating the cache key. 446 @property abstract string[] sourceDependencies(); 447 448 /// The components the state and configuration of which this component depends on. 449 /// Used for calculating the cache key. 450 @property abstract string[] dependencies(); 451 452 /// This metadata is saved to a .json file, 453 /// and is also used to calculate the cache key. 454 struct Metadata 455 { 456 int cacheVersion; /// 457 string name; /// 458 string commit; /// 459 string configString; /// 460 string[] sourceDepCommits; /// 461 Metadata[] dependencyMetadata; /// 462 @JSONOptional string cacheKey; /// 463 } 464 465 Metadata getMetadata() 466 { 467 return Metadata( 468 cacheVersion, 469 name, 470 commit, 471 configString, 472 sourceDependencies.map!( 473 dependency => getComponent(dependency).commit 474 ).array(), 475 dependencies.map!( 476 dependency => getComponent(dependency).getMetadata() 477 ).array(), 478 config.build.cacheKey, 479 ); 480 } /// ditto 481 482 void saveMetaData(string target) 483 { 484 std.file.write(buildPath(target, "digger-metadata.json"), getMetadata().toJson()); 485 // Use a separate file to avoid double-encoding JSON 486 std.file.write(buildPath(target, "digger-config.json"), configString); 487 } /// ditto 488 489 /// Calculates the cache key, which should be unique and immutable 490 /// for the same source, build parameters, and build algorithm. 491 string getBuildID() 492 { 493 auto configBlob = getMetadata().toJson() ~ configString; 494 return "%s-%s-%s".format( 495 name, 496 commit, 497 configBlob.getDigestString!MD5().toLower(), 498 ); 499 } 500 501 @property string sourceDir() { return submodule.git.path; } /// 502 503 /// Directory to which built files are copied to. 504 /// This will then be atomically added to the cache. 505 protected string stageDir; 506 507 /// Prepare the source checkout for this component. 508 /// Usually needed by other components. 509 void needSource(bool needClean = false) 510 { 511 tempError++; scope(success) tempError--; 512 513 if (incrementalBuild) 514 return; 515 if (!submoduleName) 516 return; 517 518 bool needHead; 519 if (needClean) 520 needHead = true; 521 else 522 { 523 // It's OK to run tests with a dirty worktree (i.e. after a build). 524 needHead = commit != submodule.getHead(); 525 } 526 527 if (needHead) 528 { 529 foreach (component; getSubmoduleComponents(submoduleName)) 530 component.haveBuild = false; 531 submodule.needHead(commit); 532 } 533 submodule.clean = false; 534 } 535 536 private bool haveBuild; 537 538 /// Build the component in-place, as needed, 539 /// without moving the built files anywhere. 540 void needBuild(bool clean = true) 541 { 542 if (haveBuild) return; 543 scope(success) haveBuild = true; 544 545 log("needBuild: " ~ getBuildID()); 546 547 needSource(clean); 548 549 prepareEnv(); 550 551 log("Building " ~ getBuildID()); 552 performBuild(); 553 log(getBuildID() ~ " built OK!"); 554 } 555 556 /// Set up / clean the build environment. 557 private void prepareEnv() 558 { 559 // Nuke any additional directories cloned by makefiles 560 if (!incrementalBuild) 561 { 562 getMetaRepo().git.run(["clean", "-ffdx"]); 563 564 foreach (dir; [tmpDir, homeDir]) 565 { 566 if (dir.exists && !dir.dirEntries(SpanMode.shallow).empty) 567 log("Clearing %s ...".format(dir)); 568 dir.recreateEmptyDirectory(); 569 } 570 } 571 572 // Set up compiler wrappers. 573 recreateEmptyDirectory(binDir); 574 version (linux) 575 { 576 foreach (cc; ["cc", "gcc", "c++", "g++"]) 577 { 578 auto fileName = binDir.buildPath(cc); 579 write(fileName, q"EOF 580 #!/bin/sh 581 set -eu 582 583 tool=$(basename "$0") 584 next=/usr/bin/$tool 585 tmpdir=${TMP:-/tmp} 586 flagfile=$tmpdir/nopie-flag-$tool 587 588 if [ ! -e "$flagfile" ] 589 then 590 echo 'Testing for -no-pie...' 1>&2 591 testfile=$tmpdir/test-$$.c 592 echo 'int main(){return 0;}' > $testfile 593 if $next -no-pie -c -o$testfile.o $testfile 594 then 595 printf "%s" "-no-pie" > "$flagfile".$$.tmp 596 mv "$flagfile".$$.tmp "$flagfile" 597 else 598 touch "$flagfile" 599 fi 600 rm -f "$testfile" "$testfile.o" 601 fi 602 603 exec "$next" $(cat "$flagfile") "$@" 604 EOF"); 605 setAttributes(fileName, octal!755); 606 } 607 } 608 } 609 610 private bool haveInstalled; 611 612 /// Build and "install" the component to buildDir as necessary. 613 void needInstalled() 614 { 615 if (haveInstalled) return; 616 scope(success) haveInstalled = true; 617 618 auto buildID = getBuildID(); 619 log("needInstalled: " ~ buildID); 620 621 needCacheEngine(); 622 if (cacheEngine.haveEntry(buildID)) 623 { 624 log("Cache hit!"); 625 if (cacheEngine.listFiles(buildID).canFind(unbuildableMarker)) 626 throw new Exception(buildID ~ " was cached as unbuildable"); 627 } 628 else 629 { 630 log("Cache miss."); 631 632 auto tempDir = buildPath(config.local.workDir, "temp"); 633 if (tempDir.exists) 634 tempDir.removeRecurse(); 635 stageDir = buildPath(tempDir, buildID); 636 stageDir.mkdirRecurse(); 637 638 bool failed = false; 639 tempError = 0; 640 641 // Save the results to cache, failed or not 642 void saveToCache() 643 { 644 // Use a separate function to work around 645 // "cannot put scope(success) statement inside scope(exit)" 646 647 int currentTempError = tempError; 648 649 // Treat cache errors an environmental errors 650 // (for when needInstalled is invoked to build a dependency) 651 tempError++; scope(success) tempError--; 652 653 // tempDir might be removed by a dependency's build failure. 654 if (!tempDir.exists) 655 log("Not caching %s dependency build failure.".format(name)); 656 else 657 // Don't cache failed build results due to temporary/environment problems 658 if (failed && currentTempError > 0) 659 { 660 log("Not caching %s build failure due to temporary/environment error.".format(name)); 661 rmdirRecurse(tempDir); 662 } 663 else 664 // Don't cache failed build results during delve 665 if (failed && !cacheFailures) 666 { 667 log("Not caching failed %s build.".format(name)); 668 rmdirRecurse(tempDir); 669 } 670 else 671 if (cacheEngine.haveEntry(buildID)) 672 { 673 // Can happen due to force==true 674 log("Already in cache."); 675 rmdirRecurse(tempDir); 676 } 677 else 678 { 679 log("Saving to cache."); 680 saveMetaData(stageDir); 681 cacheEngine.add(buildID, stageDir); 682 rmdirRecurse(tempDir); 683 } 684 } 685 686 scope (exit) 687 saveToCache(); 688 689 // An incomplete build is useless, nuke the directory 690 // and create a new one just for the "unbuildable" marker. 691 scope (failure) 692 { 693 failed = true; 694 if (stageDir.exists) 695 { 696 rmdirRecurse(stageDir); 697 mkdir(stageDir); 698 buildPath(stageDir, unbuildableMarker).touch(); 699 } 700 } 701 702 needBuild(); 703 704 performStage(); 705 } 706 707 install(); 708 } 709 710 /// Build the component in-place, without moving the built files anywhere. 711 void performBuild() {} 712 713 /// Place resulting files to stageDir 714 void performStage() {} 715 716 /// Update the environment post-install, to allow 717 /// building components that depend on this one. 718 void updateEnv(ref Environment env) {} 719 720 /// Copy build results from cacheDir to buildDir 721 void install() 722 { 723 log("Installing " ~ getBuildID()); 724 needCacheEngine().extract(getBuildID(), buildDir, de => !de.baseName.startsWith("digger-")); 725 } 726 727 /// Prepare the dependencies then run the component's tests. 728 void test() 729 { 730 log("Testing " ~ getBuildID()); 731 732 needSource(); 733 734 submodule.clean = false; 735 performTest(); 736 log(getBuildID() ~ " tests OK!"); 737 } 738 739 /// Run the component's tests. 740 void performTest() {} 741 742 protected final: 743 // Utility declarations for component implementations 744 745 string modelSuffix(string model) { return model == "32" ? "" : model; } 746 version (Windows) 747 { 748 enum string makeFileName = "win32.mak"; 749 string makeFileNameModel(string model) 750 { 751 if (model == "32mscoff") 752 model = "64"; 753 return "win"~model~".mak"; 754 } 755 enum string binExt = ".exe"; 756 } 757 else 758 { 759 enum string makeFileName = "posix.mak"; 760 string makeFileNameModel(string model) { return "posix.mak"; } 761 enum string binExt = ""; 762 } 763 764 version (Windows) 765 enum platform = "windows"; 766 else 767 version (linux) 768 enum platform = "linux"; 769 else 770 version (OSX) 771 enum platform = "osx"; 772 else 773 version (FreeBSD) 774 enum platform = "freebsd"; 775 else 776 static assert(false); 777 778 /// Returns the command for the make utility. 779 string[] getMake(ref const Environment env) 780 { 781 version (FreeBSD) 782 enum makeProgram = "gmake"; // GNU make 783 else 784 version (Posix) 785 enum makeProgram = "make"; // GNU make 786 else 787 enum makeProgram = "make"; // DigitalMars make 788 return [env.vars.get("MAKE", makeProgram)]; 789 } 790 791 /// Returns the path to the built dmd executable. 792 @property string dmd() { return buildPath(buildDir, "bin", "dmd" ~ binExt).absolutePath(); } 793 794 /// Escape a path for d_do_test's very "special" criteria. 795 /// Spaces must be escaped, but there must be no double-quote at the end. 796 private static string dDoTestEscape(string str) 797 { 798 return str.replaceAll(re!`\\([^\\ ]*? [^\\]*)(?=\\)`, `\"$1"`); 799 } 800 801 unittest 802 { 803 assert(dDoTestEscape(`C:\Foo boo bar\baz quuz\derp.exe`) == `C:\"Foo boo bar"\"baz quuz"\derp.exe`); 804 } 805 806 string[] getPlatformMakeVars(ref const Environment env, string model, bool quote = true) 807 { 808 string[] args; 809 810 args ~= "MODEL=" ~ model; 811 812 version (Windows) 813 if (model != "32") 814 { 815 args ~= "VCDIR=" ~ env.deps.vsDir.buildPath("VC").absolutePath(); 816 args ~= "SDKDIR=" ~ env.deps.sdkDir.absolutePath(); 817 818 // Work around https://github.com/dlang/druntime/pull/2438 819 auto quoteStr = quote ? `"` : ``; 820 args ~= "CC=" ~ quoteStr ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "cl.exe").absolutePath() ~ quoteStr; 821 args ~= "LD=" ~ quoteStr ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "link.exe").absolutePath() ~ quoteStr; 822 args ~= "AR=" ~ quoteStr ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "lib.exe").absolutePath() ~ quoteStr; 823 } 824 825 return args; 826 } 827 828 @property string[] gnuMakeArgs() 829 { 830 string[] args; 831 if (config.local.makeJobs) 832 { 833 if (config.local.makeJobs == "auto") 834 { 835 import std.parallelism, std.conv; 836 args ~= "-j" ~ text(totalCPUs); 837 } 838 else 839 if (config.local.makeJobs == "unlimited") 840 args ~= "-j"; 841 else 842 args ~= "-j" ~ config.local.makeJobs; 843 } 844 return args; 845 } 846 847 @property string[] dMakeArgs() 848 { 849 version (Windows) 850 return null; // On Windows, DigitalMars make is used for all makefiles except the dmd test suite 851 else 852 return gnuMakeArgs; 853 } 854 855 /// Older versions did not use the posix.mak/win32.mak convention. 856 static string findMakeFile(string dir, string fn) 857 { 858 version (OSX) 859 if (!dir.buildPath(fn).exists && dir.buildPath("osx.mak").exists) 860 return "osx.mak"; 861 version (Posix) 862 if (!dir.buildPath(fn).exists && dir.buildPath("linux.mak").exists) 863 return "linux.mak"; 864 return fn; 865 } 866 867 void needCC(ref Environment env, string model, string dmcVer = null) 868 { 869 version (Windows) 870 { 871 needDMC(env, dmcVer); // We need DMC even for 64-bit builds (for DM make) 872 if (model != "32") 873 needVC(env, model); 874 } 875 } 876 877 void run(const(string)[] args, in string[string] newEnv, string dir) 878 { 879 // Apply user environment 880 auto env = applyEnv(newEnv, config.build.environment); 881 882 // Temporarily apply PATH from newEnv to our process, 883 // so process creation lookup can use it. 884 string oldPath = std.process.environment["PATH"]; 885 scope (exit) std.process.environment["PATH"] = oldPath; 886 std.process.environment["PATH"] = env["PATH"]; 887 888 // Apply timeout setting 889 if (config.local.timeout) 890 args = ["timeout", config.local.timeout.text] ~ args; 891 892 foreach (name, value; env) 893 log("Environment: " ~ name ~ "=" ~ value); 894 log("Working directory: " ~ dir); 895 log("Running: " ~ escapeShellCommand(args)); 896 897 auto status = spawnProcess(args, env, std.process.Config.newEnv, dir).wait(); 898 enforce(status == 0, "Command %s failed with status %d".format(args, status)); 899 } 900 } 901 902 /// The dmd executable 903 final class DMD : Component 904 { 905 protected @property override string submoduleName () { return "dmd"; } 906 protected @property override string[] sourceDependencies() { return []; } 907 protected @property override string[] dependencies() { return []; } 908 909 /// DMD build configuration. 910 struct Config 911 { 912 /// Whether to build a debug DMD. 913 /// Debug builds are faster to build, 914 /// but run slower. 915 @JSONOptional bool debugDMD = false; 916 917 /// Whether to build a release DMD. 918 /// Mutually exclusive with debugDMD. 919 @JSONOptional bool releaseDMD = false; 920 921 /// Model for building DMD itself (on Windows). 922 /// Can be used to build a 64-bit DMD, to avoid 4GB limit. 923 @JSONOptional string dmdModel = CommonConfig.defaultModel; 924 925 /// How to build DMD versions written in D. 926 /// We can either download a pre-built binary DMD 927 /// package, or build an earlier version from source 928 /// (e.g. starting with the last C++-only version.) 929 struct Bootstrap 930 { 931 /// Whether to download a pre-built D version, 932 /// or build one from source. If set, then build 933 /// from source according to the value of ver, 934 @JSONOptional bool fromSource = false; 935 936 /// Version specification. 937 /// When building from source, syntax can be defined 938 /// by outer application (see parseSpec method); 939 /// When the bootstrapping compiler is not built from source, 940 /// it is understood as a version number, such as "v2.070.2", 941 /// which also doubles as a tag name. 942 /// By default (when set to null), an appropriate version 943 /// is selected automatically. 944 @JSONOptional string ver = null; 945 946 /// Build configuration for the compiler used for bootstrapping. 947 /// If not set, then use the default build configuration. 948 /// Used when fromSource is set. 949 @JSONOptional DManager.Config.Build* build; 950 } 951 @JSONOptional Bootstrap bootstrap; /// ditto 952 953 /// Use Visual C++ to build DMD instead of DMC. 954 /// Currently, this is a hack, as msbuild will consult the system 955 /// registry and use the system-wide installation of Visual Studio. 956 /// Only relevant for older versions, as newer versions are written in D. 957 @JSONOptional bool useVC; 958 } 959 960 protected @property override string configString() 961 { 962 static struct FullConfig 963 { 964 Config config; 965 string[] makeArgs; 966 967 // Include the common models as well as the DMD model (from config). 968 // Necessary to ensure the correct sc.ini is generated on Windows 969 // (we don't want to pull in MSVC unless either DMD or Phobos are 970 // built as 64-bit, but also we can't reuse a DMD build with 32-bit 971 // DMD and Phobos for a 64-bit Phobos build because it won't have 972 // the VC vars set up in its sc.ini). 973 // Possibly refactor the compiler configuration to a separate 974 // component in the future to avoid the inefficiency of rebuilding 975 // DMD just to generate a different sc.ini. 976 @JSONOptional string commonModel = Component.CommonConfig.defaultModel; 977 } 978 979 return FullConfig( 980 config.build.components.dmd, 981 config.build.components.common.makeArgs, 982 config.build.components.common.model, 983 ).toJson(); 984 } /// 985 986 /// Name of the Visual Studio build configuration to use. 987 @property string vsConfiguration() { return config.build.components.dmd.debugDMD ? "Debug" : "Release"; } 988 /// Name of the Visual Studio build platform to use. 989 @property string vsPlatform () { return config.build.components.dmd.dmdModel == "64" ? "x64" : "Win32"; } 990 991 protected override void performBuild() 992 { 993 // We need an older DMC for older DMD versions 994 string dmcVer = null; 995 auto idgen = buildPath(sourceDir, "src", "idgen.c"); 996 if (idgen.exists && idgen.readText().indexOf(`{ "alignof" },`) >= 0) 997 dmcVer = "850"; 998 999 auto env = baseEnvironment; 1000 needCC(env, config.build.components.dmd.dmdModel, dmcVer); // Need VC too for VSINSTALLDIR 1001 1002 auto srcDir = buildPath(sourceDir, "src"); 1003 string dmdMakeFileName = findMakeFile(srcDir, makeFileName); 1004 string dmdMakeFullName = srcDir.buildPath(dmdMakeFileName); 1005 1006 if (buildPath(sourceDir, "src", "idgen.d").exists || 1007 buildPath(sourceDir, "src", "ddmd", "idgen.d").exists || 1008 buildPath(sourceDir, "src", "ddmd", "mars.d").exists || 1009 buildPath(sourceDir, "src", "dmd", "mars.d").exists) 1010 { 1011 // Need an older DMD for bootstrapping. 1012 string dmdVer = "v2.067.1"; 1013 if (sourceDir.buildPath("test/compilable/staticforeach.d").exists) 1014 dmdVer = "v2.068.0"; 1015 version (Windows) 1016 if (config.build.components.dmd.dmdModel != Component.CommonConfig.defaultModel) 1017 dmdVer = "v2.070.2"; // dmd/src/builtin.d needs core.stdc.math.fabsl. 2.068.2 generates a dmd which crashes on building Phobos 1018 if (sourceDir.buildPath("src/dmd/backend/dvec.d").exists) // 2.079 is needed since 2.080 1019 dmdVer = "v2.079.0"; 1020 needDMD(env, dmdVer); 1021 1022 // Go back to our commit (in case we bootstrapped from source). 1023 needSource(true); 1024 submodule.clean = false; 1025 } 1026 1027 if (config.build.components.dmd.useVC) // Mostly obsolete, see useVC ddoc 1028 { 1029 version (Windows) 1030 { 1031 needVC(env, config.build.components.dmd.dmdModel); 1032 1033 env.vars["PATH"] = env.vars["PATH"] ~ pathSeparator ~ env.deps.hostDC.dirName; 1034 1035 auto solutionFile = `dmd_msc_vs10.sln`; 1036 if (!exists(srcDir.buildPath(solutionFile))) 1037 solutionFile = `vcbuild\dmd.sln`; 1038 if (!exists(srcDir.buildPath(solutionFile))) 1039 throw new Exception("Can't find Visual Studio solution file"); 1040 1041 return run(["msbuild", "/p:Configuration=" ~ vsConfiguration, "/p:Platform=" ~ vsPlatform, solutionFile], env.vars, srcDir); 1042 } 1043 else 1044 throw new Exception("Can only use Visual Studio on Windows"); 1045 } 1046 1047 version (Windows) 1048 auto scRoot = env.deps.dmcDir.absolutePath(); 1049 1050 string modelFlag = config.build.components.dmd.dmdModel; 1051 if (dmdMakeFullName.readText().canFind("MODEL=-m32")) 1052 modelFlag = "-m" ~ modelFlag; 1053 1054 version (Windows) 1055 { 1056 auto m = dmdMakeFullName.readText(); 1057 m = m 1058 // A make argument is insufficient, 1059 // because of recursive make invocations 1060 .replace(`CC=\dm\bin\dmc`, `CC=dmc`) 1061 .replace(`SCROOT=$D\dm`, `SCROOT=` ~ scRoot) 1062 // Debug crashes in build.d 1063 .replaceAll(re!(`^( \$\(HOST_DC\) .*) (build\.d)$`, "m"), "$1 -g $2") 1064 ; 1065 dmdMakeFullName.write(m); 1066 } 1067 else 1068 { 1069 auto m = dmdMakeFullName.readText(); 1070 m = m 1071 // Fix hard-coded reference to gcc as linker 1072 .replace(`gcc -m32 -lstdc++`, `g++ -m32 -lstdc++`) 1073 .replace(`gcc $(MODEL) -lstdc++`, `g++ $(MODEL) -lstdc++`) 1074 // Fix compilation of older versions of go.c with GCC 6 1075 .replace(`-Wno-deprecated`, `-Wno-deprecated -Wno-narrowing`) 1076 ; 1077 // Fix pthread linker error 1078 version (linux) 1079 m = m.replace(`-lpthread`, `-pthread`); 1080 dmdMakeFullName.write(m); 1081 } 1082 1083 submodule.saveFileState("src/" ~ dmdMakeFileName); 1084 1085 version (Windows) 1086 { 1087 auto buildDFileName = "build.d"; 1088 auto buildDPath = srcDir.buildPath(buildDFileName); 1089 if (buildDPath.exists) 1090 { 1091 auto buildD = buildDPath.readText(); 1092 buildD = buildD 1093 // https://github.com/dlang/dmd/pull/10491 1094 // Needs WBEM PATH entry, and also fails under Wine as its wmic outputs UTF-16. 1095 .replace(`["wmic", "OS", "get", "OSArchitecture"].execute.output`, isWin64 ? `"64-bit"` : `"32-bit"`) 1096 ; 1097 buildDPath.write(buildD); 1098 submodule.saveFileState("src/" ~ buildDFileName); 1099 } 1100 } 1101 1102 // Fix compilation error of older DMDs with glibc >= 2.25 1103 version (linux) 1104 {{ 1105 auto fn = srcDir.buildPath("root", "port.c"); 1106 if (fn.exists) 1107 { 1108 fn.write(fn.readText 1109 .replace(`#include <bits/mathdef.h>`, `#include <complex.h>`) 1110 .replace(`#include <bits/nan.h>`, `#include <math.h>`) 1111 ); 1112 submodule.saveFileState(fn.relativePath(sourceDir)); 1113 } 1114 }} 1115 1116 // Fix alignment issue in older DMDs with GCC >= 7 1117 // See https://issues.dlang.org/show_bug.cgi?id=17726 1118 version (Posix) 1119 { 1120 foreach (fn; [srcDir.buildPath("tk", "mem.c"), srcDir.buildPath("ddmd", "tk", "mem.c")]) 1121 if (fn.exists) 1122 { 1123 fn.write(fn.readText.replace( 1124 // `#if defined(__llvm__) && (defined(__GNUC__) || defined(__clang__))`, 1125 // `#if defined(__GNUC__) || defined(__clang__)`, 1126 `numbytes = (numbytes + 3) & ~3;`, 1127 `numbytes = (numbytes + 0xF) & ~0xF;` 1128 )); 1129 submodule.saveFileState(fn.relativePath(sourceDir)); 1130 } 1131 } 1132 1133 string[] extraArgs, targets; 1134 version (Posix) 1135 { 1136 if (config.build.components.dmd.debugDMD) 1137 extraArgs ~= "DEBUG=1"; 1138 if (config.build.components.dmd.releaseDMD) 1139 extraArgs ~= "ENABLE_RELEASE=1"; 1140 } 1141 else 1142 { 1143 if (config.build.components.dmd.debugDMD) 1144 targets ~= []; 1145 else 1146 if (config.build.components.dmd.releaseDMD && dmdMakeFullName.readText().canFind("reldmd")) 1147 targets ~= ["reldmd"]; 1148 else 1149 targets ~= ["dmd"]; 1150 } 1151 1152 version (Windows) 1153 { 1154 if (config.build.components.dmd.dmdModel != CommonConfig.defaultModel) 1155 { 1156 dmdMakeFileName = "win64.mak"; 1157 dmdMakeFullName = srcDir.buildPath(dmdMakeFileName); 1158 enforce(dmdMakeFullName.exists, "dmdModel not supported for this DMD version"); 1159 extraArgs ~= "DMODEL=-m" ~ config.build.components.dmd.dmdModel; 1160 if (config.build.components.dmd.dmdModel == "32mscoff") 1161 { 1162 auto objFiles = dmdMakeFullName.readText().splitLines().filter!(line => line.startsWith("OBJ_MSVC=")); 1163 enforce(!objFiles.empty, "Can't find OBJ_MSVC in win64.mak"); 1164 extraArgs ~= "OBJ_MSVC=" ~ objFiles.front.findSplit("=")[2].split().filter!(obj => obj != "ldfpu.obj").join(" "); 1165 } 1166 } 1167 } 1168 1169 // Avoid HOST_DC reading ~/dmd.conf 1170 string hostDC = env.deps.hostDC; 1171 version (Posix) 1172 if (hostDC && needConfSwitch()) 1173 { 1174 auto dcProxy = buildPath(config.local.workDir, "host-dc-proxy.sh"); 1175 std.file.write(dcProxy, escapeShellCommand(["exec", hostDC, "-conf=" ~ buildPath(dirName(hostDC), configFileName)]) ~ ` "$@"`); 1176 setAttributes(dcProxy, octal!755); 1177 hostDC = dcProxy; 1178 } 1179 1180 run(getMake(env) ~ [ 1181 "-f", dmdMakeFileName, 1182 "MODEL=" ~ modelFlag, 1183 "HOST_DC=" ~ hostDC, 1184 ] ~ config.build.components.common.makeArgs ~ dMakeArgs ~ extraArgs ~ targets, 1185 env.vars, srcDir 1186 ); 1187 } 1188 1189 protected override void performStage() 1190 { 1191 if (config.build.components.dmd.useVC) 1192 { 1193 foreach (ext; [".exe", ".pdb"]) 1194 cp( 1195 buildPath(sourceDir, "src", "vcbuild", vsPlatform, vsConfiguration, "dmd_msc" ~ ext), 1196 buildPath(stageDir , "bin", "dmd" ~ ext), 1197 ); 1198 } 1199 else 1200 { 1201 string dmdPath = buildPath(sourceDir, "generated", platform, "release", config.build.components.dmd.dmdModel, "dmd" ~ binExt); 1202 if (!dmdPath.exists) 1203 dmdPath = buildPath(sourceDir, "src", "dmd" ~ binExt); // legacy 1204 enforce(dmdPath.exists && dmdPath.isFile, "Can't find built DMD executable"); 1205 1206 cp( 1207 dmdPath, 1208 buildPath(stageDir , "bin", "dmd" ~ binExt), 1209 ); 1210 } 1211 1212 version (Windows) 1213 { 1214 auto env = baseEnvironment; 1215 needCC(env, config.build.components.dmd.dmdModel); 1216 foreach (model; config.build.components.common.models) 1217 needCC(env, model); 1218 1219 auto ini = q"EOS 1220 [Environment] 1221 LIB=%@P%\..\lib 1222 DFLAGS="-I%@P%\..\import" 1223 DMC=__DMC__ 1224 LINKCMD=%DMC%\link.exe 1225 EOS" 1226 .replace("__DMC__", env.deps.dmcDir.buildPath(`bin`).absolutePath()) 1227 ; 1228 1229 if (env.deps.vsDir && env.deps.sdkDir) 1230 { 1231 ini ~= q"EOS 1232 1233 [Environment64] 1234 LIB=%@P%\..\lib 1235 DFLAGS=%DFLAGS% -L/OPT:NOICF 1236 VSINSTALLDIR=__VS__\ 1237 VCINSTALLDIR=%VSINSTALLDIR%VC\ 1238 PATH=%PATH%;%VCINSTALLDIR%\bin\__MODELDIR__;%VCINSTALLDIR%\bin 1239 WindowsSdkDir=__SDK__ 1240 LINKCMD=%VCINSTALLDIR%\bin\__MODELDIR__\link.exe 1241 LIB=%LIB%;%VCINSTALLDIR%\lib\amd64 1242 LIB=%LIB%;%WindowsSdkDir%\Lib\x64 1243 1244 [Environment32mscoff] 1245 LIB=%@P%\..\lib 1246 DFLAGS=%DFLAGS% -L/OPT:NOICF 1247 VSINSTALLDIR=__VS__\ 1248 VCINSTALLDIR=%VSINSTALLDIR%VC\ 1249 PATH=%PATH%;%VCINSTALLDIR%\bin 1250 WindowsSdkDir=__SDK__ 1251 LINKCMD=%VCINSTALLDIR%\bin\link.exe 1252 LIB=%LIB%;%VCINSTALLDIR%\lib 1253 LIB=%LIB%;%WindowsSdkDir%\Lib 1254 EOS" 1255 .replace("__VS__" , env.deps.vsDir .absolutePath()) 1256 .replace("__SDK__" , env.deps.sdkDir.absolutePath()) 1257 .replace("__MODELDIR__", msvcModelDir("64")) 1258 ; 1259 } 1260 1261 buildPath(stageDir, "bin", configFileName).write(ini); 1262 } 1263 else version (OSX) 1264 { 1265 auto ini = q"EOS 1266 [Environment] 1267 DFLAGS="-I%@P%/../import" "-L-L%@P%/../lib" 1268 EOS"; 1269 buildPath(stageDir, "bin", configFileName).write(ini); 1270 } 1271 else version (linux) 1272 { 1273 auto ini = q"EOS 1274 [Environment32] 1275 DFLAGS="-I%@P%/../import" "-L-L%@P%/../lib" -L--export-dynamic 1276 1277 [Environment64] 1278 DFLAGS="-I%@P%/../import" "-L-L%@P%/../lib" -L--export-dynamic -fPIC 1279 EOS"; 1280 buildPath(stageDir, "bin", configFileName).write(ini); 1281 } 1282 else 1283 { 1284 auto ini = q"EOS 1285 [Environment] 1286 DFLAGS="-I%@P%/../import" "-L-L%@P%/../lib" -L--export-dynamic 1287 EOS"; 1288 buildPath(stageDir, "bin", configFileName).write(ini); 1289 } 1290 } 1291 1292 protected override void updateEnv(ref Environment env) 1293 { 1294 // Add the DMD we built for Phobos/Druntime/Tools 1295 env.vars["PATH"] = buildPath(buildDir, "bin").absolutePath() ~ pathSeparator ~ env.vars["PATH"]; 1296 } 1297 1298 protected override void performTest() 1299 { 1300 foreach (dep; ["dmd", "druntime", "phobos"]) 1301 getComponent(dep).needBuild(true); 1302 1303 foreach (model; config.build.components.common.models) 1304 { 1305 auto env = baseEnvironment; 1306 version (Windows) 1307 { 1308 // In this order so it uses the MSYS make 1309 needCC(env, model); 1310 needMSYS(env); 1311 1312 disableCrashDialog(); 1313 } 1314 1315 auto makeArgs = getMake(env) ~ config.build.components.common.makeArgs ~ getPlatformMakeVars(env, model) ~ gnuMakeArgs; 1316 version (Windows) 1317 { 1318 makeArgs ~= ["OS=win" ~ model[0..2], "SHELL=bash"]; 1319 if (model == "32") 1320 { 1321 auto extrasDir = needExtras(); 1322 // The autotester seems to pass this via environment. Why does that work there??? 1323 makeArgs ~= "LIB=" ~ extrasDir.buildPath("localextras-windows", "dmd2", "windows", "lib") ~ `;..\..\phobos`; 1324 } 1325 else 1326 { 1327 // Fix path for d_do_test and its special escaping (default is the system VS2010 install) 1328 // We can't use the same syntax in getPlatformMakeVars because win64.mak uses "CC=\$(CC32)"\"" 1329 auto cl = env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "cl.exe"); 1330 foreach (ref arg; makeArgs) 1331 if (arg.startsWith("CC=")) 1332 arg = "CC=" ~ dDoTestEscape(cl); 1333 } 1334 } 1335 1336 version (test) 1337 { 1338 // Only try a few tests during CI runs, to check for 1339 // platform integration and correct invocation. 1340 // For this purpose, the C++ ABI tests will do nicely. 1341 makeArgs ~= [ 1342 // "test_results/runnable/cppa.d.out", // https://github.com/dlang/dmd/pull/5686 1343 "test_results/runnable/cpp_abi_tests.d.out", 1344 "test_results/runnable/cabi1.d.out", 1345 ]; 1346 } 1347 1348 run(makeArgs, env.vars, sourceDir.buildPath("test")); 1349 } 1350 } 1351 } 1352 1353 /// Phobos import files. 1354 /// In older versions of D, Druntime depended on Phobos modules. 1355 final class PhobosIncludes : Component 1356 { 1357 protected @property override string submoduleName() { return "phobos"; } 1358 protected @property override string[] sourceDependencies() { return []; } 1359 protected @property override string[] dependencies() { return []; } 1360 protected @property override string configString() { return null; } 1361 1362 protected override void performStage() 1363 { 1364 foreach (f; ["std", "etc", "crc32.d"]) 1365 if (buildPath(sourceDir, f).exists) 1366 cp( 1367 buildPath(sourceDir, f), 1368 buildPath(stageDir , "import", f), 1369 ); 1370 } 1371 } 1372 1373 /// Druntime. Installs only import files, but builds the library too. 1374 final class Druntime : Component 1375 { 1376 protected @property override string submoduleName () { return "druntime"; } 1377 protected @property override string[] sourceDependencies() { return ["phobos", "phobos-includes"]; } 1378 protected @property override string[] dependencies() { return ["dmd"]; } 1379 1380 protected @property override string configString() 1381 { 1382 static struct FullConfig 1383 { 1384 string model; 1385 string[] makeArgs; 1386 } 1387 1388 return FullConfig( 1389 config.build.components.common.model, 1390 config.build.components.common.makeArgs, 1391 ).toJson(); 1392 } 1393 1394 protected override void performBuild() 1395 { 1396 foreach (model; config.build.components.common.models) 1397 { 1398 auto env = baseEnvironment; 1399 needCC(env, model); 1400 1401 if (needHostDMD) 1402 { 1403 enum dmdVer = "v2.079.0"; // Same as latest version in DMD.performBuild 1404 needDMD(env, dmdVer); 1405 } 1406 1407 getComponent("phobos").needSource(); 1408 getComponent("dmd").needSource(); 1409 getComponent("dmd").needInstalled(); 1410 getComponent("phobos-includes").needInstalled(); 1411 1412 mkdirRecurse(sourceDir.buildPath("import")); 1413 mkdirRecurse(sourceDir.buildPath("lib")); 1414 1415 setTimes(sourceDir.buildPath("src", "rt", "minit.obj"), Clock.currTime(), Clock.currTime()); // Don't rebuild 1416 submodule.saveFileState("src/rt/minit.obj"); 1417 1418 runMake(env, model, "import"); 1419 runMake(env, model); 1420 } 1421 } 1422 1423 protected override void performStage() 1424 { 1425 cp( 1426 buildPath(sourceDir, "import"), 1427 buildPath(stageDir , "import"), 1428 ); 1429 } 1430 1431 protected override void performTest() 1432 { 1433 getComponent("druntime").needBuild(true); 1434 getComponent("dmd").needInstalled(); 1435 1436 foreach (model; config.build.components.common.models) 1437 { 1438 auto env = baseEnvironment; 1439 needCC(env, model); 1440 runMake(env, model, "unittest"); 1441 } 1442 } 1443 1444 private bool needHostDMD() 1445 { 1446 version (Windows) 1447 return sourceDir.buildPath("mak", "copyimports.d").exists; 1448 else 1449 return false; 1450 } 1451 1452 private final void runMake(ref Environment env, string model, string target = null) 1453 { 1454 // Work around https://github.com/dlang/druntime/pull/2438 1455 bool quotePaths = !(isVersion!"Windows" && model != "32" && sourceDir.buildPath("win64.mak").readText().canFind(`"$(CC)"`)); 1456 1457 string[] args = 1458 getMake(env) ~ 1459 ["-f", makeFileNameModel(model)] ~ 1460 (target ? [target] : []) ~ 1461 ["DMD=" ~ dmd] ~ 1462 (needHostDMD ? ["HOST_DMD=" ~ env.deps.hostDC] : []) ~ 1463 (config.build.components.common.debugLib ? ["BUILD=debug"] : []) ~ 1464 config.build.components.common.makeArgs ~ 1465 getPlatformMakeVars(env, model, quotePaths) ~ 1466 dMakeArgs; 1467 run(args, env.vars, sourceDir); 1468 } 1469 } 1470 1471 /// Phobos library and imports. 1472 final class Phobos : Component 1473 { 1474 protected @property override string submoduleName () { return "phobos"; } 1475 protected @property override string[] sourceDependencies() { return []; } 1476 protected @property override string[] dependencies() { return ["druntime", "dmd"]; } 1477 1478 protected @property override string configString() 1479 { 1480 static struct FullConfig 1481 { 1482 string model; 1483 string[] makeArgs; 1484 } 1485 1486 return FullConfig( 1487 config.build.components.common.model, 1488 config.build.components.common.makeArgs, 1489 ).toJson(); 1490 } 1491 1492 private string[] targets; 1493 1494 protected override void performBuild() 1495 { 1496 getComponent("dmd").needSource(); 1497 getComponent("dmd").needInstalled(); 1498 getComponent("druntime").needBuild(); 1499 1500 targets = null; 1501 1502 foreach (model; config.build.components.common.models) 1503 { 1504 // Clean up old object files with mismatching model. 1505 // Necessary for a consecutive 32/64 build. 1506 version (Windows) 1507 { 1508 foreach (de; dirEntries(sourceDir.buildPath("etc", "c", "zlib"), "*.obj", SpanMode.shallow)) 1509 { 1510 auto data = cast(ubyte[])read(de.name); 1511 1512 string fileModel; 1513 if (data.length < 4) 1514 fileModel = "invalid"; 1515 else 1516 if (data[0] == 0x80) 1517 fileModel = "32"; // OMF 1518 else 1519 if (data[0] == 0x01 && data[0] == 0x4C) 1520 fileModel = "32mscoff"; // COFF - IMAGE_FILE_MACHINE_I386 1521 else 1522 if (data[0] == 0x86 && data[0] == 0x64) 1523 fileModel = "64"; // COFF - IMAGE_FILE_MACHINE_AMD64 1524 else 1525 fileModel = "unknown"; 1526 1527 if (fileModel != model) 1528 { 1529 log("Cleaning up object file '%s' with mismatching model (file is %s, building %s)".format(de.name, fileModel, model)); 1530 remove(de.name); 1531 } 1532 } 1533 } 1534 1535 auto env = baseEnvironment; 1536 needCC(env, model); 1537 1538 string phobosMakeFileName = findMakeFile(sourceDir, makeFileNameModel(model)); 1539 string phobosMakeFullName = sourceDir.buildPath(phobosMakeFileName); 1540 1541 version (Windows) 1542 { 1543 auto lib = "phobos%s.lib".format(modelSuffix(model)); 1544 runMake(env, model, lib); 1545 enforce(sourceDir.buildPath(lib).exists); 1546 targets ~= ["phobos%s.lib".format(modelSuffix(model))]; 1547 } 1548 else 1549 { 1550 string[] makeArgs; 1551 if (phobosMakeFullName.readText().canFind("DRUNTIME = $(DRUNTIME_PATH)/lib/libdruntime-$(OS)$(MODEL).a") && 1552 getComponent("druntime").sourceDir.buildPath("lib").dirEntries(SpanMode.shallow).walkLength == 0 && 1553 exists(getComponent("druntime").sourceDir.buildPath("generated"))) 1554 { 1555 auto dir = getComponent("druntime").sourceDir.buildPath("generated"); 1556 auto aFile = dir.dirEntries("libdruntime.a", SpanMode.depth); 1557 if (!aFile .empty) makeArgs ~= ["DRUNTIME=" ~ aFile .front]; 1558 auto soFile = dir.dirEntries("libdruntime.so.a", SpanMode.depth); 1559 if (!soFile.empty) makeArgs ~= ["DRUNTIMESO=" ~ soFile.front]; 1560 } 1561 runMake(env, model, makeArgs); 1562 targets ~= sourceDir 1563 .buildPath("generated") 1564 .dirEntries(SpanMode.depth) 1565 .filter!(de => de.name.endsWith(".a") || de.name.endsWith(".so")) 1566 .map!(de => de.name.relativePath(sourceDir)) 1567 .array() 1568 ; 1569 } 1570 } 1571 } 1572 1573 protected override void performStage() 1574 { 1575 assert(targets.length, "Phobos stage without build"); 1576 foreach (lib; targets) 1577 cp( 1578 buildPath(sourceDir, lib), 1579 buildPath(stageDir , "lib", lib.baseName()), 1580 ); 1581 } 1582 1583 protected override void performTest() 1584 { 1585 getComponent("druntime").needBuild(true); 1586 getComponent("phobos").needBuild(true); 1587 getComponent("dmd").needInstalled(); 1588 1589 foreach (model; config.build.components.common.models) 1590 { 1591 auto env = baseEnvironment; 1592 needCC(env, model); 1593 version (Windows) 1594 { 1595 getComponent("curl").needInstalled(); 1596 getComponent("curl").updateEnv(env); 1597 1598 // Patch out std.datetime unittest to work around Digger test 1599 // suite failure on AppVeyor due to Windows time zone changes 1600 auto stdDateTime = buildPath(sourceDir, "std", "datetime.d"); 1601 if (stdDateTime.exists && !stdDateTime.readText().canFind("Altai Standard Time")) 1602 { 1603 auto m = stdDateTime.readText(); 1604 m = m 1605 .replace(`assert(tzName !is null, format("TZName which is missing: %s", winName));`, ``) 1606 .replace(`assert(tzDatabaseNameToWindowsTZName(tzName) !is null, format("TZName which failed: %s", tzName));`, `{}`) 1607 .replace(`assert(windowsTZNameToTZDatabaseName(tzName) !is null, format("TZName which failed: %s", tzName));`, `{}`) 1608 ; 1609 stdDateTime.write(m); 1610 submodule.saveFileState("std/datetime.d"); 1611 } 1612 1613 if (model == "32") 1614 getComponent("extras").needInstalled(); 1615 } 1616 runMake(env, model, "unittest"); 1617 } 1618 } 1619 1620 private final void runMake(ref Environment env, string model, string[] makeArgs...) 1621 { 1622 // Work around https://github.com/dlang/druntime/pull/2438 1623 bool quotePaths = !(isVersion!"Windows" && model != "32" && sourceDir.buildPath("win64.mak").readText().canFind(`"$(CC)"`)); 1624 1625 string[] args = 1626 getMake(env) ~ 1627 ["-f", makeFileNameModel(model)] ~ 1628 makeArgs ~ 1629 ["DMD=" ~ dmd] ~ 1630 config.build.components.common.makeArgs ~ 1631 (config.build.components.common.debugLib ? ["BUILD=debug"] : []) ~ 1632 getPlatformMakeVars(env, model, quotePaths) ~ 1633 dMakeArgs; 1634 run(args, env.vars, sourceDir); 1635 } 1636 } 1637 1638 /// The rdmd build tool by itself. 1639 /// It predates the tools package. 1640 final class RDMD : Component 1641 { 1642 protected @property override string submoduleName() { return "tools"; } 1643 protected @property override string[] sourceDependencies() { return []; } 1644 protected @property override string[] dependencies() { return ["dmd", "druntime", "phobos"]; } 1645 1646 private @property string model() { return config.build.components.common.models.get(0); } 1647 1648 protected @property override string configString() 1649 { 1650 static struct FullConfig 1651 { 1652 string model; 1653 } 1654 1655 return FullConfig( 1656 this.model, 1657 ).toJson(); 1658 } 1659 1660 protected override void performBuild() 1661 { 1662 foreach (dep; ["dmd", "druntime", "phobos", "phobos-includes"]) 1663 getComponent(dep).needInstalled(); 1664 1665 auto env = baseEnvironment; 1666 needCC(env, this.model); 1667 1668 // Just build rdmd 1669 bool needModel; // Need -mXX switch? 1670 1671 if (sourceDir.buildPath("posix.mak").exists) 1672 needModel = true; // Known to be needed for recent versions 1673 1674 string[] args; 1675 if (needConfSwitch()) 1676 args ~= ["-conf=" ~ buildPath(buildDir , "bin", configFileName)]; 1677 args ~= ["rdmd"]; 1678 1679 if (!needModel) 1680 try 1681 run([dmd] ~ args, env.vars, sourceDir); 1682 catch (Exception e) 1683 needModel = true; 1684 1685 if (needModel) 1686 run([dmd, "-m" ~ this.model] ~ args, env.vars, sourceDir); 1687 } 1688 1689 protected override void performStage() 1690 { 1691 cp( 1692 buildPath(sourceDir, "rdmd" ~ binExt), 1693 buildPath(stageDir , "bin", "rdmd" ~ binExt), 1694 ); 1695 } 1696 1697 protected override void performTest() 1698 { 1699 auto env = baseEnvironment; 1700 version (Windows) 1701 needDMC(env); // Need DigitalMars Make 1702 1703 string[] args; 1704 if (sourceDir.buildPath(makeFileName).readText.canFind("\ntest_rdmd")) 1705 args = getMake(env) ~ ["-f", makeFileName, "test_rdmd", "DFLAGS=-g -m" ~ model] ~ config.build.components.common.makeArgs ~ getPlatformMakeVars(env, model) ~ dMakeArgs; 1706 else 1707 { 1708 // Legacy (before makefile rules) 1709 1710 args = ["dmd", "-m" ~ this.model, "-run", "rdmd_test.d"]; 1711 if (sourceDir.buildPath("rdmd_test.d").readText.canFind("modelSwitch")) 1712 args ~= "--model=" ~ this.model; 1713 else 1714 { 1715 version (Windows) 1716 if (this.model != "32") 1717 { 1718 // Can't test rdmd on non-32-bit Windows until compiler model matches Phobos model. 1719 // rdmd_test does not use -m when building rdmd, thus linking will fail 1720 // (because of model mismatch with the phobos we built). 1721 log("Can't test rdmd with model " ~ this.model ~ ", skipping"); 1722 return; 1723 } 1724 } 1725 } 1726 1727 foreach (dep; ["dmd", "druntime", "phobos", "phobos-includes"]) 1728 getComponent(dep).needInstalled(); 1729 1730 getComponent("dmd").updateEnv(env); 1731 run(args, env.vars, sourceDir); 1732 } 1733 } 1734 1735 /// Tools package with all its components, including rdmd. 1736 final class Tools : Component 1737 { 1738 protected @property override string submoduleName() { return "tools"; } 1739 protected @property override string[] sourceDependencies() { return []; } 1740 protected @property override string[] dependencies() { return ["dmd", "druntime", "phobos"]; } 1741 1742 private @property string model() { return config.build.components.common.models.get(0); } 1743 1744 protected @property override string configString() 1745 { 1746 static struct FullConfig 1747 { 1748 string model; 1749 string[] makeArgs; 1750 } 1751 1752 return FullConfig( 1753 this.model, 1754 config.build.components.common.makeArgs, 1755 ).toJson(); 1756 } 1757 1758 protected override void performBuild() 1759 { 1760 getComponent("dmd").needSource(); 1761 foreach (dep; ["dmd", "druntime", "phobos"]) 1762 getComponent(dep).needInstalled(); 1763 1764 auto env = baseEnvironment; 1765 needCC(env, this.model); 1766 1767 run(getMake(env) ~ ["-f", makeFileName, "DMD=" ~ dmd] ~ config.build.components.common.makeArgs ~ getPlatformMakeVars(env, this.model) ~ dMakeArgs, env.vars, sourceDir); 1768 } 1769 1770 protected override void performStage() 1771 { 1772 foreach (os; buildPath(sourceDir, "generated").dirEntries(SpanMode.shallow)) 1773 foreach (de; os.buildPath(this.model).dirEntries(SpanMode.shallow)) 1774 if (de.extension == binExt) 1775 cp(de, buildPath(stageDir, "bin", de.baseName)); 1776 } 1777 } 1778 1779 /// Website (dlang.org). Only buildable on POSIX. 1780 final class Website : Component 1781 { 1782 protected @property override string submoduleName() { return "dlang.org"; } 1783 protected @property override string[] sourceDependencies() { return ["druntime", "phobos", "dub"]; } 1784 protected @property override string[] dependencies() { return ["dmd", "druntime", "phobos", "rdmd"]; } 1785 1786 /// Website build configuration. 1787 struct Config 1788 { 1789 /// Do not include timestamps, line numbers, or other 1790 /// volatile dynamic content in generated .ddoc files. 1791 /// Improves cache efficiency and allows meaningful diffs. 1792 bool diffable = false; 1793 1794 deprecated alias noDateTime = diffable; 1795 } 1796 1797 protected @property override string configString() 1798 { 1799 static struct FullConfig 1800 { 1801 Config config; 1802 } 1803 1804 return FullConfig( 1805 config.build.components.website, 1806 ).toJson(); 1807 } 1808 1809 /// Get the latest version of DMD at the time. 1810 /// Needed for the makefile's "LATEST" parameter. 1811 string getLatest() 1812 { 1813 auto dmd = getComponent("dmd").submodule; 1814 1815 auto t = dmd.git.query(["log", "--pretty=format:%ct"]).splitLines.map!(to!int).filter!(n => n > 0).front; 1816 1817 foreach (line; dmd.git.query(["log", "--decorate=full", "--tags", "--pretty=format:%ct%d"]).splitLines()) 1818 if (line.length > 10 && line[0..10].to!int < t) 1819 if (line[10..$].startsWith(" (") && line.endsWith(")")) 1820 { 1821 foreach (r; line[12..$-1].split(", ")) 1822 if (r.skipOver("tag: refs/tags/")) 1823 if (r.match(re!`^v2\.\d\d\d(\.\d)?$`)) 1824 return r[1..$]; 1825 } 1826 throw new Exception("Can't find any DMD version tags at this point!"); 1827 } 1828 1829 private enum Target { build, test } 1830 1831 private void make(Target target) 1832 { 1833 foreach (dep; ["dmd", "druntime", "phobos"]) 1834 { 1835 auto c = getComponent(dep); 1836 c.needInstalled(); 1837 1838 // Need DMD source because https://github.com/dlang/phobos/pull/4613#issuecomment-266462596 1839 // Need Druntime/Phobos source because we are building its documentation from there. 1840 c.needSource(); 1841 } 1842 foreach (dep; ["tools", "dub"]) // for changelog; also tools for changed.d 1843 getComponent(dep).needSource(); 1844 1845 auto env = baseEnvironment; 1846 1847 version (Windows) 1848 throw new Exception("The dlang.org website is only buildable on POSIX platforms."); 1849 else 1850 { 1851 getComponent("dmd").updateEnv(env); 1852 1853 // Need an in-tree build for SYSCONFDIR.imp, which is 1854 // needed to parse .d files for the DMD API 1855 // documentation. 1856 getComponent("dmd").needBuild(target == Target.test); 1857 1858 needKindleGen(env); 1859 1860 foreach (dep; dependencies) 1861 getComponent(dep).submodule.clean = false; 1862 1863 auto makeFullName = sourceDir.buildPath(makeFileName); 1864 auto makeSrc = makeFullName.readText(); 1865 makeSrc 1866 // https://github.com/D-Programming-Language/dlang.org/pull/1011 1867 .replace(": modlist.d", ": modlist.d $(DMD)") 1868 // https://github.com/D-Programming-Language/dlang.org/pull/1017 1869 .replace("dpl-docs: ${DUB} ${STABLE_DMD}\n\tDFLAGS=", "dpl-docs: ${DUB} ${STABLE_DMD}\n\t${DUB} upgrade --missing-only --root=${DPL_DOCS_PATH}\n\tDFLAGS=") 1870 .toFile(makeFullName) 1871 ; 1872 submodule.saveFileState(makeFileName); 1873 1874 // Retroactive OpenSSL 1.1.0 fix 1875 // See https://github.com/dlang/dlang.org/pull/1654 1876 auto dubJson = sourceDir.buildPath("dpl-docs/dub.json"); 1877 dubJson 1878 .readText() 1879 .replace(`"versions": ["VibeCustomMain"]`, `"versions": ["VibeCustomMain", "VibeNoSSL"]`) 1880 .toFile(dubJson); 1881 submodule.saveFileState("dpl-docs/dub.json"); 1882 scope(exit) submodule.saveFileState("dpl-docs/dub.selections.json"); 1883 1884 string latest = null; 1885 if (!sourceDir.buildPath("VERSION").exists) 1886 { 1887 latest = getLatest(); 1888 log("LATEST=" ~ latest); 1889 } 1890 else 1891 log("VERSION file found, not passing LATEST parameter"); 1892 1893 string[] diffable = null; 1894 1895 auto pdf = makeSrc.indexOf("pdf") >= 0 ? ["pdf"] : []; 1896 1897 string[] targets = 1898 [ 1899 config.build.components.website.diffable 1900 ? makeSrc.indexOf("dautotest") >= 0 1901 ? ["dautotest"] 1902 : ["all", "verbatim"] ~ pdf ~ ( 1903 makeSrc.indexOf("diffable-intermediaries") >= 0 1904 ? ["diffable-intermediaries"] 1905 : ["dlangspec.html"]) 1906 : ["all", "verbatim", "kindle"] ~ pdf, 1907 ["test"] 1908 ][target]; 1909 1910 if (config.build.components.website.diffable) 1911 { 1912 if (makeSrc.indexOf("DIFFABLE") >= 0) 1913 diffable = ["DIFFABLE=1"]; 1914 else 1915 diffable = ["NODATETIME=nodatetime.ddoc"]; 1916 1917 env.vars["SOURCE_DATE_EPOCH"] = "0"; 1918 } 1919 1920 auto args = 1921 getMake(env) ~ 1922 [ "-f", makeFileName ] ~ 1923 diffable ~ 1924 (latest ? ["LATEST=" ~ latest] : []) ~ 1925 targets ~ 1926 gnuMakeArgs; 1927 run(args, env.vars, sourceDir); 1928 } 1929 } 1930 1931 protected override void performBuild() 1932 { 1933 make(Target.build); 1934 } 1935 1936 protected override void performTest() 1937 { 1938 make(Target.test); 1939 } 1940 1941 protected override void performStage() 1942 { 1943 foreach (item; ["web", "dlangspec.tex", "dlangspec.html"]) 1944 { 1945 auto src = buildPath(sourceDir, item); 1946 auto dst = buildPath(stageDir , item); 1947 if (src.exists) 1948 cp(src, dst); 1949 } 1950 } 1951 } 1952 1953 /// Extras not built from source (DigitalMars and third-party tools and libraries) 1954 final class Extras : Component 1955 { 1956 protected @property override string submoduleName() { return null; } 1957 protected @property override string[] sourceDependencies() { return []; } 1958 protected @property override string[] dependencies() { return []; } 1959 protected @property override string configString() { return null; } 1960 1961 protected override void performBuild() 1962 { 1963 needExtras(); 1964 } 1965 1966 protected override void performStage() 1967 { 1968 auto extrasDir = needExtras(); 1969 1970 void copyDir(string source, string target) 1971 { 1972 source = buildPath(extrasDir, "localextras-" ~ platform, "dmd2", platform, source); 1973 target = buildPath(stageDir, target); 1974 if (source.exists) 1975 cp(source, target); 1976 } 1977 1978 copyDir("bin", "bin"); 1979 foreach (model; config.build.components.common.models) 1980 copyDir("bin" ~ model, "bin"); 1981 copyDir("lib", "lib"); 1982 1983 version (Windows) 1984 foreach (model; config.build.components.common.models) 1985 if (model == "32") 1986 { 1987 // The version of snn.lib bundled with DMC will be newer. 1988 Environment env; 1989 needDMC(env); 1990 cp(buildPath(env.deps.dmcDir, "lib", "snn.lib"), buildPath(stageDir, "lib", "snn.lib")); 1991 } 1992 } 1993 } 1994 1995 /// libcurl DLL and import library for Windows. 1996 final class Curl : Component 1997 { 1998 protected @property override string submoduleName() { return null; } 1999 protected @property override string[] sourceDependencies() { return []; } 2000 protected @property override string[] dependencies() { return []; } 2001 protected @property override string configString() { return null; } 2002 2003 protected override void performBuild() 2004 { 2005 version (Windows) 2006 needCurl(); 2007 else 2008 log("Not on Windows, skipping libcurl download"); 2009 } 2010 2011 protected override void performStage() 2012 { 2013 version (Windows) 2014 { 2015 auto curlDir = needCurl(); 2016 2017 void copyDir(string source, string target) 2018 { 2019 source = buildPath(curlDir, "dmd2", "windows", source); 2020 target = buildPath(stageDir, target); 2021 if (source.exists) 2022 cp(source, target); 2023 } 2024 2025 foreach (model; config.build.components.common.models) 2026 { 2027 auto suffix = model == "64" ? "64" : ""; 2028 copyDir("bin" ~ suffix, "bin"); 2029 copyDir("lib" ~ suffix, "lib"); 2030 } 2031 } 2032 else 2033 log("Not on Windows, skipping libcurl install"); 2034 } 2035 2036 protected override void updateEnv(ref Environment env) 2037 { 2038 env.vars["PATH"] = buildPath(buildDir, "bin").absolutePath() ~ pathSeparator ~ env.vars["PATH"]; 2039 } 2040 } 2041 2042 /// The Dub package manager and build tool 2043 final class Dub : Component 2044 { 2045 protected @property override string submoduleName() { return "dub"; } 2046 protected @property override string[] sourceDependencies() { return []; } 2047 protected @property override string[] dependencies() { return []; } 2048 protected @property override string configString() { return null; } 2049 2050 protected override void performBuild() 2051 { 2052 auto env = baseEnvironment; 2053 run([dmd, "-i", "-run", "build.d"], env.vars, sourceDir); 2054 } 2055 2056 protected override void performStage() 2057 { 2058 cp( 2059 buildPath(sourceDir, "bin", "dub" ~ binExt), 2060 buildPath(stageDir , "bin", "dub" ~ binExt), 2061 ); 2062 } 2063 } 2064 2065 private int tempError; 2066 2067 private Component[string] components; 2068 2069 /// Retrieve a component by name 2070 /// (as it would occur in `config.build.components.enable`). 2071 Component getComponent(string name) 2072 { 2073 if (name !in components) 2074 { 2075 Component c; 2076 2077 switch (name) 2078 { 2079 case "dmd": 2080 c = new DMD(); 2081 break; 2082 case "phobos-includes": 2083 c = new PhobosIncludes(); 2084 break; 2085 case "druntime": 2086 c = new Druntime(); 2087 break; 2088 case "phobos": 2089 c = new Phobos(); 2090 break; 2091 case "rdmd": 2092 c = new RDMD(); 2093 break; 2094 case "tools": 2095 c = new Tools(); 2096 break; 2097 case "website": 2098 c = new Website(); 2099 break; 2100 case "extras": 2101 c = new Extras(); 2102 break; 2103 case "curl": 2104 c = new Curl(); 2105 break; 2106 case "dub": 2107 c = new Dub(); 2108 break; 2109 default: 2110 throw new Exception("Unknown component: " ~ name); 2111 } 2112 2113 c.name = name; 2114 return components[name] = c; 2115 } 2116 2117 return components[name]; 2118 } 2119 2120 /// Retrieve components built from the given submodule name. 2121 Component[] getSubmoduleComponents(string submoduleName) 2122 { 2123 return components 2124 .byValue 2125 .filter!(component => component.submoduleName == submoduleName) 2126 .array(); 2127 } 2128 2129 // ***************************** GitHub API ****************************** 2130 2131 private GitHub github; 2132 2133 private ref GitHub needGitHub() 2134 { 2135 if (github is GitHub.init) 2136 { 2137 github.log = &this.log; 2138 github.token = config.local.githubToken; 2139 github.cache = new class GitHub.ICache 2140 { 2141 final string cacheFileName(string key) 2142 { 2143 return githubDir.buildPath(getDigestString!MD5(key).toLower()); 2144 } 2145 2146 string get(string key) 2147 { 2148 auto fn = cacheFileName(key); 2149 return fn.exists ? fn.readText : null; 2150 } 2151 2152 void put(string key, string value) 2153 { 2154 githubDir.ensureDirExists; 2155 std.file.write(cacheFileName(key), value); 2156 } 2157 }; 2158 github.offline = config.local.offline; 2159 } 2160 return github; 2161 } 2162 2163 // **************************** Customization **************************** 2164 2165 /// Fetch latest D history. 2166 /// Return true if any updates were fetched. 2167 bool update() 2168 { 2169 return getMetaRepo().update(); 2170 } 2171 2172 /// Indicates the state of a build customization. 2173 struct SubmoduleState 2174 { 2175 string[string] submoduleCommits; /// Commit hashes of submodules to build. 2176 } 2177 2178 /// Begin customization, starting at the specified commit. 2179 SubmoduleState begin(string commit) 2180 { 2181 log("Starting at meta repository commit " ~ commit); 2182 return SubmoduleState(getMetaRepo().getSubmoduleCommits(commit)); 2183 } 2184 2185 alias MergeMode = ManagedRepository.MergeMode; /// 2186 2187 /// Applies a merge onto the given SubmoduleState. 2188 void merge(ref SubmoduleState submoduleState, string submoduleName, string[2] branch, MergeMode mode) 2189 { 2190 log("Merging %s commits %s..%s".format(submoduleName, branch[0], branch[1])); 2191 enforce(submoduleName in submoduleState.submoduleCommits, "Unknown submodule: " ~ submoduleName); 2192 auto submodule = getSubmodule(submoduleName); 2193 auto head = submoduleState.submoduleCommits[submoduleName]; 2194 auto result = submodule.getMerge(head, branch, mode); 2195 submoduleState.submoduleCommits[submoduleName] = result; 2196 } 2197 2198 /// Removes a merge from the given SubmoduleState. 2199 void unmerge(ref SubmoduleState submoduleState, string submoduleName, string[2] branch, MergeMode mode) 2200 { 2201 log("Unmerging %s commits %s..%s".format(submoduleName, branch[0], branch[1])); 2202 enforce(submoduleName in submoduleState.submoduleCommits, "Unknown submodule: " ~ submoduleName); 2203 auto submodule = getSubmodule(submoduleName); 2204 auto head = submoduleState.submoduleCommits[submoduleName]; 2205 auto result = submodule.getUnMerge(head, branch, mode); 2206 submoduleState.submoduleCommits[submoduleName] = result; 2207 } 2208 2209 /// Reverts a commit from the given SubmoduleState. 2210 /// parent is the 1-based mainline index (as per `man git-revert`), 2211 /// or 0 if commit is not a merge commit. 2212 void revert(ref SubmoduleState submoduleState, string submoduleName, string[2] branch, MergeMode mode) 2213 { 2214 log("Reverting %s commits %s..%s".format(submoduleName, branch[0], branch[1])); 2215 enforce(submoduleName in submoduleState.submoduleCommits, "Unknown submodule: " ~ submoduleName); 2216 auto submodule = getSubmodule(submoduleName); 2217 auto head = submoduleState.submoduleCommits[submoduleName]; 2218 auto result = submodule.getRevert(head, branch, mode); 2219 submoduleState.submoduleCommits[submoduleName] = result; 2220 } 2221 2222 /// Returns the commit hash for the given pull request # (base and tip). 2223 /// The result can then be used with addMerge/removeMerge. 2224 string[2] getPull(string submoduleName, int pullNumber) 2225 { 2226 auto tip = getSubmodule(submoduleName).getPullTip(pullNumber); 2227 auto pull = needGitHub().query("https://api.github.com/repos/%s/%s/pulls/%d" 2228 .format("dlang", submoduleName, pullNumber)).data.parseJSON; 2229 auto base = pull["base"]["sha"].str; 2230 return [base, tip]; 2231 } 2232 2233 /// Returns the commit hash for the given branch (optionally GitHub fork). 2234 /// The result can then be used with addMerge/removeMerge. 2235 string[2] getBranch(string submoduleName, string user, string base, string tip) 2236 { 2237 return getSubmodule(submoduleName).getBranch(user, base, tip); 2238 } 2239 2240 // ****************************** Building ******************************* 2241 2242 private SubmoduleState submoduleState; 2243 private bool incrementalBuild; 2244 2245 /// Returns the name of the cache engine being used. 2246 @property string cacheEngineName() 2247 { 2248 if (incrementalBuild) 2249 return "none"; 2250 else 2251 return config.local.cache; 2252 } 2253 2254 private string getComponentCommit(string componentName) 2255 { 2256 auto submoduleName = getComponent(componentName).submoduleName; 2257 auto commit = submoduleState.submoduleCommits.get(submoduleName, null); 2258 enforce(commit, "Unknown commit to build for component %s (submodule %s)" 2259 .format(componentName, submoduleName)); 2260 return commit; 2261 } 2262 2263 static const string[] defaultComponents = ["dmd", "druntime", "phobos-includes", "phobos", "rdmd"]; /// Components enabled by default. 2264 static const string[] additionalComponents = ["tools", "website", "extras", "curl", "dub"]; /// Components disabled by default. 2265 static const string[] allComponents = defaultComponents ~ additionalComponents; /// All components that may be enabled and built. 2266 2267 /// Build the specified components according to the specified configuration. 2268 void build(SubmoduleState submoduleState, bool incremental = false) 2269 { 2270 auto componentNames = config.build.components.getEnabledComponentNames(); 2271 log("Building components %-(%s, %)".format(componentNames)); 2272 2273 this.components = null; 2274 this.submoduleState = submoduleState; 2275 this.incrementalBuild = incremental; 2276 2277 if (buildDir.exists) 2278 buildDir.removeRecurse(); 2279 enforce(!buildDir.exists); 2280 2281 scope(exit) if (cacheEngine) cacheEngine.finalize(); 2282 2283 foreach (componentName; componentNames) 2284 getComponent(componentName).needInstalled(); 2285 } 2286 2287 /// Shortcut for begin + build 2288 void buildRev(string rev) 2289 { 2290 auto submoduleState = begin(rev); 2291 build(submoduleState); 2292 } 2293 2294 /// Simply check out the source code for the given submodules. 2295 void checkout(SubmoduleState submoduleState) 2296 { 2297 auto componentNames = config.build.components.getEnabledComponentNames(); 2298 log("Checking out components %-(%s, %)".format(componentNames)); 2299 2300 this.components = null; 2301 this.submoduleState = submoduleState; 2302 this.incrementalBuild = false; 2303 2304 foreach (componentName; componentNames) 2305 getComponent(componentName).needSource(true); 2306 } 2307 2308 /// Rerun build without cleaning up any files. 2309 void rebuild() 2310 { 2311 build(SubmoduleState(null), true); 2312 } 2313 2314 /// Run all tests for the current checkout (like rebuild). 2315 void test(bool incremental = true) 2316 { 2317 auto componentNames = config.build.components.getEnabledComponentNames(); 2318 log("Testing components %-(%s, %)".format(componentNames)); 2319 2320 if (incremental) 2321 { 2322 this.components = null; 2323 this.submoduleState = SubmoduleState(null); 2324 this.incrementalBuild = true; 2325 } 2326 2327 foreach (componentName; componentNames) 2328 getComponent(componentName).test(); 2329 } 2330 2331 /// Check if the given build is cached. 2332 bool isCached(SubmoduleState submoduleState) 2333 { 2334 this.components = null; 2335 this.submoduleState = submoduleState; 2336 2337 needCacheEngine(); 2338 foreach (componentName; config.build.components.getEnabledComponentNames()) 2339 if (!cacheEngine.haveEntry(getComponent(componentName).getBuildID())) 2340 return false; 2341 return true; 2342 } 2343 2344 /// Returns the `isCached` state for all commits in the history of the given ref. 2345 bool[string] getCacheState(string[string][string] history) 2346 { 2347 log("Enumerating cache entries..."); 2348 auto cacheEntries = needCacheEngine().getEntries().toSet(); 2349 2350 this.components = null; 2351 auto componentNames = config.build.components.getEnabledComponentNames(); 2352 auto components = componentNames.map!(componentName => getComponent(componentName)).array; 2353 auto requiredSubmodules = components 2354 .map!(component => chain(component.name.only, component.sourceDependencies, component.dependencies)) 2355 .joiner 2356 .map!(componentName => getComponent(componentName).submoduleName) 2357 .array.sort().uniq().array 2358 ; 2359 2360 log("Collating cache state..."); 2361 bool[string] result; 2362 foreach (commit, submoduleCommits; history) 2363 { 2364 import ae.utils.meta : I; 2365 this.submoduleState.submoduleCommits = submoduleCommits; 2366 result[commit] = 2367 requiredSubmodules.all!(submoduleName => submoduleName in submoduleCommits) && 2368 componentNames.all!(componentName => 2369 getComponent(componentName).I!(component => 2370 component.getBuildID() in cacheEntries 2371 ) 2372 ); 2373 } 2374 return result; 2375 } 2376 2377 /// ditto 2378 bool[string] getCacheState(string[] refs) 2379 { 2380 auto history = getMetaRepo().getSubmoduleHistory(refs); 2381 return getCacheState(history); 2382 } 2383 2384 // **************************** Dependencies ***************************** 2385 2386 private void needInstaller() 2387 { 2388 Installer.logger = &log; 2389 Installer.installationDirectory = dlDir; 2390 } 2391 2392 /// Pull in a built DMD as configured. 2393 /// Note that this function invalidates the current repository state. 2394 void needDMD(ref Environment env, string dmdVer) 2395 { 2396 tempError++; scope(success) tempError--; 2397 2398 auto numericVersion(string dmdVer) 2399 { 2400 assert(dmdVer.startsWith("v")); 2401 return dmdVer[1 .. $].splitter('.').map!(to!int).array; 2402 } 2403 2404 // Nudge indicated version if we know it won't be usable on the current system. 2405 version (OSX) 2406 { 2407 enum minimalWithoutEnumerateTLV = "v2.088.0"; 2408 if (numericVersion(dmdVer) < numericVersion(minimalWithoutEnumerateTLV) && !haveEnumerateTLV()) 2409 { 2410 log("DMD " ~ dmdVer ~ " not usable on this system - using " ~ minimalWithoutEnumerateTLV ~ " instead."); 2411 dmdVer = minimalWithoutEnumerateTLV; 2412 } 2413 } 2414 2415 // User setting overrides autodetection 2416 if (config.build.components.dmd.bootstrap.ver) 2417 { 2418 log("Using user-specified bootstrap DMD version " ~ 2419 config.build.components.dmd.bootstrap.ver ~ 2420 " instead of auto-detected version " ~ dmdVer ~ "."); 2421 dmdVer = config.build.components.dmd.bootstrap.ver; 2422 } 2423 2424 if (config.build.components.dmd.bootstrap.fromSource) 2425 { 2426 log("Bootstrapping DMD " ~ dmdVer); 2427 2428 auto bootstrapBuildConfig = config.build.components.dmd.bootstrap.build; 2429 2430 // Back up and clear component state 2431 enum backupTemplate = q{ 2432 auto VARBackup = this.VAR; 2433 this.VAR = typeof(VAR).init; 2434 scope(exit) this.VAR = VARBackup; 2435 }; 2436 mixin(backupTemplate.replace(q{VAR}, q{components})); 2437 mixin(backupTemplate.replace(q{VAR}, q{config})); 2438 mixin(backupTemplate.replace(q{VAR}, q{submoduleState})); 2439 2440 config.local = configBackup.local; 2441 if (bootstrapBuildConfig) 2442 config.build = *bootstrapBuildConfig; 2443 2444 // Disable building rdmd in the bootstrap compiler by default 2445 if ("rdmd" !in config.build.components.enable) 2446 config.build.components.enable["rdmd"] = false; 2447 2448 build(parseSpec(dmdVer)); 2449 2450 log("Built bootstrap DMD " ~ dmdVer ~ " successfully."); 2451 2452 auto bootstrapDir = buildPath(config.local.workDir, "bootstrap"); 2453 if (bootstrapDir.exists) 2454 bootstrapDir.removeRecurse(); 2455 ensurePathExists(bootstrapDir); 2456 rename(buildDir, bootstrapDir); 2457 2458 env.deps.hostDC = buildPath(bootstrapDir, "bin", "dmd" ~ binExt); 2459 } 2460 else 2461 { 2462 import std.ascii; 2463 log("Preparing DMD " ~ dmdVer); 2464 enforce(dmdVer.startsWith("v"), "Invalid DMD version spec for binary bootstrap. Did you forget to " ~ 2465 ((dmdVer.length && dmdVer[0].isDigit && dmdVer.contains('.')) ? "add a leading 'v'" : "enable fromSource") ~ "?"); 2466 needInstaller(); 2467 auto dmdInstaller = new DMDInstaller(dmdVer[1..$]); 2468 dmdInstaller.requireLocal(false); 2469 env.deps.hostDC = dmdInstaller.exePath("dmd").absolutePath(); 2470 } 2471 2472 log("hostDC=" ~ env.deps.hostDC); 2473 } 2474 2475 protected void needKindleGen(ref Environment env) 2476 { 2477 needInstaller(); 2478 kindleGenInstaller.requireLocal(false); 2479 env.vars["PATH"] = kindleGenInstaller.directory ~ pathSeparator ~ env.vars["PATH"]; 2480 } 2481 2482 version (Windows) 2483 protected void needMSYS(ref Environment env) 2484 { 2485 needInstaller(); 2486 MSYS.msysCORE.requireLocal(false); 2487 MSYS.libintl.requireLocal(false); 2488 MSYS.libiconv.requireLocal(false); 2489 MSYS.libtermcap.requireLocal(false); 2490 MSYS.libregex.requireLocal(false); 2491 MSYS.coreutils.requireLocal(false); 2492 MSYS.bash.requireLocal(false); 2493 MSYS.make.requireLocal(false); 2494 MSYS.grep.requireLocal(false); 2495 MSYS.sed.requireLocal(false); 2496 MSYS.diffutils.requireLocal(false); 2497 env.vars["PATH"] = MSYS.bash.directory.buildPath("bin") ~ pathSeparator ~ env.vars["PATH"]; 2498 } 2499 2500 /// Get DMD unbuildable extras 2501 /// (proprietary DigitalMars utilities, 32-bit import libraries) 2502 protected string needExtras() 2503 { 2504 import ae.utils.meta : I, singleton; 2505 2506 static class DExtrasInstaller : Installer 2507 { 2508 protected @property override string name() { return "dmd-localextras"; } 2509 string url = "http://semitwist.com/download/app/dmd-localextras.7z"; 2510 2511 protected override void installImpl(string target) 2512 { 2513 url 2514 .I!save() 2515 .I!unpackTo(target); 2516 } 2517 2518 static this() 2519 { 2520 urlDigests["http://semitwist.com/download/app/dmd-localextras.7z"] = "ef367c2d25d4f19f45ade56ab6991c726b07d3d9"; 2521 } 2522 } 2523 2524 alias extrasInstaller = singleton!DExtrasInstaller; 2525 2526 needInstaller(); 2527 extrasInstaller.requireLocal(false); 2528 return extrasInstaller.directory; 2529 } 2530 2531 /// Get libcurl for Windows (DLL and import libraries) 2532 version (Windows) 2533 protected string needCurl() 2534 { 2535 import ae.utils.meta : I, singleton; 2536 2537 static class DCurlInstaller : Installer 2538 { 2539 protected @property override string name() { return "libcurl-" ~ curlVersion; } 2540 string curlVersion = "7.47.1"; 2541 @property string url() { return "http://downloads.dlang.org/other/libcurl-" ~ curlVersion ~ "-WinSSL-zlib-x86-x64.zip"; } 2542 2543 protected override void installImpl(string target) 2544 { 2545 url 2546 .I!save() 2547 .I!unpackTo(target); 2548 } 2549 2550 static this() 2551 { 2552 urlDigests["http://downloads.dlang.org/other/libcurl-7.47.1-WinSSL-zlib-x86-x64.zip"] = "4b8a7bb237efab25a96588093ae51994c821e097"; 2553 } 2554 } 2555 2556 alias curlInstaller = singleton!DCurlInstaller; 2557 2558 needInstaller(); 2559 curlInstaller.requireLocal(false); 2560 return curlInstaller.directory; 2561 } 2562 2563 version (Windows) 2564 protected void needDMC(ref Environment env, string ver = null) 2565 { 2566 tempError++; scope(success) tempError--; 2567 2568 needInstaller(); 2569 2570 auto dmc = ver ? new LegacyDMCInstaller(ver) : dmcInstaller; 2571 if (!dmc.installedLocally) 2572 log("Preparing DigitalMars C++ " ~ ver); 2573 dmc.requireLocal(false); 2574 env.deps.dmcDir = dmc.directory; 2575 2576 auto binPath = buildPath(env.deps.dmcDir, `bin`).absolutePath(); 2577 log("DMC=" ~ binPath); 2578 env.vars["DMC"] = binPath; 2579 env.vars["PATH"] = binPath ~ pathSeparator ~ env.vars.get("PATH", null); 2580 } 2581 2582 version (Windows) 2583 auto getVSInstaller() 2584 { 2585 needInstaller(); 2586 return vs2013community; 2587 } 2588 2589 version (Windows) 2590 protected static string msvcModelStr(string model, string str32, string str64) 2591 { 2592 switch (model) 2593 { 2594 case "32": 2595 throw new Exception("Shouldn't need VC for 32-bit builds"); 2596 case "64": 2597 return str64; 2598 case "32mscoff": 2599 return str32; 2600 default: 2601 throw new Exception("Unknown model: " ~ model); 2602 } 2603 } 2604 2605 version (Windows) 2606 protected static string msvcModelDir(string model, string dir64 = "x86_amd64") 2607 { 2608 return msvcModelStr(model, null, dir64); 2609 } 2610 2611 version (Windows) 2612 protected void needVC(ref Environment env, string model) 2613 { 2614 tempError++; scope(success) tempError--; 2615 2616 auto vs = getVSInstaller(); 2617 2618 // At minimum, we want the C compiler (cl.exe) and linker (link.exe). 2619 vs["vc_compilercore86"].requireLocal(false); // Contains both x86 and x86_amd64 cl.exe 2620 vs["vc_compilercore86res"].requireLocal(false); // Contains clui.dll needed by cl.exe 2621 2622 // Include files. Needed when using VS to build either DMD or Druntime. 2623 vs["vc_librarycore86"].requireLocal(false); // Contains include files, e.g. errno.h needed by Druntime 2624 2625 // C runtime. Needed for all programs built with VC. 2626 vs[msvcModelStr(model, "vc_libraryDesktop_x86", "vc_libraryDesktop_x64")].requireLocal(false); // libcmt.lib 2627 2628 // XP-compatible import libraries. 2629 vs["win_xpsupport"].requireLocal(false); // shell32.lib 2630 2631 // MSBuild, for the useVC option 2632 if (config.build.components.dmd.useVC) 2633 vs["Msi_BuildTools_MSBuild_x86"].requireLocal(false); // msbuild.exe 2634 2635 env.deps.vsDir = vs.directory.buildPath("Program Files (x86)", "Microsoft Visual Studio 12.0").absolutePath(); 2636 env.deps.sdkDir = vs.directory.buildPath("Program Files", "Microsoft SDKs", "Windows", "v7.1A").absolutePath(); 2637 2638 env.vars["PATH"] ~= pathSeparator ~ vs.modelBinPaths(msvcModelDir(model)).map!(path => vs.directory.buildPath(path).absolutePath()).join(pathSeparator); 2639 env.vars["VisualStudioVersion"] = "12"; // Work-around for problem fixed in dmd 38da6c2258c0ff073b0e86e0a1f6ba190f061e5e 2640 env.vars["VSINSTALLDIR"] = env.deps.vsDir ~ dirSeparator; // ditto 2641 env.vars["VCINSTALLDIR"] = env.deps.vsDir.buildPath("VC") ~ dirSeparator; 2642 env.vars["INCLUDE"] = env.deps.vsDir.buildPath("VC", "include") ~ ";" ~ env.deps.sdkDir.buildPath("Include"); 2643 env.vars["LIB"] = env.deps.vsDir.buildPath("VC", "lib", msvcModelDir(model, "amd64")) ~ ";" ~ env.deps.sdkDir.buildPath("Lib", msvcModelDir(model, "x64")); 2644 env.vars["WindowsSdkDir"] = env.deps.sdkDir ~ dirSeparator; 2645 env.vars["Platform"] = "x64"; 2646 env.vars["LINKCMD64"] = env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "link.exe"); // Used by dmd 2647 env.vars["MSVC_CC"] = env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "cl.exe"); // For the msvc-dmc wrapper 2648 env.vars["MSVC_AR"] = env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "lib.exe"); // For the msvc-lib wrapper 2649 env.vars["CL"] = "-D_USING_V110_SDK71_"; // Work around __userHeader macro redifinition VS bug 2650 } 2651 2652 private void needGit() 2653 { 2654 tempError++; scope(success) tempError--; 2655 2656 needInstaller(); 2657 gitInstaller.require(); 2658 } 2659 2660 /// Disable the "<program> has stopped working" 2661 /// standard Windows dialog. 2662 version (Windows) 2663 static void disableCrashDialog() 2664 { 2665 enum : uint { SEM_FAILCRITICALERRORS = 1, SEM_NOGPFAULTERRORBOX = 2 } 2666 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); 2667 } 2668 2669 version (OSX) protected 2670 { 2671 bool needWorkingCCChecked; 2672 void needWorkingCC() 2673 { 2674 if (!needWorkingCCChecked) 2675 { 2676 log("Checking for a working C compiler..."); 2677 auto dir = buildPath(config.local.workDir, "temp", "cc-test"); 2678 if (dir.exists) dir.rmdirRecurse(); 2679 dir.mkdirRecurse(); 2680 scope(success) rmdirRecurse(dir); 2681 2682 write(dir.buildPath("test.c"), "int main() { return 0; }"); 2683 auto status = spawnProcess(["cc", "test.c"], baseEnvironment.vars, std.process.Config.newEnv, dir).wait(); 2684 enforce(status == 0, "Failed to compile a simple C program - no C compiler."); 2685 2686 log("> OK"); 2687 needWorkingCCChecked = true; 2688 } 2689 }; 2690 2691 bool haveEnumerateTLVChecked, haveEnumerateTLVValue; 2692 bool haveEnumerateTLV() 2693 { 2694 if (!haveEnumerateTLVChecked) 2695 { 2696 needWorkingCC(); 2697 2698 log("Checking for dyld_enumerate_tlv_storage..."); 2699 auto dir = buildPath(config.local.workDir, "temp", "cc-tlv-test"); 2700 if (dir.exists) dir.rmdirRecurse(); 2701 dir.mkdirRecurse(); 2702 scope(success) rmdirRecurse(dir); 2703 2704 write(dir.buildPath("test.c"), "extern void dyld_enumerate_tlv_storage(void* handler); int main() { dyld_enumerate_tlv_storage(0); return 0; }"); 2705 if (spawnProcess(["cc", "test.c"], baseEnvironment.vars, std.process.Config.newEnv, dir).wait() == 0) 2706 { 2707 log("> Present (probably 10.14 or older)"); 2708 haveEnumerateTLVValue = true; 2709 } 2710 else 2711 { 2712 log("> Absent (probably 10.15 or newer)"); 2713 haveEnumerateTLVValue = false; 2714 } 2715 haveEnumerateTLVChecked = true; 2716 } 2717 return haveEnumerateTLVValue; 2718 } 2719 } 2720 2721 /// Create a build environment base. 2722 protected @property Environment baseEnvironment() 2723 { 2724 Environment env; 2725 2726 // Build a new environment from scratch, to avoid tainting the build with the current environment. 2727 string[] newPaths; 2728 2729 version (Windows) 2730 { 2731 import std.utf; 2732 import ae.sys.windows.imports; 2733 mixin(importWin32!q{winbase}); 2734 mixin(importWin32!q{winnt}); 2735 2736 TCHAR[1024] buf; 2737 // Needed for DLLs 2738 auto winDir = buf[0..GetWindowsDirectory(buf.ptr, buf.length)].toUTF8(); 2739 auto sysDir = buf[0..GetSystemDirectory (buf.ptr, buf.length)].toUTF8(); 2740 newPaths ~= [sysDir, winDir]; 2741 2742 newPaths ~= gitInstaller.exePath("git").absolutePath().dirName; // For git-describe and such 2743 } 2744 else 2745 { 2746 // Needed for coreutils, make, gcc, git etc. 2747 newPaths = ["/bin", "/usr/bin", "/usr/local/bin"]; 2748 2749 version (linux) 2750 { 2751 // GCC wrappers 2752 ensureDirExists(binDir); 2753 newPaths = binDir ~ newPaths; 2754 } 2755 } 2756 2757 env.vars["PATH"] = newPaths.join(pathSeparator); 2758 2759 ensureDirExists(tmpDir); 2760 env.vars["TMPDIR"] = env.vars["TEMP"] = env.vars["TMP"] = tmpDir; 2761 2762 version (Windows) 2763 { 2764 env.vars["SystemDrive"] = winDir.driveName; 2765 env.vars["SystemRoot"] = winDir; 2766 } 2767 2768 ensureDirExists(homeDir); 2769 env.vars["HOME"] = homeDir; 2770 2771 return env; 2772 } 2773 2774 /// Apply user modifications onto an environment. 2775 /// Supports Windows-style %VAR% expansions. 2776 static string[string] applyEnv(in string[string] target, in string[string] source) 2777 { 2778 // The source of variable expansions is variables in the target environment, 2779 // if they exist, and the host environment otherwise, so e.g. 2780 // `PATH=C:\...;%PATH%` and `MAKE=%MAKE%` work as expected. 2781 auto oldEnv = std.process.environment.toAA(); 2782 foreach (name, value; target) 2783 oldEnv[name] = value; 2784 2785 string[string] result; 2786 foreach (name, value; target) 2787 result[name] = value; 2788 foreach (name, value; source) 2789 { 2790 string newValue = value; 2791 foreach (oldName, oldValue; oldEnv) 2792 newValue = newValue.replace("%" ~ oldName ~ "%", oldValue); 2793 result[name] = oldEnv[name] = newValue; 2794 } 2795 return result; 2796 } 2797 2798 // ******************************** Cache ******************************** 2799 2800 /// Unbuildable versions are saved in the cache as a single empty file with this name. 2801 enum unbuildableMarker = "unbuildable"; 2802 2803 private DCache cacheEngine; /// Caches builds. 2804 2805 DCache needCacheEngine() 2806 { 2807 if (!cacheEngine) 2808 { 2809 if (cacheEngineName == "git") 2810 needGit(); 2811 cacheEngine = createCache(cacheEngineName, cacheEngineDir(cacheEngineName), this); 2812 } 2813 return cacheEngine; 2814 } /// ditto 2815 2816 protected void cp(string src, string dst) 2817 { 2818 needCacheEngine().cp(src, dst); 2819 } 2820 2821 private string[] getComponentKeyOrder(string componentName) 2822 { 2823 auto submodule = getComponent(componentName).submodule; 2824 return submodule 2825 .git.query("log", "--pretty=format:%H", "--all", "--topo-order") 2826 .splitLines() 2827 .map!(commit => componentName ~ "-" ~ commit ~ "-") 2828 .array 2829 ; 2830 } 2831 2832 protected string componentNameFromKey(string key) 2833 { 2834 auto parts = key.split("-"); 2835 return parts[0..$-2].join("-"); 2836 } 2837 2838 protected string[][] getKeyOrder(string key) 2839 { 2840 if (key !is null) 2841 return [getComponentKeyOrder(componentNameFromKey(key))]; 2842 else 2843 return allComponents.map!(componentName => getComponentKeyOrder(componentName)).array; 2844 } 2845 2846 /// Optimize entire cache. 2847 void optimizeCache() 2848 { 2849 needCacheEngine().optimize(); 2850 } 2851 2852 protected bool shouldPurge(string key) 2853 { 2854 auto files = cacheEngine.listFiles(key); 2855 if (files.canFind(unbuildableMarker)) 2856 return true; 2857 2858 if (componentNameFromKey(key) == "druntime") 2859 { 2860 if (!files.canFind("import/core/memory.d") 2861 && !files.canFind("import/core/memory.di")) 2862 return true; 2863 } 2864 2865 return false; 2866 } 2867 2868 /// Delete cached "unbuildable" build results. 2869 void purgeUnbuildable() 2870 { 2871 needCacheEngine() 2872 .getEntries 2873 .filter!(key => shouldPurge(key)) 2874 .each!((key) 2875 { 2876 log("Deleting: " ~ key); 2877 cacheEngine.remove(key); 2878 }) 2879 ; 2880 } 2881 2882 /// Move cached files from one cache engine to another. 2883 void migrateCache(string sourceEngineName, string targetEngineName) 2884 { 2885 auto sourceEngine = createCache(sourceEngineName, cacheEngineDir(sourceEngineName), this); 2886 auto targetEngine = createCache(targetEngineName, cacheEngineDir(targetEngineName), this); 2887 auto tempDir = buildPath(config.local.workDir, "temp"); 2888 if (tempDir.exists) 2889 tempDir.removeRecurse(); 2890 log("Enumerating source entries..."); 2891 auto sourceEntries = sourceEngine.getEntries(); 2892 log("Enumerating target entries..."); 2893 auto targetEntries = targetEngine.getEntries().sort(); 2894 foreach (key; sourceEntries) 2895 if (!targetEntries.canFind(key)) 2896 { 2897 log(key); 2898 sourceEngine.extract(key, tempDir, fn => true); 2899 targetEngine.add(key, tempDir); 2900 if (tempDir.exists) 2901 tempDir.removeRecurse(); 2902 } 2903 targetEngine.optimize(); 2904 } 2905 2906 // **************************** Miscellaneous **************************** 2907 2908 /// Gets the D merge log (newest first). 2909 struct LogEntry 2910 { 2911 string hash; /// 2912 string[] message; /// 2913 SysTime time; /// 2914 } 2915 2916 /// ditto 2917 LogEntry[] getLog(string refName = "refs/remotes/origin/master") 2918 { 2919 auto history = getMetaRepo().git.getHistory(); 2920 LogEntry[] logs; 2921 auto master = history.commits[history.refs[refName]]; 2922 for (auto c = master; c; c = c.parents.length ? c.parents[0] : null) 2923 { 2924 auto time = SysTime(c.time.unixTimeToStdTime); 2925 logs ~= LogEntry(c.oid.toString(), c.message, time); 2926 } 2927 return logs; 2928 } 2929 2930 // ***************************** Integration ***************************** 2931 2932 /// Override to add logging. 2933 void log(string line) 2934 { 2935 } 2936 2937 /// Bootstrap description resolution. 2938 /// See DMD.Config.Bootstrap.spec. 2939 /// This is essentially a hack to allow the entire 2940 /// Config structure to be parsed from an .ini file. 2941 SubmoduleState parseSpec(string spec) 2942 { 2943 auto rev = getMetaRepo().getRef("refs/tags/" ~ spec); 2944 log("Resolved " ~ spec ~ " to " ~ rev); 2945 return begin(rev); 2946 } 2947 2948 /// Override this method with one which returns a command, 2949 /// which will invoke the unmergeRebaseEdit function below, 2950 /// passing to it any additional parameters. 2951 /// Note: Currently unused. Was previously used 2952 /// for unmerging things using interactive rebase. 2953 deprecated abstract string getCallbackCommand(); 2954 2955 deprecated void callback(string[] args) { assert(false); } 2956 }