Newer
Older
dub_jkp / source / dub / dub.d
@Marcelo Silva Nascimento Mancini Marcelo Silva Nascimento Mancini on 13 Aug 2023 66 KB Implemented recipe files for dub #2684 (#2685)
  1. /**
  2. A package manager.
  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.dub;
  9.  
  10. import dub.compilers.compiler;
  11. import dub.data.settings : SPS = SkipPackageSuppliers, Settings;
  12. import dub.dependency;
  13. import dub.dependencyresolver;
  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.url;
  18. import dub.internal.logging;
  19. import dub.package_;
  20. import dub.packagemanager;
  21. import dub.packagesuppliers;
  22. import dub.project;
  23. import dub.generators.generator;
  24. import dub.init;
  25.  
  26. import std.algorithm;
  27. import std.array : array, replace;
  28. import std.conv : text, to;
  29. import std.encoding : sanitize;
  30. import std.exception : enforce;
  31. import std.file;
  32. import std.process : environment;
  33. import std.range : assumeSorted, empty;
  34. import std.string;
  35.  
  36. // Set output path and options for coverage reports
  37. version (DigitalMars) version (D_Coverage)
  38. {
  39. shared static this()
  40. {
  41. import core.runtime, std.file, std.path, std.stdio;
  42. dmd_coverSetMerge(true);
  43. auto path = buildPath(dirName(thisExePath()), "../cov");
  44. if (!path.exists)
  45. mkdir(path);
  46. dmd_coverDestPath(path);
  47. }
  48. }
  49.  
  50. static this()
  51. {
  52. import dub.compilers.dmd : DMDCompiler;
  53. import dub.compilers.gdc : GDCCompiler;
  54. import dub.compilers.ldc : LDCCompiler;
  55. registerCompiler(new DMDCompiler);
  56. registerCompiler(new GDCCompiler);
  57. registerCompiler(new LDCCompiler);
  58. }
  59.  
  60. deprecated("use defaultRegistryURLs") enum defaultRegistryURL = defaultRegistryURLs[0];
  61.  
  62. /// The URL to the official package registry and it's default fallback registries.
  63. static immutable string[] defaultRegistryURLs = [
  64. "https://code.dlang.org/",
  65. "https://codemirror.dlang.org/",
  66. "https://dub.bytecraft.nl/",
  67. "https://code-mirror.dlang.io/",
  68. ];
  69.  
  70. /** Returns a default list of package suppliers.
  71.  
  72. This will contain a single package supplier that points to the official
  73. package registry.
  74.  
  75. See_Also: `defaultRegistryURLs`
  76. */
  77. PackageSupplier[] defaultPackageSuppliers()
  78. {
  79. logDiagnostic("Using dub registry url '%s'", defaultRegistryURLs[0]);
  80. return [new FallbackPackageSupplier(defaultRegistryURLs.map!getRegistryPackageSupplier.array)];
  81. }
  82.  
  83. /** Returns a registry package supplier according to protocol.
  84.  
  85. Allowed protocols are dub+http(s):// and maven+http(s)://.
  86. */
  87. PackageSupplier getRegistryPackageSupplier(string url)
  88. {
  89. switch (url.startsWith("dub+", "mvn+", "file://"))
  90. {
  91. case 1:
  92. return new RegistryPackageSupplier(URL(url[4..$]));
  93. case 2:
  94. return new MavenRegistryPackageSupplier(URL(url[4..$]));
  95. case 3:
  96. return new FileSystemPackageSupplier(NativePath(url[7..$]));
  97. default:
  98. return new RegistryPackageSupplier(URL(url));
  99. }
  100. }
  101.  
  102. unittest
  103. {
  104. auto dubRegistryPackageSupplier = getRegistryPackageSupplier("dub+https://code.dlang.org");
  105. assert(dubRegistryPackageSupplier.description.canFind(" https://code.dlang.org"));
  106.  
  107. dubRegistryPackageSupplier = getRegistryPackageSupplier("https://code.dlang.org");
  108. assert(dubRegistryPackageSupplier.description.canFind(" https://code.dlang.org"));
  109.  
  110. auto mavenRegistryPackageSupplier = getRegistryPackageSupplier("mvn+http://localhost:8040/maven/libs-release/dubpackages");
  111. assert(mavenRegistryPackageSupplier.description.canFind(" http://localhost:8040/maven/libs-release/dubpackages"));
  112.  
  113. auto fileSystemPackageSupplier = getRegistryPackageSupplier("file:///etc/dubpackages");
  114. assert(fileSystemPackageSupplier.description.canFind(" " ~ NativePath("/etc/dubpackages").toNativeString));
  115. }
  116.  
  117. /** Provides a high-level entry point for DUB's functionality.
  118.  
  119. This class provides means to load a certain project (a root package with
  120. all of its dependencies) and to perform high-level operations as found in
  121. the command line interface.
  122. */
  123. class Dub {
  124. private {
  125. bool m_dryRun = false;
  126. PackageManager m_packageManager;
  127. PackageSupplier[] m_packageSuppliers;
  128. NativePath m_rootPath;
  129. string m_mainRecipePath;
  130. SpecialDirs m_dirs;
  131. Settings m_config;
  132. Project m_project;
  133. string m_defaultCompiler;
  134. }
  135.  
  136. /** The default placement location of fetched packages.
  137.  
  138. This property can be altered, so that packages which are downloaded as part
  139. of the normal upgrade process are stored in a certain location. This is
  140. how the "--local" and "--system" command line switches operate.
  141. */
  142. PlacementLocation defaultPlacementLocation = PlacementLocation.user;
  143.  
  144.  
  145. /** Initializes the instance for use with a specific root package.
  146.  
  147. Note that a package still has to be loaded using one of the
  148. `loadPackage` overloads.
  149.  
  150. Params:
  151. root_path = Path to the root package
  152. additional_package_suppliers = A list of package suppliers to try
  153. before the suppliers found in the configurations files and the
  154. `defaultPackageSuppliers`.
  155. skip_registry = Can be used to skip using the configured package
  156. suppliers, as well as the default suppliers.
  157. */
  158. this(string root_path = ".", PackageSupplier[] additional_package_suppliers = null,
  159. SkipPackageSuppliers skip_registry = SkipPackageSuppliers.none)
  160. {
  161. m_rootPath = NativePath(root_path);
  162. if (!m_rootPath.absolute) m_rootPath = getWorkingDirectory() ~ m_rootPath;
  163.  
  164. init();
  165.  
  166. m_packageSuppliers = this.computePkgSuppliers(additional_package_suppliers,
  167. skip_registry, environment.get("DUB_REGISTRY", null));
  168. m_packageManager = new PackageManager(m_rootPath, m_dirs.userPackages, m_dirs.systemSettings, false);
  169.  
  170. auto ccps = m_config.customCachePaths;
  171. if (ccps.length)
  172. m_packageManager.customCachePaths = ccps;
  173.  
  174. // TODO: Move this environment read out of the ctor
  175. if (auto p = environment.get("DUBPATH")) {
  176. version(Windows) enum pathsep = ";";
  177. else enum pathsep = ":";
  178. NativePath[] paths = p.split(pathsep)
  179. .map!(p => NativePath(p))().array();
  180. m_packageManager.searchPath = paths;
  181. }
  182. }
  183.  
  184. /** Initializes the instance with a single package search path, without
  185. loading a package.
  186.  
  187. This constructor corresponds to the "--bare" option of the command line
  188. interface.
  189.  
  190. Params:
  191. root = The root path of the Dub instance itself.
  192. pkg_root = The root of the location where packages are located
  193. Only packages under this location will be accessible.
  194. Note that packages at the top levels will be ignored.
  195. */
  196. this(NativePath root, NativePath pkg_root)
  197. {
  198. // Note: We're doing `init()` before setting the `rootPath`,
  199. // to prevent `init` from reading the project's settings.
  200. init();
  201. this.m_rootPath = root;
  202. m_packageManager = new PackageManager(pkg_root);
  203. }
  204.  
  205. deprecated("Use the overload that takes `(NativePath pkg_root, NativePath root)`")
  206. this(NativePath pkg_root)
  207. {
  208. this(pkg_root, pkg_root);
  209. }
  210.  
  211. private void init()
  212. {
  213. this.m_dirs = SpecialDirs.make();
  214. this.loadConfig();
  215. this.determineDefaultCompiler();
  216. }
  217.  
  218. /**
  219. * Load user configuration for this instance
  220. *
  221. * This can be overloaded in child classes to prevent library / unittest
  222. * dub from doing any kind of file IO.
  223. */
  224. protected void loadConfig()
  225. {
  226. import dub.internal.configy.Read;
  227.  
  228. void readSettingsFile (NativePath path_)
  229. {
  230. // TODO: Remove `StrictMode.Warn` after v1.40 release
  231. // The default is to error, but as the previous parser wasn't
  232. // complaining, we should first warn the user.
  233. const path = path_.toNativeString();
  234. if (path.exists) {
  235. auto newConf = parseConfigFileSimple!Settings(path, StrictMode.Warn);
  236. if (!newConf.isNull())
  237. this.m_config = this.m_config.merge(newConf.get());
  238. }
  239. }
  240.  
  241. const dubFolderPath = NativePath(thisExePath).parentPath;
  242.  
  243. // override default userSettings + userPackages if a $DPATH or
  244. // $DUB_HOME environment variable is set.
  245. bool overrideDubHomeFromEnv;
  246. {
  247. string dubHome = environment.get("DUB_HOME");
  248. if (!dubHome.length) {
  249. auto dpath = environment.get("DPATH");
  250. if (dpath.length)
  251. dubHome = (NativePath(dpath) ~ "dub/").toNativeString();
  252.  
  253. }
  254. if (dubHome.length) {
  255. overrideDubHomeFromEnv = true;
  256.  
  257. m_dirs.userSettings = NativePath(dubHome);
  258. m_dirs.userPackages = m_dirs.userSettings;
  259. m_dirs.cache = m_dirs.userPackages ~ "cache";
  260. }
  261. }
  262.  
  263. readSettingsFile(m_dirs.systemSettings ~ "settings.json");
  264. readSettingsFile(dubFolderPath ~ "../etc/dub/settings.json");
  265. version (Posix) {
  266. if (dubFolderPath.absolute && dubFolderPath.startsWith(NativePath("usr")))
  267. readSettingsFile(NativePath("/etc/dub/settings.json"));
  268. }
  269.  
  270. // Override user + local package path from system / binary settings
  271. // Then continues loading local settings from these folders. (keeping
  272. // global /etc/dub/settings.json settings intact)
  273. //
  274. // Don't use it if either $DPATH or $DUB_HOME are set, as environment
  275. // variables usually take precedence over configuration.
  276. if (!overrideDubHomeFromEnv && this.m_config.dubHome.set) {
  277. m_dirs.userSettings = NativePath(this.m_config.dubHome.expandEnvironmentVariables);
  278. }
  279.  
  280. // load user config:
  281. readSettingsFile(m_dirs.userSettings ~ "settings.json");
  282.  
  283. // load per-package config:
  284. if (!this.m_rootPath.empty)
  285. readSettingsFile(this.m_rootPath ~ "dub.settings.json");
  286.  
  287. // same as userSettings above, but taking into account the
  288. // config loaded from user settings and per-package config as well.
  289. if (!overrideDubHomeFromEnv && this.m_config.dubHome.set) {
  290. m_dirs.userPackages = NativePath(this.m_config.dubHome.expandEnvironmentVariables);
  291. m_dirs.cache = m_dirs.userPackages ~ "cache";
  292. }
  293. }
  294.  
  295. unittest
  296. {
  297. scope (exit) environment.remove("DUB_REGISTRY");
  298. auto dub = new TestDub(".", null, SkipPackageSuppliers.configured);
  299. assert(dub.m_packageSuppliers.length == 0);
  300. environment["DUB_REGISTRY"] = "http://example.com/";
  301. dub = new TestDub(".", null, SkipPackageSuppliers.configured);
  302. assert(dub.m_packageSuppliers.length == 1);
  303. environment["DUB_REGISTRY"] = "http://example.com/;http://foo.com/";
  304. dub = new TestDub(".", null, SkipPackageSuppliers.configured);
  305. assert(dub.m_packageSuppliers.length == 2);
  306. dub = new TestDub(".", [new RegistryPackageSupplier(URL("http://bar.com/"))], SkipPackageSuppliers.configured);
  307. assert(dub.m_packageSuppliers.length == 3);
  308. }
  309.  
  310. /** Get the list of package suppliers.
  311.  
  312. Params:
  313. additional_package_suppliers = A list of package suppliers to try
  314. before the suppliers found in the configurations files and the
  315. `defaultPackageSuppliers`.
  316. skip_registry = Can be used to skip using the configured package
  317. suppliers, as well as the default suppliers.
  318. */
  319. deprecated("This is an implementation detail. " ~
  320. "Use `packageSuppliers` to get the computed list of package " ~
  321. "suppliers once a `Dub` instance has been constructed.")
  322. public PackageSupplier[] getPackageSuppliers(PackageSupplier[] additional_package_suppliers, SkipPackageSuppliers skip_registry)
  323. {
  324. return this.computePkgSuppliers(additional_package_suppliers, skip_registry, environment.get("DUB_REGISTRY", null));
  325. }
  326.  
  327. /// Ditto
  328. private PackageSupplier[] computePkgSuppliers(
  329. PackageSupplier[] additional_package_suppliers, SkipPackageSuppliers skip_registry,
  330. string dub_registry_var)
  331. {
  332. PackageSupplier[] ps = additional_package_suppliers;
  333.  
  334. if (skip_registry < SkipPackageSuppliers.all)
  335. {
  336. ps ~= dub_registry_var
  337. .splitter(";")
  338. .map!(url => getRegistryPackageSupplier(url))
  339. .array;
  340. }
  341.  
  342. if (skip_registry < SkipPackageSuppliers.configured)
  343. {
  344. ps ~= m_config.registryUrls
  345. .map!(url => getRegistryPackageSupplier(url))
  346. .array;
  347. }
  348.  
  349. if (skip_registry < SkipPackageSuppliers.standard)
  350. ps ~= defaultPackageSuppliers();
  351.  
  352. return ps;
  353. }
  354.  
  355. /// ditto
  356. deprecated("This is an implementation detail. " ~
  357. "Use `packageSuppliers` to get the computed list of package " ~
  358. "suppliers once a `Dub` instance has been constructed.")
  359. public PackageSupplier[] getPackageSuppliers(PackageSupplier[] additional_package_suppliers)
  360. {
  361. return getPackageSuppliers(additional_package_suppliers, m_config.skipRegistry);
  362. }
  363.  
  364. unittest
  365. {
  366. auto dub = new TestDub();
  367.  
  368. assert(dub.computePkgSuppliers(null, SkipPackageSuppliers.none, null).length == 1);
  369. assert(dub.computePkgSuppliers(null, SkipPackageSuppliers.configured, null).length == 0);
  370. assert(dub.computePkgSuppliers(null, SkipPackageSuppliers.standard, null).length == 0);
  371.  
  372. assert(dub.computePkgSuppliers(null, SkipPackageSuppliers.standard, "http://example.com/")
  373. .length == 1);
  374. }
  375.  
  376. @property bool dryRun() const { return m_dryRun; }
  377. @property void dryRun(bool v) { m_dryRun = v; }
  378.  
  379. /** Returns the root path (usually the current working directory).
  380. */
  381. @property NativePath rootPath() const { return m_rootPath; }
  382. /// ditto
  383. deprecated("Changing the root path is deprecated as it has non-obvious pitfalls " ~
  384. "(e.g. settings aren't reloaded). Instantiate a new `Dub` instead")
  385. @property void rootPath(NativePath root_path)
  386. {
  387. m_rootPath = root_path;
  388. if (!m_rootPath.absolute) m_rootPath = getWorkingDirectory() ~ m_rootPath;
  389. }
  390.  
  391. /// Returns the name listed in the dub.json of the current
  392. /// application.
  393. @property string projectName() const { return m_project.name; }
  394.  
  395. @property string mainRecipePath() const { return m_mainRecipePath; }
  396. /// Whenever the switch --recipe= is supplied, this member will be populated.
  397. @property string mainRecipePath(string recipePath)
  398. {
  399. return m_mainRecipePath = recipePath;
  400. }
  401.  
  402.  
  403. @property NativePath projectPath() const { return this.m_project.rootPackage.path; }
  404.  
  405. @property string[] configurations() const { return m_project.configurations; }
  406.  
  407. @property inout(PackageManager) packageManager() inout { return m_packageManager; }
  408.  
  409. @property inout(Project) project() inout { return m_project; }
  410.  
  411. @property inout(PackageSupplier)[] packageSuppliers() inout { return m_packageSuppliers; }
  412.  
  413. /** Returns the default compiler binary to use for building D code.
  414.  
  415. If set, the "defaultCompiler" field of the DUB user or system
  416. configuration file will be used. Otherwise the PATH environment variable
  417. will be searched for files named "dmd", "gdc", "gdmd", "ldc2", "ldmd2"
  418. (in that order, taking into account operating system specific file
  419. extensions) and the first match is returned. If no match is found, "dmd"
  420. will be used.
  421. */
  422. @property string defaultCompiler() const { return m_defaultCompiler; }
  423.  
  424. /** Returns the default architecture to use for building D code.
  425.  
  426. If set, the "defaultArchitecture" field of the DUB user or system
  427. configuration file will be used. Otherwise null will be returned.
  428. */
  429. @property string defaultArchitecture() const { return this.m_config.defaultArchitecture; }
  430.  
  431. /** Returns the default low memory option to use for building D code.
  432.  
  433. If set, the "defaultLowMemory" field of the DUB user or system
  434. configuration file will be used. Otherwise false will be returned.
  435. */
  436. @property bool defaultLowMemory() const { return this.m_config.defaultLowMemory; }
  437.  
  438. @property const(string[string]) defaultEnvironments() const { return this.m_config.defaultEnvironments; }
  439. @property const(string[string]) defaultBuildEnvironments() const { return this.m_config.defaultBuildEnvironments; }
  440. @property const(string[string]) defaultRunEnvironments() const { return this.m_config.defaultRunEnvironments; }
  441. @property const(string[string]) defaultPreGenerateEnvironments() const { return this.m_config.defaultPreGenerateEnvironments; }
  442. @property const(string[string]) defaultPostGenerateEnvironments() const { return this.m_config.defaultPostGenerateEnvironments; }
  443. @property const(string[string]) defaultPreBuildEnvironments() const { return this.m_config.defaultPreBuildEnvironments; }
  444. @property const(string[string]) defaultPostBuildEnvironments() const { return this.m_config.defaultPostBuildEnvironments; }
  445. @property const(string[string]) defaultPreRunEnvironments() const { return this.m_config.defaultPreRunEnvironments; }
  446. @property const(string[string]) defaultPostRunEnvironments() const { return this.m_config.defaultPostRunEnvironments; }
  447.  
  448. /** Loads the package that resides within the configured `rootPath`.
  449. */
  450. void loadPackage()
  451. {
  452. loadPackage(m_rootPath);
  453. }
  454.  
  455. /// Loads the package from the specified path as the main project package.
  456. void loadPackage(NativePath path)
  457. {
  458. m_project = new Project(m_packageManager, path);
  459. }
  460.  
  461. /// Loads a specific package as the main project package (can be a sub package)
  462. void loadPackage(Package pack)
  463. {
  464. m_project = new Project(m_packageManager, pack);
  465. }
  466.  
  467. /** Loads a single file package.
  468.  
  469. Single-file packages are D files that contain a package recipe comment
  470. at their top. A recipe comment must be a nested `/+ ... +/` style
  471. comment, containing the virtual recipe file name and a colon, followed by the
  472. recipe contents (what would normally be in dub.sdl/dub.json).
  473.  
  474. Example:
  475. ---
  476. /+ dub.sdl:
  477. name "test"
  478. dependency "vibe-d" version="~>0.7.29"
  479. +/
  480. import vibe.http.server;
  481.  
  482. void main()
  483. {
  484. auto settings = new HTTPServerSettings;
  485. settings.port = 8080;
  486. listenHTTP(settings, &hello);
  487. }
  488.  
  489. void hello(HTTPServerRequest req, HTTPServerResponse res)
  490. {
  491. res.writeBody("Hello, World!");
  492. }
  493. ---
  494.  
  495. The script above can be invoked with "dub --single test.d".
  496. */
  497. void loadSingleFilePackage(NativePath path)
  498. {
  499. import dub.recipe.io : parsePackageRecipe;
  500. import std.file : readText;
  501. import std.path : baseName, stripExtension;
  502.  
  503. path = makeAbsolute(path);
  504.  
  505. string file_content = readText(path.toNativeString());
  506.  
  507. if (file_content.startsWith("#!")) {
  508. auto idx = file_content.indexOf('\n');
  509. enforce(idx > 0, "The source fine doesn't contain anything but a shebang line.");
  510. file_content = file_content[idx+1 .. $];
  511. }
  512.  
  513. file_content = file_content.strip();
  514.  
  515. string recipe_content;
  516.  
  517. if (file_content.startsWith("/+")) {
  518. file_content = file_content[2 .. $];
  519. auto idx = file_content.indexOf("+/");
  520. enforce(idx >= 0, "Missing \"+/\" to close comment.");
  521. recipe_content = file_content[0 .. idx].strip();
  522. } else throw new Exception("The source file must start with a recipe comment.");
  523.  
  524. auto nidx = recipe_content.indexOf('\n');
  525.  
  526. auto idx = recipe_content.indexOf(':');
  527. enforce(idx > 0 && (nidx < 0 || nidx > idx),
  528. "The first line of the recipe comment must list the recipe file name followed by a colon (e.g. \"/+ dub.sdl:\").");
  529. auto recipe_filename = recipe_content[0 .. idx];
  530. recipe_content = recipe_content[idx+1 .. $];
  531. auto recipe_default_package_name = path.toString.baseName.stripExtension.strip;
  532.  
  533. auto recipe = parsePackageRecipe(recipe_content, recipe_filename, null, recipe_default_package_name);
  534. enforce(recipe.buildSettings.sourceFiles.length == 0, "Single-file packages are not allowed to specify source files.");
  535. enforce(recipe.buildSettings.sourcePaths.length == 0, "Single-file packages are not allowed to specify source paths.");
  536. enforce(recipe.buildSettings.cSourcePaths.length == 0, "Single-file packages are not allowed to specify C source paths.");
  537. enforce(recipe.buildSettings.importPaths.length == 0, "Single-file packages are not allowed to specify import paths.");
  538. enforce(recipe.buildSettings.cImportPaths.length == 0, "Single-file packages are not allowed to specify C import paths.");
  539. recipe.buildSettings.sourceFiles[""] = [path.toNativeString()];
  540. recipe.buildSettings.sourcePaths[""] = [];
  541. recipe.buildSettings.cSourcePaths[""] = [];
  542. recipe.buildSettings.importPaths[""] = [];
  543. recipe.buildSettings.cImportPaths[""] = [];
  544. recipe.buildSettings.mainSourceFile = path.toNativeString();
  545. if (recipe.buildSettings.targetType == TargetType.autodetect)
  546. recipe.buildSettings.targetType = TargetType.executable;
  547.  
  548. auto pack = new Package(recipe, path.parentPath, null, "~master");
  549. loadPackage(pack);
  550. }
  551. /// ditto
  552. void loadSingleFilePackage(string path)
  553. {
  554. loadSingleFilePackage(NativePath(path));
  555. }
  556.  
  557. /** Gets the default configuration for a particular build platform.
  558.  
  559. This forwards to `Project.getDefaultConfiguration` and requires a
  560. project to be loaded.
  561. */
  562. string getDefaultConfiguration(in BuildPlatform platform, bool allow_non_library_configs = true) const { return m_project.getDefaultConfiguration(platform, allow_non_library_configs); }
  563.  
  564. /** Attempts to upgrade the dependency selection of the loaded project.
  565.  
  566. Params:
  567. options = Flags that control how the upgrade is carried out
  568. packages_to_upgrade = Optional list of packages. If this list
  569. contains one or more packages, only those packages will
  570. be upgraded. Otherwise, all packages will be upgraded at
  571. once.
  572. */
  573. void upgrade(UpgradeOptions options, string[] packages_to_upgrade = null)
  574. {
  575. // clear non-existent version selections
  576. if (!(options & UpgradeOptions.upgrade)) {
  577. next_pack:
  578. foreach (p; m_project.selections.selectedPackages) {
  579. auto dep = m_project.selections.getSelectedVersion(p);
  580. if (!dep.path.empty) {
  581. auto path = dep.path;
  582. if (!path.absolute) path = this.rootPath ~ path;
  583. try if (m_packageManager.getOrLoadPackage(path)) continue;
  584. catch (Exception e) { logDebug("Failed to load path based selection: %s", e.toString().sanitize); }
  585. } else if (!dep.repository.empty) {
  586. if (m_packageManager.loadSCMPackage(getBasePackageName(p), dep.repository))
  587. continue;
  588. } else {
  589. if (m_packageManager.getPackage(p, dep.version_)) continue;
  590. foreach (ps; m_packageSuppliers) {
  591. try {
  592. auto versions = ps.getVersions(p);
  593. if (versions.canFind!(v => dep.matches(v, VersionMatchMode.strict)))
  594. continue next_pack;
  595. } catch (Exception e) {
  596. logWarn("Error querying versions for %s, %s: %s", p, ps.description, e.msg);
  597. logDebug("Full error: %s", e.toString().sanitize());
  598. }
  599. }
  600. }
  601.  
  602. logWarn("Selected package %s %s doesn't exist. Using latest matching version instead.", p, dep);
  603. m_project.selections.deselectVersion(p);
  604. }
  605. }
  606.  
  607. auto resolver = new DependencyVersionResolver(
  608. this, options, m_project.rootPackage, m_project.selections);
  609. Dependency[string] versions = resolver.resolve(packages_to_upgrade);
  610.  
  611. if (options & UpgradeOptions.dryRun) {
  612. bool any = false;
  613. string rootbasename = getBasePackageName(m_project.rootPackage.name);
  614.  
  615. foreach (p, ver; versions) {
  616. if (!ver.path.empty || !ver.repository.empty) continue;
  617.  
  618. auto basename = getBasePackageName(p);
  619. if (basename == rootbasename) continue;
  620.  
  621. if (!m_project.selections.hasSelectedVersion(basename)) {
  622. logInfo("Upgrade", Color.cyan,
  623. "Package %s would be selected with version %s", basename, ver);
  624. any = true;
  625. continue;
  626. }
  627. auto sver = m_project.selections.getSelectedVersion(basename);
  628. if (!sver.path.empty || !sver.repository.empty) continue;
  629. if (ver.version_ <= sver.version_) continue;
  630. logInfo("Upgrade", Color.cyan,
  631. "%s would be upgraded from %s to %s.",
  632. basename.color(Mode.bold), sver, ver);
  633. any = true;
  634. }
  635. if (any) logInfo("Use \"%s\" to perform those changes", "dub upgrade".color(Mode.bold));
  636. return;
  637. }
  638.  
  639. foreach (p, ver; versions) {
  640. assert(!p.canFind(":"), "Resolved packages contain a sub package!?: "~p);
  641. Package pack;
  642. if (!ver.path.empty) {
  643. try pack = m_packageManager.getOrLoadPackage(ver.path);
  644. catch (Exception e) {
  645. logDebug("Failed to load path based selection: %s", e.toString().sanitize);
  646. continue;
  647. }
  648. } else if (!ver.repository.empty) {
  649. pack = m_packageManager.loadSCMPackage(p, ver.repository);
  650. } else {
  651. assert(ver.isExactVersion, "Resolved dependency is neither path, nor repository, nor exact version based!?");
  652. pack = m_packageManager.getPackage(p, ver.version_);
  653. if (pack && m_packageManager.isManagedPackage(pack)
  654. && ver.version_.isBranch && (options & UpgradeOptions.upgrade) != 0)
  655. {
  656. // TODO: only re-install if there is actually a new commit available
  657. logInfo("Re-installing branch based dependency %s %s", p, ver.toString());
  658. m_packageManager.remove(pack);
  659. pack = null;
  660. }
  661. }
  662.  
  663. FetchOptions fetchOpts;
  664. fetchOpts |= (options & UpgradeOptions.preRelease) != 0 ? FetchOptions.usePrerelease : FetchOptions.none;
  665. if (!pack) fetch(p, ver.version_, defaultPlacementLocation, fetchOpts, "getting selected version");
  666. if ((options & UpgradeOptions.select) && p != m_project.rootPackage.name) {
  667. if (!ver.repository.empty) {
  668. m_project.selections.selectVersion(p, ver.repository);
  669. } else if (ver.path.empty) {
  670. m_project.selections.selectVersion(p, ver.version_);
  671. } else {
  672. NativePath relpath = ver.path;
  673. if (relpath.absolute) relpath = relpath.relativeTo(m_project.rootPackage.path);
  674. m_project.selections.selectVersion(p, relpath);
  675. }
  676. }
  677. }
  678.  
  679. string[] missingDependenciesBeforeReinit = m_project.missingDependencies;
  680. m_project.reinit();
  681.  
  682. if (!m_project.hasAllDependencies) {
  683. auto resolvedDependencies = setDifference(
  684. assumeSorted(missingDependenciesBeforeReinit),
  685. assumeSorted(m_project.missingDependencies)
  686. );
  687. if (!resolvedDependencies.empty)
  688. upgrade(options, m_project.missingDependencies);
  689. }
  690.  
  691. if ((options & UpgradeOptions.select) && !(options & (UpgradeOptions.noSaveSelections | UpgradeOptions.dryRun)))
  692. m_project.saveSelections();
  693. }
  694.  
  695. /** Generate project files for a specified generator.
  696.  
  697. Any existing project files will be overridden.
  698. */
  699. void generateProject(string ide, GeneratorSettings settings)
  700. {
  701. settings.cache = this.m_dirs.cache;
  702. if (settings.overrideToolWorkingDirectory is NativePath.init)
  703. settings.overrideToolWorkingDirectory = m_rootPath;
  704. // With a requested `unittest` config, switch to the special test runner
  705. // config (which doesn't require an existing `unittest` configuration).
  706. if (settings.config == "unittest") {
  707. const test_config = m_project.addTestRunnerConfiguration(settings, !m_dryRun);
  708. if (test_config) settings.config = test_config;
  709. }
  710.  
  711. auto generator = createProjectGenerator(ide, m_project);
  712. if (m_dryRun) return; // TODO: pass m_dryRun to the generator
  713. generator.generate(settings);
  714. }
  715.  
  716. /** Generate project files using the special test runner (`dub test`) configuration.
  717.  
  718. Any existing project files will be overridden.
  719. */
  720. void testProject(GeneratorSettings settings, string config, NativePath custom_main_file)
  721. {
  722. settings.cache = this.m_dirs.cache;
  723. if (settings.overrideToolWorkingDirectory is NativePath.init)
  724. settings.overrideToolWorkingDirectory = m_rootPath;
  725. if (!custom_main_file.empty && !custom_main_file.absolute) custom_main_file = m_rootPath ~ custom_main_file;
  726.  
  727. const test_config = m_project.addTestRunnerConfiguration(settings, !m_dryRun, config, custom_main_file);
  728. if (!test_config) return; // target type "none"
  729.  
  730. settings.config = test_config;
  731.  
  732. auto generator = createProjectGenerator("build", m_project);
  733. generator.generate(settings);
  734. }
  735.  
  736. /** Executes D-Scanner tests on the current project. **/
  737. void lintProject(string[] args)
  738. {
  739. import std.path : buildPath, buildNormalizedPath;
  740.  
  741. if (m_dryRun) return;
  742.  
  743. auto tool = "dscanner";
  744.  
  745. auto tool_pack = m_packageManager.getBestPackage(tool);
  746. if (!tool_pack) {
  747. logInfo("Hint", Color.light_blue, "%s is not present, getting and storing it user wide", tool);
  748. tool_pack = fetch(tool, VersionRange.Any, defaultPlacementLocation, FetchOptions.none);
  749. }
  750.  
  751. auto dscanner_dub = new Dub(null, m_packageSuppliers);
  752. dscanner_dub.loadPackage(tool_pack);
  753. dscanner_dub.upgrade(UpgradeOptions.select);
  754.  
  755. GeneratorSettings settings = this.makeAppSettings();
  756. foreach (dependencyPackage; m_project.dependencies)
  757. {
  758. auto cfgs = m_project.getPackageConfigs(settings.platform, null, true);
  759. auto buildSettings = dependencyPackage.getBuildSettings(settings.platform, cfgs[dependencyPackage.name]);
  760. foreach (importPath; buildSettings.importPaths) {
  761. settings.runArgs ~= ["-I", buildNormalizedPath(dependencyPackage.path.toNativeString(), importPath.idup)];
  762. }
  763. foreach (cimportPath; buildSettings.cImportPaths) {
  764. settings.runArgs ~= ["-I", buildNormalizedPath(dependencyPackage.path.toNativeString(), cimportPath.idup)];
  765. }
  766. }
  767.  
  768. string configFilePath = buildPath(m_project.rootPackage.path.toNativeString(), "dscanner.ini");
  769. if (!args.canFind("--config") && exists(configFilePath)) {
  770. settings.runArgs ~= ["--config", configFilePath];
  771. }
  772.  
  773. settings.runArgs ~= args ~ [m_project.rootPackage.path.toNativeString()];
  774. dscanner_dub.generateProject("build", settings);
  775. }
  776.  
  777. /** Prints the specified build settings necessary for building the root package.
  778. */
  779. void listProjectData(GeneratorSettings settings, string[] requestedData, ListBuildSettingsFormat list_type)
  780. {
  781. import std.stdio;
  782. import std.ascii : newline;
  783.  
  784. if (settings.overrideToolWorkingDirectory is NativePath.init)
  785. settings.overrideToolWorkingDirectory = m_rootPath;
  786.  
  787. // Split comma-separated lists
  788. string[] requestedDataSplit =
  789. requestedData
  790. .map!(a => a.splitter(",").map!strip)
  791. .joiner()
  792. .array();
  793.  
  794. auto data = m_project.listBuildSettings(settings, requestedDataSplit, list_type);
  795.  
  796. string delimiter;
  797. final switch (list_type) with (ListBuildSettingsFormat) {
  798. case list: delimiter = newline ~ newline; break;
  799. case listNul: delimiter = "\0\0"; break;
  800. case commandLine: delimiter = " "; break;
  801. case commandLineNul: delimiter = "\0\0"; break;
  802. }
  803.  
  804. write(data.joiner(delimiter));
  805. if (delimiter != "\0\0") writeln();
  806. }
  807.  
  808. /// Cleans intermediate/cache files of the given package (or all packages)
  809. deprecated("Use `clean(Package)` instead")
  810. void cleanPackage(NativePath path)
  811. {
  812. auto ppack = Package.findPackageFile(path);
  813. enforce(!ppack.empty, "No package found.", path.toNativeString());
  814. this.clean(Package.load(path, ppack));
  815. }
  816.  
  817. /// Ditto
  818. void clean()
  819. {
  820. const cache = this.m_dirs.cache;
  821. logInfo("Cleaning", Color.green, "all artifacts at %s",
  822. cache.toNativeString().color(Mode.bold));
  823. if (existsFile(cache))
  824. rmdirRecurse(cache.toNativeString());
  825. }
  826.  
  827. /// Ditto
  828. void clean(Package pack)
  829. {
  830. const cache = this.packageCache(pack);
  831. logInfo("Cleaning", Color.green, "artifacts for package %s at %s",
  832. pack.name.color(Mode.bold),
  833. cache.toNativeString().color(Mode.bold));
  834.  
  835. // TODO: clear target files and copy files
  836. if (existsFile(cache))
  837. rmdirRecurse(cache.toNativeString());
  838. }
  839.  
  840. /// Fetches the package matching the dependency and places it in the specified location.
  841. deprecated("Use the overload that accepts either a `Version` or a `VersionRange` as second argument")
  842. Package fetch(string packageId, const Dependency dep, PlacementLocation location, FetchOptions options, string reason = "")
  843. {
  844. const vrange = dep.visit!(
  845. (VersionRange range) => range,
  846. function VersionRange (any) { throw new Exception("Cannot call `dub.fetch` with a " ~ typeof(any).stringof ~ " dependency"); }
  847. );
  848. return this.fetch(packageId, vrange, location, options, reason);
  849. }
  850.  
  851. /// Ditto
  852. Package fetch(string packageId, in Version vers, PlacementLocation location, FetchOptions options, string reason = "")
  853. {
  854. return this.fetch(packageId, VersionRange(vers, vers), location, options, reason);
  855. }
  856.  
  857. /// Ditto
  858. Package fetch(string packageId, in VersionRange range, PlacementLocation location, FetchOptions options, string reason = "")
  859. {
  860. auto basePackageName = getBasePackageName(packageId);
  861. Json pinfo;
  862. PackageSupplier supplier;
  863. foreach(ps; m_packageSuppliers){
  864. try {
  865. pinfo = ps.fetchPackageRecipe(basePackageName, Dependency(range), (options & FetchOptions.usePrerelease) != 0);
  866. if (pinfo.type == Json.Type.null_)
  867. continue;
  868. supplier = ps;
  869. break;
  870. } catch(Exception e) {
  871. logWarn("Package %s not found for %s: %s", packageId, ps.description, e.msg);
  872. logDebug("Full error: %s", e.toString().sanitize());
  873. }
  874. }
  875. enforce(pinfo.type != Json.Type.undefined, "No package "~packageId~" was found matching the dependency " ~ range.toString());
  876. Version ver = Version(pinfo["version"].get!string);
  877.  
  878. // always upgrade branch based versions - TODO: actually check if there is a new commit available
  879. Package existing = m_packageManager.getPackage(packageId, ver, location);
  880. if (options & FetchOptions.printOnly) {
  881. if (existing && existing.version_ != ver)
  882. logInfo("A new version for %s is available (%s -> %s). Run \"%s\" to switch.",
  883. packageId.color(Mode.bold), existing, ver,
  884. text("dub upgrade ", packageId).color(Mode.bold));
  885. return null;
  886. }
  887.  
  888. if (existing) {
  889. if (!ver.isBranch() || !(options & FetchOptions.forceBranchUpgrade) || location == PlacementLocation.local) {
  890. // TODO: support git working trees by performing a "git pull" instead of this
  891. logDiagnostic("Package %s %s (in %s packages) is already present with the latest version, skipping upgrade.",
  892. packageId, ver, location.toString);
  893. return existing;
  894. } else {
  895. logInfo("Removing", Color.yellow, "%s %s to prepare replacement with a new version", packageId.color(Mode.bold), ver);
  896. if (!m_dryRun) m_packageManager.remove(existing);
  897. }
  898. }
  899.  
  900. if (reason.length) logInfo("Fetching", Color.yellow, "%s %s (%s)", packageId.color(Mode.bold), ver, reason);
  901. else logInfo("Fetching", Color.yellow, "%s %s", packageId.color(Mode.bold), ver);
  902. if (m_dryRun) return null;
  903.  
  904. logDebug("Acquiring package zip file");
  905.  
  906. // repeat download on corrupted zips, see #1336
  907. foreach_reverse (i; 0..3)
  908. {
  909. import std.zip : ZipException;
  910.  
  911. auto path = getTempFile(basePackageName, ".zip");
  912. supplier.fetchPackage(path, basePackageName, Dependency(range), (options & FetchOptions.usePrerelease) != 0); // Q: continue on fail?
  913. scope(exit) removeFile(path);
  914. logDiagnostic("Placing to %s...", location.toString());
  915.  
  916. try {
  917. return m_packageManager.store(path, location, basePackageName, ver);
  918. } catch (ZipException e) {
  919. logInfo("Failed to extract zip archive for %s %s...", packageId, ver);
  920. // re-throw the exception at the end of the loop
  921. if (i == 0)
  922. throw e;
  923. }
  924. }
  925. assert(0, "Should throw a ZipException instead.");
  926. }
  927.  
  928. /** Removes a specific locally cached package.
  929.  
  930. This will delete the package files from disk and removes the
  931. corresponding entry from the list of known packages.
  932.  
  933. Params:
  934. pack = Package instance to remove
  935. */
  936. void remove(in Package pack)
  937. {
  938. logInfo("Removing", Color.yellow, "%s (in %s)", pack.name.color(Mode.bold), pack.path.toNativeString());
  939. if (!m_dryRun) m_packageManager.remove(pack);
  940. }
  941.  
  942. /// Compatibility overload. Use the version without a `force_remove` argument instead.
  943. deprecated("Use `remove(pack)` directly instead, the boolean has no effect")
  944. void remove(in Package pack, bool force_remove)
  945. {
  946. remove(pack);
  947. }
  948.  
  949. /// @see remove(string, string, RemoveLocation)
  950. enum RemoveVersionWildcard = "*";
  951.  
  952. /** Removes one or more versions of a locally cached package.
  953.  
  954. This will remove a given package with a specified version from the
  955. given location. It will remove at most one package, unless `version_`
  956. is set to `RemoveVersionWildcard`.
  957.  
  958. Params:
  959. package_id = Name of the package to be removed
  960. location = Specifies the location to look for the given package
  961. name/version.
  962. resolve_version = Callback to select package version.
  963. */
  964. void remove(string package_id, PlacementLocation location,
  965. scope size_t delegate(in Package[] packages) resolve_version)
  966. {
  967. enforce(!package_id.empty);
  968. if (location == PlacementLocation.local) {
  969. logInfo("To remove a locally placed package, make sure you don't have any data"
  970. ~ "\nleft in it's directory and then simply remove the whole directory.");
  971. throw new Exception("dub cannot remove locally installed packages.");
  972. }
  973.  
  974. Package[] packages;
  975.  
  976. // Retrieve packages to be removed.
  977. foreach(pack; m_packageManager.getPackageIterator(package_id))
  978. if (m_packageManager.isManagedPackage(pack))
  979. packages ~= pack;
  980.  
  981. // Check validity of packages to be removed.
  982. if(packages.empty) {
  983. throw new Exception("Cannot find package to remove. ("
  984. ~ "id: '" ~ package_id ~ "', location: '" ~ to!string(location) ~ "'"
  985. ~ ")");
  986. }
  987.  
  988. // Sort package list in ascending version order
  989. packages.sort!((a, b) => a.version_ < b.version_);
  990.  
  991. immutable idx = resolve_version(packages);
  992. if (idx == size_t.max)
  993. return;
  994. else if (idx != packages.length)
  995. packages = packages[idx .. idx + 1];
  996.  
  997. logDebug("Removing %s packages.", packages.length);
  998. foreach(pack; packages) {
  999. try {
  1000. remove(pack);
  1001. } catch (Exception e) {
  1002. logError("Failed to remove %s %s: %s", package_id, pack, e.msg);
  1003. logInfo("Continuing with other packages (if any).");
  1004. }
  1005. }
  1006. }
  1007.  
  1008. /// Compatibility overload. Use the version without a `force_remove` argument instead.
  1009. deprecated("Use the overload without the 3rd argument (`force_remove`) instead")
  1010. void remove(string package_id, PlacementLocation location, bool force_remove,
  1011. scope size_t delegate(in Package[] packages) resolve_version)
  1012. {
  1013. remove(package_id, location, resolve_version);
  1014. }
  1015.  
  1016. /** Removes a specific version of a package.
  1017.  
  1018. Params:
  1019. package_id = Name of the package to be removed
  1020. version_ = Identifying a version or a wild card. If an empty string
  1021. is passed, the package will be removed from the location, if
  1022. there is only one version retrieved. This will throw an
  1023. exception, if there are multiple versions retrieved.
  1024. location = Specifies the location to look for the given package
  1025. name/version.
  1026. */
  1027. void remove(string package_id, string version_, PlacementLocation location)
  1028. {
  1029. remove(package_id, location, (in packages) {
  1030. if (version_ == RemoveVersionWildcard || version_.empty)
  1031. return packages.length;
  1032.  
  1033. foreach (i, p; packages) {
  1034. if (p.version_ == Version(version_))
  1035. return i;
  1036. }
  1037. throw new Exception("Cannot find package to remove. ("
  1038. ~ "id: '" ~ package_id ~ "', version: '" ~ version_ ~ "', location: '" ~ to!string(location) ~ "'"
  1039. ~ ")");
  1040. });
  1041. }
  1042.  
  1043. /// Compatibility overload. Use the version without a `force_remove` argument instead.
  1044. deprecated("Use the overload without force_remove instead")
  1045. void remove(string package_id, string version_, PlacementLocation location, bool force_remove)
  1046. {
  1047. remove(package_id, version_, location);
  1048. }
  1049.  
  1050. /** Adds a directory to the list of locally known packages.
  1051.  
  1052. Forwards to `PackageManager.addLocalPackage`.
  1053.  
  1054. Params:
  1055. path = Path to the package
  1056. ver = Optional version to associate with the package (can be left
  1057. empty)
  1058. system = Make the package known system wide instead of user wide
  1059. (requires administrator privileges).
  1060.  
  1061. See_Also: `removeLocalPackage`
  1062. */
  1063. void addLocalPackage(string path, string ver, bool system)
  1064. {
  1065. if (m_dryRun) return;
  1066. m_packageManager.addLocalPackage(makeAbsolute(path), ver, system ? PlacementLocation.system : PlacementLocation.user);
  1067. }
  1068.  
  1069. /** Removes a directory from the list of locally known packages.
  1070.  
  1071. Forwards to `PackageManager.removeLocalPackage`.
  1072.  
  1073. Params:
  1074. path = Path to the package
  1075. system = Make the package known system wide instead of user wide
  1076. (requires administrator privileges).
  1077.  
  1078. See_Also: `addLocalPackage`
  1079. */
  1080. void removeLocalPackage(string path, bool system)
  1081. {
  1082. if (m_dryRun) return;
  1083. m_packageManager.removeLocalPackage(makeAbsolute(path), system ? PlacementLocation.system : PlacementLocation.user);
  1084. }
  1085.  
  1086. /** Registers a local directory to search for packages to use for satisfying
  1087. dependencies.
  1088.  
  1089. Params:
  1090. path = Path to a directory containing package directories
  1091. system = Make the package known system wide instead of user wide
  1092. (requires administrator privileges).
  1093.  
  1094. See_Also: `removeSearchPath`
  1095. */
  1096. void addSearchPath(string path, bool system)
  1097. {
  1098. if (m_dryRun) return;
  1099. m_packageManager.addSearchPath(makeAbsolute(path), system ? PlacementLocation.system : PlacementLocation.user);
  1100. }
  1101.  
  1102. /** Deregisters a local directory search path.
  1103.  
  1104. Params:
  1105. path = Path to a directory containing package directories
  1106. system = Make the package known system wide instead of user wide
  1107. (requires administrator privileges).
  1108.  
  1109. See_Also: `addSearchPath`
  1110. */
  1111. void removeSearchPath(string path, bool system)
  1112. {
  1113. if (m_dryRun) return;
  1114. m_packageManager.removeSearchPath(makeAbsolute(path), system ? PlacementLocation.system : PlacementLocation.user);
  1115. }
  1116.  
  1117. /** Queries all package suppliers with the given query string.
  1118.  
  1119. Returns a list of tuples, where the first entry is the human readable
  1120. name of the package supplier and the second entry is the list of
  1121. matched packages.
  1122.  
  1123. Params:
  1124. query = the search term to match packages on
  1125.  
  1126. See_Also: `PackageSupplier.searchPackages`
  1127. */
  1128. auto searchPackages(string query)
  1129. {
  1130. import std.typecons : Tuple, tuple;
  1131. Tuple!(string, PackageSupplier.SearchResult[])[] results;
  1132. foreach (ps; this.m_packageSuppliers) {
  1133. try
  1134. results ~= tuple(ps.description, ps.searchPackages(query));
  1135. catch (Exception e) {
  1136. logWarn("Searching %s for '%s' failed: %s", ps.description, query, e.msg);
  1137. }
  1138. }
  1139. return results.filter!(tup => tup[1].length);
  1140. }
  1141.  
  1142. /** Returns a list of all available versions (including branches) for a
  1143. particular package.
  1144.  
  1145. The list returned is based on the registered package suppliers. Local
  1146. packages are not queried in the search for versions.
  1147.  
  1148. See_also: `getLatestVersion`
  1149. */
  1150. Version[] listPackageVersions(string name)
  1151. {
  1152. Version[] versions;
  1153. auto basePackageName = getBasePackageName(name);
  1154. foreach (ps; this.m_packageSuppliers) {
  1155. try versions ~= ps.getVersions(basePackageName);
  1156. catch (Exception e) {
  1157. logWarn("Failed to get versions for package %s on provider %s: %s", name, ps.description, e.msg);
  1158. }
  1159. }
  1160. return versions.sort().uniq.array;
  1161. }
  1162.  
  1163. /** Returns the latest available version for a particular package.
  1164.  
  1165. This function returns the latest numbered version of a package. If no
  1166. numbered versions are available, it will return an available branch,
  1167. preferring "~master".
  1168.  
  1169. Params:
  1170. package_name = The name of the package in question.
  1171. prefer_stable = If set to `true` (the default), returns the latest
  1172. stable version, even if there are newer pre-release versions.
  1173.  
  1174. See_also: `listPackageVersions`
  1175. */
  1176. Version getLatestVersion(string package_name, bool prefer_stable = true)
  1177. {
  1178. auto vers = listPackageVersions(package_name);
  1179. enforce(!vers.empty, "Failed to find any valid versions for a package name of '"~package_name~"'.");
  1180. auto final_versions = vers.filter!(v => !v.isBranch && !v.isPreRelease).array;
  1181. if (prefer_stable && final_versions.length) return final_versions[$-1];
  1182. else return vers[$-1];
  1183. }
  1184.  
  1185. /** Initializes a directory with a package skeleton.
  1186.  
  1187. Params:
  1188. path = Path of the directory to create the new package in. The
  1189. directory will be created if it doesn't exist.
  1190. deps = List of dependencies to add to the package recipe.
  1191. type = Specifies the type of the application skeleton to use.
  1192. format = Determines the package recipe format to use.
  1193. recipe_callback = Optional callback that can be used to
  1194. customize the recipe before it gets written.
  1195. app_args = Arguments to provide to the custom initialization routine.
  1196. */
  1197. void createEmptyPackage(NativePath path, string[] deps, string type,
  1198. PackageFormat format = PackageFormat.sdl,
  1199. scope void delegate(ref PackageRecipe, ref PackageFormat) recipe_callback = null,
  1200. string[] app_args = [])
  1201. {
  1202. if (!path.absolute) path = m_rootPath ~ path;
  1203. path.normalize();
  1204.  
  1205. VersionRange[string] depVers;
  1206. string[] notFound; // keep track of any failed packages in here
  1207. foreach (dep; deps) {
  1208. try {
  1209. Version ver = getLatestVersion(dep);
  1210. if (ver.isBranch())
  1211. depVers[dep] = VersionRange(ver);
  1212. else
  1213. depVers[dep] = VersionRange.fromString("~>" ~ ver.toString());
  1214. } catch (Exception e) {
  1215. notFound ~= dep;
  1216. }
  1217. }
  1218.  
  1219. if(notFound.length > 1){
  1220. throw new Exception(.format("Couldn't find packages: %-(%s, %).", notFound));
  1221. }
  1222. else if(notFound.length == 1){
  1223. throw new Exception(.format("Couldn't find package: %-(%s, %).", notFound));
  1224. }
  1225.  
  1226. if (m_dryRun) return;
  1227.  
  1228. initPackage(path, depVers, type, format, recipe_callback);
  1229.  
  1230. if (!["vibe.d", "deimos", "minimal"].canFind(type)) {
  1231. runCustomInitialization(path, type, app_args);
  1232. }
  1233.  
  1234. //Act smug to the user.
  1235. logInfo("Success", Color.green, "created empty project in %s", path.toNativeString().color(Mode.bold));
  1236. }
  1237.  
  1238. private void runCustomInitialization(NativePath path, string type, string[] runArgs)
  1239. {
  1240. string packageName = type;
  1241. auto template_pack = m_packageManager.getBestPackage(packageName);
  1242. if (!template_pack) {
  1243. logInfo("%s is not present, getting and storing it user wide", packageName);
  1244. template_pack = fetch(packageName, VersionRange.Any, defaultPlacementLocation, FetchOptions.none);
  1245. }
  1246.  
  1247. Package initSubPackage = m_packageManager.getSubPackage(template_pack, "init-exec", false);
  1248. auto template_dub = new Dub(null, m_packageSuppliers);
  1249. template_dub.loadPackage(initSubPackage);
  1250.  
  1251. GeneratorSettings settings = this.makeAppSettings();
  1252. settings.runArgs = runArgs;
  1253.  
  1254. initSubPackage.recipe.buildSettings.workingDirectory = path.toNativeString();
  1255. template_dub.generateProject("build", settings);
  1256. }
  1257.  
  1258. /** Converts the package recipe of the loaded root package to the given format.
  1259.  
  1260. Params:
  1261. destination_file_ext = The file extension matching the desired
  1262. format. Possible values are "json" or "sdl".
  1263. print_only = Print the converted recipe instead of writing to disk
  1264. */
  1265. void convertRecipe(string destination_file_ext, bool print_only = false)
  1266. {
  1267. import std.path : extension;
  1268. import std.stdio : stdout;
  1269. import dub.recipe.io : serializePackageRecipe, writePackageRecipe;
  1270.  
  1271. if (print_only) {
  1272. auto dst = stdout.lockingTextWriter;
  1273. serializePackageRecipe(dst, m_project.rootPackage.rawRecipe, "dub."~destination_file_ext);
  1274. return;
  1275. }
  1276.  
  1277. auto srcfile = m_project.rootPackage.recipePath;
  1278. auto srcext = srcfile.head.name.extension;
  1279. if (srcext == "."~destination_file_ext) {
  1280. // no logging before this point
  1281. tagWidth.push(5);
  1282. logError("Package format is already %s.", destination_file_ext);
  1283. return;
  1284. }
  1285.  
  1286. writePackageRecipe(srcfile.parentPath ~ ("dub."~destination_file_ext), m_project.rootPackage.rawRecipe);
  1287. removeFile(srcfile);
  1288. }
  1289.  
  1290. /** Runs DDOX to generate or serve documentation.
  1291.  
  1292. Params:
  1293. run = If set to true, serves documentation on a local web server.
  1294. Otherwise generates actual HTML files.
  1295. generate_args = Additional command line arguments to pass to
  1296. "ddox generate-html" or "ddox serve-html".
  1297. */
  1298. void runDdox(bool run, string[] generate_args = null)
  1299. {
  1300. import std.process : browse;
  1301.  
  1302. if (m_dryRun) return;
  1303.  
  1304. // allow to choose a custom ddox tool
  1305. auto tool = m_project.rootPackage.recipe.ddoxTool;
  1306. if (tool.empty) tool = "ddox";
  1307.  
  1308. auto tool_pack = m_packageManager.getBestPackage(tool);
  1309. if (!tool_pack) {
  1310. logInfo("%s is not present, getting and storing it user wide", tool);
  1311. tool_pack = fetch(tool, VersionRange.Any, defaultPlacementLocation, FetchOptions.none);
  1312. }
  1313.  
  1314. auto ddox_dub = new Dub(null, m_packageSuppliers);
  1315. ddox_dub.loadPackage(tool_pack);
  1316. ddox_dub.upgrade(UpgradeOptions.select);
  1317.  
  1318. GeneratorSettings settings = this.makeAppSettings();
  1319.  
  1320. auto filterargs = m_project.rootPackage.recipe.ddoxFilterArgs.dup;
  1321. if (filterargs.empty) filterargs = ["--min-protection=Protected", "--only-documented"];
  1322.  
  1323. settings.runArgs = "filter" ~ filterargs ~ "docs.json";
  1324. ddox_dub.generateProject("build", settings);
  1325.  
  1326. auto p = tool_pack.path;
  1327. p.endsWithSlash = true;
  1328. auto tool_path = p.toNativeString();
  1329.  
  1330. if (run) {
  1331. settings.runArgs = ["serve-html", "--navigation-type=ModuleTree", "docs.json", "--web-file-dir="~tool_path~"public"] ~ generate_args;
  1332. browse("http://127.0.0.1:8080/");
  1333. } else {
  1334. settings.runArgs = ["generate-html", "--navigation-type=ModuleTree", "docs.json", "docs"] ~ generate_args;
  1335. }
  1336. ddox_dub.generateProject("build", settings);
  1337.  
  1338. if (!run) {
  1339. // TODO: ddox should copy those files itself
  1340. version(Windows) runCommand(`xcopy /S /D "`~tool_path~`public\*" docs\`, null, m_rootPath.toNativeString());
  1341. else runCommand("rsync -ru '"~tool_path~"public/' docs/", null, m_rootPath.toNativeString());
  1342. }
  1343. }
  1344.  
  1345. /**
  1346. * Compute and returns the path were artifacts are stored
  1347. *
  1348. * Expose `dub.generator.generator : packageCache` with this instance's
  1349. * configured cache.
  1350. */
  1351. protected NativePath packageCache (Package pkg) const
  1352. {
  1353. return .packageCache(this.m_dirs.cache, pkg);
  1354. }
  1355.  
  1356. /// Exposed because `commandLine` replicates `generateProject` for `dub describe`
  1357. /// instead of treating it like a regular generator... Remove this once the
  1358. /// flaw is fixed, and don't add more calls to this function!
  1359. package(dub) NativePath cachePathDontUse () const @safe pure nothrow @nogc
  1360. {
  1361. return this.m_dirs.cache;
  1362. }
  1363.  
  1364. /// Make a `GeneratorSettings` suitable to generate tools (DDOC, DScanner, etc...)
  1365. private GeneratorSettings makeAppSettings () const
  1366. {
  1367. GeneratorSettings settings;
  1368. auto compiler_binary = this.defaultCompiler;
  1369.  
  1370. settings.config = "application";
  1371. settings.buildType = "debug";
  1372. settings.compiler = getCompiler(compiler_binary);
  1373. settings.platform = settings.compiler.determinePlatform(
  1374. settings.buildSettings, compiler_binary, this.defaultArchitecture);
  1375. if (this.defaultLowMemory)
  1376. settings.buildSettings.options |= BuildOption.lowmem;
  1377. if (this.defaultEnvironments)
  1378. settings.buildSettings.addEnvironments(this.defaultEnvironments);
  1379. if (this.defaultBuildEnvironments)
  1380. settings.buildSettings.addBuildEnvironments(this.defaultBuildEnvironments);
  1381. if (this.defaultRunEnvironments)
  1382. settings.buildSettings.addRunEnvironments(this.defaultRunEnvironments);
  1383. if (this.defaultPreGenerateEnvironments)
  1384. settings.buildSettings.addPreGenerateEnvironments(this.defaultPreGenerateEnvironments);
  1385. if (this.defaultPostGenerateEnvironments)
  1386. settings.buildSettings.addPostGenerateEnvironments(this.defaultPostGenerateEnvironments);
  1387. if (this.defaultPreBuildEnvironments)
  1388. settings.buildSettings.addPreBuildEnvironments(this.defaultPreBuildEnvironments);
  1389. if (this.defaultPostBuildEnvironments)
  1390. settings.buildSettings.addPostBuildEnvironments(this.defaultPostBuildEnvironments);
  1391. if (this.defaultPreRunEnvironments)
  1392. settings.buildSettings.addPreRunEnvironments(this.defaultPreRunEnvironments);
  1393. if (this.defaultPostRunEnvironments)
  1394. settings.buildSettings.addPostRunEnvironments(this.defaultPostRunEnvironments);
  1395. settings.run = true;
  1396. settings.overrideToolWorkingDirectory = m_rootPath;
  1397.  
  1398. return settings;
  1399. }
  1400.  
  1401. private void determineDefaultCompiler()
  1402. {
  1403. import std.file : thisExePath;
  1404. import std.path : buildPath, dirName, expandTilde, isAbsolute, isDirSeparator;
  1405. import std.range : front;
  1406.  
  1407. // Env takes precedence
  1408. if (auto envCompiler = environment.get("DC"))
  1409. m_defaultCompiler = envCompiler;
  1410. else
  1411. m_defaultCompiler = m_config.defaultCompiler.expandTilde;
  1412. if (m_defaultCompiler.length && m_defaultCompiler.isAbsolute)
  1413. return;
  1414.  
  1415. static immutable BinaryPrefix = `$DUB_BINARY_PATH`;
  1416. if(m_defaultCompiler.startsWith(BinaryPrefix))
  1417. {
  1418. m_defaultCompiler = thisExePath().dirName() ~ m_defaultCompiler[BinaryPrefix.length .. $];
  1419. return;
  1420. }
  1421.  
  1422. if (!find!isDirSeparator(m_defaultCompiler).empty)
  1423. throw new Exception("defaultCompiler specified in a DUB config file cannot use an unqualified relative path:\n\n" ~ m_defaultCompiler ~
  1424. "\n\nUse \"$DUB_BINARY_PATH/../path/you/want\" instead.");
  1425.  
  1426. version (Windows) enum sep = ";", exe = ".exe";
  1427. version (Posix) enum sep = ":", exe = "";
  1428.  
  1429. auto compilers = ["dmd", "gdc", "gdmd", "ldc2", "ldmd2"];
  1430. // If a compiler name is specified, look for it next to dub.
  1431. // Otherwise, look for any of the common compilers adjacent to dub.
  1432. if (m_defaultCompiler.length)
  1433. {
  1434. string compilerPath = buildPath(thisExePath().dirName(), m_defaultCompiler ~ exe);
  1435. if (existsFile(compilerPath))
  1436. {
  1437. m_defaultCompiler = compilerPath;
  1438. return;
  1439. }
  1440. }
  1441. else
  1442. {
  1443. auto nextFound = compilers.find!(bin => existsFile(buildPath(thisExePath().dirName(), bin ~ exe)));
  1444. if (!nextFound.empty)
  1445. {
  1446. m_defaultCompiler = buildPath(thisExePath().dirName(), nextFound.front ~ exe);
  1447. return;
  1448. }
  1449. }
  1450.  
  1451. // If nothing found next to dub, search the user's PATH, starting
  1452. // with the compiler name from their DUB config file, if specified.
  1453. auto paths = environment.get("PATH", "").splitter(sep).map!NativePath;
  1454. if (m_defaultCompiler.length && paths.canFind!(p => existsFile(p ~ (m_defaultCompiler~exe))))
  1455. return;
  1456. foreach (p; paths) {
  1457. auto res = compilers.find!(bin => existsFile(p ~ (bin~exe)));
  1458. if (!res.empty) {
  1459. m_defaultCompiler = res.front;
  1460. return;
  1461. }
  1462. }
  1463. m_defaultCompiler = compilers[0];
  1464. }
  1465.  
  1466. unittest
  1467. {
  1468. import std.path: buildPath, absolutePath;
  1469. auto dub = new TestDub(".", null, SkipPackageSuppliers.configured);
  1470. immutable olddc = environment.get("DC", null);
  1471. immutable oldpath = environment.get("PATH", null);
  1472. immutable testdir = "test-determineDefaultCompiler";
  1473. void repairenv(string name, string var)
  1474. {
  1475. if (var !is null)
  1476. environment[name] = var;
  1477. else if (name in environment)
  1478. environment.remove(name);
  1479. }
  1480. scope (exit) repairenv("DC", olddc);
  1481. scope (exit) repairenv("PATH", oldpath);
  1482. scope (exit) rmdirRecurse(testdir);
  1483.  
  1484. version (Windows) enum sep = ";", exe = ".exe";
  1485. version (Posix) enum sep = ":", exe = "";
  1486.  
  1487. immutable dmdpath = testdir.buildPath("dmd", "bin");
  1488. immutable ldcpath = testdir.buildPath("ldc", "bin");
  1489. mkdirRecurse(dmdpath);
  1490. mkdirRecurse(ldcpath);
  1491. immutable dmdbin = dmdpath.buildPath("dmd"~exe);
  1492. immutable ldcbin = ldcpath.buildPath("ldc2"~exe);
  1493. std.file.write(dmdbin, null);
  1494. std.file.write(ldcbin, null);
  1495.  
  1496. environment["DC"] = dmdbin.absolutePath();
  1497. dub.determineDefaultCompiler();
  1498. assert(dub.m_defaultCompiler == dmdbin.absolutePath());
  1499.  
  1500. environment["DC"] = "dmd";
  1501. environment["PATH"] = dmdpath ~ sep ~ ldcpath;
  1502. dub.determineDefaultCompiler();
  1503. assert(dub.m_defaultCompiler == "dmd");
  1504.  
  1505. environment["DC"] = "ldc2";
  1506. environment["PATH"] = dmdpath ~ sep ~ ldcpath;
  1507. dub.determineDefaultCompiler();
  1508. assert(dub.m_defaultCompiler == "ldc2");
  1509.  
  1510. environment.remove("DC");
  1511. environment["PATH"] = ldcpath ~ sep ~ dmdpath;
  1512. dub.determineDefaultCompiler();
  1513. assert(dub.m_defaultCompiler == "ldc2");
  1514. }
  1515.  
  1516. private NativePath makeAbsolute(NativePath p) const { return p.absolute ? p : m_rootPath ~ p; }
  1517. private NativePath makeAbsolute(string p) const { return makeAbsolute(NativePath(p)); }
  1518. }
  1519.  
  1520.  
  1521. /// Option flags for `Dub.fetch`
  1522. enum FetchOptions
  1523. {
  1524. none = 0,
  1525. forceBranchUpgrade = 1<<0,
  1526. usePrerelease = 1<<1,
  1527. forceRemove = 1<<2, /// Deprecated, does nothing.
  1528. printOnly = 1<<3,
  1529. }
  1530.  
  1531. /// Option flags for `Dub.upgrade`
  1532. enum UpgradeOptions
  1533. {
  1534. none = 0,
  1535. upgrade = 1<<1, /// Upgrade existing packages
  1536. preRelease = 1<<2, /// include pre-release versions in upgrade
  1537. forceRemove = 1<<3, /// Deprecated, does nothing.
  1538. select = 1<<4, /// Update the dub.selections.json file with the upgraded versions
  1539. dryRun = 1<<5, /// Instead of downloading new packages, just print a message to notify the user of their existence
  1540. /*deprecated*/ printUpgradesOnly = dryRun, /// deprecated, use dryRun instead
  1541. /*deprecated*/ useCachedResult = 1<<6, /// deprecated, has no effect
  1542. noSaveSelections = 1<<7, /// Don't store updated selections on disk
  1543. }
  1544.  
  1545. /// Determines which of the default package suppliers are queried for packages.
  1546. public alias SkipPackageSuppliers = SPS;
  1547.  
  1548. private class DependencyVersionResolver : DependencyResolver!(Dependency, Dependency) {
  1549. protected {
  1550. Dub m_dub;
  1551. UpgradeOptions m_options;
  1552. Dependency[][string] m_packageVersions;
  1553. Package[string] m_remotePackages;
  1554. SelectedVersions m_selectedVersions;
  1555. Package m_rootPackage;
  1556. bool[string] m_packagesToUpgrade;
  1557. Package[PackageDependency] m_packages;
  1558. TreeNodes[][TreeNode] m_children;
  1559. }
  1560.  
  1561.  
  1562. this(Dub dub, UpgradeOptions options, Package root, SelectedVersions selected_versions)
  1563. {
  1564. assert(dub !is null);
  1565. assert(root !is null);
  1566. assert(selected_versions !is null);
  1567.  
  1568. if (environment.get("DUB_NO_RESOLVE_LIMIT") !is null)
  1569. super(ulong.max);
  1570. else
  1571. super(1_000_000);
  1572.  
  1573. m_dub = dub;
  1574. m_options = options;
  1575. m_rootPackage = root;
  1576. m_selectedVersions = selected_versions;
  1577. }
  1578.  
  1579. Dependency[string] resolve(string[] filter)
  1580. {
  1581. foreach (name; filter)
  1582. m_packagesToUpgrade[name] = true;
  1583. return super.resolve(TreeNode(m_rootPackage.name, Dependency(m_rootPackage.version_)),
  1584. (m_options & UpgradeOptions.dryRun) == 0);
  1585. }
  1586.  
  1587. protected bool isFixedPackage(string pack)
  1588. {
  1589. return m_packagesToUpgrade !is null && pack !in m_packagesToUpgrade;
  1590. }
  1591.  
  1592. protected override Dependency[] getAllConfigs(string pack)
  1593. {
  1594. if (auto pvers = pack in m_packageVersions)
  1595. return *pvers;
  1596.  
  1597. if ((!(m_options & UpgradeOptions.upgrade) || isFixedPackage(pack)) && m_selectedVersions.hasSelectedVersion(pack)) {
  1598. auto ret = [m_selectedVersions.getSelectedVersion(pack)];
  1599. logDiagnostic("Using fixed selection %s %s", pack, ret[0]);
  1600. m_packageVersions[pack] = ret;
  1601. return ret;
  1602. }
  1603.  
  1604. logDiagnostic("Search for versions of %s (%s package suppliers)", pack, m_dub.m_packageSuppliers.length);
  1605. Version[] versions;
  1606. foreach (p; m_dub.packageManager.getPackageIterator(pack))
  1607. versions ~= p.version_;
  1608.  
  1609. foreach (ps; m_dub.m_packageSuppliers) {
  1610. try {
  1611. auto vers = ps.getVersions(pack);
  1612. vers.reverse();
  1613. if (!vers.length) {
  1614. logDiagnostic("No versions for %s for %s", pack, ps.description);
  1615. continue;
  1616. }
  1617.  
  1618. versions ~= vers;
  1619. break;
  1620. } catch (Exception e) {
  1621. logWarn("Package %s not found in %s: %s", pack, ps.description, e.msg);
  1622. logDebug("Full error: %s", e.toString().sanitize);
  1623. }
  1624. }
  1625.  
  1626. // sort by version, descending, and remove duplicates
  1627. versions = versions.sort!"a>b".uniq.array;
  1628.  
  1629. // move pre-release versions to the back of the list if no preRelease flag is given
  1630. if (!(m_options & UpgradeOptions.preRelease))
  1631. versions = versions.filter!(v => !v.isPreRelease).array ~ versions.filter!(v => v.isPreRelease).array;
  1632.  
  1633. // filter out invalid/unreachable dependency specs
  1634. versions = versions.filter!((v) {
  1635. bool valid = getPackage(pack, Dependency(v)) !is null;
  1636. if (!valid) logDiagnostic("Excluding invalid dependency specification %s %s from dependency resolution process.", pack, v);
  1637. return valid;
  1638. }).array;
  1639.  
  1640. if (!versions.length) logDiagnostic("Nothing found for %s", pack);
  1641. else logDiagnostic("Return for %s: %s", pack, versions);
  1642.  
  1643. auto ret = versions.map!(v => Dependency(v)).array;
  1644. m_packageVersions[pack] = ret;
  1645. return ret;
  1646. }
  1647.  
  1648. protected override Dependency[] getSpecificConfigs(string pack, TreeNodes nodes)
  1649. {
  1650. if (!nodes.configs.path.empty || !nodes.configs.repository.empty) {
  1651. if (getPackage(nodes.pack, nodes.configs)) return [nodes.configs];
  1652. else return null;
  1653. }
  1654. else return null;
  1655. }
  1656.  
  1657.  
  1658. protected override TreeNodes[] getChildren(TreeNode node)
  1659. {
  1660. if (auto pc = node in m_children)
  1661. return *pc;
  1662. auto ret = getChildrenRaw(node);
  1663. m_children[node] = ret;
  1664. return ret;
  1665. }
  1666.  
  1667. private final TreeNodes[] getChildrenRaw(TreeNode node)
  1668. {
  1669. import std.array : appender;
  1670. auto ret = appender!(TreeNodes[]);
  1671. auto pack = getPackage(node.pack, node.config);
  1672. if (!pack) {
  1673. // this can happen when the package description contains syntax errors
  1674. logDebug("Invalid package in dependency tree: %s %s", node.pack, node.config);
  1675. return null;
  1676. }
  1677. auto basepack = pack.basePackage;
  1678.  
  1679. foreach (d; pack.getAllDependenciesRange()) {
  1680. auto dbasename = getBasePackageName(d.name);
  1681.  
  1682. // detect dependencies to the root package (or sub packages thereof)
  1683. if (dbasename == basepack.name) {
  1684. auto absdeppath = d.spec.mapToPath(pack.path).path;
  1685. absdeppath.endsWithSlash = true;
  1686. auto subpack = m_dub.m_packageManager.getSubPackage(basepack, getSubPackageName(d.name), true);
  1687. if (subpack) {
  1688. auto desireddeppath = basepack.path;
  1689. desireddeppath.endsWithSlash = true;
  1690.  
  1691. auto altdeppath = d.name == dbasename ? basepack.path : subpack.path;
  1692. altdeppath.endsWithSlash = true;
  1693.  
  1694. if (!d.spec.path.empty && absdeppath != desireddeppath)
  1695. logWarn("Sub package %s, referenced by %s %s must be referenced using the path to its base package",
  1696. subpack.name, pack.name, pack);
  1697.  
  1698. enforce(d.spec.path.empty || absdeppath == desireddeppath || absdeppath == altdeppath,
  1699. format("Dependency from %s to %s uses wrong path: %s vs. %s",
  1700. node.pack, subpack.name, absdeppath.toNativeString(), desireddeppath.toNativeString()));
  1701. }
  1702. ret ~= TreeNodes(d.name, node.config);
  1703. continue;
  1704. }
  1705.  
  1706. DependencyType dt;
  1707. if (d.spec.optional) {
  1708. if (d.spec.default_) dt = DependencyType.optionalDefault;
  1709. else dt = DependencyType.optional;
  1710. } else dt = DependencyType.required;
  1711.  
  1712. Dependency dspec = d.spec.mapToPath(pack.path);
  1713.  
  1714. // if not upgrading, use the selected version
  1715. if (!(m_options & UpgradeOptions.upgrade) && m_selectedVersions.hasSelectedVersion(dbasename))
  1716. dspec = m_selectedVersions.getSelectedVersion(dbasename);
  1717.  
  1718. // keep selected optional dependencies and avoid non-selected optional-default dependencies by default
  1719. if (!m_selectedVersions.bare) {
  1720. if (dt == DependencyType.optionalDefault && !m_selectedVersions.hasSelectedVersion(dbasename))
  1721. dt = DependencyType.optional;
  1722. else if (dt == DependencyType.optional && m_selectedVersions.hasSelectedVersion(dbasename))
  1723. dt = DependencyType.optionalDefault;
  1724. }
  1725.  
  1726. ret ~= TreeNodes(d.name, dspec, dt);
  1727. }
  1728. return ret.data;
  1729. }
  1730.  
  1731. protected override bool matches(Dependency configs, Dependency config)
  1732. {
  1733. if (!configs.path.empty) return configs.path == config.path;
  1734. return configs.merge(config).valid;
  1735. }
  1736.  
  1737. private Package getPackage(string name, Dependency dep)
  1738. {
  1739. auto key = PackageDependency(name, dep);
  1740. if (auto pp = key in m_packages)
  1741. return *pp;
  1742. auto p = getPackageRaw(name, dep);
  1743. m_packages[key] = p;
  1744. return p;
  1745. }
  1746.  
  1747. private Package getPackageRaw(string name, Dependency dep)
  1748. {
  1749. auto basename = getBasePackageName(name);
  1750.  
  1751. // for sub packages, first try to get them from the base package
  1752. if (basename != name) {
  1753. auto subname = getSubPackageName(name);
  1754. auto basepack = getPackage(basename, dep);
  1755. if (!basepack) return null;
  1756. if (auto sp = m_dub.m_packageManager.getSubPackage(basepack, subname, true)) {
  1757. return sp;
  1758. } else if (!basepack.subPackages.canFind!(p => p.path.length)) {
  1759. // note: external sub packages are handled further below
  1760. auto spr = basepack.getInternalSubPackage(subname);
  1761. if (!spr.isNull) {
  1762. auto sp = new Package(spr.get, basepack.path, basepack);
  1763. m_remotePackages[sp.name] = sp;
  1764. return sp;
  1765. } else {
  1766. logDiagnostic("Sub package %s doesn't exist in %s %s.", name, basename, dep);
  1767. return null;
  1768. }
  1769. } else {
  1770. logDiagnostic("External sub package %s %s not found.", name, dep);
  1771. return null;
  1772. }
  1773. }
  1774.  
  1775. // shortcut if the referenced package is the root package
  1776. if (basename == m_rootPackage.basePackage.name)
  1777. return m_rootPackage.basePackage;
  1778.  
  1779. if (!dep.repository.empty) {
  1780. auto ret = m_dub.packageManager.loadSCMPackage(name, dep.repository);
  1781. return ret !is null && dep.matches(ret.version_) ? ret : null;
  1782. } else if (!dep.path.empty) {
  1783. try {
  1784. return m_dub.packageManager.getOrLoadPackage(dep.path);
  1785. } catch (Exception e) {
  1786. logDiagnostic("Failed to load path based dependency %s: %s", name, e.msg);
  1787. logDebug("Full error: %s", e.toString().sanitize);
  1788. return null;
  1789. }
  1790. }
  1791. const vers = dep.version_;
  1792.  
  1793. if (auto ret = m_dub.m_packageManager.getBestPackage(name, vers))
  1794. return ret;
  1795.  
  1796. auto key = name ~ ":" ~ vers.toString();
  1797. if (auto ret = key in m_remotePackages)
  1798. return *ret;
  1799.  
  1800. auto prerelease = (m_options & UpgradeOptions.preRelease) != 0;
  1801.  
  1802. auto rootpack = name.split(":")[0];
  1803.  
  1804. foreach (ps; m_dub.m_packageSuppliers) {
  1805. if (rootpack == name) {
  1806. try {
  1807. auto desc = ps.fetchPackageRecipe(name, dep, prerelease);
  1808. if (desc.type == Json.Type.null_)
  1809. continue;
  1810. auto ret = new Package(desc);
  1811. m_remotePackages[key] = ret;
  1812. return ret;
  1813. } catch (Exception e) {
  1814. logDiagnostic("Metadata for %s %s could not be downloaded from %s: %s", name, vers, ps.description, e.msg);
  1815. logDebug("Full error: %s", e.toString().sanitize);
  1816. }
  1817. } else {
  1818. logDiagnostic("Package %s not found in base package description (%s). Downloading whole package.", name, vers.toString());
  1819. try {
  1820. FetchOptions fetchOpts;
  1821. fetchOpts |= prerelease ? FetchOptions.usePrerelease : FetchOptions.none;
  1822. m_dub.fetch(rootpack, vers, m_dub.defaultPlacementLocation, fetchOpts, "need sub package description");
  1823. auto ret = m_dub.m_packageManager.getBestPackage(name, vers);
  1824. if (!ret) {
  1825. logWarn("Package %s %s doesn't have a sub package %s", rootpack, dep, name);
  1826. return null;
  1827. }
  1828. m_remotePackages[key] = ret;
  1829. return ret;
  1830. } catch (Exception e) {
  1831. logDiagnostic("Package %s could not be downloaded from %s: %s", rootpack, ps.description, e.msg);
  1832. logDebug("Full error: %s", e.toString().sanitize);
  1833. }
  1834. }
  1835. }
  1836.  
  1837. m_remotePackages[key] = null;
  1838.  
  1839. logWarn("Package %s %s could not be loaded either locally, or from the configured package registries.", name, dep);
  1840. return null;
  1841. }
  1842. }
  1843.  
  1844. /**
  1845. * An instance of Dub that does not rely on the environment
  1846. *
  1847. * This instance of dub should not read any environment variables,
  1848. * nor should it do any file IO, to make it usable and reliable in unittests.
  1849. * Currently it reads environment variables but does not read the configuration.
  1850. */
  1851. package final class TestDub : Dub
  1852. {
  1853. /// Forward to base constructor
  1854. public this (string root = ".", PackageSupplier[] extras = null,
  1855. SkipPackageSuppliers skip = SkipPackageSuppliers.none)
  1856. {
  1857. super(root, extras, skip);
  1858. }
  1859.  
  1860. /// Avoid loading user configuration
  1861. protected override void loadConfig() { /* No-op */ }
  1862. }
  1863.  
  1864. private struct SpecialDirs {
  1865. /// The path where to store temporary files and directory
  1866. NativePath temp;
  1867. /// The system-wide dub-specific folder
  1868. NativePath systemSettings;
  1869. /// The dub-specific folder in the user home directory
  1870. NativePath userSettings;
  1871. /**
  1872. * User location where to install packages
  1873. *
  1874. * On Windows, this folder, unlike `userSettings`, does not roam,
  1875. * so an account on a company network will not save the content of this data,
  1876. * unlike `userSettings`.
  1877. *
  1878. * On Posix, this is currently equivalent to `userSettings`.
  1879. *
  1880. * See_Also: https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid
  1881. */
  1882. NativePath userPackages;
  1883.  
  1884. /**
  1885. * Location at which build/generation artifact will be written
  1886. *
  1887. * All build artifacts are stored under a single build cache,
  1888. * which is usually located under `$HOME/.dub/cache/` on POSIX,
  1889. * and `%LOCALAPPDATA%/dub/cache` on Windows.
  1890. *
  1891. * Versions of dub prior to v1.31.0 used to store artifact under the
  1892. * project directory, but this led to issues with packages stored on
  1893. * read-only file system / location, and lingering artifacts scattered
  1894. * through the file system.
  1895. *
  1896. * Dub writes in the cache directory some Json description files
  1897. * of the available artifacts. These files are intended to be read by
  1898. * 3rd party software (e.g. Meson). The default cache location specified
  1899. * in this function should therefore not change across future Dub versions.
  1900. */
  1901. NativePath cache;
  1902.  
  1903. /// Returns: An instance of `SpecialDirs` initialized from the environment
  1904. public static SpecialDirs make () {
  1905. import std.file : tempDir;
  1906.  
  1907. SpecialDirs result;
  1908. result.temp = NativePath(tempDir);
  1909.  
  1910. version(Windows) {
  1911. result.systemSettings = NativePath(environment.get("ProgramData")) ~ "dub/";
  1912. immutable appDataDir = environment.get("APPDATA");
  1913. result.userSettings = NativePath(appDataDir) ~ "dub/";
  1914. // LOCALAPPDATA is not defined before Windows Vista
  1915. result.userPackages = NativePath(environment.get("LOCALAPPDATA", appDataDir)) ~ "dub";
  1916. } else version(Posix) {
  1917. result.systemSettings = NativePath("/var/lib/dub/");
  1918. result.userSettings = NativePath(environment.get("HOME")) ~ ".dub/";
  1919. if (!result.userSettings.absolute)
  1920. result.userSettings = getWorkingDirectory() ~ result.userSettings;
  1921. result.userPackages = result.userSettings;
  1922. }
  1923. result.cache = result.userPackages ~ "cache";
  1924. return result;
  1925. }
  1926. }