/
commandline.d
3243 lines (2828 loc) · 106 KB
/
commandline.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
Defines the behavior of the DUB command line client.
Copyright: © 2012-2013 Matthias Dondorff, Copyright © 2012-2016 Sönke Ludwig
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Matthias Dondorff, Sönke Ludwig
*/
module dub.commandline;
import dub.compilers.compiler;
import dub.dependency;
import dub.dub;
import dub.generators.generator;
import dub.internal.vibecompat.core.file;
import dub.internal.vibecompat.data.json;
import dub.internal.vibecompat.inet.path;
import dub.internal.logging;
import dub.package_;
import dub.packagemanager;
import dub.packagesuppliers;
import dub.project;
import dub.internal.utils : getDUBVersion, getClosestMatch, getTempFile;
import dub.internal.dyaml.stdsumtype;
import std.algorithm;
import std.array;
import std.conv;
import std.encoding;
import std.exception;
static import std.file;
import std.getopt;
import std.path : absolutePath, buildNormalizedPath, expandTilde, setExtension;
import std.process : environment, spawnProcess, wait;
import std.stdio;
import std.string;
import std.typecons : Tuple, tuple;
/** Retrieves a list of all available commands.
Commands are grouped by category.
*/
CommandGroup[] getCommands() @safe pure nothrow
{
return [
CommandGroup("Package creation",
new InitCommand
),
CommandGroup("Build, test and run",
new RunCommand,
new BuildCommand,
new TestCommand,
new LintCommand,
new GenerateCommand,
new DescribeCommand,
new CleanCommand,
new DustmiteCommand
),
CommandGroup("Package management",
new FetchCommand,
new AddCommand,
new RemoveCommand,
new UpgradeCommand,
new AddPathCommand,
new RemovePathCommand,
new AddLocalCommand,
new RemoveLocalCommand,
new ListCommand,
new SearchCommand,
new AddOverrideCommand,
new RemoveOverrideCommand,
new ListOverridesCommand,
new CleanCachesCommand,
new ConvertCommand,
)
];
}
/** Extract the command name from the argument list
Params:
args = a list of string arguments that will be processed
Returns:
The command name that was found (may be null).
*/
string commandNameArgument(ref string[] args)
{
if (args.length >= 1 && !args[0].startsWith("-") && !args[0].canFind(":")) {
const result = args[0];
args = args[1 .. $];
return result;
}
return null;
}
/// test extractCommandNameArgument usage
unittest {
{
string[] args;
/// It returns an empty string on when there are no args
assert(commandNameArgument(args) is null);
assert(!args.length);
}
{
string[] args = [ "test" ];
/// It returns the first argument when it does not start with `-`
assert(commandNameArgument(args) == "test");
/// There is nothing to extract when the arguments only contain the `test` cmd
assert(!args.length);
}
{
string[] args = [ "-a", "-b" ];
/// It extracts two arguments when they are not a command
assert(commandNameArgument(args) is null);
assert(args == ["-a", "-b"]);
}
{
string[] args = [ "-test" ];
/// It returns the an empty string when it starts with `-`
assert(commandNameArgument(args) is null);
assert(args.length == 1);
}
{
string[] args = [ "foo:bar" ];
// Sub package names are ignored as command names
assert(commandNameArgument(args) is null);
assert(args.length == 1);
args[0] = ":foo";
assert(commandNameArgument(args) is null);
assert(args.length == 1);
}
}
/** Handles the Command Line options and commands.
*/
struct CommandLineHandler
{
/// The list of commands that can be handled
CommandGroup[] commandGroups;
/// General options parser
CommonOptions options;
/** Create the list of all supported commands
Returns:
Returns the list of the supported command names
*/
string[] commandNames()
{
return commandGroups.map!(g => g.commands).joiner.map!(c => c.name).array;
}
/** Parses the general options and sets up the log level
and the root_path
*/
string[] prepareOptions(CommandArgs args) {
LogLevel loglevel = LogLevel.info;
options.prepare(args);
if (options.vverbose) loglevel = LogLevel.debug_;
else if (options.verbose) loglevel = LogLevel.diagnostic;
else if (options.vquiet) loglevel = LogLevel.none;
else if (options.quiet) loglevel = LogLevel.warn;
else if (options.verror) loglevel = LogLevel.error;
setLogLevel(loglevel);
if (options.root_path.empty)
{
options.root_path = std.file.getcwd();
}
else
{
options.root_path = options.root_path.expandTilde.absolutePath.buildNormalizedPath;
}
final switch (options.colorMode) with (options.Color)
{
case automatic:
// Use default determined in internal.logging.initLogging().
break;
case on:
foreach (ref grp; commandGroups)
foreach (ref cmd; grp.commands)
if (auto pc = cast(PackageBuildCommand)cmd)
pc.baseSettings.buildSettings.options |= BuildOption.color;
setLoggingColorsEnabled(true); // enable colors, no matter what
break;
case off:
foreach (ref grp; commandGroups)
foreach (ref cmd; grp.commands)
if (auto pc = cast(PackageBuildCommand)cmd)
pc.baseSettings.buildSettings.options &= ~BuildOption.color;
setLoggingColorsEnabled(false); // disable colors, no matter what
break;
}
return args.extractAllRemainingArgs();
}
/** Get an instance of the requested command.
If there is no command in the argument list, the `run` command is returned
by default.
If the `--help` argument previously handled by `prepareOptions`,
`this.options.help` is already `true`, with this returning the requested
command. If no command was requested (just dub --help) this returns the
help command.
Params:
name = the command name
Returns:
Returns the command instance if it exists, null otherwise
*/
Command getCommand(string name) {
if (name == "help" || (name == "" && options.help))
{
return new HelpCommand();
}
if (name == "")
{
name = "run";
}
foreach (grp; commandGroups)
foreach (c; grp.commands)
if (c.name == name) {
return c;
}
return null;
}
/** Get an instance of the requested command after the args are sent.
It uses getCommand to get the command instance and then calls prepare.
Params:
name = the command name
args = the command arguments
Returns:
Returns the command instance if it exists, null otherwise
*/
Command prepareCommand(string name, CommandArgs args) {
auto cmd = getCommand(name);
if (cmd !is null && !(cast(HelpCommand)cmd))
{
// process command line options for the selected command
cmd.prepare(args);
enforceUsage(cmd.acceptsAppArgs || !args.hasAppArgs, name ~ " doesn't accept application arguments.");
}
return cmd;
}
}
/// Can get the command names
unittest {
CommandLineHandler handler;
handler.commandGroups = getCommands();
assert(handler.commandNames == ["init", "run", "build", "test", "lint", "generate",
"describe", "clean", "dustmite", "fetch", "add", "remove",
"upgrade", "add-path", "remove-path", "add-local", "remove-local", "list", "search",
"add-override", "remove-override", "list-overrides", "clean-caches", "convert"]);
}
/// It sets the cwd as root_path by default
unittest {
CommandLineHandler handler;
auto args = new CommandArgs([]);
handler.prepareOptions(args);
assert(handler.options.root_path == std.file.getcwd());
}
/// It can set a custom root_path
unittest {
CommandLineHandler handler;
auto args = new CommandArgs(["--root=/tmp/test"]);
handler.prepareOptions(args);
assert(handler.options.root_path == "/tmp/test".absolutePath.buildNormalizedPath);
args = new CommandArgs(["--root=./test"]);
handler.prepareOptions(args);
assert(handler.options.root_path == "./test".absolutePath.buildNormalizedPath);
}
/// It sets the info log level by default
unittest {
scope(exit) setLogLevel(LogLevel.info);
CommandLineHandler handler;
auto args = new CommandArgs([]);
handler.prepareOptions(args);
assert(getLogLevel() == LogLevel.info);
}
/// It can set a custom error level
unittest {
scope(exit) setLogLevel(LogLevel.info);
CommandLineHandler handler;
auto args = new CommandArgs(["--vverbose"]);
handler.prepareOptions(args);
assert(getLogLevel() == LogLevel.debug_);
handler = CommandLineHandler();
args = new CommandArgs(["--verbose"]);
handler.prepareOptions(args);
assert(getLogLevel() == LogLevel.diagnostic);
handler = CommandLineHandler();
args = new CommandArgs(["--vquiet"]);
handler.prepareOptions(args);
assert(getLogLevel() == LogLevel.none);
handler = CommandLineHandler();
args = new CommandArgs(["--quiet"]);
handler.prepareOptions(args);
assert(getLogLevel() == LogLevel.warn);
handler = CommandLineHandler();
args = new CommandArgs(["--verror"]);
handler.prepareOptions(args);
assert(getLogLevel() == LogLevel.error);
}
/// It returns the `run` command by default
unittest {
CommandLineHandler handler;
handler.commandGroups = getCommands();
assert(handler.getCommand("").name == "run");
}
/// It returns the `help` command when there is none set and the --help arg
/// was set
unittest {
CommandLineHandler handler;
auto args = new CommandArgs(["--help"]);
handler.prepareOptions(args);
handler.commandGroups = getCommands();
assert(cast(HelpCommand)handler.getCommand("") !is null);
}
/// It returns the `help` command when the `help` command is sent
unittest {
CommandLineHandler handler;
handler.commandGroups = getCommands();
assert(cast(HelpCommand) handler.getCommand("help") !is null);
}
/// It returns the `init` command when the `init` command is sent
unittest {
CommandLineHandler handler;
handler.commandGroups = getCommands();
assert(handler.getCommand("init").name == "init");
}
/// It returns null when a missing command is sent
unittest {
CommandLineHandler handler;
handler.commandGroups = getCommands();
assert(handler.getCommand("missing") is null);
}
/** Processes the given command line and executes the appropriate actions.
Params:
args = This command line argument array as received in `main`. The first
entry is considered to be the name of the binary invoked.
Returns:
Returns the exit code that is supposed to be returned to the system.
*/
int runDubCommandLine(string[] args)
{
static string[] toSinglePackageArgs (string args0, string file, string[] trailing)
{
return [args0, "run", "-q", "--temp-build", "--single", file, "--"] ~ trailing;
}
// Initialize the logging module, ensure that whether stdout/stderr are a TTY
// or not is detected in order to disable colors if the output isn't a console
initLogging();
logDiagnostic("DUB version %s", getDUBVersion());
{
version(Windows) {
// Guarantee that this environment variable is set
// this is specifically needed because of the Windows fix that follows this statement.
// While it probably isn't needed for all targets, it does simplify things a bit.
// Question is can it be more generic? Probably not due to $TMP
if ("TEMP" !in environment)
environment["TEMP"] = std.file.tempDir();
// rdmd uses $TEMP to compute a temporary path. since cygwin substitutes backslashes
// with slashes, this causes OPTLINK to fail (it thinks path segments are options)
// we substitute the other way around here to fix this.
// In case the environment variable TEMP is empty (it should never be), we'll swap out
// opIndex in favor of get with the fallback.
environment["TEMP"] = environment.get("TEMP", null).replace("/", "\\");
}
}
auto handler = CommandLineHandler(getCommands());
// Special syntaxes need to be handled before regular argument parsing
if (args.length >= 2)
{
// Read input source code from stdin
if (args[1] == "-")
{
auto path = getTempFile("app", ".d");
stdin.byChunk(4096).joiner.toFile(path.toNativeString());
args = toSinglePackageArgs(args[0], path.toNativeString(), args[2 .. $]);
}
// Dub has a shebang syntax to be able to use it as script, e.g.
// #/usr/bin/env dub
// With this approach, we need to support the file having
// both the `.d` extension, or having none at all.
// We also need to make sure arguments passed to the script
// are passed to the program, not `dub`, e.g.:
// ./my_dub_script foo bar
// Gives us `args = [ "dub", "./my_dub_script" "foo", "bar" ]`,
// which we need to interpret as:
// `args = [ "dub", "./my_dub_script", "--", "foo", "bar" ]`
else if (args[1].endsWith(".d"))
args = toSinglePackageArgs(args[0], args[1], args[2 .. $]);
// Here we have a problem: What if the script name is a command name ?
// We have to assume it isn't, and to reduce the risk of false positive
// we only consider the case where the file name is the first argument,
// as the shell invocation cannot be controlled.
else if (handler.getCommand(args[1]) is null && !args[1].startsWith("-")) {
if (std.file.exists(args[1])) {
auto path = getTempFile("app", ".d");
std.file.copy(args[1], path.toNativeString());
args = toSinglePackageArgs(args[0], path.toNativeString(), args[2 .. $]);
} else if (std.file.exists(args[1].setExtension(".d"))) {
args = toSinglePackageArgs(args[0], args[1].setExtension(".d"), args[2 .. $]);
}
}
}
auto common_args = new CommandArgs(args[1..$]);
try
args = handler.prepareOptions(common_args);
catch (Exception e) {
logError("Error processing arguments: %s", e.msg);
logDiagnostic("Full exception: %s", e.toString().sanitize);
logInfo("Run 'dub help' for usage information.");
return 1;
}
if (handler.options.version_)
{
showVersion();
return 0;
}
const command_name = commandNameArgument(args);
auto command_args = new CommandArgs(args);
Command cmd;
try {
cmd = handler.prepareCommand(command_name, command_args);
} catch (Exception e) {
logError("Error processing arguments: %s", e.msg);
logDiagnostic("Full exception: %s", e.toString().sanitize);
logInfo("Run 'dub help' for usage information.");
return 1;
}
if (cmd is null) {
logInfoNoTag("USAGE: dub [--version] [<command>] [<options...>] [-- [<application arguments...>]]");
logInfoNoTag("");
logError("Unknown command: %s", command_name);
import std.algorithm.iteration : filter;
import std.uni : toUpper;
foreach (CommandGroup key; handler.commandGroups)
{
auto similarCommands = key.commands.filter!(cmd => levenshteinDistance(command_name, cmd.name) < 4).array();
if (similarCommands) {
sort!((a, b) => levenshteinDistance(command_name, a.name) < levenshteinDistance(
command_name, b.name))(similarCommands);
foreach (command; similarCommands) {
logInfo("Did you mean '%s'?", command.name);
}
}
}
logInfoNoTag("");
return 1;
}
if (cast(HelpCommand)cmd !is null) {
showHelp(handler.commandGroups, common_args);
return 0;
}
if (handler.options.help) {
showCommandHelp(cmd, command_args, common_args);
return 0;
}
auto remaining_args = command_args.extractRemainingArgs();
if (remaining_args.any!(a => a.startsWith("-"))) {
logError("Unknown command line flags: %s", remaining_args.filter!(a => a.startsWith("-")).array.join(" ").color(Mode.bold));
logInfo(`Type "%s" to get a list of all supported flags.`, text("dub ", cmd.name, " -h").color(Mode.bold));
return 1;
}
try {
// initialize the root package
Dub dub = cmd.prepareDub(handler.options);
// execute the command
return cmd.execute(dub, remaining_args, command_args.appArgs);
}
catch (UsageException e) {
// usage exceptions get thrown before any logging, so we are
// making the errors more narrow to better fit on small screens.
tagWidth.push(5);
logError("%s", e.msg);
logDebug("Full exception: %s", e.toString().sanitize);
logInfo(`Run "%s" for more information about the "%s" command.`,
text("dub ", cmd.name, " -h").color(Mode.bold), cmd.name.color(Mode.bold));
return 1;
}
catch (Exception e) {
// most exceptions get thrown before logging, so same thing here as
// above. However this might be subject to change if it results in
// weird behavior anywhere.
tagWidth.push(5);
logError("%s", e.msg);
logDebug("Full exception: %s", e.toString().sanitize);
return 2;
}
}
/** Contains and parses options common to all commands.
*/
struct CommonOptions {
bool verbose, vverbose, quiet, vquiet, verror, version_;
bool help, annotate, bare;
string[] registry_urls;
string root_path, recipeFile;
enum Color { automatic, on, off }
Color colorMode = Color.automatic;
SkipPackageSuppliers skipRegistry = SkipPackageSuppliers.none;
PlacementLocation placementLocation = PlacementLocation.user;
deprecated("Use `Color` instead, the previous naming was a limitation of error message formatting")
alias color = Color;
deprecated("Use `colorMode` instead")
alias color_mode = colorMode;
private void parseColor(string option, string value) @safe
{
// `automatic`, `on`, `off` are there for backwards compatibility
// `auto`, `always`, `never` is being used for compatibility with most
// other development and linux tools, after evaluating what other tools
// are doing, to help users intuitively pick correct values.
// See https://github.com/dlang/dub/issues/2410 for discussion
if (!value.length || value == "auto" || value == "automatic")
colorMode = Color.automatic;
else if (value == "always" || value == "on")
colorMode = Color.on;
else if (value == "never" || value == "off")
colorMode = Color.off;
else
throw new ConvException("Unable to parse argument '--" ~ option ~ "=" ~ value
~ "', supported values: --color[=auto], --color=always, --color=never");
}
/// Parses all common options and stores the result in the struct instance.
void prepare(CommandArgs args)
{
args.getopt("h|help", &help, ["Display general or command specific help"]);
args.getopt("root", &root_path, ["Path to operate in instead of the current working dir"]);
args.getopt("recipe", &recipeFile, ["Loads a custom recipe path instead of dub.json/dub.sdl"]);
args.getopt("registry", ®istry_urls, [
"Search the given registry URL first when resolving dependencies. Can be specified multiple times. Available registry types:",
" DUB: URL to DUB registry (default)",
" Maven: URL to Maven repository + group id containing dub packages as artifacts. E.g. mvn+http://localhost:8040/maven/libs-release/dubpackages",
]);
args.getopt("skip-registry", &skipRegistry, [
"Sets a mode for skipping the search on certain package registry types:",
" none: Search all configured or default registries (default)",
" standard: Don't search the main registry (e.g. "~defaultRegistryURLs[0]~")",
" configured: Skip all default and user configured registries",
" all: Only search registries specified with --registry",
]);
args.getopt("annotate", &annotate, ["Do not perform any action, just print what would be done"]);
args.getopt("bare", &bare, ["Read only packages contained in the current directory"]);
args.getopt("v|verbose", &verbose, ["Print diagnostic output"]);
args.getopt("vverbose", &vverbose, ["Print debug output"]);
args.getopt("q|quiet", &quiet, ["Only print warnings and errors"]);
args.getopt("verror", &verror, ["Only print errors"]);
args.getopt("vquiet", &vquiet, ["Print no messages"]);
args.getopt("color", &colorMode, &parseColor, [
"Configure colored output. Accepted values:",
" auto: Colored output on console/terminal,",
" unless NO_COLOR is set and non-empty (default)",
" always: Force colors enabled",
" never: Force colors disabled"
]);
args.getopt("cache", &placementLocation, ["Puts any fetched packages in the specified location [local|system|user]."]);
version_ = args.hasAppVersion;
}
}
/** Encapsulates a set of application arguments.
This class serves two purposes. The first is to provide an API for parsing
command line arguments (`getopt`). At the same time it records all calls
to `getopt` and provides a list of all possible options using the
`recognizedArgs` property.
*/
class CommandArgs {
struct Arg {
alias Value = SumType!(string[], string, bool, int, uint);
Value defaultValue;
Value value;
string names;
string[] helpText;
bool hidden;
}
private {
string[] m_args;
Arg[] m_recognizedArgs;
string[] m_appArgs;
}
/** Initializes the list of source arguments.
Note that all array entries are considered application arguments (i.e.
no application name entry is present as the first entry)
*/
this(string[] args) @safe pure nothrow
{
auto app_args_idx = args.countUntil("--");
m_appArgs = app_args_idx >= 0 ? args[app_args_idx+1 .. $] : [];
m_args = "dummy" ~ (app_args_idx >= 0 ? args[0..app_args_idx] : args);
}
/** Checks if the app arguments are present.
Returns:
true if an -- argument is given with arguments after it, otherwise false
*/
@property bool hasAppArgs() { return m_appArgs.length > 0; }
/** Checks if the `--version` argument is present on the first position in
the list.
Returns:
true if the application version argument was found on the first position
*/
@property bool hasAppVersion() { return m_args.length > 1 && m_args[1] == "--version"; }
/** Returns the list of app args.
The app args are provided after the `--` argument.
*/
@property string[] appArgs() { return m_appArgs; }
/** Returns the list of all options recognized.
This list is created by recording all calls to `getopt`.
*/
@property const(Arg)[] recognizedArgs() { return m_recognizedArgs; }
void getopt(T)(string names, T* var, string[] help_text = null, bool hidden=false)
{
getopt!T(names, var, null, help_text, hidden);
}
void getopt(T)(string names, T* var, void delegate(string, string) @safe parseValue, string[] help_text = null, bool hidden=false)
{
import std.traits : OriginalType;
foreach (ref arg; m_recognizedArgs)
if (names == arg.names) {
assert(help_text is null, format!("Duplicated argument '%s' must not change helptext, consider to remove the duplication")(names));
*var = arg.value.match!(
(OriginalType!T v) => cast(T)v,
(_) {
if (false)
return T.init;
assert(false, "value from previous getopt has different type than the current getopt call");
}
);
return;
}
assert(help_text.length > 0);
Arg arg;
arg.defaultValue = cast(OriginalType!T)*var;
arg.names = names;
arg.helpText = help_text;
arg.hidden = hidden;
if (parseValue is null)
m_args.getopt(config.passThrough, names, var);
else
m_args.getopt(config.passThrough, names, parseValue);
arg.value = cast(OriginalType!T)*var;
m_recognizedArgs ~= arg;
}
/** Resets the list of available source arguments.
*/
void dropAllArgs()
{
m_args = null;
}
/** Returns the list of unprocessed arguments, ignoring the app arguments,
and resets the list of available source arguments.
*/
string[] extractRemainingArgs()
{
assert(m_args !is null, "extractRemainingArgs must be called only once.");
auto ret = m_args[1 .. $];
m_args = null;
return ret;
}
/** Returns the list of unprocessed arguments, including the app arguments
and resets the list of available source arguments.
*/
string[] extractAllRemainingArgs()
{
auto ret = extractRemainingArgs();
if (this.hasAppArgs)
{
ret ~= "--" ~ m_appArgs;
}
return ret;
}
}
/// Using CommandArgs
unittest {
/// It should not find the app version for an empty arg list
assert(new CommandArgs([]).hasAppVersion == false);
/// It should find the app version when `--version` is the first arg
assert(new CommandArgs(["--version"]).hasAppVersion == true);
/// It should not find the app version when `--version` is the second arg
assert(new CommandArgs(["a", "--version"]).hasAppVersion == false);
/// It returns an empty app arg list when `--` arg is missing
assert(new CommandArgs(["1", "2"]).appArgs == []);
/// It returns an empty app arg list when `--` arg is missing
assert(new CommandArgs(["1", "2"]).appArgs == []);
/// It returns app args set after "--"
assert(new CommandArgs(["1", "2", "--", "a"]).appArgs == ["a"]);
assert(new CommandArgs(["1", "2", "--"]).appArgs == []);
assert(new CommandArgs(["--"]).appArgs == []);
assert(new CommandArgs(["--", "a"]).appArgs == ["a"]);
/// It returns the list of all args when no args are processed
assert(new CommandArgs(["1", "2", "--", "a"]).extractAllRemainingArgs == ["1", "2", "--", "a"]);
}
/// It removes the extracted args
unittest {
auto args = new CommandArgs(["-a", "-b", "--", "-c"]);
bool value;
args.getopt("b", &value, [""]);
assert(args.extractAllRemainingArgs == ["-a", "--", "-c"]);
}
/// It should not be able to remove app args
unittest {
auto args = new CommandArgs(["-a", "-b", "--", "-c"]);
bool value;
args.getopt("-c", &value, [""]);
assert(!value);
assert(args.extractAllRemainingArgs == ["-a", "-b", "--", "-c"]);
}
/** Base class for all commands.
This cass contains a high-level description of the command, including brief
and full descriptions and a human readable command line pattern. On top of
that it defines the two main entry functions for command execution.
*/
class Command {
string name;
string argumentsPattern;
string description;
string[] helpText;
bool acceptsAppArgs;
bool hidden = false; // used for deprecated commands
/** Parses all known command line options without executing any actions.
This function will be called prior to execute, or may be called as
the only method when collecting the list of recognized command line
options.
Only `args.getopt` should be called within this method.
*/
abstract void prepare(scope CommandArgs args);
/**
* Initialize the dub instance used by `execute`
*/
public Dub prepareDub(CommonOptions options) {
Dub dub;
if (options.bare) {
dub = new Dub(NativePath(options.root_path), getWorkingDirectory());
dub.defaultPlacementLocation = options.placementLocation;
return dub;
}
// initialize DUB
auto package_suppliers = options.registry_urls
.map!((url) {
// Allow to specify fallback mirrors as space separated urls. Undocumented as we
// should simply retry over all registries instead of using a special
// FallbackPackageSupplier.
auto urls = url.splitter(' ');
PackageSupplier ps = getRegistryPackageSupplier(urls.front);
urls.popFront;
if (!urls.empty)
ps = new FallbackPackageSupplier(ps ~ urls.map!getRegistryPackageSupplier.array);
return ps;
})
.array;
dub = new Dub(options.root_path, package_suppliers, options.skipRegistry);
dub.dryRun = options.annotate;
dub.defaultPlacementLocation = options.placementLocation;
dub.mainRecipePath = options.recipeFile;
// make the CWD package available so that for example sub packages can reference their
// parent package.
try dub.packageManager.getOrLoadPackage(NativePath(options.root_path), NativePath(options.recipeFile), false, StrictMode.Warn);
catch (Exception e) {
// by default we ignore CWD package load fails in prepareDUB, since
// they will fail again later when they are actually requested. This
// is done to provide custom options to the loading logic and should
// ideally be moved elsewhere. (This catch has been around since 10
// years when it was first introduced in _app.d_)
logDiagnostic("No valid package found in current working directory: %s", e.msg);
// for now, we work around not knowing if the package is needed or
// not, simply by trusting the user to only use `--recipe` when the
// recipe file actually exists, otherwise we throw the error.
bool loadMustSucceed = options.recipeFile.length > 0;
if (loadMustSucceed)
throw e;
}
return dub;
}
/** Executes the actual action.
Note that `prepare` will be called before any call to `execute`.
*/
abstract int execute(Dub dub, string[] free_args, string[] app_args);
private bool loadCwdPackage(Dub dub, bool warn_missing_package)
{
auto filePath = dub.packageManager.findPackageFile(dub.rootPath);
if (filePath.empty) {
if (warn_missing_package) {
logInfoNoTag("");
logInfoNoTag("No package manifest (dub.json or dub.sdl) was found in");
logInfoNoTag(dub.rootPath.toNativeString());
logInfoNoTag("Please run DUB from the root directory of an existing package, or run");
logInfoNoTag("\"%s\" to get information on creating a new package.", "dub init --help".color(Mode.bold));
logInfoNoTag("");
}
return false;
}
dub.loadPackage();
return true;
}
}
/** Encapsulates a group of commands that fit into a common category.
*/
struct CommandGroup {
/// Caption of the command category
string caption;
/// List of commands contained in this group
Command[] commands;
this(string caption, Command[] commands...) @safe pure nothrow
{
this.caption = caption;
this.commands = commands.dup;
}
}
/******************************************************************************/
/* HELP */
/******************************************************************************/
class HelpCommand : Command {
this() @safe pure nothrow
{
this.name = "help";
this.description = "Shows the help message";
this.helpText = [
"Shows the help message and the supported command options."
];
}
/// HelpCommand.prepare is not supposed to be called, use
/// cast(HelpCommand)this to check if help was requested before execution.
override void prepare(scope CommandArgs args)
{
assert(false, "HelpCommand.prepare is not supposed to be called, use cast(HelpCommand)this to check if help was requested before execution.");
}
/// HelpCommand.execute is not supposed to be called, use
/// cast(HelpCommand)this to check if help was requested before execution.
override int execute(Dub dub, string[] free_args, string[] app_args) {
assert(false, "HelpCommand.execute is not supposed to be called, use cast(HelpCommand)this to check if help was requested before execution.");
}
}
/******************************************************************************/
/* INIT */
/******************************************************************************/
class InitCommand : Command {
private{
string m_templateType = "minimal";
PackageFormat m_format = PackageFormat.json;
bool m_nonInteractive;
}
this() @safe pure nothrow
{
this.name = "init";
this.argumentsPattern = "[<directory> [<dependency>...]]";
this.description = "Initializes an empty package skeleton";
this.helpText = [
"Initializes an empty package of the specified type in the given directory.",
"By default, the current working directory is used.",
"",
"Custom templates can be defined by packages by providing a sub-package called \"init-exec\". No default source files are added in this case.",
"The \"init-exec\" sub-package is compiled and executed inside the destination folder after the base project directory has been created.",
"Free arguments \"dub init -t custom -- free args\" are passed into the \"init-exec\" sub-package as app arguments."
];
this.acceptsAppArgs = true;
}
override void prepare(scope CommandArgs args)
{
args.getopt("t|type", &m_templateType, [
"Set the type of project to generate. Available types:",
"",
"minimal - simple \"hello world\" project (default)",
"vibe.d - minimal HTTP server based on vibe.d",
"deimos - skeleton for C header bindings",
"custom - custom project provided by dub package",
]);