1 /**
2 	Representing a full project, with a root Package and several dependencies.
3 
4 	Copyright: © 2012-2013 Matthias Dondorff, 2012-2016 Sönke Ludwig
5 	License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
6 	Authors: Matthias Dondorff, Sönke Ludwig
7 */
8 module dub.project;
9 
10 import dub.compilers.compiler;
11 import dub.dependency;
12 import dub.description;
13 import dub.generators.generator;
14 import dub.internal.utils;
15 import dub.internal.vibecompat.core.file;
16 import dub.internal.vibecompat.data.json;
17 import dub.internal.vibecompat.inet.path;
18 import dub.internal.logging;
19 import dub.package_;
20 import dub.packagemanager;
21 import dub.recipe.selection;
22 
23 import dub.internal.configy.Read;
24 
25 import std.algorithm;
26 import std.array;
27 import std.conv : to;
28 import std.datetime;
29 import std.encoding : sanitize;
30 import std.exception : enforce;
31 import std.string;
32 
33 /**
34 	Represents a full project, a root package with its dependencies and package
35 	selection.
36 
37 	All dependencies must be available locally so that the package dependency
38 	graph can be built. Use `Project.reinit` if necessary for reloading
39 	dependencies after more packages are available.
40 */
41 class Project {
42 	private {
43 		PackageManager m_packageManager;
44 		Package m_rootPackage;
45 		Package[] m_dependencies;
46 		Package[][Package] m_dependees;
47 		SelectedVersions m_selections;
48 		string[] m_missingDependencies;
49 		string[string] m_overriddenConfigs;
50 	}
51 
52 	/** Loads a project.
53 
54 		Params:
55 			package_manager = Package manager instance to use for loading
56 				dependencies
57 			project_path = Path of the root package to load
58 			pack = An existing `Package` instance to use as the root package
59 	*/
60 	this(PackageManager package_manager, NativePath project_path)
61 	{
62 		Package pack;
63 		auto packageFile = Package.findPackageFile(project_path);
64 		if (packageFile.empty) {
65 			logWarn("There was no package description found for the application in '%s'.", project_path.toNativeString());
66 			pack = new Package(PackageRecipe.init, project_path);
67 		} else {
68 			pack = package_manager.getOrLoadPackage(project_path, packageFile, false, StrictMode.Warn);
69 		}
70 
71 		this(package_manager, pack);
72 	}
73 
74 	/// ditto
75 	this(PackageManager package_manager, Package pack)
76 	{
77 		m_packageManager = package_manager;
78 		m_rootPackage = pack;
79 
80 		auto selverfile = (m_rootPackage.path ~ SelectedVersions.defaultFile).toNativeString();
81 		if (existsFile(selverfile)) {
82 			// TODO: Remove `StrictMode.Warn` after v1.40 release
83 			// The default is to error, but as the previous parser wasn't
84 			// complaining, we should first warn the user.
85 			auto selected = parseConfigFileSimple!Selected(selverfile, StrictMode.Warn);
86 			m_selections = !selected.isNull() ?
87 				new SelectedVersions(selected.get()) : new SelectedVersions();
88 		} else m_selections = new SelectedVersions;
89 
90 		reinit();
91 	}
92 
93 	/** List of all resolved dependencies.
94 
95 		This includes all direct and indirect dependencies of all configurations
96 		combined. Optional dependencies that were not chosen are not included.
97 	*/
98 	@property const(Package[]) dependencies() const { return m_dependencies; }
99 
100 	/// The root package of the project.
101 	@property inout(Package) rootPackage() inout { return m_rootPackage; }
102 
103 	/// The versions to use for all dependencies. Call reinit() after changing these.
104 	@property inout(SelectedVersions) selections() inout { return m_selections; }
105 
106 	/// Package manager instance used by the project.
107 	@property inout(PackageManager) packageManager() inout { return m_packageManager; }
108 
109 	/** Determines if all dependencies necessary to build have been collected.
110 
111 		If this function returns `false`, it may be necessary to add more entries
112 		to `selections`, or to use `Dub.upgrade` to automatically select all
113 		missing dependencies.
114 	*/
115 	bool hasAllDependencies() const { return m_missingDependencies.length == 0; }
116 
117 	/// Sorted list of missing dependencies.
118 	string[] missingDependencies() { return m_missingDependencies; }
119 
120 	/** Allows iteration of the dependency tree in topological order
121 	*/
122 	int delegate(int delegate(ref Package)) getTopologicalPackageList(bool children_first = false, Package root_package = null, string[string] configs = null)
123 	{
124 		// ugly way to avoid code duplication since inout isn't compatible with foreach type inference
125 		return cast(int delegate(int delegate(ref Package)))(cast(const)this).getTopologicalPackageList(children_first, root_package, configs);
126 	}
127 	/// ditto
128 	int delegate(int delegate(ref const Package)) getTopologicalPackageList(bool children_first = false, in Package root_package = null, string[string] configs = null)
129 	const {
130 		const(Package) rootpack = root_package ? root_package : m_rootPackage;
131 
132 		int iterator(int delegate(ref const Package) del)
133 		{
134 			int ret = 0;
135 			bool[const(Package)] visited;
136 			void perform_rec(in Package p){
137 				if( p in visited ) return;
138 				visited[p] = true;
139 
140 				if( !children_first ){
141 					ret = del(p);
142 					if( ret ) return;
143 				}
144 
145 				auto cfg = configs.get(p.name, null);
146 
147 				PackageDependency[] deps;
148 				if (!cfg.length) deps = p.getAllDependencies();
149 				else {
150 					auto depmap = p.getDependencies(cfg);
151 					deps = depmap.byKey.map!(k => PackageDependency(k, depmap[k])).array;
152 				}
153 				deps.sort!((a, b) => a.name < b.name);
154 
155 				foreach (d; deps) {
156 					auto dependency = getDependency(d.name, true);
157 					assert(dependency || d.spec.optional,
158 						format("Non-optional dependency '%s' of '%s' not found in dependency tree!?.", d.name, p.name));
159 					if(dependency) perform_rec(dependency);
160 					if( ret ) return;
161 				}
162 
163 				if( children_first ){
164 					ret = del(p);
165 					if( ret ) return;
166 				}
167 			}
168 			perform_rec(rootpack);
169 			return ret;
170 		}
171 
172 		return &iterator;
173 	}
174 
175 	/** Retrieves a particular dependency by name.
176 
177 		Params:
178 			name = (Qualified) package name of the dependency
179 			is_optional = If set to true, will return `null` for unsatisfiable
180 				dependencies instead of throwing an exception.
181 	*/
182 	inout(Package) getDependency(string name, bool is_optional)
183 	inout {
184 		foreach(dp; m_dependencies)
185 			if( dp.name == name )
186 				return dp;
187 		if (!is_optional) throw new Exception("Unknown dependency: "~name);
188 		else return null;
189 	}
190 
191 	/** Returns the name of the default build configuration for the specified
192 		target platform.
193 
194 		Params:
195 			platform = The target build platform
196 			allow_non_library_configs = If set to true, will use the first
197 				possible configuration instead of the first "executable"
198 				configuration.
199 	*/
200 	string getDefaultConfiguration(in BuildPlatform platform, bool allow_non_library_configs = true)
201 	const {
202 		auto cfgs = getPackageConfigs(platform, null, allow_non_library_configs);
203 		return cfgs[m_rootPackage.name];
204 	}
205 
206 	/** Overrides the configuration chosen for a particular package in the
207 		dependency graph.
208 
209 		Setting a certain configuration here is equivalent to removing all
210 		but one configuration from the package.
211 
212 		Params:
213 			package_ = The package for which to force selecting a certain
214 				dependency
215 			config = Name of the configuration to force
216 	*/
217 	void overrideConfiguration(string package_, string config)
218 	{
219 		auto p = getDependency(package_, true);
220 		enforce(p !is null,
221 			format("Package '%s', marked for configuration override, is not present in dependency graph.", package_));
222 		enforce(p.configurations.canFind(config),
223 			format("Package '%s' does not have a configuration named '%s'.", package_, config));
224 		m_overriddenConfigs[package_] = config;
225 	}
226 
227 	/** Adds a test runner configuration for the root package.
228 
229 		Params:
230 			generate_main = Whether to generate the main.d file
231 			base_config = Optional base configuration
232 			custom_main_file = Optional path to file with custom main entry point
233 
234 		Returns:
235 			Name of the added test runner configuration, or null for base configurations with target type `none`
236 	*/
237 	string addTestRunnerConfiguration(in GeneratorSettings settings, bool generate_main = true, string base_config = "", NativePath custom_main_file = NativePath())
238 	{
239 		if (base_config.length == 0) {
240 			// if a custom main file was given, favor the first library configuration, so that it can be applied
241 			if (!custom_main_file.empty) base_config = getDefaultConfiguration(settings.platform, false);
242 			// else look for a "unittest" configuration
243 			if (!base_config.length && rootPackage.configurations.canFind("unittest")) base_config = "unittest";
244 			// if not found, fall back to the first "library" configuration
245 			if (!base_config.length) base_config = getDefaultConfiguration(settings.platform, false);
246 			// if still nothing found, use the first executable configuration
247 			if (!base_config.length) base_config = getDefaultConfiguration(settings.platform, true);
248 		}
249 
250 		BuildSettings lbuildsettings = settings.buildSettings.dup;
251 		addBuildSettings(lbuildsettings, settings, base_config, null, true);
252 
253 		if (lbuildsettings.targetType == TargetType.none) {
254 			logInfo(`Configuration '%s' has target type "none". Skipping test runner configuration.`, base_config);
255 			return null;
256 		}
257 
258 		if (lbuildsettings.targetType == TargetType.executable && base_config == "unittest") {
259 			if (!custom_main_file.empty) logWarn("Ignoring custom main file.");
260 			return base_config;
261 		}
262 
263 		if (lbuildsettings.sourceFiles.empty) {
264 			logInfo(`No source files found in configuration '%s'. Falling back to default configuration for test runner.`, base_config);
265 			if (!custom_main_file.empty) logWarn("Ignoring custom main file.");
266 			return getDefaultConfiguration(settings.platform);
267 		}
268 
269 		const config = format("%s-test-%s", rootPackage.name.replace(".", "-").replace(":", "-"), base_config);
270 		logInfo(`Generating test runner configuration '%s' for '%s' (%s).`, config, base_config, lbuildsettings.targetType);
271 
272 		BuildSettingsTemplate tcinfo = rootPackage.recipe.getConfiguration(base_config).buildSettings.dup;
273 		tcinfo.targetType = TargetType.executable;
274 
275 		// set targetName unless specified explicitly in unittest base configuration
276 		if (tcinfo.targetName.empty || base_config != "unittest")
277 			tcinfo.targetName = config;
278 
279 		auto mainfil = tcinfo.mainSourceFile;
280 		if (!mainfil.length) mainfil = rootPackage.recipe.buildSettings.mainSourceFile;
281 
282 		string custommodname;
283 		if (!custom_main_file.empty) {
284 			import std.path;
285 			tcinfo.sourceFiles[""] ~= custom_main_file.relativeTo(rootPackage.path).toNativeString();
286 			tcinfo.importPaths[""] ~= custom_main_file.parentPath.toNativeString();
287 			custommodname = custom_main_file.head.name.baseName(".d");
288 		}
289 
290 		// prepare the list of tested modules
291 
292 		string[] import_modules;
293 		if (settings.single)
294 			lbuildsettings.importPaths ~= NativePath(mainfil).parentPath.toNativeString;
295 		bool firstTimePackage = true;
296 		foreach (file; lbuildsettings.sourceFiles) {
297 			if (file.endsWith(".d")) {
298 				auto fname = NativePath(file).head.name;
299 				NativePath msf = NativePath(mainfil);
300 				if (msf.absolute)
301 					msf = msf.relativeTo(rootPackage.path);
302 				if (!settings.single && NativePath(file).relativeTo(rootPackage.path) == msf) {
303 					logWarn("Excluding main source file %s from test.", mainfil);
304 					tcinfo.excludedSourceFiles[""] ~= mainfil;
305 					continue;
306 				}
307 				if (fname == "package.d") {
308 					if (firstTimePackage) {
309 						firstTimePackage = false;
310 						logDiagnostic("Excluding package.d file from test due to https://issues.dlang.org/show_bug.cgi?id=11847");
311 					}
312 					continue;
313 				}
314 				import_modules ~= dub.internal.utils.determineModuleName(lbuildsettings, NativePath(file), rootPackage.path);
315 			}
316 		}
317 
318 		NativePath mainfile;
319 		if (settings.tempBuild)
320 			mainfile = getTempFile("dub_test_root", ".d");
321 		else {
322 			import dub.generators.build : computeBuildName;
323 			mainfile = packageCache(settings.cache, this.rootPackage) ~
324 				format("code/%s/dub_test_root.d",
325 					computeBuildName(config, settings, import_modules));
326 		}
327 
328 		auto escapedMainFile = mainfile.toNativeString().replace("$", "$$");
329 		tcinfo.sourceFiles[""] ~= escapedMainFile;
330 		tcinfo.mainSourceFile = escapedMainFile;
331 		if (!settings.tempBuild) {
332 			// add the directory containing dub_test_root.d to the import paths
333 			tcinfo.importPaths[""] ~= NativePath(escapedMainFile).parentPath.toNativeString();
334 		}
335 
336 		if (generate_main && (settings.force || !existsFile(mainfile))) {
337 		    ensureDirectory(mainfile.parentPath);
338 
339 			const runnerCode = custommodname.length ?
340 				format("import %s;", custommodname) : DefaultTestRunnerCode;
341 			const content = TestRunnerTemplate.format(
342 				import_modules, import_modules, runnerCode);
343 			writeFile(mainfile, content);
344 		}
345 
346 		rootPackage.recipe.configurations ~= ConfigurationInfo(config, tcinfo);
347 
348 		return config;
349 	}
350 
351 	/** Performs basic validation of various aspects of the package.
352 
353 		This will emit warnings to `stderr` if any discouraged names or
354 		dependency patterns are found.
355 	*/
356 	void validate()
357 	{
358 		// some basic package lint
359 		m_rootPackage.warnOnSpecialCompilerFlags();
360 		string nameSuggestion() {
361 			string ret;
362 			ret ~= `Please modify the "name" field in %s accordingly.`.format(m_rootPackage.recipePath.toNativeString());
363 			if (!m_rootPackage.recipe.buildSettings.targetName.length) {
364 				if (m_rootPackage.recipePath.head.name.endsWith(".sdl")) {
365 					ret ~= ` You can then add 'targetName "%s"' to keep the current executable name.`.format(m_rootPackage.name);
366 				} else {
367 					ret ~= ` You can then add '"targetName": "%s"' to keep the current executable name.`.format(m_rootPackage.name);
368 				}
369 			}
370 			return ret;
371 		}
372 		if (m_rootPackage.name != m_rootPackage.name.toLower()) {
373 			logWarn(`WARNING: DUB package names should always be lower case. %s`, nameSuggestion());
374 		} else if (!m_rootPackage.recipe.name.all!(ch => ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_')) {
375 			logWarn(`WARNING: DUB package names may only contain alphanumeric characters, `
376 				~ `as well as '-' and '_'. %s`, nameSuggestion());
377 		}
378 		enforce(!m_rootPackage.name.canFind(' '), "Aborting due to the package name containing spaces.");
379 
380 		foreach (d; m_rootPackage.getAllDependencies())
381 			if (d.spec.isExactVersion && d.spec.version_.isBranch) {
382 				logWarn("WARNING: A deprecated branch based version specification is used "
383 					~ "for the dependency %s. Please use numbered versions instead. Also "
384 					~ "note that you can still use the %s file to override a certain "
385 					~ "dependency to use a branch instead.",
386 					d.name, SelectedVersions.defaultFile);
387 			}
388 
389 		// search for orphan sub configurations
390 		void warnSubConfig(string pack, string config) {
391 			logWarn("The sub configuration directive \"%s\" -> [%s] "
392 				~ "references a package that is not specified as a dependency "
393 				~ "and will have no effect.", pack.color(Mode.bold), config.color(Color.blue));
394 		}
395 
396 		void checkSubConfig(string pack, string config) {
397 			auto p = getDependency(pack, true);
398 			if (p && !p.configurations.canFind(config)) {
399 				logWarn("The sub configuration directive \"%s\" -> [%s] "
400 					~ "references a configuration that does not exist.",
401 					pack.color(Mode.bold), config.color(Color.red));
402 			}
403 		}
404 		auto globalbs = m_rootPackage.getBuildSettings();
405 		foreach (p, c; globalbs.subConfigurations) {
406 			if (p !in globalbs.dependencies) warnSubConfig(p, c);
407 			else checkSubConfig(p, c);
408 		}
409 		foreach (c; m_rootPackage.configurations) {
410 			auto bs = m_rootPackage.getBuildSettings(c);
411 			foreach (p, subConf; bs.subConfigurations) {
412 				if (p !in bs.dependencies && p !in globalbs.dependencies)
413 					warnSubConfig(p, subConf);
414 				else checkSubConfig(p, subConf);
415 			}
416 		}
417 
418 		// check for version specification mismatches
419 		bool[Package] visited;
420 		void validateDependenciesRec(Package pack) {
421 			// perform basic package linting
422 			pack.simpleLint();
423 
424 			foreach (d; pack.getAllDependencies()) {
425 				auto basename = getBasePackageName(d.name);
426 				d.spec.visit!(
427 					(NativePath path) { /* Valid */ },
428 					(Repository repo) { /* Valid */ },
429 					(VersionRange vers) {
430 						if (m_selections.hasSelectedVersion(basename)) {
431 							auto selver = m_selections.getSelectedVersion(basename);
432 							if (d.spec.merge(selver) == Dependency.invalid) {
433 								logWarn(`Selected package %s %s does not match the dependency specification %s in package %s. Need to "%s"?`,
434 									basename.color(Mode.bold), selver, vers, pack.name.color(Mode.bold), "dub upgrade".color(Mode.bold));
435 							}
436 						}
437 					},
438 				);
439 
440 				auto deppack = getDependency(d.name, true);
441 				if (deppack in visited) continue;
442 				visited[deppack] = true;
443 				if (deppack) validateDependenciesRec(deppack);
444 			}
445 		}
446 		validateDependenciesRec(m_rootPackage);
447 	}
448 
449 	/// Reloads dependencies.
450 	void reinit()
451 	{
452 		m_dependencies = null;
453 		m_missingDependencies = [];
454 
455 		Package resolveSubPackage(Package p, string subname, bool silentFail) {
456 			return subname.length ? m_packageManager.getSubPackage(p, subname, silentFail) : p;
457 		}
458 
459 		void collectDependenciesRec(Package pack, int depth = 0)
460 		{
461 			auto indent = replicate("  ", depth);
462 			logDebug("%sCollecting dependencies for %s", indent, pack.name);
463 			indent ~= "  ";
464 
465 			foreach (dep; pack.getAllDependencies()) {
466 				Dependency vspec = dep.spec;
467 				Package p;
468 
469 				auto basename = getBasePackageName(dep.name);
470 				auto subname = getSubPackageName(dep.name);
471 
472 				// non-optional and optional-default dependencies (if no selections file exists)
473 				// need to be satisfied
474 				bool is_desired = !vspec.optional || m_selections.hasSelectedVersion(basename) || (vspec.default_ && m_selections.bare);
475 
476 				if (dep.name == m_rootPackage.basePackage.name) {
477 					vspec = Dependency(m_rootPackage.version_);
478 					p = m_rootPackage.basePackage;
479 				} else if (basename == m_rootPackage.basePackage.name) {
480 					vspec = Dependency(m_rootPackage.version_);
481 					try p = m_packageManager.getSubPackage(m_rootPackage.basePackage, subname, false);
482 					catch (Exception e) {
483 						logDiagnostic("%sError getting sub package %s: %s", indent, dep.name, e.msg);
484 						if (is_desired) m_missingDependencies ~= dep.name;
485 						continue;
486 					}
487 				} else if (m_selections.hasSelectedVersion(basename)) {
488 					vspec = m_selections.getSelectedVersion(basename);
489 					p = vspec.visit!(
490 						(NativePath path_) {
491 							auto path = path_.absolute ? path_ : m_rootPackage.path ~ path_;
492 							auto tmp = m_packageManager.getOrLoadPackage(path, NativePath.init, true);
493 							return resolveSubPackage(tmp, subname, true);
494 						},
495 						(Repository repo) {
496 							auto tmp = m_packageManager.loadSCMPackage(basename, repo);
497 							return resolveSubPackage(tmp, subname, true);
498 						},
499 						(VersionRange range) {
500 							// See `dub.recipe.selection : SelectedDependency.fromYAML`
501 							assert(range.isExactVersion());
502 							return m_packageManager.getPackage(dep.name, vspec.version_);
503 						},
504 					);
505 				} else if (m_dependencies.canFind!(d => getBasePackageName(d.name) == basename)) {
506 					auto idx = m_dependencies.countUntil!(d => getBasePackageName(d.name) == basename);
507 					auto bp = m_dependencies[idx].basePackage;
508 					vspec = Dependency(bp.path);
509 					p = resolveSubPackage(bp, subname, false);
510 				} else {
511 					logDiagnostic("%sVersion selection for dependency %s (%s) of %s is missing.",
512 						indent, basename, dep.name, pack.name);
513 				}
514 
515 				// We didn't find the package
516 				if (p is null)
517 				{
518 					if (!vspec.repository.empty) {
519 						p = m_packageManager.loadSCMPackage(basename, vspec.repository);
520 						resolveSubPackage(p, subname, false);
521 					} else if (!vspec.path.empty && is_desired) {
522 						NativePath path = vspec.path;
523 						if (!path.absolute) path = pack.path ~ path;
524 						logDiagnostic("%sAdding local %s in %s", indent, dep.name, path);
525 						p = m_packageManager.getOrLoadPackage(path, NativePath.init, true);
526 						if (p.parentPackage !is null) {
527 							logWarn("%sSub package %s must be referenced using the path to it's parent package.", indent, dep.name);
528 							p = p.parentPackage;
529 						}
530 						p = resolveSubPackage(p, subname, false);
531 						enforce(p.name == dep.name,
532 							format("Path based dependency %s is referenced with a wrong name: %s vs. %s",
533 								path.toNativeString(), dep.name, p.name));
534 					} else {
535 						logDiagnostic("%sMissing dependency %s %s of %s", indent, dep.name, vspec, pack.name);
536 						if (is_desired) m_missingDependencies ~= dep.name;
537 						continue;
538 					}
539 				}
540 
541 				if (!m_dependencies.canFind(p)) {
542 					logDiagnostic("%sFound dependency %s %s", indent, dep.name, vspec.toString());
543 					m_dependencies ~= p;
544 					if (basename == m_rootPackage.basePackage.name)
545 						p.warnOnSpecialCompilerFlags();
546 					collectDependenciesRec(p, depth+1);
547 				}
548 
549 				m_dependees[p] ~= pack;
550 				//enforce(p !is null, "Failed to resolve dependency "~dep.name~" "~vspec.toString());
551 			}
552 		}
553 		collectDependenciesRec(m_rootPackage);
554 		m_missingDependencies.sort();
555 	}
556 
557 	/// Returns the name of the root package.
558 	@property string name() const { return m_rootPackage ? m_rootPackage.name : "app"; }
559 
560 	/// Returns the names of all configurations of the root package.
561 	@property string[] configurations() const { return m_rootPackage.configurations; }
562 
563 	/// Returns the names of all built-in and custom build types of the root package.
564 	/// The default built-in build type is the first item in the list.
565 	@property string[] builds() const { return builtinBuildTypes ~ m_rootPackage.customBuildTypes; }
566 
567 	/// Returns a map with the configuration for all packages in the dependency tree.
568 	string[string] getPackageConfigs(in BuildPlatform platform, string config, bool allow_non_library = true)
569 	const {
570 		struct Vertex { string pack, config; }
571 		struct Edge { size_t from, to; }
572 
573 		Vertex[] configs;
574 		Edge[] edges;
575 		string[][string] parents;
576 		parents[m_rootPackage.name] = null;
577 		foreach (p; getTopologicalPackageList())
578 			foreach (d; p.getAllDependencies())
579 				parents[d.name] ~= p.name;
580 
581 		size_t createConfig(string pack, string config) {
582 			foreach (i, v; configs)
583 				if (v.pack == pack && v.config == config)
584 					return i;
585 			assert(pack !in m_overriddenConfigs || config == m_overriddenConfigs[pack]);
586 			logDebug("Add config %s %s", pack, config);
587 			configs ~= Vertex(pack, config);
588 			return configs.length-1;
589 		}
590 
591 		bool haveConfig(string pack, string config) {
592 			return configs.any!(c => c.pack == pack && c.config == config);
593 		}
594 
595 		size_t createEdge(size_t from, size_t to) {
596 			auto idx = edges.countUntil(Edge(from, to));
597 			if (idx >= 0) return idx;
598 			logDebug("Including %s %s -> %s %s", configs[from].pack, configs[from].config, configs[to].pack, configs[to].config);
599 			edges ~= Edge(from, to);
600 			return edges.length-1;
601 		}
602 
603 		void removeConfig(size_t i) {
604 			logDebug("Eliminating config %s for %s", configs[i].config, configs[i].pack);
605 			auto had_dep_to_pack = new bool[configs.length];
606 			auto still_has_dep_to_pack = new bool[configs.length];
607 
608 			edges = edges.filter!((e) {
609 					if (e.to == i) {
610 						had_dep_to_pack[e.from] = true;
611 						return false;
612 					} else if (configs[e.to].pack == configs[i].pack) {
613 						still_has_dep_to_pack[e.from] = true;
614 					}
615 					if (e.from == i) return false;
616 					return true;
617 				}).array;
618 
619 			configs[i] = Vertex.init; // mark config as removed
620 
621 			// also remove any configs that cannot be satisfied anymore
622 			foreach (j; 0 .. configs.length)
623 				if (j != i && had_dep_to_pack[j] && !still_has_dep_to_pack[j])
624 					removeConfig(j);
625 		}
626 
627 		bool isReachable(string pack, string conf) {
628 			if (pack == configs[0].pack && configs[0].config == conf) return true;
629 			foreach (e; edges)
630 				if (configs[e.to].pack == pack && configs[e.to].config == conf)
631 					return true;
632 			return false;
633 			//return (pack == configs[0].pack && conf == configs[0].config) || edges.canFind!(e => configs[e.to].pack == pack && configs[e.to].config == config);
634 		}
635 
636 		bool isReachableByAllParentPacks(size_t cidx) {
637 			bool[string] r;
638 			foreach (p; parents[configs[cidx].pack]) r[p] = false;
639 			foreach (e; edges) {
640 				if (e.to != cidx) continue;
641 				if (auto pp = configs[e.from].pack in r) *pp = true;
642 			}
643 			foreach (bool v; r) if (!v) return false;
644 			return true;
645 		}
646 
647 		string[] allconfigs_path;
648 
649 		void determineDependencyConfigs(in Package p, string c)
650 		{
651 			string[][string] depconfigs;
652 			foreach (d; p.getAllDependencies()) {
653 				auto dp = getDependency(d.name, true);
654 				if (!dp) continue;
655 
656 				string[] cfgs;
657 				if (auto pc = dp.name in m_overriddenConfigs) cfgs = [*pc];
658 				else {
659 					auto subconf = p.getSubConfiguration(c, dp, platform);
660 					if (!subconf.empty) cfgs = [subconf];
661 					else cfgs = dp.getPlatformConfigurations(platform);
662 				}
663 				cfgs = cfgs.filter!(c => haveConfig(d.name, c)).array;
664 
665 				// if no valid configuration was found for a dependency, don't include the
666 				// current configuration
667 				if (!cfgs.length) {
668 					logDebug("Skip %s %s (missing configuration for %s)", p.name, c, dp.name);
669 					return;
670 				}
671 				depconfigs[d.name] = cfgs;
672 			}
673 
674 			// add this configuration to the graph
675 			size_t cidx = createConfig(p.name, c);
676 			foreach (d; p.getAllDependencies())
677 				foreach (sc; depconfigs.get(d.name, null))
678 					createEdge(cidx, createConfig(d.name, sc));
679 		}
680 
681 		// create a graph of all possible package configurations (package, config) -> (subpackage, subconfig)
682 		void determineAllConfigs(in Package p)
683 		{
684 			auto idx = allconfigs_path.countUntil(p.name);
685 			enforce(idx < 0, format("Detected dependency cycle: %s", (allconfigs_path[idx .. $] ~ p.name).join("->")));
686 			allconfigs_path ~= p.name;
687 			scope (exit) allconfigs_path.length--;
688 
689 			// first, add all dependency configurations
690 			foreach (d; p.getAllDependencies) {
691 				auto dp = getDependency(d.name, true);
692 				if (!dp) continue;
693 				determineAllConfigs(dp);
694 			}
695 
696 			// for each configuration, determine the configurations usable for the dependencies
697 			if (auto pc = p.name in m_overriddenConfigs)
698 				determineDependencyConfigs(p, *pc);
699 			else
700 				foreach (c; p.getPlatformConfigurations(platform, p is m_rootPackage && allow_non_library))
701 					determineDependencyConfigs(p, c);
702 		}
703 		if (config.length) createConfig(m_rootPackage.name, config);
704 		determineAllConfigs(m_rootPackage);
705 
706 		// successively remove configurations until only one configuration per package is left
707 		bool changed;
708 		do {
709 			// remove all configs that are not reachable by all parent packages
710 			changed = false;
711 			foreach (i, ref c; configs) {
712 				if (c == Vertex.init) continue; // ignore deleted configurations
713 				if (!isReachableByAllParentPacks(i)) {
714 					logDebug("%s %s NOT REACHABLE by all of (%s):", c.pack, c.config, parents[c.pack]);
715 					removeConfig(i);
716 					changed = true;
717 				}
718 			}
719 
720 			// when all edges are cleaned up, pick one package and remove all but one config
721 			if (!changed) {
722 				foreach (p; getTopologicalPackageList()) {
723 					size_t cnt = 0;
724 					foreach (i, ref c; configs)
725 						if (c.pack == p.name && ++cnt > 1) {
726 							logDebug("NON-PRIMARY: %s %s", c.pack, c.config);
727 							removeConfig(i);
728 						}
729 					if (cnt > 1) {
730 						changed = true;
731 						break;
732 					}
733 				}
734 			}
735 		} while (changed);
736 
737 		// print out the resulting tree
738 		foreach (e; edges) logDebug("    %s %s -> %s %s", configs[e.from].pack, configs[e.from].config, configs[e.to].pack, configs[e.to].config);
739 
740 		// return the resulting configuration set as an AA
741 		string[string] ret;
742 		foreach (c; configs) {
743 			if (c == Vertex.init) continue; // ignore deleted configurations
744 			assert(ret.get(c.pack, c.config) == c.config, format("Conflicting configurations for %s found: %s vs. %s", c.pack, c.config, ret[c.pack]));
745 			logDebug("Using configuration '%s' for %s", c.config, c.pack);
746 			ret[c.pack] = c.config;
747 		}
748 
749 		// check for conflicts (packages missing in the final configuration graph)
750 		void checkPacksRec(in Package pack) {
751 			auto pc = pack.name in ret;
752 			enforce(pc !is null, "Could not resolve configuration for package "~pack.name);
753 			foreach (p, dep; pack.getDependencies(*pc)) {
754 				auto deppack = getDependency(p, dep.optional);
755 				if (deppack) checkPacksRec(deppack);
756 			}
757 		}
758 		checkPacksRec(m_rootPackage);
759 
760 		return ret;
761 	}
762 
763 	/**
764 	 * Fills `dst` with values from this project.
765 	 *
766 	 * `dst` gets initialized according to the given platform and config.
767 	 *
768 	 * Params:
769 	 *   dst = The BuildSettings struct to fill with data.
770 	 *   gsettings = The generator settings to retrieve the values for.
771 	 *   config = Values of the given configuration will be retrieved.
772 	 *   root_package = If non null, use it instead of the project's real root package.
773 	 *   shallow = If true, collects only build settings for the main package (including inherited settings) and doesn't stop on target type none and sourceLibrary.
774 	 */
775 	void addBuildSettings(ref BuildSettings dst, in GeneratorSettings gsettings, string config, in Package root_package = null, bool shallow = false)
776 	const {
777 		import dub.internal.utils : stripDlangSpecialChars;
778 
779 		auto configs = getPackageConfigs(gsettings.platform, config);
780 
781 		foreach (pkg; this.getTopologicalPackageList(false, root_package, configs)) {
782 			auto pkg_path = pkg.path.toNativeString();
783 			dst.addVersions(["Have_" ~ stripDlangSpecialChars(pkg.name)]);
784 
785 			assert(pkg.name in configs, "Missing configuration for "~pkg.name);
786 			logDebug("Gathering build settings for %s (%s)", pkg.name, configs[pkg.name]);
787 
788 			auto psettings = pkg.getBuildSettings(gsettings.platform, configs[pkg.name]);
789 			if (psettings.targetType != TargetType.none) {
790 				if (shallow && pkg !is m_rootPackage)
791 					psettings.sourceFiles = null;
792 				processVars(dst, this, pkg, psettings, gsettings);
793 				if (!gsettings.single && psettings.importPaths.empty)
794 					logWarn(`Package %s (configuration "%s") defines no import paths, use {"importPaths": [...]} or the default package directory structure to fix this.`, pkg.name, configs[pkg.name]);
795 				if (psettings.mainSourceFile.empty && pkg is m_rootPackage && psettings.targetType == TargetType.executable)
796 					logWarn(`Executable configuration "%s" of package %s defines no main source file, this may cause certain build modes to fail. Add an explicit "mainSourceFile" to the package description to fix this.`, configs[pkg.name], pkg.name);
797 			}
798 			if (pkg is m_rootPackage) {
799 				if (!shallow) {
800 					enforce(psettings.targetType != TargetType.none, "Main package has target type \"none\" - stopping build.");
801 					enforce(psettings.targetType != TargetType.sourceLibrary, "Main package has target type \"sourceLibrary\" which generates no target - stopping build.");
802 				}
803 				dst.targetType = psettings.targetType;
804 				dst.targetPath = psettings.targetPath;
805 				dst.targetName = psettings.targetName;
806 				if (!psettings.workingDirectory.empty)
807 					dst.workingDirectory = processVars(psettings.workingDirectory, this, pkg, gsettings, true, [dst.environments, dst.buildEnvironments]);
808 				if (psettings.mainSourceFile.length)
809 					dst.mainSourceFile = processVars(psettings.mainSourceFile, this, pkg, gsettings, true, [dst.environments, dst.buildEnvironments]);
810 			}
811 		}
812 
813 		// always add all version identifiers of all packages
814 		foreach (pkg; this.getTopologicalPackageList(false, null, configs)) {
815 			auto psettings = pkg.getBuildSettings(gsettings.platform, configs[pkg.name]);
816 			dst.addVersions(psettings.versions);
817 		}
818 	}
819 
820 	/** Fills `dst` with build settings specific to the given build type.
821 
822 		Params:
823 			dst = The `BuildSettings` instance to add the build settings to
824 			gsettings = Target generator settings
825 			build_type = Name of the build type
826 			for_root_package = Selects if the build settings are for the root
827 				package or for one of the dependencies. Unittest flags will
828 				only be added to the root package.
829 	*/
830 	void addBuildTypeSettings(ref BuildSettings dst, in GeneratorSettings gsettings, bool for_root_package = true)
831 	{
832 		bool usedefflags = !(dst.requirements & BuildRequirement.noDefaultFlags);
833 		if (usedefflags) {
834 			BuildSettings btsettings;
835 			m_rootPackage.addBuildTypeSettings(btsettings, gsettings.platform, gsettings.buildType);
836 
837 			if (!for_root_package) {
838 				// don't propagate unittest switch to dependencies, as dependent
839 				// unit tests aren't run anyway and the additional code may
840 				// cause linking to fail on Windows (issue #640)
841 				btsettings.removeOptions(BuildOption.unittests);
842 			}
843 
844 			processVars(dst, this, m_rootPackage, btsettings, gsettings);
845 		}
846 	}
847 
848 	/// Outputs a build description of the project, including its dependencies.
849 	ProjectDescription describe(GeneratorSettings settings)
850 	{
851 		import dub.generators.targetdescription;
852 
853 		// store basic build parameters
854 		ProjectDescription ret;
855 		ret.rootPackage = m_rootPackage.name;
856 		ret.configuration = settings.config;
857 		ret.buildType = settings.buildType;
858 		ret.compiler = settings.platform.compiler;
859 		ret.architecture = settings.platform.architecture;
860 		ret.platform = settings.platform.platform;
861 
862 		// collect high level information about projects (useful for IDE display)
863 		auto configs = getPackageConfigs(settings.platform, settings.config);
864 		ret.packages ~= m_rootPackage.describe(settings.platform, settings.config);
865 		foreach (dep; m_dependencies)
866 			ret.packages ~= dep.describe(settings.platform, configs[dep.name]);
867 
868 		foreach (p; getTopologicalPackageList(false, null, configs))
869 			ret.packages[ret.packages.countUntil!(pp => pp.name == p.name)].active = true;
870 
871 		if (settings.buildType.length) {
872 			// collect build target information (useful for build tools)
873 			auto gen = new TargetDescriptionGenerator(this);
874 			try {
875 				gen.generate(settings);
876 				ret.targets = gen.targetDescriptions;
877 				ret.targetLookup = gen.targetDescriptionLookup;
878 			} catch (Exception e) {
879 				logDiagnostic("Skipping targets description: %s", e.msg);
880 				logDebug("Full error: %s", e.toString().sanitize);
881 			}
882 		}
883 
884 		return ret;
885 	}
886 
887 	private string[] listBuildSetting(string attributeName)(ref GeneratorSettings settings,
888 		string config, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
889 	{
890 		return listBuildSetting!attributeName(settings, getPackageConfigs(settings.platform, config),
891 			projectDescription, compiler, disableEscaping);
892 	}
893 
894 	private string[] listBuildSetting(string attributeName)(ref GeneratorSettings settings,
895 		string[string] configs, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
896 	{
897 		if (compiler)
898 			return formatBuildSettingCompiler!attributeName(settings, configs, projectDescription, compiler, disableEscaping);
899 		else
900 			return formatBuildSettingPlain!attributeName(settings, configs, projectDescription);
901 	}
902 
903 	// Output a build setting formatted for a compiler
904 	private string[] formatBuildSettingCompiler(string attributeName)(ref GeneratorSettings settings,
905 		string[string] configs, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
906 	{
907 		import std.process : escapeShellFileName;
908 		import std.path : dirSeparator;
909 
910 		assert(compiler);
911 
912 		auto targetDescription = projectDescription.lookupTarget(projectDescription.rootPackage);
913 		auto buildSettings = targetDescription.buildSettings;
914 
915 		string[] values;
916 		switch (attributeName)
917 		{
918 		case "dflags":
919 		case "linkerFiles":
920 		case "mainSourceFile":
921 		case "importFiles":
922 			values = formatBuildSettingPlain!attributeName(settings, configs, projectDescription);
923 			break;
924 
925 		case "lflags":
926 		case "sourceFiles":
927 		case "injectSourceFiles":
928 		case "versions":
929 		case "debugVersions":
930 		case "importPaths":
931 		case "stringImportPaths":
932 		case "options":
933 			auto bs = buildSettings.dup;
934 			bs.dflags = null;
935 
936 			// Ensure trailing slash on directory paths
937 			auto ensureTrailingSlash = (string path) => path.endsWith(dirSeparator) ? path : path ~ dirSeparator;
938 			static if (attributeName == "importPaths")
939 				bs.importPaths = bs.importPaths.map!(ensureTrailingSlash).array();
940 			else static if (attributeName == "stringImportPaths")
941 				bs.stringImportPaths = bs.stringImportPaths.map!(ensureTrailingSlash).array();
942 
943 			compiler.prepareBuildSettings(bs, settings.platform, BuildSetting.all & ~to!BuildSetting(attributeName));
944 			values = bs.dflags;
945 			break;
946 
947 		case "libs":
948 			auto bs = buildSettings.dup;
949 			bs.dflags = null;
950 			bs.lflags = null;
951 			bs.sourceFiles = null;
952 			bs.targetType = TargetType.none; // Force Compiler to NOT omit dependency libs when package is a library.
953 
954 			compiler.prepareBuildSettings(bs, settings.platform, BuildSetting.all & ~to!BuildSetting(attributeName));
955 
956 			if (bs.lflags)
957 				values = compiler.lflagsToDFlags( bs.lflags );
958 			else if (bs.sourceFiles)
959 				values = compiler.lflagsToDFlags( bs.sourceFiles );
960 			else
961 				values = bs.dflags;
962 
963 			break;
964 
965 		default: assert(0);
966 		}
967 
968 		// Escape filenames and paths
969 		if(!disableEscaping)
970 		{
971 			switch (attributeName)
972 			{
973 			case "mainSourceFile":
974 			case "linkerFiles":
975 			case "injectSourceFiles":
976 			case "copyFiles":
977 			case "importFiles":
978 			case "stringImportFiles":
979 			case "sourceFiles":
980 			case "importPaths":
981 			case "stringImportPaths":
982 				return values.map!(escapeShellFileName).array();
983 
984 			default:
985 				return values;
986 			}
987 		}
988 
989 		return values;
990 	}
991 
992 	// Output a build setting without formatting for any particular compiler
993 	private string[] formatBuildSettingPlain(string attributeName)(ref GeneratorSettings settings, string[string] configs, ProjectDescription projectDescription)
994 	{
995 		import std.path : buildNormalizedPath, dirSeparator;
996 		import std.range : only;
997 
998 		string[] list;
999 
1000 		enforce(attributeName == "targetType" || projectDescription.lookupRootPackage().targetType != TargetType.none,
1001 			"Target type is 'none'. Cannot list build settings.");
1002 
1003 		static if (attributeName == "targetType")
1004 			if (projectDescription.rootPackage !in projectDescription.targetLookup)
1005 				return ["none"];
1006 
1007 		auto targetDescription = projectDescription.lookupTarget(projectDescription.rootPackage);
1008 		auto buildSettings = targetDescription.buildSettings;
1009 
1010 		string[] substituteCommands(Package pack, string[] commands, CommandType type)
1011 		{
1012 			auto env = makeCommandEnvironmentVariables(type, pack, this, settings, buildSettings);
1013 			return processVars(this, pack, settings, commands, false, env);
1014 		}
1015 
1016 		// Return any BuildSetting member attributeName as a range of strings. Don't attempt to fixup values.
1017 		// allowEmptyString: When the value is a string (as opposed to string[]),
1018 		//                   is empty string an actual permitted value instead of
1019 		//                   a missing value?
1020 		auto getRawBuildSetting(Package pack, bool allowEmptyString) {
1021 			auto value = __traits(getMember, buildSettings, attributeName);
1022 
1023 			static if( attributeName.endsWith("Commands") )
1024 				return substituteCommands(pack, value, mixin("CommandType.", attributeName[0 .. $ - "Commands".length]));
1025 			else static if( is(typeof(value) == string[]) )
1026 				return value;
1027 			else static if( is(typeof(value) == string) )
1028 			{
1029 				auto ret = only(value);
1030 
1031 				// only() has a different return type from only(value), so we
1032 				// have to empty the range rather than just returning only().
1033 				if(value.empty && !allowEmptyString) {
1034 					ret.popFront();
1035 					assert(ret.empty);
1036 				}
1037 
1038 				return ret;
1039 			}
1040 			else static if( is(typeof(value) == string[string]) )
1041 				return value.byKeyValue.map!(a => a.key ~ "=" ~ a.value);
1042 			else static if( is(typeof(value) == enum) )
1043 				return only(value);
1044 			else static if( is(typeof(value) == Flags!BuildRequirement) )
1045 				return only(cast(BuildRequirement) cast(int) value.values);
1046 			else static if( is(typeof(value) == Flags!BuildOption) )
1047 				return only(cast(BuildOption) cast(int) value.values);
1048 			else
1049 				static assert(false, "Type of BuildSettings."~attributeName~" is unsupported.");
1050 		}
1051 
1052 		// Adjust BuildSetting member attributeName as needed.
1053 		// Returns a range of strings.
1054 		auto getFixedBuildSetting(Package pack) {
1055 			// Is relative path(s) to a directory?
1056 			enum isRelativeDirectory =
1057 				attributeName == "importPaths" || attributeName == "stringImportPaths" ||
1058 				attributeName == "targetPath" || attributeName == "workingDirectory";
1059 
1060 			// Is relative path(s) to a file?
1061 			enum isRelativeFile =
1062 				attributeName == "sourceFiles" || attributeName == "linkerFiles" ||
1063 				attributeName == "importFiles" || attributeName == "stringImportFiles" ||
1064 				attributeName == "copyFiles" || attributeName == "mainSourceFile" ||
1065 				attributeName == "injectSourceFiles";
1066 
1067 			// For these, empty string means "main project directory", not "missing value"
1068 			enum allowEmptyString =
1069 				attributeName == "targetPath" || attributeName == "workingDirectory";
1070 
1071 			enum isEnumBitfield =
1072 				attributeName == "requirements" || attributeName == "options";
1073 
1074 			enum isEnum = attributeName == "targetType";
1075 
1076 			auto values = getRawBuildSetting(pack, allowEmptyString);
1077 			string fixRelativePath(string importPath) { return buildNormalizedPath(pack.path.toString(), importPath); }
1078 			static string ensureTrailingSlash(string path) { return path.endsWith(dirSeparator) ? path : path ~ dirSeparator; }
1079 
1080 			static if(isRelativeDirectory) {
1081 				// Return full paths for the paths, making sure a
1082 				// directory separator is on the end of each path.
1083 				return values.map!(fixRelativePath).map!(ensureTrailingSlash);
1084 			}
1085 			else static if(isRelativeFile) {
1086 				// Return full paths.
1087 				return values.map!(fixRelativePath);
1088 			}
1089 			else static if(isEnumBitfield)
1090 				return bitFieldNames(values.front);
1091 			else static if (isEnum)
1092 				return [values.front.to!string];
1093 			else
1094 				return values;
1095 		}
1096 
1097 		foreach(value; getFixedBuildSetting(m_rootPackage)) {
1098 			list ~= value;
1099 		}
1100 
1101 		return list;
1102 	}
1103 
1104 	// The "compiler" arg is for choosing which compiler the output should be formatted for,
1105 	// or null to imply "list" format.
1106 	private string[] listBuildSetting(ref GeneratorSettings settings, string[string] configs,
1107 		ProjectDescription projectDescription, string requestedData, Compiler compiler, bool disableEscaping)
1108 	{
1109 		// Certain data cannot be formatter for a compiler
1110 		if (compiler)
1111 		{
1112 			switch (requestedData)
1113 			{
1114 			case "target-type":
1115 			case "target-path":
1116 			case "target-name":
1117 			case "working-directory":
1118 			case "string-import-files":
1119 			case "copy-files":
1120 			case "extra-dependency-files":
1121 			case "pre-generate-commands":
1122 			case "post-generate-commands":
1123 			case "pre-build-commands":
1124 			case "post-build-commands":
1125 			case "pre-run-commands":
1126 			case "post-run-commands":
1127 			case "environments":
1128 			case "build-environments":
1129 			case "run-environments":
1130 			case "pre-generate-environments":
1131 			case "post-generate-environments":
1132 			case "pre-build-environments":
1133 			case "post-build-environments":
1134 			case "pre-run-environments":
1135 			case "post-run-environments":
1136 				enforce(false, "--data="~requestedData~" can only be used with `--data-list` or `--data-list --data-0`.");
1137 				break;
1138 
1139 			case "requirements":
1140 				enforce(false, "--data=requirements can only be used with `--data-list` or `--data-list --data-0`. Use --data=options instead.");
1141 				break;
1142 
1143 			default: break;
1144 			}
1145 		}
1146 
1147 		import std.typetuple : TypeTuple;
1148 		auto args = TypeTuple!(settings, configs, projectDescription, compiler, disableEscaping);
1149 		switch (requestedData)
1150 		{
1151 		case "target-type":                return listBuildSetting!"targetType"(args);
1152 		case "target-path":                return listBuildSetting!"targetPath"(args);
1153 		case "target-name":                return listBuildSetting!"targetName"(args);
1154 		case "working-directory":          return listBuildSetting!"workingDirectory"(args);
1155 		case "main-source-file":           return listBuildSetting!"mainSourceFile"(args);
1156 		case "dflags":                     return listBuildSetting!"dflags"(args);
1157 		case "lflags":                     return listBuildSetting!"lflags"(args);
1158 		case "libs":                       return listBuildSetting!"libs"(args);
1159 		case "linker-files":               return listBuildSetting!"linkerFiles"(args);
1160 		case "source-files":               return listBuildSetting!"sourceFiles"(args);
1161 		case "inject-source-files":        return listBuildSetting!"injectSourceFiles"(args);
1162 		case "copy-files":                 return listBuildSetting!"copyFiles"(args);
1163 		case "extra-dependency-files":     return listBuildSetting!"extraDependencyFiles"(args);
1164 		case "versions":                   return listBuildSetting!"versions"(args);
1165 		case "debug-versions":             return listBuildSetting!"debugVersions"(args);
1166 		case "import-paths":               return listBuildSetting!"importPaths"(args);
1167 		case "string-import-paths":        return listBuildSetting!"stringImportPaths"(args);
1168 		case "import-files":               return listBuildSetting!"importFiles"(args);
1169 		case "string-import-files":        return listBuildSetting!"stringImportFiles"(args);
1170 		case "pre-generate-commands":      return listBuildSetting!"preGenerateCommands"(args);
1171 		case "post-generate-commands":     return listBuildSetting!"postGenerateCommands"(args);
1172 		case "pre-build-commands":         return listBuildSetting!"preBuildCommands"(args);
1173 		case "post-build-commands":        return listBuildSetting!"postBuildCommands"(args);
1174 		case "pre-run-commands":           return listBuildSetting!"preRunCommands"(args);
1175 		case "post-run-commands":          return listBuildSetting!"postRunCommands"(args);
1176 		case "environments":               return listBuildSetting!"environments"(args);
1177 		case "build-environments":         return listBuildSetting!"buildEnvironments"(args);
1178 		case "run-environments":           return listBuildSetting!"runEnvironments"(args);
1179 		case "pre-generate-environments":  return listBuildSetting!"preGenerateEnvironments"(args);
1180 		case "post-generate-environments": return listBuildSetting!"postGenerateEnvironments"(args);
1181 		case "pre-build-environments":     return listBuildSetting!"preBuildEnvironments"(args);
1182 		case "post-build-environments":    return listBuildSetting!"postBuildEnvironments"(args);
1183 		case "pre-run-environments":       return listBuildSetting!"preRunEnvironments"(args);
1184 		case "post-run-environments":      return listBuildSetting!"postRunEnvironments"(args);
1185 		case "requirements":               return listBuildSetting!"requirements"(args);
1186 		case "options":                    return listBuildSetting!"options"(args);
1187 
1188 		default:
1189 			enforce(false, "--data="~requestedData~
1190 				" is not a valid option. See 'dub describe --help' for accepted --data= values.");
1191 		}
1192 
1193 		assert(0);
1194 	}
1195 
1196 	/// Outputs requested data for the project, optionally including its dependencies.
1197 	string[] listBuildSettings(GeneratorSettings settings, string[] requestedData, ListBuildSettingsFormat list_type)
1198 	{
1199 		import dub.compilers.utils : isLinkerFile;
1200 
1201 		auto projectDescription = describe(settings);
1202 		auto configs = getPackageConfigs(settings.platform, settings.config);
1203 		PackageDescription packageDescription;
1204 		foreach (pack; projectDescription.packages) {
1205 			if (pack.name == projectDescription.rootPackage)
1206 				packageDescription = pack;
1207 		}
1208 
1209 		if (projectDescription.rootPackage in projectDescription.targetLookup) {
1210 			// Copy linker files from sourceFiles to linkerFiles
1211 			auto target = projectDescription.lookupTarget(projectDescription.rootPackage);
1212 			foreach (file; target.buildSettings.sourceFiles.filter!(f => isLinkerFile(settings.platform, f)))
1213 				target.buildSettings.addLinkerFiles(file);
1214 
1215 			// Remove linker files from sourceFiles
1216 			target.buildSettings.sourceFiles =
1217 				target.buildSettings.sourceFiles
1218 				.filter!(a => !isLinkerFile(settings.platform, a))
1219 				.array();
1220 			projectDescription.lookupTarget(projectDescription.rootPackage) = target;
1221 		}
1222 
1223 		Compiler compiler;
1224 		bool no_escape;
1225 		final switch (list_type) with (ListBuildSettingsFormat) {
1226 			case list: break;
1227 			case listNul: no_escape = true; break;
1228 			case commandLine: compiler = settings.compiler; break;
1229 			case commandLineNul: compiler = settings.compiler; no_escape = true; break;
1230 
1231 		}
1232 
1233 		auto result = requestedData
1234 			.map!(dataName => listBuildSetting(settings, configs, projectDescription, dataName, compiler, no_escape));
1235 
1236 		final switch (list_type) with (ListBuildSettingsFormat) {
1237 			case list: return result.map!(l => l.join("\n")).array();
1238 			case listNul: return result.map!(l => l.join("\0")).array;
1239 			case commandLine: return result.map!(l => l.join(" ")).array;
1240 			case commandLineNul: return result.map!(l => l.join("\0")).array;
1241 		}
1242 	}
1243 
1244 	/** Saves the currently selected dependency versions to disk.
1245 
1246 		The selections will be written to a file named
1247 		`SelectedVersions.defaultFile` ("dub.selections.json") within the
1248 		directory of the root package. Any existing file will get overwritten.
1249 	*/
1250 	void saveSelections()
1251 	{
1252 		assert(m_selections !is null, "Cannot save selections for non-disk based project (has no selections).");
1253 		if (m_selections.hasSelectedVersion(m_rootPackage.basePackage.name))
1254 			m_selections.deselectVersion(m_rootPackage.basePackage.name);
1255 
1256 		auto path = m_rootPackage.path ~ SelectedVersions.defaultFile;
1257 		if (m_selections.dirty || !existsFile(path))
1258 			m_selections.save(path);
1259 	}
1260 
1261 	deprecated bool isUpgradeCacheUpToDate()
1262 	{
1263 		return false;
1264 	}
1265 
1266 	deprecated Dependency[string] getUpgradeCache()
1267 	{
1268 		return null;
1269 	}
1270 }
1271 
1272 
1273 /// Determines the output format used for `Project.listBuildSettings`.
1274 enum ListBuildSettingsFormat {
1275 	list,           /// Newline separated list entries
1276 	listNul,        /// NUL character separated list entries (unescaped)
1277 	commandLine,    /// Formatted for compiler command line (one data list per line)
1278 	commandLineNul, /// NUL character separated list entries (unescaped, data lists separated by two NUL characters)
1279 }
1280 
1281 deprecated("Use `dub.packagemanager : PlacementLocation` instead")
1282 public alias PlacementLocation = dub.packagemanager.PlacementLocation;
1283 
1284 void processVars(ref BuildSettings dst, in Project project, in Package pack,
1285 	BuildSettings settings, in GeneratorSettings gsettings, bool include_target_settings = false)
1286 {
1287 	string[string] processVerEnvs(in string[string] targetEnvs, in string[string] defaultEnvs)
1288 	{
1289 		string[string] retEnv;
1290 		foreach (k, v; targetEnvs)
1291 			retEnv[k] = v;
1292 		foreach (k, v; defaultEnvs) {
1293 			if (k !in targetEnvs)
1294 				retEnv[k] = v;
1295 		}
1296 		return processVars(project, pack, gsettings, retEnv);
1297 	}
1298 	dst.addEnvironments(processVerEnvs(settings.environments, gsettings.buildSettings.environments));
1299 	dst.addBuildEnvironments(processVerEnvs(settings.buildEnvironments, gsettings.buildSettings.buildEnvironments));
1300 	dst.addRunEnvironments(processVerEnvs(settings.runEnvironments, gsettings.buildSettings.runEnvironments));
1301 	dst.addPreGenerateEnvironments(processVerEnvs(settings.preGenerateEnvironments, gsettings.buildSettings.preGenerateEnvironments));
1302 	dst.addPostGenerateEnvironments(processVerEnvs(settings.postGenerateEnvironments, gsettings.buildSettings.postGenerateEnvironments));
1303 	dst.addPreBuildEnvironments(processVerEnvs(settings.preBuildEnvironments, gsettings.buildSettings.preBuildEnvironments));
1304 	dst.addPostBuildEnvironments(processVerEnvs(settings.postBuildEnvironments, gsettings.buildSettings.postBuildEnvironments));
1305 	dst.addPreRunEnvironments(processVerEnvs(settings.preRunEnvironments, gsettings.buildSettings.preRunEnvironments));
1306 	dst.addPostRunEnvironments(processVerEnvs(settings.postRunEnvironments, gsettings.buildSettings.postRunEnvironments));
1307 
1308 	auto buildEnvs = [dst.environments, dst.buildEnvironments];
1309 
1310 	dst.addDFlags(processVars(project, pack, gsettings, settings.dflags, false, buildEnvs));
1311 	dst.addLFlags(processVars(project, pack, gsettings, settings.lflags, false, buildEnvs));
1312 	dst.addLibs(processVars(project, pack, gsettings, settings.libs, false, buildEnvs));
1313 	dst.addSourceFiles(processVars!true(project, pack, gsettings, settings.sourceFiles, true, buildEnvs));
1314 	dst.addImportFiles(processVars(project, pack, gsettings, settings.importFiles, true, buildEnvs));
1315 	dst.addStringImportFiles(processVars(project, pack, gsettings, settings.stringImportFiles, true, buildEnvs));
1316 	dst.addInjectSourceFiles(processVars!true(project, pack, gsettings, settings.injectSourceFiles, true, buildEnvs));
1317 	dst.addCopyFiles(processVars(project, pack, gsettings, settings.copyFiles, true, buildEnvs));
1318 	dst.addExtraDependencyFiles(processVars(project, pack, gsettings, settings.extraDependencyFiles, true, buildEnvs));
1319 	dst.addVersions(processVars(project, pack, gsettings, settings.versions, false, buildEnvs));
1320 	dst.addDebugVersions(processVars(project, pack, gsettings, settings.debugVersions, false, buildEnvs));
1321 	dst.addVersionFilters(processVars(project, pack, gsettings, settings.versionFilters, false, buildEnvs));
1322 	dst.addDebugVersionFilters(processVars(project, pack, gsettings, settings.debugVersionFilters, false, buildEnvs));
1323 	dst.addImportPaths(processVars(project, pack, gsettings, settings.importPaths, true, buildEnvs));
1324 	dst.addStringImportPaths(processVars(project, pack, gsettings, settings.stringImportPaths, true, buildEnvs));
1325 	dst.addRequirements(settings.requirements);
1326 	dst.addOptions(settings.options);
1327 
1328 	// commands are substituted in dub.generators.generator : runBuildCommands
1329 	dst.addPreGenerateCommands(settings.preGenerateCommands);
1330 	dst.addPostGenerateCommands(settings.postGenerateCommands);
1331 	dst.addPreBuildCommands(settings.preBuildCommands);
1332 	dst.addPostBuildCommands(settings.postBuildCommands);
1333 	dst.addPreRunCommands(settings.preRunCommands);
1334 	dst.addPostRunCommands(settings.postRunCommands);
1335 
1336 	if (include_target_settings) {
1337 		dst.targetType = settings.targetType;
1338 		dst.targetPath = processVars(settings.targetPath, project, pack, gsettings, true, buildEnvs);
1339 		dst.targetName = settings.targetName;
1340 		if (!settings.workingDirectory.empty)
1341 			dst.workingDirectory = processVars(settings.workingDirectory, project, pack, gsettings, true, buildEnvs);
1342 		if (settings.mainSourceFile.length)
1343 			dst.mainSourceFile = processVars(settings.mainSourceFile, project, pack, gsettings, true, buildEnvs);
1344 	}
1345 }
1346 
1347 string[] processVars(bool glob = false)(in Project project, in Package pack, in GeneratorSettings gsettings, in string[] vars, bool are_paths = false, in string[string][] extraVers = null)
1348 {
1349 	auto ret = appender!(string[])();
1350 	processVars!glob(ret, project, pack, gsettings, vars, are_paths, extraVers);
1351 	return ret.data;
1352 }
1353 void processVars(bool glob = false)(ref Appender!(string[]) dst, in Project project, in Package pack, in GeneratorSettings gsettings, in string[] vars, bool are_paths = false, in string[string][] extraVers = null)
1354 {
1355 	static if (glob)
1356 		alias process = processVarsWithGlob!(Project, Package);
1357 	else
1358 		alias process = processVars!(Project, Package);
1359 	foreach (var; vars)
1360 		dst.put(process(var, project, pack, gsettings, are_paths, extraVers));
1361 }
1362 
1363 string processVars(Project, Package)(string var, in Project project, in Package pack, in GeneratorSettings gsettings, bool is_path, in string[string][] extraVers = null)
1364 {
1365 	var = var.expandVars!(varName => getVariable(varName, project, pack, gsettings, extraVers));
1366 	if (!is_path)
1367 		return var;
1368 	auto p = NativePath(var);
1369 	if (!p.absolute)
1370 		return (pack.path ~ p).toNativeString();
1371 	else
1372 		return p.toNativeString();
1373 }
1374 string[string] processVars(bool glob = false)(in Project project, in Package pack, in GeneratorSettings gsettings, in string[string] vars, in string[string][] extraVers = null)
1375 {
1376 	string[string] ret;
1377 	processVars!glob(ret, project, pack, gsettings, vars, extraVers);
1378 	return ret;
1379 }
1380 void processVars(bool glob = false)(ref string[string] dst, in Project project, in Package pack, in GeneratorSettings gsettings, in string[string] vars, in string[string][] extraVers)
1381 {
1382 	static if (glob)
1383 		alias process = processVarsWithGlob!(Project, Package);
1384 	else
1385 		alias process = processVars!(Project, Package);
1386 	foreach (k, var; vars)
1387 		dst[k] = process(var, project, pack, gsettings, false, extraVers);
1388 }
1389 
1390 private string[] processVarsWithGlob(Project, Package)(string var, in Project project, in Package pack, in GeneratorSettings gsettings, bool is_path, in string[string][] extraVers)
1391 {
1392 	assert(is_path, "can't glob something that isn't a path");
1393 	string res = processVars(var, project, pack, gsettings, is_path, extraVers);
1394 	// Find the unglobbed prefix and iterate from there.
1395 	size_t i = 0;
1396 	size_t sepIdx = 0;
1397 	loop: while (i < res.length) {
1398 		switch_: switch (res[i])
1399 		{
1400 		case '*', '?', '[', '{': break loop;
1401 		case '/': sepIdx = i; goto default;
1402 		version (Windows) { case '\\': sepIdx = i; goto default; }
1403 		default: ++i; break switch_;
1404 		}
1405 	}
1406 	if (i == res.length) //no globbing found in the path
1407 		return [res];
1408 	import std.path : globMatch;
1409 	import std.file : dirEntries, SpanMode;
1410 	return dirEntries(res[0 .. sepIdx], SpanMode.depth)
1411 		.map!(de => de.name)
1412 		.filter!(name => globMatch(name, res))
1413 		.array;
1414 }
1415 /// Expand variables using `$VAR_NAME` or `${VAR_NAME}` syntax.
1416 /// `$$` escapes itself and is expanded to a single `$`.
1417 private string expandVars(alias expandVar)(string s)
1418 {
1419 	import std.functional : not;
1420 
1421 	auto result = appender!string;
1422 
1423 	static bool isVarChar(char c)
1424 	{
1425 		import std.ascii;
1426 		return isAlphaNum(c) || c == '_';
1427 	}
1428 
1429 	while (true)
1430 	{
1431 		auto pos = s.indexOf('$');
1432 		if (pos < 0)
1433 		{
1434 			result.put(s);
1435 			return result.data;
1436 		}
1437 		result.put(s[0 .. pos]);
1438 		s = s[pos + 1 .. $];
1439 		enforce(s.length > 0, "Variable name expected at end of string");
1440 		switch (s[0])
1441 		{
1442 			case '$':
1443 				result.put("$");
1444 				s = s[1 .. $];
1445 				break;
1446 			case '{':
1447 				pos = s.indexOf('}');
1448 				enforce(pos >= 0, "Could not find '}' to match '${'");
1449 				result.put(expandVar(s[1 .. pos]));
1450 				s = s[pos + 1 .. $];
1451 				break;
1452 			default:
1453 				pos = s.representation.countUntil!(not!isVarChar);
1454 				if (pos < 0)
1455 					pos = s.length;
1456 				result.put(expandVar(s[0 .. pos]));
1457 				s = s[pos .. $];
1458 				break;
1459 		}
1460 	}
1461 }
1462 
1463 unittest
1464 {
1465 	string[string] vars =
1466 	[
1467 		"A" : "a",
1468 		"B" : "b",
1469 	];
1470 
1471 	string expandVar(string name) { auto p = name in vars; enforce(p, name); return *p; }
1472 
1473 	assert(expandVars!expandVar("") == "");
1474 	assert(expandVars!expandVar("x") == "x");
1475 	assert(expandVars!expandVar("$$") == "$");
1476 	assert(expandVars!expandVar("x$$") == "x$");
1477 	assert(expandVars!expandVar("$$x") == "$x");
1478 	assert(expandVars!expandVar("$$$$") == "$$");
1479 	assert(expandVars!expandVar("x$A") == "xa");
1480 	assert(expandVars!expandVar("x$$A") == "x$A");
1481 	assert(expandVars!expandVar("$A$B") == "ab");
1482 	assert(expandVars!expandVar("${A}$B") == "ab");
1483 	assert(expandVars!expandVar("$A${B}") == "ab");
1484 	assert(expandVars!expandVar("a${B}") == "ab");
1485 	assert(expandVars!expandVar("${A}b") == "ab");
1486 
1487 	import std.exception : assertThrown;
1488 	assertThrown(expandVars!expandVar("$"));
1489 	assertThrown(expandVars!expandVar("${}"));
1490 	assertThrown(expandVars!expandVar("$|"));
1491 	assertThrown(expandVars!expandVar("x$"));
1492 	assertThrown(expandVars!expandVar("$X"));
1493 	assertThrown(expandVars!expandVar("${"));
1494 	assertThrown(expandVars!expandVar("${X"));
1495 
1496 	// https://github.com/dlang/dmd/pull/9275
1497 	assert(expandVars!expandVar("$${DUB_EXE:-dub}") == "${DUB_EXE:-dub}");
1498 }
1499 
1500 /// Expands the variables in the input string with the same rules as command
1501 /// variables inside custom dub commands.
1502 ///
1503 /// Params:
1504 ///     s = the input string where environment variables in form `$VAR` should be replaced
1505 ///     throwIfMissing = if true, throw an exception if the given variable is not found,
1506 ///                      otherwise replace unknown variables with the empty string.
1507 string expandEnvironmentVariables(string s, bool throwIfMissing = true)
1508 {
1509 	import std.process : environment;
1510 
1511 	return expandVars!((v) {
1512 		auto ret = environment.get(v);
1513 		if (ret is null && throwIfMissing)
1514 			throw new Exception("Specified environment variable `$" ~ v ~ "` is not set");
1515 		return ret;
1516 	})(s);
1517 }
1518 
1519 // Keep the following list up-to-date if adding more build settings variables.
1520 /// List of variables that can be used in build settings
1521 package(dub) immutable buildSettingsVars = [
1522 	"ARCH", "PLATFORM", "PLATFORM_POSIX", "BUILD_TYPE"
1523 ];
1524 
1525 private string getVariable(Project, Package)(string name, in Project project, in Package pack, in GeneratorSettings gsettings, in string[string][] extraVars = null)
1526 {
1527 	import dub.internal.utils : getDUBExePath;
1528 	import std.process : environment, escapeShellFileName;
1529 	import std.uni : asUpperCase;
1530 
1531 	NativePath path;
1532 	if (name == "PACKAGE_DIR")
1533 		path = pack.path;
1534 	else if (name == "ROOT_PACKAGE_DIR")
1535 		path = project.rootPackage.path;
1536 
1537 	if (name.endsWith("_PACKAGE_DIR")) {
1538 		auto pname = name[0 .. $-12];
1539 		foreach (prj; project.getTopologicalPackageList())
1540 			if (prj.name.asUpperCase.map!(a => a == '-' ? '_' : a).equal(pname))
1541 			{
1542 				path = prj.path;
1543 				break;
1544 			}
1545 	}
1546 
1547 	if (!path.empty)
1548 	{
1549 		// no trailing slash for clean path concatenation (see #1392)
1550 		path.endsWithSlash = false;
1551 		return path.toNativeString();
1552 	}
1553 
1554 	if (name == "DUB") {
1555 		return getDUBExePath(gsettings.platform.compilerBinary);
1556 	}
1557 
1558 	if (name == "ARCH") {
1559 		foreach (a; gsettings.platform.architecture)
1560 			return a;
1561 		return "";
1562 	}
1563 
1564 	if (name == "PLATFORM") {
1565 		import std.algorithm : filter;
1566 		foreach (p; gsettings.platform.platform.filter!(p => p != "posix"))
1567 			return p;
1568 		foreach (p; gsettings.platform.platform)
1569 			return p;
1570 		return "";
1571 	}
1572 
1573 	if (name == "PLATFORM_POSIX") {
1574 		import std.algorithm : canFind;
1575 		if (gsettings.platform.platform.canFind("posix"))
1576 			return "posix";
1577 		foreach (p; gsettings.platform.platform)
1578 			return p;
1579 		return "";
1580 	}
1581 
1582 	if (name == "BUILD_TYPE") return gsettings.buildType;
1583 
1584 	if (name == "DFLAGS" || name == "LFLAGS")
1585 	{
1586 		auto buildSettings = pack.getBuildSettings(gsettings.platform, gsettings.config);
1587 		if (name == "DFLAGS")
1588 			return join(buildSettings.dflags," ");
1589 		else if (name == "LFLAGS")
1590 			return join(buildSettings.lflags," ");
1591 	}
1592 
1593 	import std.range;
1594 	foreach (aa; retro(extraVars))
1595 		if (auto exvar = name in aa)
1596 			return *exvar;
1597 
1598 	auto envvar = environment.get(name);
1599 	if (envvar !is null) return envvar;
1600 
1601 	throw new Exception("Invalid variable: "~name);
1602 }
1603 
1604 
1605 unittest
1606 {
1607 	static struct MockPackage
1608 	{
1609 		this(string name)
1610 		{
1611 			this.name = name;
1612 			version (Posix)
1613 				path = NativePath("/pkgs/"~name);
1614 			else version (Windows)
1615 				path = NativePath(`C:\pkgs\`~name);
1616 			// see 4d4017c14c, #268, and #1392 for why this all package paths end on slash internally
1617 			path.endsWithSlash = true;
1618 		}
1619 		string name;
1620 		NativePath path;
1621 		BuildSettings getBuildSettings(in BuildPlatform platform, string config) const
1622 		{
1623 			return BuildSettings();
1624 		}
1625 	}
1626 
1627 	static struct MockProject
1628 	{
1629 		MockPackage rootPackage;
1630 		inout(MockPackage)[] getTopologicalPackageList() inout
1631 		{
1632 			return _dependencies;
1633 		}
1634 	private:
1635 		MockPackage[] _dependencies;
1636 	}
1637 
1638 	MockProject proj = {
1639 		rootPackage: MockPackage("root"),
1640 		_dependencies: [MockPackage("dep1"), MockPackage("dep2")]
1641 	};
1642 	auto pack = MockPackage("test");
1643 	GeneratorSettings gsettings;
1644 	enum isPath = true;
1645 
1646 	import std.path : dirSeparator;
1647 
1648 	static NativePath woSlash(NativePath p) { p.endsWithSlash = false; return p; }
1649 	// basic vars
1650 	assert(processVars("Hello $PACKAGE_DIR", proj, pack, gsettings, !isPath) == "Hello "~woSlash(pack.path).toNativeString);
1651 	assert(processVars("Hello $ROOT_PACKAGE_DIR", proj, pack, gsettings, !isPath) == "Hello "~woSlash(proj.rootPackage.path).toNativeString.chomp(dirSeparator));
1652 	assert(processVars("Hello $DEP1_PACKAGE_DIR", proj, pack, gsettings, !isPath) == "Hello "~woSlash(proj._dependencies[0].path).toNativeString);
1653 	// ${VAR} replacements
1654 	assert(processVars("Hello ${PACKAGE_DIR}"~dirSeparator~"foobar", proj, pack, gsettings, !isPath) == "Hello "~(pack.path ~ "foobar").toNativeString);
1655 	assert(processVars("Hello $PACKAGE_DIR"~dirSeparator~"foobar", proj, pack, gsettings, !isPath) == "Hello "~(pack.path ~ "foobar").toNativeString);
1656 	// test with isPath
1657 	assert(processVars("local", proj, pack, gsettings, isPath) == (pack.path ~ "local").toNativeString);
1658 	assert(processVars("foo/$$ESCAPED", proj, pack, gsettings, isPath) == (pack.path ~ "foo/$ESCAPED").toNativeString);
1659 	assert(processVars("$$ESCAPED", proj, pack, gsettings, !isPath) == "$ESCAPED");
1660 	// test other env variables
1661 	import std.process : environment;
1662 	environment["MY_ENV_VAR"] = "blablabla";
1663 	assert(processVars("$MY_ENV_VAR", proj, pack, gsettings, !isPath) == "blablabla");
1664 	assert(processVars("${MY_ENV_VAR}suffix", proj, pack, gsettings, !isPath) == "blablablasuffix");
1665 	assert(processVars("$MY_ENV_VAR-suffix", proj, pack, gsettings, !isPath) == "blablabla-suffix");
1666 	assert(processVars("$MY_ENV_VAR:suffix", proj, pack, gsettings, !isPath) == "blablabla:suffix");
1667 	assert(processVars("$MY_ENV_VAR$MY_ENV_VAR", proj, pack, gsettings, !isPath) == "blablablablablabla");
1668 	environment.remove("MY_ENV_VAR");
1669 }
1670 
1671 /** Holds and stores a set of version selections for package dependencies.
1672 
1673 	This is the runtime representation of the information contained in
1674 	"dub.selections.json" within a package's directory.
1675 */
1676 final class SelectedVersions {
1677 	private {
1678 		enum FileVersion = 1;
1679 		Selected m_selections;
1680 		bool m_dirty = false; // has changes since last save
1681 		bool m_bare = true;
1682 	}
1683 
1684 	/// Default file name to use for storing selections.
1685 	enum defaultFile = "dub.selections.json";
1686 
1687 	/// Constructs a new empty version selection.
1688 	public this(uint version_ = FileVersion) @safe pure nothrow @nogc
1689 	{
1690 		this.m_selections = Selected(version_);
1691 	}
1692 
1693 	/// Constructs a new non-empty version selection.
1694 	public this(Selected data) @safe pure nothrow @nogc
1695 	{
1696 		this.m_selections = data;
1697 		this.m_bare = false;
1698 	}
1699 
1700 	/** Constructs a new version selection from JSON data.
1701 
1702 		The structure of the JSON document must match the contents of the
1703 		"dub.selections.json" file.
1704 	*/
1705 	deprecated("Pass a `dub.recipe.selection : Selected` directly")
1706 	this(Json data)
1707 	{
1708 		deserialize(data);
1709 		m_dirty = false;
1710 	}
1711 
1712 	/** Constructs a new version selections from an existing JSON file.
1713 	*/
1714 	deprecated("JSON deserialization is deprecated")
1715 	this(NativePath path)
1716 	{
1717 		auto json = jsonFromFile(path);
1718 		deserialize(json);
1719 		m_dirty = false;
1720 		m_bare = false;
1721 	}
1722 
1723 	/// Returns a list of names for all packages that have a version selection.
1724 	@property string[] selectedPackages() const { return m_selections.versions.keys; }
1725 
1726 	/// Determines if any changes have been made after loading the selections from a file.
1727 	@property bool dirty() const { return m_dirty; }
1728 
1729 	/// Determine if this set of selections is still empty (but not `clear`ed).
1730 	@property bool bare() const { return m_bare && !m_dirty; }
1731 
1732 	/// Removes all selections.
1733 	void clear()
1734 	{
1735 		m_selections.versions = null;
1736 		m_dirty = true;
1737 	}
1738 
1739 	/// Duplicates the set of selected versions from another instance.
1740 	void set(SelectedVersions versions)
1741 	{
1742 		m_selections.fileVersion = versions.m_selections.fileVersion;
1743 		m_selections.versions = versions.m_selections.versions.dup;
1744 		m_dirty = true;
1745 	}
1746 
1747 	/// Selects a certain version for a specific package.
1748 	void selectVersion(string package_id, Version version_)
1749 	{
1750 		if (auto pdep = package_id in m_selections.versions) {
1751 			if (*pdep == Dependency(version_))
1752 				return;
1753 		}
1754 		m_selections.versions[package_id] = Dependency(version_);
1755 		m_dirty = true;
1756 	}
1757 
1758 	/// Selects a certain path for a specific package.
1759 	void selectVersion(string package_id, NativePath path)
1760 	{
1761 		if (auto pdep = package_id in m_selections.versions) {
1762 			if (*pdep == Dependency(path))
1763 				return;
1764 		}
1765 		m_selections.versions[package_id] = Dependency(path);
1766 		m_dirty = true;
1767 	}
1768 
1769 	/// Selects a certain Git reference for a specific package.
1770 	void selectVersion(string package_id, Repository repository)
1771 	{
1772 		const dependency = Dependency(repository);
1773 		if (auto pdep = package_id in m_selections.versions) {
1774 			if (*pdep == dependency)
1775 				return;
1776 		}
1777 		m_selections.versions[package_id] = dependency;
1778 		m_dirty = true;
1779 	}
1780 
1781 	deprecated("Move `spec` inside of the `repository` parameter and call `selectVersion`")
1782 	void selectVersionWithRepository(string package_id, Repository repository, string spec)
1783 	{
1784 		this.selectVersion(package_id, Repository(repository.remote(), spec));
1785 	}
1786 
1787 	/// Removes the selection for a particular package.
1788 	void deselectVersion(string package_id)
1789 	{
1790 		m_selections.versions.remove(package_id);
1791 		m_dirty = true;
1792 	}
1793 
1794 	/// Determines if a particular package has a selection set.
1795 	bool hasSelectedVersion(string packageId)
1796 	const {
1797 		return (packageId in m_selections.versions) !is null;
1798 	}
1799 
1800 	/** Returns the selection for a particular package.
1801 
1802 		Note that the returned `Dependency` can either have the
1803 		`Dependency.path` property set to a non-empty value, in which case this
1804 		is a path based selection, or its `Dependency.version_` property is
1805 		valid and it is a version selection.
1806 	*/
1807 	Dependency getSelectedVersion(string packageId)
1808 	const {
1809 		enforce(hasSelectedVersion(packageId));
1810 		return m_selections.versions[packageId];
1811 	}
1812 
1813 	/** Stores the selections to disk.
1814 
1815 		The target file will be written in JSON format. Usually, `defaultFile`
1816 		should be used as the file name and the directory should be the root
1817 		directory of the project's root package.
1818 	*/
1819 	void save(NativePath path)
1820 	{
1821 		Json json = serialize();
1822 		auto result = appender!string();
1823 
1824 		assert(json.type == Json.Type.object);
1825 		assert(json.length == 2);
1826 		assert(json["versions"].type != Json.Type.undefined);
1827 
1828 		result.put("{\n\t\"fileVersion\": ");
1829 		result.writeJsonString(json["fileVersion"]);
1830 		result.put(",\n\t\"versions\": {");
1831 		auto vers = json["versions"].get!(Json[string]);
1832 		bool first = true;
1833 		foreach (k; vers.byKey.array.sort()) {
1834 			if (!first) result.put(",");
1835 			else first = false;
1836 			result.put("\n\t\t");
1837 			result.writeJsonString(Json(k));
1838 			result.put(": ");
1839 			result.writeJsonString(vers[k]);
1840 		}
1841 		result.put("\n\t}\n}\n");
1842 		path.writeFile(result.data);
1843 		m_dirty = false;
1844 		m_bare = false;
1845 	}
1846 
1847 	deprecated("Use `dub.dependency : Dependency.toJson(true)`")
1848 	static Json dependencyToJson(Dependency d)
1849 	{
1850 		return d.toJson(true);
1851 	}
1852 
1853 	deprecated("JSON deserialization is deprecated")
1854 	static Dependency dependencyFromJson(Json j)
1855 	{
1856 		if (j.type == Json.Type..string)
1857 			return Dependency(Version(j.get!string));
1858 		else if (j.type == Json.Type.object && "path" in j)
1859 			return Dependency(NativePath(j["path"].get!string));
1860 		else if (j.type == Json.Type.object && "repository" in j)
1861 			return Dependency(Repository(j["repository"].get!string,
1862 				enforce("version" in j, "Expected \"version\" field in repository version object").get!string));
1863 		else throw new Exception(format("Unexpected type for dependency: %s", j));
1864 	}
1865 
1866 	Json serialize()
1867 	const {
1868 		Json json = serializeToJson(m_selections);
1869 		Json serialized = Json.emptyObject;
1870 		serialized["fileVersion"] = m_selections.fileVersion;
1871 		serialized["versions"] = Json.emptyObject;
1872 		foreach (p, dep; m_selections.versions)
1873 			serialized["versions"][p] = dep.toJson(true);
1874 		return serialized;
1875 	}
1876 
1877 	deprecated("JSON deserialization is deprecated")
1878 	private void deserialize(Json json)
1879 	{
1880 		const fileVersion = json["fileVersion"].get!int;
1881 		enforce(fileVersion == FileVersion, "Mismatched dub.selections.json version: " ~ to!string(fileVersion) ~ " vs. " ~ to!string(FileVersion));
1882 		clear();
1883 		m_selections.fileVersion = fileVersion;
1884 		scope(failure) clear();
1885 		foreach (string p, dep; json["versions"])
1886 			m_selections.versions[p] = dependencyFromJson(dep);
1887 	}
1888 }
1889 
1890 /// The template code from which the test runner is generated
1891 private immutable TestRunnerTemplate = q{
1892 module dub_test_root;
1893 
1894 import std.typetuple;
1895 
1896 %-(static import %s;
1897 %);
1898 
1899 alias allModules = TypeTuple!(
1900     %-(%s, %)
1901 );
1902 
1903 %s
1904 };
1905 
1906 /// The default test runner that gets used if none is provided
1907 private immutable DefaultTestRunnerCode = q{
1908 import core.runtime;
1909 
1910 void main() {
1911 	version (D_Coverage) {
1912 	} else {
1913 		import std.stdio : writeln;
1914 		writeln("All unit tests have been run successfully.");
1915 	}
1916 }
1917 shared static this() {
1918 	version (Have_tested) {
1919 		import tested;
1920 		import core.runtime;
1921 		import std.exception;
1922 		Runtime.moduleUnitTester = () => true;
1923 		enforce(runUnitTests!allModules(new ConsoleTestResultWriter), "Unit tests failed.");
1924 	}
1925 }
1926 };