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