Created
December 29, 2021 00:51
-
-
Save Comamoca/bfcff85fef1085e7f6ab356939ddbcf6 to your computer and use it in GitHub Desktop.
exploition is This is a script to extract functions. You can generate pytest and other test code templates from existing Python scripts.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import ast | |
import sys | |
import os | |
import pathlib | |
import traceback | |
if os.name == "nt": | |
import ctypes | |
# https://docs.microsoft.com/en-us/windows/console/setconsolemode?redirectedfrom=MSDN | |
ENABLE_PROCESSED_OUTPUT = 0x0001 | |
ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 | |
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 | |
MODE = ( | |
ENABLE_PROCESSED_OUTPUT | |
+ ENABLE_WRAP_AT_EOL_OUTPUT | |
+ ENABLE_VIRTUAL_TERMINAL_PROCESSING | |
) | |
kernel32 = ctypes.windll.kernel32 | |
handle = kernel32.GetStdHandle(-11) | |
kernel32.SetConsoleMode(handle, MODE) | |
class TerminalColor: | |
"""ターミナル色変更用クラス""" | |
INFO_BLUE = "\033[94m" | |
INFO_GREEN = "\033[92m" | |
WARN = "\033[93m" | |
ERR = "\033[91m" | |
MARKER = "\033[7m" | |
BOLD = "\033[1m" | |
UNDERLINE = "\033[4m" | |
_END = "\033[0m" | |
@classmethod | |
def c_print(cls, text, styles=()): | |
colored_text = "" | |
for style in styles: | |
colored_text += style | |
colored_text += text | |
colored_text += cls._END | |
print(colored_text) | |
my_style = [ | |
TerminalColor.MARKER, | |
TerminalColor.UNDERLINE, | |
TerminalColor.INFO_BLUE, | |
] | |
# TerminalColor.c_print("サンプル文字列", my_style) | |
err_style = [TerminalColor.ERR] | |
style_info = [] | |
under_func_pass = True | |
func_templete = """ | |
def test_{}(): | |
pass | |
""" | |
try: | |
class Collection: | |
def __init__(self, name="", def_line_no=0, last_line_no=0): | |
self.name = name | |
self.def_line_no = def_line_no | |
self.last_line_no = last_line_no | |
class MethodLastLineNoCollector: | |
def __init__(self): | |
self.res = {} | |
self.searched_line_no = 0 | |
def run(self, node): | |
if isinstance(node, ast.FunctionDef): | |
self.res[node.lineno] = Collection(node.name, def_line_no=node.lineno) | |
for child in ast.iter_child_nodes(node): | |
self.run(child) | |
if hasattr(node, "lineno"): | |
if node.lineno > self.searched_line_no: | |
self.searched_line_no = node.lineno | |
else: | |
if self.res.get(node.lineno): | |
self.res[node.lineno].last_line_no = self.searched_line_no | |
def echo_log(func, msg="Running {}..."): | |
def add_log(*args, **kwargs): | |
fname = func.__name__ | |
print(msg.format(fname)) | |
result = func | |
TerminalColor.c_print("✅" + fname + " done.", TerminalColor.INFO_GREEN) | |
return result | |
return add_log | |
def gen(fnlist): | |
script = str() | |
for fn in fnlist: | |
fnsrc = func_templete.format(fn) | |
script += fnsrc | |
return script | |
def writer(file_name, res): | |
with open(file_name, "w") as f: | |
f.write(res) | |
def check_tests_dir(): | |
path = pathlib.Path("tests/") | |
file_list = list() | |
if path.exists() and path.dir(): | |
pass | |
for file in path.glob("*.py"): | |
if file.is_file(): | |
file_list.append(file) | |
def help(): | |
print( | |
""" | |
Usage: | |
python get_fname.py (PATH of the file to be read) (Output destination file PATH) | |
""" | |
) | |
if __name__ == "__main__": | |
FILENAME = sys.argv[1] | |
TARGETNAME = sys.argv[2] | |
# FILENAME = 'bundler/bundler/bundler.py' | |
# TARGETNAME = "testscript.py" | |
TerminalColor.c_print( | |
"read file path: " + FILENAME + "\n" "write to file path: " + TARGETNAME, | |
[TerminalColor.WARN, TerminalColor.MARKER], | |
) | |
TerminalColor.c_print("❓Start process ok? (y/n)", TerminalColor.INFO_BLUE) | |
res = input() | |
if res != "y": | |
print("exit.") | |
exit() | |
with open(FILENAME, "r") as f: | |
source = f.read() | |
tree = ast.parse(source, FILENAME) | |
collector = MethodLastLineNoCollector() | |
collector.run(tree) | |
fnlist = list() | |
print("Parce start") | |
for v in collector.res.values(): | |
TerminalColor.c_print( | |
"ℹ{} -> def:{}, last:{}".format(v.name, v.def_line_no, v.last_line_no), | |
TerminalColor.INFO_BLUE, | |
) | |
fnlist.append(str(v.name)) | |
gen = echo_log(gen, "Generating scripts...") | |
writer = echo_log(writer, msg="Writeing script...") | |
result = gen(fnlist) | |
writer(TARGETNAME, result) | |
TerminalColor.c_print("🎉Script done.", TerminalColor.INFO_GREEN) | |
except (NameError, IndexError) as e: | |
TerminalColor.c_print("Specifying an invalid value", err_style) | |
except FileNotFoundError as e: | |
TerminalColor.c_print("The PATH you specified is wrong", err_style) | |
except: | |
# err = sys.exc_info() | |
# print(err) | |
TerminalColor.c_print( | |
"😱 Oh no! script was Error!!", [TerminalColor.ERR, TerminalColor.MARKER] | |
) | |
# print traceback | |
print(traceback.format_exc()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm sorry. This script is not working properly!
Also, it has not been updated in Gist.
The latest script is in the repository