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.url;
  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. Json m_packageSettings;
  42. Package m_rootPackage;
  43. Package[] m_dependencies;
  44. Package[][Package] m_dependees;
  45. SelectedVersions m_selections;
  46. bool m_hasAllDependencies;
  47. string[string] m_overriddenConfigs;
  48. }
  49.  
  50. /** Loads a project.
  51.  
  52. Params:
  53. package_manager = Package manager instance to use for loading
  54. dependencies
  55. project_path = Path of the root package to load
  56. pack = An existing `Package` instance to use as the root package
  57. */
  58. this(PackageManager package_manager, NativePath project_path)
  59. {
  60. Package pack;
  61. auto packageFile = Package.findPackageFile(project_path);
  62. if (packageFile.empty) {
  63. logWarn("There was no package description found for the application in '%s'.", project_path.toNativeString());
  64. pack = new Package(PackageRecipe.init, project_path);
  65. } else {
  66. pack = package_manager.getOrLoadPackage(project_path, packageFile);
  67. }
  68.  
  69. this(package_manager, pack);
  70. }
  71.  
  72. /// ditto
  73. this(PackageManager package_manager, Package pack)
  74. {
  75. m_packageManager = package_manager;
  76. m_rootPackage = pack;
  77. m_packageSettings = Json.emptyObject;
  78.  
  79. try m_packageSettings = jsonFromFile(m_rootPackage.path ~ ".dub/dub.json", true);
  80. catch(Exception t) logDiagnostic("Failed to read .dub/dub.json: %s", t.msg);
  81.  
  82. auto selverfile = m_rootPackage.path ~ SelectedVersions.defaultFile;
  83. if (existsFile(selverfile)) {
  84. try m_selections = new SelectedVersions(selverfile);
  85. catch(Exception e) {
  86. logWarn("Failed to load %s: %s", SelectedVersions.defaultFile, e.msg);
  87. logDiagnostic("Full error: %s", e.toString().sanitize);
  88. m_selections = new SelectedVersions;
  89. }
  90. } else m_selections = new SelectedVersions;
  91.  
  92. reinit();
  93. }
  94.  
  95. /** List of all resolved dependencies.
  96.  
  97. This includes all direct and indirect dependencies of all configurations
  98. combined. Optional dependencies that were not chosen are not included.
  99. */
  100. @property const(Package[]) dependencies() const { return m_dependencies; }
  101.  
  102. /// The root package of the project.
  103. @property inout(Package) rootPackage() inout { return m_rootPackage; }
  104.  
  105. /// The versions to use for all dependencies. Call reinit() after changing these.
  106. @property inout(SelectedVersions) selections() inout { return m_selections; }
  107.  
  108. /// Package manager instance used by the project.
  109. @property inout(PackageManager) packageManager() inout { return m_packageManager; }
  110.  
  111. /** Determines if all dependencies necessary to build have been collected.
  112.  
  113. If this function returns `false`, it may be necessary to add more entries
  114. to `selections`, or to use `Dub.upgrade` to automatically select all
  115. missing dependencies.
  116. */
  117. bool hasAllDependencies() const { return m_hasAllDependencies; }
  118.  
  119. /** Allows iteration of the dependency tree in topological order
  120. */
  121. int delegate(int delegate(ref Package)) getTopologicalPackageList(bool children_first = false, Package root_package = null, string[string] configs = null)
  122. {
  123. // ugly way to avoid code duplication since inout isn't compatible with foreach type inference
  124. return cast(int delegate(int delegate(ref Package)))(cast(const)this).getTopologicalPackageList(children_first, root_package, configs);
  125. }
  126. /// ditto
  127. int delegate(int delegate(ref const Package)) getTopologicalPackageList(bool children_first = false, in Package root_package = null, string[string] configs = null)
  128. const {
  129. const(Package) rootpack = root_package ? root_package : m_rootPackage;
  130.  
  131. int iterator(int delegate(ref const Package) del)
  132. {
  133. int ret = 0;
  134. bool[const(Package)] visited;
  135. void perform_rec(in Package p){
  136. if( p in visited ) return;
  137. visited[p] = true;
  138.  
  139. if( !children_first ){
  140. ret = del(p);
  141. if( ret ) return;
  142. }
  143.  
  144. auto cfg = configs.get(p.name, null);
  145.  
  146. PackageDependency[] deps;
  147. if (!cfg.length) deps = p.getAllDependencies();
  148. else {
  149. auto depmap = p.getDependencies(cfg);
  150. deps = depmap.byKey.map!(k => PackageDependency(k, depmap[k])).array;
  151. }
  152. deps.sort!((a, b) => a.name < b.name);
  153.  
  154. foreach (d; deps) {
  155. auto dependency = getDependency(d.name, true);
  156. assert(dependency || d.spec.optional,
  157. format("Non-optional dependency %s of %s not found in dependency tree!?.", d.name, p.name));
  158. if(dependency) perform_rec(dependency);
  159. if( ret ) return;
  160. }
  161.  
  162. if( children_first ){
  163. ret = del(p);
  164. if( ret ) return;
  165. }
  166. }
  167. perform_rec(rootpack);
  168. return ret;
  169. }
  170.  
  171. return &iterator;
  172. }
  173.  
  174. /** Retrieves a particular dependency by name.
  175.  
  176. Params:
  177. name = (Qualified) package name of the dependency
  178. is_optional = If set to true, will return `null` for unsatisfiable
  179. dependencies instead of throwing an exception.
  180. */
  181. inout(Package) getDependency(string name, bool is_optional)
  182. inout {
  183. foreach(dp; m_dependencies)
  184. if( dp.name == name )
  185. return dp;
  186. if (!is_optional) throw new Exception("Unknown dependency: "~name);
  187. else return null;
  188. }
  189.  
  190. /** Returns the name of the default build configuration for the specified
  191. target platform.
  192.  
  193. Params:
  194. platform = The target build platform
  195. allow_non_library_configs = If set to true, will use the first
  196. possible configuration instead of the first "executable"
  197. configuration.
  198. */
  199. string getDefaultConfiguration(BuildPlatform platform, bool allow_non_library_configs = true)
  200. const {
  201. auto cfgs = getPackageConfigs(platform, null, allow_non_library_configs);
  202. return cfgs[m_rootPackage.name];
  203. }
  204.  
  205. /** Overrides the configuration chosen for a particular package in the
  206. dependency graph.
  207.  
  208. Setting a certain configuration here is equivalent to removing all
  209. but one configuration from the package.
  210.  
  211. Params:
  212. package_ = The package for which to force selecting a certain
  213. dependency
  214. config = Name of the configuration to force
  215. */
  216. void overrideConfiguration(string package_, string config)
  217. {
  218. auto p = getDependency(package_, true);
  219. enforce(p !is null,
  220. format("Package '%s', marked for configuration override, is not present in dependency graph.", package_));
  221. enforce(p.configurations.canFind(config),
  222. format("Package '%s' does not have a configuration named '%s'.", package_, config));
  223. m_overriddenConfigs[package_] = config;
  224. }
  225.  
  226. /** Performs basic validation of various aspects of the package.
  227.  
  228. This will emit warnings to `stderr` if any discouraged names or
  229. dependency patterns are found.
  230. */
  231. void validate()
  232. {
  233. // some basic package lint
  234. m_rootPackage.warnOnSpecialCompilerFlags();
  235. string nameSuggestion() {
  236. string ret;
  237. ret ~= `Please modify the "name" field in %s accordingly.`.format(m_rootPackage.recipePath.toNativeString());
  238. if (!m_rootPackage.recipe.buildSettings.targetName.length) {
  239. if (m_rootPackage.recipePath.head.toString().endsWith(".sdl")) {
  240. ret ~= ` You can then add 'targetName "%s"' to keep the current executable name.`.format(m_rootPackage.name);
  241. } else {
  242. ret ~= ` You can then add '"targetName": "%s"' to keep the current executable name.`.format(m_rootPackage.name);
  243. }
  244. }
  245. return ret;
  246. }
  247. if (m_rootPackage.name != m_rootPackage.name.toLower()) {
  248. logWarn(`WARNING: DUB package names should always be lower case. %s`, nameSuggestion());
  249. } else if (!m_rootPackage.recipe.name.all!(ch => ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_')) {
  250. logWarn(`WARNING: DUB package names may only contain alphanumeric characters, `
  251. ~ `as well as '-' and '_'. %s`, nameSuggestion());
  252. }
  253. enforce(!m_rootPackage.name.canFind(' '), "Aborting due to the package name containing spaces.");
  254.  
  255. foreach (d; m_rootPackage.getAllDependencies())
  256. if (d.spec.isExactVersion && d.spec.version_.isBranch) {
  257. logWarn("WARNING: A deprecated branch based version specification is used "
  258. ~ "for the dependency %s. Please use numbered versions instead. Also "
  259. ~ "note that you can still use the %s file to override a certain "
  260. ~ "dependency to use a branch instead.",
  261. d.name, SelectedVersions.defaultFile);
  262. }
  263.  
  264. // search for orphan sub configurations
  265. void warnSubConfig(string pack, string config) {
  266. logWarn("The sub configuration directive \"%s\" -> \"%s\" "
  267. ~ "references a package that is not specified as a dependency "
  268. ~ "and will have no effect.", pack, config);
  269. }
  270. void checkSubConfig(string pack, string config) {
  271. auto p = getDependency(pack, true);
  272. if (p && !p.configurations.canFind(config)) {
  273. logWarn("The sub configuration directive \"%s\" -> \"%s\" "
  274. ~ "references a configuration that does not exist.",
  275. pack, config);
  276. }
  277. }
  278. auto globalbs = m_rootPackage.getBuildSettings();
  279. foreach (p, c; globalbs.subConfigurations) {
  280. if (p !in globalbs.dependencies) warnSubConfig(p, c);
  281. else checkSubConfig(p, c);
  282. }
  283. foreach (c; m_rootPackage.configurations) {
  284. auto bs = m_rootPackage.getBuildSettings(c);
  285. foreach (p, c; bs.subConfigurations) {
  286. if (p !in bs.dependencies && p !in globalbs.dependencies)
  287. warnSubConfig(p, c);
  288. else checkSubConfig(p, c);
  289. }
  290. }
  291.  
  292. // check for version specification mismatches
  293. bool[Package] visited;
  294. void validateDependenciesRec(Package pack) {
  295. // perform basic package linting
  296. pack.simpleLint();
  297.  
  298. foreach (d; pack.getAllDependencies()) {
  299. auto basename = getBasePackageName(d.name);
  300. if (m_selections.hasSelectedVersion(basename)) {
  301. auto selver = m_selections.getSelectedVersion(basename);
  302. if (d.spec.merge(selver) == Dependency.invalid) {
  303. logWarn("Selected package %s %s does not match the dependency specification %s in package %s. Need to \"dub upgrade\"?",
  304. basename, selver, d.spec, pack.name);
  305. }
  306. }
  307.  
  308. auto deppack = getDependency(d.name, true);
  309. if (deppack in visited) continue;
  310. visited[deppack] = true;
  311. if (deppack) validateDependenciesRec(deppack);
  312. }
  313. }
  314. validateDependenciesRec(m_rootPackage);
  315. }
  316.  
  317. /// Reloads dependencies.
  318. void reinit()
  319. {
  320. m_dependencies = null;
  321. m_hasAllDependencies = true;
  322. m_packageManager.refresh(false);
  323.  
  324. void collectDependenciesRec(Package pack, int depth = 0)
  325. {
  326. auto indent = replicate(" ", depth);
  327. logDebug("%sCollecting dependencies for %s", indent, pack.name);
  328. indent ~= " ";
  329.  
  330. foreach (dep; pack.getAllDependencies()) {
  331. Dependency vspec = dep.spec;
  332. Package p;
  333.  
  334. auto basename = getBasePackageName(dep.name);
  335. auto subname = getSubPackageName(dep.name);
  336.  
  337. // non-optional and optional-default dependencies (if no selections file exists)
  338. // need to be satisfied
  339. bool is_desired = !vspec.optional || m_selections.hasSelectedVersion(basename) || (vspec.default_ && m_selections.bare);
  340.  
  341. if (dep.name == m_rootPackage.basePackage.name) {
  342. vspec = Dependency(m_rootPackage.version_);
  343. p = m_rootPackage.basePackage;
  344. } else if (basename == m_rootPackage.basePackage.name) {
  345. vspec = Dependency(m_rootPackage.version_);
  346. try p = m_packageManager.getSubPackage(m_rootPackage.basePackage, subname, false);
  347. catch (Exception e) {
  348. logDiagnostic("%sError getting sub package %s: %s", indent, dep.name, e.msg);
  349. if (is_desired) m_hasAllDependencies = false;
  350. continue;
  351. }
  352. } else if (m_selections.hasSelectedVersion(basename)) {
  353. vspec = m_selections.getSelectedVersion(basename);
  354. if (vspec.path.empty) p = m_packageManager.getBestPackage(dep.name, vspec);
  355. else {
  356. auto path = vspec.path;
  357. if (!path.absolute) path = m_rootPackage.path ~ path;
  358. p = m_packageManager.getOrLoadPackage(path, NativePath.init, true);
  359. if (subname.length) p = m_packageManager.getSubPackage(p, subname, true);
  360. }
  361. } else if (m_dependencies.canFind!(d => getBasePackageName(d.name) == basename)) {
  362. auto idx = m_dependencies.countUntil!(d => getBasePackageName(d.name) == basename);
  363. auto bp = m_dependencies[idx].basePackage;
  364. vspec = Dependency(bp.path);
  365. if (subname.length) p = m_packageManager.getSubPackage(bp, subname, false);
  366. else p = bp;
  367. } else {
  368. logDiagnostic("%sVersion selection for dependency %s (%s) of %s is missing.",
  369. indent, basename, dep.name, pack.name);
  370. }
  371.  
  372. if (!p && !vspec.path.empty) {
  373. NativePath path = vspec.path;
  374. if (!path.absolute) path = pack.path ~ path;
  375. logDiagnostic("%sAdding local %s in %s", indent, dep.name, path);
  376. p = m_packageManager.getOrLoadPackage(path, NativePath.init, true);
  377. if (p.parentPackage !is null) {
  378. logWarn("%sSub package %s must be referenced using the path to it's parent package.", indent, dep.name);
  379. p = p.parentPackage;
  380. }
  381. if (subname.length) p = m_packageManager.getSubPackage(p, subname, false);
  382. enforce(p.name == dep.name,
  383. format("Path based dependency %s is referenced with a wrong name: %s vs. %s",
  384. path.toNativeString(), dep.name, p.name));
  385. }
  386.  
  387. if (!p) {
  388. logDiagnostic("%sMissing dependency %s %s of %s", indent, dep.name, vspec, pack.name);
  389. if (is_desired) m_hasAllDependencies = false;
  390. continue;
  391. }
  392.  
  393. if (!m_dependencies.canFind(p)) {
  394. logDiagnostic("%sFound dependency %s %s", indent, dep.name, vspec.toString());
  395. m_dependencies ~= p;
  396. if (basename == m_rootPackage.basePackage.name)
  397. p.warnOnSpecialCompilerFlags();
  398. collectDependenciesRec(p, depth+1);
  399. }
  400.  
  401. m_dependees[p] ~= pack;
  402. //enforce(p !is null, "Failed to resolve dependency "~dep.name~" "~vspec.toString());
  403. }
  404. }
  405. collectDependenciesRec(m_rootPackage);
  406. }
  407.  
  408. /// Returns the name of the root package.
  409. @property string name() const { return m_rootPackage ? m_rootPackage.name : "app"; }
  410.  
  411. /// Returns the names of all configurations of the root package.
  412. @property string[] configurations() const { return m_rootPackage.configurations; }
  413.  
  414. /// Returns a map with the configuration for all packages in the dependency tree.
  415. string[string] getPackageConfigs(in BuildPlatform platform, string config, bool allow_non_library = true)
  416. const {
  417. struct Vertex { string pack, config; }
  418. struct Edge { size_t from, to; }
  419.  
  420. Vertex[] configs;
  421. Edge[] edges;
  422. string[][string] parents;
  423. parents[m_rootPackage.name] = null;
  424. foreach (p; getTopologicalPackageList())
  425. foreach (d; p.getAllDependencies())
  426. parents[d.name] ~= p.name;
  427.  
  428. size_t createConfig(string pack, string config) {
  429. foreach (i, v; configs)
  430. if (v.pack == pack && v.config == config)
  431. return i;
  432. assert(pack !in m_overriddenConfigs || config == m_overriddenConfigs[pack]);
  433. logDebug("Add config %s %s", pack, config);
  434. configs ~= Vertex(pack, config);
  435. return configs.length-1;
  436. }
  437.  
  438. bool haveConfig(string pack, string config) {
  439. return configs.any!(c => c.pack == pack && c.config == config);
  440. }
  441.  
  442. size_t createEdge(size_t from, size_t to) {
  443. auto idx = edges.countUntil(Edge(from, to));
  444. if (idx >= 0) return idx;
  445. logDebug("Including %s %s -> %s %s", configs[from].pack, configs[from].config, configs[to].pack, configs[to].config);
  446. edges ~= Edge(from, to);
  447. return edges.length-1;
  448. }
  449.  
  450. void removeConfig(size_t i) {
  451. logDebug("Eliminating config %s for %s", configs[i].config, configs[i].pack);
  452. auto had_dep_to_pack = new bool[configs.length];
  453. auto still_has_dep_to_pack = new bool[configs.length];
  454.  
  455. edges = edges.filter!((e) {
  456. if (e.to == i) {
  457. had_dep_to_pack[e.from] = true;
  458. return false;
  459. } else if (configs[e.to].pack == configs[i].pack) {
  460. still_has_dep_to_pack[e.from] = true;
  461. }
  462. if (e.from == i) return false;
  463. return true;
  464. }).array;
  465.  
  466. configs[i] = Vertex.init; // mark config as removed
  467.  
  468. // also remove any configs that cannot be satisfied anymore
  469. foreach (j; 0 .. configs.length)
  470. if (j != i && had_dep_to_pack[j] && !still_has_dep_to_pack[j])
  471. removeConfig(j);
  472. }
  473.  
  474. bool isReachable(string pack, string conf) {
  475. if (pack == configs[0].pack && configs[0].config == conf) return true;
  476. foreach (e; edges)
  477. if (configs[e.to].pack == pack && configs[e.to].config == conf)
  478. return true;
  479. return false;
  480. //return (pack == configs[0].pack && conf == configs[0].config) || edges.canFind!(e => configs[e.to].pack == pack && configs[e.to].config == config);
  481. }
  482.  
  483. bool isReachableByAllParentPacks(size_t cidx) {
  484. bool[string] r;
  485. foreach (p; parents[configs[cidx].pack]) r[p] = false;
  486. foreach (e; edges) {
  487. if (e.to != cidx) continue;
  488. if (auto pp = configs[e.from].pack in r) *pp = true;
  489. }
  490. foreach (bool v; r) if (!v) return false;
  491. return true;
  492. }
  493.  
  494. string[] allconfigs_path;
  495.  
  496. void determineDependencyConfigs(in Package p, string c)
  497. {
  498. string[][string] depconfigs;
  499. foreach (d; p.getAllDependencies()) {
  500. auto dp = getDependency(d.name, true);
  501. if (!dp) continue;
  502.  
  503. string[] cfgs;
  504. if (auto pc = dp.name in m_overriddenConfigs) cfgs = [*pc];
  505. else {
  506. auto subconf = p.getSubConfiguration(c, dp, platform);
  507. if (!subconf.empty) cfgs = [subconf];
  508. else cfgs = dp.getPlatformConfigurations(platform);
  509. }
  510. cfgs = cfgs.filter!(c => haveConfig(d.name, c)).array;
  511.  
  512. // if no valid configuration was found for a dependency, don't include the
  513. // current configuration
  514. if (!cfgs.length) {
  515. logDebug("Skip %s %s (missing configuration for %s)", p.name, c, dp.name);
  516. return;
  517. }
  518. depconfigs[d.name] = cfgs;
  519. }
  520.  
  521. // add this configuration to the graph
  522. size_t cidx = createConfig(p.name, c);
  523. foreach (d; p.getAllDependencies())
  524. foreach (sc; depconfigs.get(d.name, null))
  525. createEdge(cidx, createConfig(d.name, sc));
  526. }
  527.  
  528. // create a graph of all possible package configurations (package, config) -> (subpackage, subconfig)
  529. void determineAllConfigs(in Package p)
  530. {
  531. auto idx = allconfigs_path.countUntil(p.name);
  532. enforce(idx < 0, format("Detected dependency cycle: %s", (allconfigs_path[idx .. $] ~ p.name).join("->")));
  533. allconfigs_path ~= p.name;
  534. scope (exit) allconfigs_path.length--;
  535.  
  536. // first, add all dependency configurations
  537. foreach (d; p.getAllDependencies) {
  538. auto dp = getDependency(d.name, true);
  539. if (!dp) continue;
  540. determineAllConfigs(dp);
  541. }
  542.  
  543. // for each configuration, determine the configurations usable for the dependencies
  544. if (auto pc = p.name in m_overriddenConfigs)
  545. determineDependencyConfigs(p, *pc);
  546. else
  547. foreach (c; p.getPlatformConfigurations(platform, p is m_rootPackage && allow_non_library))
  548. determineDependencyConfigs(p, c);
  549. }
  550. if (config.length) createConfig(m_rootPackage.name, config);
  551. determineAllConfigs(m_rootPackage);
  552.  
  553. // successively remove configurations until only one configuration per package is left
  554. bool changed;
  555. do {
  556. // remove all configs that are not reachable by all parent packages
  557. changed = false;
  558. foreach (i, ref c; configs) {
  559. if (c == Vertex.init) continue; // ignore deleted configurations
  560. if (!isReachableByAllParentPacks(i)) {
  561. logDebug("%s %s NOT REACHABLE by all of (%s):", c.pack, c.config, parents[c.pack]);
  562. removeConfig(i);
  563. changed = true;
  564. }
  565. }
  566.  
  567. // when all edges are cleaned up, pick one package and remove all but one config
  568. if (!changed) {
  569. foreach (p; getTopologicalPackageList()) {
  570. size_t cnt = 0;
  571. foreach (i, ref c; configs)
  572. if (c.pack == p.name && ++cnt > 1) {
  573. logDebug("NON-PRIMARY: %s %s", c.pack, c.config);
  574. removeConfig(i);
  575. }
  576. if (cnt > 1) {
  577. changed = true;
  578. break;
  579. }
  580. }
  581. }
  582. } while (changed);
  583.  
  584. // print out the resulting tree
  585. foreach (e; edges) logDebug(" %s %s -> %s %s", configs[e.from].pack, configs[e.from].config, configs[e.to].pack, configs[e.to].config);
  586.  
  587. // return the resulting configuration set as an AA
  588. string[string] ret;
  589. foreach (c; configs) {
  590. if (c == Vertex.init) continue; // ignore deleted configurations
  591. 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]));
  592. logDebug("Using configuration '%s' for %s", c.config, c.pack);
  593. ret[c.pack] = c.config;
  594. }
  595.  
  596. // check for conflicts (packages missing in the final configuration graph)
  597. void checkPacksRec(in Package pack) {
  598. auto pc = pack.name in ret;
  599. enforce(pc !is null, "Could not resolve configuration for package "~pack.name);
  600. foreach (p, dep; pack.getDependencies(*pc)) {
  601. auto deppack = getDependency(p, dep.optional);
  602. if (deppack) checkPacksRec(deppack);
  603. }
  604. }
  605. checkPacksRec(m_rootPackage);
  606.  
  607. return ret;
  608. }
  609.  
  610. /**
  611. * Fills `dst` with values from this project.
  612. *
  613. * `dst` gets initialized according to the given platform and config.
  614. *
  615. * Params:
  616. * dst = The BuildSettings struct to fill with data.
  617. * gsettings = The generator settings to retrieve the values for.
  618. * config = Values of the given configuration will be retrieved.
  619. * root_package = If non null, use it instead of the project's real root package.
  620. * shallow = If true, collects only build settings for the main package (including inherited settings) and doesn't stop on target type none and sourceLibrary.
  621. */
  622. void addBuildSettings(ref BuildSettings dst, in GeneratorSettings gsettings, string config, in Package root_package = null, bool shallow = false)
  623. const {
  624. import dub.internal.utils : stripDlangSpecialChars;
  625.  
  626. auto configs = getPackageConfigs(gsettings.platform, config);
  627.  
  628. foreach (pkg; this.getTopologicalPackageList(false, root_package, configs)) {
  629. auto pkg_path = pkg.path.toNativeString();
  630. dst.addVersions(["Have_" ~ stripDlangSpecialChars(pkg.name)]);
  631.  
  632. assert(pkg.name in configs, "Missing configuration for "~pkg.name);
  633. logDebug("Gathering build settings for %s (%s)", pkg.name, configs[pkg.name]);
  634.  
  635. auto psettings = pkg.getBuildSettings(gsettings.platform, configs[pkg.name]);
  636. if (psettings.targetType != TargetType.none) {
  637. if (shallow && pkg !is m_rootPackage)
  638. psettings.sourceFiles = null;
  639. processVars(dst, this, pkg, psettings, gsettings);
  640. if (psettings.importPaths.empty)
  641. 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]);
  642. if (psettings.mainSourceFile.empty && pkg is m_rootPackage && psettings.targetType == TargetType.executable)
  643. 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);
  644. }
  645. if (pkg is m_rootPackage) {
  646. if (!shallow) {
  647. enforce(psettings.targetType != TargetType.none, "Main package has target type \"none\" - stopping build.");
  648. enforce(psettings.targetType != TargetType.sourceLibrary, "Main package has target type \"sourceLibrary\" which generates no target - stopping build.");
  649. }
  650. dst.targetType = psettings.targetType;
  651. dst.targetPath = psettings.targetPath;
  652. dst.targetName = psettings.targetName;
  653. if (!psettings.workingDirectory.empty)
  654. dst.workingDirectory = processVars(psettings.workingDirectory, this, pkg, gsettings, true);
  655. if (psettings.mainSourceFile.length)
  656. dst.mainSourceFile = processVars(psettings.mainSourceFile, this, pkg, gsettings, true);
  657. }
  658. }
  659.  
  660. // always add all version identifiers of all packages
  661. foreach (pkg; this.getTopologicalPackageList(false, null, configs)) {
  662. auto psettings = pkg.getBuildSettings(gsettings.platform, configs[pkg.name]);
  663. dst.addVersions(psettings.versions);
  664. }
  665. }
  666.  
  667. /** Fills `dst` with build settings specific to the given build type.
  668.  
  669. Params:
  670. dst = The `BuildSettings` instance to add the build settings to
  671. gsettings = Target generator settings
  672. build_type = Name of the build type
  673. for_root_package = Selects if the build settings are for the root
  674. package or for one of the dependencies. Unittest flags will
  675. only be added to the root package.
  676. */
  677. void addBuildTypeSettings(ref BuildSettings dst, in GeneratorSettings gsettings, bool for_root_package = true)
  678. {
  679. bool usedefflags = !(dst.requirements & BuildRequirement.noDefaultFlags);
  680. if (usedefflags) {
  681. BuildSettings btsettings;
  682. m_rootPackage.addBuildTypeSettings(btsettings, gsettings.platform, gsettings.buildType);
  683.  
  684. if (!for_root_package) {
  685. // don't propagate unittest switch to dependencies, as dependent
  686. // unit tests aren't run anyway and the additional code may
  687. // cause linking to fail on Windows (issue #640)
  688. btsettings.removeOptions(BuildOption.unittests);
  689. }
  690.  
  691. processVars(dst, this, m_rootPackage, btsettings, gsettings);
  692. }
  693. }
  694.  
  695. /// Outputs a build description of the project, including its dependencies.
  696. ProjectDescription describe(GeneratorSettings settings)
  697. {
  698. import dub.generators.targetdescription;
  699.  
  700. // store basic build parameters
  701. ProjectDescription ret;
  702. ret.rootPackage = m_rootPackage.name;
  703. ret.configuration = settings.config;
  704. ret.buildType = settings.buildType;
  705. ret.compiler = settings.platform.compiler;
  706. ret.architecture = settings.platform.architecture;
  707. ret.platform = settings.platform.platform;
  708.  
  709. // collect high level information about projects (useful for IDE display)
  710. auto configs = getPackageConfigs(settings.platform, settings.config);
  711. ret.packages ~= m_rootPackage.describe(settings.platform, settings.config);
  712. foreach (dep; m_dependencies)
  713. ret.packages ~= dep.describe(settings.platform, configs[dep.name]);
  714.  
  715. foreach (p; getTopologicalPackageList(false, null, configs))
  716. ret.packages[ret.packages.countUntil!(pp => pp.name == p.name)].active = true;
  717.  
  718. if (settings.buildType.length) {
  719. // collect build target information (useful for build tools)
  720. auto gen = new TargetDescriptionGenerator(this);
  721. try {
  722. gen.generate(settings);
  723. ret.targets = gen.targetDescriptions;
  724. ret.targetLookup = gen.targetDescriptionLookup;
  725. } catch (Exception e) {
  726. logDiagnostic("Skipping targets description: %s", e.msg);
  727. logDebug("Full error: %s", e.toString().sanitize);
  728. }
  729. }
  730.  
  731. return ret;
  732. }
  733.  
  734. private string[] listBuildSetting(string attributeName)(BuildPlatform platform,
  735. string config, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
  736. {
  737. return listBuildSetting!attributeName(platform, getPackageConfigs(platform, config),
  738. projectDescription, compiler, disableEscaping);
  739. }
  740.  
  741. private string[] listBuildSetting(string attributeName)(BuildPlatform platform,
  742. string[string] configs, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
  743. {
  744. if (compiler)
  745. return formatBuildSettingCompiler!attributeName(platform, configs, projectDescription, compiler, disableEscaping);
  746. else
  747. return formatBuildSettingPlain!attributeName(platform, configs, projectDescription);
  748. }
  749.  
  750. // Output a build setting formatted for a compiler
  751. private string[] formatBuildSettingCompiler(string attributeName)(BuildPlatform platform,
  752. string[string] configs, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
  753. {
  754. import std.process : escapeShellFileName;
  755. import std.path : dirSeparator;
  756.  
  757. assert(compiler);
  758.  
  759. auto targetDescription = projectDescription.lookupTarget(projectDescription.rootPackage);
  760. auto buildSettings = targetDescription.buildSettings;
  761.  
  762. string[] values;
  763. switch (attributeName)
  764. {
  765. case "dflags":
  766. case "linkerFiles":
  767. case "mainSourceFile":
  768. case "importFiles":
  769. values = formatBuildSettingPlain!attributeName(platform, configs, projectDescription);
  770. break;
  771.  
  772. case "lflags":
  773. case "sourceFiles":
  774. case "versions":
  775. case "debugVersions":
  776. case "importPaths":
  777. case "stringImportPaths":
  778. case "options":
  779. auto bs = buildSettings.dup;
  780. bs.dflags = null;
  781.  
  782. // Ensure trailing slash on directory paths
  783. auto ensureTrailingSlash = (string path) => path.endsWith(dirSeparator) ? path : path ~ dirSeparator;
  784. static if (attributeName == "importPaths")
  785. bs.importPaths = bs.importPaths.map!(ensureTrailingSlash).array();
  786. else static if (attributeName == "stringImportPaths")
  787. bs.stringImportPaths = bs.stringImportPaths.map!(ensureTrailingSlash).array();
  788.  
  789. compiler.prepareBuildSettings(bs, BuildSetting.all & ~to!BuildSetting(attributeName));
  790. values = bs.dflags;
  791. break;
  792.  
  793. case "libs":
  794. auto bs = buildSettings.dup;
  795. bs.dflags = null;
  796. bs.lflags = null;
  797. bs.sourceFiles = null;
  798. bs.targetType = TargetType.none; // Force Compiler to NOT omit dependency libs when package is a library.
  799.  
  800. compiler.prepareBuildSettings(bs, BuildSetting.all & ~to!BuildSetting(attributeName));
  801.  
  802. if (bs.lflags)
  803. values = compiler.lflagsToDFlags( bs.lflags );
  804. else if (bs.sourceFiles)
  805. values = compiler.lflagsToDFlags( bs.sourceFiles );
  806. else
  807. values = bs.dflags;
  808.  
  809. break;
  810.  
  811. default: assert(0);
  812. }
  813.  
  814. // Escape filenames and paths
  815. if(!disableEscaping)
  816. {
  817. switch (attributeName)
  818. {
  819. case "mainSourceFile":
  820. case "linkerFiles":
  821. case "copyFiles":
  822. case "importFiles":
  823. case "stringImportFiles":
  824. case "sourceFiles":
  825. case "importPaths":
  826. case "stringImportPaths":
  827. return values.map!(escapeShellFileName).array();
  828.  
  829. default:
  830. return values;
  831. }
  832. }
  833.  
  834. return values;
  835. }
  836.  
  837. // Output a build setting without formatting for any particular compiler
  838. private string[] formatBuildSettingPlain(string attributeName)(BuildPlatform platform, string[string] configs, ProjectDescription projectDescription)
  839. {
  840. import std.path : buildNormalizedPath, dirSeparator;
  841. import std.range : only;
  842.  
  843. string[] list;
  844.  
  845. enforce(attributeName == "targetType" || projectDescription.lookupRootPackage().targetType != TargetType.none,
  846. "Target type is 'none'. Cannot list build settings.");
  847.  
  848. static if (attributeName == "targetType")
  849. if (projectDescription.rootPackage !in projectDescription.targetLookup)
  850. return ["none"];
  851.  
  852. auto targetDescription = projectDescription.lookupTarget(projectDescription.rootPackage);
  853. auto buildSettings = targetDescription.buildSettings;
  854.  
  855. // Return any BuildSetting member attributeName as a range of strings. Don't attempt to fixup values.
  856. // allowEmptyString: When the value is a string (as opposed to string[]),
  857. // is empty string an actual permitted value instead of
  858. // a missing value?
  859. auto getRawBuildSetting(Package pack, bool allowEmptyString) {
  860. auto value = __traits(getMember, buildSettings, attributeName);
  861.  
  862. static if( is(typeof(value) == string[]) )
  863. return value;
  864. else static if( is(typeof(value) == string) )
  865. {
  866. auto ret = only(value);
  867.  
  868. // only() has a different return type from only(value), so we
  869. // have to empty the range rather than just returning only().
  870. if(value.empty && !allowEmptyString) {
  871. ret.popFront();
  872. assert(ret.empty);
  873. }
  874.  
  875. return ret;
  876. }
  877. else static if( is(typeof(value) == enum) )
  878. return only(value);
  879. else static if( is(typeof(value) == BuildRequirements) )
  880. return only(cast(BuildRequirement) cast(int) value.values);
  881. else static if( is(typeof(value) == BuildOptions) )
  882. return only(cast(BuildOption) cast(int) value.values);
  883. else
  884. static assert(false, "Type of BuildSettings."~attributeName~" is unsupported.");
  885. }
  886.  
  887. // Adjust BuildSetting member attributeName as needed.
  888. // Returns a range of strings.
  889. auto getFixedBuildSetting(Package pack) {
  890. // Is relative path(s) to a directory?
  891. enum isRelativeDirectory =
  892. attributeName == "importPaths" || attributeName == "stringImportPaths" ||
  893. attributeName == "targetPath" || attributeName == "workingDirectory";
  894.  
  895. // Is relative path(s) to a file?
  896. enum isRelativeFile =
  897. attributeName == "sourceFiles" || attributeName == "linkerFiles" ||
  898. attributeName == "importFiles" || attributeName == "stringImportFiles" ||
  899. attributeName == "copyFiles" || attributeName == "mainSourceFile";
  900.  
  901. // For these, empty string means "main project directory", not "missing value"
  902. enum allowEmptyString =
  903. attributeName == "targetPath" || attributeName == "workingDirectory";
  904.  
  905. enum isEnumBitfield =
  906. attributeName == "requirements" || attributeName == "options";
  907.  
  908. enum isEnum = attributeName == "targetType";
  909.  
  910. auto values = getRawBuildSetting(pack, allowEmptyString);
  911. string fixRelativePath(string importPath) { return buildNormalizedPath(pack.path.toString(), importPath); }
  912. static string ensureTrailingSlash(string path) { return path.endsWith(dirSeparator) ? path : path ~ dirSeparator; }
  913.  
  914. static if(isRelativeDirectory) {
  915. // Return full paths for the paths, making sure a
  916. // directory separator is on the end of each path.
  917. return values.map!(fixRelativePath).map!(ensureTrailingSlash);
  918. }
  919. else static if(isRelativeFile) {
  920. // Return full paths.
  921. return values.map!(fixRelativePath);
  922. }
  923. else static if(isEnumBitfield)
  924. return bitFieldNames(values.front);
  925. else static if (isEnum)
  926. return [values.front.to!string];
  927. else
  928. return values;
  929. }
  930.  
  931. foreach(value; getFixedBuildSetting(m_rootPackage)) {
  932. list ~= value;
  933. }
  934.  
  935. return list;
  936. }
  937.  
  938. // The "compiler" arg is for choosing which compiler the output should be formatted for,
  939. // or null to imply "list" format.
  940. private string[] listBuildSetting(BuildPlatform platform, string[string] configs,
  941. ProjectDescription projectDescription, string requestedData, Compiler compiler, bool disableEscaping)
  942. {
  943. // Certain data cannot be formatter for a compiler
  944. if (compiler)
  945. {
  946. switch (requestedData)
  947. {
  948. case "target-type":
  949. case "target-path":
  950. case "target-name":
  951. case "working-directory":
  952. case "string-import-files":
  953. case "copy-files":
  954. case "pre-generate-commands":
  955. case "post-generate-commands":
  956. case "pre-build-commands":
  957. case "post-build-commands":
  958. enforce(false, "--data="~requestedData~" can only be used with --data-list or --data-0.");
  959. break;
  960.  
  961. case "requirements":
  962. enforce(false, "--data=requirements can only be used with --data-list or --data-0. Use --data=options instead.");
  963. break;
  964.  
  965. default: break;
  966. }
  967. }
  968.  
  969. import std.typetuple : TypeTuple;
  970. auto args = TypeTuple!(platform, configs, projectDescription, compiler, disableEscaping);
  971. switch (requestedData)
  972. {
  973. case "target-type": return listBuildSetting!"targetType"(args);
  974. case "target-path": return listBuildSetting!"targetPath"(args);
  975. case "target-name": return listBuildSetting!"targetName"(args);
  976. case "working-directory": return listBuildSetting!"workingDirectory"(args);
  977. case "main-source-file": return listBuildSetting!"mainSourceFile"(args);
  978. case "dflags": return listBuildSetting!"dflags"(args);
  979. case "lflags": return listBuildSetting!"lflags"(args);
  980. case "libs": return listBuildSetting!"libs"(args);
  981. case "linker-files": return listBuildSetting!"linkerFiles"(args);
  982. case "source-files": return listBuildSetting!"sourceFiles"(args);
  983. case "copy-files": return listBuildSetting!"copyFiles"(args);
  984. case "versions": return listBuildSetting!"versions"(args);
  985. case "debug-versions": return listBuildSetting!"debugVersions"(args);
  986. case "import-paths": return listBuildSetting!"importPaths"(args);
  987. case "string-import-paths": return listBuildSetting!"stringImportPaths"(args);
  988. case "import-files": return listBuildSetting!"importFiles"(args);
  989. case "string-import-files": return listBuildSetting!"stringImportFiles"(args);
  990. case "pre-generate-commands": return listBuildSetting!"preGenerateCommands"(args);
  991. case "post-generate-commands": return listBuildSetting!"postGenerateCommands"(args);
  992. case "pre-build-commands": return listBuildSetting!"preBuildCommands"(args);
  993. case "post-build-commands": return listBuildSetting!"postBuildCommands"(args);
  994. case "requirements": return listBuildSetting!"requirements"(args);
  995. case "options": return listBuildSetting!"options"(args);
  996.  
  997. default:
  998. enforce(false, "--data="~requestedData~
  999. " is not a valid option. See 'dub describe --help' for accepted --data= values.");
  1000. }
  1001.  
  1002. assert(0);
  1003. }
  1004.  
  1005. /// Outputs requested data for the project, optionally including its dependencies.
  1006. string[] listBuildSettings(GeneratorSettings settings, string[] requestedData, ListBuildSettingsFormat list_type)
  1007. {
  1008. import dub.compilers.utils : isLinkerFile;
  1009.  
  1010. auto projectDescription = describe(settings);
  1011. auto configs = getPackageConfigs(settings.platform, settings.config);
  1012. PackageDescription packageDescription;
  1013. foreach (pack; projectDescription.packages) {
  1014. if (pack.name == projectDescription.rootPackage)
  1015. packageDescription = pack;
  1016. }
  1017.  
  1018. if (projectDescription.rootPackage in projectDescription.targetLookup) {
  1019. // Copy linker files from sourceFiles to linkerFiles
  1020. auto target = projectDescription.lookupTarget(projectDescription.rootPackage);
  1021. foreach (file; target.buildSettings.sourceFiles.filter!(isLinkerFile))
  1022. target.buildSettings.addLinkerFiles(file);
  1023.  
  1024. // Remove linker files from sourceFiles
  1025. target.buildSettings.sourceFiles =
  1026. target.buildSettings.sourceFiles
  1027. .filter!(a => !isLinkerFile(a))
  1028. .array();
  1029. projectDescription.lookupTarget(projectDescription.rootPackage) = target;
  1030. }
  1031.  
  1032. Compiler compiler;
  1033. bool no_escape;
  1034. final switch (list_type) with (ListBuildSettingsFormat) {
  1035. case list: break;
  1036. case listNul: no_escape = true; break;
  1037. case commandLine: compiler = settings.compiler; break;
  1038. case commandLineNul: compiler = settings.compiler; no_escape = true; break;
  1039.  
  1040. }
  1041.  
  1042. auto result = requestedData
  1043. .map!(dataName => listBuildSetting(settings.platform, configs, projectDescription, dataName, compiler, no_escape));
  1044.  
  1045. final switch (list_type) with (ListBuildSettingsFormat) {
  1046. case list: return result.map!(l => l.join("\n")).array();
  1047. case listNul: return result.map!(l => l.join("\0")).array;
  1048. case commandLine: return result.map!(l => l.join(" ")).array;
  1049. case commandLineNul: return result.map!(l => l.join("\0")).array;
  1050. }
  1051. }
  1052.  
  1053. /** Saves the currently selected dependency versions to disk.
  1054.  
  1055. The selections will be written to a file named
  1056. `SelectedVersions.defaultFile` ("dub.selections.json") within the
  1057. directory of the root package. Any existing file will get overwritten.
  1058. */
  1059. void saveSelections()
  1060. {
  1061. assert(m_selections !is null, "Cannot save selections for non-disk based project (has no selections).");
  1062. if (m_selections.hasSelectedVersion(m_rootPackage.basePackage.name))
  1063. m_selections.deselectVersion(m_rootPackage.basePackage.name);
  1064.  
  1065. auto path = m_rootPackage.path ~ SelectedVersions.defaultFile;
  1066. if (m_selections.dirty || !existsFile(path))
  1067. m_selections.save(path);
  1068. }
  1069.  
  1070. deprecated bool isUpgradeCacheUpToDate()
  1071. {
  1072. return false;
  1073. }
  1074.  
  1075. deprecated Dependency[string] getUpgradeCache()
  1076. {
  1077. return null;
  1078. }
  1079.  
  1080. /** Sets a new set of versions for the upgrade cache.
  1081. */
  1082. void setUpgradeCache(Dependency[string] versions)
  1083. {
  1084. logDebug("markUpToDate");
  1085. Json create(ref Json json, string object) {
  1086. if (json[object].type == Json.Type.undefined) json[object] = Json.emptyObject;
  1087. return json[object];
  1088. }
  1089. create(m_packageSettings, "dub");
  1090. m_packageSettings["dub"]["lastUpgrade"] = Clock.currTime().toISOExtString();
  1091.  
  1092. create(m_packageSettings["dub"], "cachedUpgrades");
  1093. foreach (p, d; versions)
  1094. m_packageSettings["dub"]["cachedUpgrades"][p] = SelectedVersions.dependencyToJson(d);
  1095.  
  1096. writeDubJson();
  1097. }
  1098.  
  1099. private void writeDubJson() {
  1100. import std.file : exists, mkdir;
  1101. // don't bother to write an empty file
  1102. if( m_packageSettings.length == 0 ) return;
  1103.  
  1104. try {
  1105. logDebug("writeDubJson");
  1106. auto dubpath = m_rootPackage.path~".dub";
  1107. if( !exists(dubpath.toNativeString()) ) mkdir(dubpath.toNativeString());
  1108. auto dstFile = openFile((dubpath~"dub.json").toString(), FileMode.createTrunc);
  1109. scope(exit) dstFile.close();
  1110. dstFile.writePrettyJsonString(m_packageSettings);
  1111. } catch( Exception e ){
  1112. logWarn("Could not write .dub/dub.json.");
  1113. }
  1114. }
  1115. }
  1116.  
  1117.  
  1118. /// Determines the output format used for `Project.listBuildSettings`.
  1119. enum ListBuildSettingsFormat {
  1120. list, /// Newline separated list entries
  1121. listNul, /// NUL character separated list entries (unescaped)
  1122. commandLine, /// Formatted for compiler command line (one data list per line)
  1123. commandLineNul, /// NUL character separated list entries (unescaped, data lists separated by two NUL characters)
  1124. }
  1125.  
  1126.  
  1127. /// Indicates where a package has been or should be placed to.
  1128. enum PlacementLocation {
  1129. /// Packages retrieved with 'local' will be placed in the current folder
  1130. /// using the package name as destination.
  1131. local,
  1132. /// Packages with 'userWide' will be placed in a folder accessible by
  1133. /// all of the applications from the current user.
  1134. user,
  1135. /// Packages retrieved with 'systemWide' will be placed in a shared folder,
  1136. /// which can be accessed by all users of the system.
  1137. system
  1138. }
  1139.  
  1140. void processVars(ref BuildSettings dst, in Project project, in Package pack,
  1141. BuildSettings settings, in GeneratorSettings gsettings, bool include_target_settings = false)
  1142. {
  1143. dst.addDFlags(processVars(project, pack, gsettings, settings.dflags));
  1144. dst.addLFlags(processVars(project, pack, gsettings, settings.lflags));
  1145. dst.addLibs(processVars(project, pack, gsettings, settings.libs));
  1146. dst.addSourceFiles(processVars(project, pack, gsettings, settings.sourceFiles, true));
  1147. dst.addImportFiles(processVars(project, pack, gsettings, settings.importFiles, true));
  1148. dst.addStringImportFiles(processVars(project, pack, gsettings, settings.stringImportFiles, true));
  1149. dst.addCopyFiles(processVars(project, pack, gsettings, settings.copyFiles, true));
  1150. dst.addVersions(processVars(project, pack, gsettings, settings.versions));
  1151. dst.addDebugVersions(processVars(project, pack, gsettings, settings.debugVersions));
  1152. dst.addImportPaths(processVars(project, pack, gsettings, settings.importPaths, true));
  1153. dst.addStringImportPaths(processVars(project, pack, gsettings, settings.stringImportPaths, true));
  1154. dst.addPreGenerateCommands(processVars(project, pack, gsettings, settings.preGenerateCommands));
  1155. dst.addPostGenerateCommands(processVars(project, pack, gsettings, settings.postGenerateCommands));
  1156. dst.addPreBuildCommands(processVars(project, pack, gsettings, settings.preBuildCommands));
  1157. dst.addPostBuildCommands(processVars(project, pack, gsettings, settings.postBuildCommands));
  1158. dst.addRequirements(settings.requirements);
  1159. dst.addOptions(settings.options);
  1160.  
  1161. if (include_target_settings) {
  1162. dst.targetType = settings.targetType;
  1163. dst.targetPath = processVars(settings.targetPath, project, pack, gsettings, true);
  1164. dst.targetName = settings.targetName;
  1165. if (!settings.workingDirectory.empty)
  1166. dst.workingDirectory = processVars(settings.workingDirectory, project, pack, gsettings, true);
  1167. if (settings.mainSourceFile.length)
  1168. dst.mainSourceFile = processVars(settings.mainSourceFile, project, pack, gsettings, true);
  1169. }
  1170. }
  1171.  
  1172. private string[] processVars(in Project project, in Package pack, in GeneratorSettings gsettings, string[] vars, bool are_paths = false)
  1173. {
  1174. auto ret = appender!(string[])();
  1175. processVars(ret, project, pack, gsettings, vars, are_paths);
  1176. return ret.data;
  1177.  
  1178. }
  1179. private void processVars(ref Appender!(string[]) dst, in Project project, in Package pack, in GeneratorSettings gsettings, string[] vars, bool are_paths = false)
  1180. {
  1181. foreach (var; vars) dst.put(processVars(var, project, pack, gsettings, are_paths));
  1182. }
  1183.  
  1184. private string processVars(Project, Package)(string var, in Project project, in Package pack,in GeneratorSettings gsettings, bool is_path)
  1185. {
  1186. import std.regex : regex, replaceAll;
  1187.  
  1188. auto varRE = regex(`\$([\w_]+)|\$\{([\w_]+)\}|(\$\$[\w_]+|\$\$\{[\w_]+\})`);
  1189. var = var.replaceAll!(
  1190. m => m[3].length ? m[3][1..$] : (getVariable(m[1].length ? m[1] : m[2], project, pack, gsettings))
  1191. )(varRE);
  1192. if (is_path) {
  1193. auto p = NativePath(var);
  1194. if (!p.absolute) {
  1195. return (pack.path ~ p).toNativeString();
  1196. } else return p.toNativeString();
  1197. } else return var;
  1198. }
  1199.  
  1200. // Keep the following list up-to-date if adding more build settings variables.
  1201. /// List of variables that can be used in build settings
  1202. package(dub) immutable buildSettingsVars = [
  1203. "ARCH", "PLATFORM", "PLATFORM_POSIX", "BUILD_TYPE"
  1204. ];
  1205.  
  1206. private string getVariable(Project, Package)(string name, in Project project, in Package pack, in GeneratorSettings gsettings)
  1207. {
  1208. import std.process : environment;
  1209. import std.uni : asUpperCase;
  1210. NativePath path;
  1211. if (name == "PACKAGE_DIR")
  1212. path = pack.path;
  1213. else if (name == "ROOT_PACKAGE_DIR")
  1214. path = project.rootPackage.path;
  1215.  
  1216. if (name.endsWith("_PACKAGE_DIR")) {
  1217. auto pname = name[0 .. $-12];
  1218. foreach (prj; project.getTopologicalPackageList())
  1219. if (prj.name.asUpperCase.map!(a => a == '-' ? '_' : a).equal(pname))
  1220. {
  1221. path = prj.path;
  1222. break;
  1223. }
  1224. }
  1225.  
  1226. if (!path.empty)
  1227. {
  1228. // no trailing slash for clean path concatenation (see #1392)
  1229. path.endsWithSlash = false;
  1230. return path.toNativeString();
  1231. }
  1232.  
  1233. if (name == "ARCH") {
  1234. foreach (a; gsettings.platform.architecture)
  1235. return a;
  1236. return "";
  1237. }
  1238.  
  1239. if (name == "PLATFORM") {
  1240. import std.algorithm : filter;
  1241. foreach (p; gsettings.platform.platform.filter!(p => p != "posix"))
  1242. return p;
  1243. foreach (p; gsettings.platform.platform)
  1244. return p;
  1245. return "";
  1246. }
  1247.  
  1248. if (name == "PLATFORM_POSIX") {
  1249. import std.algorithm : canFind;
  1250. if (gsettings.platform.platform.canFind("posix"))
  1251. return "posix";
  1252. foreach (p; gsettings.platform.platform)
  1253. return p;
  1254. return "";
  1255. }
  1256.  
  1257. if (name == "BUILD_TYPE") return gsettings.buildType;
  1258.  
  1259. auto envvar = environment.get(name);
  1260. if (envvar !is null) return envvar;
  1261.  
  1262. throw new Exception("Invalid variable: "~name);
  1263. }
  1264.  
  1265.  
  1266. unittest
  1267. {
  1268. static struct MockPackage
  1269. {
  1270. this(string name)
  1271. {
  1272. this.name = name;
  1273. version (Posix)
  1274. path = NativePath("/pkgs/"~name);
  1275. else version (Windows)
  1276. path = NativePath(`C:\pkgs\`~name);
  1277. // see 4d4017c14c, #268, and #1392 for why this all package paths end on slash internally
  1278. path.endsWithSlash = true;
  1279. }
  1280. string name;
  1281. NativePath path;
  1282. }
  1283.  
  1284. static struct MockProject
  1285. {
  1286. MockPackage rootPackage;
  1287. inout(MockPackage)[] getTopologicalPackageList() inout
  1288. {
  1289. return _dependencies;
  1290. }
  1291. private:
  1292. MockPackage[] _dependencies;
  1293. }
  1294.  
  1295. MockProject proj = {
  1296. rootPackage: MockPackage("root"),
  1297. _dependencies: [MockPackage("dep1"), MockPackage("dep2")]
  1298. };
  1299. auto pack = MockPackage("test");
  1300. GeneratorSettings gsettings;
  1301. enum isPath = true;
  1302.  
  1303. import std.path : dirSeparator;
  1304.  
  1305. static Path woSlash(Path p) { p.endsWithSlash = false; return p; }
  1306. // basic vars
  1307. assert(processVars("Hello $PACKAGE_DIR", proj, pack, gsettings, !isPath) == "Hello "~woSlash(pack.path).toNativeString);
  1308. assert(processVars("Hello $ROOT_PACKAGE_DIR", proj, pack, gsettings, !isPath) == "Hello "~woSlash(proj.rootPackage.path).toNativeString.chomp(dirSeparator));
  1309. assert(processVars("Hello $DEP1_PACKAGE_DIR", proj, pack, gsettings, !isPath) == "Hello "~woSlash(proj._dependencies[0].path).toNativeString);
  1310. // ${VAR} replacements
  1311. assert(processVars("Hello ${PACKAGE_DIR}"~dirSeparator~"foobar", proj, pack, gsettings, !isPath) == "Hello "~(pack.path ~ "foobar").toNativeString);
  1312. assert(processVars("Hello $PACKAGE_DIR"~dirSeparator~"foobar", proj, pack, gsettings, !isPath) == "Hello "~(pack.path ~ "foobar").toNativeString);
  1313. // test with isPath
  1314. assert(processVars("local", proj, pack, gsettings, isPath) == (pack.path ~ "local").toNativeString);
  1315. assert(processVars("foo/$$ESCAPED", proj, pack, gsettings, isPath) == (pack.path ~ "foo/$ESCAPED").toNativeString);
  1316. assert(processVars("$$ESCAPED", proj, pack, gsettings, !isPath) == "$ESCAPED");
  1317. // test other env variables
  1318. import std.process : environment;
  1319. environment["MY_ENV_VAR"] = "blablabla";
  1320. assert(processVars("$MY_ENV_VAR", proj, pack, gsettings, !isPath) == "blablabla");
  1321. assert(processVars("${MY_ENV_VAR}suffix", proj, pack, gsettings, !isPath) == "blablablasuffix");
  1322. assert(processVars("$MY_ENV_VAR-suffix", proj, pack, gsettings, !isPath) == "blablabla-suffix");
  1323. assert(processVars("$MY_ENV_VAR:suffix", proj, pack, gsettings, !isPath) == "blablabla:suffix");
  1324. assert(processVars("$MY_ENV_VAR$MY_ENV_VAR", proj, pack, gsettings, !isPath) == "blablablablablabla");
  1325. environment.remove("MY_ENV_VAR");
  1326. }
  1327.  
  1328. /** Holds and stores a set of version selections for package dependencies.
  1329.  
  1330. This is the runtime representation of the information contained in
  1331. "dub.selections.json" within a package's directory.
  1332. */
  1333. final class SelectedVersions {
  1334. private struct Selected {
  1335. Dependency dep;
  1336. //Dependency[string] packages;
  1337. }
  1338. private {
  1339. enum FileVersion = 1;
  1340. Selected[string] m_selections;
  1341. bool m_dirty = false; // has changes since last save
  1342. bool m_bare = true;
  1343. }
  1344.  
  1345. /// Default file name to use for storing selections.
  1346. enum defaultFile = "dub.selections.json";
  1347.  
  1348. /// Constructs a new empty version selection.
  1349. this() {}
  1350.  
  1351. /** Constructs a new version selection from JSON data.
  1352.  
  1353. The structure of the JSON document must match the contents of the
  1354. "dub.selections.json" file.
  1355. */
  1356. this(Json data)
  1357. {
  1358. deserialize(data);
  1359. m_dirty = false;
  1360. }
  1361.  
  1362. /** Constructs a new version selections from an existing JSON file.
  1363. */
  1364. this(NativePath path)
  1365. {
  1366. auto json = jsonFromFile(path);
  1367. deserialize(json);
  1368. m_dirty = false;
  1369. m_bare = false;
  1370. }
  1371.  
  1372. /// Returns a list of names for all packages that have a version selection.
  1373. @property string[] selectedPackages() const { return m_selections.keys; }
  1374.  
  1375. /// Determines if any changes have been made after loading the selections from a file.
  1376. @property bool dirty() const { return m_dirty; }
  1377.  
  1378. /// Determine if this set of selections is still empty (but not `clear`ed).
  1379. @property bool bare() const { return m_bare && !m_dirty; }
  1380.  
  1381. /// Removes all selections.
  1382. void clear()
  1383. {
  1384. m_selections = null;
  1385. m_dirty = true;
  1386. }
  1387.  
  1388. /// Duplicates the set of selected versions from another instance.
  1389. void set(SelectedVersions versions)
  1390. {
  1391. m_selections = versions.m_selections.dup;
  1392. m_dirty = true;
  1393. }
  1394.  
  1395. /// Selects a certain version for a specific package.
  1396. void selectVersion(string package_id, Version version_)
  1397. {
  1398. if (auto ps = package_id in m_selections) {
  1399. if (ps.dep == Dependency(version_))
  1400. return;
  1401. }
  1402. m_selections[package_id] = Selected(Dependency(version_)/*, issuer*/);
  1403. m_dirty = true;
  1404. }
  1405.  
  1406. /// Selects a certain path for a specific package.
  1407. void selectVersion(string package_id, NativePath path)
  1408. {
  1409. if (auto ps = package_id in m_selections) {
  1410. if (ps.dep == Dependency(path))
  1411. return;
  1412. }
  1413. m_selections[package_id] = Selected(Dependency(path));
  1414. m_dirty = true;
  1415. }
  1416.  
  1417. /// Removes the selection for a particular package.
  1418. void deselectVersion(string package_id)
  1419. {
  1420. m_selections.remove(package_id);
  1421. m_dirty = true;
  1422. }
  1423.  
  1424. /// Determines if a particular package has a selection set.
  1425. bool hasSelectedVersion(string packageId)
  1426. const {
  1427. return (packageId in m_selections) !is null;
  1428. }
  1429.  
  1430. /** Returns the selection for a particular package.
  1431.  
  1432. Note that the returned `Dependency` can either have the
  1433. `Dependency.path` property set to a non-empty value, in which case this
  1434. is a path based selection, or its `Dependency.version_` property is
  1435. valid and it is a version selection.
  1436. */
  1437. Dependency getSelectedVersion(string packageId)
  1438. const {
  1439. enforce(hasSelectedVersion(packageId));
  1440. return m_selections[packageId].dep;
  1441. }
  1442.  
  1443. /** Stores the selections to disk.
  1444.  
  1445. The target file will be written in JSON format. Usually, `defaultFile`
  1446. should be used as the file name and the directory should be the root
  1447. directory of the project's root package.
  1448. */
  1449. void save(NativePath path)
  1450. {
  1451. Json json = serialize();
  1452. auto file = openFile(path, FileMode.createTrunc);
  1453. scope(exit) file.close();
  1454.  
  1455. assert(json.type == Json.Type.object);
  1456. assert(json.length == 2);
  1457. assert(json["versions"].type != Json.Type.undefined);
  1458.  
  1459. file.write("{\n\t\"fileVersion\": ");
  1460. file.writeJsonString(json["fileVersion"]);
  1461. file.write(",\n\t\"versions\": {");
  1462. auto vers = json["versions"].get!(Json[string]);
  1463. bool first = true;
  1464. foreach (k; vers.byKey.array.sort()) {
  1465. if (!first) file.write(",");
  1466. else first = false;
  1467. file.write("\n\t\t");
  1468. file.writeJsonString(Json(k));
  1469. file.write(": ");
  1470. file.writeJsonString(vers[k]);
  1471. }
  1472. file.write("\n\t}\n}\n");
  1473. m_dirty = false;
  1474. m_bare = false;
  1475. }
  1476.  
  1477. static Json dependencyToJson(Dependency d)
  1478. {
  1479. if (d.path.empty) return Json(d.version_.toString());
  1480. else return serializeToJson(["path": d.path.toString()]);
  1481. }
  1482.  
  1483. static Dependency dependencyFromJson(Json j)
  1484. {
  1485. if (j.type == Json.Type.string)
  1486. return Dependency(Version(j.get!string));
  1487. else if (j.type == Json.Type.object)
  1488. return Dependency(NativePath(j["path"].get!string));
  1489. else throw new Exception(format("Unexpected type for dependency: %s", j.type));
  1490. }
  1491.  
  1492. Json serialize()
  1493. const {
  1494. Json json = serializeToJson(m_selections);
  1495. Json serialized = Json.emptyObject;
  1496. serialized["fileVersion"] = FileVersion;
  1497. serialized["versions"] = Json.emptyObject;
  1498. foreach (p, v; m_selections)
  1499. serialized["versions"][p] = dependencyToJson(v.dep);
  1500. return serialized;
  1501. }
  1502.  
  1503. private void deserialize(Json json)
  1504. {
  1505. enforce(cast(int)json["fileVersion"] == FileVersion, "Mismatched dub.select.json version: " ~ to!string(cast(int)json["fileVersion"]) ~ "vs. " ~to!string(FileVersion));
  1506. clear();
  1507. scope(failure) clear();
  1508. foreach (string p, v; json["versions"])
  1509. m_selections[p] = Selected(dependencyFromJson(v));
  1510. }
  1511. }