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