Newer
Older
dub_jkp / source / dub / package_.d
  1. /**
  2. Contains high-level functionality for working with packages.
  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, Martin Nowak, Nick Sabalausky
  7. */
  8. module dub.package_;
  9.  
  10. public import dub.recipe.packagerecipe;
  11.  
  12. import dub.compilers.compiler;
  13. import dub.dependency;
  14. import dub.description;
  15. import dub.recipe.json;
  16. import dub.recipe.sdl;
  17.  
  18. import dub.internal.logging;
  19. import dub.internal.utils;
  20. import dub.internal.vibecompat.core.file;
  21. import dub.internal.vibecompat.data.json;
  22. import dub.internal.vibecompat.inet.path;
  23.  
  24. import dub.internal.configy.Read : StrictMode;
  25.  
  26. import std.algorithm;
  27. import std.array;
  28. import std.conv;
  29. import std.exception;
  30. import std.file;
  31. import std.range;
  32. import std.string;
  33. import std.typecons : Nullable;
  34.  
  35.  
  36. /// Lists the supported package recipe formats.
  37. enum PackageFormat {
  38. json, /// JSON based, using the ".json" file extension
  39. sdl /// SDLang based, using the ".sdl" file extension
  40. }
  41.  
  42. struct FilenameAndFormat {
  43. string filename;
  44. PackageFormat format;
  45. }
  46.  
  47. /// Supported package descriptions in decreasing order of preference.
  48. static immutable FilenameAndFormat[] packageInfoFiles = [
  49. {"dub.json", PackageFormat.json},
  50. {"dub.sdl", PackageFormat.sdl},
  51. {"package.json", PackageFormat.json}
  52. ];
  53.  
  54. /// Returns a list of all recognized package recipe file names in descending order of precedence.
  55. @property string[] packageInfoFilenames() { return packageInfoFiles.map!(f => cast(string)f.filename).array; }
  56.  
  57. /// Returns the default package recile file name.
  58. @property string defaultPackageFilename() { return packageInfoFiles[0].filename; }
  59.  
  60. /// All built-in build type names except for the special `$DFLAGS` build type.
  61. /// Has the default build type (`debug`) as first index.
  62. static immutable string[] builtinBuildTypes = [
  63. "debug",
  64. "plain",
  65. "release",
  66. "release-debug",
  67. "release-nobounds",
  68. "unittest",
  69. "profile",
  70. "profile-gc",
  71. "docs",
  72. "ddox",
  73. "cov",
  74. "cov-ctfe",
  75. "unittest-cov",
  76. "unittest-cov-ctfe",
  77. "syntax"
  78. ];
  79.  
  80. /** Represents a package, including its sub packages.
  81. */
  82. class Package {
  83. private {
  84. NativePath m_path;
  85. NativePath m_infoFile;
  86. PackageRecipe m_info;
  87. PackageRecipe m_rawRecipe;
  88. Package m_parentPackage;
  89. }
  90.  
  91. /** Constructs a `Package` using an in-memory package recipe.
  92.  
  93. Params:
  94. json_recipe = The package recipe in JSON format
  95. recipe = The package recipe in generic format
  96. root = The directory in which the package resides (if any).
  97. parent = Reference to the parent package, if the new package is a
  98. sub package.
  99. version_override = Optional version to associate to the package
  100. instead of the one declared in the package recipe, or the one
  101. determined by invoking the VCS (GIT currently).
  102. */
  103. this(Json json_recipe, NativePath root = NativePath(), Package parent = null, string version_override = "")
  104. {
  105. import dub.recipe.json;
  106.  
  107. PackageRecipe recipe;
  108. parseJson(recipe, json_recipe, parent ? parent.name : null);
  109. this(recipe, root, parent, version_override);
  110. }
  111. /// ditto
  112. this(PackageRecipe recipe, NativePath root = NativePath(), Package parent = null, string version_override = "")
  113. {
  114. // save the original recipe
  115. m_rawRecipe = recipe.clone;
  116.  
  117. if (!version_override.empty)
  118. recipe.version_ = version_override;
  119.  
  120. // try to run git to determine the version of the package if no explicit version was given
  121. if (recipe.version_.length == 0 && !parent) {
  122. try recipe.version_ = determineVersionFromSCM(root);
  123. catch (Exception e) logDebug("Failed to determine version by SCM: %s", e.msg);
  124.  
  125. if (recipe.version_.length == 0) {
  126. logDiagnostic("Note: Failed to determine version of package %s at %s. Assuming ~master.", recipe.name, this.path.toNativeString());
  127. // TODO: Assume unknown version here?
  128. // recipe.version_ = Version.unknown.toString();
  129. recipe.version_ = Version.masterBranch.toString();
  130. } else logDiagnostic("Determined package version using GIT: %s %s", recipe.name, recipe.version_);
  131. }
  132.  
  133. m_parentPackage = parent;
  134. m_path = root;
  135. m_path.endsWithSlash = true;
  136.  
  137. // use the given recipe as the basis
  138. m_info = recipe;
  139.  
  140. checkDubRequirements();
  141. fillWithDefaults();
  142. mutuallyExcludeMainFiles();
  143. }
  144.  
  145. /** Searches the given directory for package recipe files.
  146.  
  147. Params:
  148. directory = The directory to search
  149.  
  150. Returns:
  151. Returns the full path to the package file, if any was found.
  152. Otherwise returns an empty path.
  153. */
  154. static NativePath findPackageFile(NativePath directory)
  155. {
  156. foreach (file; packageInfoFiles) {
  157. auto filename = directory ~ file.filename;
  158. if (existsFile(filename)) return filename;
  159. }
  160. return NativePath.init;
  161. }
  162.  
  163. /** Constructs a `Package` using a package that is physically present on the local file system.
  164.  
  165. Params:
  166. root = The directory in which the package resides.
  167. recipe_file = Optional path to the package recipe file. If left
  168. empty, the `root` directory will be searched for a recipe file.
  169. parent = Reference to the parent package, if the new package is a
  170. sub package.
  171. version_override = Optional version to associate to the package
  172. instead of the one declared in the package recipe, or the one
  173. determined by invoking the VCS (GIT currently).
  174. mode = Whether to issue errors, warning, or ignore unknown keys in dub.json
  175. */
  176. static Package load(NativePath root, NativePath recipe_file = NativePath.init,
  177. Package parent = null, string version_override = "",
  178. StrictMode mode = StrictMode.Ignore)
  179. {
  180. import dub.recipe.io;
  181.  
  182. if (recipe_file.empty) recipe_file = findPackageFile(root);
  183.  
  184. enforce(!recipe_file.empty,
  185. "No package file found in %s, expected one of %s"
  186. .format(root.toNativeString(),
  187. packageInfoFiles.map!(f => cast(string)f.filename).join("/")));
  188.  
  189. auto recipe = readPackageRecipe(recipe_file, parent ? parent.name : null, mode);
  190.  
  191. auto ret = new Package(recipe, root, parent, version_override);
  192. ret.m_infoFile = recipe_file;
  193. return ret;
  194. }
  195.  
  196. /** Returns the qualified name of the package.
  197.  
  198. The qualified name includes any possible parent package if this package
  199. is a sub package.
  200. */
  201. @property string name()
  202. const {
  203. if (m_parentPackage) return m_parentPackage.name ~ ":" ~ m_info.name;
  204. else return m_info.name;
  205. }
  206.  
  207. /** Returns the directory in which the package resides.
  208.  
  209. Note that this can be empty for packages that are not stored in the
  210. local file system.
  211. */
  212. @property NativePath path() const { return m_path; }
  213.  
  214.  
  215. /** Accesses the version associated with this package.
  216.  
  217. Note that this is a shortcut to `this.recipe.version_`.
  218. */
  219. @property Version version_() const { return m_parentPackage ? m_parentPackage.version_ : Version(m_info.version_); }
  220. /// ditto
  221. @property void version_(Version value) { assert(m_parentPackage is null); m_info.version_ = value.toString(); }
  222.  
  223. /** Accesses the recipe contents of this package.
  224.  
  225. The recipe contains any default values and configurations added by DUB.
  226. To access the raw user recipe, use the `rawRecipe` property.
  227.  
  228. See_Also: `rawRecipe`
  229. */
  230. @property ref inout(PackageRecipe) recipe() inout { return m_info; }
  231.  
  232. /** Accesses the original package recipe.
  233.  
  234. The returned recipe matches exactly the contents of the original package
  235. recipe. For the effective package recipe, augmented with DUB generated
  236. default settings and configurations, use the `recipe` property.
  237.  
  238. See_Also: `recipe`
  239. */
  240. @property ref const(PackageRecipe) rawRecipe() const { return m_rawRecipe; }
  241.  
  242. /** Returns the path to the package recipe file.
  243.  
  244. Note that this can be empty for packages that are not stored in the
  245. local file system.
  246. */
  247. @property NativePath recipePath() const { return m_infoFile; }
  248.  
  249.  
  250. /** Returns the base package of this package.
  251.  
  252. The base package is the root of the sub package hierarchy (i.e. the
  253. topmost parent). This will be `null` for packages that are not sub
  254. packages.
  255. */
  256. @property inout(Package) basePackage() inout { return m_parentPackage ? m_parentPackage.basePackage : this; }
  257.  
  258. /** Returns the parent of this package.
  259.  
  260. The parent package is the package that contains a sub package. This will
  261. be `null` for packages that are not sub packages.
  262. */
  263. @property inout(Package) parentPackage() inout { return m_parentPackage; }
  264.  
  265. /** Returns the list of all sub packages.
  266.  
  267. Note that this is a shortcut for `this.recipe.subPackages`.
  268. */
  269. @property inout(SubPackage)[] subPackages() inout { return m_info.subPackages; }
  270.  
  271. /** Returns the list of all build configuration names.
  272.  
  273. Configuration contents can be accessed using `this.recipe.configurations`.
  274. */
  275. @property string[] configurations()
  276. const {
  277. auto ret = appender!(string[])();
  278. foreach (ref config; m_info.configurations)
  279. ret.put(config.name);
  280. return ret.data;
  281. }
  282.  
  283. /** Returns the list of all custom build type names.
  284.  
  285. Build type contents can be accessed using `this.recipe.buildTypes`.
  286. */
  287. @property string[] customBuildTypes()
  288. const {
  289. auto ret = appender!(string[])();
  290. foreach (name; m_info.buildTypes.byKey)
  291. ret.put(name);
  292. return ret.data;
  293. }
  294.  
  295. /** Writes the current recipe contents to a recipe file.
  296.  
  297. The parameter-less overload writes to `this.path`, which must not be
  298. empty. The default recipe file name will be used in this case.
  299. */
  300. void storeInfo()
  301. {
  302. storeInfo(m_path);
  303. m_infoFile = m_path ~ defaultPackageFilename;
  304. }
  305. /// ditto
  306. void storeInfo(NativePath path)
  307. const {
  308. auto filename = path ~ defaultPackageFilename;
  309. writeJsonFile(filename, m_info.toJson());
  310. }
  311.  
  312. /// Get the metadata cache for this package
  313. @property Json metadataCache()
  314. {
  315. enum silent_fail = true;
  316. return jsonFromFile(m_path ~ ".dub/metadata_cache.json", silent_fail);
  317. }
  318.  
  319. /// Write metadata cache for this package
  320. @property void metadataCache(Json json)
  321. {
  322. enum create_if_missing = true;
  323. if (isWritableDir(m_path ~ ".dub", create_if_missing))
  324. writeJsonFile(m_path ~ ".dub/metadata_cache.json", json);
  325. // TODO: store elsewhere
  326. }
  327.  
  328. /** Returns the package recipe of a non-path-based sub package.
  329.  
  330. For sub packages that are declared within the package recipe of the
  331. parent package, this function will return the corresponding recipe. Sub
  332. packages declared using a path must be loaded manually (or using the
  333. `PackageManager`).
  334. */
  335. Nullable!PackageRecipe getInternalSubPackage(string name)
  336. {
  337. foreach (ref p; m_info.subPackages)
  338. if (p.path.empty && p.recipe.name == name)
  339. return Nullable!PackageRecipe(p.recipe);
  340. return Nullable!PackageRecipe();
  341. }
  342.  
  343. /** Searches for use of compiler-specific flags that have generic
  344. alternatives.
  345.  
  346. This will output a warning message for each such flag to the console.
  347. */
  348. void warnOnSpecialCompilerFlags()
  349. {
  350. // warn about use of special flags
  351. m_info.buildSettings.warnOnSpecialCompilerFlags(m_info.name, null);
  352. foreach (ref config; m_info.configurations)
  353. config.buildSettings.warnOnSpecialCompilerFlags(m_info.name, config.name);
  354. }
  355.  
  356. /** Retrieves a build settings template.
  357.  
  358. If no `config` is given, this returns the build settings declared at the
  359. root level of the package recipe. Otherwise returns the settings
  360. declared within the given configuration (excluding those at the root
  361. level).
  362.  
  363. Note that this is a shortcut to accessing `this.recipe.buildSettings` or
  364. `this.recipe.configurations[].buildSettings`.
  365. */
  366. const(BuildSettingsTemplate) getBuildSettings(string config = null)
  367. const {
  368. if (config.length) {
  369. foreach (ref conf; m_info.configurations)
  370. if (conf.name == config)
  371. return conf.buildSettings;
  372. assert(false, "Unknown configuration: "~config);
  373. } else {
  374. return m_info.buildSettings;
  375. }
  376. }
  377.  
  378. /** Returns all BuildSettings for the given platform and configuration.
  379.  
  380. This will gather the effective build settings declared in tha package
  381. recipe for when building on a particular platform and configuration.
  382. Root build settings and configuration specific settings will be
  383. merged.
  384. */
  385. BuildSettings getBuildSettings(in BuildPlatform platform, string config)
  386. const {
  387. BuildSettings ret;
  388. m_info.buildSettings.getPlatformSettings(ret, platform, this.path);
  389. bool found = false;
  390. foreach(ref conf; m_info.configurations){
  391. if( conf.name != config ) continue;
  392. conf.buildSettings.getPlatformSettings(ret, platform, this.path);
  393. found = true;
  394. break;
  395. }
  396. assert(found || config is null, "Unknown configuration for "~m_info.name~": "~config);
  397.  
  398. // construct default target name based on package name
  399. if( ret.targetName.empty ) ret.targetName = this.name.replace(":", "_");
  400.  
  401. // special support for DMD style flags
  402. getCompiler("dmd").extractBuildOptions(ret);
  403.  
  404. return ret;
  405. }
  406.  
  407. /** Returns the combination of all build settings for all configurations
  408. and platforms.
  409.  
  410. This can be useful for IDEs to gather a list of all potentially used
  411. files or settings.
  412. */
  413. BuildSettings getCombinedBuildSettings()
  414. const {
  415. BuildSettings ret;
  416. m_info.buildSettings.getPlatformSettings(ret, BuildPlatform.any, this.path);
  417. foreach(ref conf; m_info.configurations)
  418. conf.buildSettings.getPlatformSettings(ret, BuildPlatform.any, this.path);
  419.  
  420. // construct default target name based on package name
  421. if (ret.targetName.empty) ret.targetName = this.name.replace(":", "_");
  422.  
  423. // special support for DMD style flags
  424. getCompiler("dmd").extractBuildOptions(ret);
  425.  
  426. return ret;
  427. }
  428.  
  429. /** Adds build type specific settings to an existing set of build settings.
  430.  
  431. This function searches the package recipe for overridden build types. If
  432. none is found, the default build settings will be applied, if
  433. `build_type` matches a default build type name. An exception is thrown
  434. otherwise.
  435. */
  436. void addBuildTypeSettings(ref BuildSettings settings, in BuildPlatform platform, string build_type)
  437. const {
  438. import std.process;
  439. string dflags = environment.get("DFLAGS", "");
  440. settings.addDFlags(dflags.split());
  441.  
  442. if (auto pbt = build_type in m_info.buildTypes) {
  443. logDiagnostic("Using custom build type '%s'.", build_type);
  444. pbt.getPlatformSettings(settings, platform, this.path);
  445. } else {
  446. with(BuildOption) switch (build_type) {
  447. default: throw new Exception(format("Unknown build type for %s: '%s'", this.name, build_type));
  448. case "$DFLAGS": break;
  449. case "plain": break;
  450. case "debug": settings.addOptions(debugMode, debugInfo); break;
  451. case "release": settings.addOptions(releaseMode, optimize, inline); break;
  452. case "release-debug": settings.addOptions(releaseMode, optimize, inline, debugInfo); break;
  453. case "release-nobounds": settings.addOptions(releaseMode, optimize, inline, noBoundsCheck); break;
  454. case "unittest": settings.addOptions(unittests, debugMode, debugInfo); break;
  455. case "docs": settings.addOptions(syntaxOnly, _docs); break;
  456. case "ddox": settings.addOptions(syntaxOnly, _ddox); break;
  457. case "profile": settings.addOptions(profile, optimize, inline, debugInfo); break;
  458. case "profile-gc": settings.addOptions(profileGC, debugInfo); break;
  459. case "cov": settings.addOptions(coverage, debugInfo); break;
  460. case "cov-ctfe": settings.addOptions(coverageCTFE, debugInfo); break;
  461. case "unittest-cov": settings.addOptions(unittests, coverage, debugMode, debugInfo); break;
  462. case "unittest-cov-ctfe": settings.addOptions(unittests, coverageCTFE, debugMode, debugInfo); break;
  463. case "syntax": settings.addOptions(syntaxOnly); break;
  464. }
  465. }
  466. }
  467.  
  468. /** Returns the selected configuration for a certain dependency.
  469.  
  470. If no configuration is specified in the package recipe, null will be
  471. returned instead.
  472.  
  473. FIXME: The `platform` parameter is currently ignored, as the
  474. `"subConfigurations"` field doesn't support platform suffixes.
  475. */
  476. string getSubConfiguration(string config, in Package dependency, in BuildPlatform platform)
  477. const {
  478. bool found = false;
  479. foreach(ref c; m_info.configurations){
  480. if( c.name == config ){
  481. if( auto pv = dependency.name in c.buildSettings.subConfigurations ) return *pv;
  482. found = true;
  483. break;
  484. }
  485. }
  486. assert(found || config is null, "Invalid configuration \""~config~"\" for "~this.name);
  487. if( auto pv = dependency.name in m_info.buildSettings.subConfigurations ) return *pv;
  488. return null;
  489. }
  490.  
  491. /** Returns the default configuration to build for the given platform.
  492.  
  493. This will return the first configuration that is applicable to the given
  494. platform, or `null` if none is applicable. By default, only library
  495. configurations will be returned. Setting `allow_non_library` to `true`
  496. will also return executable configurations.
  497.  
  498. See_Also: `getPlatformConfigurations`
  499. */
  500. string getDefaultConfiguration(in BuildPlatform platform, bool allow_non_library = false)
  501. const {
  502. foreach (ref conf; m_info.configurations) {
  503. if (!conf.matchesPlatform(platform)) continue;
  504. if (!allow_non_library && conf.buildSettings.targetType == TargetType.executable) continue;
  505. return conf.name;
  506. }
  507. return null;
  508. }
  509.  
  510. /** Returns a list of configurations suitable for the given platform.
  511.  
  512. Params:
  513. platform = The platform against which to match configurations
  514. allow_non_library = If set to true, executable configurations will
  515. also be included.
  516.  
  517. See_Also: `getDefaultConfiguration`
  518. */
  519. string[] getPlatformConfigurations(in BuildPlatform platform, bool allow_non_library = false)
  520. const {
  521. auto ret = appender!(string[]);
  522. foreach(ref conf; m_info.configurations){
  523. if (!conf.matchesPlatform(platform)) continue;
  524. if (!allow_non_library && conf.buildSettings.targetType == TargetType.executable) continue;
  525. ret ~= conf.name;
  526. }
  527. if (ret.data.length == 0) ret.put(null);
  528. return ret.data;
  529. }
  530.  
  531. /** Determines if the package has a dependency to a certain package.
  532.  
  533. Params:
  534. dependency_name = The name of the package to search for
  535. config = Name of the configuration to use when searching
  536. for dependencies
  537.  
  538. See_Also: `getDependencies`
  539. */
  540. bool hasDependency(string dependency_name, string config)
  541. const {
  542. if (dependency_name in m_info.buildSettings.dependencies) return true;
  543. foreach (ref c; m_info.configurations)
  544. if ((config.empty || c.name == config) && dependency_name in c.buildSettings.dependencies)
  545. return true;
  546. return false;
  547. }
  548.  
  549. /** Retrieves all dependencies for a particular configuration.
  550.  
  551. This includes dependencies that are declared at the root level of the
  552. package recipe, as well as those declared within the specified
  553. configuration. If no configuration with the given name exists, only
  554. dependencies declared at the root level will be returned.
  555.  
  556. See_Also: `hasDependency`
  557. */
  558. const(Dependency[string]) getDependencies(string config)
  559. const {
  560. Dependency[string] ret;
  561. foreach (k, v; m_info.buildSettings.dependencies) {
  562. // DMD bug: Not giving `Dependency` here leads to RangeError
  563. Dependency dep = v;
  564. ret[k] = dep;
  565. }
  566. foreach (ref conf; m_info.configurations)
  567. if (conf.name == config) {
  568. foreach (k, v; conf.buildSettings.dependencies) {
  569. Dependency dep = v;
  570. ret[k] = dep;
  571. }
  572. break;
  573. }
  574. return ret;
  575. }
  576.  
  577. /** Returns a list of all possible dependencies of the package.
  578.  
  579. This list includes all dependencies of all configurations. The same
  580. package may occur multiple times with possibly different `Dependency`
  581. values.
  582. */
  583. PackageDependency[] getAllDependencies()
  584. const {
  585. auto ret = appender!(PackageDependency[]);
  586. getAllDependenciesRange().copy(ret);
  587. return ret.data;
  588. }
  589.  
  590. // Left as package until the final API for this has been found
  591. package auto getAllDependenciesRange()
  592. const {
  593. return
  594. chain(
  595. only(this.recipe.buildSettings.dependencies.byKeyValue),
  596. this.recipe.configurations.map!(c => c.buildSettings.dependencies.byKeyValue)
  597. )
  598. .joiner()
  599. .map!(d => PackageDependency(d.key, d.value));
  600. }
  601.  
  602.  
  603. /** Returns a description of the package for use in IDEs or build tools.
  604. */
  605. PackageDescription describe(BuildPlatform platform, string config)
  606. const {
  607. return describe(platform, getCompiler(platform.compilerBinary), config);
  608. }
  609. /// ditto
  610. PackageDescription describe(BuildPlatform platform, Compiler compiler, string config)
  611. const {
  612. PackageDescription ret;
  613. ret.configuration = config;
  614. ret.path = m_path.toNativeString();
  615. ret.name = this.name;
  616. ret.version_ = this.version_;
  617. ret.description = m_info.description;
  618. ret.homepage = m_info.homepage;
  619. ret.authors = m_info.authors.dup;
  620. ret.copyright = m_info.copyright;
  621. ret.license = m_info.license;
  622. ret.dependencies = getDependencies(config).keys;
  623.  
  624. // save build settings
  625. BuildSettings bs = getBuildSettings(platform, config);
  626. BuildSettings allbs = getCombinedBuildSettings();
  627.  
  628. ret.targetType = bs.targetType;
  629. ret.targetPath = bs.targetPath;
  630. ret.targetName = bs.targetName;
  631. if (ret.targetType != TargetType.none && compiler)
  632. ret.targetFileName = compiler.getTargetFileName(bs, platform);
  633. ret.workingDirectory = bs.workingDirectory;
  634. ret.mainSourceFile = bs.mainSourceFile;
  635. ret.dflags = bs.dflags;
  636. ret.lflags = bs.lflags;
  637. ret.libs = bs.libs;
  638. ret.injectSourceFiles = bs.injectSourceFiles;
  639. ret.copyFiles = bs.copyFiles;
  640. ret.versions = bs.versions;
  641. ret.debugVersions = bs.debugVersions;
  642. ret.importPaths = bs.importPaths;
  643. ret.stringImportPaths = bs.stringImportPaths;
  644. ret.preGenerateCommands = bs.preGenerateCommands;
  645. ret.postGenerateCommands = bs.postGenerateCommands;
  646. ret.preBuildCommands = bs.preBuildCommands;
  647. ret.postBuildCommands = bs.postBuildCommands;
  648. ret.environments = bs.environments;
  649. ret.buildEnvironments = bs.buildEnvironments;
  650. ret.runEnvironments = bs.runEnvironments;
  651. ret.preGenerateEnvironments = bs.preGenerateEnvironments;
  652. ret.postGenerateEnvironments = bs.postGenerateEnvironments;
  653. ret.preBuildEnvironments = bs.preBuildEnvironments;
  654. ret.postBuildEnvironments = bs.postBuildEnvironments;
  655. ret.preRunEnvironments = bs.preRunEnvironments;
  656. ret.postRunEnvironments = bs.postRunEnvironments;
  657.  
  658. // prettify build requirements output
  659. for (int i = 1; i <= BuildRequirement.max; i <<= 1)
  660. if (bs.requirements & cast(BuildRequirement)i)
  661. ret.buildRequirements ~= cast(BuildRequirement)i;
  662.  
  663. // prettify options output
  664. for (int i = 1; i <= BuildOption.max; i <<= 1)
  665. if (bs.options & cast(BuildOption)i)
  666. ret.options ~= cast(BuildOption)i;
  667.  
  668. // collect all possible source files and determine their types
  669. SourceFileRole[string] sourceFileTypes;
  670. foreach (f; allbs.stringImportFiles) sourceFileTypes[f] = SourceFileRole.unusedStringImport;
  671. foreach (f; allbs.importFiles) sourceFileTypes[f] = SourceFileRole.unusedImport;
  672. foreach (f; allbs.sourceFiles) sourceFileTypes[f] = SourceFileRole.unusedSource;
  673. foreach (f; bs.stringImportFiles) sourceFileTypes[f] = SourceFileRole.stringImport;
  674. foreach (f; bs.importFiles) sourceFileTypes[f] = SourceFileRole.import_;
  675. foreach (f; bs.sourceFiles) sourceFileTypes[f] = SourceFileRole.source;
  676. foreach (f; sourceFileTypes.byKey.array.sort()) {
  677. SourceFileDescription sf;
  678. sf.path = f;
  679. sf.role = sourceFileTypes[f];
  680. ret.files ~= sf;
  681. }
  682.  
  683. return ret;
  684. }
  685.  
  686. private void checkDubRequirements()
  687. {
  688. import dub.dependency : Dependency;
  689. import dub.semver : isValidVersion;
  690. import dub.version_ : dubVersion;
  691. import std.exception : enforce;
  692.  
  693. const dep = m_info.toolchainRequirements.dub;
  694.  
  695. static assert(dubVersion.length);
  696. static if (dubVersion[0] == 'v') {
  697. enum dv = dubVersion[1 .. $];
  698. }
  699. else {
  700. enum dv = dubVersion;
  701. }
  702. static assert(isValidVersion(dv));
  703.  
  704. enforce(dep.matches(dv),
  705. "dub-" ~ dv ~ " does not comply with toolchainRequirements.dub "
  706. ~ "specification: " ~ m_info.toolchainRequirements.dub.toString()
  707. ~ "\nPlease consider upgrading your DUB installation");
  708. }
  709.  
  710. private void fillWithDefaults()
  711. {
  712. auto bs = &m_info.buildSettings;
  713.  
  714. // check for default string import folders
  715. if ("" !in bs.stringImportPaths) {
  716. foreach(defvf; ["views"]){
  717. if( existsFile(m_path ~ defvf) )
  718. bs.stringImportPaths[""] ~= defvf;
  719. }
  720. }
  721.  
  722. // check for default source folders
  723. immutable hasSP = ("" in bs.sourcePaths) !is null;
  724. immutable hasIP = ("" in bs.importPaths) !is null;
  725. if (!hasSP || !hasIP) {
  726. foreach (defsf; ["source/", "src/"]) {
  727. if (existsFile(m_path ~ defsf)) {
  728. if (!hasSP) bs.sourcePaths[""] ~= defsf;
  729. if (!hasIP) bs.importPaths[""] ~= defsf;
  730. }
  731. }
  732. }
  733.  
  734. // generate default configurations if none are defined
  735. if (m_info.configurations.length == 0) {
  736. // check for default app_main
  737. string app_main_file;
  738. auto pkg_name = m_info.name.length ? m_info.name : "unknown";
  739. MainFileSearch: foreach_reverse(sf; bs.sourcePaths.get("", null)){
  740. auto p = m_path ~ sf;
  741. if( !existsFile(p) ) continue;
  742. foreach(fil; ["app.d", "main.d", pkg_name ~ "/main.d", pkg_name ~ "/" ~ "app.d"]){
  743. if( existsFile(p ~ fil) ) {
  744. app_main_file = (NativePath(sf) ~ fil).toNativeString();
  745. break MainFileSearch;
  746. }
  747. }
  748. }
  749.  
  750. if (bs.targetType == TargetType.executable) {
  751. BuildSettingsTemplate app_settings;
  752. app_settings.targetType = TargetType.executable;
  753. if (bs.mainSourceFile.empty) app_settings.mainSourceFile = app_main_file;
  754. m_info.configurations ~= ConfigurationInfo("application", app_settings);
  755. } else if (bs.targetType != TargetType.none) {
  756. BuildSettingsTemplate lib_settings;
  757. lib_settings.targetType = bs.targetType == TargetType.autodetect ? TargetType.library : bs.targetType;
  758.  
  759. if (bs.targetType == TargetType.autodetect) {
  760. if (app_main_file.length) {
  761. lib_settings.excludedSourceFiles[""] ~= app_main_file;
  762.  
  763. BuildSettingsTemplate app_settings;
  764. app_settings.targetType = TargetType.executable;
  765. app_settings.mainSourceFile = app_main_file;
  766. m_info.configurations ~= ConfigurationInfo("application", app_settings);
  767. }
  768. }
  769.  
  770. m_info.configurations ~= ConfigurationInfo("library", lib_settings);
  771. }
  772. }
  773. }
  774.  
  775. package void simpleLint()
  776. const {
  777. if (m_parentPackage) {
  778. if (m_parentPackage.path != path) {
  779. if (this.recipe.license.length && this.recipe.license != m_parentPackage.recipe.license)
  780. logWarn("Warning: License in subpackage %s is different than it's parent package, this is discouraged.", name);
  781. }
  782. }
  783. if (name.empty) logWarn("Warning: The package in %s has no name.", path);
  784. bool[string] cnames;
  785. foreach (ref c; this.recipe.configurations) {
  786. if (c.name in cnames)
  787. logWarn("Warning: Multiple configurations with the name \"%s\" are defined in package \"%s\". This will most likely cause configuration resolution issues.",
  788. c.name, this.name);
  789. cnames[c.name] = true;
  790. }
  791. }
  792.  
  793. /// Exclude files listed in mainSourceFile for other configurations unless they are listed in sourceFiles
  794. private void mutuallyExcludeMainFiles()
  795. {
  796. string[] allMainFiles;
  797. foreach (ref config; m_info.configurations)
  798. if (!config.buildSettings.mainSourceFile.empty())
  799. allMainFiles ~= config.buildSettings.mainSourceFile;
  800.  
  801. if (allMainFiles.length == 0)
  802. return;
  803.  
  804. foreach (ref config; m_info.configurations) {
  805. import std.algorithm.searching : canFind;
  806. auto bs = &config.buildSettings;
  807. auto otherMainFiles = allMainFiles.filter!(elem => (elem != bs.mainSourceFile)).array;
  808.  
  809. if (bs.sourceFiles.length == 0)
  810. bs.excludedSourceFiles[""] ~= otherMainFiles;
  811. else
  812. foreach (suffix, arr; bs.sourceFiles)
  813. bs.excludedSourceFiles[suffix] ~= otherMainFiles.filter!(elem => !canFind(arr, elem)).array;
  814. }
  815. }
  816. }
  817.  
  818. private string determineVersionFromSCM(NativePath path)
  819. {
  820. if (existsFile(path ~ ".git"))
  821. {
  822. import dub.internal.git : determineVersionWithGit;
  823.  
  824. return determineVersionWithGit(path);
  825. }
  826. return null;
  827. }