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