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