hinamizawa-downporter/parser.py

128 lines
3.5 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import config
def get_functions_from_file(filepath: str):
"""
Gets the function calls from a file and returns
a list of lists with the following structure:
["<function_name>", "<argument_1>, <argument2>, ..."]
"""
tokens = []
with open(filepath, 'r') as file:
insideQuotes = False
insideComment = False
insideToken = False
currentWord = ""
currentToken = []
currentTokenParameter = ""
# TODO: Prettify this
while True:
char = file.read(1)
if len(char) != 1:
break
#print(currentWord)
if char in " \n\t\r":
currentWord = ""
else:
currentWord += char
if insideToken and char not in "\n\r":
currentTokenParameter += char
# Skip comments
if insideComment:
if char == "\n":
#print("Skipped comment....")
insideComment = False
continue
# Keep track of whether or not we're inside quotes
# Also handle the case where the quotation marks are
# escaped. We do this by seeing if in the current word
# there's a backtick in the second to last position.
if (
char == '"'
and (
len(currentWord) <= 1
or currentWord[-2] != "\\"
)
):
insideQuotes = not insideQuotes
if not insideQuotes:
if currentWord == "//":
insideComment = True
if char == "(":
# Write the function name
currentToken.append(currentWord[:-1])
insideToken = True
if char == ",":
currentToken.append(currentTokenParameter[:-1].strip())
currentTokenParameter = ""
if insideToken and char == ")":
insideToken = False
currentToken.append(currentTokenParameter[:-1].strip())
currentTokenParameter = ""
# We have the whole function call, save the result
tokens.append(currentToken)
currentToken = []
return tokens
def main():
scripts_path = config.get("scripts_path")
tokens = get_functions_from_file(
os.path.join(scripts_path,"onik_000.txt")
)
structure = []
for token in tokens:
if token[0] == "OutputLine":
dialogue = token[4][1:-1].replace('\\', '')
if token[-1] == "Line_Normal":
dialogue += "\\"
elif token[-1] == "Line_WaitForInput":
dialogue += "@"
elif token[-1] == "Line_ContinueAfterTyping":
pass
else:
raise Exception("Unhandled output termination")
structure.append(["OutputLine", dialogue])
elif (
token[0] == "OutputLineAll"
and "Line_ContinueAfterTyping" == token[-1]
and "\\n" in token[2]
):
count = token[2].count("\\n")
#structure.append(["LineBreak", count])
#for coso in structure:
# if coso[0] == "OutputLine":
# print(coso[1], end="")
# elif coso[0] == "LineBreak":
# print(":".join(["br"] * coso[1]))
return structure
if __name__ == "__main__":
main()