More sort routes

This commit is contained in:
2024-04-28 12:03:06 +01:00
parent b96239639c
commit 26e9889061
15 changed files with 549 additions and 235 deletions

107
sm2gen.py
View File

@@ -12,30 +12,9 @@ from datetime import datetime
import xml.etree.ElementTree as ET
SME2Gen_version = '0.6'
try:
chameleon_version = pkg_resources.get_distribution("Chameleon").version
except pkg_resources.DistributionNotFound:
chameleon_version = "Version information not available"
python_version = sys.version
python_version = python_version[:8]
current_datetime = datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M")
strVersion = "SME2Gen version:"+SME2Gen_version+" Chameleon version:"+chameleon_version+" On Python:"+python_version+" at "+formatted_datetime
json5_dict: dict = {}
json5_html_list: list = []
print(f"SM2 code from JSON5 - {strVersion}")
quit()
# Get the version of Chameleon using pkg_resources
try:
version = pkg_resources.get_distribution("Chameleon").version
print("Using Chameleon version:", version)
except pkg_resources.DistributionNotFound:
print("Chameleon is not installed or found.")
def parse_json(json_obj, prefix=''):
structured_list = []
if isinstance(json_obj, dict):
@@ -203,29 +182,43 @@ def get_table_control_data():
return find_values_with_key(json5_html_list,'TableControl')
if __name__ == "__main__":
try:
chameleon_version = pkg_resources.get_distribution("Chameleon").version
except pkg_resources.DistributionNotFound:
chameleon_version = "Version information not available"
python_version = sys.version
python_version = python_version[:8]
current_datetime = datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M")
strVersion = "SME2Gen version:"+SME2Gen_version+" Chameleon version:"+chameleon_version+" On Python:"+python_version+" at "+formatted_datetime
json5_dict: dict = {}
json5_html_list: list = []
print(f"SM2 code from JSON5 - {strVersion}")
filename = '/home/brianr/clients/SM2/SM2Gen/nfsshare.json5'
# Command line parameters
parser = argparse.ArgumentParser(description="SM2Gen")
parser.add_argument('-f', '--filename', help='Specify a filename for the JSON5 file', default=filename)
parser.add_argument('-nc', '--noController', help='Stop it creating a controller file', default="no")
parser.add_argument('-nco', '--noController', help='Stop it creating a controller file', default="no")
parser.add_argument('-nh', '--noHtml', help='Stop it creating html files(s)', default="no")
parser.add_argument('-nl', '--noLang', help='Stop it creating language localise files(s)', default="no")
parser.add_argument('-ncu', '--noCust', help='Stop it creating Custom controller file', default="no")
args = parser.parse_args()
filename = args.filename
print(f"JSON5 from {filename} with noController={args.noController}, noHtml={args.noHtml} and noLang={args.noLang}") #Not yet activated
#print("Chameleon version:", chameleon.__version__)
# check syntax of JSON5
lint_json5(filename);
# Get dict of it all
json5_dict = json5_to_dict(filename)
#print(json5_dict)
# Get dict of just the html bit
json5_html_list = json5_dict['html']
#print(json5_html_list)
#Identify message
print(f"\nGenerating mojo panels for {hl('PackageName')}")
@@ -238,9 +231,12 @@ if __name__ == "__main__":
#File names
controller_file = 'Targets/'+hl('PackageName')+'.pm'
custom_controller_file = 'Targets/'+hl('PackageName')+'-Custom.pm'
# see if it has been modified by developer
# see if it has been modified by developer - this did not work - the modified by was the same as the creation time/date
#if has_file_been_modified(custom_controller_file):
# custom_controller_file = custom_controller_file+'.new'
# Call it .new if one is already there (and may have been editted by the developer)
if os.path.exists(custom_controller_file):
custom_controller_file = custom_controller_file+'.new'
layout_file = 'Targets/'+hl('PackageName')+'.html.ep'
@@ -250,19 +246,19 @@ if __name__ == "__main__":
print(partial_files)
lex_file = 'Targets/'+hl('PackageName').lower()+'_en.lex'
tablecontrols = get_table_control_data() #arrays of hashes used to drive rows in tables
#print(tablecontrols)
#quit()
#Generate controller file
try:
controller_template = PageTemplateFile("Templates/controller.pm.tem")
dbentries = get_db_fields() #Params which correspond to Db fields
try:
controller_perl = controller_template.render(tablecontrols=tablecontrols, dbentries=dbentries,**json5_dict,panels=routes,lcPackageName=json5_dict['PackageName'].lower())
#print()
#print(controller_perl)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#controller_perl = controller_perl.replace("$ ", "$")
controller_perl = controller_template.render(version=strVersion,
tablecontrols=tablecontrols,
dbentries=dbentries,
**json5_dict,
panels=routes,
lcPackageName=json5_dict['PackageName'].lower()
)
with open(controller_file, 'w') as file:
file.write(controller_perl)
print(f"{controller_file} controller generated ok")
@@ -275,7 +271,10 @@ if __name__ == "__main__":
try:
custom_controller_template = PageTemplateFile("Templates/custom.pm.tem")
try:
custom_controller_perl = custom_controller_template.render(panels=routes,tablecontrols=tablecontrols)
custom_controller_perl = custom_controller_template.render(version=strVersion,
panels=routes,
tablecontrols=tablecontrols
)
# We must be careful to not overwrite the custom file if the developer has already written to it - TBD
with open(custom_controller_file, 'w') as file:
file.write(custom_controller_perl)
@@ -289,16 +288,12 @@ if __name__ == "__main__":
layout_template = PageTemplateFile("Templates/layout.html.ep.tem")
try:
try:
layout_mojo = layout_template.render(**json5_dict,conditions=routes)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#layout_mojo = layout_mojo.replace("$ ", "$")
layout_mojo = layout_template.render(version=strVersion,**json5_dict,conditions=routes)
with open(layout_file, 'w') as file:
file.write(layout_mojo)
print(f"{layout_file} mojo template layout file generated ok")
except Exception as e:
print(f"An chameleon render on layout file error occurred: {e}")
#print()
#print(layout_mojo_template)
except Exception as e:
print(f"An chameleon template layout file error occurred: {e}")
@@ -306,7 +301,6 @@ if __name__ == "__main__":
#Pull in the template code for each of the input types
#html_controls = json5_to_dict('Templates/html_controls.html.ep.tem')
html_controls = parse_xml_to_dict('Templates/html_controls.html.ep.xml')
#print(html_controls)
i = 0
for html in json5_html_list:
# Generate a mojo template file, and then add in the controls
@@ -315,9 +309,7 @@ if __name__ == "__main__":
partial_template = PageTemplateFile("Templates/partial.html.ep.tem")
partial_mojo_context = {**json5_dict,**html}
try:
partial_mojo_template = partial_template.render(**partial_mojo_context)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#partial_mojo_template = partial_mojo_template.replace("$ ", "$")
partial_mojo_template = partial_template.render(version=strVersion,**partial_mojo_context)
with open( partial_files[i], 'w') as file:
file.write(partial_mojo_template)
print(f"{partial_files[i]} mojo template generated ok - phase 1")
@@ -327,31 +319,15 @@ if __name__ == "__main__":
print(f"An chameleon html {html['route']} error occurred: {e}")
#Now generate the controls from the rest of the entries in the dict.
#print()
#print(html['route']);
all_controls_html = "";
prefix_is = hl('prefix')
for html_control in html:
#print(html_control)
inner_html = html[html_control]
if isinstance(inner_html, dict):
#print("\t\t"+inner_html['route']+":"+inner_html['Type'])
try:
control_template = PageTemplate(html_controls[inner_html['Type']])
try:
control_html = control_template.render(**inner_html,prefix=prefix_is) #Contents=Contents,Headings=Headings)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#control_html = control_html.replace("$ ", "$")
# Add in two tabs before each newline
#control_html = control_html.replace("\n", "\n\t\t")
# and an extra tab before each "%"
#control_html = control_html.replace("%", "\t%")
#print(control_html)
# And re-run it if the type is "table"
#if inner_html['Type'] == 'Table'
#Another scan
# print("Another scan for the table")
#Else just move on.
control_html = control_template.render(version=strVersion,**inner_html,prefix=prefix_is)
all_controls_html = all_controls_html + control_html
except Exception as e:
print(f"An chameleon render on partial file control {inner_html['Name']} error occurred: {e}")
@@ -360,15 +336,10 @@ if __name__ == "__main__":
else:
#just a simple entry - name less numerics is type
html_Type = ''.join(char for char in html_control if not char.isdigit())
#print(html_Type);
try:
simple_control_template = PageTemplate(html_controls[html_Type])
try:
simple_control_html = simple_control_template.render(value=inner_html,prefix=prefix_is)
# Map '$ 'to '$' to overcome problem with escaping $ signs
#simple_control_html = simple_control_html.replace("$ ", "$")
# Add in two tabs before each newline
#simple_control_html = simple_control_html.replace("\n", "\n\t\t")
simple_control_html = simple_control_template.render(version=strVersion,value=inner_html,prefix=prefix_is)
all_controls_html = all_controls_html + simple_control_html
except Exception as e:
print(f"An chameleon render on partial file control {html_control} error occurred: {e}")
@@ -395,7 +366,6 @@ if __name__ == "__main__":
# create a combined list of all the files
all_files = [controller_file,layout_file]+partial_files
#print(all_files)
all_strings = []
for filename in all_files:
with open(filename, 'r') as file:
@@ -404,12 +374,9 @@ if __name__ == "__main__":
pattern = r"l[\s|(][\'|\"](.*)[\'|\"]\)"
# Use re.findall to extract all occurrences of the pattern from the file content
extracted_strings = re.findall(pattern, file_content)
#print(len(extracted_strings))
all_strings = all_strings + extracted_strings
#print(len(all_strings))
#Take out any duplicates
all_strings = deduplicate_array(all_strings)
#print(len(all_strings))
# Now process them one by one into the lexical file
lex_all = "";
# '<prefix>_english-message' => 'English Message',