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