vhdl-style-guide/vsg/fix_runtime.py

59 lines
1.5 KiB
Python

# -*- coding: utf-8 -*-
"""Makes stdin/stdout fixing a non-destructive machine interface."""
import contextlib
import io
import sys
def run(fMain):
"""Returns the original stdin text whenever stdout fixing cannot complete."""
if not _is_stdout_fix_request():
return fMain()
sSource = sys.stdin.read()
sys.stdin = io.StringIO(sSource)
oStdout = io.StringIO()
oStderr = io.StringIO()
iExitStatus = 0
oFailure = None
try:
with contextlib.redirect_stdout(oStdout), contextlib.redirect_stderr(oStderr):
fMain()
except SystemExit as oError:
iExitStatus = _exit_status(oError.code)
except Exception as oError: # pragma: no branch - this is the process boundary
iExitStatus = 1
oFailure = oError
sOutput = oStdout.getvalue()
sError = oStderr.getvalue()
if sError:
print(sError, file=sys.stderr, end="" if sError.endswith("\n") else "\n")
if oFailure is not None:
print(
"ERROR: stdout fixing raised " + oFailure.__class__.__name__ + ": " + str(oFailure),
file=sys.stderr,
)
if iExitStatus == 0 and sOutput:
sys.stdout.write(sOutput)
else:
sys.stdout.write(sSource)
raise SystemExit(iExitStatus)
def _is_stdout_fix_request():
lArguments = sys.argv[1:]
return "--stdin" in lArguments and "--fix" in lArguments and "--stdout" in lArguments
def _exit_status(oCode):
if oCode is None:
return 0
if isinstance(oCode, int):
return oCode
return 1