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