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