Skip to content

Instantly share code, notes, and snippets.

@charlesbedrosian
Last active May 17, 2023 00:57
Show Gist options
  • Save charlesbedrosian/1ae985d4878ca2670cbcd83aa2d44c61 to your computer and use it in GitHub Desktop.
Save charlesbedrosian/1ae985d4878ca2670cbcd83aa2d44c61 to your computer and use it in GitHub Desktop.
Merge java source to single file
#!/usr/bin/python3
#
# can simply execute `python3 prepjava.py` from the root of your project, if given the following folder structure:
# /project
# discussion.txt
# header.txt
# output.txt
# src/*.java
#
# and the script will include header.txt content in a comment preceeding the code
# and will include discussion.txt and output.txt in comments after the code
# and the output file will be project.java in the current folder
#
# alternately you can specify the source folder as first parameter and the
# desired output file name as the second parameter
# if the header.txt, output.txt, discussion.txt files are found they will be included
#
import os, sys, glob, re
from io import StringIO
if len(sys.argv) == 2:
folder = sys.argv[1]
outfile = sys.argv[2]
docfolder = folder
elif len(sys.argv) == 1:
folder = os.getcwd() + '/src'
outfile = os.getcwd() + '/' + os.path.split(os.getcwd())[1] + '.java'
docfolder = os.getcwd()
else:
print("prepjava.py folder_with_java output_file")
sys.exit()
out = StringIO()
header = docfolder + '/header.txt'
if os.path.isfile(header):
lines = (open(header, 'r')).readlines()
out.writelines('\n/*\n')
out.writelines(lines)
out.writelines('\n--------------------------------------------------------------------------------\n')
out.writelines('\n*/\n')
imports = []
os.chdir(folder)
for file in glob.glob("*.java"):
out.writelines('\n/*\n' +
'=================================================================================\n' +
'File: ' + file + '\n*/\n\n')
lines = (open(file, 'r')).readlines()
for line in lines:
if re.search('^import [^;]+;$', line):
imports.append(line)
else:
out.writelines(line)
discussion = docfolder + '/discussion.txt'
if os.path.isfile(discussion):
lines = (open(discussion, 'r')).readlines()
out.writelines('\n/*\n')
out.writelines('\n------------------------------------ DISCUSSION ------------------------------------\n')
out.writelines(lines)
out.writelines('\n*/\n')
output = docfolder + '/output.txt'
if os.path.isfile(output):
lines = (open(output, 'r')).readlines()
out.writelines('\n/*\n')
out.writelines('\n------------------------------------ OUTPUT ------------------------------------\n')
out.writelines(lines)
out.writelines('\n*/\n')
sortedImports = [*set(imports)]
f = open(outfile, "w")
for importLine in sortedImports:
f.write(importLine)
f.write(out.getvalue())
f.close()
print('File saved at ' + outfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment