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