Files
RMC-WhatsApp-Bot/fix_args.py

64 lines
2.7 KiB
Python

import re
with open('src/main/java/com/example/whatsappautomation/service/ChatbotService.java', 'r') as f:
content = f.read()
# We want to match: sendPaginatedButtons(state, arg2, arg3, new String[]{...}, new String[]{...})
# and replace it with: sendPaginatedButtons(state, arg2, new String[]{...}, new String[]{...})
# Note: arg2 and arg3 might be getMessage(...) or "string".
# It's safest to match: sendPaginatedButtons(state, (whatever), (whatever), new String[]{
def replacer(match):
# match.group(1) is the part from `state, ` up to `, new String[]{`
# this part contains `arg2, arg3`. We need to split by comma from the right, but arg2 or arg3 might have commas!
# Wait, getting the last argument before `new String[]{` is the best way.
# Actually, the button text (arg3) is almost always `getMessage("something.btn", state)` or `"View Options"` or similar.
# Let's just use regex to match the third argument which is always followed by `, new String\[\]\{`
pass
# Let's write a simple python parser for the arguments of sendPaginatedButtons
new_content = ""
idx = 0
while True:
start_idx = content.find('sendPaginatedButtons(state, ', idx)
if start_idx == -1:
new_content += content[idx:]
break
new_content += content[idx:start_idx]
# find the start of `new String[]{`
arrays_start = content.find('new String[]{', start_idx)
# The text between `start_idx + len('sendPaginatedButtons(state, ')` and `arrays_start` is `arg2, arg3, `
# We want to remove `arg3, `.
# `arg3` is either a string literal `"..."` or a `getMessage(...)` call.
args_str = content[start_idx + len('sendPaginatedButtons(state, '):arrays_start].strip()
# args_str ends with `,`. Let's remove the trailing comma.
args_str = args_str[:-1].strip()
# Now we need to split args_str into arg2 and arg3.
# If it ends with `state)`, arg3 is `getMessage(..., state)`.
# If it ends with `"`, arg3 is a string literal.
# Actually, we can just find the LAST comma that is NOT inside parentheses!
# A simple comma split works if we respect parens.
def rsplit_args(s):
depth = 0
for i in range(len(s)-1, -1, -1):
if s[i] == ')': depth += 1
elif s[i] == '(': depth -= 1
elif s[i] == ',' and depth == 0:
return s[:i].strip(), s[i+1:].strip()
return s, ""
arg2, arg3 = rsplit_args(args_str)
new_content += f"sendPaginatedButtons(state, {arg2}, "
idx = arrays_start
with open('src/main/java/com/example/whatsappautomation/service/ChatbotService.java', 'w') as f:
f.write(new_content)
print("Fixed arguments")