Skip to content

Commit ede4f11

Browse files
Refactor setup.py
Made all code into clean functions Improved error handling for any situation Fixed minor bug where color was not unset if an error occurs Minor bug and QoL fixes as well
1 parent d17022c commit ede4f11

File tree

1 file changed

+129
-85
lines changed

1 file changed

+129
-85
lines changed

tool/setup.py

Lines changed: 129 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -15,27 +15,33 @@
1515
" Suggested action: Run 'compilerHelper.ps1' to generate the DLLs before building."
1616
)
1717

18-
print("[*] Starting setup.py script for pyCTools...\n")
1918

20-
# Change to the script's root directory
21-
os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
19+
def cleanup():
20+
try:
21+
# Cleanup: remove pyCTools.egg-info and build directories if they exist
22+
for cleanup_dir in ["pyCTools.egg-info", "build", "../pyCTools.egg-info", "../build", "dist"]:
23+
cleanup_path = pathlib.Path(__file__).parent / cleanup_dir
24+
if cleanup_path.exists() and cleanup_path.is_dir():
25+
shutil.rmtree(cleanup_path)
26+
print("\n\033[90m[*] Completed setup.py script cleanup successfully.\033[0m\n")
27+
except Exception as e:
28+
sys.exit(f"[x] Cleanup failed: {e}")
2229

2330

24-
def prompt_version():
31+
def prompt_version() -> str:
2532
try:
2633
pattern = re.compile(r"^\d+\.\d+\.\d+(-[A-Za-z0-9]+)?$")
2734
while True:
2835
version_ = input("[?] Enter package version (format x.x.x or x.x.x-suffix): ").strip()
2936
if pattern.match(version_):
30-
print("\033[90m")
3137
return version_
3238
else:
33-
print("[!] Invalid version format. Expected something like 1.0.0 or 1.0.0-beta => Trying again...\n")
34-
except KeyboardInterrupt:
39+
print("[!] Invalid version format. Expected something like 1.0.0 or 1.0.0-beta\n")
40+
except (KeyboardInterrupt, EOFError):
3541
sys.exit("\n[!] Version input interrupted. Exiting setup.\n")
3642

3743

38-
def get_latest_wheel(dist_dir: str, package_name: str):
44+
def get_latest_wheel(dist_dir: str, package_name: str) -> pathlib.Path:
3945
dist_path = pathlib.Path(dist_dir)
4046
pattern = f"{package_name}-*.whl"
4147
wheel_files = sorted(
@@ -44,89 +50,127 @@ def get_latest_wheel(dist_dir: str, package_name: str):
4450
reverse=True
4551
)
4652
if not wheel_files:
47-
sys.exit(f"[x] No wheel files matching '{pattern}' found in {dist_dir}??")
48-
return wheel_files[0]
53+
cleanup()
54+
sys.exit(f"[x] No wheel files matching '{pattern}' found in {dist_dir}??\n")
55+
56+
if len(wheel_files) == 1:
57+
print(f"[*] Found wheel file successfully\n")
58+
return wheel_files[0]
59+
60+
print("\n[*] Multiple wheel files found:")
61+
for idx, wf in enumerate(wheel_files, 1):
62+
print(f"\033[96m[{idx}]\033[0m {wf.name}")
63+
while True:
64+
try:
65+
choice = input("[?] Select the wheel file to use (number): ").strip()
66+
if choice.isdigit() and 1 <= int(choice) <= len(wheel_files):
67+
print(f"[*] Selected wheel file successfully\n")
68+
return wheel_files[int(choice) - 1]
69+
else:
70+
print("[!] Invalid selection. Please enter a valid number.\n")
71+
except (KeyboardInterrupt, EOFError):
72+
cleanup()
73+
sys.exit("\n[!] Selection interrupted. Exiting setup.\n")
74+
75+
76+
def success_finale(whl_filename_: str, version_: str):
77+
# Complete the setup process and provide instructions on what to do next
78+
print("\033[0m\n[*] Completed setup.py execution.")
79+
if not os.path.isfile("../dist/bin.zip"):
80+
print(
81+
" Suggested action: Run 'distributionHelper.ps1' to create the distribution package for github releases.")
82+
print(" Suggested action: Execute the following to test in VENV:\n\033[96m"
83+
" cd ..\n"
84+
" python -m venv dist/venv_test\n"
85+
" dist\\venv_test\\Scripts\\Activate.ps1\n"
86+
" python -m pip install --upgrade pip\n"
87+
f" pip install dist/libraryWheel/{whl_filename_}\n"
88+
" python example/hwrng_example.py\n"
89+
" python example/process_inspect_example.py\n"
90+
" deactivate\n"
91+
" Remove-Item -Recurse -Force dist\\venv_test\n\033[0m")
92+
93+
print("[*] For local installation, run:")
94+
print(f" \033[96mpython -m pip install dist/libraryWheel/{whl_filename_}\033[0m")
95+
print("[*] If you place the WHL file on the GitHub releases page, users can download it and install it with:")
96+
print(
97+
f" \033[96mpip install https://github.com/DefinetlyNotAI/PyCTools/releases/download/{version_}/{whl_filename_}\033[0m")
98+
print(f" > Assuming the version[{version_}] entered earlier is the exact same as the tag release.\n")
4999

