Add CL handling to hyc

This adds real command line handling to 'hyc' for issue #256

This fix catches missing/unreadable files and prints a nice
error message instead of a nasty stack trace when trying to
compile a non-existent file.

Also add this non-existent file check to hy to prevent the
current stack trace from something like "hy foobarbaz" when
"foobarbaz" doesn't exist.

also changes the failure return value to 2 to match Python.
This commit is contained in:
Bob Tolbert 2013-07-25 23:33:14 -06:00
parent 6d9b93567d
commit d960dc963f
2 changed files with 41 additions and 3 deletions

View File

@ -248,7 +248,12 @@ def cmdline_handler(scriptname, argv):
else: else:
# User did "hy <filename>" # User did "hy <filename>"
return run_file(options.args[0]) try:
return run_file(options.args[0])
except IOError as x:
sys.stderr.write("hy: Can't open file '%s': [Errno %d] %s\n" %
(x.filename, x.errno, x.strerror))
sys.exit(x.errno)
# User did NOTHING! # User did NOTHING!
return run_repl() return run_repl()
@ -262,4 +267,18 @@ def hy_main():
# entry point for cmd line script "hyc" # entry point for cmd line script "hyc"
def hyc_main(): def hyc_main():
from hy.importer import write_hy_as_pyc from hy.importer import write_hy_as_pyc
write_hy_as_pyc(sys.argv[1]) parser = argparse.ArgumentParser(prog="hyc")
parser.add_argument("files", metavar="FILE", nargs='+',
help="file to compile")
parser.add_argument("-v", action="version", version=VERSION)
options = parser.parse_args(sys.argv[1:])
for file in options.files:
try:
write_hy_as_pyc(file)
print("Compiling %s" % file)
except IOError as x:
sys.stderr.write("hyc: Can't open file '%s': [Errno %d] %s\n" %
(x.filename, x.errno, x.strerror))
sys.exit(x.errno)

View File

@ -83,7 +83,7 @@ def test_bin_hy_file():
def test_bin_hy_missing_file(): def test_bin_hy_missing_file():
ret = run_cmd("hy foobarbaz") ret = run_cmd("hy foobarbaz")
assert ret[0] == 1 assert ret[0] == 2
assert "No such file" in ret[2] assert "No such file" in ret[2]
@ -102,6 +102,25 @@ def test_bin_hy_file_with_args():
assert "foo" in ret[1] assert "foo" in ret[1]
def test_bin_hyc():
ret = run_cmd("hyc")
assert ret[0] == 2
assert "usage" in ret[2]
ret = run_cmd("hyc -h")
assert ret[0] == 0
assert "usage" in ret[1]
ret = run_cmd("hyc tests/resources/argparse_ex.hy")
assert ret[0] == 0
assert "Compiling" in ret[1]
assert os.path.exists("tests/resources/argparse_ex.pyc")
def test_bin_hyc_missing_file():
ret = run_cmd("hyc foobarbaz")
assert ret[0] == 2
assert "[Errno 2]" in ret[2]
def test_hy2py(): def test_hy2py():
# XXX Astor doesn't seem to support Python3 :( # XXX Astor doesn't seem to support Python3 :(
if sys.version_info[0] == 3: if sys.version_info[0] == 3: