I made a quick script, that inputs file paths(made for C files), function names and 2 indexes. The script goes over all of the files and switches the indexes of the 2 functions. e.g.:
Running the following code:
python switch_args.py temp_funct 0 1 tmp.c
If tmp.c contains this code:
int my_func(a, b, c, d)
after the execution of the script it would have this code:
int my_func(b, a, c, d)
Code:
https://github.com/martin-varbanov96/toolboxz/blob/master/switch_function_args/switch_args.py:
import argparse
import re
parser = argparse.ArgumentParser()
parser.add_argument("function_name", type=str,
help="function name whose arguments will be switched")
parser.add_argument("index", type=int,
help="first argument to be switched")
parser.add_argument("destination", type=int,
help="second argument to be switched")
parser.add_argument('files', metavar='files', type=str, nargs='+',
help='files in which function arguments will be switched')
args = parser.parse_args()
def switch_function_args(func_name, args, index=0, destination=1, ):
function_call_pattern = "{}[^\)]+".format(func_name)
for file in args:
has_function = False
file_content = ""
with open(file, "r") as f:
file_content = f.read()
if(func_name in file_content):
has_function = True
if(has_function):
for current_function_structure in re.findall(function_call_pattern, file_content):
current_arguments = re.split("\(", current_function_structure)[1]
current_arguments = re.split(",", current_arguments)
# switch arguments
current_arguments[index], current_arguments[destination] = current_arguments[destination], current_arguments[index]
fixed_arguments = ",".join(current_arguments)
fixed_function_structure = "{}({}".format(func_name, fixed_arguments)
old_struct_pattern = current_function_structure.replace("(", "\(")
file_content = re.sub(old_struct_pattern, fixed_function_structure, file_content)
with open(file, "w") as f:
f.write(file_content)
switch_function_args(args.function_name, args.files, index=args.index, destination=args.destination)
Question:
How can this code be optimized for performance?
EDIT:
what is the consistency of the following code and is it a good idea to ignore it?
with open(file, "r") as f_read:
# code
with open(file, "w") as f_write:
# code
with open(file, "r") as f_read, open(file, "w") as f_write: ... # code\$\endgroup\$