Files
PyJail/autoconvert.py
2025-01-09 07:37:24 +01:00

83 lines
3.1 KiB
Python

"""
Converts files to be jail-compatible
"""
import importlib
class FileConverter:
def __init__(self):
self.jail_mgr = importlib.import_module(".jail_mgr", "vfs.sys")
self.jailmgr = self.jail_mgr.PyJail()
self._file_openers = ["os.path", "open", "shutil.copy", "shutil.rm"]
self._unsupported_file_openers = ["QFile"]
def convert_file(self, fn):
unsupported_openers_found = 0
lines = []
with open(self.jailmgr.fs(fn), "a") as f:
for line in f:
line = line.strip()
lines.append(line)
blank_line_found = False
init_found = False
i_total = 0
for i, line in enumerate(lines):
if line == "" and blank_line_found is False:
line = "import importlib\n"
lines[i] = line
blank_line_found = True
if "def __init__" in line and init_found is False:
line_to_export = (
"\nself.jail_mgr = importlib.import_module('.jail_mgr', 'vfs.sys')\n"
"self.jailmgr = self.jail_mgr.PyJail()"
)
lines[i + 1] = line_to_export
init_found = True
if self._file_openers in line:
idx = line.index("(")
idx2 = line.index(")")
# if idx2 - idx != 1:
# self.jailmgr.msg(f"{self}", "Unsupported type!", False, "WARN")
# unsupported_openers_found += 1
# else:
expression = line[idx : idx2 + 1]
line_to_edit = f"self.jailmgr.fs({expression})"
idx -= 1
idx2 += 2
full_line = f"{line[:idx]}{line_to_edit}{line[idx2:]}"
lines[i] = full_line
elif self._unsupported_file_openers in line:
self.jailmgr.msg(f"{self}", "Unsupported opener!", False, "WARN")
unsupported_openers_found += 1
else:
pass
i_total = i
if unsupported_openers_found > 0:
self.jailmgr.msg(
f"{self}",
f"Some/all of the openers in this file aren't compatible with the converter, amount: {unsupported_openers_found} of the {i_total}",
True,
"WARN",
)
return lines
def file_writer(self, fn, content):
for i, line in enumerate(content):
line.rstrip("\n")
with open(self.jailmgr.fs(fn), "a+") as f:
f.write(f"{line}\n")
f.close()
self.jailmgr.msg(f"{self}", "Conversion OK! Please check results.", True)
return 0
if __name__ == "__main__":
fc = FileConverter()
fn = input("Enter filepath to convert (fullpath): ")
try:
lines = fc.convert_file(fn)
fc.file_writer(lines)
except Exception:
print("Failure to convert!")