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