Skip to content

Commit

Permalink
[refactor] Remove redundant ui.Stderr().
Browse files Browse the repository at this point in the history
And translate ui.PrintAst().
  • Loading branch information
Andy Chu committed Jun 15, 2020
1 parent d3c9240 commit f128339
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 76 deletions.
13 changes: 7 additions & 6 deletions bin/oil.py
Expand Up @@ -57,6 +57,7 @@ def _tlog(msg):
from core import shell
from core import optview
from core import pyutil
from core.pyutil import stderr_line
from core import ui
from core.util import log
from frontend import args
Expand Down Expand Up @@ -127,8 +128,8 @@ def OshCommandMain(argv):
try:
f = open(script_name)
except IOError as e:
ui.Stderr("oshc: Couldn't open %r: %s", script_name,
posix.strerror(e.errno))
stderr_line("oshc: Couldn't open %r: %s", script_name,
posix.strerror(e.errno))
return 2

aliases = {} # Dummy value; not respecting aliases!
Expand Down Expand Up @@ -205,8 +206,8 @@ def TeaMain(argv0, argv):
try:
f = open(script_name)
except IOError as e:
ui.Stderr("tea: Couldn't open %r: %s", script_name,
posix.strerror(e.errno))
stderr_line("tea: Couldn't open %r: %s", script_name,
posix.strerror(e.errno))
return 2

aliases = {} # Dummy value; not respecting aliases!
Expand Down Expand Up @@ -295,7 +296,7 @@ def AppBundleMain(argv):
try:
return OshCommandMain(main_argv)
except error.Usage as e:
ui.Stderr('oshc usage error: %s', e.msg)
stderr_line('oshc usage error: %s', e.msg)
return 2

elif main_name == 'oil':
Expand Down Expand Up @@ -344,7 +345,7 @@ def main(argv):
traceback.print_exc()

# test this with prlimit --nproc=1 --pid=$$
ui.Stderr('osh I/O error: %s', posix.strerror(e.errno))
stderr_line('osh I/O error: %s', posix.strerror(e.errno))
return 2 # dash gives status 2
finally:
_tlog('Exiting main()')
Expand Down
15 changes: 8 additions & 7 deletions core/completion.py
Expand Up @@ -42,6 +42,7 @@
from _devbuild.gen.types_asdl import redir_arg_type_e

from core import error
from core.pyutil import stderr_line
from core import ui
from core import util
from core.util import log
Expand Down Expand Up @@ -489,8 +490,8 @@ def Matches(self, comp):
# Not changing it means there were no completions.
# TODO: This writes over the command line; it would be better to use an
# error object.
ui.Stderr('osh: Ran function %r but COMPREPLY was unset',
self.func.name)
stderr_line('osh: Ran function %r but COMPREPLY was unset',
self.func.name)
return []

if val.tag_() != value_e.MaybeStrArray:
Expand Down Expand Up @@ -1203,26 +1204,26 @@ def __call__(self, unused_word, state):
return self._GetNextCompletion(state)
except util.UserExit as e:
# TODO: Could use errfmt to show this
ui.Stderr("osh: Ignoring 'exit' in completion plugin")
stderr_line("osh: Ignoring 'exit' in completion plugin")
except error.FatalRuntime as e:
# From -W. TODO: -F is swallowed now.
# We should have a nicer UI for displaying errors. Maybe they shouldn't
# print it to stderr. That messes up the completion display. We could
# print what WOULD have been COMPREPLY here.
ui.Stderr('osh: Runtime error while completing: %s', e)
stderr_line('osh: Runtime error while completing: %s', e)
self.debug_f.log('Runtime error while completing: %s', e)
except (IOError, OSError) as e:
# test this with prlimit --nproc=1 --pid=$$
ui.Stderr('osh: I/O error in completion: %s', posix.strerror(e.errno))
stderr_line('osh: I/O error in completion: %s', posix.strerror(e.errno))
except KeyboardInterrupt:
# It appears GNU readline handles Ctrl-C to cancel a long completion.
# So this may never happen?
ui.Stderr('Ctrl-C in completion')
stderr_line('Ctrl-C in completion')
except Exception as e: # ESSENTIAL because readline swallows exceptions.
if 0:
import traceback
traceback.print_exc()
ui.Stderr('osh: Unhandled exception while completing: %s', e)
stderr_line('osh: Unhandled exception while completing: %s', e)
self.debug_f.log('Unhandled exception while completing: %s', e)
except SystemExit as e:
# Because readline ignores SystemExit!
Expand Down
5 changes: 3 additions & 2 deletions core/process.py
Expand Up @@ -26,6 +26,7 @@
redir_loc, redir_loc_e, redir_loc_t, redir_loc__VarName, redir_loc__Fd,
)
from qsn_ import qsn
from core.pyutil import stderr_line
from core import util
from core import ui
from core.util import log
Expand Down Expand Up @@ -732,7 +733,7 @@ def Run(self):
print()
status = 130 # 128 + 2
except (IOError, OSError) as e:
ui.Stderr('osh I/O error: %s', posix.strerror(e.errno))
stderr_line('osh I/O error: %s', posix.strerror(e.errno))
status = 2

