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