OnJava8-Examples/OutputGenerator.py

136 lines
5.2 KiB
Python
Raw Normal View History

2015-05-02 23:49:25 -07:00
#! python
2015-04-20 15:36:01 -07:00
"""
Runs a Java program, appends output if it's not there
-force as first argument when doing batch files forces overwrite
"""
import os, re, sys
argTag = '// {Args: '
oldOutput = re.compile("/* Output:.*?\n(.*)\n\*///:~(?s)")
def makeOutputIncludedFile(path, fileName, changeReport, force = False):
oldDir = os.getcwd()
os.chdir(path)
base = fileName.split('.')[0]
package = ''
args = ''
command = None
2015-05-02 23:49:25 -07:00
for line in open(fileName):
2015-04-20 15:36:01 -07:00
if line.startswith("} /*"):
break # Out of for loop
if line.startswith("package"):
words = line.strip().split()
package = words[1][:-1] + '.' # remove ';'
if line.startswith(argTag):
args = line[len(argTag):].strip()
assert args.rfind('}') != -1, "%s, %s" % (args, fileName)
args = " " +args[:args.rfind('}')]
if line.startswith("// {main:"):
base = line.split()[-1]
base = base[:-1]
if line.startswith("// {Exec:"):
command = line.split(':', 1)[1].strip()[:-1]
2015-05-02 23:49:25 -07:00
if "{TimeOutDuringTesting}" in line:
return # Don't run this one.
2015-04-20 15:36:01 -07:00
if not command:
command = "java " + package + base + args
command += " > " + base + "-output.txt"
2015-05-02 23:49:25 -07:00
print(command)
2015-04-20 15:36:01 -07:00
result = os.system(command)
if(result != 0):
2015-05-02 23:49:25 -07:00
raise Exception("Command returned nonzero value: " + str(result))
2015-04-20 15:36:01 -07:00
# Read output file that was just generated:
2015-05-02 23:49:25 -07:00
results = open(base + "-output.txt").read().strip()
2015-04-20 15:36:01 -07:00
# Strip off trailing spaces on each line:
results = "\n".join([line.rstrip() for line in results.split("\n")])
results = results.replace('\t', ' ')
if results:
2015-05-02 23:49:25 -07:00
if force or not oldOutput.findall(open(fileName).read()):
2015-04-20 15:36:01 -07:00
processedText = createProcessedJavaText(results, fileName)
open(fileName, 'w').write(processedText + "\n")
if changeReport:
changeReport.write(os.path.join(path, fileName) + "\n")
return # Don't need to try for error output
##### Duplicate for standard error output:
command += " 2> " + base + "-erroroutput.txt"
2015-05-02 23:49:25 -07:00
print(command)
2015-04-20 15:36:01 -07:00
result = os.system(command)
if(result != 0):
2015-05-02 23:49:25 -07:00
raise Exception("Command returned nonzero value: " + str(result))
2015-04-20 15:36:01 -07:00
# Read error file that was just generated:
2015-05-02 23:49:25 -07:00
results = open(base + "-erroroutput.txt").read().strip()
2015-04-20 15:36:01 -07:00
# Strip off trailing spaces on each line:
results = "\n".join([line.rstrip() for line in results.split("\n")])
results = results.replace('\t', ' ')
if results:
2015-05-02 23:49:25 -07:00
if force or not oldOutput.findall(open(fileName).read()):
2015-04-20 15:36:01 -07:00
processedText = createProcessedJavaText(results, fileName)
open(fileName, 'w').write(processedText + "\n")
if changeReport:
changeReport.write(os.path.join(path, fileName) + "\n")
os.chdir(oldDir)
def createProcessedJavaText(results, fileName):
processedJava = ''
2015-05-02 23:49:25 -07:00
for line in [line.rstrip() for line in open(fileName)]:
2015-04-20 15:36:01 -07:00
if line.startswith("} ///:~"):
processedJava += "} /* Output:\n" + results + "\n*///:~"
return processedJava
if line.startswith("} /* Output:"):
processedJava += line + "\n" + results + "\n*///:~" # Preserve modifiers
return processedJava
processedJava += line + "\n"
2015-05-02 23:49:25 -07:00
raise Exception("No marker found at end of file " + path + " " + fileName)
2015-04-20 15:36:01 -07:00
class ReportFile:
def __init__(self, filePath):
self.filePath = filePath
self.file = None
def write(self, line):
if not self.file:
2015-05-02 23:49:25 -07:00
self.file = open(self.filePath, 'w')
2015-04-20 15:36:01 -07:00
self.file.write(line)
2015-05-02 23:49:25 -07:00
print(line)
2015-04-20 15:36:01 -07:00
def close(self):
if self.file:
self.file.close()
if __name__ == "__main__":
start = os.getcwd()
args = sys.argv[1:]
forceFlag = False
if len(args):
if args[0] == "-force":
forceFlag = True
2015-05-02 23:49:25 -07:00
print("forceFlag = ", forceFlag)
2015-04-20 15:36:01 -07:00
del args[0]
if len(args) > 0:
for javaSource in args:
if javaSource.endswith("."): javaSource = javaSource[:-1]
if not javaSource.endswith(".java"): javaSource += ".java"
os.system("javac " + javaSource)
makeOutputIncludedFile(os.getcwd(), javaSource, None, force = True)
else:
changeReport = ReportFile(os.path.join(start, "Changes.txt"))
for root, dirs, files in os.walk('.'):
if (os.sep + "gui") in root: continue
path = os.path.normpath(os.path.join(start,root))
2015-05-02 23:49:25 -07:00
print(path)
2015-04-20 15:36:01 -07:00
for name in [name for name in files if name.endswith(".java")]:
2015-05-02 23:49:25 -07:00
java = open(os.path.join(path, name)).read()
2015-04-20 15:36:01 -07:00
if "public static void main(String" in java and \
not "{RunByHand}" in java and \
not "{ThrowsException}" in java and \
not "/* (Execute to see output) *///:~" in java and \
not "} /* Same output as" in java:
if forceFlag or not "} /* Output:" in java:
2015-05-02 23:49:25 -07:00
print("\t", name)
2015-04-20 15:36:01 -07:00
makeOutputIncludedFile(path, name, changeReport, force = forceFlag)
changeReport.close()
2015-05-02 23:49:25 -07:00
os.system("subl /f Changes.txt &")
2015-04-20 15:36:01 -07:00