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