# Raises SystemExit, so we still have time to write a crash dump.
Expand Down Expand Up @@ -1345,7 +1346,7 @@ def WaitForOne(self):
# notification of its exit, even though we didn't start it. We can't have
# any knowledge of such processes, so print a warning.
if pid not in self.job_state.child_procs:
ui.Stderr("osh: PID %d stopped, but osh didn't start it", pid)
stderr_line("osh: PID %d stopped, but osh didn't start it", pid)
return True # caller should keep waiting

proc = self.job_state.child_procs[pid]
Expand Down
1 change: 0 additions & 1 deletion core/pyutil.py
Expand Up @@ -14,7 +14,6 @@
from typing import IO, Any


# TODO: Remove ui.Stderr in favor of this
def stderr_line(msg, *args):
# type: (str, *Any) -> None
"""Print a message to stderr for the user.
Expand Down
10 changes: 5 additions & 5 deletions core/shell.py
Expand Up @@ -201,7 +201,7 @@ def Main(lang, argv0, arg_r, environ, login_shell, loader, line_input):
try:
attrs = flag_spec.ParseMore('main', arg_r)
except error.Usage as e:
ui.Stderr('osh usage error: %s', e.msg)
stderr_line('osh usage error: %s', e.msg)
return 2
flag = arg_types.main(attrs.attrs)

Expand Down Expand Up @@ -321,8 +321,8 @@ def Main(lang, argv0, arg_r, environ, login_shell, loader, line_input):
try:
debug_f = util.DebugFile(fd_state.OpenForWrite(debug_path))
except OSError as e:
ui.Stderr("osh: Couldn't open %r: %s", debug_path,
posix.strerror(e.errno))
stderr_line("osh: Couldn't open %r: %s", debug_path,
posix.strerror(e.errno))
return 2
else:
debug_f = util.NullDebugFile()
Expand Down Expand Up @@ -545,8 +545,8 @@ def Main(lang, argv0, arg_r, environ, login_shell, loader, line_input):
try:
f = fd_state.Open(script_name)
except OSError as e:
ui.Stderr("osh: Couldn't open %r: %s", script_name,
posix.strerror(e.errno))
stderr_line("osh: Couldn't open %r: %s", script_name,
posix.strerror(e.errno))
return 1
line_reader = reader.FileLineReader(f, arena)

Expand Down
80 changes: 33 additions & 47 deletions core/ui.py
Expand Up @@ -27,6 +27,7 @@

from typing import List, Optional, cast, Any, TYPE_CHECKING
if TYPE_CHECKING:
from _devbuild.gen import arg_types
from core.alloc import Arena
from core.error import _ErrorWithLocation
from mycpp.mylib import Writer
Expand Down Expand Up @@ -280,51 +281,36 @@ def PrettyPrintError(self, err, prefix=''):
_pp(err, self.arena, prefix)


if mylib.PYTHON:
def Stderr(msg, *args):
# type: (str, *Any) -> None
"""Print a message to stderr for the user.
def PrintAst(node, flag):
# type: (command_t, arg_types.main) -> None

