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

597 lines, 378 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
440 def _OptInd(self):
441 # type: () -> int
442 """Returns OPTIND that's >= 1, or -1 if it's invalid."""
443 # Note: OPTIND could be value.Int?
444 try:
445 result = state.GetInteger(self.mem, 'OPTIND')
446 except error.Runtime as e:
447 self.errfmt.Print_(e.UserErrorString())
448 result = -1
449 return result
450
451 def GetArg(self, argv):
452 # type: (List[str]) -> Optional[str]
453 """Get the value of argv at OPTIND.
454
455 Returns None if it's out of range.
456 """
457
458 #log('_optind %d flag_pos %d', self._optind, self.flag_pos)
459
460 optind = self._OptInd()
461 if optind == -1:
462 return None
463 self._optind = optind # save for later
464
465 i = optind - 1 # 1-based index
466 #log('argv %s i %d', argv, i)
467 if 0 <= i and i < len(argv):
468 return argv[i]
469 else:
470 return None
471
472 def IncIndex(self):
473 # type: () -> None
474 """Increment OPTIND."""
475 # Note: bash-completion uses a *local* OPTIND ! Not global.
476 assert self._optind != -1
477 state.BuiltinSetString(self.mem, 'OPTIND', str(self._optind + 1))
478 self.flag_pos = 1
479
480 def SetArg(self, optarg):
481 # type: (str) -> None
482 """Set OPTARG."""
483 state.BuiltinSetString(self.mem, 'OPTARG', optarg)
484
485 def Fail(self):
486 # type: () -> None
487 """On failure, reset OPTARG."""
488 state.BuiltinSetString(self.mem, 'OPTARG', '')
489
490
491def _GetOpts(
492 spec, # type: Dict[str, bool]
493 argv, # type: List[str]
494 my_state, # type: GetOptsState
495 errfmt, # type: ui.ErrorFormatter
496):
497 # type: (...) -> Tuple[int, str]
498 current = my_state.GetArg(argv)
499 #log('current %s', current)
500
501 if current is None: # out of range, etc.
502 my_state.Fail()
503 return 1, '?'
504
505 if not current.startswith('-') or current == '-':
506 my_state.Fail()
507 return 1, '?'
508
509 if current == "--": # special case, stop processing remaining args
510 my_state.IncIndex()
511 return 1, '?'
512
513 flag_char = current[my_state.flag_pos]
514
515 if my_state.flag_pos < len(current) - 1:
516 my_state.flag_pos += 1 # don't move past this arg yet
517 more_chars = True
518 else:
519 my_state.IncIndex()
520 my_state.flag_pos = 1
521 more_chars = False
522
523 if flag_char not in spec: # Invalid flag
524 return 0, '?'
525
526 if spec[flag_char]: # does it need an argument?
527 if more_chars:
528 optarg = current[my_state.flag_pos:]
529 else:
530 optarg = my_state.GetArg(argv)
531 if optarg is None:
532 my_state.Fail()
533 # TODO: Add location info
534 errfmt.Print_('getopts: option %r requires an argument.' %
535 current)
536 tmp = [j8_lite.MaybeShellEncode(a) for a in argv]
537 print_stderr('(getopts argv: %s)' % ' '.join(tmp))
538
539 # Hm doesn't cause status 1?
540 return 0, '?'
541 my_state.IncIndex()
542 my_state.SetArg(optarg)
543 else:
544 my_state.SetArg('')
545
546 return 0, flag_char
547
548
549class GetOpts(vm._Builtin):
550 """
551 Vars used:
552 OPTERR: disable printing of error messages
553 Vars set:
554 The variable named by the second arg
555 OPTIND - initialized to 1 at startup
556 OPTARG - argument
557 """
558
559 def __init__(self, mem, errfmt):
560 # type: (Mem, ui.ErrorFormatter) -> None
561 self.mem = mem
562 self.errfmt = errfmt
563
564 # TODO: state could just be in this object
565 self.my_state = GetOptsState(mem, errfmt)
566 self.spec_cache = {} # type: Dict[str, Dict[str, bool]]
567
568 def Run(self, cmd_val):
569 # type: (cmd_value.Argv) -> int
570 arg_r = args.Reader(cmd_val.argv, locs=cmd_val.arg_locs)
571 arg_r.Next()
572
573 # NOTE: If first char is a colon, error reporting is different. Alpine
574 # might not use that?
575 spec_str = arg_r.ReadRequired('requires an argspec')
576
577 var_name, var_loc = arg_r.ReadRequired2(
578 'requires the name of a variable to set')
579
580 spec = self.spec_cache.get(spec_str)
581 if spec is None:
582 spec = _ParseOptSpec(spec_str)
583 self.spec_cache[spec_str] = spec
584
585 user_argv = self.mem.GetArgv() if arg_r.AtEnd() else arg_r.Rest()
586 #log('user_argv %s', user_argv)
587 status, flag_char = _GetOpts(spec, user_argv, self.my_state,
588 self.errfmt)
589
590 if match.IsValidVarName(var_name):
591 state.BuiltinSetString(self.mem, var_name, flag_char)
592 else:
593 # NOTE: The builtin has PARTIALLY set state. This happens in all shells
594 # except mksh.
595 raise error.Usage('got invalid variable name %r' % var_name,
596 var_loc)
597 return status