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