-
Notifications
You must be signed in to change notification settings - Fork 212
/
SystemRegistryImpl.java
1919 lines (1765 loc) · 72.2 KB
/
SystemRegistryImpl.java
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
/*
* Copyright (c) 2002-2020, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* https://opensource.org/licenses/BSD-3-Clause
*/
package org.jline.console.impl;
import static org.jline.keymap.KeyMap.ctrl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jline.builtins.Completers.FilesCompleter;
import org.jline.builtins.Completers.OptDesc;
import org.jline.builtins.Completers.OptionCompleter;
import org.jline.builtins.ConfigurationPath;
import org.jline.builtins.Options;
import org.jline.builtins.Styles;
import org.jline.builtins.Options.HelpException;
import org.jline.console.*;
import org.jline.console.ConsoleEngine.ExecutionResult;
import org.jline.reader.*;
import org.jline.reader.Parser.ParseContext;
import org.jline.reader.impl.completer.AggregateCompleter;
import org.jline.reader.impl.completer.ArgumentCompleter;
import org.jline.reader.impl.completer.NullCompleter;
import org.jline.reader.impl.completer.StringsCompleter;
import org.jline.reader.impl.completer.SystemCompleter;
import org.jline.terminal.Attributes;
import org.jline.terminal.Attributes.InputFlag;
import org.jline.utils.*;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
/**
* Aggregate command registries.
*
* @author <a href="mailto:matti.rintanikkola@gmail.com">Matti Rinta-Nikkola</a>
*/
public class SystemRegistryImpl implements SystemRegistry {
public enum Pipe {
FLIP, NAMED, AND, OR
}
private static final Class<?>[] BUILTIN_REGISTRIES = { Builtins.class, ConsoleEngineImpl.class };
private CommandRegistry[] commandRegistries;
private Integer consoleId;
private final Parser parser;
private final ConfigurationPath configPath;
private final Map<String,CommandRegistry> subcommands = new HashMap<>();
private final Map<Pipe, String> pipeName = new HashMap<>();
private final Map<String, CommandMethods> commandExecute = new HashMap<>();
private final Map<String, List<String>> commandInfos = new HashMap<>();
private Exception exception;
private final CommandOutputStream outputStream;
private ScriptStore scriptStore = new ScriptStore();
private NamesAndValues names = new NamesAndValues();
private final Supplier<Path> workDir;
private final SystemCompleter customSystemCompleter = new SystemCompleter();
private final AggregateCompleter customAggregateCompleter = new AggregateCompleter(new ArrayList<>());
private boolean commandGroups = true;
private Function<CmdLine,CmdDesc> scriptDescription;
public SystemRegistryImpl(Parser parser, Terminal terminal, Supplier<Path> workDir, ConfigurationPath configPath) {
this.parser = parser;
this.workDir = workDir;
this.configPath = configPath;
outputStream = new CommandOutputStream(terminal);
pipeName.put(Pipe.FLIP, "|;");
pipeName.put(Pipe.NAMED, "|");
pipeName.put(Pipe.AND, "&&");
pipeName.put(Pipe.OR, "||");
commandExecute.put("exit", new CommandMethods(this::exit, this::exitCompleter));
commandExecute.put("help", new CommandMethods(this::help, this::helpCompleter));
}
public void rename(Pipe pipe, String name) {
if (name.matches("/w+") || pipeName.containsValue(name)) {
throw new IllegalArgumentException();
}
pipeName.put(pipe, name);
}
@Override
public Collection<String> getPipeNames() {
return pipeName.values();
}
@Override
public void setCommandRegistries(CommandRegistry... commandRegistries) {
this.commandRegistries = commandRegistries;
for (int i = 0; i < commandRegistries.length; i++) {
if (commandRegistries[i] instanceof ConsoleEngine) {
if (consoleId != null) {
throw new IllegalArgumentException();
} else {
this.consoleId = i;
((ConsoleEngine) commandRegistries[i]).setSystemRegistry(this);
this.scriptStore = new ScriptStore((ConsoleEngine)commandRegistries[i]);
this.names = new NamesAndValues(configPath);
}
} else if (commandRegistries[i] instanceof SystemRegistry) {
throw new IllegalArgumentException();
}
}
SystemRegistry.add(this);
}
@Override
public void initialize(File script) {
if (consoleId != null) {
try {
consoleEngine().execute(script);
} catch (Exception e) {
trace(e);
}
}
}
@Override
public Set<String> commandNames() {
Set<String> out = new HashSet<>();
for (CommandRegistry r : commandRegistries) {
out.addAll(r.commandNames());
}
out.addAll(localCommandNames());
return out;
}
private Set<String> localCommandNames() {
return commandExecute.keySet();
}
@Override
public Map<String, String> commandAliases() {
Map<String, String> out = new HashMap<>();
for (CommandRegistry r : commandRegistries) {
out.putAll(r.commandAliases());
}
return out;
}
@Override
public Object consoleOption(String name) {
Object out = null;
if (consoleId != null) {
out = consoleEngine().consoleOption(name, null);
}
return out;
}
/**
* Register subcommand registry
* @param command main command
* @param subcommandRegistry subcommand registry
*/
@Override
public void register(String command, CommandRegistry subcommandRegistry) {
subcommands.put(command, subcommandRegistry);
commandExecute.put(command, new CommandMethods(this::subcommand, this::emptyCompleter));
}
private List<String> localCommandInfo(String command) {
try {
if (subcommands.containsKey(command)) {
registryHelp(subcommands.get(command));
} else {
localExecute(command, new String[] { "--help" });
}
} catch (HelpException e) {
exception = null;
return JlineCommandRegistry.compileCommandInfo(e.getMessage());
} catch (Exception e) {
trace(e);
}
return new ArrayList<>();
}
@Override
public List<String> commandInfo(String command) {
int id = registryId(command);
List<String> out = new ArrayList<>();
if (id > -1) {
if (!commandInfos.containsKey(command)) {
commandInfos.put(command, commandRegistries[id].commandInfo(command));
}
out = commandInfos.get(command);
} else if (scriptStore.hasScript(command) && consoleEngine() != null) {
out = consoleEngine().commandInfo(command);
} else if (isLocalCommand(command)) {
out = localCommandInfo(command);
}
return out;
}
@Override
public boolean hasCommand(String command) {
return registryId(command) > -1 || isLocalCommand(command);
}
public void setGroupCommandsInHelp(boolean commandGroups) {
this.commandGroups = commandGroups;
}
public SystemRegistryImpl groupCommandsInHelp(boolean commandGroups) {
this.commandGroups = commandGroups;
return this;
}
private boolean isLocalCommand(String command) {
return commandExecute.containsKey(command);
}
@Override
public boolean isCommandOrScript(ParsedLine line) {
return isCommandOrScript(parser.getCommand(line.words().get(0)));
}
@Override
public boolean isCommandOrScript(String command) {
if (hasCommand(command)) {
return true;
}
return scriptStore.hasScript(command);
}
public void addCompleter(Completer completer) {
if (completer instanceof SystemCompleter) {
SystemCompleter sc = (SystemCompleter)completer;
if (sc.isCompiled()) {
customAggregateCompleter.getCompleters().add(sc);
} else {
customSystemCompleter.add(sc);
}
} else {
customAggregateCompleter.getCompleters().add(completer);
}
}
@Override
public SystemCompleter compileCompleters() {
throw new IllegalStateException("Use method completer() to retrieve Completer!");
}
private SystemCompleter _compileCompleters() {
SystemCompleter out = CommandRegistry.aggregateCompleters(commandRegistries);
SystemCompleter local = new SystemCompleter();
for (String command : commandExecute.keySet()) {
if (subcommands.containsKey(command)) {
for(Map.Entry<String,List<Completer>> entry : subcommands.get(command).compileCompleters().getCompleters().entrySet()) {
for (Completer cc : entry.getValue()) {
if (!(cc instanceof ArgumentCompleter)) {
throw new IllegalArgumentException();
}
List<Completer> cmps = ((ArgumentCompleter)cc).getCompleters();
cmps.add(0, NullCompleter.INSTANCE);
cmps.set(1, new StringsCompleter(entry.getKey()));
Completer last = cmps.get(cmps.size() - 1);
if (last instanceof OptionCompleter) {
((OptionCompleter)last).setStartPos(cmps.size() - 1);
cmps.set(cmps.size() - 1, last);
}
local.add(command, new ArgumentCompleter(cmps));
}
}
} else {
local.add(command, commandExecute.get(command).compileCompleter().apply(command));
}
}
local.add(customSystemCompleter);
out.add(local);
out.compile();
return out;
}
@Override
public Completer completer() {
List<Completer> completers = new ArrayList<>();
completers.add(_compileCompleters());
completers.add(customAggregateCompleter);
if (consoleId != null) {
completers.addAll(consoleEngine().scriptCompleters());
completers.add(new PipelineCompleter(workDir, pipeName, names).doCompleter());
}
return new AggregateCompleter(completers);
}
private CmdDesc localCommandDescription(String command) {
if (!isLocalCommand(command)) {
throw new IllegalArgumentException();
}
try {
localExecute(command, new String[] { "--help" });
} catch (HelpException e) {
exception = null;
return JlineCommandRegistry.compileCommandDescription(e.getMessage());
} catch (Exception e) {
trace(e);
}
return null;
}
@Override
public CmdDesc commandDescription(List<String> args) {
CmdDesc out = new CmdDesc(false);
String command = args.get(0);
int id = registryId(command);
if (id > -1) {
out = commandRegistries[id].commandDescription(args);
} else if (scriptStore.hasScript(command) && consoleEngine() != null) {
out = consoleEngine().commandDescription(args);
} else if (isLocalCommand(command)) {
out = localCommandDescription(command);
}
return out;
}
private CmdDesc commandDescription(CommandRegistry subreg) {
List<AttributedString> main = new ArrayList<>();
Map<String, List<AttributedString>> options = new HashMap<>();
StyleResolver helpStyle = Styles.helpStyle();
for (String sc : new TreeSet<>(subreg.commandNames())) {
for (String info : subreg.commandInfo(sc)) {
main.add(HelpException.highlightSyntax(sc + " - " + info, helpStyle, true));
break;
}
}
return new CmdDesc(main, ArgDesc.doArgNames(Collections.singletonList("")), options);
}
public void setScriptDescription(Function<CmdLine,CmdDesc> scriptDescription) {
this.scriptDescription = scriptDescription;
}
@Override
public CmdDesc commandDescription(CmdLine line) {
CmdDesc out = null;
String cmd = parser.getCommand(line.getArgs().get(0));
switch (line.getDescriptionType()) {
case COMMAND:
if (isCommandOrScript(cmd) && !names.hasPipes(line.getArgs())) {
List<String> args = line.getArgs();
if (subcommands.containsKey(cmd)) {
String c = args.size() > 1 ? args.get(1) : null;
if (c == null || subcommands.get(cmd).hasCommand(c)) {
if (c != null && c.equals("help")) {
out = null;
} else if (c != null) {
out = subcommands.get(cmd).commandDescription(Collections.singletonList(c));
} else {
out = commandDescription(subcommands.get(cmd));
}
} else {
out = commandDescription(subcommands.get(cmd));
}
if (out != null) {
out.setSubcommand(true);
}
} else {
args.set(0, cmd);
out = commandDescription(args);
}
}
break;
case METHOD:
case SYNTAX:
if (!isCommandOrScript(cmd)) {
out = scriptDescription.apply(line);
}
break;
}
return out;
}
@Override
public Object invoke(String command, Object... args) throws Exception {
Object out = null;
command = ConsoleEngine.plainCommand(command);
args = args == null ? new Object[] {null} : args;
int id = registryId(command);
if (id > -1) {
out = commandRegistries[id].invoke(commandSession(), command, args);
} else if (isLocalCommand(command)) {
out = localExecute(command, args);
} else if (consoleId != null) {
out = consoleEngine().invoke(commandSession(), command, args);
}
return out;
}
private Object localExecute(String command, Object[] args) throws Exception {
if (!isLocalCommand(command)) {
throw new IllegalArgumentException();
}
Object out = commandExecute.get(command).execute()
.apply(new CommandInput(command, args, commandSession()));
if (exception != null) {
throw exception;
}
return out;
}
public Terminal terminal() {
return commandSession().terminal();
}
private CommandSession commandSession() {
return outputStream.getCommandSession();
}
private static class CommandOutputStream {
private final PrintStream origOut;
private final PrintStream origErr;
private final Terminal origTerminal;
private OutputStream outputStream;
private Terminal terminal;
private String output;
private CommandRegistry.CommandSession commandSession;
private boolean redirecting = false;
public CommandOutputStream(Terminal terminal) {
this.origOut = System.out;
this.origErr = System.err;
this.origTerminal = terminal;
this.terminal = terminal;
PrintStream ps = new PrintStream(terminal.output());
this.commandSession = new CommandRegistry.CommandSession(terminal, terminal.input(), ps, ps);
}
public void redirect() {
outputStream = new ByteArrayOutputStream();
}
public void redirect(File file, boolean append) throws IOException {
if (!file.exists()){
try {
file.createNewFile();
} catch(IOException e){
(new File(file.getParent())).mkdirs();
file.createNewFile();
}
}
outputStream = new FileOutputStream(file, append);
}
public void open() throws IOException {
if (redirecting || outputStream == null) {
return;
}
output = null;
PrintStream out = new PrintStream(outputStream);
System.setOut(out);
System.setErr(out);
String input = ctrl('X') + "q";
InputStream in = new ByteArrayInputStream(input.getBytes());
Attributes attrs = new Attributes();
if (OSUtils.IS_WINDOWS) {
attrs.setInputFlag(InputFlag.IGNCR, true);
}
try {
terminal = TerminalBuilder.builder()
.streams(in, outputStream)
.attributes(attrs)
.jna(false)
.jansi(false)
.type(Terminal.TYPE_DUMB).build();
this.commandSession = new CommandRegistry.CommandSession(terminal, terminal.input(), out, out);
redirecting = true;
} catch (IOException e) {
reset();
throw e;
}
}
public void close() {
if (!redirecting) {
return;
}
try {
terminal.flush();
if (outputStream instanceof ByteArrayOutputStream) {
output = outputStream.toString();
}
terminal.close();
} catch (Exception e) {
// ignore
}
reset();
}
private void reset() {
outputStream = null;
System.setOut(origOut);
System.setErr(origErr);
terminal = null;
terminal = origTerminal;
PrintStream ps = new PrintStream(terminal.output());
this.commandSession = new CommandRegistry.CommandSession(terminal, terminal.input(), ps, ps);
redirecting = false;
}
public CommandRegistry.CommandSession getCommandSession() {
return commandSession;
}
public String getOutput() {
return output;
}
public boolean isRedirecting() {
return redirecting;
}
public boolean isByteOutputStream() {
return outputStream instanceof ByteArrayOutputStream;
}
}
private boolean isCommandAlias(String command) {
if (consoleEngine() == null) {
return false;
}
ConsoleEngine consoleEngine = consoleEngine();
if (!parser.validCommandName(command) || !consoleEngine.hasAlias(command)) {
return false;
}
String value = consoleEngine.getAlias(command).split("\\s+")[0];
return !names.isPipe(value);
}
private String replaceCommandAlias(String variable, String command, String rawLine) {
ConsoleEngine consoleEngine = consoleEngine();
assert consoleEngine != null;
return variable == null ? rawLine.replaceFirst(command + "(\\b|$)", consoleEngine.getAlias(command))
: rawLine.replaceFirst("=" + command + "(\\b|$)", "=" + consoleEngine.getAlias(command));
}
private String replacePipeAlias(ArgsParser ap, String pipeAlias, List<String> args, Map<String,List<String>> customPipes){
ConsoleEngine consoleEngine = consoleEngine();
assert consoleEngine != null;
String alias = pipeAlias;
for (int j = 0; j < args.size(); j++) {
alias = alias.replaceAll("\\s\\$" + j + "\\b", " " + args.get(j));
alias = alias.replaceAll("\\$\\{" + j + "(|:-.*)}", args.get(j));
}
alias = alias.replaceAll("\\$\\{@}", consoleEngine.expandToList(args));
alias = alias.replaceAll("\\$@", consoleEngine.expandToList(args));
alias = alias.replaceAll("\\s+\\$\\d\\b", "");
alias = alias.replaceAll("\\s+\\$\\{\\d+}", "");
alias = alias.replaceAll("\\$\\{\\d+}", "");
Matcher matcher = Pattern.compile("\\$\\{\\d+:-(.*?)}").matcher(alias);
if (matcher.find()) {
alias = matcher.replaceAll("$1");
}
ap.parse(alias);
List<String> ws = ap.args();
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < ws.size(); i++) {
if (ws.get(i).equals(pipeName.get(Pipe.NAMED))) {
if (i + 1 < ws.size() && consoleEngine.hasAlias(ws.get(i + 1))) {
args.clear();
String innerPipe = consoleEngine.getAlias(ws.get(++i));
while (i < ws.size() - 1 && !names.isPipe(ws.get(i + 1), customPipes.keySet())) {
args.add(ws.get(++i));
}
sb.append(replacePipeAlias(ap, innerPipe, args, customPipes));
} else {
sb.append(ws.get(i)).append(' ');
}
} else {
sb.append(ws.get(i)).append(' ');
}
}
return sb.toString();
}
private void replacePipeAliases(ConsoleEngine consoleEngine, Map<String,List<String>> customPipes, ArgsParser ap) {
List<String> words = ap.args();
if (consoleEngine != null && words.contains(pipeName.get(Pipe.NAMED))) {
StringBuilder sb = new StringBuilder();
boolean trace = false;
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals(pipeName.get(Pipe.NAMED))) {
if (i + 1 < words.size() && consoleEngine.hasAlias(words.get(i + 1))) {
trace = true;
List<String> args = new ArrayList<>();
String pipeAlias = consoleEngine.getAlias(words.get(++i));
while (i < words.size() - 1 && !names.isPipe(words.get(i + 1), customPipes.keySet())) {
args.add(words.get(++i));
}
sb.append(replacePipeAlias(ap, pipeAlias, args, customPipes));
} else {
sb.append(words.get(i)).append(' ');
}
} else {
sb.append(words.get(i)).append(' ');
}
}
ap.parse(sb.toString());
if (trace) {
consoleEngine.trace(ap.line());
}
}
}
private List<CommandData> compileCommandLine(String commandLine) {
List<CommandData> out = new ArrayList<>();
ArgsParser ap = new ArgsParser(parser);
ap.parse(commandLine);
ConsoleEngine consoleEngine = consoleEngine();
Map<String,List<String>> customPipes = consoleEngine != null ? consoleEngine.getPipes() : new HashMap<>();
replacePipeAliases(consoleEngine, customPipes, ap);
List<String> words = ap.args();
String nextRawLine = ap.line();
int first = 0;
int last;
List<String> pipes = new ArrayList<>();
String pipeSource = null;
String rawLine = null;
String pipeResult = null;
if (isCommandAlias(ap.command())) {
ap.parse(replaceCommandAlias(ap.variable(), ap.command(), nextRawLine));
replacePipeAliases(consoleEngine, customPipes, ap);
nextRawLine = ap.line();
words = ap.args();
}
if (!names.hasPipes(words)) {
out.add(new CommandData(ap, false, nextRawLine, ap.variable(), null, false,""));
} else {
//
// compile pipe line
//
do {
String rawCommand = parser.getCommand(words.get(first));
String command = ConsoleEngine.plainCommand(rawCommand);
String variable = parser.getVariable(words.get(first));
if (isCommandAlias(command)) {
ap.parse(replaceCommandAlias(variable, command, nextRawLine));
replacePipeAliases(consoleEngine, customPipes, ap);
rawCommand = ap.rawCommand();
command = ap.command();
words = ap.args();
first = 0;
}
if (scriptStore.isConsoleScript(command) && !rawCommand.startsWith(":") ) {
throw new IllegalArgumentException("Commands must be used in pipes with colon prefix!");
}
last = words.size();
File file = null;
boolean append = false;
boolean pipeStart = false;
boolean skipPipe = false;
List<String> _words = new ArrayList<>();
//
// find next pipe
//
for (int i = first; i < last; i++) {
if (words.get(i).equals(">") || words.get(i).equals(">>")) {
pipes.add(words.get(i));
append = words.get(i).equals(">>");
if (i + 1 >= last) {
throw new IllegalArgumentException();
}
file = redirectFile(words.get(i + 1));
last = i + 1;
break;
} else if (consoleId == null) {
_words.add(words.get(i));
} else if (words.get(i).equals(pipeName.get(Pipe.FLIP))) {
if (variable != null || file != null || pipeResult != null || consoleId == null) {
throw new IllegalArgumentException();
}
pipes.add(words.get(i));
last = i;
variable = "_pipe" + (pipes.size() - 1);
break;
} else if (words.get(i).equals(pipeName.get(Pipe.NAMED))
|| (words.get(i).matches("^.*[^a-zA-Z0-9 ].*$") && customPipes.containsKey(words.get(i)))) {
String pipe = words.get(i);
if (pipe.equals(pipeName.get(Pipe.NAMED))) {
if (i + 1 >= last) {
throw new IllegalArgumentException("Pipe is NULL!");
}
pipe = words.get(i + 1);
if (!pipe.matches("\\w+") || !customPipes.containsKey(pipe)) {
throw new IllegalArgumentException("Unknown or illegal pipe name: " + pipe);
}
}
pipes.add(pipe);
last = i;
if (pipeSource == null) {
pipeSource = "_pipe" + (pipes.size() - 1);
pipeResult = variable;
variable = pipeSource;
pipeStart = true;
}
break;
} else if (words.get(i).equals(pipeName.get(Pipe.OR))
|| words.get(i).equals(pipeName.get(Pipe.AND))) {
if (variable != null || pipeSource != null) {
pipes.add(words.get(i));
} else if (pipes.size() > 0 && (pipes.get(pipes.size() - 1).equals(">")
|| pipes.get(pipes.size() - 1).equals(">>"))) {
pipes.remove(pipes.size() - 1);
out.get(out.size() - 1).setPipe(words.get(i));
skipPipe = true;
} else {
pipes.add(words.get(i));
pipeSource = "_pipe" + (pipes.size() - 1);
pipeResult = variable;
variable = pipeSource;
pipeStart = true;
}
last = i;
break;
} else {
_words.add(words.get(i));
}
}
if (last == words.size()) {
pipes.add("END_PIPE");
} else if (skipPipe) {
first = last + 1;
continue;
}
//
// compose pipe command
//
String subLine = last < words.size() || first > 0 ? String.join(" ", _words)
: ap.line();
if (last + 1 < words.size()) {
nextRawLine = String.join(" ", words.subList(last + 1, words.size()));
}
boolean done = true;
boolean statement = false;
List<String> arglist = new ArrayList<>();
if (_words.size() > 0) {
arglist.addAll(_words.subList(1, _words.size()));
}
if (rawLine != null || (pipes.size() > 1 && customPipes.containsKey(pipes.get(pipes.size() - 2)))) {
done = false;
if (rawLine == null) {
rawLine = pipeSource;
}
if (customPipes.containsKey(pipes.get(pipes.size() - 2))) {
List<String> fixes = customPipes.get(pipes.get(pipes.size() - 2));
if (pipes.get(pipes.size() - 2).matches("\\w+")) {
int idx = subLine.indexOf(" ");
subLine = idx > 0 ? subLine.substring(idx + 1) : "";
}
rawLine += fixes.get(0)
+ (consoleId != null ? consoleEngine().expandCommandLine(subLine) : subLine)
+ fixes.get(1);
statement = true;
}
if (pipes.get(pipes.size() - 1).equals(pipeName.get(Pipe.FLIP))
|| pipes.get(pipes.size() - 1).equals(pipeName.get(Pipe.AND))
|| pipes.get(pipes.size() - 1).equals(pipeName.get(Pipe.OR))) {
done = true;
pipeSource = null;
if (variable != null) {
rawLine = variable + " = " + rawLine;
}
}
if (last + 1 >= words.size() || file != null) {
done = true;
pipeSource = null;
if (pipeResult != null) {
rawLine = pipeResult + " = " + rawLine;
}
}
} else if (pipes.get(pipes.size() - 1).equals(pipeName.get(Pipe.FLIP)) || pipeStart) {
if (pipeStart && pipeResult != null) {
subLine = subLine.substring(subLine.indexOf("=") + 1);
}
rawLine = flipArgument(command, subLine, pipes, arglist);
rawLine = variable + "=" + rawLine;
} else {
rawLine = flipArgument(command, subLine, pipes, arglist);
}
if (done) {
//
// add composed command to return list
//
out.add(new CommandData(ap, statement, rawLine, variable, file, append, pipes.get(pipes.size() - 1)));
if (pipes.get(pipes.size() - 1).equals(pipeName.get(Pipe.AND))
|| pipes.get(pipes.size() - 1).equals(pipeName.get(Pipe.OR))) {
pipeSource = null;
pipeResult = null;
}
rawLine = null;
}
first = last + 1;
} while (first < words.size());
}
return out;
}
private File redirectFile(String name) {
File out;
if (name.equals("null")) {
out = OSUtils.IS_WINDOWS ? new File("NUL") : new File("/dev/null");
} else {
out = new File(name);
}
return out;
}
private static class ArgsParser {
private int round = 0;
private int curly = 0;
private int square = 0;
private boolean quoted;
private boolean doubleQuoted;
private String line;
private String command;
private String variable;
private List<String> args;
private final Parser parser;
public ArgsParser(Parser parser) {
this.parser = parser;
}
private void reset() {
round = 0;
curly = 0;
square = 0;
quoted = false;
doubleQuoted = false;
}
private void next(String arg) {
char prevChar = ' ';
for (int i = 0; i < arg.length(); i++) {
char c = arg.charAt(i);
if (!parser.isEscapeChar(prevChar)) {
if (!quoted && !doubleQuoted) {
if (c == '(') {
round++;
} else if (c == ')') {
round--;
} else if (c == '{') {
curly++;
} else if (c == '}') {
curly--;
} else if (c == '[') {
square++;
} else if (c == ']') {
square--;
} else if (c == '"') {
doubleQuoted = true;
} else if (c == '\'') {
quoted = true;
}
} else if (quoted && c == '\'') {
quoted = false;
} else if (doubleQuoted && c == '"') {
doubleQuoted = false;
}
}
prevChar = c;
}
}
private boolean isEnclosed() {
return round == 0 && curly == 0 && square == 0 && !quoted && !doubleQuoted;
}
public boolean isEnclosed(String arg) {
reset();
next(arg);
return isEnclosed();
}
private void enclosedArgs(List<String> words) {
args = new ArrayList<>();
reset();
boolean first = true;
StringBuilder sb = new StringBuilder();
for (String a : words) {
next(a);
if (!first) {
sb.append(" ");
}
if (isEnclosed()) {
sb.append(a);
args.add(sb.toString());
sb = new StringBuilder();
first = true;
} else {
sb.append(a);
first = false;
}
}
if (!first) {
args.add(sb.toString());
}
}
public void parse(String line) {
this.line = line;
ParsedLine pl = parser.parse(line, 0, ParseContext.SPLIT_LINE);
enclosedArgs(pl.words());
this.command = parser.getCommand(args.get(0));
if (!parser.validCommandName(command)) {
this.command = "";
}
this.variable = parser.getVariable(args.get(0));
}
public String line() {
return line;
}
public String command() {
return ConsoleEngine.plainCommand(command);
}
public String rawCommand() {
return command;
}
public String variable() {
return variable;
}
public List<String> args() {
return args;
}
private int closingQuote(String arg) {
int out = -1;
char prevChar = ' ';
for (int i = 1; i < arg.length(); i++) {
char c = arg.charAt(i);
if (!parser.isEscapeChar(prevChar)) {
if (c == arg.charAt(0)) {
out = i;
break;
}
}
prevChar = c;
}
return out;
}
private String unquote(String arg) {
if (arg.length() > 1 && (arg.startsWith("\"") && arg.endsWith("\""))
|| (arg.startsWith("'") && arg.endsWith("'"))) {
if (closingQuote(arg) == arg.length() - 1) {
return arg.substring(1, arg.length() -1);
}
}
return arg;
}
}
private String flipArgument(final String command, final String subLine, final List<String> pipes, List<String> arglist) {
String out;
if (pipes.size() > 1 && pipes.get(pipes.size() - 2).equals(pipeName.get(Pipe.FLIP))) {
String s = isCommandOrScript(command) ? "$" : "";
out = subLine + " " + s + "_pipe" + (pipes.size() - 2);
if (!command.isEmpty()) {
arglist.add(s + "_pipe" + (pipes.size() - 2));
}
} else {
out = subLine;
}
return out;
}
protected static class CommandData {
private final String rawLine;
private String command;
private String[] args;
private final File file;
private final boolean append;
private final String variable;
private String pipe;