OILS / frontend / flag_util.py View on Github | oilshell.org

69 lines, 35 significant
1"""
2flag_util.py - API for builtin commands
3"""
4from __future__ import print_function
5
6from _devbuild.gen.runtime_asdl import cmd_value
7from _devbuild.gen.syntax_asdl import ArgList
8from core.error import e_usage
9from frontend import args
10from frontend import flag_spec
11from mycpp import mylib
12
13from typing import Tuple, Optional
14
15if mylib.PYTHON:
16
17 def LookupFlagSpec(name):
18 # type: (str) -> flag_spec._FlagSpec
19 return flag_spec.FLAG_SPEC[name]
20
21 def LookupFlagSpec2(name):
22 # type: (str) -> flag_spec._FlagSpecAndMore
23 return flag_spec.FLAG_SPEC_AND_MORE[name]
24
25
26def _DoesNotAccept(arg_list):
27 # type: (Optional[ArgList]) -> None
28 """ Copy from frontend/typed_args.py, to break dependency """
29 if arg_list is not None:
30 e_usage('got unexpected typed args', arg_list.left)
31
32
33def ParseCmdVal(spec_name, cmd_val, accept_typed_args=False):
34 # type: (str, cmd_value.Argv, bool) -> Tuple[args._Attributes, args.Reader]
35
36 if not accept_typed_args:
37 _DoesNotAccept(cmd_val.typed_args)
38
39 arg_r = args.Reader(cmd_val.argv, locs=cmd_val.arg_locs)
40 arg_r.Next() # move past the builtin name
41
42 spec = LookupFlagSpec(spec_name)
43 return args.Parse(spec, arg_r), arg_r
44
45
46def ParseLikeEcho(spec_name, cmd_val):
47 # type: (str, cmd_value.Argv) -> Tuple[args._Attributes, args.Reader]
48
49 _DoesNotAccept(cmd_val.typed_args)
50
51 arg_r = args.Reader(cmd_val.argv, locs=cmd_val.arg_locs)
52 arg_r.Next() # move past the builtin name
53
54 spec = LookupFlagSpec(spec_name)
55 return args.ParseLikeEcho(spec, arg_r), arg_r
56
57
58def Parse(spec_name, arg_r):
59 # type: (str, args.Reader) -> args._Attributes
60 """Parse argv using a given FlagSpec."""
61 spec = LookupFlagSpec(spec_name)
62 return args.Parse(spec, arg_r)
63
64
65def ParseMore(spec_name, arg_r):
66 # type: (str, args.Reader) -> args._Attributes
67 """Parse argv using a given FlagSpecAndMore."""
68 spec = LookupFlagSpec2(spec_name)
69 return args.ParseMore(spec, arg_r)