-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
482 lines (411 loc) · 17.1 KB
/
build.py
File metadata and controls
482 lines (411 loc) · 17.1 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#!/usr/bin/env python3
"""
CyberClean — Build Script
VERSION được đọc tự động từ version.py — không bao giờ hardcode ở đây nữa.
Usage:
python3 build.py → auto-detect platform
python3 build.py --windows → build .exe (run on Windows)
python3 build.py --inno → build .exe + generate Inno Setup script
python3 build.py --linux → build tar.gz (run on Linux)
python3 build.py --appimage → build AppImage
python3 build.py --deb → build .deb (Debian/Ubuntu)
python3 build.py --check → check dependencies only
"""
import sys, os, shutil, subprocess, platform, re
from pathlib import Path
OS = platform.system()
ROOT = Path(__file__).parent
DIST = ROOT / 'dist'
BUILD = ROOT / 'build'
# ── Version đọc từ version.py (single source of truth) ───
def _read_version() -> str:
"""
Đọc version từ version.py — không hardcode ở đây.
Fallback về '0.0.0' nếu không tìm thấy để build không crash.
"""
vfile = ROOT / 'version.py'
if not vfile.exists():
print(f" ⚠ version.py not found — using 0.0.0 (create it!)")
return '0.0.0'
src = vfile.read_text(encoding="utf-8")
m = re.search(r'__version__\s*=\s*["\'](.+?)["\']', src)
if not m:
print(f" ⚠ __version__ not found in version.py — using 0.0.0")
return '0.0.0'
return m.group(1)
VERSION = _read_version()
APP = 'CyberClean'
AUTHOR = 'vuphitung'
URL = f'https://github.com/{AUTHOR}/{APP}'
ICON_ICO = ROOT / 'assets' / 'logo.ico'
ICON_PNG = ROOT / 'assets' / 'logo.png'
# ── Colors ────────────────────────────────────────────────
G = '\033[0;32m'; Y = '\033[1;33m'; R = '\033[0;31m'
C = '\033[0;36m'; B = '\033[0;34m'; NC = '\033[0m'
def ok(msg): print(f' {G}✓{NC} {msg}')
def warn(msg): print(f' {Y}⚠{NC} {msg}')
def err(msg): print(f' {R}✗{NC} {msg}')
def head(msg): print(f'\n{B}━━━ {msg} ━━━{NC}')
def run(cmd, **kw):
return subprocess.run(cmd, shell=True, **kw)
def _pyinstaller_bin() -> str:
if shutil.which('pyinstaller'):
return 'pyinstaller'
local = Path.home() / '.local/bin/pyinstaller'
if local.exists():
return str(local)
return f'{sys.executable} -m PyInstaller'
def _has_pyinstaller() -> bool:
try:
__import__('PyInstaller')
return True
except ImportError:
return False
# ── Dependency check ──────────────────────────────────────
def check_deps():
head(f'Checking dependencies [v{VERSION}]')
ok_all = True
for pkg, hint in {
'psutil': 'sudo pacman -S python-psutil OR pip install psutil --break-system-packages',
'PyQt6': 'sudo pacman -S python-pyqt6 OR pip install PyQt6 --break-system-packages',
}.items():
try:
__import__(pkg); ok(pkg)
except ImportError:
err(f'{pkg} missing - {hint}'); ok_all = False
if _has_pyinstaller():
ok(f'PyInstaller ({_pyinstaller_bin()})')
else:
err('PyInstaller missing - python3 -m pip install pyinstaller --break-system-packages')
ok_all = False
return ok_all
# ── PyInstaller shared options ────────────────────────────
def _pyinstaller_cmd(onefile: bool, icon: Path | None) -> str:
sep = ';' if OS == 'Windows' else ':'
mode = '--onefile' if onefile else '--onedir'
dll = ROOT / 'LibreHardwareMonitorLib.dll'
if OS == 'Windows' and not dll.exists():
warn('LibreHardwareMonitorLib.dll not found - temp will use WMI fallback')
parts = [
f'{_pyinstaller_bin()} {mode} --noconsole',
f'--name {APP}',
f'--add-data "version.py{sep}."', # bundle version.py
f'--add-data "core/*.py{sep}core"',
f'--add-data "utils/*.py{sep}utils"',
f'--add-data "assets{sep}assets"',
]
if dll.exists():
parts.append(f'--add-data "LibreHardwareMonitorLib.dll{sep}."')
ok('Bundling LibreHardwareMonitorLib.dll')
parts += [
'--hidden-import psutil',
'--hidden-import PyQt6',
'--hidden-import PyQt6.QtWidgets',
'--hidden-import PyQt6.QtCore',
'--hidden-import PyQt6.QtGui',
'--hidden-import utils.updater',
'--hidden-import json',
'--hidden-import urllib.request',
'--hidden-import urllib.error',
'--hidden-import tarfile',
'--hidden-import tempfile',
'--hidden-import clr',
'--hidden-import clr._extra',
'--exclude-module tkinter',
'--exclude-module matplotlib',
'--exclude-module numpy',
'--exclude-module gi',
]
if icon and icon.exists():
parts.append(f'--icon "{icon}"')
ok(f'Icon: {icon.name}')
else:
warn(f'No icon at {icon} - building without icon')
parts.append('main.py')
return ' '.join(parts)
# ── Windows build ─────────────────────────────────────────
def build_windows(make_inno: bool = False):
head(f'Building Windows .exe [v{VERSION}]')
if not _has_pyinstaller():
err('PyInstaller not found')
return False
DIST.mkdir(exist_ok=True)
# onedir (not onefile): keeps DLLs next to exe instead of extracting to %TEMP%
# onefile extracts python312.dll etc to %TEMP% at runtime -> AV blocks it
cmd = _pyinstaller_cmd(onefile=False, icon=ICON_ICO)
if run(cmd).returncode != 0:
err('Build failed')
return False
app_dir = DIST / APP
exe = app_dir / f'{APP}.exe'
if not exe.exists():
err(f'{exe} not found after build')
return False
ok(f'Built: {app_dir} ({sum(f.stat().st_size for f in app_dir.rglob("*") if f.is_file()) / 1024/1024:.1f} MB total)')
if make_inno:
_generate_inno_script(exe)
return True
def _generate_inno_script(exe: Path):
head('Generating Inno Setup script')
# Resolve icon path to absolute (Inno needs absolute or relative-to-script path)
if ICON_ICO.exists():
# Use relative path from project root — works when .iss is in project root
icon_line = f'SetupIconFile=assets\\logo.ico'
else:
icon_line = '; SetupIconFile=assets\\logo.ico (file not found — add logo.ico)'
iss_lines = [
f'; CyberClean v{VERSION} — Inno Setup Script',
'; AUTO-GENERATED by build.py — do not edit VERSION here, edit version.py',
'; Build: Open in Inno Setup Compiler → Compile (F9)',
'; Download Inno Setup: https://jrsoftware.org/isinfo.php',
'',
'[Setup]',
f'AppName={APP}',
f'AppVersion={VERSION}',
f'AppPublisher={AUTHOR}',
f'AppPublisherURL={URL}',
f'AppSupportURL={URL}/issues',
f'AppUpdatesURL={URL}/releases',
r'DefaultDirName={autopf}' + f'\\{APP}',
f'DefaultGroupName={APP}',
'AllowNoIcons=yes',
'OutputDir=dist',
f'OutputBaseFilename={APP}_Setup_v{VERSION}',
icon_line,
'Compression=lzma',
'CloseApplications=yes', # Báo Setup đóng app đang chạy
'RestartApplications=no', # Không tự restart app sau khi cài
'AppMutex=CyberClean_Single_Instance_Lock', # Tên mutex — Setup dùng để detect process cũ
'SolidCompression=yes',
'WizardStyle=modern',
'PrivilegesRequired=admin',
f'UninstallDisplayName={APP}',
r'UninstallDisplayIcon={app}' + f'\\{APP}.exe',
f'VersionInfoVersion={VERSION}.0', # Windows needs 4-part: 2.2.0.0
'VersionInfoDescription=Smart Disk Cleaner',
'VersionInfoCompany=' + AUTHOR,
'VersionInfoProductName=' + APP,
'',
'[Languages]',
'Name: "english"; MessagesFile: "compiler:Default.isl"',
'',
'[Tasks]',
'Name: "desktopicon"; Description: "Create a &desktop shortcut"; GroupDescription: "Additional icons:"',
'',
'[Files]',
f'Source: "dist\\{APP}\\*"; DestDir: "{{app}}"; Flags: ignoreversion recursesubdirs createallsubdirs',
'',
'[Icons]',
'; Shortcut trực tiếp vào .exe — không dùng schtasks',
'; schtasks /rl highest dễ bị Defender/EDR đánh dấu hành vi đáng ngờ',
f'Name: "{{group}}\\{APP}"; Filename: "{{app}}\\{APP}.exe"',
f'Name: "{{group}}\\Uninstall {APP}"; Filename: "{{uninstallexe}}"',
f'Name: "{{userdesktop}}\\{APP}"; Filename: "{{app}}\\{APP}.exe"; Tasks: desktopicon',
'',
'[Run]',
'; Launch app sau khi cài xong',
f'Filename: "{{app}}\\{APP}.exe"; Description: "Launch {APP}"; Flags: nowait postinstall',
'',
'[UninstallDelete]',
f'Type: filesandordirs; Name: "{{localappdata}}\\{APP}"',
f'Type: filesandordirs; Name: "{{userappdata}}\\{APP}"',
]
iss_path = ROOT / f'{APP}.iss'
iss_path.write_text('\n'.join(iss_lines) + '\n', encoding='utf-8')
ok(f'Inno script: {iss_path}')
print(f'\n {C}Next:{NC}')
print(f' 1. Open {APP}.iss in Inno Setup Compiler')
print(f' 2. Press Compile (F9) → dist/{APP}_Setup_v{VERSION}.exe')
print(f' 3. Upload .exe to GitHub Releases\n')
# ── Linux AppImage ────────────────────────────────────────
def build_linux_appimage():
head(f'Building Linux AppImage [v{VERSION}]')
if not _has_pyinstaller():
err('PyInstaller not found')
return False
cmd = _pyinstaller_cmd(onefile=False, icon=ICON_PNG)
if run(cmd).returncode != 0:
err('PyInstaller step failed')
return False
appdir = BUILD / 'AppDir'
if appdir.exists():
shutil.rmtree(appdir)
appdir.mkdir(parents=True)
shutil.copytree(DIST / APP, appdir / 'usr/bin' / APP)
apprun = appdir / 'AppRun'
apprun.write_text(
'#!/bin/bash\n'
f'exec "$APPDIR/usr/bin/{APP}/{APP}" "$@"\n',
encoding='utf-8')
apprun.chmod(0o755)
(appdir / f'{APP}.desktop').write_text(
f'[Desktop Entry]\n'
f'Name={APP}\n'
f'Exec={APP}\n'
f'Icon={APP}\n'
f'Type=Application\n'
f'Categories=System;Utility;\n'
f'Comment=Smart Disk Cleaner v{VERSION}\n',
encoding='utf-8')
if ICON_PNG.exists():
shutil.copy(ICON_PNG, appdir / f'{APP}.png')
else:
warn(f'No icon at {ICON_PNG}')
MIN_SIZE = 1_000_000
tool = Path('/tmp/appimagetool')
if not tool.exists() or tool.stat().st_size < MIN_SIZE:
warn('Downloading appimagetool...')
run(
'wget -q -O /tmp/appimagetool '
'"https://github.com/AppImage/AppImageKit/releases/download/'
'continuous/appimagetool-x86_64.AppImage"'
)
if not tool.exists() or tool.stat().st_size < MIN_SIZE:
err('appimagetool download failed — check internet / GitHub status')
return False
tool.chmod(0o755)
out = DIST / f'{APP}-{VERSION}-x86_64.AppImage'
DIST.mkdir(exist_ok=True)
result = run(f'ARCH=x86_64 APPIMAGE_EXTRACT_AND_RUN=1 /tmp/appimagetool {appdir} {out}')
if result.returncode == 0 and out.exists():
out.chmod(0o755)
ok(f'Built: {out} ({out.stat().st_size/1024/1024:.1f} MB)')
_print_release_note(out)
return True
err('AppImage packaging failed')
return False
# ── Linux .deb ────────────────────────────────────────────
def build_linux_deb():
head(f'Building Linux .deb [v{VERSION}]')
if not _has_pyinstaller():
err('PyInstaller not found')
return False
cmd = _pyinstaller_cmd(onefile=False, icon=ICON_PNG)
if run(cmd).returncode != 0:
err('PyInstaller step failed')
return False
pkg_name = APP.lower()
deb_root = BUILD / f'{pkg_name}_{VERSION}'
if deb_root.exists():
shutil.rmtree(deb_root)
install_dir = deb_root / f'opt/{APP}'
install_dir.mkdir(parents=True)
shutil.copytree(DIST / APP, install_dir / APP)
apps_dir = deb_root / 'usr/share/applications'
apps_dir.mkdir(parents=True)
icon_dest = deb_root / f'usr/share/pixmaps/{APP}.png'
icon_dest.parent.mkdir(parents=True)
if ICON_PNG.exists():
shutil.copy(ICON_PNG, icon_dest)
(apps_dir / f'{APP}.desktop').write_text(
f'[Desktop Entry]\n'
f'Name={APP}\n'
f'Exec=/opt/{APP}/{APP}/{APP}\n'
f'Icon={APP}\n'
f'Type=Application\n'
f'Categories=System;Utility;\n'
f'Comment=Smart Disk Cleaner v{VERSION}\n'
f'Terminal=false\n',
encoding='utf-8')
debian_dir = deb_root / 'DEBIAN'
debian_dir.mkdir()
(debian_dir / 'control').write_text(
f'Package: {pkg_name}\n'
f'Version: {VERSION}\n'
f'Architecture: amd64\n'
f'Maintainer: {AUTHOR} <{AUTHOR}@users.noreply.github.com>\n'
f'Description: Smart Disk Cleaner\n'
f' CyberClean — safe, fast disk cleaning for Linux.\n'
f'Homepage: {URL}\n'
f'Section: utils\n'
f'Priority: optional\n'
f'Depends: libxcb-cursor0\n', # Qt6 runtime dep on Ubuntu 22.04+
encoding='utf-8')
postinst = debian_dir / 'postinst'
postinst.write_text(
'#!/bin/bash\n'
f'chmod +x /opt/{APP}/{APP}/{APP}\n'
'update-desktop-database /usr/share/applications 2>/dev/null || true\n',
encoding='utf-8')
postinst.chmod(0o755)
postrm = debian_dir / 'postrm'
postrm.write_text(
'#!/bin/bash\n'
f'rm -rf /opt/{APP}\n'
'update-desktop-database /usr/share/applications 2>/dev/null || true\n',
encoding='utf-8')
postrm.chmod(0o755)
DIST.mkdir(exist_ok=True)
out = DIST / f'{pkg_name}_{VERSION}_amd64.deb'
if run(f'dpkg-deb --build {deb_root} {out}').returncode == 0 and out.exists():
ok(f'Built: {out} ({out.stat().st_size/1024/1024:.1f} MB)')
print(f'\n {C}Install:{NC} sudo apt install ./{out.name}')
print(f' {C}Remove:{NC} sudo apt remove {pkg_name}\n')
return True
err('.deb build failed — is dpkg-deb installed? (sudo apt install dpkg)')
return False
# ── Linux tar.gz ──────────────────────────────────────────
def build_linux_targz():
head(f'Building Linux tar.gz [v{VERSION}]')
if not _has_pyinstaller():
err('PyInstaller not found')
return False
cmd = _pyinstaller_cmd(onefile=False, icon=ICON_PNG)
if run(cmd).returncode != 0:
err('PyInstaller step failed')
return False
DIST.mkdir(exist_ok=True)
out = DIST / f'{APP}-{VERSION}-linux-x86_64.tar.gz'
run(f'tar -czf {out} -C {DIST} {APP}')
if out.exists():
ok(f'Built: {out} ({out.stat().st_size/1024/1024:.1f} MB)')
_print_release_note(out)
return True
err('tar.gz build failed')
return False
# ── Linux zip fallback ────────────────────────────────────
def build_linux_zip():
head(f'Building source zip fallback [v{VERSION}]')
DIST.mkdir(exist_ok=True)
out = DIST / f'{APP}-{VERSION}-linux-source.zip'
run(f'zip -r {out} main.py version.py core/ utils/ requirements.txt install.sh README.md 2>/dev/null')
if out.exists():
ok(f'Built: {out}')
return True
return False
def _print_release_note(path: Path):
print(f'\n {C}Upload to GitHub Releases:{NC}')
print(f' gh release create v{VERSION} {path} \\')
print(f' --title "v{VERSION}" --notes "See CHANGELOG"\n')
# ── Main ──────────────────────────────────────────────────
def main():
print(f'\n{C} ⚡ {APP} Build Tool — v{VERSION}{NC}\n')
args = sys.argv[1:]
if '--check' in args:
check_deps()
return
if not check_deps():
print(f'\n{R}Fix dependencies first, then re-run.{NC}')
return
make_inno = '--inno' in args
make_deb = '--deb' in args
make_aimg = '--appimage' in args
if '--windows' in args or make_inno: target = 'Windows'
elif '--linux' in args or make_deb or make_aimg: target = 'Linux'
else: target = OS
success = False
if target == 'Windows':
success = build_windows(make_inno=make_inno)
elif target == 'Linux':
if make_deb:
success = build_linux_deb()
elif make_aimg:
success = build_linux_appimage()
else:
success = build_linux_targz()
else:
warn(f'Platform "{target}" not recognized — use --windows or --linux')
status = f'{G}✅ Done → {DIST}{NC}' if success else f'{R}✗ Build failed{NC}'
print(f'\n {status}\n')
if __name__ == '__main__':
main()