-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_exe_ci.py
More file actions
executable file
·285 lines (241 loc) · 8.68 KB
/
Copy pathbuild_exe_ci.py
File metadata and controls
executable file
·285 lines (241 loc) · 8.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#!/usr/bin/env python3
"""
Script de build optimisé pour CI/CD GitHub Actions.
Version multi-plateforme compatible Windows, Linux et macOS.
"""
import sys
import subprocess
import shutil
import platform
import os
from pathlib import Path
# Configuration de l'encoding UTF-8 pour Windows
if platform.system() == "Windows":
import codecs
import locale
# Force UTF-8 encoding pour stdout
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(encoding='utf-8')
if hasattr(sys.stderr, 'reconfigure'):
sys.stderr.reconfigure(encoding='utf-8')
# Variables d'environnement pour forcer UTF-8
os.environ['PYTHONIOENCODING'] = 'utf-8'
os.environ['PYTHONUTF8'] = '1'
def get_platform_info():
"""Détecte les informations de la plateforme."""
system = platform.system().lower()
if system == "windows":
return {
"name": "windows",
"exe_ext": ".exe",
"separator": ";",
"executable_name": "Minuteur.exe"
}
elif system == "darwin":
return {
"name": "macos",
"exe_ext": "",
"separator": ":",
"executable_name": "Minuteur"
}
else: # Linux et autres Unix
return {
"name": "linux",
"exe_ext": "",
"separator": ":",
"executable_name": "Minuteur"
}
def log(message, level="INFO"):
"""Logging avec couleurs pour CI, compatible Windows encoding."""
colors = {
"INFO": "\033[94m", # Bleu
"SUCCESS": "\033[92m", # Vert
"WARNING": "\033[93m", # Jaune
"ERROR": "\033[91m", # Rouge
"RESET": "\033[0m" # Reset
}
color = colors.get(level, colors["INFO"])
reset = colors["RESET"]
# Tentative d'affichage avec emojis
try:
print(f"{color}[{level}]{reset} {message}")
except UnicodeEncodeError:
# Fallback: remplacer les emojis par des équivalents ASCII
safe_message = message
emoji_replacements = {
"🚀": "[BUILD]",
"🔍": "[CHECK]",
"✅": "[OK]",
"❌": "[FAIL]",
"🔨": "[COMPILE]",
"🧹": "[CLEAN]",
"📦": "[PACKAGE]",
"🎯": "[TARGET]",
"📊": "[SIZE]",
"🖥️": "[OS]",
"🐍": "[PYTHON]",
"📁": "[DIR]",
"🔧": "[CONFIG]",
"🎉": "[SUCCESS]",
"💥": "[ERROR]"
}
for emoji, replacement in emoji_replacements.items():
safe_message = safe_message.replace(emoji, replacement)
print(f"{color}[{level}]{reset} {safe_message}")
def check_dependencies():
"""Vérifie les dépendances nécessaires."""
log("🔍 Vérification des dépendances...")
try:
import customtkinter
log(f"✅ CustomTkinter: {customtkinter.__version__}")
except ImportError:
log("❌ CustomTkinter non trouvé", "ERROR")
return False
try:
import pystray
log(f"✅ pystray: OK")
except ImportError:
log("❌ pystray non trouvé", "ERROR")
return False
try:
import PIL
log(f"✅ Pillow: {PIL.__version__}")
except ImportError:
log("❌ Pillow non trouvé", "ERROR")
return False
try:
import PyInstaller
log(f"✅ PyInstaller: {PyInstaller.__version__}")
except ImportError:
log("❌ PyInstaller non trouvé", "ERROR")
return False
return True
def build_executable():
"""Génère l'exécutable avec PyInstaller."""
platform_info = get_platform_info()
project_root = Path(__file__).parent
main_script = project_root / "minuteur" / "main.py"
log(f"🔨 Build pour {platform_info['name'].upper()}...")
if not main_script.exists():
log(f"❌ Script principal non trouvé: {main_script}", "ERROR")
return False
# Nettoyage préalable
dist_folder = project_root / "dist"
build_folder = project_root / "build"
if dist_folder.exists():
log("🧹 Suppression dist/ existant...")
shutil.rmtree(dist_folder)
if build_folder.exists():
log("🧹 Suppression build/ existant...")
shutil.rmtree(build_folder)
# Configuration PyInstaller adaptée par OS
base_cmd = [
sys.executable, "-m", "PyInstaller",
"--name", "Minuteur",
"--windowed",
"--onedir",
"--collect-all", "customtkinter",
"--collect-all", "pystray",
"--collect-all", "PIL",
"--optimize", "2",
"--clean",
"--noconfirm",
str(main_script)
]
# Ajustements spécifiques par OS
if platform_info["name"] == "windows":
# Windows: options spéciales
base_cmd.extend([
"--collect-all", "darkdetect",
"--hidden-import", "tkinter",
"--hidden-import", "tkinter.ttk"
])
elif platform_info["name"] == "linux":
# Linux: gestion X11
base_cmd.extend([
"--collect-all", "darkdetect",
"--hidden-import", "Xlib"
])
elif platform_info["name"] == "macos":
# macOS: options spéciales
base_cmd.extend([
"--collect-all", "darkdetect",
"--osx-bundle-identifier", "com.minuteur.app"
])
log("📦 Commande PyInstaller:")
log(" ".join(base_cmd))
try:
# Exécution de PyInstaller
env = os.environ.copy()
# Variables d'environnement spéciales pour Linux (CI)
if platform_info["name"] == "linux" and "DISPLAY" not in env:
env["DISPLAY"] = ":99"
log("🖥️ Configuration DISPLAY pour Linux CI")
result = subprocess.run(
base_cmd,
cwd=project_root,
env=env,
capture_output=True,
text=True,
timeout=600 # 10 minutes max
)
if result.returncode == 0:
log("✅ Build PyInstaller réussi!", "SUCCESS")
# Vérification de la sortie
exe_folder = dist_folder / "Minuteur"
if exe_folder.exists():
executable = exe_folder / platform_info["executable_name"]
if executable.exists():
size_mb = executable.stat().st_size / (1024 * 1024)
log(f"🎯 Exécutable créé: {executable.name} ({size_mb:.1f} MB)", "SUCCESS")
# Calcul taille totale
total_size = sum(f.stat().st_size for f in exe_folder.rglob('*') if f.is_file())
total_mb = total_size / (1024 * 1024)
log(f"📊 Taille totale: {total_mb:.1f} MB", "SUCCESS")
return True
else:
log(f"❌ Exécutable non trouvé: {platform_info['executable_name']}", "ERROR")
log("📋 Contenu du dossier dist/Minuteur/:")
for item in exe_folder.iterdir():
log(f" - {item.name}")
else:
log("❌ Dossier de build non créé", "ERROR")
else:
log("❌ Échec du build PyInstaller", "ERROR")
log("STDOUT:", "ERROR")
log(result.stdout, "ERROR")
log("STDERR:", "ERROR")
log(result.stderr, "ERROR")
except subprocess.TimeoutExpired:
log("❌ Timeout du build (> 10 minutes)", "ERROR")
except Exception as e:
log(f"❌ Erreur inattendue: {e}", "ERROR")
return False
def main():
"""Point d'entrée principal."""
platform_info = get_platform_info()
print("=" * 60)
log(f"🚀 Build CI/CD - Minuteur pour {platform_info['name'].upper()}")
print("=" * 60)
# Informations système
log(f"🖥️ OS: {platform.system()} {platform.release()}")
log(f"🐍 Python: {sys.version.split()[0]}")
log(f"📁 Répertoire: {Path.cwd()}")
# Variables d'environnement CI utiles
ci_vars = ["GITHUB_ACTIONS", "CI", "RUNNER_OS", "DISPLAY"]
for var in ci_vars:
if var in os.environ:
log(f"🔧 {var}: {os.environ[var]}")
# Vérification des dépendances
if not check_dependencies():
log("❌ Dépendances manquantes", "ERROR")
return 1
# Build
if build_executable():
log("🎉 Build terminé avec succès!", "SUCCESS")
return 0
else:
log("💥 Échec du build", "ERROR")
return 1
if __name__ == "__main__":
sys.exit(main())