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