OILS / builtin / pure_osh.py View on Github | oils.pub

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