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