Skip to content

Commit

Permalink
Refactored assemble scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
geugenm committed Dec 13, 2023
1 parent a611686 commit 6eeb2ac
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 43 deletions.
33 changes: 21 additions & 12 deletions scripts/compile_to_exe.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,46 @@
import shutil
import subprocess
import sys
from typing import List

BUILD_DIR = ".build"
DIST_DIR = "dist"
PYINSTALLER = "pyinstaller"
ONEFILE_FLAG = "--onefile"
NOCONSOLE_FLAG = "--noconsole"
EXE_EXT = ".exe"

def compile_exe(script_file, config):
output_directory = os.path.join(".build", config)
def compile_exe(script_file: str, config: str) -> None:
output_directory = os.path.join(BUILD_DIR, config)
os.makedirs(output_directory, exist_ok=True)

# PyInstaller flags
pyinstaller_flags = ["--onefile", "--noconsole"]
pyinstaller_flags = [ONEFILE_FLAG]

if config == "debug":
pyinstaller_flags.remove("--noconsole")
# Add debug flags specific to your project if needed
# Example: pyinstaller_flags.extend(["--debug"])
pyinstaller_flags.append("--debug")
else:
pyinstaller_flags.append(NOCONSOLE_FLAG)

try:
subprocess.run(["pyinstaller", *pyinstaller_flags, script_file])
subprocess.run([PYINSTALLER, *pyinstaller_flags, script_file])
except FileNotFoundError:
print("PyInstaller not found. Please install PyInstaller to proceed.")
print(f"{PYINSTALLER} not found. Please install {PYINSTALLER} to proceed.")
sys.exit(1)

# Move the compiled executable to the output directory
script_name = os.path.splitext(os.path.basename(script_file))[0]
exe_name = f"{script_name}.exe"
shutil.move(os.path.join("dist", exe_name), os.path.join(output_directory, exe_name))
exe_name = f"{script_name}{EXE_EXT}"
shutil.move(os.path.join(DIST_DIR, exe_name), os.path.join(output_directory, exe_name))


if __name__ == "__main__":
def main() -> None:
parser = argparse.ArgumentParser(description="Compile and move executable based on configuration")
parser.add_argument("script_file", help="Python script file to compile")
parser.add_argument("--config", choices=["release", "debug"], default="debug",
help="Configuration type (release or debug, default is debug)")
args = parser.parse_args()

compile_exe(args.script_file, args.config)

if __name__ == "__main__":
main()
60 changes: 29 additions & 31 deletions scripts/create_release.py
Original file line number Diff line number Diff line change
@@ -1,55 +1,55 @@
import logging
import os
import platform
import shutil
import subprocess

LOG_FILE = 'logs/create_release.log'
LOG_LEVEL = logging.INFO
LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
BUILD_DIR = '.build'
SOURCE_DIRS = ['docs', 'src']
EXCLUDE_DIRS = ['decompiled', 'logs']
COMPILE_SCRIPT = 'compile_to_exe.py'
SERVER_UI_SCRIPT = 'start_server_ui.py'
WINDOWS_COMPILED_SCRIPT = 'start_server_ui.exe'
CONFIG = 'release'
SPEC_FILE = 'start_server_ui.spec'


def setup_logger():
logging.basicConfig(filename='logs/create_release.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.basicConfig(filename=LOG_FILE, level=LOG_LEVEL, format=LOG_FORMAT)


def clean_build():
# Delete .build directory if it exists
if os.path.exists('.build'):
shutil.rmtree('.build', ignore_errors=True)
if os.path.exists(BUILD_DIR):
shutil.rmtree(BUILD_DIR, ignore_errors=True)


def copy_files():
# Define source and destination directories
source_dirs = ['docs', 'src']
exclude_dirs = ['decompiled', 'logs']
destination_dir = '.build'

# Check if required directories exist
if not all(os.path.exists(dir) for dir in ['docs', 'src', 'scripts']):
if not all(os.path.exists(dir) for dir in SOURCE_DIRS + ['scripts']):
logging.error("Required directories (docs/, src/, scripts/) not found.")
return

# Create destination directory if it doesn't exist
os.makedirs(destination_dir, exist_ok=True)
os.makedirs(BUILD_DIR, exist_ok=True)

# Copy files from source to destination, excluding certain directories
for src_dir in source_dirs:
for root, dirs, files in os.walk(src_dir):
if any(exclude_dir in root for exclude_dir in exclude_dirs):
for src_dir in SOURCE_DIRS:
for root, _, files in os.walk(src_dir):
if any(exclude_dir in root for exclude_dir in EXCLUDE_DIRS):
continue
for file in files:
src_file = os.path.join(root, file)
dest_file = os.path.join(destination_dir, os.path.relpath(src_file, start=src_dir))
dest_file = os.path.join(BUILD_DIR, os.path.relpath(src_file, start=src_dir))
os.makedirs(os.path.dirname(dest_file), exist_ok=True)
shutil.copy(src_file, dest_file)
logging.info(f"Copied {src_file} to {dest_file}")


def start_compile():
# Change working directory to scripts/
original_dir = os.getcwd()
os.chdir('scripts')

# Start subprocess to run compile_to_exe.py with flags
logging.info("Starting compile_to_exe.py...")
compile_process = subprocess.run(['python', 'compile_to_exe.py', 'start_server_ui.py', '--config=release'],
compile_process = subprocess.run(['python', COMPILE_SCRIPT, SERVER_UI_SCRIPT, f'--config={CONFIG}'],
capture_output=True, text=True)

if compile_process.returncode != 0:
Expand All @@ -58,21 +58,19 @@ def start_compile():
logging.error(compile_process.stderr)
return

# Move the compiled file to .build directory
current_os = platform.system().lower()
compiled_file = f".build/release/start_server_ui.exe" # Replace with actual extension
shutil.move(compiled_file, f"../.build/start_server_ui.exe")
logging.info(f"Moved {compiled_file} to .build folder")
compiled_file = f"{BUILD_DIR}/{CONFIG}/{WINDOWS_COMPILED_SCRIPT}"
shutil.move(compiled_file, f"../{BUILD_DIR}/{WINDOWS_COMPILED_SCRIPT}")
logging.info(f"Moved {compiled_file} to {BUILD_DIR} folder")

# Remove unnecessary directories and files
shutil.rmtree('build', ignore_errors=True)
shutil.rmtree('dist', ignore_errors=True)
shutil.rmtree('.build', ignore_errors=True)
os.remove('start_server_ui.spec') # Remove start_server_ui.spec file
os.remove(SPEC_FILE)
logging.info("Cleaned up build artifacts")

os.chdir(original_dir)


# Main execution
if __name__ == "__main__":
setup_logger()
clean_build()
Expand Down

0 comments on commit 6eeb2ac

Please sign in to comment.