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