Skip to content

Instantly share code, notes, and snippets.

@ehbc221
Last active June 23, 2022 09:22
Show Gist options
  • Save ehbc221/8de6f135c1f2e3895d009a07d5fbc45b to your computer and use it in GitHub Desktop.
Save ehbc221/8de6f135c1f2e3895d009a07d5fbc45b to your computer and use it in GitHub Desktop.
Convert Jhipster translations to dot annotation (for Wieldy React Admin Template)
from getopt import getopt, GetoptError
from json import load, loads, dumps
from os import listdir, SEEK_END
from os.path import isfile, isdir, join
from sys import argv, exit, stdout
# Query Yes or No to the user
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == "":
return valid[default]
elif choice in valid:
return valid[choice]
else:
stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
# Get the files from a directory
def get_files_from_dir(input_folder):
files = []
# Loop over the folder's files
for input_file in listdir(input_folder):
# Check if element found is file and add it to the folder's list
new_file = join(input_folder, input_file)
if (isfile(new_file)):
files.append(new_file)
return files
# Get the input string from a file
def get_input_string_from_file(input_file_name):
with open(input_file_name, "r") as input_file:
input_string = load(input_file)
return input_string
# Convert json to dots notation
def json_to_dot_notation(input_folder, output_file_name):
try:
input_files = get_files_from_dir(input_folder)
# Open the output file and add the first characters
output_file = open(output_file_name, "w", 1, "UTF-8")
output_file.write("{\n")
# Loop in folder to get file by file
for input_file in input_files:
write_output_file(output_file, get_input_string_from_file(input_file))
# Add the file's last characters and close it
output_file.write("}\n")
output_file.close()
# Remove the last unused characters from previous appendings
with open(output_file_name, "rb+") as filehandle:
filehandle.seek(-4, SEEK_END)
filehandle.truncate()
# Add the last file characters
output_file = open(output_file_name, "a", 1, "UTF-8")
output_file.write("\n}\n")
output_file.close()
return True
except Exception as e:
print(e)
return False
# Write text in output file
def write_output_file(output_file, val, old=""):
if isinstance(val, dict):
for k in val.keys():
write_output_file(output_file, val[k], old + "." + str(k))
elif isinstance(val, list):
for i, k in enumerate(val):
write_output_file(output_file, k, old + "." + str(i))
else:
line = "\t\"{}\": \"{}\",\n".format(old, str(val).replace("\"", "\\\"").replace("{{", "{").replace("}}", "}"))
new_line = line[0:2] + line[3:]
output_file.write(new_line)
# Print help message
def print_help():
print("========== Error in command: ==========")
print("Convert json folder into dot notation.")
print("usage: python json-folder-to-dot-notation.py -i <input_folder> -o output_file")
print("Options and arguments")
print("-h : print this help message and exit (also --help)")
print("-i : input folder")
print("-o : output file")
# Main function
def main(argv):
input_folder_name = ""
output_file_name = ""
# Check if parameters are correctly entered
try:
opts, args = getopt(argv, "hci:o:")
# If there is errors in the parameters, print a help message for the command
except GetoptError:
print_help()
exit(2)
# Get other parameters accordingly to the args passed
for opt, arg in opts:
# Help
if opt in ("-h", "--help"):
print_help()
exit()
# Input folder
elif opt in ("-i"):
input_folder_name = arg.strip()
# Output folder
elif opt in ("-o"):
output_file_name = arg.strip()
# Check if input folder and output file are correctly entered
if input_folder_name != "" and output_file_name != "":
# Check if input folder exists
if (isdir(input_folder_name)):
start_convertion = False
# Check if output file already exists
if (isfile(output_file_name)):
# Query if the user wants to override the file Yes or No
if (query_yes_no("The output file already exists. Do you want to override it?")):
start_convertion = True
else:
print("Operation stopped due to overriting file not approved")
else:
start_convertion = True
# Start convertion if allowed
if (start_convertion == True):
print("\nConverting Json files in folder ", input_folder_name, " to file ", output_file_name)
if (json_to_dot_notation(input_folder_name, output_file_name)):
print("..........\nJson files converted in ", output_file_name)
else:
print("An error has occurred while converting the files")
else:
print("Error: The input folder doesn't exist")
else:
print_help()
if __name__ == "__main__":
main(argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment