-
Notifications
You must be signed in to change notification settings - Fork 3
/
nml_patcher.py
312 lines (227 loc) · 10 KB
/
nml_patcher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#Importing required things
from time import sleep, gmtime, strftime
import time
from random import randint
import sys
import os
import argparse
print("\n=======StarRaid's NML patcher!=======\n")
#Starting with argument handling from command-line interface
parser = argparse.ArgumentParser(description="Patch a GRF in NML from pnml files into one NML file. If no arguments provided, the program will loop and prompt an input for the file to patch. WARNING! This does NOT compile into a .grf file, it patches your pnml files into an nml file for you to compile with NMLC!")
parser.add_argument("-o", "--output", type=str, help='The file to output the written file to. Please enclose the file name in quotation marks (e.g. python nml_patcher.py -o "output.nml)"')
parser.add_argument("-f", "--file", type=str, help="The header file to read from. Please enclose the file name in quotation marks.")
parser.add_argument("-b", "--backup", type=int, help="1 or 0, to say if the program will create a backup if overwriting the output file.", choices=[0,1])
parser.add_argument("-v", "--verbose", type=int, help="1 or 0, print all the possible un-needed information.", choices=[0,1])
args = parser.parse_args()
arguments = vars(args)
"""
#Checking if any of the arguments have any value that is not "None"
used_args = False
for argument in arguments:
if not used_args and arguments[argument] != None:
used_args = True
"""
#Defining general purpose functions
def rm_file_extension(file_name):
found_file_extension = False
end_point = len(file_name)-1
#Finding the last decimal point in the header name
for pos in range(len(file_name)-1,-1,-1):
if file_name[pos] == "." and not found_file_extension:
end_point = pos
found_file_extension = True
return file_name[:end_point]
#Backup function that backs up the output file first (if it already exists)
def backup(name):
if name in os.listdir():
if not ("backups" in os.listdir()):
os.mkdir("backups")
new_file_name = rm_file_extension(name) + "-" + strftime("%H-%M-%S-%Y-%m-%d", gmtime())+".nml"
os.rename(name, "backups/" + new_file_name)
if new_file_name in os.listdir("backups"):
print('Successfully backed up to "backups/' + new_file_name + '"!')
else:
print_general_error("Failed to backup file")
#Known error printing
def print_error(cause, place, action):
print("\nEncountered error!")
print("Cause : ", cause)
print("Found at : ", place)
print("How to fix : ", action)
#Unknown error printing
def print_general_error(cause):
print("\nEncountered error!")
print("Cause : ", cause)
print("This was most likely an internal error.\n")
#Defining the class that writes to the output file
class writer:
"""The interface that writes to the output file"""
output_text = ""
def __init__(self):
output = arguments["output"]
self.output = open(output, "w")
def write_line(self, line):
self.output.write(str(line) + "\n")
def close(self):
self.output.close()
def patch(self):
#Writing the header beggining
self.write_line('# 1 "' + arguments["file"] + '"')
#The main sequence that opens the files and then writes to the output
header.main()
self.close()
header.close()
#Defining the main reader class
class reader:
"""The class that reads from a file and does various things with it"""
list_of_definitions = {}
total_list_of_errors = []
faulty_definitions = []
main_header = []
def __init__(self, file_name, *parent_variables):
try:
if not (True in self.main_header):
self.main_header.append(True)
self.write_header = False
print('Opening "' + file_name + '" as the main header.')
self.first_header = 0
self.current_line = 0
self.errors_made = 0
self.file_name = file_name
self.input = ""
self.input = open(self.file_name, "r")
except (OSError, FileNotFoundError) as inst:
self.errors_made += 1
if parent_variables:
self.total_list_of_errors.append([inst, "Line " + str(parent_variables[2]) + " of " + str(parent_variables[0]) + ": " + str(parent_variables[1]), "Check that the line of code is correct"])
else:
self.total_list_of_errors.append([inst, "Direct/Argument input", "Make sure you enter a valid file name"])
def read_line(self):
line_read = self.input.readline()
return line_read.replace("\n","")
def close(self):
if str(type(self.input)) == "<class '_io.TextIOWrapper'>":
self.input.close()
if len(self.total_list_of_errors):
if len(self.total_list_of_errors) == 1:
print("\nEncountered 1 error in this patch")
else:
print("\nEncountered", len(self.total_list_of_errors), "errors in this patch.")
for error in self.total_list_of_errors:
if len(error) == 1:
print_general_error(error[0])
else:
print_error(error[0], error[1], error[2])
def main(self):
#The main function that reads a file and writes it to the output file
#Generating a list of each line of code in the target file, then removing the new line characters
lines = [line.replace("\n","") for line in self.input]
#The main loop that loops through each line of code
self.line_counter = 0
for line in lines:
self.line_counter += 1
do_write = True
#If the line starts with the "#include" command, then it create another instance that reads and writes that file first
if line.lower()[:8] == "#include":
if self.first_header == 0:
self.first_header = self.line_counter
output.write_line('# 1 ' + line[9:] + ' 1')
self.subreader = reader(line.replace('"', '')[9:], self.file_name, line, self.line_counter)
self.subreader.main()
if self.subreader.errors_made == 1:
print("Patched", line.replace('"', '')[9:], "with 1 error!")
elif self.subreader.errors_made > 1:
print("Patched", line.replace('"', '')[9:], "with", self.subreader.errors_made, "errors!")
elif arguments["verbose"]:
print("Patched", line.replace('"', '')[9:], "with no errors.")
output.write_line('# ' + str(self.current_line+1) + ' "' + self.file_name + '" ' + str(self.first_header))
do_write = False
elif line.lower()[:7] == "#define":
new_line = line[8:]
#Finding the end of the definition name
def_name = ""
found_def_name = False
for letter in new_line:
if letter == " " and not found_def_name:
new_line = new_line.replace(def_name + " ", "")
if len(new_line) > 0:
if arguments["verbose"]:
print("Made custom definition", def_name, "with a value of", new_line)
self.list_of_definitions[def_name] = new_line
elif len(def_name) > 1:
self.total_list_of_errors.append(["Invalid custom definition!", "Line" + str(self.line_counter) + " of " + self.file_name + ": " + line, "Check the definition's value"])
found_def_name = True
def_name += letter
do_write = False
else:
#Checking for custom definitions
for definition in self.list_of_definitions:
if definition in line:
line = line.replace(definition, self.list_of_definitions[definition])
#If a definition that is known to be faulty is found then throw an error
for definition in self.faulty_definitions:
if definition in line:
self.errors_made +=1
self.total_list_of_errors.append(["Invalid custom definition used!", "Line " + str(self.line_counter) + " of " + self.file_name + ": " + line, "Check the definition's value"])
if do_write:
output.write_line(line)
#Defining other general functions
#If output is not defined but the header file is, then it will be defined as the same as the input
if arguments["file"] != None and arguments["output"] == None:
arguments["output"] = rm_file_extension(arguments["file"])+".nml"
#Backing up if backup is set to 1
if arguments["backup"] != None and str(arguments["backup"]) != "0" :
print("Attempting to backup", arguments["output"])
backup(arguments["output"])
#Displaying the given arguments to the user
for argument in arguments:
if arguments[argument] != None:
print(argument.capitalize(), ":", arguments[argument])
#Checking if any arguments are used
if arguments["file"] != None:
try:
#The main sequence that opens the files and then writes to the output
output = writer()
header = reader(arguments["file"])
output.patch()
#Display messages after patching
if len(header.list_of_definitions) > 0 and arguments["verbose"]:
print("\nList of custom definitions used in this file:")
for definition in header.list_of_definitions:
print(definition, header.list_of_definitions[definition])
#Catch any other raised errors
except SyntaxError:#Exception as inst:
print_general_error(str(inst) + " from " + str(type(inst)))
else:
print("\nType 'exit' to exit the program\n")
#Entering a loop that can be broken with either Ctrl + C or a command
while True:
try:
print("\n==============================\n")
#Getting the users input
arguments["file"] = input("Input file: ")
#If the user types exit the program will exit
if arguments["file"].lower() == "exit":
raise KeyboardInterrupt
#Creating the output file from the input file name
if arguments["output"] == None:
arguments["output"] = rm_file_extension(arguments["file"])+".nml"
#The main sequence that opens the files and then writes to the output
output = writer()
header = reader(arguments["file"])
output.patch()
#Display messages after patching
if len(header.list_of_definitions) > 0 and arguments["verbose"]:
print("\nList of custom definitions used in this file:")
for definition in header.list_of_definitions:
print(definition, header.list_of_definitions[definition])
if arguments["output"] == rm_file_extension(arguments["file"])+".nml":
arguments["output"] == None
#If the command is entered or Ctrl + C is pressed, then the program will terminate
except KeyboardInterrupt:
print("\nExiting the program!")
break
#Catching any other raised errors
except Exception as inst:
print_general_error(str(inst) + " from " + str(type(inst)))
#input("\nPress enter to continue\n")