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

243 lines, 146 significant
1#!/usr/bin/env python2
2"""
3builtin/io_ysh.py - YSH builtins that perform I/O
4"""
5from __future__ import print_function
6
7from _devbuild.gen import arg_types
8from _devbuild.gen.runtime_asdl import cmd_value
9from _devbuild.gen.syntax_asdl import command_e, BraceGroup, loc
10from asdl import format as fmt
11from core import error
12from core.error import e_usage
13from core import state
14from core import ui
15from core import vm
16from data_lang import j8
17from frontend import flag_util
18from frontend import match
19from frontend import typed_args
20from mycpp import mylib
21from mycpp.mylib import log
22
23from typing import TYPE_CHECKING, cast
24if TYPE_CHECKING:
25 from core.alloc import Arena
26 from core.ui import ErrorFormatter
27 from osh import cmd_eval
28
29_ = log
30
31
32class _Builtin(vm._Builtin):
33
34 def __init__(self, mem, errfmt):
35 # type: (state.Mem, ErrorFormatter) -> None
36 self.mem = mem
37 self.errfmt = errfmt
38
39
40class Pp(_Builtin):
41 """Given a list of variable names, print their values.
42
43 'pp cell a' is a lot easier to type than 'argv.py "${a[@]}"'.
44 """
45
46 def __init__(self, mem, errfmt, procs, arena):
47 # type: (state.Mem, ErrorFormatter, state.Procs, Arena) -> None
48 _Builtin.__init__(self, mem, errfmt)
49 self.procs = procs
50 self.arena = arena
51 self.stdout_ = mylib.Stdout()
52
53 def Run(self, cmd_val):
54 # type: (cmd_value.Argv) -> int
55 arg, arg_r = flag_util.ParseCmdVal('pp',
56 cmd_val,
57 accept_typed_args=True)
58
59 action, action_loc = arg_r.ReadRequired2(
60 'expected an action (proc, cell, etc.)')
61
62 # Actions that print unstable formats start with '.'
63 if action == 'cell':
64 argv, locs = arg_r.Rest2()
65
66 status = 0
67 for i, name in enumerate(argv):
68 if name.startswith(':'):
69 name = name[1:]
70
71 if not match.IsValidVarName(name):
72 raise error.Usage('got invalid variable name %r' % name,
73 locs[i])
74
75 cell = self.mem.GetCell(name)
76 if cell is None:
77 self.errfmt.Print_("Couldn't find a variable named %r" %
78 name,
79 blame_loc=locs[i])
80 status = 1
81 else:
82 self.stdout_.write('%s = ' % name)
83 pretty_f = fmt.DetectConsoleOutput(self.stdout_)
84 fmt.PrintTree(cell.PrettyTree(), pretty_f)
85 self.stdout_.write('\n')
86
87 elif action == 'asdl':
88 # TODO: could be pp asdl (x, y, z)
89 rd = typed_args.ReaderForProc(cmd_val)
90 val = rd.PosValue()
91 rd.Done()
92
93 tree = val.PrettyTree()
94 #tree = val.AbbreviatedTree() # I used this to test cycle detection
95
96 # TODO: ASDL should print the IDs. And then they will be
97 # line-wrapped.
98 # The IDs should also be used to detect cycles, and omit values
99 # already printed.
100 #id_str = vm.ValueIdString(val)
101 #f.write(' <%s%s>\n' % (ysh_type, id_str))
102
103 pretty_f = fmt.DetectConsoleOutput(self.stdout_)
104 fmt.PrintTree(tree, pretty_f)
105 self.stdout_.write('\n')
106
107 status = 0
108
109 elif action == 'line':
110 # Print format for unit tests
111
112 # TODO: could be pp line (x, y, z)
113 rd = typed_args.ReaderForProc(cmd_val)
114 val = rd.PosValue()
115 rd.Done()
116
117 ysh_type = ui.ValType(val)
118 self.stdout_.write('(%s) ' % ysh_type)
119
120 j8.PrintLine(val, self.stdout_)
121
122 status = 0
123
124 elif action == 'gc-stats':
125 print('TODO')
126 status = 0
127
128 elif action == 'proc':
129 names, locs = arg_r.Rest2()
130 if len(names):
131 for i, name in enumerate(names):
132 node = self.procs.Get(name)
133 if node is None:
134 self.errfmt.Print_('Invalid proc %r' % name,
135 blame_loc=locs[i])
136 return 1
137 else:
138 names = self.procs.GetNames()
139
140 # TSV8 header
141 print('proc_name\tdoc_comment')
142 for name in names:
143 proc = self.procs.Get(name) # must exist
144 #log('Proc %s', proc)
145 body = proc.body
146
147 # TODO: not just command.ShFunction, but command.Proc!
148 doc = ''
149 if body.tag() == command_e.BraceGroup:
150 bgroup = cast(BraceGroup, body)
151 if bgroup.doc_token:
152 token = bgroup.doc_token
153 # 1 to remove leading space
154 doc = token.line.content[token.col + 1:token.col +
155 token.length]
156
157 # Note: these should be attributes on value.Proc
158 buf = mylib.BufWriter()
159 j8.EncodeString(name, buf, unquoted_ok=True)
160 buf.write('\t')
161 j8.EncodeString(doc, buf, unquoted_ok=True)
162 print(buf.getvalue())
163
164 status = 0
165
166 else:
167 e_usage('got invalid action %r' % action, action_loc)
168
169 return status
170
171
172class Write(_Builtin):
173 """
174 write -- @strs
175 write --sep ' ' --end '' -- @strs
176 write -n -- @
177 write --j8 -- @strs # argv serialization
178 write --j8 --sep $'\t' -- @strs # this is like TSV8
179 """
180
181 def __init__(self, mem, errfmt):
182 # type: (state.Mem, ErrorFormatter) -> None
183 _Builtin.__init__(self, mem, errfmt)
184 self.stdout_ = mylib.Stdout()
185
186 def Run(self, cmd_val):
187 # type: (cmd_value.Argv) -> int
188 attrs, arg_r = flag_util.ParseCmdVal('write', cmd_val)
189 arg = arg_types.write(attrs.attrs)
190 #print(arg)
191
192 i = 0
193 while not arg_r.AtEnd():
194 if i != 0:
195 self.stdout_.write(arg.sep)
196 s = arg_r.Peek()
197
198 if arg.json:
199 s = j8.MaybeEncodeJsonString(s)
200
201 elif arg.j8:
202 s = j8.MaybeEncodeString(s)
203
204 self.stdout_.write(s)
205
206 arg_r.Next()
207 i += 1
208
209 if arg.n:
210 pass
211 elif len(arg.end):
212 self.stdout_.write(arg.end)
213
214 return 0
215
216
217class Fopen(vm._Builtin):
218 """fopen does nothing but run a block.
219
220 It's used solely for its redirects.
221 fopen >out.txt { echo hi }
222
223 It's a subset of eval
224 eval >out.txt { echo hi }
225 """
226
227 def __init__(self, mem, cmd_ev):
228 # type: (state.Mem, cmd_eval.CommandEvaluator) -> None
229 self.mem = mem
230 self.cmd_ev = cmd_ev # To run blocks
231
232 def Run(self, cmd_val):
233 # type: (cmd_value.Argv) -> int
234 _, arg_r = flag_util.ParseCmdVal('fopen',
235 cmd_val,
236 accept_typed_args=True)
237
238 cmd = typed_args.OptionalBlock(cmd_val)
239 if not cmd:
240 raise error.Usage('expected a block', loc.Missing)
241
242 unused = self.cmd_ev.EvalCommand(cmd)
243 return 0