/
builtin.py
executable file
·1283 lines (1010 loc) · 31.6 KB
/
builtin.py
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
#!/usr/bin/env python
# Copyright 2016 Andy Chu. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
from __future__ import print_function
"""
builtins.py - Implementation of builtins, along with their metadata.
- used for lookup in cmd_exec.py
- need a hash of builtin names for quick testing?
- handle completion of builtin NAMES -- pass to completion.py
- handle aliases : . and source, [ and test
- handle flags they take
- handle completion of builtin FLAGS
- Add the "help" builtin itself
NOTE: bash has help -d -m -s. Default is -s, like a man page.
Links on special builtins:
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_14
- syntax errors in special builtins may cause the shell to abort, but NOT for
regular builtins?
"""
import os
import sys
from core import args
from core import lexer
from core import runtime
from core import util
from core import state
from core import word_compile
from osh import lex
from _devbuild.gen import osh_help # generated file
value_e = runtime.value_e
scope_e = runtime.scope_e
span_e = runtime.span_e
var_flags_e = runtime.var_flags_e
log = util.log
e_die = util.e_die
# NOTE: NONE is a special value.
EBuiltin = util.Enum('EBuiltin', """
NONE READ ECHO SHIFT
CD PUSHD POPD DIRS
EXPORT UNSET SET SHOPT
TRAP UMASK
SOURCE DOT EVAL EXEC WAIT JOBS
COMPLETE COMPGEN DEBUG_LINE
TRUE FALSE
COLON
TEST BRACKET GETOPTS
COMMAND TYPE HELP
DECLARE TYPESET
""".split())
# Special builtins can't be redefined by functions. On the other hand, 'cd'
# CAN be redefined.
#
# http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_14
_SPECIAL_BUILTINS = {
":": EBuiltin.COLON,
".": EBuiltin.DOT,
"eval": EBuiltin.EVAL,
"exec": EBuiltin.EXEC,
"export": EBuiltin.EXPORT,
"set": EBuiltin.SET,
"shift": EBuiltin.SHIFT,
#"times": EBuiltin.TIMES, # no implemented
"trap": EBuiltin.TRAP,
"unset": EBuiltin.UNSET,
# May be a builtin or an assignment
#"readonly": EBuiltin.READONLY,
#"local": EBuiltin.LOCAL,
"declare": EBuiltin.DECLARE,
"typeset": EBuiltin.TYPESET,
# Not treated as builtins by OSH. TODO: Need to auto-complete these
# break continue return
}
_NORMAL_BUILTINS = {
"read": EBuiltin.READ,
"echo": EBuiltin.ECHO,
"cd": EBuiltin.CD,
"pushd": EBuiltin.PUSHD,
"popd": EBuiltin.POPD,
"dirs": EBuiltin.DIRS,
"source": EBuiltin.SOURCE, # note that . alias is special
"umask": EBuiltin.UMASK,
"wait": EBuiltin.WAIT,
"jobs": EBuiltin.JOBS,
"shopt": EBuiltin.SHOPT,
"complete": EBuiltin.COMPLETE,
"compgen": EBuiltin.COMPGEN,
"true": EBuiltin.TRUE,
"false": EBuiltin.FALSE,
"test": EBuiltin.TEST,
"[": EBuiltin.BRACKET,
"getopts": EBuiltin.GETOPTS,
"command": EBuiltin.COMMAND,
"type": EBuiltin.TYPE,
"declare": EBuiltin.DECLARE,
"typeset": EBuiltin.TYPESET,
"help": EBuiltin.HELP,
"debug-line": EBuiltin.DEBUG_LINE,
}
class BuiltinDef(object):
"""
NOTE: Used by completion.py.
"""
def __init__(self):
# Is this what we want?
names = set()
names.update(_NORMAL_BUILTINS.keys())
names.update(_SPECIAL_BUILTINS.keys())
# TODO: Also complete keywords first for, while, etc. Bash/zsh/fish/yash
# all do this. See osh/lex/{_KEYWORDS, _MORE_KEYWORDS}.
self.arg_specs = {}
self.to_complete = sorted(names)
def GetNamesToComplete(self):
"""For completion of builtin names."""
return self.to_complete
def Register(self, name, help_topic=None):
help_topic = help_topic or name
arg_spec = args.BuiltinFlags()
self.arg_specs[name] = arg_spec
return arg_spec
# Global instance for "metaprogramming" before main().
BUILTIN_DEF = BuiltinDef()
def _Register(name, help_topic=None):
return BUILTIN_DEF.Register(name, help_topic=help_topic)
def ResolveSpecial(argv0):
return _SPECIAL_BUILTINS.get(argv0, EBuiltin.NONE)
def Resolve(argv0):
return _NORMAL_BUILTINS.get(argv0, EBuiltin.NONE)
#
# Implementation of builtins.
#
ECHO_LEXER = lexer.SimpleLexer(lex.ECHO_E_DEF)
ECHO_SPEC = _Register('echo')
ECHO_SPEC.ShortFlag('-e') # no backslash escapes
ECHO_SPEC.ShortFlag('-n')
def Echo(argv):
"""echo builtin.
set -o sane-echo could do the following:
- only one arg, no implicit joining.
- no -e: should be echo c'one\ttwo\t'
- no -n: should be write 'one'
multiple args on a line:
echo-lines one two three
"""
# NOTE: both getopt and optparse are unsuitable for 'echo' because:
# - 'echo -c' should print '-c', not fail
# - echo '---' should print ---, not fail
arg, arg_index = ECHO_SPEC.ParseLikeEcho(argv)
argv = argv[arg_index:]
if arg.e:
new_argv = []
for a in argv:
parts = []
for id_, value in ECHO_LEXER.Tokens(a):
p = word_compile.EvalCStringToken(id_, value)
# Unusual behavior: '\c' prints what is there and aborts processing!
if p is None:
new_argv.append(''.join(parts))
for i, a in enumerate(new_argv):
if i != 0:
sys.stdout.write(' ') # arg separator
sys.stdout.write(a)
return 0 # EARLY RETURN
parts.append(p)
new_argv.append(''.join(parts))
# Replace it
argv = new_argv
#log('echo argv %s', argv)
for i, a in enumerate(argv):
if i != 0:
sys.stdout.write(' ') # arg separator
sys.stdout.write(a)
if not arg.n:
sys.stdout.write('\n')
# Do I need the flush? Had a problem here under load, but it might not have
# been because of that.
# File "/home/andy/git/oil/bin/../core/cmd_exec.py", line 251, in _RunBuiltin
# status = builtin.Echo(argv)
# File "/home/andy/git/oil/bin/../core/builtin.py", line 431, in Echo
# sys.stdout.flush()
# IOError: [Errno 32] Broken pipe
sys.stdout.flush()
return 0
WAIT_SPEC = _Register('wait')
WAIT_SPEC.ShortFlag('-n')
def Wait(argv, waiter, job_state, mem):
"""
wait: wait [-n] [id ...]
Wait for job completion and return exit status.
Waits for each process identified by an ID, which may be a process ID or a
job specification, and reports its termination status. If ID is not
given, waits for all currently active child processes, and the return
status is zero. If ID is a a job specification, waits for all processes
in that job's pipeline.
If the -n option is supplied, waits for the next job to terminate and
returns its exit status.
Exit Status:
Returns the status of the last ID; fails if ID is invalid or an invalid
option is given.
# Job spec, %1 %2, %%, %?a etc.
http://mywiki.wooledge.org/BashGuide/JobControl#jobspec
This is different than a PID? But it does have a PID.
"""
arg, i = WAIT_SPEC.Parse(argv)
pids = argv[i:]
if arg.n:
# wait -n returns the exit status of the process. But how do you know
# WHICH process? That doesn't seem useful.
log('wait next')
if waiter.Wait():
return waiter.last_status
else:
return 127 # nothing to wait for
if not pids:
log('wait all')
# TODO: get all background jobs from JobState?
i = 0
while True:
if not waiter.Wait():
break # nothing to wait for
i += 1
if job_state.AllDone():
break
log('waited for %d processes', i)
return 0
# Get list of jobs. Then we need to check if they are ALL stopped.
# Returns the exit code of the last one on the COMMAND LINE, not the exit
# code of last one to FINSIH.
status = 1 # error
for pid in pids:
# NOTE: osh doesn't accept 'wait %1' yet
try:
jid = int(pid)
except ValueError:
util.error('Invalid argument %r', pid)
return 127
job = job_state.jobs.get(jid)
if job is None:
util.error('No such job: %s', jid)
return 127
st = job.WaitUntilDone(waiter)
if isinstance(st, list):
status = st[-1]
state.SetGlobalArray(mem, 'PIPESTATUS', [str(p) for p in st])
else:
status = st
return status
def Jobs(argv, job_state):
"""List jobs."""
job_state.List()
return 0
# Summary:
# - Split with IFS, except \ can escape them! This is different than the
# algorithm for splitting words (at least the way I've represented it.)
# - And
# Bash manual:
# - If there are more words than names, the remaining words and their
# intervening delimiters are assigned to the last name.
# - If there are fewer words read from the input stream than names, the
# remaining names are assigned empty values.
# - The characters in the value of the IFS variable are used to split the line
# into words using the same rules the shell uses for expansion (described
# above in Word Splitting).
# - The backslash character '\' may be used to remove any special meaning for
# the next character read and for line continuation.
#
# Hm but word splitting isn't affected by \<space>
#
# I think I have to make two passes.
#
# 1. Process backslashes (or don't if it's -r)
# 2. Split.
def _AppendParts(s, spans, max_results, join_next, parts):
"""
Args:
s: The original string
spans: List of (span, end_index)
max_results: the maximum number of parts we want
join_next: Whether to join the next span to the previous part. This
happens in two cases:
- when we have '\ '
- and when we have more spans # than max_results.
"""
start_index = 0
# If the last span was black, and we get a backslash, set join_next to merge
# two black spans.
last_span_was_black = False
for span_type, end_index in spans:
if span_type == span_e.Black:
if join_next and parts:
parts[-1] += s[start_index:end_index]
join_next = False
else:
parts.append(s[start_index:end_index])
last_span_was_black = True
elif span_type == span_e.Delim:
if join_next:
parts[-1] += s[start_index:end_index]
join_next = False
last_span_was_black = False
elif span_type == span_e.Backslash:
if last_span_was_black:
join_next = True
last_span_was_black = False
if len(parts) >= max_results:
join_next = True
start_index = end_index
done = True
if spans:
#log('%s %s', s, spans)
#log('%s', spans[-1])
last_span_type, _ = spans[-1]
if last_span_type == span_e.Backslash:
done = False
#log('PARTS %s', parts)
return done, join_next
READ_SPEC = _Register('read')
READ_SPEC.ShortFlag('-r')
READ_SPEC.ShortFlag('-n', args.Int)
# sys.stdin.readline() in Python has buffering! TODO: Rewrite this tight loop
# in C? Less garbage probably.
# NOTE that dash, mksh, and zsh all read a single byte at a time. It appears
# to be required by POSIX? Could try libc getline and make this an option.
def ReadLineFromStdin():
chars = []
while True:
c = os.read(0, 1)
if not c:
break
chars.append(c)
if c == '\n':
break
return ''.join(chars)
def Read(argv, splitter, mem):
arg, i = READ_SPEC.Parse(argv)
names = argv[i:]
if arg.n is not None: # read a certain number of bytes
try:
name = names[0]
except IndexError:
name = 'REPLY' # default variable name
s = os.read(sys.stdin.fileno(), arg.n)
#log('read -n: %s = %s', name, s)
state.SetLocalString(mem, name, s)
# NOTE: Even if we don't get n bytes back, there is no error?
return 0
if not names:
names.append('REPLY')
# leftover words assigned to the last name
max_results = len(names)
# We have to read more than one line if there is a line continuation (and
# it's not -r).
parts = []
join_next = False
while True:
line = ReadLineFromStdin()
#log('LINE %r', line)
if not line: # EOF
status = 1
break
if line.endswith('\n'): # strip trailing newline
line = line[:-1]
status = 0
else:
# odd bash behavior: fail even if we can set variables.
status = 1
spans = splitter.SplitForRead(line, not arg.r)
done, join_next = _AppendParts(line, spans, max_results, join_next, parts)
#log('PARTS %s continued %s', parts, continued)
if done:
break
for i in xrange(max_results):
try:
s = parts[i]
except IndexError:
s = '' # if there are too many variables
#log('read: %s = %s', names[i], s)
state.SetLocalString(mem, names[i], s)
return status
def Shift(argv, mem):
if len(argv) > 1:
util.error('shift: too many arguments')
return 1
try:
n = int(argv[0])
except IndexError:
n = 1
except ValueError as e:
print("Invalid shift argument %r" % argv[1], file=sys.stderr)
return 1 # runtime error
return mem.Shift(n)
def Cd(argv, mem, dir_stack):
# TODO: Parse flags, error checking, etc.
try:
dest_dir = argv[0]
except IndexError:
val = mem.GetVar('HOME')
if val.tag == value_e.Undef:
util.error("$HOME isn't defined")
return 1
elif val.tag == value_e.Str:
dest_dir = val.s
elif val.tag == value_e.StrArray:
util.error("$HOME shouldn't be an array.")
return 1
if dest_dir == '-':
old = mem.GetVar('OLDPWD', scope_e.GlobalOnly)
if old.tag == value_e.Undef:
log('OLDPWD not set')
return 1
elif old.tag == value_e.Str:
dest_dir = old.s
print(dest_dir) # Shells print the directory
elif old.tag == value_e.StrArray:
# TODO: Prevent the user from setting OLDPWD to array (or maybe they
# can't even set it at all.)
raise AssertionError('Invalid OLDPWD')
# NOTE: We can't call os.getcwd() because it can raise OSError if the
# directory was removed (ENOENT.)
pwd = mem.GetVar('PWD')
assert pwd.tag == value_e.Str, pwd # TODO: Need a general scheme to avoid
state.SetGlobalString(mem, 'OLDPWD', pwd.s)
try:
os.chdir(dest_dir)
except OSError as e:
# TODO: Add line number, etc.
util.error("cd %r: %s", dest_dir, os.strerror(e.errno))
return 1
state.SetGlobalString(mem, 'PWD', dest_dir) # Set $PWD.
dir_stack.Reset() # for pushd/popd/dirs
return 0
WITH_LINE_NUMBERS = 1
WITHOUT_LINE_NUMBERS = 2
SINGLE_LINE = 3
def _PrintDirStack(dir_stack, style, home_dir):
"""Helper for 'dirs'."""
if style == WITH_LINE_NUMBERS:
for i, entry in enumerate(dir_stack.Iter()):
print('%2d %s' % (i, _FormatDir(entry, home_dir)))
elif style == WITHOUT_LINE_NUMBERS:
for entry in dir_stack.Iter():
print(_FormatDir(entry, home_dir))
elif style == SINGLE_LINE:
print(' '.join(_FormatDir(entry, home_dir)
for entry in dir_stack.Iter()))
sys.stdout.flush()
def _FormatDir(dir_name, home_dir):
if home_dir and home_dir.tag == value_e.Str and (
dir_name == home_dir.s or dir_name.startswith(home_dir.s + '/')):
return dir_name.replace(home_dir.s, '~', 1)
return dir_name
def Pushd(argv, home_dir, dir_stack):
num_args = len(argv)
if num_args <= 0:
util.error('pushd: no other directory')
return 1
elif num_args > 1:
util.error('pushd: too many arguments')
return 1
dest_dir = os.path.abspath(argv[0])
try:
os.chdir(dest_dir)
except OSError as e:
util.error("pushd: %r: %s", dest_dir, os.strerror(e.errno))
return 1
dir_stack.Push(dest_dir)
_PrintDirStack(dir_stack, SINGLE_LINE, home_dir)
return 0
def Popd(argv, home_dir, dir_stack):
dest_dir = dir_stack.Pop()
if dest_dir is None:
util.error('popd: directory stack is empty')
return 1
try:
os.chdir(dest_dir)
except OSError as e:
util.error("popd: %r: %s", dest_dir, os.strerror(e.errno))
return 1
_PrintDirStack(dir_stack, SINGLE_LINE, home_dir)
return 0
DIRS_SPEC = _Register('dirs')
DIRS_SPEC.ShortFlag('-c')
DIRS_SPEC.ShortFlag('-l')
DIRS_SPEC.ShortFlag('-p')
DIRS_SPEC.ShortFlag('-v')
def Dirs(argv, home_dir, dir_stack):
arg, i = DIRS_SPEC.Parse(argv)
style = SINGLE_LINE
# Following bash order of flag priority
if arg.l:
home_dir = None
if arg.c:
dir_stack.Reset()
return 0
elif arg.v:
style = WITH_LINE_NUMBERS
elif arg.p:
style = WITHOUT_LINE_NUMBERS
_PrintDirStack(dir_stack, style, home_dir)
return 0
EXPORT_SPEC = _Register('export')
EXPORT_SPEC.ShortFlag('-n')
def Export(argv, mem):
arg, i = EXPORT_SPEC.Parse(argv)
if arg.n:
for name in argv[i:]:
m = lex.VAR_NAME_RE.match(name)
if not m:
raise args.UsageError('export: Invalid variable name %r' % name)
# NOTE: bash doesn't care if it wasn't found.
_ = mem.ClearFlag(name, var_flags_e.Exported, scope_e.Dynamic)
else:
for arg in argv[i:]:
parts = arg.split('=', 1)
if len(parts) == 1:
name = parts[0]
val = None # Creates an empty variable
else:
name, s = parts
val = runtime.Str(s)
m = lex.VAR_NAME_RE.match(name)
if not m:
raise args.UsageError('export: Invalid variable name %r' % name)
#log('%s %s', name, val)
mem.SetVar(
runtime.LhsName(name), val, (var_flags_e.Exported,), scope_e.Dynamic)
return 0
def AddOptionsToArgSpec(spec):
"""Shared between 'set' builtin and the shell's own arg parser."""
for short_flag, opt_name in state.SET_OPTIONS:
spec.Option(short_flag, opt_name)
SET_SPEC = args.FlagsAndOptions()
AddOptionsToArgSpec(SET_SPEC)
def SetExecOpts(exec_opts, opt_changes):
"""Used by bin/oil.py too."""
for opt_name, b in opt_changes:
exec_opts.SetOption(opt_name, b)
def Set(argv, exec_opts, mem):
# TODO:
# - How to integrate this with auto-completion? Have to handle '+'.
if not argv: # empty
# TODO:
# - This should be set -o, not plain 'set'.
# - When no arguments are given, it shows functions/vars? Why not show
# other state?
exec_opts.ShowOptions([])
return 0
arg, i = SET_SPEC.Parse(argv)
SetExecOpts(exec_opts, arg.opt_changes)
if arg.saw_double_dash or i != len(argv): # set -u shouldn't affect argv
mem.SetArgv(argv[i:])
return 0
# TODO:
# - STRICT: should be a combination of errexit,nounset,pipefail, plus
# strict-*, plus IFS? Caps because it's a composite.
# - SANE: disallow constructs like $* ? That can be done with an explicit
# join, like s="$@" or something?
# or s="$@" # osh: join
#
# This should be done at the module level.
#
# Maybe:
# option -o foo
# option +o foo
# But it can only be in a module with all functions? I don't want the state
# to persist.
# It's a flag on functions? Were they defined in a FILE with -o?
#
# source
# This way they're not global variables.
# or what about shopt?
#
# Ways of setting options:
# set -o +o
# shopt -o +o
# shopt -s / shopt -u
#
# shopt is also a runtime thing, not a delaration.
#
# PROBLEM:
# shopt -s noglob
# set -o pipefail
# source 'lib.sh' # behavior is changed. Although not if you put everything
# in functions! In that case, it's really the settings in main() that matter
# (as long as nobody later turns things off.)
SHOPT_SPEC = _Register('shopt')
SHOPT_SPEC.ShortFlag('-s') # set
SHOPT_SPEC.ShortFlag('-u') # unset
SHOPT_SPEC.ShortFlag('-o') # use 'set -o' up names
SHOPT_SPEC.ShortFlag('-p') # print
def Shopt(argv, exec_opts):
arg, i = SHOPT_SPEC.Parse(argv)
if arg.p: # print values
if arg.o: # use set -o names
exec_opts.ShowOptions(argv[i:])
else:
exec_opts.ShowShoptOptions(argv[i:])
return 0
b = None
if arg.s:
b = True
elif arg.u:
b = False
if b is None:
raise NotImplementedError # Display options
for opt_name in argv[i:]:
if arg.o:
exec_opts.SetOption(opt_name, b)
else:
exec_opts.SetShoptOption(opt_name, b)
return 0
UNSET_SPEC = _Register('unset')
UNSET_SPEC.ShortFlag('-v')
UNSET_SPEC.ShortFlag('-f')
# TODO:
# - Parse lvalue expression: unset 'a[ i - 1 ]'. Static or dynamic parsing?
def Unset(argv, mem, funcs):
arg, i = UNSET_SPEC.Parse(argv)
for name in argv[i:]:
if arg.f:
if name in funcs:
del funcs[name]
elif arg.v:
ok, _ = mem.Unset(runtime.LhsName(name), scope_e.Dynamic)
if not ok:
util.error("Can't unset readonly variable %r", name)
return 1
else:
# Try to delete var first, then func.
ok, found = mem.Unset(runtime.LhsName(name), scope_e.Dynamic)
if not ok:
util.error("Can't unset readonly variable %r", name)
return 1
#log('%s: %s', name, found)
if not found:
if name in funcs:
del funcs[name]
return 0
def _ResolveNames(names, funcs, path_val):
if path_val.tag == value_e.Str:
path_list = path_val.s.split(':')
else:
path_list = [] # treat as empty path
results = []
for name in names:
if name in funcs:
kind = ('function', name)
elif Resolve(name) != EBuiltin.NONE:
kind = ('builtin', name)
elif ResolveSpecial(name) != EBuiltin.NONE:
kind = ('builtin', name)
elif lex.IsOtherBuiltin(name): # declare, continue, etc.
kind = ('builtin', name)
elif lex.IsKeyword(name):
kind = ('keyword', name)
else:
# Now look for files.
found = False
for path_dir in path_list:
full_path = os.path.join(path_dir, name)
if os.path.exists(full_path):
kind = ('file', full_path)
found = True
break
if not found: # Nothing printed, but status is 1.
kind = (None, None)
results.append(kind)
return results
COMMAND_SPEC = _Register('command')
COMMAND_SPEC.ShortFlag('-v')
COMMAND_SPEC.ShortFlag('-V')
def Command(argv, funcs, path_val):
arg, i = COMMAND_SPEC.Parse(argv)
status = 0
if arg.v:
for kind, arg in _ResolveNames(argv[i:], funcs, path_val):
if kind is None:
status = 1 # nothing printed, but we fail
else:
# This is for -v, -V is more detailed.
print(arg)
else:
util.warn('*** command without -v not not implemented ***')
status = 1
return status
TYPE_SPEC = _Register('type')
TYPE_SPEC.ShortFlag('-t')
def Type(argv, funcs, path_val):
arg, i = TYPE_SPEC.Parse(argv)
status = 0
for kind, name in _ResolveNames(argv[i:], funcs, path_val):
if kind is None:
status = 1 # nothing printed, but we fail
else:
if arg.t:
print(kind)
else:
# Alpine's abuild relies on this text because busybox ash doesn't have
# -t!
# ash prints "is a shell function" instead of "is a function", but the
# regex accouts for that.
print('%s is a %s' % (name, kind))
if kind == 'function':
# bash prints the function body, busybox ash doesn't.
pass
# REQUIRED because of Python's buffering. A command sub may give the wrong
# result otherwise.
sys.stdout.flush()
return status
DECLARE_SPEC = _Register('declare')
DECLARE_SPEC.ShortFlag('-f')
DECLARE_SPEC.ShortFlag('-F')
DECLARE_SPEC.ShortFlag('-p')
def DeclareTypeset(argv, mem, funcs):
arg, i = DECLARE_SPEC.Parse(argv)
status = 0
# NOTE: in bash, -f shows the function body, while -F shows the name. In
# osh, they're identical and behave like -F.
if arg.f or arg.F: # Lookup and print functions.
names = argv[i:]
if names:
for name in names:
if name in funcs:
print(name)
# TODO: Could print LST, or render LST. Bash does this. 'trap' too.
#print(funcs[name])
else:
status = 1
else:
raise NotImplementedError('declare/typeset -f without args')
elif arg.p: # Lookup and print variables.
names = argv[i:]
if names:
for name in names:
val = mem.GetVar(name)
if val.tag != value_e.Undef:
# TODO: Print flags.
print(name)
else:
status = 1
else:
raise NotImplementedError('declare/typeset -p without args')
else:
raise NotImplementedError
sys.stdout.flush()
return status
import signal
class _TrapHandler(object):
"""A function that is called by Python's signal module.
Similar to process.SubProgramThunk."""
def __init__(self, node, nodes_to_run):
self.node = node
self.nodes_to_run = nodes_to_run
def __call__(self, unused_signalnum, unused_frame):
"""For Python's signal module."""
# TODO: set -o xtrace/verbose should enable this.
#log('*** SETTING TRAP for %d ***', unused_signalnum)
self.nodes_to_run.append(self.node)
def __str__(self):
# Used by trap -p
# TODO: Abbreviate with fmt.PrettyPrint?
return str(self.node)
def _MakeSignals():
"""Piggy-back on CPython to get a list of portable signals.
When Oil is ported to C, we might want to do something like bash/dash.
"""
names = {}
for name in dir(signal):
# don't want SIG_DFL or SIG_IGN
if name.startswith('SIG') and not name.startswith('SIG_'):
int_val = getattr(signal, name)
abbrev = name[3:]
names[abbrev] = int_val
return names
def _GetSignalValue(sig_spec):
# INT is an alias for SIGINT
if sig_spec.startswith('SIG'):
sig_spec = sig_spec[3:]
return _SIGNAL_NAMES.get(sig_spec)
_SIGNAL_NAMES = _MakeSignals()
_HOOK_NAMES = ('EXIT', 'ERR', 'RETURN', 'DEBUG')