Skip to content

Commit aec3be5

Browse files
committed
build : add dev run_api file to test binary locally
1 parent 1b5aed0 commit aec3be5

2 files changed

Lines changed: 173 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import subprocess
2+
import os
3+
import sys
4+
from src.shared.config.conf import Config
5+
import src.shared.database.sqlite_db as db
6+
from src.web_api.factory import create_flask_app
7+
8+
def create_app():
9+
# Conf path, created by Tauri
10+
conf_path = os.path.join(os.path.dirname(sys.executable), "resources", "conf.json")
11+
12+
conf = Config(conf_path)
13+
14+
if not os.path.exists(conf.log_file):
15+
subprocess.call(f"mkdir -p {os.path.abspath(os.path.dirname(conf.log_file))}")
16+
17+
conn = db.connect(conf.database)
18+
db.create_tables(conn)
19+
db.set_version(conn)
20+
conn.commit()
21+
conn.close()
22+
23+
app = create_flask_app(conf)
24+
app.run(port=5000, debug=True)
25+
26+
27+
def validate_conf_path(filepath, is_test) :
28+
if not os.path.isfile(filepath) :
29+
raise ValueError("Filename doesn't lead to a file")
30+
if is_test and not filepath.startswith("test_"):
31+
raise ValueError("Test launch requires a conf filename beginning with 'test_'.")
32+
return filepath
33+
34+
35+
if __name__ == "__main__":
36+
create_app()
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import shutil
2+
from typing import Literal
3+
import os
4+
import subprocess
5+
from shutil import rmtree
6+
import json
7+
import stat
8+
9+
FOLDER_CP_PROJECT = "C:/Users/romain/code/timetracker-back"
10+
CP_PROJECT = os.path.join(FOLDER_CP_PROJECT, 'timer_sans_classe')
11+
ORIGINAL_ROOT = "C:/Users/romain/code/python/timer_sans_classe"
12+
CURR_FILE = os.path.abspath(__file__)
13+
CP_CURR_FILE = os.path.join(CP_PROJECT, os.path.basename(CURR_FILE))
14+
PATH_PREFIX = '../'
15+
16+
def remove_readonly(func, path, _):
17+
"""Clear the readonly bit and reattempt the removal."""
18+
os.chmod(path, stat.S_IWRITE)
19+
func(path)
20+
21+
def main(dest_path : str, arg: Literal['api', 'tui'], test : bool) -> None:
22+
# if not os.path.exists(dest_path):
23+
# print("Destination doesn't exist, creating folder")
24+
# os.mkdir(dest_path)
25+
26+
# print("cloning front")
27+
# subprocess.call(f'git clone https://github.com/CandussoR/timetracker_front.git {dest_path}', shell=True)
28+
# os.chdir(dest_path)
29+
30+
# print("creating env")
31+
# with open('.env', 'w') as fw:
32+
# content = """VITE_APP_IP_DEV = "http://127.0.0.1:5000/"
33+
# VITE_APP_IP_PROD = "http://127.0.0.1:63267/"
34+
# VITE_APP_RING = /timer_end.mp3
35+
# VITE_APP_VERSION = 0.9.0"""
36+
# fw.writelines(content)
37+
38+
# print("installing npm packages and tauri plugins")
39+
# subprocess.call('npm install', shell=True)
40+
# subprocess.call("npm run tauri add shell", shell=True)
41+
# subprocess.call("npm run tauri add dialog", shell=True)
42+
43+
# assert os.path.exists('src-tauri'), "No tauri path"
44+
45+
print(f"Copying this project into {FOLDER_CP_PROJECT}")
46+
if os.path.exists(FOLDER_CP_PROJECT):
47+
print("path exists")
48+
subprocess.call(f'rm -rf {FOLDER_CP_PROJECT}')
49+
os.mkdir(FOLDER_CP_PROJECT)
50+
subprocess.call(f'cp -r {ORIGINAL_ROOT} {FOLDER_CP_PROJECT}/')
51+
52+
print(f"Creating gitattributes in copy project")
53+
os.chdir(CP_PROJECT)
54+
55+
attributes_path = os.path.abspath(os.path.join('.', '.gitattributes'))
56+
with open(attributes_path, 'w') as fw:
57+
general = ".github/ export-ignore\ntests/ export-ignore\narchived export-ignore\nscripts export-ignore\n__pycache__/ export-ignore"
58+
content_api = "\nsrc/tui export-ignore\ntui_requirements.txt export-ignore"
59+
content_tui = "tests/ export-ignore\nsrc/web_api export-ignore\nrequirements.txt export-ignore"
60+
fw.writelines(general)
61+
fw.writelines(content_api if arg=='api' else content_tui)
62+
63+
try:
64+
print("creating git archive")
65+
ret_code = subprocess.call('git archive --format=tar.gz --worktree-attributes --output=backend.tar.gz HEAD', shell=True)
66+
if not ret_code:
67+
os.remove(attributes_path)
68+
subprocess.call('mkdir backend')
69+
subprocess.call('tar -xzf backend.tar.gz -C backend')
70+
assert os.path.exists(os.path.join(CP_PROJECT, 'backend')), "Backend doesn't exists"
71+
print("\tGetting platform target triple")
72+
command = 'powershell -Command "rustc -Vv | Select-String \'host:\' | ForEach-Object {($_.Line -split \' \')[1]}"'
73+
target_triple = subprocess.run(command, shell=True, text=True, capture_output=True)
74+
if target_triple.returncode == 0:
75+
target_triple = target_triple.stdout.strip()
76+
77+
print("Replacing run.py")
78+
os.remove(os.path.join(CP_PROJECT, "backend", "run.py"))
79+
print(os.path.join(os.path.dirname(CURR_FILE), 'python', 'run_api.py'))
80+
if test :
81+
subprocess.call(f"cp {os.path.join(os.path.dirname(CURR_FILE), 'python', 'run_api_test.py')} {os.path.join(CP_PROJECT, 'backend', '')}")
82+
else:
83+
subprocess.call(f"cp {os.path.join(os.path.dirname(CURR_FILE), 'python', 'run_api.py')} {os.path.join(CP_PROJECT, 'backend', '')}")
84+
print(os.listdir(os.path.join(CP_PROJECT, 'backend', '')))
85+
os.rename(os.path.join(CP_PROJECT, 'backend', 'run_api_test.py' if test else 'run_api.test'), os.path.join(CP_PROJECT, 'backend', 'run.py'))
86+
87+
conf = {"database": "./timer_data.db",
88+
"timer_sound_path": "",
89+
"log_file": "./logs/logs.log",
90+
}
91+
with open(os.path.join(CP_PROJECT, "backend", "conf.json"), 'w') as fw:
92+
json.dump(conf, fw)
93+
os.remove('backend/conf_example.jsonc')
94+
95+
subprocess.call(f'C:/Users/romain/.python-venv/timetracker/Scripts/pyinstaller.exe --name timetracker-backend-{target_triple} --onefile --noconsole --hidden-import=flask --add-data "backend/conf.json;." backend/run.py')
96+
# subprocess.call(f'C:/Users/romain/.python-venv/timetracker/Scripts/pyinstaller.exe --name timetracker-backend-{target_triple} --hidden-import=flask --add-data "backend/conf.json;." backend/run.py')
97+
except Exception as e:
98+
print(f"Exception occured during the creation of the Python executable : {e}")
99+
100+
print("cleaning Python build files")
101+
if os.path.exists('./backend'):
102+
rmtree('./backend')
103+
if os.path.exists('./build'):
104+
rmtree('./build')
105+
if os.path.exists('backend.spec'):
106+
os.remove('backend.spec')
107+
if os.path.exists('backend.tar.gz'):
108+
os.remove('backend.tar.gz')
109+
110+
print("moving executable")
111+
tauri_path = os.path.join(dest_path, 'src-tauri')
112+
tauri_bin_path = os.path.join(tauri_path, 'bin')
113+
if not (os.path.exists(tauri_bin_path)):
114+
os.mkdir(tauri_bin_path)
115+
if os.path.isfile(f'{dest_path}\\src-tauri\\bin\\timetracker-backend-{target_triple}.exe'):
116+
os.remove(f'{dest_path}\\src-tauri\\bin\\timetracker-backend-{target_triple}.exe')
117+
shutil.copy2(f'./dist/timetracker-backend-{target_triple}.exe', f'{dest_path}\\src-tauri\\bin\\')
118+
rmtree('dist')
119+
120+
# print('building exe')
121+
os.chdir(dest_path)
122+
# # subprocess.call('npm run tauri build -- --features launch_binary --debug', shell=True)
123+
# subprocess.call('npm run tauri build -- --features launch_binary', shell=True)
124+
125+
print("cleaning")
126+
rmtree(FOLDER_CP_PROJECT, onerror=remove_readonly)
127+
128+
if __name__ == '__main__':
129+
import sys
130+
test = False
131+
dest_path, args = sys.argv[1:]
132+
if args[0] not in ('api', 'tui'):
133+
raise ValueError(f"Arg can only be either 'api' or 'tui' : got {args[0]}.")
134+
if args[1] and args[1] == '--test':
135+
test = True
136+
main(dest_path, args[0], test)
137+

0 commit comments

Comments
 (0)