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