-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathshell.d
More file actions
2387 lines (2063 loc) · 67.5 KB
/
shell.d
File metadata and controls
2387 lines (2063 loc) · 67.5 KB
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
/++
Support functions to build a custom unix-style shell.
$(PITFALL
Do NOT use this to try to sanitize, escape, or otherwise parse what another shell would do with a string! Every shell is different and this implements my rules which may differ in subtle ways from any other common shell.
If you want to use this to understand a command, also use it to execute that command so you get what you expect.
)
Some notes about this shell syntax:
$(LIST
* An "execution batch" is a set of command submitted to be run. This is typically a single command line or shell script.
* ; means "execute the current command and wait for it to complete". If it returns a non-zero errorlevel, the current execution batch is aborted.
* ;; means the same as ;, except that if it returned a non-zero errorlevel, the current batch is allowed to proceed.
* & means "execute current command in the background"
* ASCII space, tab, and newline outside of quotes are all collapsed to a single space, html style. If you want multiple commands in a single execution, use ;. Interactively, pressing enter usually means a new execution, but in a script, you need to use ; (or &, &&, or ||), not just newline, to separate commands.
)
History:
Added October 18, 2025
Bugs:
$(LIST
* a failure in a pipeline at any point should mark that command as failing, not just the first command.
* `sleep 1 && sleep 1 &` only puts the second sleep in the background.
* bash supports $'\e' which follows C escape rules inside the single quotes. want?
* ${name:use_if_unset} not implemented. might not bother.
* glob expansion is minimal - * works, but no ?, no [stuff]. The * is all i personally care about.
* `substitution` and $(...) is not implemented
* variable expansion ${IDENT} is not implemented.
* no !history recall. or history command in general
* job control is rudimentary - no fg, bg, jobs, ctrl+z, etc.
* i'd like it to automatically set -o ignoreeof in some circumstances
* prompt could be cooler
PS1 = normal prompt
PS2 = continuation prompt
Bash shell executes the content of the PROMPT_COMMAND just before displaying the PS1 variable.
bash does it with `\u` and stuff but i kinda think using `$USER` and such might make more sense.
* i do `alias thing args...` instead of `alias thing="args..."`. i kinda prefer it this way tho
* the api is not very good
* ulimit? sourcing things too. aliases.
* deeshrc is pulled from cwd
* tab complete of available commands not implemented - get it from path search.
)
Questionable_ideas:
$(LIST
* be able to receive an external command, e.g. from vim hotkey
* separate stdout and stderr more by default, allow stderr pipes.
* custom completion scripts? prolly not bash compatible since the scripts would be more involved
* some kind of scriptable cmdlet? a full on script language with shell stuff embeddable?
see https://hush-shell.github.io/cmd/index.html for some ok ideas
* do something fun with job control. idk what tho really.
* can terminal emulators get notifications when the foreground process group changes? i don't think so but i could make a "poll again now" sequence since i control shell and possibly terminal emulator now.
* change DISPLAY and such when attaching remote sessions
)
+/
module arsd.shell;
import arsd.core;
import core.thread.fiber;
/++
Holds some context needed for shell expansions.
+/
struct ShellContext {
// stuff you set to interface with OS data
string delegate(scope const(char)[] name) getEnvironmentVariable;
string delegate(scope const(char)[] username) getUserHome; // for ~ expansion. if the username is null, it should look up the current user.
// something you inform it of
//bool isInteractive;
// state you can set ahead of time and the shell context executor can modify
string scriptName; // $0, special
string[] scriptArgs; // $*, $@, $1...$n, $#. `shift` modifies it.
string[string] vars;
string[][string] aliases;
int mostRecentCommandStatus; // $?
// state managed internally whilst running
ShellCommand[] jobs;
string[] directoryStack;
ShellLoop[] loopStack;
bool exitRequested;
private SchedulableTask jobToForeground;
}
struct ShellLoop {
string[] args;
int position;
ShellLoop[] commands;
}
enum QuoteStyle {
none, // shell might do special treatment of characters
nonExpanding, // 'thing'. everything is unmodified in output
expanding, // "thing". $variables can be expanded, but not {a,b}, {1..3}, ~, ? or * or similar glob stuff. note the ~ and {} expansions happen regardless of if such a file exists. ? and * remains ? and * unless there is a match. "thing" can also expand to multiple arguments, but not just because it has a space in it, only if the variable has a space in it. what madness lol. $* and $@ need to expand to multiple args tho
/+
$* = all args as a single string, but can be multiple args when interpreted (basically the command line)
"$*" = the command line as a single arg
$@ = the argv is preserved without converting back into string but any args with spaces can still be split
"$@" = the only sane one tbh, forwards the args as argv w/o modification i think
$1, $2, etc. $# is count of args
+/
}
/++
+/
alias Globber = string[] delegate(ShellLexeme[] str, ShellContext context);
private bool isVarChar(char next) {
return (next >= 'A' && next <= 'Z') || (next >= 'a' && next <= 'z') || next == '_' || (next >= '0' && next <= '9');
}
/++
Represents one component of a shell command line as a precursor to parsing.
+/
struct ShellLexeme {
string l;
QuoteStyle quoteStyle;
/++
Expands shell arguments and escapes the glob characters, if necessary
+/
string[] toExpansions(ShellContext context) {
final switch(quoteStyle) {
case QuoteStyle.none:
case QuoteStyle.expanding:
// FIXME: if it is none it can return multiple arguments...
// and subcommands can be executed here. `foo` and "`foo"` are things.
/+
Expanded in here both cases:
* $VARs
* ${VAR}s
* $?, $@, etc.
* `subcommand` and $(subcommand)
* $((math))
ONLY IF QuoteStyle.none:
* {1..3}
* {a,b}
* ~, ~name
* bash does glob expansions iff files actually match? but i think that's premature for us here. because `*'.d'` should work and we're only going to see the part inside or outside of the quote at this stage. hence why in non-expanding it escapes the glob chars.
..... but echo "*" prints a * so it shouldn't be trying to glob in the expanding context either. glob is only possible if the star appears in the unquoted thing. maybe it is unquoted * and ? that gets the magic internal chars that are forbidden elsewhere instead of escaping the rest
+/
string[] ret;
ret ~= null;
size_t lastIndex = 0;
for(size_t idx = 0; idx < l.length; idx++) {
char ch = l[idx];
if(ch == '$') {
if(idx + 1 < l.length) {
char next = l[idx + 1];
string varName;
size_t finalIndex;
if(isVarChar(next)) {
finalIndex = idx + 1;
while(finalIndex < l.length && isVarChar(l[finalIndex])) {
finalIndex++;
}
varName = l[idx + 1 .. finalIndex];
finalIndex--; // it'll get ++'d again later
} else if(next == '{') {
// FIXME - var name enclosed in {}
} else if(next == '(') {
// FIXME - command substitution or arithmetic
} else if(next == '?' || next == '*' || next == '@' || next == '#') {
varName = l[idx + 1 .. idx + 2];
finalIndex = idx + 1;
}
if(varName.length) {
assert(finalIndex > 0);
string varContent;
bool useVarContent = true;
foreach(ref r; ret)
r ~= l[lastIndex .. idx];
// if we're not in double quotes, these are allowed to expand to multiple args
// but if we are they should be just one. in a normal unix shell anyway. idk
switch(varName) {
case "0":
varContent = context.scriptName;
break;
case "?":
varContent = toStringInternal(context.mostRecentCommandStatus);
break;
case "*":
import arsd.string;
varContent = join(context.scriptArgs, " ");
break;
case "@":
// needs to expand similarly to {a,b,c}
if(context.scriptArgs.length) {
useVarContent = false;
auto origR = ret.length;
// FIXME: if quoteStyle == none, we can split each script arg on spaces too...
foreach(irrelevant; 0 .. context.scriptArgs.length - 1)
for(size_t i = 0; i < origR; i++)
ret ~= ret[0].dup;
foreach(exp; 0 .. context.scriptArgs.length)
foreach(ref r; ret[origR * exp .. origR * (exp + 1)])
r ~= context.scriptArgs[exp];
}
break;
case "#":
varContent = toStringInternal(context.scriptArgs.length);
break;
default:
bool wasAllNumbers = true;
foreach(char chn; varName) {
if(!(chn >= '0' && chn <= '9')) {
wasAllNumbers = false;
break;
}
}
if(wasAllNumbers) {
import arsd.conv;
auto idxn = to!int(varName);
if(idxn == 0 || idxn > context.scriptArgs.length)
throw new Exception("Shell variable argument out of range: " ~ varName);
varContent = context.scriptArgs[idxn - 1];
} else {
if(varName !in context.vars) {
if(context.getEnvironmentVariable) {
auto ev = context.getEnvironmentVariable(varName);
if(ev is null)
throw new Exception("No such shell or environment variable: " ~ varName);
varContent = ev;
} else {
throw new Exception("No such shell variable: " ~ varName);
}
} else {
varContent = context.vars[varName];
}
}
}
if(useVarContent) {
// FIXME: if quoteStyle == none, we can split varContent on spaces too...
foreach(ref r; ret)
r ~= varContent;
}
idx = finalIndex; // will get ++'d next time through the for loop
lastIndex = finalIndex + 1;
}
}
continue; // dollar sign standing alone is not something to expand
}
if(quoteStyle == QuoteStyle.none) {
if(ch == '{') {
// expand like {a,b} stuff
// FIXME
foreach(ref r; ret)
r ~= l[lastIndex .. idx];
int count = 0;
size_t finalIndex;
foreach(i2, ch2; l[idx .. $]) {
if(ch2 == '{')
count++;
if(ch2 == '}')
count--;
if(count == 0) {
finalIndex = idx + i2;
break;
}
}
if(finalIndex == 0)
throw new Exception("unclosed {");
auto expansionInnards = l[idx + 1 .. finalIndex];
lastIndex = finalIndex + 1; // skip the closing }
idx = finalIndex;
auto origR = ret.length;
import arsd.string;
string[] expandedTo = expansionInnards.split(",");
assert(expandedTo.length > 0);
// FIXME: bash expands all of the first ones before doing any of the next ones
// do i want to do it that way too? or do i not care?
// {a,b}{c,d}
// i do ac bc ad bd
// bash does ac ad bc bd
// duplicate the original for each item beyond the first
foreach(irrelevant; 0 .. expandedTo.length - 1)
for(size_t i = 0; i < origR; i++)
ret ~= ret[0].dup;
foreach(exp; 0 .. expandedTo.length)
foreach(ref r; ret[origR * exp .. origR * (exp + 1)])
r ~= expandedTo[exp];
} else if(ch == '~') {
// expand home dir stuff
size_t finalIndex = idx + 1;
while(finalIndex < l.length && isVarChar(l[finalIndex])) {
finalIndex++;
}
auto replacement = context.getUserHome(l[idx + 1 .. finalIndex]);
if(replacement is null) {
// no replacement done
} else {
foreach(ref r; ret)
r ~= replacement;
idx = finalIndex - 1;
lastIndex = finalIndex;
}
}
}
}
if(lastIndex)
foreach(ref r; ret)
r ~= l[lastIndex .. $];
else if(ret.length == 1 && ret[0] is null) // was no expansion, reuse the original string
ret[0] = l;
return ret;
case QuoteStyle.nonExpanding:
return [l];
}
}
}
unittest {
ShellContext context;
context.mostRecentCommandStatus = 0;
assert(ShellLexeme("$", QuoteStyle.none).toExpansions(context) == ["$"]); // stand alone = no replacement
assert(ShellLexeme("$?", QuoteStyle.none).toExpansions(context) == ["0"]);
context.getUserHome = (username) => (username == "me" || username.length == 0) ? "/home/me" : null;
assert(ShellLexeme("~", QuoteStyle.none).toExpansions(context) == ["/home/me"]);
assert(ShellLexeme("~me", QuoteStyle.none).toExpansions(context) == ["/home/me"]);
assert(ShellLexeme("~/lol", QuoteStyle.none).toExpansions(context) == ["/home/me/lol"]);
assert(ShellLexeme("~me/lol", QuoteStyle.none).toExpansions(context) == ["/home/me/lol"]);
assert(ShellLexeme("~other", QuoteStyle.none).toExpansions(context) == ["~other"]); // not found = no replacement
}
/+
/++
The second thing should be have toSingleArg called on it
+/
EnvironmentPair toEnvironmentPair(ShellLexeme context) {
assert(quoteStyle == QuoteStyle.none);
size_t splitPoint = l.length;
foreach(size_t idx, char ch; l) {
if(ch == '=') {
splitPoint = idx;
break;
}
}
if(splitPoint != l.length) {
return EnvironmentPair(l[0 .. splitPoint], ShellLexeme(l[splitPoint + 1 .. $]));
} else {
return EnvironmentPair(null, ShellLexeme.init);
}
}
/++
Expands variables but not globs while replacing quotes and such. Note it is NOT safe to pass an expanded single arg to another shell
+/
string toExpandedSingleArg(ShellContext context) {
return l;
}
/++
Returns the value as an argv array, after shell expansion of variables, tildes, and globs
Does NOT attempt to execute `subcommands`.
+/
string[] toExpandedArgs(ShellContext context, Globber globber) {
return null;
}
+/
/++
This function in pure in all but formal annotation; it does not interact with the outside world.
+/
ShellLexeme[] lexShellCommandLine(string commandLine) {
ShellLexeme[] ret;
enum State {
consumingWhitespace,
readingWord,
readingSingleQuoted,
readingEscaped,
readingExpandingContextEscaped,
readingDoubleQuoted,
readingSpecialSymbol,
// FIXME: readingSubcommand for `thing`
readingComment,
}
State state = State.consumingWhitespace;
size_t first = commandLine.length;
void endWord() {
state = State.consumingWhitespace;
first = commandLine.length; // we'll rewind upon encountering the next word, if there is one
}
foreach(size_t idx, char ch; commandLine) {
again:
final switch(state) {
case State.consumingWhitespace:
switch(ch) {
case ' ', '\t', '\n':
// the arg separators should all be collapsed to exactly one
if(ret.length && !(ret[$-1].quoteStyle == QuoteStyle.none && ret[$-1].l == " "))
ret ~= ShellLexeme(" ");
continue;
case '#':
state = State.readingComment;
continue;
default:
first = idx;
state = State.readingWord;
goto again;
}
case State.readingWord:
switch(ch) {
case '\'':
if(first != idx)
ret ~= ShellLexeme(commandLine[first .. idx]);
first = idx + 1;
state = State.readingSingleQuoted;
break;
case '\\':
// a \ch can be treated as just a single quoted single char...
if(first != idx)
ret ~= ShellLexeme(commandLine[first .. idx]);
first = idx + 1;
state = State.readingEscaped;
break;
case '"':
if(first != idx)
ret ~= ShellLexeme(commandLine[first .. idx]);
first = idx + 1;
state = State.readingDoubleQuoted;
break;
case ' ':
ret ~= ShellLexeme(commandLine[first .. idx]);
ret ~= ShellLexeme(" "); // an argument separator
endWord();
continue;
/+
// single char special symbols
case ';':
if(first != idx)
ret ~= ShellLexeme(commandLine[first .. idx]);
ret ~= ShellLexeme(commandLine[idx .. idx + 1]);
endWord();
continue;
break;
+/
// two-char special symbols
case '|', '<', '>', '&', ';':
if(first != idx)
ret ~= ShellLexeme(commandLine[first .. idx]);
first = idx;
state = State.readingSpecialSymbol;
break;
default:
// keep searching
}
break;
case State.readingSpecialSymbol:
switch(ch) {
case '|', '<', '>', '&', ';':
// include this as a two-char lexeme
ret ~= ShellLexeme(commandLine[first .. idx + 1]);
endWord();
continue;
default:
// only include the previous char and send this back up
ret ~= ShellLexeme(commandLine[first .. idx]);
endWord();
goto again;
}
break;
case State.readingComment:
if(ch == '\n') {
endWord();
}
break;
case State.readingSingleQuoted:
switch(ch) {
case '\'':
ret ~= ShellLexeme(commandLine[first .. idx], QuoteStyle.nonExpanding);
endWord();
break;
default:
}
break;
case State.readingDoubleQuoted:
switch(ch) {
case '"':
ret ~= ShellLexeme(commandLine[first .. idx], QuoteStyle.expanding);
endWord();
break;
case '\\':
state = State.readingExpandingContextEscaped;
break;
default:
}
break;
case State.readingEscaped:
if(ch >= 0x80 && ch <= 0xBF) {
// continuation byte
continue;
} else if(first == idx) {
// first byte, keep searching for continuations
continue;
} else {
// same as if the user wrote the escaped character in single quotes
ret ~= ShellLexeme(commandLine[first .. idx], QuoteStyle.nonExpanding);
if(state == State.readingExpandingContextEscaped) {
state = State.readingDoubleQuoted;
first = idx;
} else {
endWord();
}
goto again;
}
case State.readingExpandingContextEscaped:
if(ch == '"') {
// the -1 trims out the \
ret ~= ShellLexeme(commandLine[first .. idx - 1], QuoteStyle.expanding);
state = State.readingDoubleQuoted;
first = idx; // we need to INCLUDE the " itself
} else {
// this was actually nothing special, the backslash is kept in the double quotes
state = State.readingDoubleQuoted;
}
break;
}
}
if(first != commandLine.length) {
if(state != State.readingWord && state != State.readingComment && state != State.readingSpecialSymbol)
throw new Exception("ran out of data in inappropriate state");
ret ~= ShellLexeme(commandLine[first .. $]);
}
return ret;
}
unittest {
ShellLexeme[] got;
got = lexShellCommandLine("FOO=bar");
assert(got.length == 1);
assert(got[0].l == "FOO=bar");
// comments can only happen at whitespace contexts, not at the end of a single word
got = lexShellCommandLine("FOO=bar#commentspam");
assert(got.length == 1);
assert(got[0].l == "FOO=bar#commentspam");
got = lexShellCommandLine("FOO=bar #commentspam");
assert(got.length == 2);
assert(got[0].l == "FOO=bar");
assert(got[1].l == " "); // arg separator still there even tho there is no arg cuz of the comment, but that's semantic
got = lexShellCommandLine("#commentspam");
assert(got.length == 0, got[0].l);
got = lexShellCommandLine("FOO=bar ./prog");
assert(got.length == 3);
assert(got[0].l == "FOO=bar");
assert(got[1].l == " "); // argument separator
assert(got[2].l == "./prog");
// all whitespace should be collapsed to a single argument separator
got = lexShellCommandLine("FOO=bar ./prog");
assert(got.length == 3);
assert(got[0].l == "FOO=bar");
assert(got[1].l == " "); // argument separator
assert(got[2].l == "./prog");
got = lexShellCommandLine("'foo'bar");
assert(got.length == 2);
assert(got[0].l == "foo");
assert(got[0].quoteStyle == QuoteStyle.nonExpanding);
assert(got[1].l == "bar");
assert(got[1].quoteStyle == QuoteStyle.none);
// escaped single char works as if you wrote it in single quotes
got = lexShellCommandLine("test\\'bar");
assert(got.length == 3);
assert(got[0].l == "test");
assert(got[1].l == "'");
assert(got[2].l == "bar");
// checking for utf-8 decode of escaped char
got = lexShellCommandLine("test\\\»bar");
assert(got.length == 3);
assert(got[0].l == "test");
assert(got[1].l == "\»");
assert(got[2].l == "bar");
got = lexShellCommandLine(`"ok"`);
assert(got.length == 1);
assert(got[0].l == "ok");
assert(got[0].quoteStyle == QuoteStyle.expanding);
got = lexShellCommandLine(`"ok\"after"`);
assert(got.length == 2);
assert(got[0].l == "ok");
assert(got[0].quoteStyle == QuoteStyle.expanding);
assert(got[1].l == "\"after");
assert(got[1].quoteStyle == QuoteStyle.expanding);
got = lexShellCommandLine(`FOO=bar ./thing 'my ard' second_arg "quoted\"thing"`);
assert(got.length == 10); // because quoted\"thing is two in this weird system
assert(got[0].l == "FOO=bar");
assert(got[1].l == " ");
assert(got[2].l == "./thing");
assert(got[3].l == " ");
assert(got[4].l == "my ard");
assert(got[5].l == " ");
assert(got[6].l == "second_arg");
assert(got[7].l == " ");
assert(got[8].l == "quoted");
assert(got[9].l == "\"thing");
got = lexShellCommandLine("a | b c");
assert(got.length == 7);
got = lexShellCommandLine("a && b c");
assert(got.length == 7);
got = lexShellCommandLine("a > b c");
assert(got.length == 7);
got = lexShellCommandLine("a 2>&1 b c");
assert(got.length == 9); // >& is also considered a special thing
}
struct ShellIo {
enum Kind {
inherit,
fd,
filename,
pipedCommand,
memoryBuffer
}
Kind kind;
int fd;
string filename;
ShellCommand pipedCommand;
bool append;
}
class ShellCommand {
ShellIo stdin;
ShellIo stdout;
ShellIo stderr;
// yes i know in unix you can do other fds too. do i care?
string[] argv;
EnvironmentPair[] environmentPairs;
string terminatingToken;
// set by the runners
ShellContext* shellContext;
private RunningCommand runningCommand;
FilePath exePath; /// may be null in which case you might search or do built in, depending on the executor.
private SchedulableTask shellTask;
}
/++
A shell component - which is likely an argument, but that is a semantic distinction we can't make until parsing - may be made up of several lexemes. Think `foo'bar'`. This will extract them from the given array up to and including the next unquoted space or newline char.
+/
ShellLexeme[] nextComponent(ref ShellLexeme[] lexemes) {
if(lexemes.length == 0)
return lexemes[$ .. $];
int pos;
while(
pos < lexemes.length &&
!(
// identify an arg or command separator
lexemes[pos].quoteStyle == QuoteStyle.none &&
(
lexemes[pos].l == " " ||
lexemes[pos].l == ";" ||
lexemes[pos].l == ";;" ||
lexemes[pos].l == "&" ||
lexemes[pos].l == "&&" ||
lexemes[pos].l == "||" ||
false
)
)
) {
pos++;
}
if(pos == 0)
pos++; // include the termination condition as its own component
auto ret = lexemes[0 .. pos];
lexemes = lexemes[pos .. $];
return ret;
}
struct EnvironmentPair {
string environmentVariableName;
string assignedValue;
string toString() {
return environmentVariableName ~ "=" ~ assignedValue;
}
}
string expandSingleArg(ShellContext context, ShellLexeme[] lexeme) {
string s;
foreach(lex; lexeme) {
auto expansions = lex.toExpansions(context);
if(expansions.length != 1)
throw new Exception("only single argument allowed here");
s ~= expansions[0];
}
return s;
}
/++
Parses a set of lexemes into set of command objects.
This function in pure in all but formal annotation; it does not interact with the outside world, except through the globber delegate you provide (which should not make any changes to the outside world!).
+/
ShellCommand[] parseShellCommand(ShellLexeme[] lexemes, ShellContext context, Globber globber) {
ShellCommand[] ret;
ShellCommand currentCommand;
ShellCommand firstCommand;
enum ParseState {
lookingForVarAssignment,
lookingForArg,
lookingForStdinFilename,
lookingForStdoutFilename,
lookingForStderrFilename,
}
ParseState parseState = ParseState.lookingForVarAssignment;
commandLoop: while(lexemes.length) {
auto component = nextComponent(lexemes);
if(component.length) {
/+
Command syntax in bash is basically:
Zero or more `ENV=value` sets, separated by whitespace, followed by zero or more arg things.
OR
a shell builtin which does special things to the rest of the command, and may even require subsequent commands
Argv[0] can be a shell built in which reads the rest of argv separately. It may even require subsequent commands!
For some shell built in keywords, you should not actually do expansion:
$ for $i in one two; do ls $i; done
bash: `$i': not a valid identifier
So there must be some kind of intermediate representation of possible expansions.
BUT THIS IS MY SHELL I CAN DO WHAT I WANT!!!!!!!!!!!!
shell the vars are ... not recursively expanded, it is just already expanded at assignment
+/
bool thisWasEnvironmentPair = false;
EnvironmentPair environmentPair;
bool thisWasRedirection = false;
bool thisWasPipe = false;
ShellLexeme[] arg;
if(component.length == 0) {
// nothing left, should never happen
break;
}
if(component.length == 1) {
if(component[0].quoteStyle == QuoteStyle.none && component[0].l == " ") {
// just an arg separator
continue;
}
}
if(currentCommand is null)
currentCommand = new ShellCommand();
if(firstCommand is null)
firstCommand = currentCommand;
foreach(lexeme; component) {
again:
final switch(parseState) {
case ParseState.lookingForVarAssignment:
if(thisWasEnvironmentPair) {
arg ~= lexeme;
} else {
// assume there is no var until we prove otherwise
parseState = ParseState.lookingForArg;
if(lexeme.quoteStyle == QuoteStyle.none) {
foreach(idx, ch; lexeme.l) {
if(ch == '=') {
// actually found one!
thisWasEnvironmentPair = true;
environmentPair.environmentVariableName = lexeme.l[0 .. idx];
arg ~= ShellLexeme(lexeme.l[idx + 1 .. $], QuoteStyle.none);
parseState = ParseState.lookingForVarAssignment;
}
}
}
if(parseState == ParseState.lookingForArg)
goto case;
}
break;
case ParseState.lookingForArg:
if(lexeme.quoteStyle == QuoteStyle.none) {
if(lexeme.l == "<" || lexeme.l == ">" || lexeme.l == ">>" || lexeme.l == ">&")
thisWasRedirection = true;
if(lexeme.l == "|")
thisWasPipe = true;
if(lexeme.l == ";" || lexeme.l == ";;" || lexeme.l == "&" || lexeme.l == "&&" || lexeme.l == "||") {
if(firstCommand) {
firstCommand.terminatingToken = lexeme.l;
ret ~= firstCommand;
}
firstCommand = null;
currentCommand = null;
continue commandLoop;
}
}
arg ~= lexeme;
break;
case ParseState.lookingForStdinFilename:
case ParseState.lookingForStdoutFilename:
case ParseState.lookingForStderrFilename:
if(lexeme.quoteStyle == QuoteStyle.none) {
if(lexeme.l == "<" || lexeme.l == ">")
throw new Exception("filename needed, not a redirection");
if(lexeme.l == "|")
throw new Exception("filename needed, not a pipe");
}
arg ~= lexeme;
break;
}
}
switch(parseState) {
case ParseState.lookingForStdinFilename:
currentCommand.stdin.filename = expandSingleArg(context, arg);
parseState = ParseState.lookingForArg;
continue;
case ParseState.lookingForStdoutFilename:
currentCommand.stdout.filename = expandSingleArg(context, arg);
parseState = ParseState.lookingForArg;
continue;
case ParseState.lookingForStderrFilename:
currentCommand.stderr.filename = expandSingleArg(context, arg);
parseState = ParseState.lookingForArg;
continue;
default:
break;
}
if(thisWasEnvironmentPair) {
environmentPair.assignedValue = expandSingleArg(context, arg);
currentCommand.environmentPairs ~= environmentPair;
} else if(thisWasRedirection) {
// FIXME: read the fd off this arg
// FIXME: read the filename off the next arg, new parse state
//assert(0, component);
string cmd;
foreach(item; component)
cmd ~= item.l;
switch(cmd) {
case ">":
case ">>":
if(currentCommand.stdout.kind != ShellIo.Kind.inherit)
throw new Exception("command has already been redirected");
currentCommand.stdout.kind = ShellIo.Kind.filename;
if(cmd == ">>")
currentCommand.stdout.append = true;
parseState = ParseState.lookingForStdoutFilename;
break;
case "2>":
case "2>>":
if(currentCommand.stderr.kind != ShellIo.Kind.inherit)
throw new Exception("command has already had stderr redirected");
currentCommand.stderr.kind = ShellIo.Kind.filename;
if(cmd == "2>>")
currentCommand.stderr.append = true;
parseState = ParseState.lookingForStderrFilename;
break;
case "2>&1":
if(currentCommand.stderr.kind != ShellIo.Kind.inherit)
throw new Exception("command has already had stderr redirected");
currentCommand.stderr.kind = ShellIo.Kind.fd;
currentCommand.stderr.fd = 1;
break;
case "<":
if(currentCommand.stdin.kind != ShellIo.Kind.inherit)
throw new Exception("command has already had stdin assigned");
currentCommand.stdin.kind = ShellIo.Kind.filename;
parseState = ParseState.lookingForStdinFilename;
break;
default:
throw new Exception("bad redirection try adding spaces around parts of " ~ cmd);
}
} else if(thisWasPipe) {
// FIXME: read the fd? i kinda wanna support 2| and such
auto newCommand = new ShellCommand();
currentCommand.stdout.kind = ShellIo.Kind.pipedCommand;
currentCommand.stdout.pipedCommand = newCommand;
newCommand.stdin.kind = ShellIo.Kind.pipedCommand;
newCommand.stdin.pipedCommand = currentCommand;
currentCommand = newCommand;
} else {
currentCommand.argv ~= globber(arg, context);
}
}
}
if(firstCommand)
ret ~= firstCommand;
return ret;
}
unittest {
string[] globber(ShellLexeme[] s, ShellContext context) {
string g;
foreach(l; s)
g ~= l.toExpansions(context)[0];
return [g];
}
ShellContext context;
ShellCommand[] commands;
commands = parseShellCommand(lexShellCommandLine("foo bar"), context, &globber);
assert(commands.length == 1);
assert(commands[0].argv.length == 2);
assert(commands[0].argv[0] == "foo");
assert(commands[0].argv[1] == "bar");
commands = parseShellCommand(lexShellCommandLine("foo bar'baz'"), context, &globber);
assert(commands.length == 1);
assert(commands[0].argv.length == 2);
assert(commands[0].argv[0] == "foo");
assert(commands[0].argv[1] == "barbaz");
}
/+
interface OSInterface {
setEnv
getEnv
getAllEnv