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

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