This should be used sparingly, since it doesn't have any location info.
Right now we use it to print fatal I/O errors that were only caught at the
top level.
"""
if args:
msg = msg % args
print(msg, file=sys.stderr)

# Doesn't translate because of Any type
# Options may need metaprogramming!
def PrintAst(node, flag):
# type: (command_t, Any) -> None

if flag.ast_format == 'none':
print('AST not printed.', file=sys.stderr)
if 0:
from _devbuild.gen.id_kind_asdl import Id_str
from frontend.lexer import ID_HIST
for id_, count in ID_HIST.most_common(10):
print('%8d %s' % (count, Id_str(id_)))
print()
total = sum(ID_HIST.values())
print('%8d total tokens returned' % total)

else: # text output
f = mylib.Stdout()

if flag.ast_format in ('text', 'abbrev-text'):
ast_f = fmt.DetectConsoleOutput(f)
elif flag.ast_format in ('html', 'abbrev-html'):
ast_f = fmt.HtmlOutput(f)
else:
raise AssertionError()

if 'abbrev-' in flag.ast_format:
tree = node.AbbreviatedTree()
else:
tree = node.PrettyTree()

ast_f.FileHeader()
fmt.PrintTree(tree, ast_f)
ast_f.FileFooter()
ast_f.write('\n')
if flag.ast_format == 'none':
stderr_line('AST not printed.')
if 0:
from _devbuild.gen.id_kind_asdl import Id_str
from frontend.lexer import ID_HIST
for id_, count in ID_HIST.most_common(10):
print('%8d %s' % (count, Id_str(id_)))
print()
total = sum(ID_HIST.values())
print('%8d total tokens returned' % total)

else: # text output
f = mylib.Stdout()

if flag.ast_format in ('text', 'abbrev-text'):
ast_f = fmt.DetectConsoleOutput(f)
elif flag.ast_format in ('html', 'abbrev-html'):
ast_f = fmt.HtmlOutput(f)
else:
raise AssertionError()

if 'abbrev-' in flag.ast_format:
tree = node.AbbreviatedTree()
else:
tree = node.PrettyTree()

ast_f.FileHeader()
fmt.PrintTree(tree, ast_f)
ast_f.FileFooter()
ast_f.write('\n')
3 changes: 0 additions & 3 deletions core/ui_test.py
Expand Up @@ -12,9 +12,6 @@

class UiTest(unittest.TestCase):

def testStderr(self):
ui.Stderr('oops')

def testErrorFormatter(self):
arena = test_lib.MakeArena('')
line_id = arena.AddLine('[line one]', 1)
Expand Down
6 changes: 3 additions & 3 deletions osh/builtin_process.py
Expand Up @@ -17,6 +17,7 @@
from asdl import runtime
from core import error
from core import main_loop
from core.pyutil import stderr_line
from core import ui
from core import vm
from core.util import log
Expand Down Expand Up @@ -446,8 +447,7 @@ def Run(self, cmd_val):
# Register a hook.
if sig_key in _HOOK_NAMES:
if sig_key in ('ERR', 'RETURN', 'DEBUG'):
ui.Stderr("osh warning: The %r hook isn't yet implemented ",
sig_spec)
stderr_line("osh warning: The %r hook isn't implemented", sig_spec)
self.traps[sig_key] = _TrapHandler(node, self.nodes_to_run)
return 0

Expand Down Expand Up @@ -493,7 +493,7 @@ def Run(self, cmd_val):
new_mask = int(a, 8)
except ValueError:
# NOTE: This happens if we have '8' or '9' in the input too.
ui.Stderr("osh warning: umask with symbolic input isn't implemented")
stderr_line("osh warning: umask with symbolic input isn't implemented")
return 1
else:
posix.umask(new_mask)
Expand Down
4 changes: 2 additions & 2 deletions tools/readlink.py
Expand Up @@ -5,7 +5,7 @@

import libc
from frontend import flag_spec
from core import ui
from core.pyutil import stderr_line

SPEC = flag_spec.FlagSpec('readlink')
SPEC.ShortFlag('-f')
Expand All @@ -14,7 +14,7 @@
def main(argv):
arg, i = SPEC.ParseArgv(argv)
if not arg.f:
ui.Stderr("readlink: -f must be passed")
stderr_line("readlink: -f must be passed")
return 1
for path in argv[i:]:
res = libc.realpath(path)
Expand Down

0 comments on commit f128339

Please sign in to comment.