50100

51-
# Path to the bin folder inside pyCTools
52-
bin_path = os.path.join("pyCTools", "bin")
101+
def check_bin_exists(bin_path: str):
102+
try:
103+
# Check that bin exists and has x86 & x64 DLLs
104+
if not os.path.isdir(bin_path):
105+
sys.exit(
106+
"[x] 'pyCTools/bin/' folder not found.\n"
107+
" Suggested action: Run 'compilerHelper.ps1' to generate the DLLs before building.\n"
108+
)
109+
110+
# Check subfolders and DLL presence
111+
for arch in ("x86", "x64"):
112+
arch_path = os.path.join(bin_path, arch)
113+
if not os.path.isdir(arch_path) or not any(f.lower().endswith(".dll") for f in os.listdir(arch_path)):
114+
sys.exit(
115+
f"[x] Missing DLLs in pyCTools/bin/{arch}/\n"
116+
" Suggested action: Run 'compilerHelper.ps1' to generate the DLLs before building.\n"
117+
)
118+
except Exception as err:
119+
sys.exit(f"[x] Fatal error while checking files exist and are ready: {err}")
120+
121+
122+
def output_dir_init() -> pathlib.Path:
123+
try:
124+
# Ensure ../dist/libraryWheel/ exists
125+
output_dir = pathlib.Path(__file__).parent.parent / "dist" / "libraryWheel"
126+
output_dir.mkdir(parents=True, exist_ok=True)
53127

54-
# Check that bin exists and has x86 & x64 DLLs
55-
if not os.path.isdir(bin_path):
56-
sys.exit(
57-
"[x] 'pyCTools/bin/' folder not found.\n"
58-
" Suggested action: Run 'compilerHelper.ps1' to generate the DLLs before building.\n"
59-
)
128+
return output_dir
129+
except Exception as e:
130+
sys.exit(f"[x] Failed to create output directory: {e}\n"
131+
" Suggested action: Ensure you have write permissions in the parent directory.\n")
60132

61-
# Check subfolders and DLL presence
62-
for arch in ("x86", "x64"):
63-
arch_path = os.path.join(bin_path, arch)
64-
if not os.path.isdir(arch_path) or not any(f.lower().endswith(".dll") for f in os.listdir(arch_path)):
65-
sys.exit(
66-
f"[x] Missing DLLs in pyCTools/bin/{arch}/\n"
67-
" Suggested action: Run 'compilerHelper.ps1' to generate the DLLs before building.\n"
68-
)
69133

70-
# Ensure ../dist/pip/ exists
71-
output_dir = pathlib.Path(__file__).parent.parent / "dist" / "pip"
72-
output_dir.mkdir(parents=True, exist_ok=True)
134+
if __name__ == "__main__":
135+
print("[*] Starting setup.py script for pyCTools...\n")
73136

