Newer
Older
dub_jkp / source / dub / commandline.d
  1. /**
  2. Defines the behavior of the DUB command line client.
  3.  
  4. Copyright: © 2012-2013 Matthias Dondorff, Copyright © 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.commandline;
  9.  
  10. import dub.compilers.compiler;
  11. import dub.dependency;
  12. import dub.dub;
  13. import dub.generators.generator;
  14. import dub.internal.vibecompat.core.file;
  15. import dub.internal.vibecompat.data.json;
  16. import dub.internal.vibecompat.inet.path;
  17. import dub.internal.logging;
  18. import dub.package_;
  19. import dub.packagemanager;
  20. import dub.packagesuppliers;
  21. import dub.project;
  22. import dub.internal.utils : getDUBVersion, getClosestMatch, getTempFile;
  23.  
  24. import std.algorithm;
  25. import std.array;
  26. import std.conv;
  27. import std.encoding;
  28. import std.exception;
  29. import std.file;
  30. import std.getopt;
  31. import std.path : expandTilde, absolutePath, buildNormalizedPath;
  32. import std.process;
  33. import std.stdio;
  34. import std.string;
  35. import std.sumtype;
  36. import std.typecons : Tuple, tuple;
  37. import std.variant;
  38. import std.path: setExtension;
  39.  
  40. /** Retrieves a list of all available commands.
  41.  
  42. Commands are grouped by category.
  43. */
  44. CommandGroup[] getCommands() @safe pure nothrow
  45. {
  46. return [
  47. CommandGroup("Package creation",
  48. new InitCommand
  49. ),
  50. CommandGroup("Build, test and run",
  51. new RunCommand,
  52. new BuildCommand,
  53. new TestCommand,
  54. new LintCommand,
  55. new GenerateCommand,
  56. new DescribeCommand,
  57. new CleanCommand,
  58. new DustmiteCommand
  59. ),
  60. CommandGroup("Package management",
  61. new FetchCommand,
  62. new AddCommand,
  63. new RemoveCommand,
  64. new UpgradeCommand,
  65. new AddPathCommand,
  66. new RemovePathCommand,
  67. new AddLocalCommand,
  68. new RemoveLocalCommand,
  69. new ListCommand,
  70. new SearchCommand,
  71. new AddOverrideCommand,
  72. new RemoveOverrideCommand,
  73. new ListOverridesCommand,
  74. new CleanCachesCommand,
  75. new ConvertCommand,
  76. )
  77. ];
  78. }
  79.  
  80. /** Extract the command name from the argument list
  81.  
  82. Params:
  83. args = a list of string arguments that will be processed
  84.  
  85. Returns:
  86. A structure with two members. `value` is the command name
  87. `remaining` is a list of unprocessed arguments
  88. */
  89. auto extractCommandNameArgument(string[] args)
  90. {
  91. struct Result {
  92. string value;
  93. string[] remaining;
  94. }
  95.  
  96. if (args.length >= 1 && !args[0].startsWith("-") && !args[0].canFind(":")) {
  97. return Result(args[0], args[1 .. $]);
  98. }
  99.  
  100. return Result(null, args);
  101. }
  102.  
  103. /// test extractCommandNameArgument usage
  104. unittest {
  105. /// It returns an empty string on when there are no args
  106. assert(extractCommandNameArgument([]).value == "");
  107. assert(extractCommandNameArgument([]).remaining == []);
  108.  
  109. /// It returns the first argument when it does not start with `-`
  110. assert(extractCommandNameArgument(["test"]).value == "test");
  111.  
  112. /// There is nothing to extract when the arguments only contain the `test` cmd
  113. assert(extractCommandNameArgument(["test"]).remaining == []);
  114.  
  115. /// It extracts two arguments when they are not a command
  116. assert(extractCommandNameArgument(["-a", "-b"]).remaining == ["-a", "-b"]);
  117.  
  118. /// It returns the an empty string when it starts with `-`
  119. assert(extractCommandNameArgument(["-test"]).value == "");
  120.  
  121. // Sub package names are ignored as command names
  122. assert(extractCommandNameArgument(["foo:bar"]).value == "");
  123. assert(extractCommandNameArgument([":foo"]).value == "");
  124. }
  125.  
  126. /** Handles the Command Line options and commands.
  127. */
  128. struct CommandLineHandler
  129. {
  130. /// The list of commands that can be handled
  131. CommandGroup[] commandGroups;
  132.  
  133. /// General options parser
  134. CommonOptions options;
  135.  
  136. /** Create the list of all supported commands
  137.  
  138. Returns:
  139. Returns the list of the supported command names
  140. */
  141. string[] commandNames()
  142. {
  143. return commandGroups.map!(g => g.commands.map!(c => c.name).array).join;
  144. }
  145.  
  146. /** Parses the general options and sets up the log level
  147. and the root_path
  148. */
  149. void prepareOptions(CommandArgs args) {
  150. LogLevel loglevel = LogLevel.info;
  151.  
  152. options.prepare(args);
  153.  
  154. if (options.vverbose) loglevel = LogLevel.debug_;
  155. else if (options.verbose) loglevel = LogLevel.diagnostic;
  156. else if (options.vquiet) loglevel = LogLevel.none;
  157. else if (options.quiet) loglevel = LogLevel.warn;
  158. else if (options.verror) loglevel = LogLevel.error;
  159. setLogLevel(loglevel);
  160.  
  161. if (options.root_path.empty)
  162. {
  163. options.root_path = getcwd();
  164. }
  165. else
  166. {
  167. options.root_path = options.root_path.expandTilde.absolutePath.buildNormalizedPath;
  168. }
  169.  
  170. final switch (options.colors_mode) with (options.colors)
  171. {
  172. case automatic:
  173. // Use default determined in internal.logging.initLogging().
  174. break;
  175. case on:
  176. setLoggingColorsEnabled(true); // enable colors, no matter what
  177. break;
  178. case off:
  179. setLoggingColorsEnabled(false); // disable colors, no matter what
  180. break;
  181. }
  182. }
  183.  
  184. /** Get an instance of the requested command.
  185.  
  186. If there is no command in the argument list, the `run` command is returned
  187. by default.
  188.  
  189. If the `--help` argument previously handled by `prepareOptions`,
  190. `this.options.help` is already `true`, with this returning the requested
  191. command. If no command was requested (just dub --help) this returns the
  192. help command.
  193.  
  194. Params:
  195. name = the command name
  196.  
  197. Returns:
  198. Returns the command instance if it exists, null otherwise
  199. */
  200. Command getCommand(string name) {
  201. if (name == "help" || (name == "" && options.help))
  202. {
  203. return new HelpCommand();
  204. }
  205.  
  206. if (name == "")
  207. {
  208. name = "run";
  209. }
  210.  
  211. foreach (grp; commandGroups)
  212. foreach (c; grp.commands)
  213. if (c.name == name) {
  214. return c;
  215. }
  216.  
  217. return null;
  218. }
  219.  
  220. /** Get an instance of the requested command after the args are sent.
  221.  
  222. It uses getCommand to get the command instance and then calls prepare.
  223.  
  224. Params:
  225. name = the command name
  226. args = the command arguments
  227.  
  228. Returns:
  229. Returns the command instance if it exists, null otherwise
  230. */
  231. Command prepareCommand(string name, CommandArgs args) {
  232. auto cmd = getCommand(name);
  233.  
  234. if (cmd !is null && !(cast(HelpCommand)cmd))
  235. {
  236. // process command line options for the selected command
  237. cmd.prepare(args);
  238. enforceUsage(cmd.acceptsAppArgs || !args.hasAppArgs, name ~ " doesn't accept application arguments.");
  239. }
  240.  
  241. return cmd;
  242. }
  243.  
  244. /** Get a configured dub instance.
  245.  
  246. Returns:
  247. A dub instance
  248. */
  249. Dub prepareDub() {
  250. Dub dub;
  251.  
  252. if (options.bare) {
  253. dub = new Dub(NativePath(getcwd()));
  254. dub.rootPath = NativePath(options.root_path);
  255. dub.defaultPlacementLocation = options.placementLocation;
  256.  
  257. return dub;
  258. }
  259.  
  260. // initialize DUB
  261. auto package_suppliers = options.registry_urls
  262. .map!((url) {
  263. // Allow to specify fallback mirrors as space separated urls. Undocumented as we
  264. // should simply retry over all registries instead of using a special
  265. // FallbackPackageSupplier.
  266. auto urls = url.splitter(' ');
  267. PackageSupplier ps = getRegistryPackageSupplier(urls.front);
  268. urls.popFront;
  269. if (!urls.empty)
  270. ps = new FallbackPackageSupplier(ps ~ urls.map!getRegistryPackageSupplier.array);
  271. return ps;
  272. })
  273. .array;
  274.  
  275. dub = new Dub(options.root_path, package_suppliers, options.skipRegistry);
  276. dub.dryRun = options.annotate;
  277. dub.defaultPlacementLocation = options.placementLocation;
  278.  
  279. // make the CWD package available so that for example sub packages can reference their
  280. // parent package.
  281. try dub.packageManager.getOrLoadPackage(NativePath(options.root_path));
  282. catch (Exception e) { logDiagnostic("No valid package found in current working directory: %s", e.msg); }
  283.  
  284. return dub;
  285. }
  286. }
  287.  
  288. /// Can get the command names
  289. unittest {
  290. CommandLineHandler handler;
  291. handler.commandGroups = getCommands();
  292.  
  293. assert(handler.commandNames == ["init", "run", "build", "test", "lint", "generate",
  294. "describe", "clean", "dustmite", "fetch", "add", "remove",
  295. "upgrade", "add-path", "remove-path", "add-local", "remove-local", "list", "search",
  296. "add-override", "remove-override", "list-overrides", "clean-caches", "convert"]);
  297. }
  298.  
  299. /// It sets the cwd as root_path by default
  300. unittest {
  301. CommandLineHandler handler;
  302.  
  303. auto args = new CommandArgs([]);
  304. handler.prepareOptions(args);
  305. assert(handler.options.root_path == getcwd());
  306. }
  307.  
  308. /// It can set a custom root_path
  309. unittest {
  310. CommandLineHandler handler;
  311.  
  312. auto args = new CommandArgs(["--root=/tmp/test"]);
  313. handler.prepareOptions(args);
  314. assert(handler.options.root_path == "/tmp/test".absolutePath.buildNormalizedPath);
  315.  
  316. args = new CommandArgs(["--root=./test"]);
  317. handler.prepareOptions(args);
  318. assert(handler.options.root_path == "./test".absolutePath.buildNormalizedPath);
  319. }
  320.  
  321. /// It sets the info log level by default
  322. unittest {
  323. scope(exit) setLogLevel(LogLevel.info);
  324. CommandLineHandler handler;
  325.  
  326. auto args = new CommandArgs([]);
  327. handler.prepareOptions(args);
  328. assert(getLogLevel() == LogLevel.info);
  329. }
  330.  
  331. /// It can set a custom error level
  332. unittest {
  333. scope(exit) setLogLevel(LogLevel.info);
  334. CommandLineHandler handler;
  335.  
  336. auto args = new CommandArgs(["--vverbose"]);
  337. handler.prepareOptions(args);
  338. assert(getLogLevel() == LogLevel.debug_);
  339.  
  340. handler = CommandLineHandler();
  341. args = new CommandArgs(["--verbose"]);
  342. handler.prepareOptions(args);
  343. assert(getLogLevel() == LogLevel.diagnostic);
  344.  
  345. handler = CommandLineHandler();
  346. args = new CommandArgs(["--vquiet"]);
  347. handler.prepareOptions(args);
  348. assert(getLogLevel() == LogLevel.none);
  349.  
  350. handler = CommandLineHandler();
  351. args = new CommandArgs(["--quiet"]);
  352. handler.prepareOptions(args);
  353. assert(getLogLevel() == LogLevel.warn);
  354.  
  355. handler = CommandLineHandler();
  356. args = new CommandArgs(["--verror"]);
  357. handler.prepareOptions(args);
  358. assert(getLogLevel() == LogLevel.error);
  359. }
  360.  
  361. /// It returns the `run` command by default
  362. unittest {
  363. CommandLineHandler handler;
  364. handler.commandGroups = getCommands();
  365. assert(handler.getCommand("").name == "run");
  366. }
  367.  
  368. /// It returns the `help` command when there is none set and the --help arg
  369. /// was set
  370. unittest {
  371. CommandLineHandler handler;
  372. auto args = new CommandArgs(["--help"]);
  373. handler.prepareOptions(args);
  374. handler.commandGroups = getCommands();
  375. assert(cast(HelpCommand)handler.getCommand("") !is null);
  376. }
  377.  
  378. /// It returns the `help` command when the `help` command is sent
  379. unittest {
  380. CommandLineHandler handler;
  381. handler.commandGroups = getCommands();
  382. assert(cast(HelpCommand) handler.getCommand("help") !is null);
  383. }
  384.  
  385. /// It returns the `init` command when the `init` command is sent
  386. unittest {
  387. CommandLineHandler handler;
  388. handler.commandGroups = getCommands();
  389. assert(handler.getCommand("init").name == "init");
  390. }
  391.  
  392. /// It returns null when a missing command is sent
  393. unittest {
  394. CommandLineHandler handler;
  395. handler.commandGroups = getCommands();
  396. assert(handler.getCommand("missing") is null);
  397. }
  398.  
  399. /** Processes the given command line and executes the appropriate actions.
  400.  
  401. Params:
  402. args = This command line argument array as received in `main`. The first
  403. entry is considered to be the name of the binary invoked.
  404.  
  405. Returns:
  406. Returns the exit code that is supposed to be returned to the system.
  407. */
  408. int runDubCommandLine(string[] args)
  409. {
  410. static string[] toSinglePackageArgs (string args0, string file, string[] trailing)
  411. {
  412. return [args0, "run", "-q", "--temp-build", "--single", file, "--"] ~ trailing;
  413. }
  414.  
  415. // Initialize the logging module, ensure that whether stdout/stderr are a TTY
  416. // or not is detected in order to disable colors if the output isn't a console
  417. initLogging();
  418.  
  419. logDiagnostic("DUB version %s", getDUBVersion());
  420.  
  421. version(Windows){
  422. // rdmd uses $TEMP to compute a temporary path. since cygwin substitutes backslashes
  423. // with slashes, this causes OPTLINK to fail (it thinks path segments are options)
  424. // we substitute the other way around here to fix this.
  425. environment["TEMP"] = environment["TEMP"].replace("/", "\\");
  426. }
  427.  
  428. auto handler = CommandLineHandler(getCommands());
  429. auto commandNames = handler.commandNames();
  430.  
  431. // Special syntaxes need to be handled before regular argument parsing
  432. if (args.length >= 2)
  433. {
  434. // Read input source code from stdin
  435. if (args[1] == "-")
  436. {
  437. auto path = getTempFile("app", ".d");
  438. stdin.byChunk(4096).joiner.toFile(path.toNativeString());
  439. args = toSinglePackageArgs(args[0], path.toNativeString(), args[2 .. $]);
  440. }
  441.  
  442. // Dub has a shebang syntax to be able to use it as script, e.g.
  443. // #/usr/bin/env dub
  444. // With this approach, we need to support the file having
  445. // both the `.d` extension, or having none at all.
  446. // We also need to make sure arguments passed to the script
  447. // are passed to the program, not `dub`, e.g.:
  448. // ./my_dub_script foo bar
  449. // Gives us `args = [ "dub", "./my_dub_script" "foo", "bar" ]`,
  450. // which we need to interpret as:
  451. // `args = [ "dub", "./my_dub_script", "--", "foo", "bar" ]`
  452. else if (args[1].endsWith(".d"))
  453. args = toSinglePackageArgs(args[0], args[1], args[2 .. $]);
  454.  
  455. // Here we have a problem: What if the script name is a command name ?
  456. // We have to assume it isn't, and to reduce the risk of false positive
  457. // we only consider the case where the file name is the first argument,
  458. // as the shell invocation cannot be controlled.
  459. else if (!commandNames.canFind(args[1]) && !args[1].startsWith("-")) {
  460. if (exists(args[1])) {
  461. auto path = getTempFile("app", ".d");
  462. copy(args[1], path.toNativeString());
  463. args = toSinglePackageArgs(args[0], path.toNativeString(), args[2 .. $]);
  464. } else if (exists(args[1].setExtension(".d"))) {
  465. args = toSinglePackageArgs(args[0], args[1].setExtension(".d"), args[2 .. $]);
  466. }
  467. }
  468. }
  469.  
  470. auto common_args = new CommandArgs(args[1..$]);
  471.  
  472. try handler.prepareOptions(common_args);
  473. catch (Exception e) {
  474. logError("Error processing arguments: %s", e.msg);
  475. logDiagnostic("Full exception: %s", e.toString().sanitize);
  476. logInfo("Run 'dub help' for usage information.");
  477. return 1;
  478. }
  479.  
  480. if (handler.options.version_)
  481. {
  482. showVersion();
  483. return 0;
  484. }
  485.  
  486. // extract the command
  487. args = common_args.extractAllRemainingArgs();
  488.  
  489. auto command_name_argument = extractCommandNameArgument(args);
  490.  
  491. auto command_args = new CommandArgs(command_name_argument.remaining);
  492. Command cmd;
  493.  
  494. try {
  495. cmd = handler.prepareCommand(command_name_argument.value, command_args);
  496. } catch (Exception e) {
  497. logError("Error processing arguments: %s", e.msg);
  498. logDiagnostic("Full exception: %s", e.toString().sanitize);
  499. logInfo("Run 'dub help' for usage information.");
  500. return 1;
  501. }
  502.  
  503. if (cmd is null) {
  504. logError("Unknown command: %s", command_name_argument.value);
  505. writeln();
  506. showHelp(handler.commandGroups, common_args);
  507. return 1;
  508. }
  509.  
  510. if (cast(HelpCommand)cmd !is null) {
  511. showHelp(handler.commandGroups, common_args);
  512. return 0;
  513. }
  514.  
  515. if (handler.options.help) {
  516. showCommandHelp(cmd, command_args, common_args);
  517. return 0;
  518. }
  519.  
  520. auto remaining_args = command_args.extractRemainingArgs();
  521. if (remaining_args.any!(a => a.startsWith("-"))) {
  522. logError("Unknown command line flags: %s", remaining_args.filter!(a => a.startsWith("-")).array.join(" ").color(Mode.bold));
  523. logInfo(`Type "%s" to get a list of all supported flags.`, text("dub ", cmd.name, " -h").color(Mode.bold));
  524. return 1;
  525. }
  526.  
  527. Dub dub;
  528.  
  529. // initialize the root package
  530. if (!cmd.skipDubInitialization) {
  531. dub = handler.prepareDub;
  532. }
  533.  
  534. // execute the command
  535. try return cmd.execute(dub, remaining_args, command_args.appArgs);
  536. catch (UsageException e) {
  537. // usage exceptions get thrown before any logging, so we are
  538. // making the errors more narrow to better fit on small screens.
  539. tagWidth.push(5);
  540. logError("%s", e.msg);
  541. logDebug("Full exception: %s", e.toString().sanitize);
  542. logInfo(`Run "%s" for more information about the "%s" command.`,
  543. text("dub ", cmd.name, " -h").color(Mode.bold), cmd.name.color(Mode.bold));
  544. return 1;
  545. }
  546. catch (Exception e) {
  547. // most exceptions get thrown before logging, so same thing here as
  548. // above. However this might be subject to change if it results in
  549. // weird behavior anywhere.
  550. tagWidth.push(5);
  551. logError("%s", e.msg);
  552. logDebug("Full exception: %s", e.toString().sanitize);
  553. return 2;
  554. }
  555. }
  556.  
  557.  
  558. /** Contains and parses options common to all commands.
  559. */
  560. struct CommonOptions {
  561. bool verbose, vverbose, quiet, vquiet, verror, version_;
  562. bool help, annotate, bare;
  563. string[] registry_urls;
  564. string root_path;
  565. enum colors { automatic, on, off } // Style violation in support of invalid option error formatting.
  566. colors colors_mode = colors.automatic;
  567. SkipPackageSuppliers skipRegistry = SkipPackageSuppliers.none;
  568. PlacementLocation placementLocation = PlacementLocation.user;
  569.  
  570. /// Parses all common options and stores the result in the struct instance.
  571. void prepare(CommandArgs args)
  572. {
  573. args.getopt("h|help", &help, ["Display general or command specific help"]);
  574. args.getopt("root", &root_path, ["Path to operate in instead of the current working dir"]);
  575. args.getopt("registry", &registry_urls, [
  576. "Search the given registry URL first when resolving dependencies. Can be specified multiple times. Available registry types:",
  577. " DUB: URL to DUB registry (default)",
  578. " Maven: URL to Maven repository + group id containing dub packages as artifacts. E.g. mvn+http://localhost:8040/maven/libs-release/dubpackages",
  579. ]);
  580. args.getopt("skip-registry", &skipRegistry, [
  581. "Sets a mode for skipping the search on certain package registry types:",
  582. " none: Search all configured or default registries (default)",
  583. " standard: Don't search the main registry (e.g. "~defaultRegistryURLs[0]~")",
  584. " configured: Skip all default and user configured registries",
  585. " all: Only search registries specified with --registry",
  586. ]);
  587. args.getopt("annotate", &annotate, ["Do not perform any action, just print what would be done"]);
  588. args.getopt("bare", &bare, ["Read only packages contained in the current directory"]);
  589. args.getopt("v|verbose", &verbose, ["Print diagnostic output"]);
  590. args.getopt("vverbose", &vverbose, ["Print debug output"]);
  591. args.getopt("q|quiet", &quiet, ["Only print warnings and errors"]);
  592. args.getopt("verror", &verror, ["Only print errors"]);
  593. args.getopt("vquiet", &vquiet, ["Print no messages"]);
  594. args.getopt("colors", &colors_mode, [
  595. "Configure colored output. Accepted values:",
  596. " automatic: Colored output on console/terminal,",
  597. " unless NO_COLOR is set and non-empty (default)",
  598. " on: Force colors enabled",
  599. " off: Force colors disabled"
  600. ]);
  601. args.getopt("cache", &placementLocation, ["Puts any fetched packages in the specified location [local|system|user]."]);
  602.  
  603. version_ = args.hasAppVersion;
  604. }
  605. }
  606.  
  607. /** Encapsulates a set of application arguments.
  608.  
  609. This class serves two purposes. The first is to provide an API for parsing
  610. command line arguments (`getopt`). At the same time it records all calls
  611. to `getopt` and provides a list of all possible options using the
  612. `recognizedArgs` property.
  613. */
  614. class CommandArgs {
  615. struct Arg {
  616. Variant defaultValue;
  617. Variant value;
  618. string names;
  619. string[] helpText;
  620. bool hidden;
  621. }
  622. private {
  623. string[] m_args;
  624. Arg[] m_recognizedArgs;
  625. string[] m_appArgs;
  626. }
  627.  
  628. /** Initializes the list of source arguments.
  629.  
  630. Note that all array entries are considered application arguments (i.e.
  631. no application name entry is present as the first entry)
  632. */
  633. this(string[] args) @safe pure nothrow
  634. {
  635. auto app_args_idx = args.countUntil("--");
  636.  
  637. m_appArgs = app_args_idx >= 0 ? args[app_args_idx+1 .. $] : [];
  638. m_args = "dummy" ~ (app_args_idx >= 0 ? args[0..app_args_idx] : args);
  639. }
  640.  
  641. /** Checks if the app arguments are present.
  642.  
  643. Returns:
  644. true if an -- argument is given with arguments after it, otherwise false
  645. */
  646. @property bool hasAppArgs() { return m_appArgs.length > 0; }
  647.  
  648.  
  649. /** Checks if the `--version` argument is present on the first position in
  650. the list.
  651.  
  652. Returns:
  653. true if the application version argument was found on the first position
  654. */
  655. @property bool hasAppVersion() { return m_args.length > 1 && m_args[1] == "--version"; }
  656.  
  657. /** Returns the list of app args.
  658.  
  659. The app args are provided after the `--` argument.
  660. */
  661. @property string[] appArgs() { return m_appArgs; }
  662.  
  663. /** Returns the list of all options recognized.
  664.  
  665. This list is created by recording all calls to `getopt`.
  666. */
  667. @property const(Arg)[] recognizedArgs() { return m_recognizedArgs; }
  668.  
  669. void getopt(T)(string names, T* var, string[] help_text = null, bool hidden=false)
  670. {
  671. foreach (ref arg; m_recognizedArgs)
  672. if (names == arg.names) {
  673. assert(help_text is null);
  674. *var = arg.value.get!T;
  675. return;
  676. }
  677. assert(help_text.length > 0);
  678. Arg arg;
  679. arg.defaultValue = *var;
  680. arg.names = names;
  681. arg.helpText = help_text;
  682. arg.hidden = hidden;
  683. m_args.getopt(config.passThrough, names, var);
  684. arg.value = *var;
  685. m_recognizedArgs ~= arg;
  686. }
  687.  
  688. /** Resets the list of available source arguments.
  689. */
  690. void dropAllArgs()
  691. {
  692. m_args = null;
  693. }
  694.  
  695. /** Returns the list of unprocessed arguments, ignoring the app arguments,
  696. and resets the list of available source arguments.
  697. */
  698. string[] extractRemainingArgs()
  699. {
  700. assert(m_args !is null, "extractRemainingArgs must be called only once.");
  701.  
  702. auto ret = m_args[1 .. $];
  703. m_args = null;
  704. return ret;
  705. }
  706.  
  707. /** Returns the list of unprocessed arguments, including the app arguments
  708. and resets the list of available source arguments.
  709. */
  710. string[] extractAllRemainingArgs()
  711. {
  712. auto ret = extractRemainingArgs();
  713.  
  714. if (this.hasAppArgs)
  715. {
  716. ret ~= "--" ~ m_appArgs;
  717. }
  718.  
  719. return ret;
  720. }
  721. }
  722.  
  723. /// Using CommandArgs
  724. unittest {
  725. /// It should not find the app version for an empty arg list
  726. assert(new CommandArgs([]).hasAppVersion == false);
  727.  
  728. /// It should find the app version when `--version` is the first arg
  729. assert(new CommandArgs(["--version"]).hasAppVersion == true);
  730.  
  731. /// It should not find the app version when `--version` is the second arg
  732. assert(new CommandArgs(["a", "--version"]).hasAppVersion == false);
  733.  
  734. /// It returns an empty app arg list when `--` arg is missing
  735. assert(new CommandArgs(["1", "2"]).appArgs == []);
  736.  
  737. /// It returns an empty app arg list when `--` arg is missing
  738. assert(new CommandArgs(["1", "2"]).appArgs == []);
  739.  
  740. /// It returns app args set after "--"
  741. assert(new CommandArgs(["1", "2", "--", "a"]).appArgs == ["a"]);
  742. assert(new CommandArgs(["1", "2", "--"]).appArgs == []);
  743. assert(new CommandArgs(["--"]).appArgs == []);
  744. assert(new CommandArgs(["--", "a"]).appArgs == ["a"]);
  745.  
  746. /// It returns the list of all args when no args are processed
  747. assert(new CommandArgs(["1", "2", "--", "a"]).extractAllRemainingArgs == ["1", "2", "--", "a"]);
  748. }
  749.  
  750. /// It removes the extracted args
  751. unittest {
  752. auto args = new CommandArgs(["-a", "-b", "--", "-c"]);
  753. bool value;
  754. args.getopt("b", &value, [""]);
  755.  
  756. assert(args.extractAllRemainingArgs == ["-a", "--", "-c"]);
  757. }
  758.  
  759. /// It should not be able to remove app args
  760. unittest {
  761. auto args = new CommandArgs(["-a", "-b", "--", "-c"]);
  762. bool value;
  763. args.getopt("-c", &value, [""]);
  764.  
  765. assert(!value);
  766. assert(args.extractAllRemainingArgs == ["-a", "-b", "--", "-c"]);
  767. }
  768.  
  769. /** Base class for all commands.
  770.  
  771. This cass contains a high-level description of the command, including brief
  772. and full descriptions and a human readable command line pattern. On top of
  773. that it defines the two main entry functions for command execution.
  774. */
  775. class Command {
  776. string name;
  777. string argumentsPattern;
  778. string description;
  779. string[] helpText;
  780. bool acceptsAppArgs;
  781. bool hidden = false; // used for deprecated commands
  782. bool skipDubInitialization = false;
  783.  
  784. /** Parses all known command line options without executing any actions.
  785.  
  786. This function will be called prior to execute, or may be called as
  787. the only method when collecting the list of recognized command line
  788. options.
  789.  
  790. Only `args.getopt` should be called within this method.
  791. */
  792. abstract void prepare(scope CommandArgs args);
  793.  
  794. /** Executes the actual action.
  795.  
  796. Note that `prepare` will be called before any call to `execute`.
  797. */
  798. abstract int execute(Dub dub, string[] free_args, string[] app_args);
  799.  
  800. private bool loadCwdPackage(Dub dub, bool warn_missing_package)
  801. {
  802. auto filePath = Package.findPackageFile(dub.rootPath);
  803.  
  804. if (filePath.empty) {
  805. if (warn_missing_package) {
  806. logInfoNoTag("");
  807. logInfoNoTag("No package manifest (dub.json or dub.sdl) was found in");
  808. logInfoNoTag(dub.rootPath.toNativeString());
  809. logInfoNoTag("Please run DUB from the root directory of an existing package, or run");
  810. logInfoNoTag("\"%s\" to get information on creating a new package.", "dub init --help".color(Mode.bold));
  811. logInfoNoTag("");
  812. }
  813. return false;
  814. }
  815.  
  816. dub.loadPackage();
  817.  
  818. return true;
  819. }
  820. }
  821.  
  822.  
  823. /** Encapsulates a group of commands that fit into a common category.
  824. */
  825. struct CommandGroup {
  826. /// Caption of the command category
  827. string caption;
  828.  
  829. /// List of commands contained inthis group
  830. Command[] commands;
  831.  
  832. this(string caption, Command[] commands...) @safe pure nothrow
  833. {
  834. this.caption = caption;
  835. this.commands = commands.dup;
  836. }
  837. }
  838.  
  839. /******************************************************************************/
  840. /* HELP */
  841. /******************************************************************************/
  842.  
  843. class HelpCommand : Command {
  844.  
  845. this() @safe pure nothrow
  846. {
  847. this.name = "help";
  848. this.description = "Shows the help message";
  849. this.helpText = [
  850. "Shows the help message and the supported command options."
  851. ];
  852. }
  853.  
  854. /// HelpCommand.prepare is not supposed to be called, use
  855. /// cast(HelpCommand)this to check if help was requested before execution.
  856. override void prepare(scope CommandArgs args)
  857. {
  858. assert(false, "HelpCommand.prepare is not supposed to be called, use cast(HelpCommand)this to check if help was requested before execution.");
  859. }
  860.  
  861. /// HelpCommand.execute is not supposed to be called, use
  862. /// cast(HelpCommand)this to check if help was requested before execution.
  863. override int execute(Dub dub, string[] free_args, string[] app_args) {
  864. assert(false, "HelpCommand.execute is not supposed to be called, use cast(HelpCommand)this to check if help was requested before execution.");
  865. }
  866. }
  867.  
  868. /******************************************************************************/
  869. /* INIT */
  870. /******************************************************************************/
  871.  
  872. class InitCommand : Command {
  873. private{
  874. string m_templateType = "minimal";
  875. PackageFormat m_format = PackageFormat.json;
  876. bool m_nonInteractive;
  877. }
  878. this() @safe pure nothrow
  879. {
  880. this.name = "init";
  881. this.argumentsPattern = "[<directory> [<dependency>...]]";
  882. this.description = "Initializes an empty package skeleton";
  883. this.helpText = [
  884. "Initializes an empty package of the specified type in the given directory. By default, the current working directory is used."
  885. ];
  886. this.acceptsAppArgs = true;
  887. }
  888.  
  889. override void prepare(scope CommandArgs args)
  890. {
  891. args.getopt("t|type", &m_templateType, [
  892. "Set the type of project to generate. Available types:",
  893. "",
  894. "minimal - simple \"hello world\" project (default)",
  895. "vibe.d - minimal HTTP server based on vibe.d",
  896. "deimos - skeleton for C header bindings",
  897. "custom - custom project provided by dub package",
  898. ]);
  899. args.getopt("f|format", &m_format, [
  900. "Sets the format to use for the package description file. Possible values:",
  901. " " ~ [__traits(allMembers, PackageFormat)].map!(f => f == m_format.init.to!string ? f ~ " (default)" : f).join(", ")
  902. ]);
  903. args.getopt("n|non-interactive", &m_nonInteractive, ["Don't enter interactive mode."]);
  904. }
  905.  
  906. override int execute(Dub dub, string[] free_args, string[] app_args)
  907. {
  908. string dir;
  909. if (free_args.length)
  910. {
  911. dir = free_args[0];
  912. free_args = free_args[1 .. $];
  913. }
  914.  
  915. static string input(string caption, string default_value)
  916. {
  917. writef("%s [%s]: ", caption, default_value);
  918. stdout.flush();
  919. auto inp = readln();
  920. return inp.length > 1 ? inp[0 .. $-1] : default_value;
  921. }
  922.  
  923. void depCallback(ref PackageRecipe p, ref PackageFormat fmt) {
  924. import std.datetime: Clock;
  925.  
  926. if (m_nonInteractive) return;
  927.  
  928. while (true) {
  929. string rawfmt = input("Package recipe format (sdl/json)", fmt.to!string);
  930. if (!rawfmt.length) break;
  931. try {
  932. fmt = rawfmt.to!PackageFormat;
  933. break;
  934. } catch (Exception) {
  935. logError(`Invalid format '%s', enter either 'sdl' or 'json'.`, rawfmt);
  936. }
  937. }
  938. auto author = p.authors.join(", ");
  939. while (true) {
  940. // Tries getting the name until a valid one is given.
  941. import std.regex;
  942. auto nameRegex = regex(`^[a-z0-9\-_]+$`);
  943. string triedName = input("Name", p.name);
  944. if (triedName.matchFirst(nameRegex).empty) {
  945. logError(`Invalid name '%s', names should consist only of lowercase alphanumeric characters, dashes ('-') and underscores ('_').`, triedName);
  946. } else {
  947. p.name = triedName;
  948. break;
  949. }
  950. }
  951. p.description = input("Description", p.description);
  952. p.authors = input("Author name", author).split(",").map!(a => a.strip).array;
  953. p.license = input("License", p.license);
  954. string copyrightString = .format("Copyright © %s, %-(%s, %)", Clock.currTime().year, p.authors);
  955. p.copyright = input("Copyright string", copyrightString);
  956.  
  957. while (true) {
  958. auto depspec = input("Add dependency (leave empty to skip)", null);
  959. if (!depspec.length) break;
  960. addDependency(dub, p, depspec);
  961. }
  962. }
  963.  
  964. if (!["vibe.d", "deimos", "minimal"].canFind(m_templateType))
  965. {
  966. free_args ~= m_templateType;
  967. }
  968. dub.createEmptyPackage(NativePath(dir), free_args, m_templateType, m_format, &depCallback, app_args);
  969.  
  970. logInfo("Package successfully created in %s", dir.length ? dir : ".");
  971. return 0;
  972. }
  973. }
  974.  
  975.  
  976. /******************************************************************************/
  977. /* GENERATE / BUILD / RUN / TEST / DESCRIBE */
  978. /******************************************************************************/
  979.  
  980. abstract class PackageBuildCommand : Command {
  981. protected {
  982. string m_compilerName;
  983. string m_arch;
  984. string[] m_debugVersions;
  985. string[] m_overrideConfigs;
  986. GeneratorSettings baseSettings;
  987. string m_defaultConfig;
  988. bool m_nodeps;
  989. bool m_forceRemove = false;
  990. }
  991.  
  992. override void prepare(scope CommandArgs args)
  993. {
  994. args.getopt("b|build", &this.baseSettings.buildType, [
  995. "Specifies the type of build to perform. Note that setting the DFLAGS environment variable will override the build type with custom flags.",
  996. "Possible names:",
  997. " "~builtinBuildTypes.join(", ")~" and custom types"
  998. ]);
  999. args.getopt("c|config", &this.baseSettings.config, [
  1000. "Builds the specified configuration. Configurations can be defined in dub.json"
  1001. ]);
  1002. args.getopt("override-config", &m_overrideConfigs, [
  1003. "Uses the specified configuration for a certain dependency. Can be specified multiple times.",
  1004. "Format: --override-config=<dependency>/<config>"
  1005. ]);
  1006. args.getopt("compiler", &m_compilerName, [
  1007. "Specifies the compiler binary to use (can be a path).",
  1008. "Arbitrary pre- and suffixes to the identifiers below are recognized (e.g. ldc2 or dmd-2.063) and matched to the proper compiler type:",
  1009. " "~["dmd", "gdc", "ldc", "gdmd", "ldmd"].join(", ")
  1010. ]);
  1011. args.getopt("a|arch", &m_arch, [
  1012. "Force a different architecture (e.g. x86 or x86_64)"
  1013. ]);
  1014. args.getopt("d|debug", &m_debugVersions, [
  1015. "Define the specified debug version identifier when building - can be used multiple times"
  1016. ]);
  1017. args.getopt("nodeps", &m_nodeps, [
  1018. "Do not resolve missing dependencies before building"
  1019. ]);
  1020. args.getopt("build-mode", &this.baseSettings.buildMode, [
  1021. "Specifies the way the compiler and linker are invoked. Valid values:",
  1022. " separate (default), allAtOnce, singleFile"
  1023. ]);
  1024. args.getopt("single", &this.baseSettings.single, [
  1025. "Treats the package name as a filename. The file must contain a package recipe comment."
  1026. ]);
  1027. args.getopt("force-remove", &m_forceRemove, [
  1028. "Deprecated option that does nothing."
  1029. ]);
  1030. args.getopt("filter-versions", &this.baseSettings.filterVersions, [
  1031. "[Experimental] Filter version identifiers and debug version identifiers to improve build cache efficiency."
  1032. ]);
  1033. }
  1034.  
  1035. protected void setupVersionPackage(Dub dub, string str_package_info, string default_build_type = "debug")
  1036. {
  1037. PackageAndVersion package_info = splitPackageName(str_package_info);
  1038. setupPackage(dub, package_info.name, default_build_type, package_info.version_);
  1039. }
  1040.  
  1041. protected void setupPackage(Dub dub, string package_name, string default_build_type = "debug", string ver = "")
  1042. {
  1043. if (!m_compilerName.length) m_compilerName = dub.defaultCompiler;
  1044. if (!m_arch.length) m_arch = dub.defaultArchitecture;
  1045. if (dub.defaultLowMemory) this.baseSettings.buildSettings.options |= BuildOption.lowmem;
  1046. if (dub.defaultEnvironments) this.baseSettings.buildSettings.addEnvironments(dub.defaultEnvironments);
  1047. if (dub.defaultBuildEnvironments) this.baseSettings.buildSettings.addBuildEnvironments(dub.defaultBuildEnvironments);
  1048. if (dub.defaultRunEnvironments) this.baseSettings.buildSettings.addRunEnvironments(dub.defaultRunEnvironments);
  1049. if (dub.defaultPreGenerateEnvironments) this.baseSettings.buildSettings.addPreGenerateEnvironments(dub.defaultPreGenerateEnvironments);
  1050. if (dub.defaultPostGenerateEnvironments) this.baseSettings.buildSettings.addPostGenerateEnvironments(dub.defaultPostGenerateEnvironments);
  1051. if (dub.defaultPreBuildEnvironments) this.baseSettings.buildSettings.addPreBuildEnvironments(dub.defaultPreBuildEnvironments);
  1052. if (dub.defaultPostBuildEnvironments) this.baseSettings.buildSettings.addPostBuildEnvironments(dub.defaultPostBuildEnvironments);
  1053. if (dub.defaultPreRunEnvironments) this.baseSettings.buildSettings.addPreRunEnvironments(dub.defaultPreRunEnvironments);
  1054. if (dub.defaultPostRunEnvironments) this.baseSettings.buildSettings.addPostRunEnvironments(dub.defaultPostRunEnvironments);
  1055. this.baseSettings.compiler = getCompiler(m_compilerName);
  1056. this.baseSettings.platform = this.baseSettings.compiler.determinePlatform(this.baseSettings.buildSettings, m_compilerName, m_arch);
  1057. this.baseSettings.buildSettings.addDebugVersions(m_debugVersions);
  1058.  
  1059. m_defaultConfig = null;
  1060. enforce (loadSpecificPackage(dub, package_name, ver), "Failed to load package.");
  1061.  
  1062. if (this.baseSettings.config.length != 0 &&
  1063. !dub.configurations.canFind(this.baseSettings.config) &&
  1064. this.baseSettings.config != "unittest")
  1065. {
  1066. string msg = "Unknown build configuration: " ~ this.baseSettings.config;
  1067. enum distance = 3;
  1068. auto match = dub.configurations.getClosestMatch(this.baseSettings.config, distance);
  1069. if (match !is null) msg ~= ". Did you mean '" ~ match ~ "'?";
  1070. enforce(0, msg);
  1071. }
  1072.  
  1073. if (this.baseSettings.buildType.length == 0) {
  1074. if (environment.get("DFLAGS") !is null) this.baseSettings.buildType = "$DFLAGS";
  1075. else this.baseSettings.buildType = default_build_type;
  1076. }
  1077.  
  1078. if (!m_nodeps) {
  1079. // retrieve missing packages
  1080. if (!dub.project.hasAllDependencies) {
  1081. logDiagnostic("Checking for missing dependencies.");
  1082. if (this.baseSettings.single)
  1083. dub.upgrade(UpgradeOptions.select | UpgradeOptions.noSaveSelections);
  1084. else dub.upgrade(UpgradeOptions.select);
  1085. }
  1086. }
  1087.  
  1088. dub.project.validate();
  1089.  
  1090. foreach (sc; m_overrideConfigs) {
  1091. auto idx = sc.indexOf('/');
  1092. enforceUsage(idx >= 0, "Expected \"<package>/<configuration>\" as argument to --override-config.");
  1093. dub.project.overrideConfiguration(sc[0 .. idx], sc[idx+1 .. $]);
  1094. }
  1095. }
  1096.  
  1097. private bool loadSpecificPackage(Dub dub, string package_name, string ver)
  1098. {
  1099. if (this.baseSettings.single) {
  1100. enforce(package_name.length, "Missing file name of single-file package.");
  1101. dub.loadSingleFilePackage(package_name);
  1102. return true;
  1103. }
  1104.  
  1105. bool from_cwd = package_name.length == 0 || package_name.startsWith(":");
  1106. // load package in root_path to enable searching for sub packages
  1107. if (loadCwdPackage(dub, from_cwd)) {
  1108. if (package_name.startsWith(":"))
  1109. {
  1110. auto pack = dub.packageManager.getSubPackage(dub.project.rootPackage, package_name[1 .. $], false);
  1111. dub.loadPackage(pack);
  1112. return true;
  1113. }
  1114. if (from_cwd) return true;
  1115. }
  1116.  
  1117. enforce(package_name.length, "No valid root package found - aborting.");
  1118.  
  1119. auto pack = dub.packageManager.getBestPackage(
  1120. package_name, ver.length ? Dependency(ver) : Dependency.any);
  1121.  
  1122. enforce(pack, format!"Failed to find a package named '%s%s' locally."(package_name,
  1123. ver == "" ? "" : ("@" ~ ver)
  1124. ));
  1125. logInfo("Building package %s in %s", pack.name, pack.path.toNativeString());
  1126. dub.loadPackage(pack);
  1127. return true;
  1128. }
  1129. }
  1130.  
  1131. class GenerateCommand : PackageBuildCommand {
  1132. protected {
  1133. string m_generator;
  1134. bool m_printPlatform, m_printBuilds, m_printConfigs;
  1135. }
  1136.  
  1137. this() @safe pure nothrow
  1138. {
  1139. this.name = "generate";
  1140. this.argumentsPattern = "<generator> [<package>[@<version-spec>]]";
  1141. this.description = "Generates project files using the specified generator";
  1142. this.helpText = [
  1143. "Generates project files using one of the supported generators:",
  1144. "",
  1145. "visuald - VisualD project files",
  1146. "sublimetext - SublimeText project file",
  1147. "cmake - CMake build scripts",
  1148. "build - Builds the package directly",
  1149. "",
  1150. "An optional package name can be given to generate a different package than the root/CWD package."
  1151. ];
  1152. }
  1153.  
  1154. override void prepare(scope CommandArgs args)
  1155. {
  1156. super.prepare(args);
  1157.  
  1158. args.getopt("combined", &this.baseSettings.combined, [
  1159. "Tries to build the whole project in a single compiler run."
  1160. ]);
  1161.  
  1162. args.getopt("print-builds", &m_printBuilds, [
  1163. "Prints the list of available build types"
  1164. ]);
  1165. args.getopt("print-configs", &m_printConfigs, [
  1166. "Prints the list of available configurations"
  1167. ]);
  1168. args.getopt("print-platform", &m_printPlatform, [
  1169. "Prints the identifiers for the current build platform as used for the build fields in dub.json"
  1170. ]);
  1171. args.getopt("parallel", &this.baseSettings.parallelBuild, [
  1172. "Runs multiple compiler instances in parallel, if possible."
  1173. ]);
  1174. }
  1175.  
  1176. override int execute(Dub dub, string[] free_args, string[] app_args)
  1177. {
  1178. string str_package_info;
  1179. if (!m_generator.length) {
  1180. enforceUsage(free_args.length >= 1 && free_args.length <= 2, "Expected one or two arguments.");
  1181. m_generator = free_args[0];
  1182. if (free_args.length >= 2) str_package_info = free_args[1];
  1183. } else {
  1184. enforceUsage(free_args.length <= 1, "Expected one or zero arguments.");
  1185. if (free_args.length >= 1) str_package_info = free_args[0];
  1186. }
  1187.  
  1188. setupVersionPackage(dub, str_package_info, "debug");
  1189.  
  1190. if (m_printBuilds) {
  1191. logInfo("Available build types:");
  1192. foreach (i, tp; dub.project.builds)
  1193. logInfo(" %s%s", tp, i == 0 ? " [default]" : null);
  1194. logInfo("");
  1195. }
  1196.  
  1197. m_defaultConfig = dub.project.getDefaultConfiguration(this.baseSettings.platform);
  1198. if (m_printConfigs) {
  1199. logInfo("Available configurations:");
  1200. foreach (tp; dub.configurations)
  1201. logInfo(" %s%s", tp, tp == m_defaultConfig ? " [default]" : null);
  1202. logInfo("");
  1203. }
  1204.  
  1205. GeneratorSettings gensettings = this.baseSettings;
  1206. if (!gensettings.config.length)
  1207. gensettings.config = m_defaultConfig;
  1208. gensettings.runArgs = app_args;
  1209.  
  1210. logDiagnostic("Generating using %s", m_generator);
  1211. dub.generateProject(m_generator, gensettings);
  1212. if (this.baseSettings.buildType == "ddox") dub.runDdox(gensettings.run, app_args);
  1213. return 0;
  1214. }
  1215. }
  1216.  
  1217. class BuildCommand : GenerateCommand {
  1218. protected {
  1219. bool m_yes; // automatic yes to prompts;
  1220. bool m_nonInteractive;
  1221. }
  1222. this() @safe pure nothrow
  1223. {
  1224. this.name = "build";
  1225. this.argumentsPattern = "[<package>[@<version-spec>]]";
  1226. this.description = "Builds a package (uses the main package in the current working directory by default)";
  1227. this.helpText = [
  1228. "Builds a package (uses the main package in the current working directory by default)"
  1229. ];
  1230. }
  1231.  
  1232. override void prepare(scope CommandArgs args)
  1233. {
  1234. args.getopt("rdmd", &this.baseSettings.rdmd, [
  1235. "Use rdmd instead of directly invoking the compiler"
  1236. ]);
  1237.  
  1238. args.getopt("f|force", &this.baseSettings.force, [
  1239. "Forces a recompilation even if the target is up to date"
  1240. ]);
  1241. args.getopt("y|yes", &m_yes, [
  1242. `Automatic yes to prompts. Assume "yes" as answer to all interactive prompts.`
  1243. ]);
  1244. args.getopt("n|non-interactive", &m_nonInteractive, [
  1245. "Don't enter interactive mode."
  1246. ]);
  1247. super.prepare(args);
  1248. m_generator = "build";
  1249. }
  1250.  
  1251. override int execute(Dub dub, string[] free_args, string[] app_args)
  1252. {
  1253. // single package files don't need to be downloaded, they are on the disk.
  1254. if (free_args.length < 1 || this.baseSettings.single)
  1255. return super.execute(dub, free_args, app_args);
  1256.  
  1257. if (!m_nonInteractive)
  1258. {
  1259. const packageParts = splitPackageName(free_args[0]);
  1260. if (auto rc = fetchMissingPackages(dub, packageParts))
  1261. return rc;
  1262. }
  1263. return super.execute(dub, free_args, app_args);
  1264. }
  1265.  
  1266. private int fetchMissingPackages(Dub dub, in PackageAndVersion packageParts)
  1267. {
  1268.  
  1269. static bool input(string caption, bool default_value = true) {
  1270. writef("%s [%s]: ", caption, default_value ? "Y/n" : "y/N");
  1271. auto inp = readln();
  1272. string userInput = "y";
  1273. if (inp.length > 1)
  1274. userInput = inp[0 .. $ - 1].toLower;
  1275.  
  1276. switch (userInput) {
  1277. case "no", "n", "0":
  1278. return false;
  1279. case "yes", "y", "1":
  1280. default:
  1281. return true;
  1282. }
  1283. }
  1284.  
  1285. VersionRange dep;
  1286.  
  1287. if (packageParts.version_.length > 0) {
  1288. // the user provided a version manually
  1289. dep = VersionRange.fromString(packageParts.version_);
  1290. } else if (packageParts.name.startsWith(":")) {
  1291. // Subpackages are always assumed to be present
  1292. return 0;
  1293. } else if (dub.packageManager.getFirstPackage(packageParts.name)) {
  1294. // found locally
  1295. return 0;
  1296. } else {
  1297. // search for the package and filter versions for exact matches
  1298. auto basePackageName = getBasePackageName(packageParts.name);
  1299. auto search = dub.searchPackages(basePackageName)
  1300. .map!(tup => tup[1].find!(p => p.name == basePackageName))
  1301. .filter!(ps => !ps.empty);
  1302. if (search.empty) {
  1303. logWarn("Package '%s' was neither found locally nor online.", packageParts.name);
  1304. return 2;
  1305. }
  1306.  
  1307. const p = search.front.front;
  1308. logInfo("Package '%s' was not found locally but is available online:", packageParts.name);
  1309. logInfo("---");
  1310. logInfo("Description: %s", p.description);
  1311. logInfo("Version: %s", p.version_);
  1312. logInfo("---");
  1313.  
  1314. const answer = m_yes ? true : input("Do you want to fetch '%s' now?".format(packageParts.name));
  1315. if (!answer)
  1316. return 0;
  1317. dep = VersionRange.fromString(p.version_);
  1318. }
  1319.  
  1320. dub.fetch(packageParts.name, dep, dub.defaultPlacementLocation, FetchOptions.none);
  1321. return 0;
  1322. }
  1323. }
  1324.  
  1325. class RunCommand : BuildCommand {
  1326. this() @safe pure nothrow
  1327. {
  1328. this.name = "run";
  1329. this.argumentsPattern = "[<package>[@<version-spec>]]";
  1330. this.description = "Builds and runs a package (default command)";
  1331. this.helpText = [
  1332. "Builds and runs a package (uses the main package in the current working directory by default)"
  1333. ];
  1334. this.acceptsAppArgs = true;
  1335. }
  1336.  
  1337. override void prepare(scope CommandArgs args)
  1338. {
  1339. args.getopt("temp-build", &this.baseSettings.tempBuild, [
  1340. "Builds the project in the temp folder if possible."
  1341. ]);
  1342.  
  1343. super.prepare(args);
  1344. this.baseSettings.run = true;
  1345. }
  1346.  
  1347. override int execute(Dub dub, string[] free_args, string[] app_args)
  1348. {
  1349. return super.execute(dub, free_args, app_args);
  1350. }
  1351. }
  1352.  
  1353. class TestCommand : PackageBuildCommand {
  1354. private {
  1355. string m_mainFile;
  1356. }
  1357.  
  1358. this() @safe pure nothrow
  1359. {
  1360. this.name = "test";
  1361. this.argumentsPattern = "[<package>[@<version-spec>]]";
  1362. this.description = "Executes the tests of the selected package";
  1363. this.helpText = [
  1364. `Builds the package and executes all contained unit tests.`,
  1365. ``,
  1366. `If no explicit configuration is given, an existing "unittest" ` ~
  1367. `configuration will be preferred for testing. If none exists, the ` ~
  1368. `first library type configuration will be used, and if that doesn't ` ~
  1369. `exist either, the first executable configuration is chosen.`,
  1370. ``,
  1371. `When a custom main file (--main-file) is specified, only library ` ~
  1372. `configurations can be used. Otherwise, depending on the type of ` ~
  1373. `the selected configuration, either an existing main file will be ` ~
  1374. `used (and needs to be properly adjusted to just run the unit ` ~
  1375. `tests for 'version(unittest)'), or DUB will generate one for ` ~
  1376. `library type configurations.`,
  1377. ``,
  1378. `Finally, if the package contains a dependency to the "tested" ` ~
  1379. `package, the automatically generated main file will use it to ` ~
  1380. `run the unit tests.`
  1381. ];
  1382. this.acceptsAppArgs = true;
  1383. }
  1384.  
  1385. override void prepare(scope CommandArgs args)
  1386. {
  1387. args.getopt("main-file", &m_mainFile, [
  1388. "Specifies a custom file containing the main() function to use for running the tests."
  1389. ]);
  1390. args.getopt("combined", &this.baseSettings.combined, [
  1391. "Tries to build the whole project in a single compiler run."
  1392. ]);
  1393. args.getopt("parallel", &this.baseSettings.parallelBuild, [
  1394. "Runs multiple compiler instances in parallel, if possible."
  1395. ]);
  1396. args.getopt("f|force", &this.baseSettings.force, [
  1397. "Forces a recompilation even if the target is up to date"
  1398. ]);
  1399.  
  1400. bool coverage = false;
  1401. args.getopt("coverage", &coverage, [
  1402. "Enables code coverage statistics to be generated."
  1403. ]);
  1404. if (coverage) this.baseSettings.buildType = "unittest-cov";
  1405.  
  1406. bool coverageCTFE = false;
  1407. args.getopt("coverage-ctfe", &coverageCTFE, [
  1408. "Enables code coverage (including CTFE) statistics to be generated."
  1409. ]);
  1410. if (coverageCTFE) this.baseSettings.buildType = "unittest-cov-ctfe";
  1411.  
  1412. super.prepare(args);
  1413. }
  1414.  
  1415. override int execute(Dub dub, string[] free_args, string[] app_args)
  1416. {
  1417. string str_package_info;
  1418. enforceUsage(free_args.length <= 1, "Expected one or zero arguments.");
  1419. if (free_args.length >= 1) str_package_info = free_args[0];
  1420.  
  1421. setupVersionPackage(dub, str_package_info, "unittest");
  1422.  
  1423. GeneratorSettings settings = this.baseSettings;
  1424. settings.compiler = getCompiler(this.baseSettings.platform.compilerBinary);
  1425. settings.run = true;
  1426. settings.runArgs = app_args;
  1427.  
  1428. dub.testProject(settings, this.baseSettings.config, NativePath(m_mainFile));
  1429. return 0;
  1430. }
  1431. }
  1432.  
  1433. class LintCommand : PackageBuildCommand {
  1434. private {
  1435. bool m_syntaxCheck = false;
  1436. bool m_styleCheck = false;
  1437. string m_errorFormat;
  1438. bool m_report = false;
  1439. string m_reportFormat;
  1440. string m_reportFile;
  1441. string[] m_importPaths;
  1442. string m_config;
  1443. }
  1444.  
  1445. this() @safe pure nothrow
  1446. {
  1447. this.name = "lint";
  1448. this.argumentsPattern = "[<package>[@<version-spec>]]";
  1449. this.description = "Executes the linter tests of the selected package";
  1450. this.helpText = [
  1451. `Builds the package and executes D-Scanner linter tests.`
  1452. ];
  1453. this.acceptsAppArgs = true;
  1454. }
  1455.  
  1456. override void prepare(scope CommandArgs args)
  1457. {
  1458. args.getopt("syntax-check", &m_syntaxCheck, [
  1459. "Lexes and parses sourceFile, printing the line and column number of " ~
  1460. "any syntax errors to stdout."
  1461. ]);
  1462.  
  1463. args.getopt("style-check", &m_styleCheck, [
  1464. "Lexes and parses sourceFiles, printing the line and column number of " ~
  1465. "any static analysis check failures stdout."
  1466. ]);
  1467.  
  1468. args.getopt("error-format", &m_errorFormat, [
  1469. "Format errors produced by the style/syntax checkers."
  1470. ]);
  1471.  
  1472. args.getopt("report", &m_report, [
  1473. "Generate a static analysis report in JSON format."
  1474. ]);
  1475.  
  1476. args.getopt("report-format", &m_reportFormat, [
  1477. "Specifies the format of the generated report."
  1478. ]);
  1479.  
  1480. args.getopt("report-file", &m_reportFile, [
  1481. "Write report to file."
  1482. ]);
  1483.  
  1484. if (m_reportFormat || m_reportFile) m_report = true;
  1485.  
  1486. args.getopt("import-paths", &m_importPaths, [
  1487. "Import paths"
  1488. ]);
  1489.  
  1490. args.getopt("config", &m_config, [
  1491. "Use the given configuration file."
  1492. ]);
  1493.  
  1494. super.prepare(args);
  1495. }
  1496.  
  1497. override int execute(Dub dub, string[] free_args, string[] app_args)
  1498. {
  1499. string str_package_info;
  1500. enforceUsage(free_args.length <= 1, "Expected one or zero arguments.");
  1501. if (free_args.length >= 1) str_package_info = free_args[0];
  1502.  
  1503. string[] args;
  1504. if (!m_syntaxCheck && !m_styleCheck && !m_report && app_args.length == 0) { m_styleCheck = true; }
  1505.  
  1506. if (m_syntaxCheck) args ~= "--syntaxCheck";
  1507. if (m_styleCheck) args ~= "--styleCheck";
  1508. if (m_errorFormat) args ~= ["--errorFormat", m_errorFormat];
  1509. if (m_report) args ~= "--report";
  1510. if (m_reportFormat) args ~= ["--reportFormat", m_reportFormat];
  1511. if (m_reportFile) args ~= ["--reportFile", m_reportFile];
  1512. foreach (import_path; m_importPaths) args ~= ["-I", import_path];
  1513. if (m_config) args ~= ["--config", m_config];
  1514.  
  1515. setupVersionPackage(dub, str_package_info);
  1516. dub.lintProject(args ~ app_args);
  1517. return 0;
  1518. }
  1519. }
  1520.  
  1521. class DescribeCommand : PackageBuildCommand {
  1522. private {
  1523. bool m_importPaths = false;
  1524. bool m_stringImportPaths = false;
  1525. bool m_dataList = false;
  1526. bool m_dataNullDelim = false;
  1527. string[] m_data;
  1528. }
  1529.  
  1530. this() @safe pure nothrow
  1531. {
  1532. this.name = "describe";
  1533. this.argumentsPattern = "[<package>[@<version-spec>]]";
  1534. this.description = "Prints a JSON description of the project and its dependencies";
  1535. this.helpText = [
  1536. "Prints a JSON build description for the root package an all of " ~
  1537. "their dependencies in a format similar to a JSON package " ~
  1538. "description file. This is useful mostly for IDEs.",
  1539. "",
  1540. "All usual options that are also used for build/run/generate apply.",
  1541. "",
  1542. "When --data=VALUE is supplied, specific build settings for a project " ~
  1543. "will be printed instead (by default, formatted for the current compiler).",
  1544. "",
  1545. "The --data=VALUE option can be specified multiple times to retrieve " ~
  1546. "several pieces of information at once. A comma-separated list is " ~
  1547. "also acceptable (ex: --data=dflags,libs). The data will be output in " ~
  1548. "the same order requested on the command line.",
  1549. "",
  1550. "The accepted values for --data=VALUE are:",
  1551. "",
  1552. "main-source-file, dflags, lflags, libs, linker-files, " ~
  1553. "source-files, versions, debug-versions, import-paths, " ~
  1554. "string-import-paths, import-files, options",
  1555. "",
  1556. "The following are also accepted by --data if --data-list is used:",
  1557. "",
  1558. "target-type, target-path, target-name, working-directory, " ~
  1559. "copy-files, string-import-files, pre-generate-commands, " ~
  1560. "post-generate-commands, pre-build-commands, post-build-commands, " ~
  1561. "pre-run-commands, post-run-commands, requirements",
  1562. ];
  1563. }
  1564.  
  1565. override void prepare(scope CommandArgs args)
  1566. {
  1567. super.prepare(args);
  1568.  
  1569. args.getopt("import-paths", &m_importPaths, [
  1570. "Shortcut for --data=import-paths --data-list"
  1571. ]);
  1572.  
  1573. args.getopt("string-import-paths", &m_stringImportPaths, [
  1574. "Shortcut for --data=string-import-paths --data-list"
  1575. ]);
  1576.  
  1577. args.getopt("data", &m_data, [
  1578. "Just list the values of a particular build setting, either for this "~
  1579. "package alone or recursively including all dependencies. Accepts a "~
  1580. "comma-separated list. See above for more details and accepted "~
  1581. "possibilities for VALUE."
  1582. ]);
  1583.  
  1584. args.getopt("data-list", &m_dataList, [
  1585. "Output --data information in list format (line-by-line), instead "~
  1586. "of formatting for a compiler command line.",
  1587. ]);
  1588.  
  1589. args.getopt("data-0", &m_dataNullDelim, [
  1590. "Output --data information using null-delimiters, rather than "~
  1591. "spaces or newlines. Result is usable with, ex., xargs -0.",
  1592. ]);
  1593. }
  1594.  
  1595. override int execute(Dub dub, string[] free_args, string[] app_args)
  1596. {
  1597. enforceUsage(
  1598. !(m_importPaths && m_stringImportPaths),
  1599. "--import-paths and --string-import-paths may not be used together."
  1600. );
  1601.  
  1602. enforceUsage(
  1603. !(m_data && (m_importPaths || m_stringImportPaths)),
  1604. "--data may not be used together with --import-paths or --string-import-paths."
  1605. );
  1606.  
  1607. // disable all log output to stdout and use "writeln" to output the JSON description
  1608. auto ll = getLogLevel();
  1609. setLogLevel(max(ll, LogLevel.warn));
  1610. scope (exit) setLogLevel(ll);
  1611.  
  1612. string str_package_info;
  1613. enforceUsage(free_args.length <= 1, "Expected one or zero arguments.");
  1614. if (free_args.length >= 1) str_package_info = free_args[0];
  1615. setupVersionPackage(dub, str_package_info);
  1616.  
  1617. m_defaultConfig = dub.project.getDefaultConfiguration(this.baseSettings.platform);
  1618.  
  1619. GeneratorSettings settings = this.baseSettings;
  1620. if (!settings.config.length)
  1621. settings.config = m_defaultConfig;
  1622. // Ignore other options
  1623. settings.buildSettings.options = this.baseSettings.buildSettings.options & BuildOption.lowmem;
  1624.  
  1625. // With a requested `unittest` config, switch to the special test runner
  1626. // config (which doesn't require an existing `unittest` configuration).
  1627. if (this.baseSettings.config == "unittest") {
  1628. const test_config = dub.project.addTestRunnerConfiguration(settings, !dub.dryRun);
  1629. if (test_config) settings.config = test_config;
  1630. }
  1631.  
  1632. if (m_importPaths) { m_data = ["import-paths"]; m_dataList = true; }
  1633. else if (m_stringImportPaths) { m_data = ["string-import-paths"]; m_dataList = true; }
  1634.  
  1635. if (m_data.length) {
  1636. ListBuildSettingsFormat lt;
  1637. with (ListBuildSettingsFormat)
  1638. lt = m_dataList ? (m_dataNullDelim ? listNul : list) : (m_dataNullDelim ? commandLineNul : commandLine);
  1639. dub.listProjectData(settings, m_data, lt);
  1640. } else {
  1641. auto desc = dub.project.describe(settings);
  1642. writeln(desc.serializeToPrettyJson());
  1643. }
  1644.  
  1645. return 0;
  1646. }
  1647. }
  1648.  
  1649. class CleanCommand : Command {
  1650. private {
  1651. bool m_allPackages;
  1652. }
  1653.  
  1654. this() @safe pure nothrow
  1655. {
  1656. this.name = "clean";
  1657. this.argumentsPattern = "[<package>]";
  1658. this.description = "Removes intermediate build files and cached build results";
  1659. this.helpText = [
  1660. "This command removes any cached build files of the given package(s). The final target file, as well as any copyFiles are currently not removed.",
  1661. "Without arguments, the package in the current working directory will be cleaned."
  1662. ];
  1663. }
  1664.  
  1665. override void prepare(scope CommandArgs args)
  1666. {
  1667. args.getopt("all-packages", &m_allPackages, [
  1668. "Cleans up *all* known packages (dub list)"
  1669. ]);
  1670. }
  1671.  
  1672. override int execute(Dub dub, string[] free_args, string[] app_args)
  1673. {
  1674. enforceUsage(free_args.length <= 1, "Expected one or zero arguments.");
  1675. enforceUsage(app_args.length == 0, "Application arguments are not supported for the clean command.");
  1676. enforceUsage(!m_allPackages || !free_args.length, "The --all-packages flag may not be used together with an explicit package name.");
  1677.  
  1678. enforce(free_args.length == 0, "Cleaning a specific package isn't possible right now.");
  1679.  
  1680. if (m_allPackages) {
  1681. bool any_error = false;
  1682.  
  1683. foreach (p; dub.packageManager.getPackageIterator()) {
  1684. try dub.cleanPackage(p.path);
  1685. catch (Exception e) {
  1686. logWarn("Failed to clean package %s at %s: %s", p.name, p.path, e.msg);
  1687. any_error = true;
  1688. }
  1689.  
  1690. foreach (sp; p.subPackages.filter!(sp => !sp.path.empty)) {
  1691. try dub.cleanPackage(p.path ~ sp.path);
  1692. catch (Exception e) {
  1693. logWarn("Failed to clean sub package of %s at %s: %s", p.name, p.path ~ sp.path, e.msg);
  1694. any_error = true;
  1695. }
  1696. }
  1697. }
  1698.  
  1699. if (any_error) return 2;
  1700. } else {
  1701. dub.cleanPackage(dub.rootPath);
  1702. }
  1703.  
  1704. return 0;
  1705. }
  1706. }
  1707.  
  1708.  
  1709. /******************************************************************************/
  1710. /* FETCH / ADD / REMOVE / UPGRADE */
  1711. /******************************************************************************/
  1712.  
  1713. class AddCommand : Command {
  1714. this() @safe pure nothrow
  1715. {
  1716. this.name = "add";
  1717. this.argumentsPattern = "<package>[@<version-spec>] [<packages...>]";
  1718. this.description = "Adds dependencies to the package file.";
  1719. this.helpText = [
  1720. "Adds <packages> as dependencies.",
  1721. "",
  1722. "Running \"dub add <package>\" is the same as adding <package> to the \"dependencies\" section in dub.json/dub.sdl.",
  1723. "If no version is specified for one of the packages, dub will query the registry for the latest version."
  1724. ];
  1725. }
  1726.  
  1727. override void prepare(scope CommandArgs args) {}
  1728.  
  1729. override int execute(Dub dub, string[] free_args, string[] app_args)
  1730. {
  1731. import dub.recipe.io : readPackageRecipe, writePackageRecipe;
  1732. import dub.internal.vibecompat.core.file : existsFile;
  1733. enforceUsage(free_args.length != 0, "Expected one or more arguments.");
  1734. enforceUsage(app_args.length == 0, "Unexpected application arguments.");
  1735.  
  1736. if (!loadCwdPackage(dub, true)) return 2;
  1737. auto recipe = dub.project.rootPackage.rawRecipe.clone;
  1738.  
  1739. foreach (depspec; free_args) {
  1740. if (!addDependency(dub, recipe, depspec))
  1741. return 2;
  1742. }
  1743. writePackageRecipe(dub.project.rootPackage.recipePath, recipe);
  1744.  
  1745. return 0;
  1746. }
  1747. }
  1748.  
  1749. class UpgradeCommand : Command {
  1750. private {
  1751. bool m_prerelease = false;
  1752. bool m_includeSubPackages = false;
  1753. bool m_forceRemove = false;
  1754. bool m_missingOnly = false;
  1755. bool m_verify = false;
  1756. bool m_dryRun = false;
  1757. }
  1758.  
  1759. this() @safe pure nothrow
  1760. {
  1761. this.name = "upgrade";
  1762. this.argumentsPattern = "[<packages...>]";
  1763. this.description = "Forces an upgrade of the dependencies";
  1764. this.helpText = [
  1765. "Upgrades all dependencies of the package by querying the package registry(ies) for new versions.",
  1766. "",
  1767. "This will update the versions stored in the selections file ("~SelectedVersions.defaultFile~") accordingly.",
  1768. "",
  1769. "If one or more package names are specified, only those dependencies will be upgraded. Otherwise all direct and indirect dependencies of the root package will get upgraded."
  1770. ];
  1771. }
  1772.  
  1773. override void prepare(scope CommandArgs args)
  1774. {
  1775. args.getopt("prerelease", &m_prerelease, [
  1776. "Uses the latest pre-release version, even if release versions are available"
  1777. ]);
  1778. args.getopt("s|sub-packages", &m_includeSubPackages, [
  1779. "Also upgrades dependencies of all directory based sub packages"
  1780. ]);
  1781. args.getopt("verify", &m_verify, [
  1782. "Updates the project and performs a build. If successful, rewrites the selected versions file <to be implemented>."
  1783. ]);
  1784. args.getopt("dry-run", &m_dryRun, [
  1785. "Only print what would be upgraded, but don't actually upgrade anything."
  1786. ]);
  1787. args.getopt("missing-only", &m_missingOnly, [
  1788. "Performs an upgrade only for dependencies that don't yet have a version selected. This is also done automatically before each build."
  1789. ]);
  1790. args.getopt("force-remove", &m_forceRemove, [
  1791. "Deprecated option that does nothing."
  1792. ]);
  1793. }
  1794.  
  1795. override int execute(Dub dub, string[] free_args, string[] app_args)
  1796. {
  1797. enforceUsage(free_args.length <= 1, "Unexpected arguments.");
  1798. enforceUsage(app_args.length == 0, "Unexpected application arguments.");
  1799. enforceUsage(!m_verify, "--verify is not yet implemented.");
  1800. enforce(loadCwdPackage(dub, true), "Failed to load package.");
  1801. logInfo("Upgrading", Color.cyan, "project in %s", dub.projectPath.toNativeString().color(Mode.bold));
  1802. auto options = UpgradeOptions.upgrade|UpgradeOptions.select;
  1803. if (m_missingOnly) options &= ~UpgradeOptions.upgrade;
  1804. if (m_prerelease) options |= UpgradeOptions.preRelease;
  1805. if (m_dryRun) options |= UpgradeOptions.dryRun;
  1806. dub.upgrade(options, free_args);
  1807.  
  1808. auto spacks = dub.project.rootPackage
  1809. .subPackages
  1810. .filter!(sp => sp.path.length);
  1811.  
  1812. if (m_includeSubPackages) {
  1813. bool any_error = false;
  1814.  
  1815. // Go through each path based sub package, load it as a new instance
  1816. // and perform an upgrade as if the upgrade had been run from within
  1817. // the sub package folder. Note that we have to use separate Dub
  1818. // instances, because the upgrade always works on the root package
  1819. // of a project, which in this case are the individual sub packages.
  1820. foreach (sp; spacks) {
  1821. try {
  1822. auto fullpath = (dub.projectPath ~ sp.path).toNativeString();
  1823. logInfo("Upgrading sub package in %s", fullpath);
  1824. auto sdub = new Dub(fullpath, dub.packageSuppliers, SkipPackageSuppliers.all);
  1825. sdub.defaultPlacementLocation = dub.defaultPlacementLocation;
  1826. sdub.loadPackage();
  1827. sdub.upgrade(options, free_args);
  1828. } catch (Exception e) {
  1829. logError("Failed to update sub package at %s: %s",
  1830. sp.path, e.msg);
  1831. any_error = true;
  1832. }
  1833. }
  1834.  
  1835. if (any_error) return 1;
  1836. } else if (!spacks.empty) {
  1837. foreach (sp; spacks)
  1838. logInfo("Not upgrading sub package in %s", sp.path);
  1839. logInfo("\nNote: specify -s to also upgrade sub packages.");
  1840. }
  1841.  
  1842. return 0;
  1843. }
  1844. }
  1845.  
  1846. class FetchRemoveCommand : Command {
  1847. protected {
  1848. string m_version;
  1849. bool m_forceRemove = false;
  1850. }
  1851.  
  1852. override void prepare(scope CommandArgs args)
  1853. {
  1854. args.getopt("version", &m_version, [
  1855. "Use the specified version/branch instead of the latest available match",
  1856. "The remove command also accepts \"*\" here as a wildcard to remove all versions of the package from the specified location"
  1857. ], true); // hide --version from help
  1858.  
  1859. args.getopt("force-remove", &m_forceRemove, [
  1860. "Deprecated option that does nothing"
  1861. ]);
  1862. }
  1863.  
  1864. abstract override int execute(Dub dub, string[] free_args, string[] app_args);
  1865. }
  1866.  
  1867. class FetchCommand : FetchRemoveCommand {
  1868. this() @safe pure nothrow
  1869. {
  1870. this.name = "fetch";
  1871. this.argumentsPattern = "<package>[@<version-spec>]";
  1872. this.description = "Manually retrieves and caches a package";
  1873. this.helpText = [
  1874. "Note: Use \"dub add <dependency>\" if you just want to use a certain package as a dependency, you don't have to explicitly fetch packages.",
  1875. "",
  1876. "Explicit retrieval/removal of packages is only needed when you want to put packages in a place where several applications can share them. If you just have a dependency to add, use the `add` command. Dub will do the rest for you.",
  1877. "",
  1878. "Without specified options, placement/removal will default to a user wide shared location.",
  1879. "",
  1880. "Complete applications can be retrieved and run easily by e.g.",
  1881. "$ dub fetch vibelog --cache=local",
  1882. "$ dub run vibelog --cache=local",
  1883. "",
  1884. "This will grab all needed dependencies and compile and run the application.",
  1885. ];
  1886. }
  1887.  
  1888. override void prepare(scope CommandArgs args)
  1889. {
  1890. super.prepare(args);
  1891. }
  1892.  
  1893. override int execute(Dub dub, string[] free_args, string[] app_args)
  1894. {
  1895. enforceUsage(free_args.length == 1, "Expecting exactly one argument.");
  1896. enforceUsage(app_args.length == 0, "Unexpected application arguments.");
  1897.  
  1898. auto location = dub.defaultPlacementLocation;
  1899.  
  1900. auto name = free_args[0];
  1901.  
  1902. FetchOptions fetchOpts;
  1903. fetchOpts |= FetchOptions.forceBranchUpgrade;
  1904. if (m_version.length) { // remove then --version removed
  1905. enforceUsage(!name.canFindVersionSplitter, "Double version spec not allowed.");
  1906. logWarn("The '--version' parameter was deprecated, use %s@%s. Please update your scripts.", name, m_version);
  1907. dub.fetch(name, VersionRange.fromString(m_version), location, fetchOpts);
  1908. } else if (name.canFindVersionSplitter) {
  1909. const parts = name.splitPackageName;
  1910. dub.fetch(parts.name, VersionRange.fromString(parts.version_), location, fetchOpts);
  1911. } else {
  1912. try {
  1913. dub.fetch(name, VersionRange.Any, location, fetchOpts);
  1914. logInfo("Finished", Color.green, "%s fetched", name.color(Mode.bold));
  1915. logInfo(
  1916. "Please note that you need to use `dub run <pkgname>` " ~
  1917. "or add it to dependencies of your package to actually use/run it. "
  1918. );
  1919. }
  1920. catch(Exception e){
  1921. logInfo("Getting a release version failed: %s", e.msg);
  1922. logInfo("Retry with ~master...");
  1923. dub.fetch(name, VersionRange.fromString("~master"), location, fetchOpts);
  1924. }
  1925. }
  1926. return 0;
  1927. }
  1928. }
  1929.  
  1930. class RemoveCommand : FetchRemoveCommand {
  1931. private {
  1932. bool m_nonInteractive;
  1933. }
  1934.  
  1935. this() @safe pure nothrow
  1936. {
  1937. this.name = "remove";
  1938. this.argumentsPattern = "<package>[@<version-spec>]";
  1939. this.description = "Removes a cached package";
  1940. this.helpText = [
  1941. "Removes a package that is cached on the local system."
  1942. ];
  1943. }
  1944.  
  1945. override void prepare(scope CommandArgs args)
  1946. {
  1947. super.prepare(args);
  1948. args.getopt("n|non-interactive", &m_nonInteractive, ["Don't enter interactive mode."]);
  1949. }
  1950.  
  1951. override int execute(Dub dub, string[] free_args, string[] app_args)
  1952. {
  1953. enforceUsage(free_args.length == 1, "Expecting exactly one argument.");
  1954. enforceUsage(app_args.length == 0, "Unexpected application arguments.");
  1955.  
  1956. auto package_id = free_args[0];
  1957. auto location = dub.defaultPlacementLocation;
  1958.  
  1959. size_t resolveVersion(in Package[] packages) {
  1960. // just remove only package version
  1961. if (packages.length == 1)
  1962. return 0;
  1963.  
  1964. writeln("Select version of '", package_id, "' to remove from location '", location, "':");
  1965. foreach (i, pack; packages)
  1966. writefln("%s) %s", i + 1, pack.version_);
  1967. writeln(packages.length + 1, ") ", "all versions");
  1968. while (true) {
  1969. writef("> ");
  1970. auto inp = readln();
  1971. if (!inp.length) // Ctrl+D
  1972. return size_t.max;
  1973. inp = inp.stripRight;
  1974. if (!inp.length) // newline or space
  1975. continue;
  1976. try {
  1977. immutable selection = inp.to!size_t - 1;
  1978. if (selection <= packages.length)
  1979. return selection;
  1980. } catch (ConvException e) {
  1981. }
  1982. logError("Please enter a number between 1 and %s.", packages.length + 1);
  1983. }
  1984. }
  1985.  
  1986. if (!m_version.empty) { // remove then --version removed
  1987. enforceUsage(!package_id.canFindVersionSplitter, "Double version spec not allowed.");
  1988. logWarn("The '--version' parameter was deprecated, use %s@%s. Please update your scripts.", package_id, m_version);
  1989. dub.remove(package_id, m_version, location);
  1990. } else {
  1991. const parts = package_id.splitPackageName;
  1992. if (m_nonInteractive || parts.version_.length) {
  1993. dub.remove(parts.name, parts.version_, location);
  1994. } else {
  1995. dub.remove(package_id, location, &resolveVersion);
  1996. }
  1997. }
  1998. return 0;
  1999. }
  2000. }
  2001.  
  2002. /******************************************************************************/
  2003. /* ADD/REMOVE PATH/LOCAL */
  2004. /******************************************************************************/
  2005.  
  2006. abstract class RegistrationCommand : Command {
  2007. private {
  2008. bool m_system;
  2009. }
  2010.  
  2011. override void prepare(scope CommandArgs args)
  2012. {
  2013. args.getopt("system", &m_system, [
  2014. "Register system-wide instead of user-wide"
  2015. ]);
  2016. }
  2017.  
  2018. abstract override int execute(Dub dub, string[] free_args, string[] app_args);
  2019. }
  2020.  
  2021. class AddPathCommand : RegistrationCommand {
  2022. this() @safe pure nothrow
  2023. {
  2024. this.name = "add-path";
  2025. this.argumentsPattern = "<path>";
  2026. this.description = "Adds a default package search path";
  2027. this.helpText = [
  2028. "Adds a default package search path. All direct sub folders of this path will be searched for package descriptions and will be made available as packages. Using this command has the equivalent effect as calling 'dub add-local' on each of the sub folders manually.",
  2029. "",
  2030. "Any packages registered using add-path will be preferred over packages downloaded from the package registry when searching for dependencies during a build operation.",
  2031. "",
  2032. "The version of the packages will be determined by one of the following:",
  2033. " - For GIT working copies, the last tag (git describe) is used to determine the version",
  2034. " - If the package contains a \"version\" field in the package description, this is used",
  2035. " - If neither of those apply, \"~master\" is assumed"
  2036. ];
  2037. }
  2038.  
  2039. override int execute(Dub dub, string[] free_args, string[] app_args)
  2040. {
  2041. enforceUsage(free_args.length == 1, "Missing search path.");
  2042. dub.addSearchPath(free_args[0], m_system);
  2043. return 0;
  2044. }
  2045. }
  2046.  
  2047. class RemovePathCommand : RegistrationCommand {
  2048. this() @safe pure nothrow
  2049. {
  2050. this.name = "remove-path";
  2051. this.argumentsPattern = "<path>";
  2052. this.description = "Removes a package search path";
  2053. this.helpText = ["Removes a package search path previously added with add-path."];
  2054. }
  2055.  
  2056. override int execute(Dub dub, string[] free_args, string[] app_args)
  2057. {
  2058. enforceUsage(free_args.length == 1, "Expected one argument.");
  2059. dub.removeSearchPath(free_args[0], m_system);
  2060. return 0;
  2061. }
  2062. }
  2063.  
  2064. class AddLocalCommand : RegistrationCommand {
  2065. this() @safe pure nothrow
  2066. {
  2067. this.name = "add-local";
  2068. this.argumentsPattern = "<path> [<version>]";
  2069. this.description = "Adds a local package directory (e.g. a git repository)";
  2070. this.helpText = [
  2071. "Adds a local package directory to be used during dependency resolution. This command is useful for registering local packages, such as GIT working copies, that are either not available in the package registry, or are supposed to be overwritten.",
  2072. "",
  2073. "The version of the package is either determined automatically (see the \"add-path\" command, or can be explicitly overwritten by passing a version on the command line.",
  2074. "",
  2075. "See 'dub add-path -h' for a way to register multiple local packages at once."
  2076. ];
  2077. }
  2078.  
  2079. override int execute(Dub dub, string[] free_args, string[] app_args)
  2080. {
  2081. enforceUsage(free_args.length == 1 || free_args.length == 2, "Expecting one or two arguments.");
  2082. string ver = free_args.length == 2 ? free_args[1] : null;
  2083. dub.addLocalPackage(free_args[0], ver, m_system);
  2084. return 0;
  2085. }
  2086. }
  2087.  
  2088. class RemoveLocalCommand : RegistrationCommand {
  2089. this() @safe pure nothrow
  2090. {
  2091. this.name = "remove-local";
  2092. this.argumentsPattern = "<path>";
  2093. this.description = "Removes a local package directory";
  2094. this.helpText = ["Removes a local package directory"];
  2095. }
  2096.  
  2097. override int execute(Dub dub, string[] free_args, string[] app_args)
  2098. {
  2099. enforceUsage(free_args.length >= 1, "Missing package path argument.");
  2100. enforceUsage(free_args.length <= 1, "Expected the package path to be the only argument.");
  2101. dub.removeLocalPackage(free_args[0], m_system);
  2102. return 0;
  2103. }
  2104. }
  2105.  
  2106. class ListCommand : Command {
  2107. this() @safe pure nothrow
  2108. {
  2109. this.name = "list";
  2110. this.argumentsPattern = "[<package>[@<version-spec>]]";
  2111. this.description = "Prints a list of all or selected local packages dub is aware of";
  2112. this.helpText = [
  2113. "Prints a list of all or selected local packages. This includes all cached "~
  2114. "packages (user or system wide), all packages in the package search paths "~
  2115. "(\"dub add-path\") and all manually registered packages (\"dub add-local\"). "~
  2116. "If package specified output filtered by package spec."
  2117. ];
  2118. }
  2119. override void prepare(scope CommandArgs args) {}
  2120. override int execute(Dub dub, string[] free_args, string[] app_args)
  2121. {
  2122. enforceUsage(free_args.length <= 1, "Expecting zero or one extra arguments.");
  2123. const pinfo = free_args.length ? splitPackageName(free_args[0]) : PackageAndVersion("","*");
  2124. const pname = pinfo.name;
  2125. const pvlim = Dependency(pinfo.version_ == "" ? "*" : pinfo.version_);
  2126. enforceUsage(app_args.length == 0, "The list command supports no application arguments.");
  2127. logInfoNoTag("Packages present in the system and known to dub:");
  2128. foreach (p; dub.packageManager.getPackageIterator()) {
  2129. if ((pname == "" || pname == p.name) && pvlim.matches(p.version_))
  2130. logInfoNoTag(" %s %s: %s", p.name.color(Mode.bold), p.version_, p.path.toNativeString());
  2131. }
  2132. logInfo("");
  2133. return 0;
  2134. }
  2135. }
  2136.  
  2137. class SearchCommand : Command {
  2138. this() @safe pure nothrow
  2139. {
  2140. this.name = "search";
  2141. this.argumentsPattern = "<package-name>";
  2142. this.description = "Search for available packages.";
  2143. this.helpText = [
  2144. "Search all specified providers for matching packages."
  2145. ];
  2146. }
  2147. override void prepare(scope CommandArgs args) {}
  2148. override int execute(Dub dub, string[] free_args, string[] app_args)
  2149. {
  2150. enforce(free_args.length == 1, "Expected one argument.");
  2151. auto res = dub.searchPackages(free_args[0]);
  2152. if (res.empty)
  2153. {
  2154. logError("No matches found.");
  2155. return 2;
  2156. }
  2157. auto justify = res
  2158. .map!((descNmatches) => descNmatches[1])
  2159. .joiner
  2160. .map!(m => m.name.length + m.version_.length)
  2161. .reduce!max + " ()".length;
  2162. justify += (~justify & 3) + 1; // round to next multiple of 4
  2163. int colorDifference = cast(int)"a".color(Mode.bold).length - 1;
  2164. justify += colorDifference;
  2165. foreach (desc, matches; res)
  2166. {
  2167. logInfoNoTag("==== %s ====", desc);
  2168. foreach (m; matches)
  2169. logInfoNoTag(" %s%s", leftJustify(m.name.color(Mode.bold)
  2170. ~ " (" ~ m.version_ ~ ")", justify), m.description);
  2171. }
  2172. return 0;
  2173. }
  2174. }
  2175.  
  2176.  
  2177. /******************************************************************************/
  2178. /* OVERRIDES */
  2179. /******************************************************************************/
  2180.  
  2181. class AddOverrideCommand : Command {
  2182. private {
  2183. bool m_system = false;
  2184. }
  2185.  
  2186. this() @safe pure nothrow
  2187. {
  2188. this.name = "add-override";
  2189. this.argumentsPattern = "<package> <version-spec> <target-path/target-version>";
  2190. this.description = "Adds a new package override.";
  2191. this.helpText = [
  2192. ];
  2193. }
  2194.  
  2195. override void prepare(scope CommandArgs args)
  2196. {
  2197. args.getopt("system", &m_system, [
  2198. "Register system-wide instead of user-wide"
  2199. ]);
  2200. }
  2201.  
  2202. override int execute(Dub dub, string[] free_args, string[] app_args)
  2203. {
  2204. enforceUsage(app_args.length == 0, "Unexpected application arguments.");
  2205. enforceUsage(free_args.length == 3, "Expected three arguments, not "~free_args.length.to!string);
  2206. auto scope_ = m_system ? PlacementLocation.system : PlacementLocation.user;
  2207. auto pack = free_args[0];
  2208. auto source = VersionRange.fromString(free_args[1]);
  2209. if (existsFile(NativePath(free_args[2]))) {
  2210. auto target = NativePath(free_args[2]);
  2211. if (!target.absolute) target = NativePath(getcwd()) ~ target;
  2212. dub.packageManager.addOverride(scope_, pack, source, target);
  2213. logInfo("Added override %s %s => %s", pack, source, target);
  2214. } else {
  2215. auto target = Version(free_args[2]);
  2216. dub.packageManager.addOverride(scope_, pack, source, target);
  2217. logInfo("Added override %s %s => %s", pack, source, target);
  2218. }
  2219. return 0;
  2220. }
  2221. }
  2222.  
  2223. class RemoveOverrideCommand : Command {
  2224. private {
  2225. bool m_system = false;
  2226. }
  2227.  
  2228. this() @safe pure nothrow
  2229. {
  2230. this.name = "remove-override";
  2231. this.argumentsPattern = "<package> <version-spec>";
  2232. this.description = "Removes an existing package override.";
  2233. this.helpText = [
  2234. ];
  2235. }
  2236.  
  2237. override void prepare(scope CommandArgs args)
  2238. {
  2239. args.getopt("system", &m_system, [
  2240. "Register system-wide instead of user-wide"
  2241. ]);
  2242. }
  2243.  
  2244. override int execute(Dub dub, string[] free_args, string[] app_args)
  2245. {
  2246. enforceUsage(app_args.length == 0, "Unexpected application arguments.");
  2247. enforceUsage(free_args.length == 2, "Expected two arguments, not "~free_args.length.to!string);
  2248. auto scope_ = m_system ? PlacementLocation.system : PlacementLocation.user;
  2249. auto source = VersionRange.fromString(free_args[1]);
  2250. dub.packageManager.removeOverride(scope_, free_args[0], source);
  2251. return 0;
  2252. }
  2253. }
  2254.  
  2255. class ListOverridesCommand : Command {
  2256. this() @safe pure nothrow
  2257. {
  2258. this.name = "list-overrides";
  2259. this.argumentsPattern = "";
  2260. this.description = "Prints a list of all local package overrides";
  2261. this.helpText = [
  2262. "Prints a list of all overridden packages added via \"dub add-override\"."
  2263. ];
  2264. }
  2265. override void prepare(scope CommandArgs args) {}
  2266. override int execute(Dub dub, string[] free_args, string[] app_args)
  2267. {
  2268. void printList(in PackageOverride[] overrides, string caption)
  2269. {
  2270. if (overrides.length == 0) return;
  2271. logInfoNoTag("# %s", caption);
  2272. foreach (ovr; overrides)
  2273. ovr.target.match!(
  2274. t => logInfoNoTag("%s %s => %s", ovr.package_.color(Mode.bold), ovr.version_, t));
  2275. }
  2276. printList(dub.packageManager.getOverrides(PlacementLocation.user), "User wide overrides");
  2277. printList(dub.packageManager.getOverrides(PlacementLocation.system), "System wide overrides");
  2278. return 0;
  2279. }
  2280. }
  2281.  
  2282. /******************************************************************************/
  2283. /* Cache cleanup */
  2284. /******************************************************************************/
  2285.  
  2286. class CleanCachesCommand : Command {
  2287. this() @safe pure nothrow
  2288. {
  2289. this.name = "clean-caches";
  2290. this.argumentsPattern = "";
  2291. this.description = "Removes cached metadata";
  2292. this.helpText = [
  2293. "This command removes any cached metadata like the list of available packages and their latest version."
  2294. ];
  2295. }
  2296.  
  2297. override void prepare(scope CommandArgs args) {}
  2298.  
  2299. override int execute(Dub dub, string[] free_args, string[] app_args)
  2300. {
  2301. return 0;
  2302. }
  2303. }
  2304.  
  2305. /******************************************************************************/
  2306. /* DUSTMITE */
  2307. /******************************************************************************/
  2308.  
  2309. class DustmiteCommand : PackageBuildCommand {
  2310. private {
  2311. int m_compilerStatusCode = int.min;
  2312. int m_linkerStatusCode = int.min;
  2313. int m_programStatusCode = int.min;
  2314. string m_compilerRegex;
  2315. string m_linkerRegex;
  2316. string m_programRegex;
  2317. string m_testPackage;
  2318. bool m_noRedirect;
  2319. string m_strategy;
  2320. uint m_jobCount; // zero means not specified
  2321. bool m_trace;
  2322. }
  2323.  
  2324. this() @safe pure nothrow
  2325. {
  2326. this.name = "dustmite";
  2327. this.argumentsPattern = "<destination-path>";
  2328. this.acceptsAppArgs = true;
  2329. this.description = "Create reduced test cases for build errors";
  2330. this.helpText = [
  2331. "This command uses the Dustmite utility to isolate the cause of build errors in a DUB project.",
  2332. "",
  2333. "It will create a copy of all involved packages and run dustmite on this copy, leaving a reduced test case.",
  2334. "",
  2335. "Determining the desired error condition is done by checking the compiler/linker status code, as well as their output (stdout and stderr combined). If --program-status or --program-regex is given and the generated binary is an executable, it will be executed and its output will also be incorporated into the final decision."
  2336. ];
  2337. }
  2338.  
  2339. override void prepare(scope CommandArgs args)
  2340. {
  2341. args.getopt("compiler-status", &m_compilerStatusCode, ["The expected status code of the compiler run"]);
  2342. args.getopt("compiler-regex", &m_compilerRegex, ["A regular expression used to match against the compiler output"]);
  2343. args.getopt("linker-status", &m_linkerStatusCode, ["The expected status code of the linker run"]);
  2344. args.getopt("linker-regex", &m_linkerRegex, ["A regular expression used to match against the linker output"]);
  2345. args.getopt("program-status", &m_programStatusCode, ["The expected status code of the built executable"]);
  2346. args.getopt("program-regex", &m_programRegex, ["A regular expression used to match against the program output"]);
  2347. args.getopt("test-package", &m_testPackage, ["Perform a test run - usually only used internally"]);
  2348. args.getopt("combined", &this.baseSettings.combined, ["Builds multiple packages with one compiler run"]);
  2349. args.getopt("no-redirect", &m_noRedirect, ["Don't redirect stdout/stderr streams of the test command"]);
  2350. args.getopt("strategy", &m_strategy, ["Set strategy (careful/lookback/pingpong/indepth/inbreadth)"]);
  2351. args.getopt("j", &m_jobCount, ["Set number of look-ahead processes"]);
  2352. args.getopt("trace", &m_trace, ["Save all attempted reductions to DIR.trace"]);
  2353. super.prepare(args);
  2354.  
  2355. // speed up loading when in test mode
  2356. if (m_testPackage.length) {
  2357. skipDubInitialization = true;
  2358. m_nodeps = true;
  2359. }
  2360. }
  2361.  
  2362. override int execute(Dub dub, string[] free_args, string[] app_args)
  2363. {
  2364. import std.format : formattedWrite;
  2365.  
  2366. if (m_testPackage.length) {
  2367. dub = new Dub(NativePath(getcwd()));
  2368.  
  2369. setupPackage(dub, m_testPackage);
  2370. m_defaultConfig = dub.project.getDefaultConfiguration(this.baseSettings.platform);
  2371.  
  2372. GeneratorSettings gensettings = this.baseSettings;
  2373. if (!gensettings.config.length)
  2374. gensettings.config = m_defaultConfig;
  2375. gensettings.run = m_programStatusCode != int.min || m_programRegex.length;
  2376. gensettings.runArgs = app_args;
  2377. gensettings.force = true;
  2378. gensettings.compileCallback = check(m_compilerStatusCode, m_compilerRegex);
  2379. gensettings.linkCallback = check(m_linkerStatusCode, m_linkerRegex);
  2380. gensettings.runCallback = check(m_programStatusCode, m_programRegex);
  2381. try dub.generateProject("build", gensettings);
  2382. catch (DustmiteMismatchException) {
  2383. logInfoNoTag("Dustmite test doesn't match.");
  2384. return 3;
  2385. }
  2386. catch (DustmiteMatchException) {
  2387. logInfoNoTag("Dustmite test matches.");
  2388. return 0;
  2389. }
  2390. } else {
  2391. enforceUsage(free_args.length == 1, "Expected destination path.");
  2392. auto path = NativePath(free_args[0]);
  2393. path.normalize();
  2394. enforceUsage(!path.empty, "Destination path must not be empty.");
  2395. if (!path.absolute) path = NativePath(getcwd()) ~ path;
  2396. enforceUsage(!path.startsWith(dub.rootPath), "Destination path must not be a sub directory of the tested package!");
  2397.  
  2398. setupPackage(dub, null);
  2399. auto prj = dub.project;
  2400. if (this.baseSettings.config.empty)
  2401. this.baseSettings.config = prj.getDefaultConfiguration(this.baseSettings.platform);
  2402.  
  2403. void copyFolderRec(NativePath folder, NativePath dstfolder)
  2404. {
  2405. mkdirRecurse(dstfolder.toNativeString());
  2406. foreach (de; iterateDirectory(folder.toNativeString())) {
  2407. if (de.name.startsWith(".")) continue;
  2408. if (de.isDirectory) {
  2409. copyFolderRec(folder ~ de.name, dstfolder ~ de.name);
  2410. } else {
  2411. if (de.name.endsWith(".o") || de.name.endsWith(".obj")) continue;
  2412. if (de.name.endsWith(".exe")) continue;
  2413. try copyFile(folder ~ de.name, dstfolder ~ de.name);
  2414. catch (Exception e) {
  2415. logWarn("Failed to copy file %s: %s", (folder ~ de.name).toNativeString(), e.msg);
  2416. }
  2417. }
  2418. }
  2419. }
  2420.  
  2421. static void fixPathDependency(string pack, ref Dependency dep) {
  2422. if (!dep.path.empty) {
  2423. auto mainpack = getBasePackageName(pack);
  2424. dep.path = NativePath("../") ~ mainpack;
  2425. }
  2426. }
  2427.  
  2428. void fixPathDependencies(ref PackageRecipe recipe, NativePath base_path)
  2429. {
  2430. foreach (name, ref dep; recipe.buildSettings.dependencies)
  2431. fixPathDependency(name, dep);
  2432.  
  2433. foreach (ref cfg; recipe.configurations)
  2434. foreach (name, ref dep; cfg.buildSettings.dependencies)
  2435. fixPathDependency(name, dep);
  2436.  
  2437. foreach (ref subp; recipe.subPackages)
  2438. if (subp.path.length) {
  2439. auto sub_path = base_path ~ NativePath(subp.path);
  2440. auto pack = prj.packageManager.getOrLoadPackage(sub_path);
  2441. fixPathDependencies(pack.recipe, sub_path);
  2442. pack.storeInfo(sub_path);
  2443. } else fixPathDependencies(subp.recipe, base_path);
  2444. }
  2445.  
  2446. bool[string] visited;
  2447. foreach (pack_; prj.getTopologicalPackageList()) {
  2448. auto pack = pack_.basePackage;
  2449. if (pack.name in visited) continue;
  2450. visited[pack.name] = true;
  2451. auto dst_path = path ~ pack.name;
  2452. logInfo("Prepare", Color.light_blue, "Copy package %s to destination folder...", pack.name.color(Mode.bold));
  2453. copyFolderRec(pack.path, dst_path);
  2454.  
  2455. // adjust all path based dependencies
  2456. fixPathDependencies(pack.recipe, dst_path);
  2457.  
  2458. // overwrite package description file with additional version information
  2459. pack.storeInfo(dst_path);
  2460. }
  2461.  
  2462. logInfo("Starting", Color.light_green, "Executing dustmite...");
  2463. auto testcmd = appender!string();
  2464. testcmd.formattedWrite("%s dustmite --test-package=%s --build=%s --config=%s",
  2465. thisExePath, prj.name, this.baseSettings.buildType, this.baseSettings.config);
  2466.  
  2467. if (m_compilerName.length) testcmd.formattedWrite(" \"--compiler=%s\"", m_compilerName);
  2468. if (m_arch.length) testcmd.formattedWrite(" --arch=%s", m_arch);
  2469. if (m_compilerStatusCode != int.min) testcmd.formattedWrite(" --compiler-status=%s", m_compilerStatusCode);
  2470. if (m_compilerRegex.length) testcmd.formattedWrite(" \"--compiler-regex=%s\"", m_compilerRegex);
  2471. if (m_linkerStatusCode != int.min) testcmd.formattedWrite(" --linker-status=%s", m_linkerStatusCode);
  2472. if (m_linkerRegex.length) testcmd.formattedWrite(" \"--linker-regex=%s\"", m_linkerRegex);
  2473. if (m_programStatusCode != int.min) testcmd.formattedWrite(" --program-status=%s", m_programStatusCode);
  2474. if (m_programRegex.length) testcmd.formattedWrite(" \"--program-regex=%s\"", m_programRegex);
  2475. if (this.baseSettings.combined) testcmd ~= " --combined";
  2476.  
  2477. // --vquiet swallows dustmite's output ...
  2478. if (!m_noRedirect) testcmd ~= " --vquiet";
  2479.  
  2480. // TODO: pass *all* original parameters
  2481. logDiagnostic("Running dustmite: %s", testcmd);
  2482.  
  2483. string[] extraArgs;
  2484. if (m_noRedirect) extraArgs ~= "--no-redirect";
  2485. if (m_strategy.length) extraArgs ~= "--strategy=" ~ m_strategy;
  2486. if (m_jobCount) extraArgs ~= "-j" ~ m_jobCount.to!string;
  2487. if (m_trace) extraArgs ~= "--trace";
  2488.  
  2489. const cmd = "dustmite" ~ extraArgs ~ [path.toNativeString(), testcmd.data];
  2490. auto dmpid = spawnProcess(cmd);
  2491. return dmpid.wait();
  2492. }
  2493. return 0;
  2494. }
  2495.  
  2496. void delegate(int, string) check(int code_match, string regex_match)
  2497. {
  2498. return (code, output) {
  2499. import std.encoding;
  2500. import std.regex;
  2501.  
  2502. logInfo("%s", output);
  2503.  
  2504. if (code_match != int.min && code != code_match) {
  2505. logInfo("Exit code %s doesn't match expected value %s", code, code_match);
  2506. throw new DustmiteMismatchException;
  2507. }
  2508.  
  2509. if (regex_match.length > 0 && !match(output.sanitize, regex_match)) {
  2510. logInfo("Output doesn't match regex:");
  2511. logInfo("%s", output);
  2512. throw new DustmiteMismatchException;
  2513. }
  2514.  
  2515. if (code != 0 && code_match != int.min || regex_match.length > 0) {
  2516. logInfo("Tool failed, but matched either exit code or output - counting as match.");
  2517. throw new DustmiteMatchException;
  2518. }
  2519. };
  2520. }
  2521.  
  2522. static class DustmiteMismatchException : Exception {
  2523. this(string message = "", string file = __FILE__, int line = __LINE__, Throwable next = null)
  2524. {
  2525. super(message, file, line, next);
  2526. }
  2527. }
  2528.  
  2529. static class DustmiteMatchException : Exception {
  2530. this(string message = "", string file = __FILE__, int line = __LINE__, Throwable next = null)
  2531. {
  2532. super(message, file, line, next);
  2533. }
  2534. }
  2535. }
  2536.  
  2537.  
  2538. /******************************************************************************/
  2539. /* CONVERT command */
  2540. /******************************************************************************/
  2541.  
  2542. class ConvertCommand : Command {
  2543. private {
  2544. string m_format;
  2545. bool m_stdout;
  2546. }
  2547.  
  2548. this() @safe pure nothrow
  2549. {
  2550. this.name = "convert";
  2551. this.argumentsPattern = "";
  2552. this.description = "Converts the file format of the package recipe.";
  2553. this.helpText = [
  2554. "This command will convert between JSON and SDLang formatted package recipe files.",
  2555. "",
  2556. "Warning: Beware that any formatting and comments within the package recipe will get lost in the conversion process."
  2557. ];
  2558. }
  2559.  
  2560. override void prepare(scope CommandArgs args)
  2561. {
  2562. args.getopt("f|format", &m_format, ["Specifies the target package recipe format. Possible values:", " json, sdl"]);
  2563. args.getopt("s|stdout", &m_stdout, ["Outputs the converted package recipe to stdout instead of writing to disk."]);
  2564. }
  2565.  
  2566. override int execute(Dub dub, string[] free_args, string[] app_args)
  2567. {
  2568. enforceUsage(app_args.length == 0, "Unexpected application arguments.");
  2569. enforceUsage(free_args.length == 0, "Unexpected arguments: "~free_args.join(" "));
  2570. enforceUsage(m_format.length > 0, "Missing target format file extension (--format=...).");
  2571. if (!loadCwdPackage(dub, true)) return 2;
  2572. dub.convertRecipe(m_format, m_stdout);
  2573. return 0;
  2574. }
  2575. }
  2576.  
  2577.  
  2578. /******************************************************************************/
  2579. /* HELP */
  2580. /******************************************************************************/
  2581.  
  2582. private {
  2583. enum shortArgColumn = 2;
  2584. enum longArgColumn = 6;
  2585. enum descColumn = 24;
  2586. enum lineWidth = 80 - 1;
  2587. }
  2588.  
  2589. private void showHelp(in CommandGroup[] commands, CommandArgs common_args)
  2590. {
  2591. writeln(
  2592. `USAGE: dub [--version] [<command>] [<options...>] [-- [<application arguments...>]]
  2593.  
  2594. Manages the DUB project in the current directory. If the command is omitted,
  2595. DUB will default to "run". When running an application, "--" can be used to
  2596. separate DUB options from options passed to the application.
  2597.  
  2598. Run "dub <command> --help" to get help for a specific command.
  2599.  
  2600. You can use the "http_proxy" environment variable to configure a proxy server
  2601. to be used for fetching packages.
  2602.  
  2603.  
  2604. Available commands
  2605. ==================`);
  2606.  
  2607. foreach (grp; commands) {
  2608. writeln();
  2609. writeWS(shortArgColumn);
  2610. writeln(grp.caption);
  2611. writeWS(shortArgColumn);
  2612. writerep!'-'(grp.caption.length);
  2613. writeln();
  2614. foreach (cmd; grp.commands) {
  2615. if (cmd.hidden) continue;
  2616. writeWS(shortArgColumn);
  2617. writef("%s %s", cmd.name, cmd.argumentsPattern);
  2618. auto chars_output = cmd.name.length + cmd.argumentsPattern.length + shortArgColumn + 1;
  2619. if (chars_output < descColumn) {
  2620. writeWS(descColumn - chars_output);
  2621. } else {
  2622. writeln();
  2623. writeWS(descColumn);
  2624. }
  2625. writeWrapped(cmd.description, descColumn, descColumn);
  2626. }
  2627. }
  2628. writeln();
  2629. writeln();
  2630. writeln(`Common options`);
  2631. writeln(`==============`);
  2632. writeln();
  2633. writeOptions(common_args);
  2634. writeln();
  2635. showVersion();
  2636. }
  2637.  
  2638. private void showVersion()
  2639. {
  2640. writefln("DUB version %s, built on %s", getDUBVersion(), __DATE__);
  2641. }
  2642.  
  2643. private void showCommandHelp(Command cmd, CommandArgs args, CommandArgs common_args)
  2644. {
  2645. writefln(`USAGE: dub %s %s [<options...>]%s`, cmd.name, cmd.argumentsPattern, cmd.acceptsAppArgs ? " [-- <application arguments...>]": null);
  2646. writeln();
  2647. foreach (ln; cmd.helpText)
  2648. ln.writeWrapped();
  2649.  
  2650. if (args.recognizedArgs.length) {
  2651. writeln();
  2652. writeln();
  2653. writeln("Command specific options");
  2654. writeln("========================");
  2655. writeln();
  2656. writeOptions(args);
  2657. }
  2658.  
  2659. writeln();
  2660. writeln();
  2661. writeln("Common options");
  2662. writeln("==============");
  2663. writeln();
  2664. writeOptions(common_args);
  2665. writeln();
  2666. writefln("DUB version %s, built on %s", getDUBVersion(), __DATE__);
  2667. }
  2668.  
  2669. private void writeOptions(CommandArgs args)
  2670. {
  2671. foreach (arg; args.recognizedArgs) {
  2672. if (arg.hidden) continue;
  2673. auto names = arg.names.split("|");
  2674. assert(names.length == 1 || names.length == 2);
  2675. string sarg = names[0].length == 1 ? names[0] : null;
  2676. string larg = names[0].length > 1 ? names[0] : names.length > 1 ? names[1] : null;
  2677. if (sarg !is null) {
  2678. writeWS(shortArgColumn);
  2679. writef("-%s", sarg);
  2680. writeWS(longArgColumn - shortArgColumn - 2);
  2681. } else writeWS(longArgColumn);
  2682. size_t col = longArgColumn;
  2683. if (larg !is null) {
  2684. if (arg.defaultValue.peek!bool) {
  2685. writef("--%s", larg);
  2686. col += larg.length + 2;
  2687. } else {
  2688. writef("--%s=VALUE", larg);
  2689. col += larg.length + 8;
  2690. }
  2691. }
  2692. if (col < descColumn) {
  2693. writeWS(descColumn - col);
  2694. } else {
  2695. writeln();
  2696. writeWS(descColumn);
  2697. }
  2698. foreach (i, ln; arg.helpText) {
  2699. if (i > 0) writeWS(descColumn);
  2700. ln.writeWrapped(descColumn, descColumn);
  2701. }
  2702. }
  2703. }
  2704.  
  2705. private void writeWrapped(string string, size_t indent = 0, size_t first_line_pos = 0)
  2706. {
  2707. // handle pre-indented strings and bullet lists
  2708. size_t first_line_indent = 0;
  2709. while (string.startsWith(" ")) {
  2710. string = string[1 .. $];
  2711. indent++;
  2712. first_line_indent++;
  2713. }
  2714. if (string.startsWith("- ")) indent += 2;
  2715.  
  2716. auto wrapped = string.wrap(lineWidth, getRepString!' '(first_line_pos+first_line_indent), getRepString!' '(indent));
  2717. wrapped = wrapped[first_line_pos .. $];
  2718. foreach (ln; wrapped.splitLines())
  2719. writeln(ln);
  2720. }
  2721.  
  2722. private void writeWS(size_t num) { writerep!' '(num); }
  2723. private void writerep(char ch)(size_t num) { write(getRepString!ch(num)); }
  2724.  
  2725. private string getRepString(char ch)(size_t len)
  2726. {
  2727. static string buf;
  2728. if (len > buf.length) buf ~= [ch].replicate(len-buf.length);
  2729. return buf[0 .. len];
  2730. }
  2731.  
  2732. /***
  2733. */
  2734.  
  2735.  
  2736. private void enforceUsage(bool cond, string text)
  2737. {
  2738. if (!cond) throw new UsageException(text);
  2739. }
  2740.  
  2741. private class UsageException : Exception {
  2742. this(string message, string file = __FILE__, int line = __LINE__, Throwable next = null)
  2743. {
  2744. super(message, file, line, next);
  2745. }
  2746. }
  2747.  
  2748. private bool addDependency(Dub dub, ref PackageRecipe recipe, string depspec)
  2749. {
  2750. Dependency dep;
  2751. const parts = splitPackageName(depspec);
  2752. const depname = parts.name;
  2753. if (parts.version_)
  2754. dep = Dependency(parts.version_);
  2755. else
  2756. {
  2757. try {
  2758. const ver = dub.getLatestVersion(depname);
  2759. dep = ver.isBranch ? Dependency(ver) : Dependency("~>" ~ ver.toString());
  2760. } catch (Exception e) {
  2761. logError("Could not find package '%s'.", depname);
  2762. logDebug("Full error: %s", e.toString().sanitize);
  2763. return false;
  2764. }
  2765. }
  2766. recipe.buildSettings.dependencies[depname] = dep;
  2767. logInfo("Adding dependency %s %s", depname, dep.toString());
  2768. return true;
  2769. }
  2770.  
  2771. private struct PackageAndVersion
  2772. {
  2773. string name;
  2774. string version_;
  2775. }
  2776.  
  2777. /* Split <package>=<version-specifier> and <package>@<version-specifier>
  2778. into `name` and `version_`. */
  2779. private PackageAndVersion splitPackageName(string packageName)
  2780. {
  2781. // split <package>@<version-specifier>
  2782. auto parts = packageName.findSplit("@");
  2783. if (parts[1].empty) {
  2784. // split <package>=<version-specifier>
  2785. parts = packageName.findSplit("=");
  2786. }
  2787.  
  2788. PackageAndVersion p;
  2789. p.name = parts[0];
  2790. if (!parts[1].empty)
  2791. p.version_ = parts[2];
  2792. return p;
  2793. }
  2794.  
  2795. unittest
  2796. {
  2797. // https://github.com/dlang/dub/issues/1681
  2798. assert(splitPackageName("") == PackageAndVersion("", null));
  2799.  
  2800. assert(splitPackageName("foo") == PackageAndVersion("foo", null));
  2801. assert(splitPackageName("foo=1.0.1") == PackageAndVersion("foo", "1.0.1"));
  2802. assert(splitPackageName("foo@1.0.1") == PackageAndVersion("foo", "1.0.1"));
  2803. assert(splitPackageName("foo@==1.0.1") == PackageAndVersion("foo", "==1.0.1"));
  2804. assert(splitPackageName("foo@>=1.0.1") == PackageAndVersion("foo", ">=1.0.1"));
  2805. assert(splitPackageName("foo@~>1.0.1") == PackageAndVersion("foo", "~>1.0.1"));
  2806. assert(splitPackageName("foo@<1.0.1") == PackageAndVersion("foo", "<1.0.1"));
  2807. }
  2808.  
  2809. private ulong canFindVersionSplitter(string packageName)
  2810. {
  2811. // see splitPackageName
  2812. return packageName.canFind("@", "=");
  2813. }
  2814.  
  2815. unittest
  2816. {
  2817. assert(!canFindVersionSplitter("foo"));
  2818. assert(canFindVersionSplitter("foo=1.0.1"));
  2819. assert(canFindVersionSplitter("foo@1.0.1"));
  2820. assert(canFindVersionSplitter("foo@==1.0.1"));
  2821. assert(canFindVersionSplitter("foo@>=1.0.1"));
  2822. assert(canFindVersionSplitter("foo@~>1.0.1"));
  2823. assert(canFindVersionSplitter("foo@<1.0.1"));
  2824. }