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