74-
try:
75-
version = prompt_version()
76-
77-
setup(
78-
name="pyCTools",
79-
version=version,
80-
packages=find_packages(),
81-
include_package_data=True,
82-
package_data={
83-
"pyCTools": ["bin/x86/*.dll", "bin/x64/*.dll"],
84-
},
85-
description="Your pyCTools package with bundled DLLs",
86-
author="Shahm Najeeb",
87-
author_email="[email protected]",
88-
url="https://github.com/DefinetlyNotAI/PyCTools",
89-
classifiers=[
90-
"Programming Language :: Python :: 3",
91-
"Operating System :: Microsoft :: Windows",
92-
],
93-
options={
94-
"bdist_wheel": {"dist_dir": str(output_dir)},
95-
"sdist": {"dist_dir": str(output_dir)},
96-
},
97-
)
137+
# Change to the script's root directory
138+
os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
98139

99-
whl_filename = get_latest_wheel("dist/pip", "pyctools")
100-
whl_filename = str(whl_filename).replace("\\", "/")
101-
except Exception as e:
102-
sys.exit(f"\033[0m[x] An error occurred during setup: {e}\n")
140+
check_bin_exists(bin_path=os.path.join("pyCTools", "bin"))
103141

104-
# Cleanup: remove pyCTools.egg-info and build directories if they exist
105-
for cleanup_dir in ["pyCTools.egg-info", "build", "../pyCTools.egg-info", "../build", "dist"]:
106-
cleanup_path = pathlib.Path(__file__).parent / cleanup_dir
107-
if cleanup_path.exists() and cleanup_path.is_dir():
108-
shutil.rmtree(cleanup_path)
109-
print("\033[90m[*] Completed setup.py script cleanup successfully.\033[0m\n")
142+
try:
143+
version = prompt_version()
144+
o_dir = output_dir_init()
145+
146+
print("\033[90m")
147+
setup(
148+
name="pyCTools",
149+
version=version,
150+
packages=find_packages(),
151+
include_package_data=True,
152+
package_data={
153+
"pyCTools": ["bin/x86/*.dll", "bin/x64/*.dll"],
154+
},
155+
description="Your pyCTools package with bundled DLLs",
156+
author="Shahm Najeeb",
157+
author_email="[email protected]",
158+
url="https://github.com/DefinetlyNotAI/PyCTools",
159+
classifiers=[
160+
"Programming Language :: Python :: 3",
161+
"Operating System :: Microsoft :: Windows",
162+
],
163+
options={
164+
"bdist_wheel": {"dist_dir": str(o_dir)},
165+
"sdist": {"dist_dir": str(o_dir)},
166+
},
167+
)
168+
print("\033[0m")
110169

111-
print("\033[0m\n[*] Completed setup.py execution.")
112-
if not os.path.isfile("../dist/bin.zip"):
113-
print(
114-
" Suggested action: Run 'distributionHelper.ps1' to create the distribution package for github releases.")
115-
print(" Suggested action: Execute the following to test in VENV:\n\033[96m"
116-
" cd ..\n"
117-
" python -m venv dist/venv_test\n"
118-
" dist\\venv_test\\Scripts\\Activate.ps1\n"
119-
" python -m pip install --upgrade pip\n"
120-
f" pip install dist/pip/{whl_filename}\n"
121-
" python example/hwrng_example.py\n"
122-
" python example/process_inspect_example.py\n"
123-
" deactivate\n"
124-
" Remove-Item -Recurse -Force dist\\venv_test\n\033[0m")
125-
126-
127-
print("[*] For local installation, run:")
128-
print(f" \033[96mpython -m pip install dist/pip/{whl_filename}\033[0m")
129-
print("[*] If you place the WHL file on the GitHub releases page, users can download it and install it with:")
130-
print(
131-
f" \033[96mpip install https://github.com/DefinetlyNotAI/PyCTools/releases/download/{version}/{whl_filename}\033[0m")
132-
print(f" > Assuming the version[{version}] entered earlier is the same as the tag release.\n")
170+
whl_filename = get_latest_wheel("dist/libraryWheel", "pyctools")
171+
whl_filename = str(whl_filename).replace("\\", "/")
172+
except Exception as e:
173+
cleanup()
174+
sys.exit(f"\033[0m[x] An error occurred during setup: {e}\n")
175+
176+
success_finale(whl_filename_=whl_filename, version_=version)

0 commit comments

Comments
 (0)