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

69 lines, 34 significant
1"""
2flag_util.py - API for builtin commands
3"""
4from __future__ import print_function
5
6from _devbuild.gen.runtime_asdl import cmd_value, ProcArgs
7from core.error import e_usage
8from frontend import args
9from frontend import flag_spec
10from mycpp import mylib
11
12from typing import Tuple, Optional
13
14if mylib.PYTHON:
15
16 def LookupFlagSpec(name):
17 # type: (str) -> flag_spec._FlagSpec
18 return flag_spec.FLAG_SPEC[name]
19
20 def LookupFlagSpec2(name):
21 # type: (str) -> flag_spec._FlagSpecAndMore
22 return flag_spec.FLAG_SPEC_AND_MORE[name]
23
24
25def _DoesNotAccept(proc_args):
26 # type: (Optional[ProcArgs]) -> None
27 """ Copy from frontend/typed_args.py, to break dependency """
28 if proc_args is not None:
29 e_usage('got unexpected typed args', proc_args.typed_args.left)
30
31
32def ParseCmdVal(spec_name, cmd_val, accept_typed_args=False):
33 # type: (str, cmd_value.Argv, bool) -> Tuple[args._Attributes, args.Reader]
34
35 if not accept_typed_args:
36 _DoesNotAccept(cmd_val.proc_args)
37
38 #assert len(cmd_val.argv) == len(cmd_val.arg_locs), cmd_val
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.proc_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)