-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
shell.py
695 lines (561 loc) · 24 KB
/
shell.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
"""
core/shell.py -- Entry point for the shell interpreter.
"""
from __future__ import print_function
import errno
import time
from _devbuild.gen import arg_types
from _devbuild.gen.option_asdl import option_i, builtin_i
from _devbuild.gen.syntax_asdl import source
from asdl import runtime
from core import alloc
from core import comp_ui
from core import dev
from core import error
from core import executor
from core import completion
from core import main_loop
from core import pyos
from core import process
from core import shell_native
from core import pyutil
from core.pyutil import stderr_line
from core import state
from core import ui
from core import util
from core.pyerror import log
unused = log
from core import vm
from frontend import args
from frontend import flag_def # side effect: flags are defined!
_ = flag_def
from frontend import flag_spec
from frontend import reader
from frontend import py_reader
from frontend import parse_lib
from oil_lang import expr_eval
from oil_lang import builtin_oil
from oil_lang import funcs_builtin
from osh import builtin_assign
from osh import builtin_comp
from osh import builtin_meta
from osh import builtin_misc
from osh import builtin_lib
from osh import builtin_printf
from osh import builtin_process
from osh import builtin_pure
from osh import cmd_eval
from osh import glob_
from osh import history
from osh import prompt
from osh import sh_expr_eval
from osh import split
from osh import word_eval
from mycpp import mylib
from pylib import os_path
import libc
import posix_ as posix
from typing import List, Dict, Optional, Any, TYPE_CHECKING
if TYPE_CHECKING:
from _devbuild.gen.runtime_asdl import Proc
def _InitDefaultCompletions(cmd_ev, complete_builtin, comp_lookup):
# type: (cmd_eval.CommandEvaluator, builtin_comp.Complete, completion.Lookup) -> None
# register builtins and words
complete_builtin.Run(shell_native.MakeBuiltinArgv(['-E', '-A', 'command']))
# register path completion
# Add -o filenames? Or should that be automatic?
complete_builtin.Run(shell_native.MakeBuiltinArgv(['-D', '-A', 'file']))
# TODO: Move this into demo/slow-completion.sh
if 1:
# Something for fun, to show off. Also: test that you don't repeatedly hit
# the file system / network / coprocess.
A1 = completion.TestAction(['foo.py', 'foo', 'bar.py'])
A2 = completion.TestAction(['m%d' % i for i in xrange(5)], delay=0.1)
C1 = completion.UserSpec([A1, A2], [], [], lambda candidate: True)
comp_lookup.RegisterName('slowc', {}, C1)
def SourceStartupFile(fd_state, rc_path, lang, parse_ctx, cmd_ev, errfmt):
# type: (process.FdState, str, str, parse_lib.ParseContext, cmd_eval.CommandEvaluator, ui.ErrorFormatter) -> None
# Right now this is called when the shell is interactive. (Maybe it should
# be called on login_shel too.)
#
# Terms:
# - interactive shell: Roughly speaking, no args or -c, and isatty() is true
# for stdin and stdout.
# - login shell: Started from the top level, e.g. from init or ssh.
#
# We're not going to copy everything bash does because it's too complex, but
# for reference:
# https://www.gnu.org/software/bash/manual/bash.html#Bash-Startup-Files
# Bash also has --login.
try:
f = fd_state.Open(rc_path)
except (IOError, OSError) as e:
# TODO: Could warn about nonexistent explicit --rcfile?
if e.errno != errno.ENOENT:
raise # Goes to top level. Handle this better?
return
arena = parse_ctx.arena
rc_line_reader = reader.FileLineReader(f, arena)
rc_c_parser = parse_ctx.MakeOshParser(rc_line_reader)
with alloc.ctx_Location(arena, source.SourcedFile(rc_path)):
# TODO: handle status, e.g. 2 for ParseError
status = main_loop.Batch(cmd_ev, rc_c_parser, errfmt)
f.close()
class ShellOptHook(state.OptHook):
def __init__(self, line_input):
# type: (Any) -> None
self.line_input = line_input
def OnChange(self, opt0_array, opt_name, b):
# type: (List[bool], str, bool) -> bool
"""This method is called whenever an option is changed.
Returns success or failure.
"""
if opt_name == 'vi' or opt_name == 'emacs':
# TODO: Replace with a hook? Just like setting LANG= can have a hook.
if self.line_input:
self.line_input.parse_and_bind("set editing-mode " + opt_name);
else:
stderr_line(
"Warning: Can't set option %r because Oil wasn't built with line editing (e.g. GNU readline)", opt_name)
return False
# Invert: they are mutually exclusive!
if opt_name == 'vi':
opt0_array[option_i.emacs] = not b
elif opt_name == 'emacs':
opt0_array[option_i.vi] = not b
return True
def AddProcess(
b, # type: Dict[int, vm._Builtin]
mem, # type: state.Mem
shell_ex, # type: vm._Executor
ext_prog, # type: process.ExternalProgram
fd_state, # type: process.FdState
job_state, # type: process.JobState
waiter, # type: process.Waiter
tracer, # type: dev.Tracer
search_path, # type: state.SearchPath
errfmt # type: ui.ErrorFormatter
):
# type: (...) -> None
# Process
b[builtin_i.exec_] = builtin_process.Exec(mem, ext_prog, fd_state,
search_path, errfmt)
b[builtin_i.wait] = builtin_process.Wait(waiter, job_state, mem, tracer,
errfmt)
b[builtin_i.jobs] = builtin_process.Jobs(job_state)
b[builtin_i.fg] = builtin_process.Fg(job_state, waiter)
b[builtin_i.bg] = builtin_process.Bg(job_state)
b[builtin_i.umask] = builtin_process.Umask()
b[builtin_i.fork] = builtin_process.Fork(shell_ex)
b[builtin_i.forkwait] = builtin_process.ForkWait(shell_ex)
def AddOil(b, mem, cmd_ev, errfmt, procs, arena):
# type: (Dict[int, vm._Builtin], state.Mem, cmd_eval.CommandEvaluator, ui.ErrorFormatter, Dict[str, Proc], alloc.Arena) -> None
b[builtin_i.append] = builtin_oil.Append(mem, errfmt)
b[builtin_i.shvar] = builtin_pure.Shvar(mem, cmd_ev)
b[builtin_i.push_registers] = builtin_pure.PushRegisters(mem, cmd_ev)
b[builtin_i.write] = builtin_oil.Write(mem, errfmt)
b[builtin_i.pp] = builtin_oil.Pp(mem, errfmt, procs, arena)
b[builtin_i.use] = builtin_pure.Use(mem, errfmt)
b[builtin_i.argparse] = builtin_oil.ArgParse(mem, errfmt)
def Main(lang, arg_r, environ, login_shell, loader, line_input):
# type: (str, args.Reader, Dict[str, str], bool, pyutil._ResourceLoader, Any) -> int
"""The full shell lifecycle. Used by bin/osh and bin/oil.
Args:
lang: 'osh' or 'oil'
argv0, arg_r: command line arguments
environ: environment
login_shell: Was - on the front?
loader: to get help, version, grammar, etc.
line_input: optional GNU readline
"""
# Differences between osh and oil:
# - --help? I guess Oil has a SUPERSET of OSH options.
# - oshrc vs oilrc
# - shopt -s oil:all
# - Change the prompt in the interactive shell?
# osh-pure:
# - no oil grammar
# - no expression evaluator
# - no interactive shell, or line_input
# - no process.*
# process.{ExternalProgram,Waiter,FdState,JobState,SignalState} -- we want
# to evaluate config files without any of these
# Modules not translated yet: completion, comp_ui, builtin_comp, process
# - word evaluator
# - shouldn't glob? set -o noglob? or hard failure?
# - ~ shouldn't read from the file system
# - I guess it can just be the HOME=HOME?
# Builtin:
# shellvm -c 'echo hi'
# shellvm <<< 'echo hi'
argv0 = arg_r.Peek()
assert argv0 is not None
arg_r.Next()
assert lang in ('osh', 'oil'), lang
try:
attrs = flag_spec.ParseMore('main', arg_r)
except error.Usage as e:
stderr_line('osh usage error: %s', e.msg)
return 2
flag = arg_types.main(attrs.attrs)
arena = alloc.Arena()
errfmt = ui.ErrorFormatter(arena)
help_builtin = builtin_misc.Help(loader, errfmt)
if flag.help:
help_builtin.Run(shell_native.MakeBuiltinArgv(['%s-usage' % lang]))
return 0
if flag.version:
# OSH version is the only binary in Oil right now, so it's all one version.
pyutil.ShowAppVersion('Oil', loader)
return 0
no_str = None # type: str
debug_stack = [] # type: List[state.DebugFrame]
if arg_r.AtEnd():
dollar0 = argv0
else:
dollar0 = arg_r.Peek() # the script name, or the arg after -c
# Copy quirky bash behavior.
frame0 = state.DebugFrame(dollar0, 'main', no_str, state.LINE_ZERO, 0, 0)
debug_stack.append(frame0)
# Copy quirky bash behavior.
frame1 = state.DebugFrame(no_str, no_str, no_str, runtime.NO_SPID, 0, 0)
debug_stack.append(frame1)
script_name = arg_r.Peek() # type: Optional[str]
arg_r.Next()
mem = state.Mem(dollar0, arg_r.Rest(), arena, debug_stack)
opt_hook = ShellOptHook(line_input)
# Note: only MutableOpts needs mem, so it's not a true circular dep.
parse_opts, exec_opts, mutable_opts = state.MakeOpts(mem, opt_hook)
mem.exec_opts = exec_opts # circular dep
mutable_opts.Init()
version_str = pyutil.GetVersion(loader)
state.InitMem(mem, environ, version_str)
funcs_builtin.Init(mem)
procs = {} # type: Dict[str, Proc]
if attrs.show_options: # special case: sh -o
mutable_opts.ShowOptions([])
return 0
# Set these BEFORE processing flags, so they can be overridden.
if lang == 'oil':
mutable_opts.SetShoptOption('oil:all', True)
builtin_pure.SetShellOpts(mutable_opts, attrs.opt_changes, attrs.shopt_changes)
# feedback between runtime and parser
aliases = {} # type: Dict[str, str]
oil_grammar = pyutil.LoadOilGrammar(loader)
if flag.one_pass_parse and not exec_opts.noexec():
raise error.Usage('--one-pass-parse requires noexec (-n)')
parse_ctx = parse_lib.ParseContext(arena, parse_opts, aliases, oil_grammar)
parse_ctx.Init_OnePassParse(flag.one_pass_parse)
# Three ParseContext instances SHARE aliases.
comp_arena = alloc.Arena()
comp_arena.PushSource(source.Unused('completion'))
trail1 = parse_lib.Trail()
# one_pass_parse needs to be turned on to complete inside backticks. TODO:
# fix the issue where ` gets erased because it's not part of
# set_completer_delims().
comp_ctx = parse_lib.ParseContext(comp_arena, parse_opts, aliases,
oil_grammar)
comp_ctx.Init_Trail(trail1)
comp_ctx.Init_OnePassParse(True)
hist_arena = alloc.Arena()
hist_arena.PushSource(source.Unused('history'))
trail2 = parse_lib.Trail()
hist_ctx = parse_lib.ParseContext(hist_arena, parse_opts, aliases,
oil_grammar)
hist_ctx.Init_Trail(trail2)
# Deps helps manages dependencies. These dependencies are circular:
# - cmd_ev and word_ev, arith_ev -- for command sub, arith sub
# - arith_ev and word_ev -- for $(( ${a} )) and $x$(( 1 ))
# - cmd_ev and builtins (which execute code, like eval)
# - prompt_ev needs word_ev for $PS1, which needs prompt_ev for @P
cmd_deps = cmd_eval.Deps()
cmd_deps.mutable_opts = mutable_opts
# TODO: In general, cmd_deps are shared between the mutually recursive
# evaluators. Some of the four below are only shared between a builtin and
# the CommandEvaluator, so we could put them somewhere else.
cmd_deps.traps = {}
cmd_deps.trap_nodes = [] # TODO: Clear on fork() to avoid duplicates
job_state = process.JobState()
fd_state = process.FdState(errfmt, job_state, mem, None, None)
my_pid = posix.getpid()
debug_path = ''
debug_dir = environ.get('OSH_DEBUG_DIR')
if flag.debug_file is not None:
# --debug-file takes precedence over OSH_DEBUG_DIR
debug_path = flag.debug_file
elif debug_dir is not None:
debug_path = os_path.join(debug_dir, '%d-osh.log' % my_pid)
if len(debug_path):
# This will be created as an empty file if it doesn't exist, or it could be
# a pipe.
try:
debug_f = util.DebugFile(fd_state.OpenForWrite(debug_path)) # type: util._DebugFile
except OSError as e:
stderr_line("osh: Couldn't open %r: %s", debug_path,
posix.strerror(e.errno))
return 2
else:
debug_f = util.NullDebugFile()
if flag.xtrace_to_debug_file:
trace_f = debug_f
else:
trace_f = util.DebugFile(mylib.Stderr())
tracer = dev.Tracer(parse_ctx, exec_opts, mutable_opts, mem, trace_f)
fd_state.tracer = tracer # circular dep
sig_state = pyos.SignalState()
sig_state.InitShell()
waiter = process.Waiter(job_state, exec_opts, sig_state, tracer)
fd_state.waiter = waiter
cmd_deps.debug_f = debug_f
# Not using datetime for dependency reasons. TODO: maybe show the date at
# the beginning of the log, and then only show time afterward? To save
# space, and make space for microseconds. (datetime supports microseconds
# but time.strftime doesn't).
if mylib.PYTHON:
iso_stamp = time.strftime("%Y-%m-%d %H:%M:%S")
debug_f.log('%s [%d] OSH started with argv %s', iso_stamp, my_pid, arg_r.argv)
if len(debug_path):
debug_f.log('Writing logs to %r', debug_path)
interp = environ.get('OSH_HIJACK_SHEBANG', '')
search_path = state.SearchPath(mem)
ext_prog = process.ExternalProgram(interp, fd_state, errfmt, debug_f)
splitter = split.SplitContext(mem)
# TODO: This is instantiation is duplicated in osh/word_eval.py
globber = glob_.Globber(exec_opts)
funcs_builtin.Init2(mem, splitter, globber)
# This could just be OSH_DEBUG_STREAMS='debug crash' ? That might be
# stuffing too much into one, since a .json crash dump isn't a stream.
crash_dump_dir = environ.get('OSH_CRASH_DUMP_DIR', '')
cmd_deps.dumper = dev.CrashDumper(crash_dump_dir)
comp_lookup = completion.Lookup()
# Various Global State objects to work around readline interfaces
compopt_state = completion.OptionState()
comp_ui_state = comp_ui.State()
prompt_state = comp_ui.PromptState()
dir_stack = state.DirStack()
#
# Initialize builtins that don't depend on evaluators
#
builtins = {} # type: Dict[int, vm._Builtin]
modules = {} # type: Dict[str, bool]
shell_ex = executor.ShellExecutor(
mem, exec_opts, mutable_opts, procs, builtins, search_path,
ext_prog, waiter, tracer, job_state, fd_state, errfmt)
shell_native.AddPure(builtins, mem, procs, modules, mutable_opts, aliases,
search_path, errfmt)
shell_native.AddIO(builtins, mem, dir_stack, exec_opts, splitter, parse_ctx,
errfmt)
AddProcess(builtins, mem, shell_ex, ext_prog, fd_state, job_state, waiter,
tracer, search_path, errfmt)
builtins[builtin_i.help] = help_builtin
# Interactive, depend on line_input
builtins[builtin_i.bind] = builtin_lib.Bind(line_input, errfmt)
builtins[builtin_i.history] = builtin_lib.History(line_input, mylib.Stdout())
#
# Initialize Evaluators
#
arith_ev = sh_expr_eval.ArithEvaluator(mem, exec_opts, parse_ctx, errfmt)
bool_ev = sh_expr_eval.BoolEvaluator(mem, exec_opts, parse_ctx, errfmt)
expr_ev = expr_eval.OilEvaluator(mem, procs, splitter, errfmt)
word_ev = word_eval.NormalWordEvaluator(mem, exec_opts, mutable_opts,
splitter, errfmt)
assign_b = shell_native.InitAssignmentBuiltins(mem, procs, errfmt)
cmd_ev = cmd_eval.CommandEvaluator(mem, exec_opts, errfmt, procs,
assign_b, arena, cmd_deps)
AddOil(builtins, mem, cmd_ev, errfmt, procs, arena)
# PromptEvaluator rendering is needed in non-interactive shells for @P.
prompt_ev = prompt.Evaluator(lang, version_str, parse_ctx, mem)
# Wire up circular dependencies.
vm.InitCircularDeps(arith_ev, bool_ev, expr_ev, word_ev, cmd_ev, shell_ex,
prompt_ev, tracer)
#
# Initialize builtins that depend on evaluators
#
unsafe_arith = sh_expr_eval.UnsafeArith(mem, exec_opts, parse_ctx, arith_ev,
errfmt)
vm.InitUnsafeArith(mem, word_ev, unsafe_arith)
builtins[builtin_i.printf] = builtin_printf.Printf(mem, parse_ctx,
unsafe_arith, errfmt)
builtins[builtin_i.unset] = builtin_assign.Unset(mem, procs, unsafe_arith,
errfmt)
builtins[builtin_i.eval] = builtin_meta.Eval(parse_ctx, exec_opts, cmd_ev,
tracer, errfmt)
builtins[builtin_i.read] = builtin_misc.Read(splitter, mem, parse_ctx,
cmd_ev, errfmt)
mapfile = builtin_misc.MapFile(mem, errfmt, cmd_ev)
builtins[builtin_i.mapfile] = mapfile
builtins[builtin_i.readarray] = mapfile
source_builtin = builtin_meta.Source(parse_ctx, search_path, cmd_ev,
fd_state, tracer, errfmt)
builtins[builtin_i.source] = source_builtin
builtins[builtin_i.dot] = source_builtin
shell_native.AddMeta(builtins, shell_ex, mutable_opts, mem, procs, aliases,
search_path, errfmt)
shell_native.AddBlock(builtins, mem, mutable_opts, dir_stack, cmd_ev,
errfmt)
builtins[builtin_i.json] = builtin_oil.Json(mem, expr_ev, errfmt)
spec_builder = builtin_comp.SpecBuilder(cmd_ev, parse_ctx, word_ev, splitter,
comp_lookup, errfmt)
complete_builtin = builtin_comp.Complete(spec_builder, comp_lookup)
builtins[builtin_i.complete] = complete_builtin
builtins[builtin_i.compgen] = builtin_comp.CompGen(spec_builder)
builtins[builtin_i.compopt] = builtin_comp.CompOpt(compopt_state, errfmt)
builtins[builtin_i.compadjust] = builtin_comp.CompAdjust(mem)
builtins[builtin_i.trap] = builtin_process.Trap(sig_state, cmd_deps.traps,
cmd_deps.trap_nodes,
parse_ctx, tracer, errfmt)
# History evaluation is a no-op if line_input is None.
hist_ev = history.Evaluator(line_input, hist_ctx, debug_f)
if flag.c is not None:
arena.PushSource(source.CFlag())
line_reader = reader.StringLineReader(flag.c, arena) # type: reader._Reader
if flag.i: # -c and -i can be combined
mutable_opts.set_interactive()
elif flag.i: # force interactive
arena.PushSource(source.Stdin(' -i'))
line_reader = py_reader.InteractiveLineReader(
arena, prompt_ev, hist_ev, line_input, prompt_state)
mutable_opts.set_interactive()
else:
if script_name is None:
if flag.headless:
arena.PushSource(source.Headless())
line_reader = None # unused!
# Not setting '-i' flag for now. Some people's bashrc may want it?
else:
stdin = mylib.Stdin()
if stdin.isatty():
arena.PushSource(source.Interactive())
line_reader = py_reader.InteractiveLineReader(
arena, prompt_ev, hist_ev, line_input, prompt_state)
mutable_opts.set_interactive()
else:
arena.PushSource(source.Stdin(''))
line_reader = reader.FileLineReader(stdin, arena)
else:
arena.PushSource(source.MainFile(script_name))
try:
f = fd_state.Open(script_name)
except (IOError, OSError) as e:
stderr_line("osh: Couldn't open %r: %s", script_name,
posix.strerror(e.errno))
return 1
line_reader = reader.FileLineReader(f, arena)
# TODO: assert arena.NumSourcePaths() == 1
# TODO: .rc file needs its own arena.
c_parser = parse_ctx.MakeOshParser(line_reader)
# Calculate ~/.config/oil/oshrc or oilrc. Used for both -i and --headless
# We avoid cluttering the user's home directory. Some users may want to ln
# -s ~/.config/oil/oshrc ~/oshrc or ~/.oshrc.
# https://unix.stackexchange.com/questions/24347/why-do-some-applications-use-config-appname-for-their-config-data-while-other
home_dir = pyos.GetMyHomeDir()
assert home_dir is not None
rc_path = flag.rcfile or os_path.join(home_dir, '.config/oil/%src' % lang)
if flag.headless:
state.InitInteractive(mem)
mutable_opts.set_redefine_proc()
mutable_opts.set_redefine_module()
# This is like an interactive shell, so we copy some initialization from
# below. Note: this may need to be tweaked.
_InitDefaultCompletions(cmd_ev, complete_builtin, comp_lookup)
# NOTE: called AFTER _InitDefaultCompletions.
with state.ctx_ThisDir(mem, rc_path):
try:
SourceStartupFile(fd_state, rc_path, lang, parse_ctx, cmd_ev, errfmt)
except util.UserExit as e:
return e.status
loop = main_loop.Headless(cmd_ev, parse_ctx, errfmt)
try:
# TODO: What other exceptions happen here?
status = loop.Loop()
except util.UserExit as e:
status = e.status
# Same logic as interactive shell
box = [status]
cmd_ev.MaybeRunExitTrap(box)
status = box[0]
return status
if exec_opts.interactive():
state.InitInteractive(mem)
# bash: 'set -o emacs' is the default only in the interactive shell
mutable_opts.set_emacs()
mutable_opts.set_redefine_proc()
mutable_opts.set_redefine_module()
if line_input:
# NOTE: We're using a different WordEvaluator here.
ev = word_eval.CompletionWordEvaluator(mem, exec_opts, mutable_opts,
splitter, errfmt)
ev.arith_ev = arith_ev
ev.expr_ev = expr_ev
ev.prompt_ev = prompt_ev
ev.CheckCircularDeps()
root_comp = completion.RootCompleter(ev, mem, comp_lookup, compopt_state,
comp_ui_state, comp_ctx, debug_f)
term_width = 0
if flag.completion_display == 'nice':
try:
term_width = libc.get_terminal_width()
except IOError: # stdin not a terminal
pass
if term_width != 0:
display = comp_ui.NiceDisplay(term_width, comp_ui_state, prompt_state,
debug_f, line_input) # type: comp_ui._IDisplay
else:
display = comp_ui.MinimalDisplay(comp_ui_state, prompt_state, debug_f)
history_filename = os_path.join(home_dir, '.config/oil/history_%s' % lang)
comp_ui.InitReadline(line_input, history_filename, root_comp, display,
debug_f)
_InitDefaultCompletions(cmd_ev, complete_builtin, comp_lookup)
else: # Without readline module
display = comp_ui.MinimalDisplay(comp_ui_state, prompt_state, debug_f)
sig_state.InitInteractiveShell(display, my_pid)
# NOTE: called AFTER _InitDefaultCompletions.
with state.ctx_ThisDir(mem, rc_path):
try:
SourceStartupFile(fd_state, rc_path, lang, parse_ctx, cmd_ev, errfmt)
except util.UserExit as e:
return e.status
line_reader.Reset() # After sourcing startup file, render $PS1
prompt_plugin = prompt.UserPlugin(mem, parse_ctx, cmd_ev, errfmt)
try:
status = main_loop.Interactive(flag, cmd_ev, c_parser, display,
prompt_plugin, errfmt)
except util.UserExit as e:
status = e.status
box = [status]
cmd_ev.MaybeRunExitTrap(box)
status = box[0]
return status
if flag.rcfile: # bash doesn't have this warning, but it's useful
stderr_line('osh warning: --rcfile ignored in non-interactive shell')
if exec_opts.noexec():
status = 0
try:
node = main_loop.ParseWholeFile(c_parser)
except error.Parse as e:
errfmt.PrettyPrintError(e)
status = 2
if status == 0 :
if flag.parser_mem_dump is not None: # only valid in -n mode
input_path = '/proc/%d/status' % posix.getpid()
pyutil.CopyFile(input_path, flag.parser_mem_dump)
ui.PrintAst(node, flag)
else:
if flag.parser_mem_dump is not None:
raise error.Usage('--parser-mem-dump can only be used with -n')
with state.ctx_ThisDir(mem, script_name):
try:
status = main_loop.Batch(cmd_ev, c_parser, errfmt,
cmd_flags=cmd_eval.IsMainProgram)
except util.UserExit as e:
status = e.status
box = [status]
cmd_ev.MaybeRunExitTrap(box)
status = box[0]
# NOTE: 'exit 1' is ControlFlow and gets here, but subshell/commandsub
# don't because they call sys.exit().
if flag.runtime_mem_dump is not None:
input_path = '/proc/%d/status' % posix.getpid()
pyutil.CopyFile(input_path, flag.runtime_mem_dump)
# NOTE: We haven't closed the file opened with fd_state.Open
return status