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 			version (Posix)
761 				enum makeProgram = "gmake"; // GNU make
762 			else
763 				enum makeProgram = "make";
764 			return [env.vars.get("MAKE", makeProgram)];
765 		}
766 
767 		/// Returns the path to the built dmd executable.
768 		@property string dmd() { return buildPath(buildDir, "bin", "dmd" ~ binExt).absolutePath(); }
769 
770 		/// Escape a path for d_do_test's very "special" criteria.
771 		/// Spaces must be escaped, but there must be no double-quote at the end.
772 		private static string dDoTestEscape(string str)
773 		{
774 			return str.replaceAll(re!`\\([^\\ ]*? [^\\]*)(?=\\)`, `\"$1"`);
775 		}
776 
777 		unittest
778 		{
779 			assert(dDoTestEscape(`C:\Foo boo bar\baz quuz\derp.exe`) == `C:\"Foo boo bar"\"baz quuz"\derp.exe`);
780 		}
781 
782 		string[] getPlatformMakeVars(in ref Environment env, string model, bool quote = true)
783 		{
784 			string[] args;
785 
786 			args ~= "MODEL=" ~ model;
787 
788 			version (Windows)
789 				if (model != "32")
790 				{
791 					args ~= "VCDIR="  ~ env.deps.vsDir.buildPath("VC").absolutePath();
792 					args ~= "SDKDIR=" ~ env.deps.sdkDir.absolutePath();
793 
794 					// Work around https://github.com/dlang/druntime/pull/2438
795 					auto quoteStr = quote ? `"` : ``;
796 					args ~= "CC=" ~ quoteStr ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "cl.exe").absolutePath() ~ quoteStr;
797 					args ~= "LD=" ~ quoteStr ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "link.exe").absolutePath() ~ quoteStr;
798 					args ~= "AR=" ~ quoteStr ~ env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "lib.exe").absolutePath() ~ quoteStr;
799 				}
800 
801 			return args;
802 		}
803 
804 		@property string[] gnuMakeArgs()
805 		{
806 			string[] args;
807 			if (config.local.makeJobs)
808 			{
809 				if (config.local.makeJobs == "auto")
810 				{
811 					import std.parallelism, std.conv;
812 					args ~= "-j" ~ text(totalCPUs);
813 				}
814 				else
815 				if (config.local.makeJobs == "unlimited")
816 					args ~= "-j";
817 				else
818 					args ~= "-j" ~ config.local.makeJobs;
819 			}
820 			return args;
821 		}
822 
823 		@property string[] dMakeArgs()
824 		{
825 			version (Windows)
826 				return null; // On Windows, DigitalMars make is used for all makefiles except the dmd test suite
827 			else
828 				return gnuMakeArgs;
829 		}
830 
831 		/// Older versions did not use the posix.mak/win32.mak convention.
832 		static string findMakeFile(string dir, string fn)
833 		{
834 			version (OSX)
835 				if (!dir.buildPath(fn).exists && dir.buildPath("osx.mak").exists)
836 					return "osx.mak";
837 			version (Posix)
838 				if (!dir.buildPath(fn).exists && dir.buildPath("linux.mak").exists)
839 					return "linux.mak";
840 			return fn;
841 		}
842 
843 		void needCC(ref Environment env, string model, string dmcVer = null)
844 		{
845 			version (Windows)
846 			{
847 				needDMC(env, dmcVer); // We need DMC even for 64-bit builds (for DM make)
848 				if (model != "32")
849 					needVC(env, model);
850 			}
851 		}
852 
853 		void run(const(string)[] args, in string[string] newEnv, string dir)
854 		{
855 			// Apply user environment
856 			auto env = applyEnv(newEnv, config.build.environment);
857 
858 			// Temporarily apply PATH from newEnv to our process,
859 			// so process creation lookup can use it.
860 			string oldPath = std.process.environment["PATH"];
861 			scope (exit) std.process.environment["PATH"] = oldPath;
862 			std.process.environment["PATH"] = env["PATH"];
863 
864 			// Apply timeout setting
865 			if (config.local.timeout)
866 				args = ["timeout", config.local.timeout.text] ~ args;
867 
868 			foreach (name, value; env)
869 				log("Environment: " ~ name ~ "=" ~ value);
870 			log("Working directory: " ~ dir);
871 			log("Running: " ~ escapeShellCommand(args));
872 
873 			auto status = spawnProcess(args, env, std.process.Config.newEnv, dir).wait();
874 			enforce(status == 0, "Command %s failed with status %d".format(args, status));
875 		}
876 	}
877 
878 	/// The dmd executable
879 	final class DMD : Component
880 	{
881 		@property override string submoduleName  () { return "dmd"; }
882 		@property override string[] sourceDependencies() { return []; }
883 		@property override string[] dependencies() { return []; }
884 
885 		struct Config
886 		{
887 			/// Whether to build a debug DMD.
888 			/// Debug builds are faster to build,
889 			/// but run slower.
890 			@JSONOptional bool debugDMD = false;
891 
892 			/// Whether to build a release DMD.
893 			/// Mutually exclusive with debugDMD.
894 			@JSONOptional bool releaseDMD = false;
895 
896 			/// Model for building DMD itself (on Windows).
897 			/// Can be used to build a 64-bit DMD, to avoid 4GB limit.
898 			@JSONOptional string dmdModel = CommonConfig.defaultModel;
899 
900 			/// How to build DMD versions written in D.
901 			/// We can either download a pre-built binary DMD
902 			/// package, or build an  earlier version from source
903 			/// (e.g. starting with the last C++-only version.)
904 			struct Bootstrap
905 			{
906 				/// Whether to download a pre-built D version,
907 				/// or build one from source. If set, then build
908 				/// from source according to the value of ver,
909 				@JSONOptional bool fromSource = false;
910 
911 				/// Version specification.
912 				/// When building from source, syntax can be defined
913 				/// by outer application (see parseSpec method);
914 				/// When the bootstrapping compiler is not built from source,
915 				/// it is understood as a version number, such as "v2.070.2",
916 				/// which also doubles as a tag name.
917 				/// By default (when set to null), an appropriate version
918 				/// is selected automatically.
919 				@JSONOptional string ver = null;
920 
921 				/// Build configuration for the compiler used for bootstrapping.
922 				/// If not set, then use the default build configuration.
923 				/// Used when fromSource is set.
924 				@JSONOptional DManager.Config.Build* build;
925 			}
926 			@JSONOptional Bootstrap bootstrap; /// ditto
927 
928 			/// Use Visual C++ to build DMD instead of DMC.
929 			/// Currently, this is a hack, as msbuild will consult the system
930 			/// registry and use the system-wide installation of Visual Studio.
931 			/// Only relevant for older versions, as newer versions are written in D.
932 			@JSONOptional bool useVC;
933 		}
934 
935 		@property override string configString()
936 		{
937 			static struct FullConfig
938 			{
939 				Config config;
940 				string[] makeArgs;
941 
942 				// Include the common models as well as the DMD model (from config).
943 				// Necessary to ensure the correct sc.ini is generated on Windows
944 				// (we don't want to pull in MSVC unless either DMD or Phobos are
945 				// built as 64-bit, but also we can't reuse a DMD build with 32-bit
946 				// DMD and Phobos for a 64-bit Phobos build because it won't have
947 				// the VC vars set up in its sc.ini).
948 				// Possibly refactor the compiler configuration to a separate
949 				// component in the future to avoid the inefficiency of rebuilding
950 				// DMD just to generate a different sc.ini.
951 				@JSONOptional string commonModel = Component.CommonConfig.defaultModel;
952 			}
953 
954 			return FullConfig(
955 				config.build.components.dmd,
956 				config.build.components.common.makeArgs,
957 				config.build.components.common.model,
958 			).toJson();
959 		}
960 
961 		@property string vsConfiguration() { return config.build.components.dmd.debugDMD ? "Debug" : "Release"; }
962 		@property string vsPlatform     () { return config.build.components.dmd.dmdModel == "64" ? "x64" : "Win32"; }
963 
964 		override void performBuild()
965 		{
966 			// We need an older DMC for older DMD versions
967 			string dmcVer = null;
968 			auto idgen = buildPath(sourceDir, "src", "idgen.c");
969 			if (idgen.exists && idgen.readText().indexOf(`{ "alignof" },`) >= 0)
970 				dmcVer = "850";
971 
972 			auto env = baseEnvironment;
973 			needCC(env, config.build.components.dmd.dmdModel, dmcVer); // Need VC too for VSINSTALLDIR
974 
975 			auto srcDir = buildPath(sourceDir, "src");
976 			string dmdMakeFileName = findMakeFile(srcDir, makeFileName);
977 			string dmdMakeFullName = srcDir.buildPath(dmdMakeFileName);
978 
979 			if (buildPath(sourceDir, "src", "idgen.d").exists ||
980 			    buildPath(sourceDir, "src", "ddmd", "idgen.d").exists ||
981 			    buildPath(sourceDir, "src", "ddmd", "mars.d").exists ||
982 			    buildPath(sourceDir, "src", "dmd", "mars.d").exists)
983 			{
984 				// Need an older DMD for bootstrapping.
985 				string dmdVer = "v2.067.1";
986 				if (sourceDir.buildPath("test/compilable/staticforeach.d").exists)
987 					dmdVer = "v2.068.0";
988 				version (Windows)
989 					if (config.build.components.dmd.dmdModel != Component.CommonConfig.defaultModel)
990 						dmdVer = "v2.070.2"; // dmd/src/builtin.d needs core.stdc.math.fabsl. 2.068.2 generates a dmd which crashes on building Phobos
991 				if (sourceDir.buildPath("src/dmd/backend/dvec.d").exists) // 2.079 is needed since 2.080
992 					dmdVer = "v2.079.0";
993 				needDMD(env, dmdVer);
994 
995 				// Go back to our commit (in case we bootstrapped from source).
996 				needSource(true);
997 				submodule.clean = false;
998 			}
999 
1000 			if (config.build.components.dmd.useVC) // Mostly obsolete, see useVC ddoc
1001 			{
1002 				version (Windows)
1003 				{
1004 					needVC(env, config.build.components.dmd.dmdModel);
1005 
1006 					env.vars["PATH"] = env.vars["PATH"] ~ pathSeparator ~ env.deps.hostDC.dirName;
1007 
1008 					auto solutionFile = `dmd_msc_vs10.sln`;
1009 					if (!exists(srcDir.buildPath(solutionFile)))
1010 						solutionFile = `vcbuild\dmd.sln`;
1011 					if (!exists(srcDir.buildPath(solutionFile)))
1012 						throw new Exception("Can't find Visual Studio solution file");
1013 
1014 					return run(["msbuild", "/p:Configuration=" ~ vsConfiguration, "/p:Platform=" ~ vsPlatform, solutionFile], env.vars, srcDir);
1015 				}
1016 				else
1017 					throw new Exception("Can only use Visual Studio on Windows");
1018 			}
1019 
1020 			version (Windows)
1021 				auto scRoot = env.deps.dmcDir.absolutePath();
1022 
1023 			string modelFlag = config.build.components.dmd.dmdModel;
1024 			if (dmdMakeFullName.readText().canFind("MODEL=-m32"))
1025 				modelFlag = "-m" ~ modelFlag;
1026 
1027 			version (Windows)
1028 			{
1029 				auto m = dmdMakeFullName.readText();
1030 				m = m
1031 					// A make argument is insufficient,
1032 					// because of recursive make invocations
1033 					.replace(`CC=\dm\bin\dmc`, `CC=dmc`)
1034 					.replace(`SCROOT=$D\dm`, `SCROOT=` ~ scRoot)
1035 					// Debug crashes in build.d
1036 					.replaceAll(re!(`^(	\$\(HOST_DC\) .*) (build\.d)$`, "m"), "$1 -g $2")
1037 				;
1038 				dmdMakeFullName.write(m);
1039 			}
1040 			else
1041 			{
1042 				auto m = dmdMakeFullName.readText();
1043 				m = m
1044 					// Fix hard-coded reference to gcc as linker
1045 					.replace(`gcc -m32 -lstdc++`, `g++ -m32 -lstdc++`)
1046 					.replace(`gcc $(MODEL) -lstdc++`, `g++ $(MODEL) -lstdc++`)
1047 					// Fix compilation of older versions of go.c with GCC 6
1048 					.replace(`-Wno-deprecated`, `-Wno-deprecated -Wno-narrowing`)
1049 				;
1050 				// Fix pthread linker error
1051 				version (linux)
1052 					m = m.replace(`-lpthread`, `-pthread`);
1053 				dmdMakeFullName.write(m);
1054 			}
1055 
1056 			submodule.saveFileState("src/" ~ dmdMakeFileName);
1057 
1058 			version (Windows)
1059 			{
1060 				auto buildDFileName = "build.d";
1061 				auto buildDPath = srcDir.buildPath(buildDFileName);
1062 				if (buildDPath.exists)
1063 				{
1064 					auto buildD = buildDPath.readText();
1065 					buildD = buildD
1066 						// https://github.com/dlang/dmd/pull/10491
1067 						// Needs WBEM PATH entry, and also fails under Wine as its wmic outputs UTF-16.
1068 						.replace(`["wmic", "OS", "get", "OSArchitecture"].execute.output`, isWin64 ? `"64-bit"` : `"32-bit"`)
1069 					;
1070 					buildDPath.write(buildD);
1071 					submodule.saveFileState("src/" ~ buildDFileName);
1072 				}
1073 			}
1074 
1075 			// Fix compilation error of older DMDs with glibc >= 2.25
1076 			version (linux)
1077 			{{
1078 				auto fn = srcDir.buildPath("root", "port.c");
1079 				if (fn.exists)
1080 				{
1081 					fn.write(fn.readText
1082 						.replace(`#include <bits/mathdef.h>`, `#include <complex.h>`)
1083 						.replace(`#include <bits/nan.h>`, `#include <math.h>`)
1084 					);
1085 					submodule.saveFileState(fn.relativePath(sourceDir));
1086 				}
1087 			}}
1088 
1089 			// Fix alignment issue in older DMDs with GCC >= 7
1090 			// See https://issues.dlang.org/show_bug.cgi?id=17726
1091 			version (Posix)
1092 			{
1093 				foreach (fn; [srcDir.buildPath("tk", "mem.c"), srcDir.buildPath("ddmd", "tk", "mem.c")])
1094 					if (fn.exists)
1095 					{
1096 						fn.write(fn.readText.replace(
1097 								// `#if defined(__llvm__) && (defined(__GNUC__) || defined(__clang__))`,
1098 								// `#if defined(__GNUC__) || defined(__clang__)`,
1099 								`numbytes = (numbytes + 3) & ~3;`,
1100 								`numbytes = (numbytes + 0xF) & ~0xF;`
1101 						));
1102 						submodule.saveFileState(fn.relativePath(sourceDir));
1103 					}
1104 			}
1105 
1106 			string[] extraArgs, targets;
1107 			version (Posix)
1108 			{
1109 				if (config.build.components.dmd.debugDMD)
1110 					extraArgs ~= "DEBUG=1";
1111 				if (config.build.components.dmd.releaseDMD)
1112 					extraArgs ~= "ENABLE_RELEASE=1";
1113 			}
1114 			else
1115 			{
1116 				if (config.build.components.dmd.debugDMD)
1117 					targets ~= [];
1118 				else
1119 				if (config.build.components.dmd.releaseDMD && dmdMakeFullName.readText().canFind("reldmd"))
1120 					targets ~= ["reldmd"];
1121 				else
1122 					targets ~= ["dmd"];
1123 			}
1124 
1125 			version (Windows)
1126 			{
1127 				if (config.build.components.dmd.dmdModel != CommonConfig.defaultModel)
1128 				{
1129 					dmdMakeFileName = "win64.mak";
1130 					dmdMakeFullName = srcDir.buildPath(dmdMakeFileName);
1131 					enforce(dmdMakeFullName.exists, "dmdModel not supported for this DMD version");
1132 					extraArgs ~= "DMODEL=-m" ~ config.build.components.dmd.dmdModel;
1133 					if (config.build.components.dmd.dmdModel == "32mscoff")
1134 					{
1135 						auto objFiles = dmdMakeFullName.readText().splitLines().filter!(line => line.startsWith("OBJ_MSVC="));
1136 						enforce(!objFiles.empty, "Can't find OBJ_MSVC in win64.mak");
1137 						extraArgs ~= "OBJ_MSVC=" ~ objFiles.front.findSplit("=")[2].split().filter!(obj => obj != "ldfpu.obj").join(" ");
1138 					}
1139 				}
1140 			}
1141 
1142 			// Avoid HOST_DC reading ~/dmd.conf
1143 			string hostDC = env.deps.hostDC;
1144 			version (Posix)
1145 			if (hostDC && needConfSwitch())
1146 			{
1147 				auto dcProxy = buildPath(config.local.workDir, "host-dc-proxy.sh");
1148 				std.file.write(dcProxy, escapeShellCommand(["exec", hostDC, "-conf=" ~ buildPath(dirName(hostDC), configFileName)]) ~ ` "$@"`);
1149 				setAttributes(dcProxy, octal!755);
1150 				hostDC = dcProxy;
1151 			}
1152 
1153 			run(getMake(env) ~ [
1154 					"-f", dmdMakeFileName,
1155 					"MODEL=" ~ modelFlag,
1156 					"HOST_DC=" ~ hostDC,
1157 				] ~ config.build.components.common.makeArgs ~ dMakeArgs ~ extraArgs ~ targets,
1158 				env.vars, srcDir
1159 			);
1160 		}
1161 
1162 		override void performStage()
1163 		{
1164 			if (config.build.components.dmd.useVC)
1165 			{
1166 				foreach (ext; [".exe", ".pdb"])
1167 					cp(
1168 						buildPath(sourceDir, "src", "vcbuild", vsPlatform, vsConfiguration, "dmd_msc" ~ ext),
1169 						buildPath(stageDir , "bin", "dmd" ~ ext),
1170 					);
1171 			}
1172 			else
1173 			{
1174 				string dmdPath = buildPath(sourceDir, "generated", platform, "release", config.build.components.dmd.dmdModel, "dmd" ~ binExt);
1175 				if (!dmdPath.exists)
1176 					dmdPath = buildPath(sourceDir, "src", "dmd" ~ binExt); // legacy
1177 				enforce(dmdPath.exists && dmdPath.isFile, "Can't find built DMD executable");
1178 
1179 				cp(
1180 					dmdPath,
1181 					buildPath(stageDir , "bin", "dmd" ~ binExt),
1182 				);
1183 			}
1184 
1185 			version (Windows)
1186 			{
1187 				auto env = baseEnvironment;
1188 				needCC(env, config.build.components.dmd.dmdModel);
1189 				foreach (model; config.build.components.common.models)
1190 					needCC(env, model);
1191 
1192 				auto ini = q"EOS
1193 [Environment]
1194 LIB=%@P%\..\lib
1195 DFLAGS="-I%@P%\..\import"
1196 DMC=__DMC__
1197 LINKCMD=%DMC%\link.exe
1198 EOS"
1199 				.replace("__DMC__", env.deps.dmcDir.buildPath(`bin`).absolutePath())
1200 			;
1201 
1202 				if (env.deps.vsDir && env.deps.sdkDir)
1203 				{
1204 					ini ~= q"EOS
1205 
1206 [Environment64]
1207 LIB=%@P%\..\lib
1208 DFLAGS=%DFLAGS% -L/OPT:NOICF
1209 VSINSTALLDIR=__VS__\
1210 VCINSTALLDIR=%VSINSTALLDIR%VC\
1211 PATH=%PATH%;%VCINSTALLDIR%\bin\__MODELDIR__;%VCINSTALLDIR%\bin
1212 WindowsSdkDir=__SDK__
1213 LINKCMD=%VCINSTALLDIR%\bin\__MODELDIR__\link.exe
1214 LIB=%LIB%;%VCINSTALLDIR%\lib\amd64
1215 LIB=%LIB%;%WindowsSdkDir%\Lib\x64
1216 
1217 [Environment32mscoff]
1218 LIB=%@P%\..\lib
1219 DFLAGS=%DFLAGS% -L/OPT:NOICF
1220 VSINSTALLDIR=__VS__\
1221 VCINSTALLDIR=%VSINSTALLDIR%VC\
1222 PATH=%PATH%;%VCINSTALLDIR%\bin
1223 WindowsSdkDir=__SDK__
1224 LINKCMD=%VCINSTALLDIR%\bin\link.exe
1225 LIB=%LIB%;%VCINSTALLDIR%\lib
1226 LIB=%LIB%;%WindowsSdkDir%\Lib
1227 EOS"
1228 						.replace("__VS__"      , env.deps.vsDir .absolutePath())
1229 						.replace("__SDK__"     , env.deps.sdkDir.absolutePath())
1230 						.replace("__MODELDIR__", msvcModelDir("64"))
1231 					;
1232 				}
1233 
1234 				buildPath(stageDir, "bin", configFileName).write(ini);
1235 			}
1236 			else version (OSX)
1237 			{
1238 				auto ini = q"EOS
1239 [Environment]
1240 DFLAGS="-I%@P%/../import" "-L-L%@P%/../lib"
1241 EOS";
1242 				buildPath(stageDir, "bin", configFileName).write(ini);
1243 			}
1244 			else version (linux)
1245 			{
1246 				auto ini = q"EOS
1247 [Environment32]
1248 DFLAGS="-I%@P%/../import" "-L-L%@P%/../lib" -L--export-dynamic
1249 
1250 [Environment64]
1251 DFLAGS="-I%@P%/../import" "-L-L%@P%/../lib" -L--export-dynamic -fPIC
1252 EOS";
1253 				buildPath(stageDir, "bin", configFileName).write(ini);
1254 			}
1255 			else
1256 			{
1257 				auto ini = q"EOS
1258 [Environment]
1259 DFLAGS="-I%@P%/../import" "-L-L%@P%/../lib" -L--export-dynamic
1260 EOS";
1261 				buildPath(stageDir, "bin", configFileName).write(ini);
1262 			}
1263 		}
1264 
1265 		override void updateEnv(ref Environment env)
1266 		{
1267 			// Add the DMD we built for Phobos/Druntime/Tools
1268 			env.vars["PATH"] = buildPath(buildDir, "bin").absolutePath() ~ pathSeparator ~ env.vars["PATH"];
1269 		}
1270 
1271 		override void performTest()
1272 		{
1273 			foreach (dep; ["dmd", "druntime", "phobos"])
1274 				getComponent(dep).needBuild(true);
1275 
1276 			foreach (model; config.build.components.common.models)
1277 			{
1278 				auto env = baseEnvironment;
1279 				version (Windows)
1280 				{
1281 					// In this order so it uses the MSYS make
1282 					needCC(env, model);
1283 					needMSYS(env);
1284 
1285 					disableCrashDialog();
1286 				}
1287 
1288 				auto makeArgs = getMake(env) ~ config.build.components.common.makeArgs ~ getPlatformMakeVars(env, model) ~ gnuMakeArgs;
1289 				version (Windows)
1290 				{
1291 					makeArgs ~= ["OS=win" ~ model[0..2], "SHELL=bash"];
1292 					if (model == "32")
1293 					{
1294 						auto extrasDir = needExtras();
1295 						// The autotester seems to pass this via environment. Why does that work there???
1296 						makeArgs ~= "LIB=" ~ extrasDir.buildPath("localextras-windows", "dmd2", "windows", "lib") ~ `;..\..\phobos`;
1297 					}
1298 					else
1299 					{
1300 						// Fix path for d_do_test and its special escaping (default is the system VS2010 install)
1301 						// We can't use the same syntax in getPlatformMakeVars because win64.mak uses "CC=\$(CC32)"\""
1302 						auto cl = env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "cl.exe");
1303 						foreach (ref arg; makeArgs)
1304 							if (arg.startsWith("CC="))
1305 								arg = "CC=" ~ dDoTestEscape(cl);
1306 					}
1307 				}
1308 
1309 				version (test)
1310 				{
1311 					// Only try a few tests during CI runs, to check for
1312 					// platform integration and correct invocation.
1313 					// For this purpose, the C++ ABI tests will do nicely.
1314 					makeArgs ~= [
1315 					//	"test_results/runnable/cppa.d.out", // https://github.com/dlang/dmd/pull/5686
1316 						"test_results/runnable/cpp_abi_tests.d.out",
1317 						"test_results/runnable/cabi1.d.out",
1318 					];
1319 				}
1320 
1321 				run(makeArgs, env.vars, sourceDir.buildPath("test"));
1322 			}
1323 		}
1324 	}
1325 
1326 	/// Phobos import files.
1327 	/// In older versions of D, Druntime depended on Phobos modules.
1328 	final class PhobosIncludes : Component
1329 	{
1330 		@property override string submoduleName() { return "phobos"; }
1331 		@property override string[] sourceDependencies() { return []; }
1332 		@property override string[] dependencies() { return []; }
1333 		@property override string configString() { return null; }
1334 
1335 		override void performStage()
1336 		{
1337 			foreach (f; ["std", "etc", "crc32.d"])
1338 				if (buildPath(sourceDir, f).exists)
1339 					cp(
1340 						buildPath(sourceDir, f),
1341 						buildPath(stageDir , "import", f),
1342 					);
1343 		}
1344 	}
1345 
1346 	/// Druntime. Installs only import files, but builds the library too.
1347 	final class Druntime : Component
1348 	{
1349 		@property override string submoduleName    () { return "druntime"; }
1350 		@property override string[] sourceDependencies() { return ["phobos", "phobos-includes"]; }
1351 		@property override string[] dependencies() { return ["dmd"]; }
1352 
1353 		@property override string configString()
1354 		{
1355 			static struct FullConfig
1356 			{
1357 				string model;
1358 				string[] makeArgs;
1359 			}
1360 
1361 			return FullConfig(
1362 				config.build.components.common.model,
1363 				config.build.components.common.makeArgs,
1364 			).toJson();
1365 		}
1366 
1367 		override void performBuild()
1368 		{
1369 			getComponent("phobos").needSource();
1370 			getComponent("dmd").needSource();
1371 			getComponent("dmd").needInstalled();
1372 			getComponent("phobos-includes").needInstalled();
1373 
1374 			foreach (model; config.build.components.common.models)
1375 			{
1376 				auto env = baseEnvironment;
1377 				needCC(env, model);
1378 
1379 				mkdirRecurse(sourceDir.buildPath("import"));
1380 				mkdirRecurse(sourceDir.buildPath("lib"));
1381 
1382 				setTimes(sourceDir.buildPath("src", "rt", "minit.obj"), Clock.currTime(), Clock.currTime()); // Don't rebuild
1383 				submodule.saveFileState("src/rt/minit.obj");
1384 
1385 				runMake(env, model, "import");
1386 				runMake(env, model);
1387 			}
1388 		}
1389 
1390 		override void performStage()
1391 		{
1392 			cp(
1393 				buildPath(sourceDir, "import"),
1394 				buildPath(stageDir , "import"),
1395 			);
1396 		}
1397 
1398 		override void performTest()
1399 		{
1400 			getComponent("druntime").needBuild(true);
1401 			getComponent("dmd").needInstalled();
1402 
1403 			foreach (model; config.build.components.common.models)
1404 			{
1405 				auto env = baseEnvironment;
1406 				needCC(env, model);
1407 				runMake(env, model, "unittest");
1408 			}
1409 		}
1410 
1411 		private final void runMake(ref Environment env, string model, string target = null)
1412 		{
1413 			// Work around https://github.com/dlang/druntime/pull/2438
1414 			bool quotePaths = !(isVersion!"Windows" && model != "32" && sourceDir.buildPath("win64.mak").readText().canFind(`"$(CC)"`));
1415 
1416 			string[] args =
1417 				getMake(env) ~
1418 				["-f", makeFileNameModel(model)] ~
1419 				(target ? [target] : []) ~
1420 				["DMD=" ~ dmd] ~
1421 				config.build.components.common.makeArgs ~
1422 				getPlatformMakeVars(env, model, quotePaths) ~
1423 				dMakeArgs;
1424 			run(args, env.vars, sourceDir);
1425 		}
1426 	}
1427 
1428 	/// Phobos library and imports.
1429 	final class Phobos : Component
1430 	{
1431 		@property override string submoduleName    () { return "phobos"; }
1432 		@property override string[] sourceDependencies() { return []; }
1433 		@property override string[] dependencies() { return ["druntime", "dmd"]; }
1434 
1435 		@property override string configString()
1436 		{
1437 			static struct FullConfig
1438 			{
1439 				string model;
1440 				string[] makeArgs;
1441 			}
1442 
1443 			return FullConfig(
1444 				config.build.components.common.model,
1445 				config.build.components.common.makeArgs,
1446 			).toJson();
1447 		}
1448 
1449 		string[] targets;
1450 
1451 		override void performBuild()
1452 		{
1453 			getComponent("dmd").needSource();
1454 			getComponent("dmd").needInstalled();
1455 			getComponent("druntime").needBuild();
1456 
1457 			targets = null;
1458 
1459 			foreach (model; config.build.components.common.models)
1460 			{
1461 				// Clean up old object files with mismatching model.
1462 				// Necessary for a consecutive 32/64 build.
1463 				version (Windows)
1464 				{
1465 					foreach (de; dirEntries(sourceDir.buildPath("etc", "c", "zlib"), "*.obj", SpanMode.shallow))
1466 					{
1467 						auto data = cast(ubyte[])read(de.name);
1468 
1469 						string fileModel;
1470 						if (data.length < 4)
1471 							fileModel = "invalid";
1472 						else
1473 						if (data[0] == 0x80)
1474 							fileModel = "32"; // OMF
1475 						else
1476 						if (data[0] == 0x01 && data[0] == 0x4C)
1477 							fileModel = "32mscoff"; // COFF - IMAGE_FILE_MACHINE_I386
1478 						else
1479 						if (data[0] == 0x86 && data[0] == 0x64)
1480 							fileModel = "64"; // COFF - IMAGE_FILE_MACHINE_AMD64
1481 						else
1482 							fileModel = "unknown";
1483 
1484 						if (fileModel != model)
1485 						{
1486 							log("Cleaning up object file '%s' with mismatching model (file is %s, building %s)".format(de.name, fileModel, model));
1487 							remove(de.name);
1488 						}
1489 					}
1490 				}
1491 
1492 				auto env = baseEnvironment;
1493 				needCC(env, model);
1494 
1495 				string phobosMakeFileName = findMakeFile(sourceDir, makeFileNameModel(model));
1496 				string phobosMakeFullName = sourceDir.buildPath(phobosMakeFileName);
1497 
1498 				version (Windows)
1499 				{
1500 					auto lib = "phobos%s.lib".format(modelSuffix(model));
1501 					runMake(env, model, lib);
1502 					enforce(sourceDir.buildPath(lib).exists);
1503 					targets ~= ["phobos%s.lib".format(modelSuffix(model))];
1504 				}
1505 				else
1506 				{
1507 					string[] makeArgs;
1508 					if (phobosMakeFullName.readText().canFind("DRUNTIME = $(DRUNTIME_PATH)/lib/libdruntime-$(OS)$(MODEL).a") &&
1509 						getComponent("druntime").sourceDir.buildPath("lib").dirEntries(SpanMode.shallow).walkLength == 0 &&
1510 						exists(getComponent("druntime").sourceDir.buildPath("generated")))
1511 					{
1512 						auto dir = getComponent("druntime").sourceDir.buildPath("generated");
1513 						auto aFile  = dir.dirEntries("libdruntime.a", SpanMode.depth);
1514 						if (!aFile .empty) makeArgs ~= ["DRUNTIME="   ~ aFile .front];
1515 						auto soFile = dir.dirEntries("libdruntime.so.a", SpanMode.depth);
1516 						if (!soFile.empty) makeArgs ~= ["DRUNTIMESO=" ~ soFile.front];
1517 					}
1518 					runMake(env, model, makeArgs);
1519 					targets ~= sourceDir
1520 						.buildPath("generated")
1521 						.dirEntries(SpanMode.depth)
1522 						.filter!(de => de.name.endsWith(".a") || de.name.endsWith(".so"))
1523 						.map!(de => de.name.relativePath(sourceDir))
1524 						.array()
1525 					;
1526 				}
1527 			}
1528 		}
1529 
1530 		override void performStage()
1531 		{
1532 			assert(targets.length, "Phobos stage without build");
1533 			foreach (lib; targets)
1534 				cp(
1535 					buildPath(sourceDir, lib),
1536 					buildPath(stageDir , "lib", lib.baseName()),
1537 				);
1538 		}
1539 
1540 		override void performTest()
1541 		{
1542 			getComponent("druntime").needBuild(true);
1543 			getComponent("phobos").needBuild(true);
1544 			getComponent("dmd").needInstalled();
1545 
1546 			foreach (model; config.build.components.common.models)
1547 			{
1548 				auto env = baseEnvironment;
1549 				needCC(env, model);
1550 				version (Windows)
1551 				{
1552 					getComponent("curl").needInstalled();
1553 					getComponent("curl").updateEnv(env);
1554 
1555 					// Patch out std.datetime unittest to work around Digger test
1556 					// suite failure on AppVeyor due to Windows time zone changes
1557 					auto stdDateTime = buildPath(sourceDir, "std", "datetime.d");
1558 					if (stdDateTime.exists && !stdDateTime.readText().canFind("Altai Standard Time"))
1559 					{
1560 						auto m = stdDateTime.readText();
1561 						m = m
1562 							.replace(`assert(tzName !is null, format("TZName which is missing: %s", winName));`, ``)
1563 							.replace(`assert(tzDatabaseNameToWindowsTZName(tzName) !is null, format("TZName which failed: %s", tzName));`, `{}`)
1564 							.replace(`assert(windowsTZNameToTZDatabaseName(tzName) !is null, format("TZName which failed: %s", tzName));`, `{}`)
1565 						;
1566 						stdDateTime.write(m);
1567 						submodule.saveFileState("std/datetime.d");
1568 					}
1569 
1570 					if (model == "32")
1571 						getComponent("extras").needInstalled();
1572 				}
1573 				runMake(env, model, "unittest");
1574 			}
1575 		}
1576 
1577 		private final void runMake(ref Environment env, string model, string[] makeArgs...)
1578 		{
1579 			// Work around https://github.com/dlang/druntime/pull/2438
1580 			bool quotePaths = !(isVersion!"Windows" && model != "32" && sourceDir.buildPath("win64.mak").readText().canFind(`"$(CC)"`));
1581 
1582 			string[] args =
1583 				getMake(env) ~
1584 				["-f", makeFileNameModel(model)] ~
1585 				makeArgs ~
1586 				["DMD=" ~ dmd] ~
1587 				config.build.components.common.makeArgs ~
1588 				getPlatformMakeVars(env, model, quotePaths) ~
1589 				dMakeArgs;
1590 			run(args, env.vars, sourceDir);
1591 		}
1592 	}
1593 
1594 	/// The rdmd build tool by itself.
1595 	/// It predates the tools package.
1596 	final class RDMD : Component
1597 	{
1598 		@property override string submoduleName() { return "tools"; }
1599 		@property override string[] sourceDependencies() { return []; }
1600 		@property override string[] dependencies() { return ["dmd", "druntime", "phobos"]; }
1601 
1602 		@property string model() { return config.build.components.common.models.get(0); }
1603 
1604 		@property override string configString()
1605 		{
1606 			static struct FullConfig
1607 			{
1608 				string model;
1609 			}
1610 
1611 			return FullConfig(
1612 				this.model,
1613 			).toJson();
1614 		}
1615 
1616 		override void performBuild()
1617 		{
1618 			foreach (dep; ["dmd", "druntime", "phobos", "phobos-includes"])
1619 				getComponent(dep).needInstalled();
1620 
1621 			auto env = baseEnvironment;
1622 			needCC(env, this.model);
1623 
1624 			// Just build rdmd
1625 			bool needModel; // Need -mXX switch?
1626 
1627 			if (sourceDir.buildPath("posix.mak").exists)
1628 				needModel = true; // Known to be needed for recent versions
1629 
1630 			string[] args;
1631 			if (needConfSwitch())
1632 				args ~= ["-conf=" ~ buildPath(buildDir , "bin", configFileName)];
1633 			args ~= ["rdmd"];
1634 
1635 			if (!needModel)
1636 				try
1637 					run([dmd] ~ args, env.vars, sourceDir);
1638 				catch (Exception e)
1639 					needModel = true;
1640 
1641 			if (needModel)
1642 				run([dmd, "-m" ~ this.model] ~ args, env.vars, sourceDir);
1643 		}
1644 
1645 		override void performStage()
1646 		{
1647 			cp(
1648 				buildPath(sourceDir, "rdmd" ~ binExt),
1649 				buildPath(stageDir , "bin", "rdmd" ~ binExt),
1650 			);
1651 		}
1652 
1653 		override void performTest()
1654 		{
1655 			auto env = baseEnvironment;
1656 			version (Windows)
1657 				needDMC(env); // Need DigitalMars Make
1658 
1659 			string[] args;
1660 			if (sourceDir.buildPath(makeFileName).readText.canFind("\ntest_rdmd"))
1661 				args = getMake(env) ~ ["-f", makeFileName, "test_rdmd", "DFLAGS=-g -m" ~ model] ~ config.build.components.common.makeArgs ~ getPlatformMakeVars(env, model) ~ dMakeArgs;
1662 			else
1663 			{
1664 				// Legacy (before makefile rules)
1665 
1666 				args = ["dmd", "-m" ~ this.model, "-run", "rdmd_test.d"];
1667 				if (sourceDir.buildPath("rdmd_test.d").readText.canFind("modelSwitch"))
1668 					args ~= "--model=" ~ this.model;
1669 				else
1670 				{
1671 					version (Windows)
1672 						if (this.model != "32")
1673 						{
1674 							// Can't test rdmd on non-32-bit Windows until compiler model matches Phobos model.
1675 							// rdmd_test does not use -m when building rdmd, thus linking will fail
1676 							// (because of model mismatch with the phobos we built).
1677 							log("Can't test rdmd with model " ~ this.model ~ ", skipping");
1678 							return;
1679 						}
1680 				}
1681 			}
1682 
1683 			foreach (dep; ["dmd", "druntime", "phobos", "phobos-includes"])
1684 				getComponent(dep).needInstalled();
1685 
1686 			getComponent("dmd").updateEnv(env);
1687 			run(args, env.vars, sourceDir);
1688 		}
1689 	}
1690 
1691 	/// Tools package with all its components, including rdmd.
1692 	final class Tools : Component
1693 	{
1694 		@property override string submoduleName() { return "tools"; }
1695 		@property override string[] sourceDependencies() { return []; }
1696 		@property override string[] dependencies() { return ["dmd", "druntime", "phobos"]; }
1697 
1698 		@property string model() { return config.build.components.common.models.get(0); }
1699 
1700 		@property override string configString()
1701 		{
1702 			static struct FullConfig
1703 			{
1704 				string model;
1705 				string[] makeArgs;
1706 			}
1707 
1708 			return FullConfig(
1709 				this.model,
1710 				config.build.components.common.makeArgs,
1711 			).toJson();
1712 		}
1713 
1714 		override void performBuild()
1715 		{
1716 			getComponent("dmd").needSource();
1717 			foreach (dep; ["dmd", "druntime", "phobos"])
1718 				getComponent(dep).needInstalled();
1719 
1720 			auto env = baseEnvironment;
1721 			needCC(env, this.model);
1722 
1723 			run(getMake(env) ~ ["-f", makeFileName, "DMD=" ~ dmd] ~ config.build.components.common.makeArgs ~ getPlatformMakeVars(env, this.model) ~ dMakeArgs, env.vars, sourceDir);
1724 		}
1725 
1726 		override void performStage()
1727 		{
1728 			foreach (os; buildPath(sourceDir, "generated").dirEntries(SpanMode.shallow))
1729 				foreach (de; os.buildPath(this.model).dirEntries(SpanMode.shallow))
1730 					if (de.extension == binExt)
1731 						cp(de, buildPath(stageDir, "bin", de.baseName));
1732 		}
1733 	}
1734 
1735 	/// Website (dlang.org). Only buildable on POSIX.
1736 	final class Website : Component
1737 	{
1738 		@property override string submoduleName() { return "dlang.org"; }
1739 		@property override string[] sourceDependencies() { return ["druntime", "phobos", "dub"]; }
1740 		@property override string[] dependencies() { return ["dmd", "druntime", "phobos", "rdmd"]; }
1741 
1742 		struct Config
1743 		{
1744 			/// Do not include timestamps, line numbers, or other
1745 			/// volatile dynamic content in generated .ddoc files.
1746 			/// Improves cache efficiency and allows meaningful diffs.
1747 			bool diffable = false;
1748 
1749 			deprecated alias noDateTime = diffable;
1750 		}
1751 
1752 		@property override string configString()
1753 		{
1754 			static struct FullConfig
1755 			{
1756 				Config config;
1757 			}
1758 
1759 			return FullConfig(
1760 				config.build.components.website,
1761 			).toJson();
1762 		}
1763 
1764 		/// Get the latest version of DMD at the time.
1765 		/// Needed for the makefile's "LATEST" parameter.
1766 		string getLatest()
1767 		{
1768 			auto dmd = getComponent("dmd").submodule;
1769 
1770 			auto t = dmd.git.query(["log", "--pretty=format:%ct"]).splitLines.map!(to!int).filter!(n => n > 0).front;
1771 
1772 			foreach (line; dmd.git.query(["log", "--decorate=full", "--tags", "--pretty=format:%ct%d"]).splitLines())
1773 				if (line.length > 10 && line[0..10].to!int < t)
1774 					if (line[10..$].startsWith(" (") && line.endsWith(")"))
1775 					{
1776 						foreach (r; line[12..$-1].split(", "))
1777 							if (r.skipOver("tag: refs/tags/"))
1778 								if (r.match(re!`^v2\.\d\d\d(\.\d)?$`))
1779 									return r[1..$];
1780 					}
1781 			throw new Exception("Can't find any DMD version tags at this point!");
1782 		}
1783 
1784 		private enum Target { build, test }
1785 
1786 		private void make(Target target)
1787 		{
1788 			foreach (dep; ["dmd", "druntime", "phobos"])
1789 			{
1790 				auto c = getComponent(dep);
1791 				c.needInstalled();
1792 
1793 				// Need DMD source because https://github.com/dlang/phobos/pull/4613#issuecomment-266462596
1794 				// Need Druntime/Phobos source because we are building its documentation from there.
1795 				c.needSource();
1796 			}
1797 			foreach (dep; ["tools", "dub"]) // for changelog; also tools for changed.d
1798 				getComponent(dep).needSource();
1799 
1800 			auto env = baseEnvironment;
1801 
1802 			version (Windows)
1803 				throw new Exception("The dlang.org website is only buildable on POSIX platforms.");
1804 			else
1805 			{
1806 				getComponent("dmd").updateEnv(env);
1807 
1808 				// Need an in-tree build for SYSCONFDIR.imp, which is
1809 				// needed to parse .d files for the DMD API
1810 				// documentation.
1811 				getComponent("dmd").needBuild(target == Target.test);
1812 
1813 				needKindleGen(env);
1814 
1815 				foreach (dep; dependencies)
1816 					getComponent(dep).submodule.clean = false;
1817 
1818 				auto makeFullName = sourceDir.buildPath(makeFileName);
1819 				auto makeSrc = makeFullName.readText();
1820 				makeSrc
1821 					// https://github.com/D-Programming-Language/dlang.org/pull/1011
1822 					.replace(": modlist.d", ": modlist.d $(DMD)")
1823 					// https://github.com/D-Programming-Language/dlang.org/pull/1017
1824 					.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=")
1825 					.toFile(makeFullName)
1826 				;
1827 				submodule.saveFileState(makeFileName);
1828 
1829 				// Retroactive OpenSSL 1.1.0 fix
1830 				// See https://github.com/dlang/dlang.org/pull/1654
1831 				auto dubJson = sourceDir.buildPath("dpl-docs/dub.json");
1832 				dubJson
1833 					.readText()
1834 					.replace(`"versions": ["VibeCustomMain"]`, `"versions": ["VibeCustomMain", "VibeNoSSL"]`)
1835 					.toFile(dubJson);
1836 				submodule.saveFileState("dpl-docs/dub.json");
1837 				scope(exit) submodule.saveFileState("dpl-docs/dub.selections.json");
1838 
1839 				string latest = null;
1840 				if (!sourceDir.buildPath("VERSION").exists)
1841 				{
1842 					latest = getLatest();
1843 					log("LATEST=" ~ latest);
1844 				}
1845 				else
1846 					log("VERSION file found, not passing LATEST parameter");
1847 
1848 				string[] diffable = null;
1849 
1850 				auto pdf = makeSrc.indexOf("pdf") >= 0 ? ["pdf"] : [];
1851 
1852 				string[] targets =
1853 					[
1854 						config.build.components.website.diffable
1855 						? makeSrc.indexOf("dautotest") >= 0
1856 							? ["dautotest"]
1857 							: ["all", "verbatim"] ~ pdf ~ (
1858 								makeSrc.indexOf("diffable-intermediaries") >= 0
1859 								? ["diffable-intermediaries"]
1860 								: ["dlangspec.html"])
1861 						: ["all", "verbatim", "kindle"] ~ pdf,
1862 						["test"]
1863 					][target];
1864 
1865 				if (config.build.components.website.diffable)
1866 				{
1867 					if (makeSrc.indexOf("DIFFABLE") >= 0)
1868 						diffable = ["DIFFABLE=1"];
1869 					else
1870 						diffable = ["NODATETIME=nodatetime.ddoc"];
1871 
1872 					env.vars["SOURCE_DATE_EPOCH"] = "0";
1873 				}
1874 
1875 				auto args =
1876 					getMake(env) ~
1877 					[ "-f", makeFileName ] ~
1878 					diffable ~
1879 					(latest ? ["LATEST=" ~ latest] : []) ~
1880 					targets ~
1881 					gnuMakeArgs;
1882 				run(args, env.vars, sourceDir);
1883 			}
1884 		}
1885 
1886 		override void performBuild()
1887 		{
1888 			make(Target.build);
1889 		}
1890 
1891 		override void performTest()
1892 		{
1893 			make(Target.test);
1894 		}
1895 
1896 		override void performStage()
1897 		{
1898 			foreach (item; ["web", "dlangspec.tex", "dlangspec.html"])
1899 			{
1900 				auto src = buildPath(sourceDir, item);
1901 				auto dst = buildPath(stageDir , item);
1902 				if (src.exists)
1903 					cp(src, dst);
1904 			}
1905 		}
1906 	}
1907 
1908 	/// Extras not built from source (DigitalMars and third-party tools and libraries)
1909 	final class Extras : Component
1910 	{
1911 		@property override string submoduleName() { return null; }
1912 		@property override string[] sourceDependencies() { return []; }
1913 		@property override string[] dependencies() { return []; }
1914 		@property override string configString() { return null; }
1915 
1916 		override void performBuild()
1917 		{
1918 			needExtras();
1919 		}
1920 
1921 		override void performStage()
1922 		{
1923 			auto extrasDir = needExtras();
1924 
1925 			void copyDir(string source, string target)
1926 			{
1927 				source = buildPath(extrasDir, "localextras-" ~ platform, "dmd2", platform, source);
1928 				target = buildPath(stageDir, target);
1929 				if (source.exists)
1930 					cp(source, target);
1931 			}
1932 
1933 			copyDir("bin", "bin");
1934 			foreach (model; config.build.components.common.models)
1935 				copyDir("bin" ~ model, "bin");
1936 			copyDir("lib", "lib");
1937 
1938 			version (Windows)
1939 				foreach (model; config.build.components.common.models)
1940 					if (model == "32")
1941 					{
1942 						// The version of snn.lib bundled with DMC will be newer.
1943 						Environment env;
1944 						needDMC(env);
1945 						cp(buildPath(env.deps.dmcDir, "lib", "snn.lib"), buildPath(stageDir, "lib", "snn.lib"));
1946 					}
1947 		}
1948 	}
1949 
1950 	/// libcurl DLL and import library for Windows.
1951 	final class Curl : Component
1952 	{
1953 		@property override string submoduleName() { return null; }
1954 		@property override string[] sourceDependencies() { return []; }
1955 		@property override string[] dependencies() { return []; }
1956 		@property override string configString() { return null; }
1957 
1958 		override void performBuild()
1959 		{
1960 			version (Windows)
1961 				needCurl();
1962 			else
1963 				log("Not on Windows, skipping libcurl download");
1964 		}
1965 
1966 		override void performStage()
1967 		{
1968 			version (Windows)
1969 			{
1970 				auto curlDir = needCurl();
1971 
1972 				void copyDir(string source, string target)
1973 				{
1974 					source = buildPath(curlDir, "dmd2", "windows", source);
1975 					target = buildPath(stageDir, target);
1976 					if (source.exists)
1977 						cp(source, target);
1978 				}
1979 
1980 				foreach (model; config.build.components.common.models)
1981 				{
1982 					auto suffix = model == "64" ? "64" : "";
1983 					copyDir("bin" ~ suffix, "bin");
1984 					copyDir("lib" ~ suffix, "lib");
1985 				}
1986 			}
1987 			else
1988 				log("Not on Windows, skipping libcurl install");
1989 		}
1990 
1991 		override void updateEnv(ref Environment env)
1992 		{
1993 			env.vars["PATH"] = buildPath(buildDir, "bin").absolutePath() ~ pathSeparator ~ env.vars["PATH"];
1994 		}
1995 	}
1996 
1997 	/// The Dub package manager and build tool
1998 	final class Dub : Component
1999 	{
2000 		@property override string submoduleName() { return "dub"; }
2001 		@property override string[] sourceDependencies() { return []; }
2002 		@property override string[] dependencies() { return []; }
2003 		@property override string configString() { return null; }
2004 
2005 		override void performBuild()
2006 		{
2007 			auto env = baseEnvironment;
2008 			run([dmd, "-i", "-run", "build.d"], env.vars, sourceDir);
2009 		}
2010 
2011 		override void performStage()
2012 		{
2013 			cp(
2014 				buildPath(sourceDir, "bin", "dub" ~ binExt),
2015 				buildPath(stageDir , "bin", "dub" ~ binExt),
2016 			);
2017 		}
2018 	}
2019 
2020 	private int tempError;
2021 
2022 	private Component[string] components;
2023 
2024 	Component getComponent(string name)
2025 	{
2026 		if (name !in components)
2027 		{
2028 			Component c;
2029 
2030 			switch (name)
2031 			{
2032 				case "dmd":
2033 					c = new DMD();
2034 					break;
2035 				case "phobos-includes":
2036 					c = new PhobosIncludes();
2037 					break;
2038 				case "druntime":
2039 					c = new Druntime();
2040 					break;
2041 				case "phobos":
2042 					c = new Phobos();
2043 					break;
2044 				case "rdmd":
2045 					c = new RDMD();
2046 					break;
2047 				case "tools":
2048 					c = new Tools();
2049 					break;
2050 				case "website":
2051 					c = new Website();
2052 					break;
2053 				case "extras":
2054 					c = new Extras();
2055 					break;
2056 				case "curl":
2057 					c = new Curl();
2058 					break;
2059 				case "dub":
2060 					c = new Dub();
2061 					break;
2062 				default:
2063 					throw new Exception("Unknown component: " ~ name);
2064 			}
2065 
2066 			c.name = name;
2067 			return components[name] = c;
2068 		}
2069 
2070 		return components[name];
2071 	}
2072 
2073 	Component[] getSubmoduleComponents(string submoduleName)
2074 	{
2075 		return components
2076 			.byValue
2077 			.filter!(component => component.submoduleName == submoduleName)
2078 			.array();
2079 	}
2080 
2081 	// ***************************** GitHub API ******************************
2082 
2083 	GitHub github;
2084 
2085 	ref GitHub needGitHub()
2086 	{
2087 		if (github is GitHub.init)
2088 		{
2089 			github.log = &this.log;
2090 			github.token = config.local.githubToken;
2091 			github.cache = new class GitHub.ICache
2092 			{
2093 				final string cacheFileName(string key)
2094 				{
2095 					return githubDir.buildPath(getDigestString!MD5(key).toLower());
2096 				}
2097 
2098 				string get(string key)
2099 				{
2100 					auto fn = cacheFileName(key);
2101 					return fn.exists ? fn.readText : null;
2102 				}
2103 
2104 				void put(string key, string value)
2105 				{
2106 					githubDir.ensureDirExists;
2107 					std.file.write(cacheFileName(key), value);
2108 				}
2109 			};
2110 		}
2111 		return github;
2112 	}
2113 
2114 	// **************************** Customization ****************************
2115 
2116 	/// Fetch latest D history.
2117 	/// Return true if any updates were fetched.
2118 	bool update()
2119 	{
2120 		return getMetaRepo().update();
2121 	}
2122 
2123 	struct SubmoduleState
2124 	{
2125 		string[string] submoduleCommits;
2126 	}
2127 
2128 	/// Begin customization, starting at the specified commit.
2129 	SubmoduleState begin(string commit)
2130 	{
2131 		log("Starting at meta repository commit " ~ commit);
2132 		return SubmoduleState(getMetaRepo().getSubmoduleCommits(commit));
2133 	}
2134 
2135 	alias MergeMode = ManagedRepository.MergeMode;
2136 
2137 	/// Applies a merge onto the given SubmoduleState.
2138 	void merge(ref SubmoduleState submoduleState, string submoduleName, string[2] branch, MergeMode mode)
2139 	{
2140 		log("Merging %s commits %s..%s".format(submoduleName, branch[0], branch[1]));
2141 		enforce(submoduleName in submoduleState.submoduleCommits, "Unknown submodule: " ~ submoduleName);
2142 		auto submodule = getSubmodule(submoduleName);
2143 		auto head = submoduleState.submoduleCommits[submoduleName];
2144 		auto result = submodule.getMerge(head, branch, mode);
2145 		submoduleState.submoduleCommits[submoduleName] = result;
2146 	}
2147 
2148 	/// Removes a merge from the given SubmoduleState.
2149 	void unmerge(ref SubmoduleState submoduleState, string submoduleName, string[2] branch, MergeMode mode)
2150 	{
2151 		log("Unmerging %s commits %s..%s".format(submoduleName, branch[0], branch[1]));
2152 		enforce(submoduleName in submoduleState.submoduleCommits, "Unknown submodule: " ~ submoduleName);
2153 		auto submodule = getSubmodule(submoduleName);
2154 		auto head = submoduleState.submoduleCommits[submoduleName];
2155 		auto result = submodule.getUnMerge(head, branch, mode);
2156 		submoduleState.submoduleCommits[submoduleName] = result;
2157 	}
2158 
2159 	/// Reverts a commit from the given SubmoduleState.
2160 	/// parent is the 1-based mainline index (as per `man git-revert`),
2161 	/// or 0 if commit is not a merge commit.
2162 	void revert(ref SubmoduleState submoduleState, string submoduleName, string[2] branch, MergeMode mode)
2163 	{
2164 		log("Reverting %s commits %s..%s".format(submoduleName, branch[0], branch[1]));
2165 		enforce(submoduleName in submoduleState.submoduleCommits, "Unknown submodule: " ~ submoduleName);
2166 		auto submodule = getSubmodule(submoduleName);
2167 		auto head = submoduleState.submoduleCommits[submoduleName];
2168 		auto result = submodule.getRevert(head, branch, mode);
2169 		submoduleState.submoduleCommits[submoduleName] = result;
2170 	}
2171 
2172 	/// Returns the commit hash for the given pull request # (base and tip).
2173 	/// The result can then be used with addMerge/removeMerge.
2174 	string[2] getPull(string submoduleName, int pullNumber)
2175 	{
2176 		auto tip = getSubmodule(submoduleName).getPullTip(pullNumber);
2177 		auto pull = needGitHub().query("https://api.github.com/repos/%s/%s/pulls/%d"
2178 			.format("dlang", submoduleName, pullNumber)).data.parseJSON;
2179 		auto base = pull["base"]["sha"].str;
2180 		return [base, tip];
2181 	}
2182 
2183 	/// Returns the commit hash for the given branch (optionally GitHub fork).
2184 	/// The result can then be used with addMerge/removeMerge.
2185 	string[2] getBranch(string submoduleName, string user, string base, string tip)
2186 	{
2187 		return getSubmodule(submoduleName).getBranch(user, base, tip);
2188 	}
2189 
2190 	// ****************************** Building *******************************
2191 
2192 	private SubmoduleState submoduleState;
2193 	private bool incrementalBuild;
2194 
2195 	@property string cacheEngineName()
2196 	{
2197 		if (incrementalBuild)
2198 			return "none";
2199 		else
2200 			return config.local.cache;
2201 	}
2202 
2203 	private string getComponentCommit(string componentName)
2204 	{
2205 		auto submoduleName = getComponent(componentName).submoduleName;
2206 		auto commit = submoduleState.submoduleCommits.get(submoduleName, null);
2207 		enforce(commit, "Unknown commit to build for component %s (submodule %s)"
2208 			.format(componentName, submoduleName));
2209 		return commit;
2210 	}
2211 
2212 	static const string[] defaultComponents = ["dmd", "druntime", "phobos-includes", "phobos", "rdmd"];
2213 	static const string[] additionalComponents = ["tools", "website", "extras", "curl", "dub"];
2214 	static const string[] allComponents = defaultComponents ~ additionalComponents;
2215 
2216 	/// Build the specified components according to the specified configuration.
2217 	void build(SubmoduleState submoduleState, bool incremental = false)
2218 	{
2219 		auto componentNames = config.build.components.getEnabledComponentNames();
2220 		log("Building components %-(%s, %)".format(componentNames));
2221 
2222 		this.components = null;
2223 		this.submoduleState = submoduleState;
2224 		this.incrementalBuild = incremental;
2225 
2226 		if (buildDir.exists)
2227 			buildDir.removeRecurse();
2228 		enforce(!buildDir.exists);
2229 
2230 		scope(exit) if (cacheEngine) cacheEngine.finalize();
2231 
2232 		foreach (componentName; componentNames)
2233 			getComponent(componentName).needInstalled();
2234 	}
2235 
2236 	/// Shortcut for begin + build
2237 	void buildRev(string rev)
2238 	{
2239 		auto submoduleState = begin(rev);
2240 		build(submoduleState);
2241 	}
2242 
2243 	/// Simply check out the source code for the given submodules.
2244 	void checkout(SubmoduleState submoduleState)
2245 	{
2246 		auto componentNames = config.build.components.getEnabledComponentNames();
2247 		log("Checking out components %-(%s, %)".format(componentNames));
2248 
2249 		this.components = null;
2250 		this.submoduleState = submoduleState;
2251 		this.incrementalBuild = false;
2252 
2253 		foreach (componentName; componentNames)
2254 			getComponent(componentName).needSource(true);
2255 	}
2256 
2257 	/// Rerun build without cleaning up any files.
2258 	void rebuild()
2259 	{
2260 		build(SubmoduleState(null), true);
2261 	}
2262 
2263 	/// Run all tests for the current checkout (like rebuild).
2264 	void test(bool incremental = true)
2265 	{
2266 		auto componentNames = config.build.components.getEnabledComponentNames();
2267 		log("Testing components %-(%s, %)".format(componentNames));
2268 
2269 		if (incremental)
2270 		{
2271 			this.components = null;
2272 			this.submoduleState = SubmoduleState(null);
2273 			this.incrementalBuild = true;
2274 		}
2275 
2276 		foreach (componentName; componentNames)
2277 			getComponent(componentName).test();
2278 	}
2279 
2280 	bool isCached(SubmoduleState submoduleState)
2281 	{
2282 		this.components = null;
2283 		this.submoduleState = submoduleState;
2284 
2285 		needCacheEngine();
2286 		foreach (componentName; config.build.components.getEnabledComponentNames())
2287 			if (!cacheEngine.haveEntry(getComponent(componentName).getBuildID()))
2288 				return false;
2289 		return true;
2290 	}
2291 
2292 	/// Returns the isCached state for all commits in the history of the given ref.
2293 	bool[string] getCacheState(string[string][string] history)
2294 	{
2295 		log("Enumerating cache entries...");
2296 		auto cacheEntries = needCacheEngine().getEntries().toSet();
2297 
2298 		this.components = null;
2299 		auto componentNames = config.build.components.getEnabledComponentNames();
2300 		auto components = componentNames.map!(componentName => getComponent(componentName)).array;
2301 		auto requiredSubmodules = components
2302 			.map!(component => chain(component.name.only, component.sourceDependencies, component.dependencies))
2303 			.joiner
2304 			.map!(componentName => getComponent(componentName).submoduleName)
2305 			.array.sort().uniq().array
2306 		;
2307 
2308 		log("Collating cache state...");
2309 		bool[string] result;
2310 		foreach (commit, submoduleCommits; history)
2311 		{
2312 			import ae.utils.meta : I;
2313 			this.submoduleState.submoduleCommits = submoduleCommits;
2314 			result[commit] =
2315 				requiredSubmodules.all!(submoduleName => submoduleName in submoduleCommits) &&
2316 				componentNames.all!(componentName =>
2317 					getComponent(componentName).I!(component =>
2318 						component.getBuildID() in cacheEntries
2319 					)
2320 				);
2321 		}
2322 		return result;
2323 	}
2324 
2325 	/// ditto
2326 	bool[string] getCacheState(string[] refs)
2327 	{
2328 		auto history = getMetaRepo().getSubmoduleHistory(refs);
2329 		return getCacheState(history);
2330 	}
2331 
2332 	// **************************** Dependencies *****************************
2333 
2334 	private void needInstaller()
2335 	{
2336 		Installer.logger = &log;
2337 		Installer.installationDirectory = dlDir;
2338 	}
2339 
2340 	/// Pull in a built DMD as configured.
2341 	/// Note that this function invalidates the current repository state.
2342 	void needDMD(ref Environment env, string dmdVer)
2343 	{
2344 		tempError++; scope(success) tempError--;
2345 
2346 		// User setting overrides autodetection
2347 		if (config.build.components.dmd.bootstrap.ver)
2348 			dmdVer = config.build.components.dmd.bootstrap.ver;
2349 
2350 		if (config.build.components.dmd.bootstrap.fromSource)
2351 		{
2352 			log("Bootstrapping DMD " ~ dmdVer);
2353 
2354 			auto bootstrapBuildConfig = config.build.components.dmd.bootstrap.build;
2355 
2356 			// Back up and clear component state
2357 			enum backupTemplate = q{
2358 				auto VARBackup = this.VAR;
2359 				this.VAR = typeof(VAR).init;
2360 				scope(exit) this.VAR = VARBackup;
2361 			};
2362 			mixin(backupTemplate.replace(q{VAR}, q{components}));
2363 			mixin(backupTemplate.replace(q{VAR}, q{config}));
2364 			mixin(backupTemplate.replace(q{VAR}, q{submoduleState}));
2365 
2366 			config.local = configBackup.local;
2367 			if (bootstrapBuildConfig)
2368 				config.build = *bootstrapBuildConfig;
2369 
2370 			// Disable building rdmd in the bootstrap compiler by default
2371 			if ("rdmd" !in config.build.components.enable)
2372 				config.build.components.enable["rdmd"] = false;
2373 
2374 			build(parseSpec(dmdVer));
2375 
2376 			log("Built bootstrap DMD " ~ dmdVer ~ " successfully.");
2377 
2378 			auto bootstrapDir = buildPath(config.local.workDir, "bootstrap");
2379 			if (bootstrapDir.exists)
2380 				bootstrapDir.removeRecurse();
2381 			ensurePathExists(bootstrapDir);
2382 			rename(buildDir, bootstrapDir);
2383 
2384 			env.deps.hostDC = buildPath(bootstrapDir, "bin", "dmd" ~ binExt);
2385 		}
2386 		else
2387 		{
2388 			import std.ascii;
2389 			log("Preparing DMD " ~ dmdVer);
2390 			enforce(dmdVer.startsWith("v"), "Invalid DMD version spec for binary bootstrap. Did you forget to " ~
2391 				((dmdVer.length && dmdVer[0].isDigit && dmdVer.contains('.')) ? "add a leading 'v'" : "enable fromSource") ~ "?");
2392 			needInstaller();
2393 			auto dmdInstaller = new DMDInstaller(dmdVer[1..$]);
2394 			dmdInstaller.requireLocal(false);
2395 			env.deps.hostDC = dmdInstaller.exePath("dmd").absolutePath();
2396 		}
2397 
2398 		log("hostDC=" ~ env.deps.hostDC);
2399 	}
2400 
2401 	void needKindleGen(ref Environment env)
2402 	{
2403 		needInstaller();
2404 		kindleGenInstaller.requireLocal(false);
2405 		env.vars["PATH"] = kindleGenInstaller.directory ~ pathSeparator ~ env.vars["PATH"];
2406 	}
2407 
2408 	version (Windows)
2409 	void needMSYS(ref Environment env)
2410 	{
2411 		needInstaller();
2412 		MSYS.msysCORE.requireLocal(false);
2413 		MSYS.libintl.requireLocal(false);
2414 		MSYS.libiconv.requireLocal(false);
2415 		MSYS.libtermcap.requireLocal(false);
2416 		MSYS.libregex.requireLocal(false);
2417 		MSYS.coreutils.requireLocal(false);
2418 		MSYS.bash.requireLocal(false);
2419 		MSYS.make.requireLocal(false);
2420 		MSYS.grep.requireLocal(false);
2421 		MSYS.sed.requireLocal(false);
2422 		MSYS.diffutils.requireLocal(false);
2423 		env.vars["PATH"] = MSYS.bash.directory.buildPath("bin") ~ pathSeparator ~ env.vars["PATH"];
2424 	}
2425 
2426 	/// Get DMD unbuildable extras
2427 	/// (proprietary DigitalMars utilities, 32-bit import libraries)
2428 	string needExtras()
2429 	{
2430 		import ae.utils.meta : I, singleton;
2431 
2432 		static class DExtrasInstaller : Installer
2433 		{
2434 			@property override string name() { return "dmd-localextras"; }
2435 			string url = "http://semitwist.com/download/app/dmd-localextras.7z";
2436 
2437 			override void installImpl(string target)
2438 			{
2439 				url
2440 					.I!save()
2441 					.I!unpackTo(target);
2442 			}
2443 
2444 			static this()
2445 			{
2446 				urlDigests["http://semitwist.com/download/app/dmd-localextras.7z"] = "ef367c2d25d4f19f45ade56ab6991c726b07d3d9";
2447 			}
2448 		}
2449 
2450 		alias extrasInstaller = singleton!DExtrasInstaller;
2451 
2452 		needInstaller();
2453 		extrasInstaller.requireLocal(false);
2454 		return extrasInstaller.directory;
2455 	}
2456 
2457 	/// Get libcurl for Windows (DLL and import libraries)
2458 	version (Windows)
2459 	string needCurl()
2460 	{
2461 		import ae.utils.meta : I, singleton;
2462 
2463 		static class DCurlInstaller : Installer
2464 		{
2465 			@property override string name() { return "libcurl-" ~ curlVersion; }
2466 			string curlVersion = "7.47.1";
2467 			@property string url() { return "http://downloads.dlang.org/other/libcurl-" ~ curlVersion ~ "-WinSSL-zlib-x86-x64.zip"; }
2468 
2469 			override void installImpl(string target)
2470 			{
2471 				url
2472 					.I!save()
2473 					.I!unpackTo(target);
2474 			}
2475 
2476 			static this()
2477 			{
2478 				urlDigests["http://downloads.dlang.org/other/libcurl-7.47.1-WinSSL-zlib-x86-x64.zip"] = "4b8a7bb237efab25a96588093ae51994c821e097";
2479 			}
2480 		}
2481 
2482 		alias curlInstaller = singleton!DCurlInstaller;
2483 
2484 		needInstaller();
2485 		curlInstaller.requireLocal(false);
2486 		return curlInstaller.directory;
2487 	}
2488 
2489 	version (Windows)
2490 	void needDMC(ref Environment env, string ver = null)
2491 	{
2492 		tempError++; scope(success) tempError--;
2493 
2494 		needInstaller();
2495 
2496 		auto dmc = ver ? new LegacyDMCInstaller(ver) : dmcInstaller;
2497 		if (!dmc.installedLocally)
2498 			log("Preparing DigitalMars C++ " ~ ver);
2499 		dmc.requireLocal(false);
2500 		env.deps.dmcDir = dmc.directory;
2501 
2502 		auto binPath = buildPath(env.deps.dmcDir, `bin`).absolutePath();
2503 		log("DMC=" ~ binPath);
2504 		env.vars["DMC"] = binPath;
2505 		env.vars["PATH"] = binPath ~ pathSeparator ~ env.vars.get("PATH", null);
2506 	}
2507 
2508 	version (Windows)
2509 	auto getVSInstaller()
2510 	{
2511 		needInstaller();
2512 		return vs2013community;
2513 	}
2514 
2515 	version (Windows)
2516 	static string msvcModelStr(string model, string str32, string str64)
2517 	{
2518 		switch (model)
2519 		{
2520 			case "32":
2521 				throw new Exception("Shouldn't need VC for 32-bit builds");
2522 			case "64":
2523 				return str64;
2524 			case "32mscoff":
2525 				return str32;
2526 			default:
2527 				throw new Exception("Unknown model: " ~ model);
2528 		}
2529 	}
2530 
2531 	version (Windows)
2532 	static string msvcModelDir(string model, string dir64 = "x86_amd64")
2533 	{
2534 		return msvcModelStr(model, null, dir64);
2535 	}
2536 
2537 	version (Windows)
2538 	void needVC(ref Environment env, string model)
2539 	{
2540 		tempError++; scope(success) tempError--;
2541 
2542 		auto vs = getVSInstaller();
2543 
2544 		// At minimum, we want the C compiler (cl.exe) and linker (link.exe).
2545 		vs["vc_compilercore86"].requireLocal(false); // Contains both x86 and x86_amd64 cl.exe
2546 		vs["vc_compilercore86res"].requireLocal(false); // Contains clui.dll needed by cl.exe
2547 
2548 		// Include files. Needed when using VS to build either DMD or Druntime.
2549 		vs["vc_librarycore86"].requireLocal(false); // Contains include files, e.g. errno.h needed by Druntime
2550 
2551 		// C runtime. Needed for all programs built with VC.
2552 		vs[msvcModelStr(model, "vc_libraryDesktop_x86", "vc_libraryDesktop_x64")].requireLocal(false); // libcmt.lib
2553 
2554 		// XP-compatible import libraries.
2555 		vs["win_xpsupport"].requireLocal(false); // shell32.lib
2556 
2557 		// MSBuild, for the useVC option
2558 		if (config.build.components.dmd.useVC)
2559 			vs["Msi_BuildTools_MSBuild_x86"].requireLocal(false); // msbuild.exe
2560 
2561 		env.deps.vsDir  = vs.directory.buildPath("Program Files (x86)", "Microsoft Visual Studio 12.0").absolutePath();
2562 		env.deps.sdkDir = vs.directory.buildPath("Program Files", "Microsoft SDKs", "Windows", "v7.1A").absolutePath();
2563 
2564 		env.vars["PATH"] ~= pathSeparator ~ vs.modelBinPaths(msvcModelDir(model)).map!(path => vs.directory.buildPath(path).absolutePath()).join(pathSeparator);
2565 		env.vars["VisualStudioVersion"] = "12"; // Work-around for problem fixed in dmd 38da6c2258c0ff073b0e86e0a1f6ba190f061e5e
2566 		env.vars["VSINSTALLDIR"] = env.deps.vsDir ~ dirSeparator; // ditto
2567 		env.vars["VCINSTALLDIR"] = env.deps.vsDir.buildPath("VC") ~ dirSeparator;
2568 		env.vars["INCLUDE"] = env.deps.vsDir.buildPath("VC", "include") ~ ";" ~ env.deps.sdkDir.buildPath("Include");
2569 		env.vars["LIB"] = env.deps.vsDir.buildPath("VC", "lib", msvcModelDir(model, "amd64")) ~ ";" ~ env.deps.sdkDir.buildPath("Lib", msvcModelDir(model, "x64"));
2570 		env.vars["WindowsSdkDir"] = env.deps.sdkDir ~ dirSeparator;
2571 		env.vars["Platform"] = "x64";
2572 		env.vars["LINKCMD64"] = env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "link.exe"); // Used by dmd
2573 		env.vars["MSVC_CC"] = env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "cl.exe"); // For the msvc-dmc wrapper
2574 		env.vars["MSVC_AR"] = env.deps.vsDir.buildPath("VC", "bin", msvcModelDir(model), "lib.exe"); // For the msvc-lib wrapper
2575 		env.vars["CL"] = "-D_USING_V110_SDK71_"; // Work around __userHeader macro redifinition VS bug
2576 	}
2577 
2578 	private void needGit()
2579 	{
2580 		tempError++; scope(success) tempError--;
2581 
2582 		needInstaller();
2583 		gitInstaller.require();
2584 	}
2585 
2586 	/// Disable the "<program> has stopped working"
2587 	/// standard Windows dialog.
2588 	version (Windows)
2589 	static void disableCrashDialog()
2590 	{
2591 		enum : uint { SEM_FAILCRITICALERRORS = 1, SEM_NOGPFAULTERRORBOX = 2 }
2592 		SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
2593 	}
2594 
2595 	/// Create a build environment base.
2596 	protected @property Environment baseEnvironment()
2597 	{
2598 		Environment env;
2599 
2600 		// Build a new environment from scratch, to avoid tainting the build with the current environment.
2601 		string[] newPaths;
2602 
2603 		version (Windows)
2604 		{
2605 			import std.utf;
2606 			import ae.sys.windows.imports;
2607 			mixin(importWin32!q{winbase});
2608 			mixin(importWin32!q{winnt});
2609 
2610 			TCHAR[1024] buf;
2611 			// Needed for DLLs
2612 			auto winDir = buf[0..GetWindowsDirectory(buf.ptr, buf.length)].toUTF8();
2613 			auto sysDir = buf[0..GetSystemDirectory (buf.ptr, buf.length)].toUTF8();
2614 			newPaths ~= [sysDir, winDir];
2615 
2616 			newPaths ~= gitInstaller.exePath("git").absolutePath().dirName; // For git-describe and such
2617 		}
2618 		else
2619 		{
2620 			// Needed for coreutils, make, gcc, git etc.
2621 			newPaths = ["/bin", "/usr/bin", "/usr/local/bin"];
2622 
2623 			version (linux)
2624 			{
2625 				// GCC wrappers
2626 				ensureDirExists(binDir);
2627 				newPaths = binDir ~ newPaths;
2628 			}
2629 		}
2630 
2631 		env.vars["PATH"] = newPaths.join(pathSeparator);
2632 
2633 		ensureDirExists(tmpDir);
2634 		env.vars["TMPDIR"] = env.vars["TEMP"] = env.vars["TMP"] = tmpDir;
2635 
2636 		version (Windows)
2637 		{
2638 			env.vars["SystemDrive"] = winDir.driveName;
2639 			env.vars["SystemRoot"] = winDir;
2640 		}
2641 
2642 		ensureDirExists(homeDir);
2643 		env.vars["HOME"] = homeDir;
2644 
2645 		return env;
2646 	}
2647 
2648 	/// Apply user modifications onto an environment.
2649 	/// Supports Windows-style %VAR% expansions.
2650 	static string[string] applyEnv(in string[string] target, in string[string] source)
2651 	{
2652 		// The source of variable expansions is variables in the target environment,
2653 		// if they exist, and the host environment otherwise, so e.g.
2654 		// `PATH=C:\...;%PATH%` and `MAKE=%MAKE%` work as expected.
2655 		auto oldEnv = std.process.environment.toAA();
2656 		foreach (name, value; target)
2657 			oldEnv[name] = value;
2658 
2659 		string[string] result;
2660 		foreach (name, value; target)
2661 			result[name] = value;
2662 		foreach (name, value; source)
2663 		{
2664 			string newValue = value;
2665 			foreach (oldName, oldValue; oldEnv)
2666 				newValue = newValue.replace("%" ~ oldName ~ "%", oldValue);
2667 			result[name] = oldEnv[name] = newValue;
2668 		}
2669 		return result;
2670 	}
2671 
2672 	// ******************************** Cache ********************************
2673 
2674 	enum unbuildableMarker = "unbuildable";
2675 
2676 	DCache cacheEngine;
2677 
2678 	DCache needCacheEngine()
2679 	{
2680 		if (!cacheEngine)
2681 		{
2682 			if (cacheEngineName == "git")
2683 				needGit();
2684 			cacheEngine = createCache(cacheEngineName, cacheEngineDir(cacheEngineName), this);
2685 		}
2686 		return cacheEngine;
2687 	}
2688 
2689 	void cp(string src, string dst)
2690 	{
2691 		needCacheEngine().cp(src, dst);
2692 	}
2693 
2694 	private string[] getComponentKeyOrder(string componentName)
2695 	{
2696 		auto submodule = getComponent(componentName).submodule;
2697 		return submodule
2698 			.git.query("log", "--pretty=format:%H", "--all", "--topo-order")
2699 			.splitLines()
2700 			.map!(commit => componentName ~ "-" ~ commit ~ "-")
2701 			.array
2702 		;
2703 	}
2704 
2705 	string componentNameFromKey(string key)
2706 	{
2707 		auto parts = key.split("-");
2708 		return parts[0..$-2].join("-");
2709 	}
2710 
2711 	string[][] getKeyOrder(string key)
2712 	{
2713 		if (key !is null)
2714 			return [getComponentKeyOrder(componentNameFromKey(key))];
2715 		else
2716 			return allComponents.map!(componentName => getComponentKeyOrder(componentName)).array;
2717 	}
2718 
2719 	/// Optimize entire cache.
2720 	void optimizeCache()
2721 	{
2722 		needCacheEngine().optimize();
2723 	}
2724 
2725 	bool shouldPurge(string key)
2726 	{
2727 		auto files = cacheEngine.listFiles(key);
2728 		if (files.canFind(unbuildableMarker))
2729 			return true;
2730 
2731 		if (componentNameFromKey(key) == "druntime")
2732 		{
2733 			if (!files.canFind("import/core/memory.d")
2734 			 && !files.canFind("import/core/memory.di"))
2735 				return true;
2736 		}
2737 
2738 		return false;
2739 	}
2740 
2741 	/// Delete cached "unbuildable" build results.
2742 	void purgeUnbuildable()
2743 	{
2744 		needCacheEngine()
2745 			.getEntries
2746 			.filter!(key => shouldPurge(key))
2747 			.each!((key)
2748 			{
2749 				log("Deleting: " ~ key);
2750 				cacheEngine.remove(key);
2751 			})
2752 		;
2753 	}
2754 
2755 	/// Move cached files from one cache engine to another.
2756 	void migrateCache(string sourceEngineName, string targetEngineName)
2757 	{
2758 		auto sourceEngine = createCache(sourceEngineName, cacheEngineDir(sourceEngineName), this);
2759 		auto targetEngine = createCache(targetEngineName, cacheEngineDir(targetEngineName), this);
2760 		auto tempDir = buildPath(config.local.workDir, "temp");
2761 		if (tempDir.exists)
2762 			tempDir.removeRecurse();
2763 		log("Enumerating source entries...");
2764 		auto sourceEntries = sourceEngine.getEntries();
2765 		log("Enumerating target entries...");
2766 		auto targetEntries = targetEngine.getEntries().sort();
2767 		foreach (key; sourceEntries)
2768 			if (!targetEntries.canFind(key))
2769 			{
2770 				log(key);
2771 				sourceEngine.extract(key, tempDir, fn => true);
2772 				targetEngine.add(key, tempDir);
2773 				if (tempDir.exists)
2774 					tempDir.removeRecurse();
2775 			}
2776 		targetEngine.optimize();
2777 	}
2778 
2779 	// **************************** Miscellaneous ****************************
2780 
2781 	struct LogEntry
2782 	{
2783 		string hash;
2784 		string[] message;
2785 		SysTime time;
2786 	}
2787 
2788 	/// Gets the D merge log (newest first).
2789 	LogEntry[] getLog(string refName = "refs/remotes/origin/master")
2790 	{
2791 		auto history = getMetaRepo().git.getHistory();
2792 		LogEntry[] logs;
2793 		auto master = history.commits[history.refs[refName]];
2794 		for (auto c = master; c; c = c.parents.length ? c.parents[0] : null)
2795 		{
2796 			auto time = SysTime(c.time.unixTimeToStdTime);
2797 			logs ~= LogEntry(c.hash.toString(), c.message, time);
2798 		}
2799 		return logs;
2800 	}
2801 
2802 	// ***************************** Integration *****************************
2803 
2804 	/// Override to add logging.
2805 	void log(string line)
2806 	{
2807 	}
2808 
2809 	/// Bootstrap description resolution.
2810 	/// See DMD.Config.Bootstrap.spec.
2811 	/// This is essentially a hack to allow the entire
2812 	/// Config structure to be parsed from an .ini file.
2813 	SubmoduleState parseSpec(string spec)
2814 	{
2815 		auto rev = getMetaRepo().getRef("refs/tags/" ~ spec);
2816 		log("Resolved " ~ spec ~ " to " ~ rev);
2817 		return begin(rev);
2818 	}
2819 
2820 	/// Override this method with one which returns a command,
2821 	/// which will invoke the unmergeRebaseEdit function below,
2822 	/// passing to it any additional parameters.
2823 	/// Note: Currently unused. Was previously used
2824 	/// for unmerging things using interactive rebase.
2825 	abstract string getCallbackCommand();
2826 
2827 	void callback(string[] args) { assert(false); }
2828 }