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

490 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: (bool, List[str]) -> None
198 if use_set_opts:
199 self.mutable_opts.ShowOptions(opt_names)
200 else:
201 self.mutable_opts.ShowShoptOptions(opt_names)
202
203 def Run(self, cmd_val):
204 # type: (cmd_value.Argv) -> int
205 attrs, arg_r = flag_util.ParseCmdVal('shopt',
206 cmd_val,
207 accept_typed_args=True)
208
209 arg = arg_types.shopt(attrs.attrs)
210 opt_names = arg_r.Rest()
211
212 if arg.q: # query values
213 for name in opt_names:
214 index = consts.OptionNum(name)
215 if index == 0:
216 return 2 # bash gives 1 for invalid option; 2 is better
217 if not self.mutable_opts.opt0_array[index]:
218 return 1 # at least one option is not true
219 return 0 # all options are true
220
221 if arg.s:
222 b = True
223 elif arg.u:
224 b = False
225 elif arg.p: # explicit -p
226 self._PrintOptions(arg.o, opt_names)
227 return 0
228 else: # otherwise -p is implicit
229 self._PrintOptions(arg.o, opt_names)
230 return 0
231
232 # shopt --set x { my-block }
233 cmd = typed_args.OptionalBlock(cmd_val)
234 if cmd:
235 opt_nums = [] # type: List[int]
236 for opt_name in opt_names:
237 # TODO: could consolidate with checks in core/state.py and option
238 # lexer?
239 opt_group = consts.OptionGroupNum(opt_name)
240 if opt_group == opt_group_i.YshUpgrade:
241 opt_nums.extend(consts.YSH_UPGRADE)
242 continue
243
244 if opt_group == opt_group_i.YshAll:
245 opt_nums.extend(consts.YSH_ALL)
246 continue
247
248 if opt_group == opt_group_i.StrictAll:
249 opt_nums.extend(consts.STRICT_ALL)
250 continue
251
252 index = consts.OptionNum(opt_name)
253 if index == 0:
254 # TODO: location info
255 e_usage('got invalid option %r' % opt_name, loc.Missing)
256 opt_nums.append(index)
257
258 with state.ctx_Option(self.mutable_opts, opt_nums, b):
259 unused = self.cmd_ev.EvalCommand(cmd)
260 return 0 # cd also returns 0
261
262 # Otherwise, set options.
263 for opt_name in opt_names:
264 # We allow set -o options here
265 self.mutable_opts.SetAnyOption(opt_name, b)
266
267 return 0
268
269
270class Hash(vm._Builtin):
271
272 def __init__(self, search_path):
273 # type: (SearchPath) -> None
274 self.search_path = search_path
275
276 def Run(self, cmd_val):
277 # type: (cmd_value.Argv) -> int
278 attrs, arg_r = flag_util.ParseCmdVal('hash', cmd_val)
279 arg = arg_types.hash(attrs.attrs)
280
281 rest = arg_r.Rest()
282 if arg.r:
283 if len(rest):
284 e_usage('got extra arguments after -r', loc.Missing)
285 self.search_path.ClearCache()
286 return 0
287
288 status = 0
289 if len(rest):
290 for cmd in rest: # enter in cache
291 full_path = self.search_path.CachedLookup(cmd)
292 if full_path is None:
293 print_stderr('hash: %r not found' % cmd)
294 status = 1
295 else: # print cache
296 commands = self.search_path.CachedCommands()
297 commands.sort()
298 for cmd in commands:
299 print(cmd)
300
301 return status
302
303
304def _ParseOptSpec(spec_str):
305 # type: (str) -> Dict[str, bool]
306 spec = {} # type: Dict[str, bool]
307 i = 0
308 n = len(spec_str)
309 while True:
310 if i >= n:
311 break
312 ch = spec_str[i]
313 spec[ch] = False
314 i += 1
315 if i >= n:
316 break
317 # If the next character is :, change the value to True.
318 if spec_str[i] == ':':
319 spec[ch] = True
320 i += 1
321 return spec
322
323
324class GetOptsState(object):
325 """State persisted across invocations.
326
327 This would be simpler in GetOpts.
328 """
329
330 def __init__(self, mem, errfmt):
331 # type: (Mem, ui.ErrorFormatter) -> None
332 self.mem = mem
333 self.errfmt = errfmt
334 self._optind = -1
335 self.flag_pos = 1 # position within the arg, public var
336
337 def _OptInd(self):
338 # type: () -> int
339 """Returns OPTIND that's >= 1, or -1 if it's invalid."""
340 # Note: OPTIND could be value.Int?
341 try:
342 result = state.GetInteger(self.mem, 'OPTIND')
343 except error.Runtime as e:
344 self.errfmt.Print_(e.UserErrorString())
345 result = -1
346 return result
347
348 def GetArg(self, argv):
349 # type: (List[str]) -> Optional[str]
350 """Get the value of argv at OPTIND.
351
352 Returns None if it's out of range.
353 """
354
355 #log('_optind %d flag_pos %d', self._optind, self.flag_pos)
356
357 optind = self._OptInd()
358 if optind == -1:
359 return None
360 self._optind = optind # save for later
361
362 i = optind - 1 # 1-based index
363 #log('argv %s i %d', argv, i)
364 if 0 <= i and i < len(argv):
365 return argv[i]
366 else:
367 return None
368
369 def IncIndex(self):
370 # type: () -> None
371 """Increment OPTIND."""
372 # Note: bash-completion uses a *local* OPTIND ! Not global.
373 assert self._optind != -1
374 state.BuiltinSetString(self.mem, 'OPTIND', str(self._optind + 1))
375 self.flag_pos = 1
376
377 def SetArg(self, optarg):
378 # type: (str) -> None
379 """Set OPTARG."""
380 state.BuiltinSetString(self.mem, 'OPTARG', optarg)
381
382 def Fail(self):
383 # type: () -> None
384 """On failure, reset OPTARG."""
385 state.BuiltinSetString(self.mem, 'OPTARG', '')
386
387
388def _GetOpts(
389 spec, # type: Dict[str, bool]
390 argv, # type: List[str]
391 my_state, # type: GetOptsState
392 errfmt, # type: ui.ErrorFormatter
393):
394 # type: (...) -> Tuple[int, str]
395 current = my_state.GetArg(argv)
396 #log('current %s', current)
397
398 if current is None: # out of range, etc.
399 my_state.Fail()
400 return 1, '?'
401
402 if not current.startswith('-') or current == '-':
403 my_state.Fail()
404 return 1, '?'
405
406 flag_char = current[my_state.flag_pos]
407
408 if my_state.flag_pos < len(current) - 1:
409 my_state.flag_pos += 1 # don't move past this arg yet
410 more_chars = True
411 else:
412 my_state.IncIndex()
413 my_state.flag_pos = 1
414 more_chars = False
415
416 if flag_char not in spec: # Invalid flag
417 return 0, '?'
418
419 if spec[flag_char]: # does it need an argument?
420 if more_chars:
421 optarg = current[my_state.flag_pos:]
422 else:
423 optarg = my_state.GetArg(argv)
424 if optarg is None:
425 my_state.Fail()
426 # TODO: Add location info
427 errfmt.Print_('getopts: option %r requires an argument.' %
428 current)
429 tmp = [j8_lite.MaybeShellEncode(a) for a in argv]
430 print_stderr('(getopts argv: %s)' % ' '.join(tmp))
431
432 # Hm doesn't cause status 1?
433 return 0, '?'
434 my_state.IncIndex()
435 my_state.SetArg(optarg)
436 else:
437 my_state.SetArg('')
438
439 return 0, flag_char
440
441
442class GetOpts(vm._Builtin):
443 """
444 Vars used:
445 OPTERR: disable printing of error messages
446 Vars set:
447 The variable named by the second arg
448 OPTIND - initialized to 1 at startup
449 OPTARG - argument
450 """
451
452 def __init__(self, mem, errfmt):
453 # type: (Mem, ui.ErrorFormatter) -> None
454 self.mem = mem
455 self.errfmt = errfmt
456
457 # TODO: state could just be in this object
458 self.my_state = GetOptsState(mem, errfmt)
459 self.spec_cache = {} # type: Dict[str, Dict[str, bool]]
460
461 def Run(self, cmd_val):
462 # type: (cmd_value.Argv) -> int
463 arg_r = args.Reader(cmd_val.argv, locs=cmd_val.arg_locs)
464 arg_r.Next()
465
466 # NOTE: If first char is a colon, error reporting is different. Alpine
467 # might not use that?
468 spec_str = arg_r.ReadRequired('requires an argspec')
469
470 var_name, var_loc = arg_r.ReadRequired2(
471 'requires the name of a variable to set')
472
473 spec = self.spec_cache.get(spec_str)
474 if spec is None:
475 spec = _ParseOptSpec(spec_str)
476 self.spec_cache[spec_str] = spec
477
478 user_argv = self.mem.GetArgv() if arg_r.AtEnd() else arg_r.Rest()
479 #log('user_argv %s', user_argv)
480 status, flag_char = _GetOpts(spec, user_argv, self.my_state,
481 self.errfmt)
482
483 if match.IsValidVarName(var_name):
484 state.BuiltinSetString(self.mem, var_name, flag_char)
485 else:
486 # NOTE: The builtin has PARTIALLY set state. This happens in all shells
487 # except mksh.
488 raise error.Usage('got invalid variable name %r' % var_name,
489 var_loc)
490 return status