OILS / builtin / pure_osh.py View on Github | oilshell.org

581 lines, 365 significant
1#!/usr/bin/env python2
2"""
3pure_osh.py - Builtins that don't do any I/O.
4
5If the OSH interpreter were embedded in another program, these builtins can be
6safely used, e.g. without worrying about modifying the file system.
7
8NOTE: There can be spew on stdout, e.g. for shopt -p and so forth.
9"""
10from __future__ import print_function
11
12from _devbuild.gen import arg_types
13from _devbuild.gen.syntax_asdl import loc
14from _devbuild.gen.types_asdl import opt_group_i
15
16from core import error
17from core.error import e_usage
18from core import state
19from display import ui
20from core import vm
21from data_lang import j8_lite
22from frontend import args
23from frontend import consts
24from frontend import flag_util
25from frontend import match
26from frontend import typed_args
27from mycpp import mylib
28from mycpp.mylib import print_stderr, log
29
30from typing import List, Dict, Tuple, Optional, TYPE_CHECKING
31if TYPE_CHECKING:
32 from _devbuild.gen.runtime_asdl import cmd_value
33 from core import optview
34 from core.state import MutableOpts, Mem
35 from core import executor
36 from osh.cmd_eval import CommandEvaluator
37
38_ = log
39
40
41class Boolean(vm._Builtin):
42 """For :, true, false."""
43
44 def __init__(self, status):
45 # type: (int) -> None
46 self.status = status
47
48 def Run(self, cmd_val):
49 # type: (cmd_value.Argv) -> int
50
51 # These ignore regular args, but shouldn't accept typed args.
52 typed_args.DoesNotAccept(cmd_val.proc_args)
53 return self.status
54
55
56class Alias(vm._Builtin):
57
58 def __init__(self, aliases, errfmt):
59 # type: (Dict[str, str], ui.ErrorFormatter) -> None
60 self.aliases = aliases
61 self.errfmt = errfmt
62
63 def Run(self, cmd_val):
64 # type: (cmd_value.Argv) -> int
65 _, arg_r = flag_util.ParseCmdVal('alias', cmd_val)
66 argv = arg_r.Rest()
67
68 if len(argv) == 0:
69 for name in sorted(self.aliases):
70 alias_exp = self.aliases[name]
71 # This is somewhat like bash, except we use %r for ''.
72 print('alias %s=%r' % (name, alias_exp))
73 return 0
74
75 status = 0
76 for i, arg in enumerate(argv):
77 name, alias_exp = mylib.split_once(arg, '=')
78 if alias_exp is None: # if we get a plain word without, print alias
79 alias_exp = self.aliases.get(name)
80 if alias_exp is None:
81 self.errfmt.Print_('No alias named %r' % name,
82 blame_loc=cmd_val.arg_locs[i])
83 status = 1
84 else:
85 print('alias %s=%r' % (name, alias_exp))
86 else:
87 self.aliases[name] = alias_exp
88
89 #print(argv)
90 #log('AFTER ALIAS %s', aliases)
91 return status
92
93
94class UnAlias(vm._Builtin):
95
96 def __init__(self, aliases, errfmt):
97 # type: (Dict[str, str], ui.ErrorFormatter) -> None
98 self.aliases = aliases
99 self.errfmt = errfmt
100
101 def Run(self, cmd_val):
102 # type: (cmd_value.Argv) -> int
103 attrs, arg_r = flag_util.ParseCmdVal('unalias', cmd_val)
104 arg = arg_types.unalias(attrs.attrs)
105
106 if arg.a:
107 self.aliases.clear()
108 return 0
109
110 argv = arg_r.Rest()
111
112 if len(argv) == 0:
113 e_usage('requires an argument', loc.Missing)
114
115 status = 0
116 for i, name in enumerate(argv):
117 if name in self.aliases:
118 mylib.dict_erase(self.aliases, name)
119 else:
120 self.errfmt.Print_('No alias named %r' % name,
121 blame_loc=cmd_val.arg_locs[i])
122 status = 1
123 return status
124
125
126def SetOptionsFromFlags(exec_opts, opt_changes, shopt_changes):
127 # type: (MutableOpts, List[Tuple[str, bool]], List[Tuple[str, bool]]) -> None
128 """Used by core/shell.py."""
129
130 # We can set ANY option with -o. -O is too annoying to type.
131 for opt_name, b in opt_changes:
132 exec_opts.SetAnyOption(opt_name, b)
133
134 for opt_name, b in shopt_changes:
135 exec_opts.SetAnyOption(opt_name, b)
136
137
138def ShowOptions(mutable_opts, opt_names):
139 # type: (state.MutableOpts, List[str]) -> bool
140 """Show traditional options, for 'set -o' and 'shopt -p -o'."""
141 # TODO: Maybe sort them differently?
142
143 if len(opt_names) == 0: # if none, supplied, show all
144 opt_names = [consts.OptionName(i) for i in consts.SET_OPTION_NUMS]
145
146 any_false = False
147 for opt_name in opt_names:
148 opt_num = state._SetOptionNum(opt_name)
149 b = mutable_opts.Get(opt_num)
150 if not b:
151 any_false = True
152 print('set %so %s' % ('-' if b else '+', opt_name))
153 return any_false
154
155
156def _ShowShoptOptions(mutable_opts, opt_nums):
157 # type: (state.MutableOpts, List[int]) -> bool
158 """For 'shopt -p'."""
159
160 if len(opt_nums) == 0:
161 # If none supplied, show all
162 # Note: the way to show BOTH shopt and set options should be a
163 # __shopt__ Dict
164 opt_nums.extend(consts.VISIBLE_SHOPT_NUMS)
165
166 any_false = False
167 for opt_num in opt_nums:
168 b = mutable_opts.Get(opt_num)
169 if not b:
170 any_false = True
171 print('shopt -%s %s' % ('s' if b else 'u', consts.OptionName(opt_num)))
172 return any_false
173
174
175class Set(vm._Builtin):
176
177 def __init__(self, exec_opts, mem):
178 # type: (MutableOpts, Mem) -> None
179 self.exec_opts = exec_opts
180 self.mem = mem
181
182 def Run(self, cmd_val):
183 # type: (cmd_value.Argv) -> int
184
185 # TODO:
186 # - How to integrate this with auto-completion? Have to handle '+'.
187
188 if len(cmd_val.argv) == 1:
189 # 'set' without args shows visible variable names and values. According
190 # to POSIX:
191 # - the names should be sorted, and
192 # - the code should be suitable for re-input to the shell. We have a
193 # spec test for this.
194 # Also:
195 # - autoconf also wants them to fit on ONE LINE.
196 # http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
197 mapping = self.mem.GetAllVars()
198 for name in sorted(mapping):
199 str_val = mapping[name]
200 code_str = '%s=%s' % (name, j8_lite.MaybeShellEncode(str_val))
201 print(code_str)
202 return 0
203
204 arg_r = args.Reader(cmd_val.argv, locs=cmd_val.arg_locs)
205 arg_r.Next() # skip 'set'
206 arg = flag_util.ParseMore('set', arg_r)
207
208 # 'set -o' shows options. This is actually used by autoconf-generated
209 # scripts!
210 if arg.show_options:
211 ShowOptions(self.exec_opts, [])
212 return 0
213
214 # Note: set -o nullglob is not valid. The 'shopt' builtin is preferred in
215 # YSH, and we want code to be consistent.
216 for opt_name, b in arg.opt_changes:
217 self.exec_opts.SetOldOption(opt_name, b)
218
219 for opt_name, b in arg.shopt_changes:
220 self.exec_opts.SetAnyOption(opt_name, b)
221
222 # Hm do we need saw_double_dash?
223 if arg.saw_double_dash or not arg_r.AtEnd():
224 self.mem.SetArgv(arg_r.Rest())
225 return 0
226
227
228class Shopt(vm._Builtin):
229
230 def __init__(self, exec_opts, mutable_opts, cmd_ev, mem, environ):
231 # type: (optview.Exec, MutableOpts, CommandEvaluator, state.Mem, Dict[str, str]) -> None
232 self.exec_opts = exec_opts
233 self.mutable_opts = mutable_opts
234 self.cmd_ev = cmd_ev
235 self.mem = mem
236 self.environ = environ
237
238 def _PrintOptions(self, use_set_opts, opt_names):
239 # type: (bool, List[str]) -> int
240 if use_set_opts:
241 any_false = ShowOptions(self.mutable_opts, opt_names)
242
243 if len(opt_names):
244 # bash behavior: behave like -q if options are set
245 return 1 if any_false else 0
246 else:
247 return 0
248 else:
249 # Respect option groups like ysh:upgrade
250 any_single_names = False
251 opt_nums = [] # type: List[int]
252 for opt_name in opt_names:
253 opt_group = consts.OptionGroupNum(opt_name)
254 if opt_group == opt_group_i.YshUpgrade:
255 opt_nums.extend(consts.YSH_UPGRADE)
256 elif opt_group == opt_group_i.YshAll:
257 opt_nums.extend(consts.YSH_ALL)
258 elif opt_group == opt_group_i.StrictAll:
259 opt_nums.extend(consts.STRICT_ALL)
260
261 else:
262 index = consts.OptionNum(opt_name)
263 # Minor incompatibility with bash: we validate everything
264 # before printing.
265 if index == 0:
266 if self.exec_opts.ignore_shopt_not_impl():
267 index = consts.UnimplOptionNum(opt_name)
268 if index == 0:
269 e_usage('got invalid option %r' % opt_name,
270 loc.Missing)
271 opt_nums.append(index)
272 any_single_names = True
273
274 any_false = _ShowShoptOptions(self.mutable_opts, opt_nums)
275
276 if any_single_names:
277 # bash behavior: behave like -q if options are set
278 return 1 if any_false else 0
279 else:
280 return 0
281
282 def Run(self, cmd_val):
283 # type: (cmd_value.Argv) -> int
284 attrs, arg_r = flag_util.ParseCmdVal('shopt',
285 cmd_val,
286 accept_typed_args=True)
287
288 arg = arg_types.shopt(attrs.attrs)
289 opt_names = arg_r.Rest()
290
291 if arg.q: # query values
292 for name in opt_names:
293 index = consts.OptionNum(name)
294 if index == 0:
295 if self.exec_opts.ignore_shopt_not_impl():
296 index = consts.UnimplOptionNum(name)
297 if index == 0:
298 return 2 # bash gives 1 for invalid option; 2 is better
299
300 if not self.mutable_opts.opt0_array[index]:
301 return 1 # at least one option is not true
302
303 return 0 # all options are true
304
305 if arg.s:
306 b = True
307 elif arg.u:
308 b = False
309 elif arg.p: # explicit -p
310 return self._PrintOptions(arg.o, opt_names)
311 else: # otherwise -p is implicit
312 return self._PrintOptions(arg.o, opt_names)
313
314 # shopt --set x { my-block }
315 cmd_frag = typed_args.OptionalBlockAsFrag(cmd_val)
316 if cmd_frag:
317 opt_nums = [] # type: List[int]
318 for opt_name in opt_names:
319 # TODO: could consolidate with checks in core/state.py and option
320 # lexer?
321 opt_group = consts.OptionGroupNum(opt_name)
322 if opt_group == opt_group_i.YshUpgrade:
323 opt_nums.extend(consts.YSH_UPGRADE)
324 if b:
325 self.mem.MaybeInitEnvDict(self.environ)
326 continue
327
328 if opt_group == opt_group_i.YshAll:
329 opt_nums.extend(consts.YSH_ALL)
330 if b:
331 self.mem.MaybeInitEnvDict(self.environ)
332 continue
333
334 if opt_group == opt_group_i.StrictAll:
335 opt_nums.extend(consts.STRICT_ALL)
336 continue
337
338 index = consts.OptionNum(opt_name)
339 if index == 0:
340 if self.exec_opts.ignore_shopt_not_impl():
341 index = consts.UnimplOptionNum(opt_name)
342 if index == 0:
343 # TODO: location info
344 e_usage('got invalid option %r' % opt_name,
345 loc.Missing)
346 opt_nums.append(index)
347
348 with state.ctx_Option(self.mutable_opts, opt_nums, b):
349 unused = self.cmd_ev.EvalCommandFrag(cmd_frag)
350 return 0 # cd also returns 0
351
352 # Otherwise, set options.
353 ignore_shopt_not_impl = self.exec_opts.ignore_shopt_not_impl()
354 for opt_name in opt_names:
355 # We allow set -o options here
356 self.mutable_opts.SetAnyOption(opt_name, b, ignore_shopt_not_impl)
357
358 return 0
359
360
361class Hash(vm._Builtin):
362
363 def __init__(self, search_path):
364 # type: (executor.SearchPath) -> None
365 self.search_path = search_path
366
367 def Run(self, cmd_val):
368 # type: (cmd_value.Argv) -> int
369 attrs, arg_r = flag_util.ParseCmdVal('hash', cmd_val)
370 arg = arg_types.hash(attrs.attrs)
371
372 rest = arg_r.Rest()
373 if arg.r:
374 if len(rest):
375 e_usage('got extra arguments after -r', loc.Missing)
376 self.search_path.ClearCache()
377 return 0
378
379 status = 0
380 if len(rest):
381 for cmd in rest: # enter in cache
382 full_path = self.search_path.CachedLookup(cmd)
383 if full_path is None:
384 print_stderr('hash: %r not found' % cmd)
385 status = 1
386 else: # print cache
387 commands = self.search_path.CachedCommands()
388 commands.sort()
389 for cmd in commands:
390 print(cmd)
391
392 return status
393
394
395def _ParseOptSpec(spec_str):
396 # type: (str) -> Dict[str, bool]
397 spec = {} # type: Dict[str, bool]
398 i = 0
399 n = len(spec_str)
400 while True:
401 if i >= n:
402 break
403 ch = spec_str[i]
404 spec[ch] = False
405 i += 1
406 if i >= n:
407 break
408 # If the next character is :, change the value to True.
409 if spec_str[i] == ':':
410 spec[ch] = True
411 i += 1
412 return spec
413
414
415class GetOptsState(object):
416 """State persisted across invocations.
417
418 This would be simpler in GetOpts.
419 """
420
421 def __init__(self, mem, errfmt):
422 # type: (Mem, ui.ErrorFormatter) -> None
423 self.mem = mem
424 self.errfmt = errfmt
425 self._optind = -1
426 self.flag_pos = 1 # position within the arg, public var
427
428 def _OptInd(self):
429 # type: () -> int
430 """Returns OPTIND that's >= 1, or -1 if it's invalid."""
431 # Note: OPTIND could be value.Int?
432 try:
433 result = state.GetInteger(self.mem, 'OPTIND')
434 except error.Runtime as e:
435 self.errfmt.Print_(e.UserErrorString())
436 result = -1
437 return result
438
439 def GetArg(self, argv):
440 # type: (List[str]) -> Optional[str]
441 """Get the value of argv at OPTIND.
442
443 Returns None if it's out of range.
444 """
445
446 #log('_optind %d flag_pos %d', self._optind, self.flag_pos)
447
448 optind = self._OptInd()
449 if optind == -1:
450 return None
451 self._optind = optind # save for later
452
453 i = optind - 1 # 1-based index
454 #log('argv %s i %d', argv, i)
455 if 0 <= i and i < len(argv):
456 return argv[i]
457 else:
458 return None
459
460 def IncIndex(self):
461 # type: () -> None
462 """Increment OPTIND."""
463 # Note: bash-completion uses a *local* OPTIND ! Not global.
464 assert self._optind != -1
465 state.BuiltinSetString(self.mem, 'OPTIND', str(self._optind + 1))
466 self.flag_pos = 1
467
468 def SetArg(self, optarg):
469 # type: (str) -> None
470 """Set OPTARG."""
471 state.BuiltinSetString(self.mem, 'OPTARG', optarg)
472
473 def Fail(self):
474 # type: () -> None
475 """On failure, reset OPTARG."""
476 state.BuiltinSetString(self.mem, 'OPTARG', '')
477
478
479def _GetOpts(
480 spec, # type: Dict[str, bool]
481 argv, # type: List[str]
482 my_state, # type: GetOptsState
483 errfmt, # type: ui.ErrorFormatter
484):
485 # type: (...) -> Tuple[int, str]
486 current = my_state.GetArg(argv)
487 #log('current %s', current)
488
489 if current is None: # out of range, etc.
490 my_state.Fail()
491 return 1, '?'
492
493 if not current.startswith('-') or current == '-':
494 my_state.Fail()
495 return 1, '?'
496
497 flag_char = current[my_state.flag_pos]
498
499 if my_state.flag_pos < len(current) - 1:
500 my_state.flag_pos += 1 # don't move past this arg yet
501 more_chars = True
502 else:
503 my_state.IncIndex()
504 my_state.flag_pos = 1
505 more_chars = False
506
507 if flag_char not in spec: # Invalid flag
508 return 0, '?'
509
510 if spec[flag_char]: # does it need an argument?
511 if more_chars:
512 optarg = current[my_state.flag_pos:]
513 else:
514 optarg = my_state.GetArg(argv)
515 if optarg is None:
516 my_state.Fail()
517 # TODO: Add location info
518 errfmt.Print_('getopts: option %r requires an argument.' %
519 current)
520 tmp = [j8_lite.MaybeShellEncode(a) for a in argv]
521 print_stderr('(getopts argv: %s)' % ' '.join(tmp))
522
523 # Hm doesn't cause status 1?
524 return 0, '?'
525 my_state.IncIndex()
526 my_state.SetArg(optarg)
527 else:
528 my_state.SetArg('')
529
530 return 0, flag_char
531
532
533class GetOpts(vm._Builtin):
534 """
535 Vars used:
536 OPTERR: disable printing of error messages
537 Vars set:
538 The variable named by the second arg
539 OPTIND - initialized to 1 at startup
540 OPTARG - argument
541 """
542
543 def __init__(self, mem, errfmt):
544 # type: (Mem, ui.ErrorFormatter) -> None
545 self.mem = mem
546 self.errfmt = errfmt
547
548 # TODO: state could just be in this object
549 self.my_state = GetOptsState(mem, errfmt)
550 self.spec_cache = {} # type: Dict[str, Dict[str, bool]]
551
552 def Run(self, cmd_val):
553 # type: (cmd_value.Argv) -> int
554 arg_r = args.Reader(cmd_val.argv, locs=cmd_val.arg_locs)
555 arg_r.Next()
556
557 # NOTE: If first char is a colon, error reporting is different. Alpine
558 # might not use that?
559 spec_str = arg_r.ReadRequired('requires an argspec')
560
561 var_name, var_loc = arg_r.ReadRequired2(
562 'requires the name of a variable to set')
563
564 spec = self.spec_cache.get(spec_str)
565 if spec is None:
566 spec = _ParseOptSpec(spec_str)
567 self.spec_cache[spec_str] = spec
568
569 user_argv = self.mem.GetArgv() if arg_r.AtEnd() else arg_r.Rest()
570 #log('user_argv %s', user_argv)
571 status, flag_char = _GetOpts(spec, user_argv, self.my_state,
572 self.errfmt)
573
574 if match.IsValidVarName(var_name):
575 state.BuiltinSetString(self.mem, var_name, flag_char)
576 else:
577 # NOTE: The builtin has PARTIALLY set state. This happens in all shells
578 # except mksh.
579 raise error.Usage('got invalid variable name %r' % var_name,
580 var_loc)
581 return status