-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
builtin.py
executable file
·1563 lines (1255 loc) · 42.7 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 python2
# 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
"""
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?
"""
from __future__ import print_function
import signal # for calculating numbers
import sys
from _devbuild.gen import osh_help # generated file
from _devbuild.gen.runtime_asdl import (
value_e, scope_e, span_e, builtin_e, arg_vector
)
from asdl import pretty
from core import ui
from core import util
from core.util import log, e_die
from frontend import args
from frontend import lex
from frontend import match
from pylib import os_path
from osh import state
from osh import string_ops
from osh import word_compile
import libc
import posix_ as posix
from typing import Dict
# 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
# https://www.gnu.org/software/bash/manual/html_node/Special-Builtins.html
_SPECIAL_BUILTINS = {
":": builtin_e.COLON,
".": builtin_e.DOT,
"eval": builtin_e.EVAL,
"exec": builtin_e.EXEC,
"export": builtin_e.EXPORT,
"set": builtin_e.SET,
"shift": builtin_e.SHIFT,
#"times": builtin_e.TIMES, # no implemented
"trap": builtin_e.TRAP,
"unset": builtin_e.UNSET,
# May be a builtin or an assignment
#"readonly": builtin_e.READONLY,
#"local": builtin_e.LOCAL,
"declare": builtin_e.DECLARE,
"typeset": builtin_e.TYPESET,
"builtin": builtin_e.BUILTIN,
# Not treated as builtins by OSH. TODO: Need to auto-complete these
# break continue return
}
_NORMAL_BUILTINS = {
"read": builtin_e.READ,
"echo": builtin_e.ECHO,
"printf": builtin_e.PRINTF,
"cd": builtin_e.CD,
"pushd": builtin_e.PUSHD,
"popd": builtin_e.POPD,
"dirs": builtin_e.DIRS,
"pwd": builtin_e.PWD,
"source": builtin_e.SOURCE, # note that . alias is special
"umask": builtin_e.UMASK,
"wait": builtin_e.WAIT,
"jobs": builtin_e.JOBS,
"fg": builtin_e.FG,
"bg": builtin_e.BG,
"shopt": builtin_e.SHOPT,
"complete": builtin_e.COMPLETE,
"compgen": builtin_e.COMPGEN,
"compopt": builtin_e.COMPOPT,
"compadjust": builtin_e.COMPADJUST,
"true": builtin_e.TRUE,
"false": builtin_e.FALSE,
"test": builtin_e.TEST,
"[": builtin_e.BRACKET,
"getopts": builtin_e.GETOPTS,
"command": builtin_e.COMMAND,
"type": builtin_e.TYPE,
"hash": builtin_e.HASH,
"help": builtin_e.HELP,
"history": builtin_e.HISTORY,
"declare": builtin_e.DECLARE,
"typeset": builtin_e.TYPESET,
"alias": builtin_e.ALIAS,
"unalias": builtin_e.UNALIAS,
# OSH only
"repr": builtin_e.REPR,
}
# This is used by completion.
BUILTIN_NAMES = _SPECIAL_BUILTINS.keys() + _NORMAL_BUILTINS.keys()
class BuiltinDef(object):
"""
NOTE: This isn't used anywhere! We're registering nothing.
We want to complete the flags to builtins. So this is a mapping from name
to arg spec. There might not be any flags.
"""
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 Register(self, name, help_topic=None):
# The help topics are in the quick ref. TODO: We should match them up?
#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, builtin_e.NONE)
def Resolve(argv0):
return _NORMAL_BUILTINS.get(argv0, builtin_e.NONE)
#
# Implementation of builtins.
#
ECHO_SPEC = _Register('echo')
ECHO_SPEC.ShortFlag('-e') # no backslash escapes
ECHO_SPEC.ShortFlag('-n')
def Echo(arg_vec):
"""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
argv = arg_vec.strs[1:]
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 match.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')
return 0
WAIT_SPEC = _Register('wait')
WAIT_SPEC.ShortFlag('-n')
class Wait(object):
"""
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.
"""
def __init__(self, waiter, job_state, mem, errfmt):
self.waiter = waiter
self.job_state = job_state
self.mem = mem
self.errfmt = errfmt
def __call__(self, arg_vec):
arg, arg_index = WAIT_SPEC.ParseVec(arg_vec)
job_ids = arg_vec.strs[arg_index:]
arg_count = len(arg_vec.strs)
if arg.n:
# wait -n returns the exit status of the JOB.
# You don't know WHICH process, which is odd.
# TODO: this should wait for the next JOB, which may be multiple
# processes.
# Bash has a wait_for_any_job() function, which loops until the jobs
# table changes.
#
# target_count = self.job_state.NumRunning() - 1
# while True:
# if not self.waiter.WaitForOne():
# break
#
# if self.job_state.NumRunning == target_count:
# break
#
#log('wait next')
if self.waiter.WaitForOne():
return self.waiter.last_status
else:
return 127 # nothing to wait for
if arg_index == arg_count: # no arguments
#log('wait all')
i = 0
while True:
# BUG: If there is a STOPPED process, this will hang forever, because
# we don't get ECHILD.
# Not sure it matters since you can now Ctrl-C it.
if not self.waiter.WaitForOne():
break # nothing to wait for
i += 1
if self.job_state.NoneAreRunning():
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 FINISH.
status = 1 # error
for i in xrange(arg_index, arg_count):
job_id = arg_vec.strs[i]
span_id = arg_vec.spids[i]
# The % syntax is sort of like ! history sub syntax, with various queries.
# https://stackoverflow.com/questions/35026395/bash-what-is-a-jobspec
if job_id.startswith('%'):
raise args.UsageError(
"doesn't support bash-style jobspecs (got %r)" % job_id,
span_id=span_id)
# Does it look like a PID?
try:
pid = int(job_id)
except ValueError:
raise args.UsageError('expected PID or jobspec, got %r' % job_id,
span_id=span_id)
job = self.job_state.JobFromPid(pid)
if job is None:
self.errfmt.Print("%s isn't a child of this shell", pid,
span_id=span_id)
return 127
# TODO: Wait for pipelines, and handle PIPESTATUS from Pipeline.Wait().
status = job.Wait(self.waiter)
return status
class Jobs(object):
"""List jobs."""
def __init__(self, job_state):
self.job_state = job_state
def __call__(self, arg_vec):
# NOTE: the + and - in the jobs list mean 'current' and 'previous', and are
# addressed with %+ and %-.
# [6] Running sleep 5 | sleep 5 &
# [7]- Running sleep 5 | sleep 5 &
# [8]+ Running sleep 5 | sleep 5 &
self.job_state.List()
return 0
class Fg(object):
"""Put a job in the foreground"""
def __init__(self, job_state, waiter):
self.job_state = job_state
self.waiter = waiter
def __call__(self, arg_vec):
# Get job instead of PID, and then do
#
# Should we also have job.SendContinueSignal() ?
# - posix.killpg()
#
# job.WaitUntilDone(self.waiter)
# - waitpid() under the hood
pid = self.job_state.GetLastStopped()
if pid is None:
log('No job to put in the foreground')
return 1
# TODO: Print job ID rather than the PID
log('Continue PID %d', pid)
posix.kill(pid, signal.SIGCONT)
job = self.job_state.JobFromPid(pid)
status = job.Wait(self.waiter)
#log('status = %d', status)
return status
class Bg(object):
"""Put a job in the background"""
def __init__(self, job_state):
self.job_state = job_state
def __call__(self, arg_vec):
# How does this differ from 'fg'? It doesn't wait and it sets controlling
# terminal?
raise args.UsageError("isn't implemented")
# 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 max_results and 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)
READ_SPEC.ShortFlag('-a', args.Str) # name of array to read into
# 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 = posix.read(0, 1)
if not c:
break
chars.append(c)
if c == '\n':
break
return ''.join(chars)
class Read(object):
def __init__(self, splitter, mem):
self.splitter = splitter
self.mem = mem
def __call__(self, arg_vec):
arg, i = READ_SPEC.ParseVec(arg_vec)
names = arg_vec.strs[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 = posix.read(sys.stdin.fileno(), arg.n)
#log('read -n: %s = %s', name, s)
state.SetLocalString(self.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
if arg.a:
max_results = 0 # no max
else:
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 = self.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
if arg.a:
state.SetArrayDynamic(self.mem, arg.a, parts)
else:
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.SetStringDynamic(self.mem, names[i], s)
return status
CD_SPEC = _Register('cd')
CD_SPEC.ShortFlag('-L')
CD_SPEC.ShortFlag('-P')
class Cd(object):
def __init__(self, mem, dir_stack, errfmt):
self.mem = mem
self.dir_stack = dir_stack
self.errfmt = errfmt
def __call__(self, arg_vec):
arg, i = CD_SPEC.ParseVec(arg_vec)
# TODO: error checking, etc.
# TODO: ensure that if multiple flags are provided, the *last* one overrides
# the others.
try:
dest_dir = arg_vec.strs[i]
except IndexError:
val = self.mem.GetVar('HOME')
if val.tag == value_e.Undef:
self.errfmt.Print("$HOME isn't defined")
return 1
elif val.tag == value_e.Str:
dest_dir = val.s
elif val.tag == value_e.StrArray:
# User would have to unset $HOME to get rid of exported flag
self.errfmt.Print("$HOME shouldn't be an array")
return 1
if dest_dir == '-':
old = self.mem.GetVar('OLDPWD', scope_e.GlobalOnly)
if old.tag == value_e.Undef:
self.errfmt.Print('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')
pwd = self.mem.GetVar('PWD')
assert pwd.tag == value_e.Str, pwd # TODO: Need a general scheme to avoid
# Calculate new directory, chdir() to it, then set PWD to it. NOTE: We can't
# call posix.getcwd() because it can raise OSError if the directory was
# removed (ENOENT.)
abspath = os_path.join(pwd.s, dest_dir) # make it absolute, for cd ..
if arg.P:
# -P means resolve symbolic links, then process '..'
real_dest_dir = libc.realpath(abspath)
else:
# -L means process '..' first. This just does string manipulation. (But
# realpath afterward isn't correct?)
real_dest_dir = os_path.normpath(abspath)
try:
posix.chdir(real_dest_dir)
except OSError as e:
self.errfmt.Print("cd %r: %s", real_dest_dir, posix.strerror(e.errno),
span_id=arg_vec.spids[i])
return 1
state.ExportGlobalString(self.mem, 'OLDPWD', pwd.s)
state.ExportGlobalString(self.mem, 'PWD', real_dest_dir)
self.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, ui.PrettyDir(entry, home_dir)))
elif style == WITHOUT_LINE_NUMBERS:
for entry in dir_stack.Iter():
print(ui.PrettyDir(entry, home_dir))
elif style == SINGLE_LINE:
s = ' '.join(ui.PrettyDir(entry, home_dir) for entry in dir_stack.Iter())
print(s)
class Pushd(object):
def __init__(self, mem, dir_stack, errfmt):
self.mem = mem
self.dir_stack = dir_stack
self.errfmt = errfmt
def __call__(self, arg_vec):
num_args = len(arg_vec.strs) - 1
if num_args == 0:
# TODO: It's suppose to try another dir before doing this?
self.errfmt.Print('pushd: no other directory')
return 1
elif num_args > 1:
raise args.UsageError('got too many arguments')
dest_dir = os_path.abspath(arg_vec.strs[1])
try:
posix.chdir(dest_dir)
except OSError as e:
self.errfmt.Print("pushd: %r: %s", dest_dir, posix.strerror(e.errno),
span_id=arg_vec.spids[1])
return 1
self.dir_stack.Push(dest_dir)
_PrintDirStack(self.dir_stack, SINGLE_LINE, self.mem.GetVar('HOME'))
state.SetGlobalString(self.mem, 'PWD', dest_dir)
return 0
class Popd(object):
def __init__(self, mem, dir_stack, errfmt):
self.mem = mem
self.dir_stack = dir_stack
self.errfmt = errfmt
def __call__(self, arg_vec):
dest_dir = self.dir_stack.Pop()
if dest_dir is None:
self.errfmt.Print('popd: directory stack is empty')
return 1
try:
posix.chdir(dest_dir)
except OSError as e:
# Happens if a directory is deleted in pushing and popping
self.errfmt.Print("popd: %r: %s", dest_dir, posix.strerror(e.errno))
return 1
_PrintDirStack(self.dir_stack, SINGLE_LINE, self.mem.GetVar('HOME'))
state.SetGlobalString(self.mem, 'PWD', dest_dir)
return 0
DIRS_SPEC = _Register('dirs')
DIRS_SPEC.ShortFlag('-c')
DIRS_SPEC.ShortFlag('-l')
DIRS_SPEC.ShortFlag('-p')
DIRS_SPEC.ShortFlag('-v')
class Dirs(object):
def __init__(self, mem, dir_stack, errfmt):
self.mem = mem
self.dir_stack = dir_stack
self.errfmt = errfmt
def __call__(self, arg_vec):
home_dir = self.mem.GetVar('HOME')
arg, i = DIRS_SPEC.ParseVec(arg_vec)
style = SINGLE_LINE
# Following bash order of flag priority
if arg.l:
home_dir = None # disable pretty ~
if arg.c:
self.dir_stack.Reset()
return 0
elif arg.v:
style = WITH_LINE_NUMBERS
elif arg.p:
style = WITHOUT_LINE_NUMBERS
_PrintDirStack(self.dir_stack, style, home_dir)
return 0
PWD_SPEC = _Register('pwd')
PWD_SPEC.ShortFlag('-L')
PWD_SPEC.ShortFlag('-P')
class Pwd(object):
def __init__(self, errfmt):
self.errfmt = errfmt
def __call__(self, arg_vec):
arg, _ = PWD_SPEC.ParseVec(arg_vec)
try:
# This comes FIRST, even if you change $PWD.
pwd = posix.getcwd()
except OSError as e:
# Happens when the directory is unlinked.
self.errfmt.Print("Can't determine working directory: %s",
posix.strerror(e.errno))
return 1
# '-L' is the default behavior; no need to check it
# TODO: ensure that if multiple flags are provided, the *last* one overrides
# the others
if arg.P:
pwd = libc.realpath(pwd)
print(pwd)
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)
class Set(object):
def __init__(self, exec_opts, mem):
self.exec_opts = exec_opts
self.mem = mem
def __call__(self, arg_vec):
# TODO:
# - How to integrate this with auto-completion? Have to handle '+'.
if len(arg_vec.strs) == 1:
# 'set' without args shows visible variable names and values. According
# to POSIX:
# - the names should be sorted, and
# - the code should be suitable for re-input to the shell. We have a
# spec test for this.
# Also:
# - autoconf also wants them to fit on ONE LINE.
# http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
mapping = self.mem.GetAllVars()
for name in sorted(mapping):
str_val = mapping[name]
code_str = '%s=%s' % (name, string_ops.ShellQuoteOneLine(str_val))
print(code_str)
return 0
arg_r = args.Reader(arg_vec.strs, spids=arg_vec.spids)
arg_r.Next() # skip 'set'
arg = SET_SPEC.Parse(arg_r)
# 'set -o' shows options. This is actually used by autoconf-generated
# scripts!
if arg.show_options:
self.exec_opts.ShowOptions([])
return 0
SetExecOpts(self.exec_opts, arg.opt_changes)
# Hm do we need saw_double_dash?
if arg.saw_double_dash or not arg_r.AtEnd():
self.mem.SetArgv(arg_r.Rest())
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
SHOPT_SPEC.ShortFlag('-q') # query option settings
class Shopt(object):
def __init__(self, exec_opts):
self.exec_opts = exec_opts
def __call__(self, arg_vec):
arg, i = SHOPT_SPEC.ParseVec(arg_vec)
opt_names = arg_vec.strs[i:]
if arg.p: # print values
if arg.o: # use set -o names
self.exec_opts.ShowOptions(opt_names)
else:
self.exec_opts.ShowShoptOptions(opt_names)
return 0
if arg.q: # query values
for name in opt_names:
if not hasattr(self.exec_opts, name):
return 2 # bash gives 1 for invalid option; 2 is better
if not getattr(self.exec_opts, name):
return 1 # at least one option is not true
return 0 # all options are true
b = None
if arg.s:
b = True
elif arg.u:
b = False
if b is None: # Print options
# bash prints uses a different format for 'shopt', but we use the
# same format as 'shopt -p'.
self.exec_opts.ShowShoptOptions(opt_names)
return 0
# Otherwise, set options.
for name in opt_names:
if arg.o:
self.exec_opts.SetOption(name, b)
else:
self.exec_opts.SetShoptOption(name, b)
return 0
def _ResolveNames(names, funcs, aliases, search_path):
results = []
for name in names:
if name in funcs:
kind = ('function', name)
elif name in aliases:
kind = ('alias', name)
elif Resolve(name) != builtin_e.NONE:
kind = ('builtin', name)
elif ResolveSpecial(name) != builtin_e.NONE:
kind = ('builtin', name)
elif lex.IsOtherBuiltin(name): # declare, continue, etc.
kind = ('builtin', name)
elif lex.IsKeyword(name):
kind = ('keyword', name)
else:
resolved = search_path.Lookup(name)
if resolved is None:
kind = (None, None)
else:
kind = ('file', resolved)
results.append(kind)
return results
COMMAND_SPEC = _Register('command')
COMMAND_SPEC.ShortFlag('-v')
#COMMAND_SPEC.ShortFlag('-V') # Another verbose mode.
class Command(object):
def __init__(self, ex, funcs, aliases, search_path):
self.ex = ex
self.funcs = funcs
self.aliases = aliases
self.search_path = search_path
def __call__(self, arg_vec, fork_external):
arg, arg_index = COMMAND_SPEC.ParseVec(arg_vec)
if arg.v:
status = 0
names = arg_vec.strs[arg_index:]
for kind, arg in _ResolveNames(names, self.funcs, self.aliases,
self.search_path):
if kind is None:
status = 1 # nothing printed, but we fail
else:
# This is for -v, -V is more detailed.
print(arg)
return status
arg_vec2 = arg_vector(arg_vec.strs[1:], arg_vec.spids[1:]) # shift by one
# 'command ls' suppresses function lookup.
return self.ex.RunSimpleCommand(arg_vec2, fork_external, funcs=False)
TYPE_SPEC = _Register('type')
TYPE_SPEC.ShortFlag('-f')
TYPE_SPEC.ShortFlag('-t')
TYPE_SPEC.ShortFlag('-p')
TYPE_SPEC.ShortFlag('-P')
class Type(object):
def __init__(self, funcs, aliases, search_path):
self.funcs = funcs
self.aliases = aliases
self.search_path = search_path
def __call__(self, arg_vec):
arg, i = TYPE_SPEC.ParseVec(arg_vec)